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 = CallInst::Create(sinExpr, opr0, "splitsin", aCI);
474 Value *cosval = CallInst::Create(cosExpr, opr0, "splitcos", aCI);
475 new StoreInst(cosval, aCI->getArgOperand(1), aCI);
476
477 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
478 << " with native version of sin/cos");
479
480 replaceCall(aCI, sinval);
481 return true;
482 }
483 }
484 return false;
485}
486
488 Function *Callee = aCI->getCalledFunction();
489 if (!Callee || aCI->isNoBuiltin())
490 return false;
491
492 FuncInfo FInfo;
493 if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.isMangled() ||
494 FInfo.getPrefix() != AMDGPULibFunc::NOPFX ||
495 getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()) ||
496 !(AllNative || useNativeFunc(FInfo.getName()))) {
497 return false;
498 }
499
500 if (FInfo.getId() == AMDGPULibFunc::EI_SINCOS)
501 return sincosUseNative(aCI, FInfo);
502
504 FunctionCallee F = getFunction(aCI->getModule(), FInfo);
505 if (!F)
506 return false;
507
508 aCI->setCalledFunction(F);
509 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
510 << " with native version");
511 return true;
512}
513
514// Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
515// builtin, with appended type size and alignment arguments, where 2 or 4
516// indicates the original number of arguments. The library has optimized version
517// of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
518// power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
519// for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
520// 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
521bool AMDGPULibCalls::fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
522 const FuncInfo &FInfo) {
523 auto *Callee = CI->getCalledFunction();
524 if (!Callee->isDeclaration())
525 return false;
526
527 assert(Callee->hasName() && "Invalid read_pipe/write_pipe function");
528 auto *M = Callee->getParent();
529 std::string Name = std::string(Callee->getName());
530 auto NumArg = CI->arg_size();
531 if (NumArg != 4 && NumArg != 6)
532 return false;
533 ConstantInt *PacketSize =
534 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 2));
535 ConstantInt *PacketAlign =
536 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 1));
537 if (!PacketSize || !PacketAlign)
538 return false;
539
540 unsigned Size = PacketSize->getZExtValue();
541 Align Alignment = PacketAlign->getAlignValue();
542 if (Alignment != Size)
543 return false;
544
545 unsigned PtrArgLoc = CI->arg_size() - 3;
546 Value *PtrArg = CI->getArgOperand(PtrArgLoc);
547 Type *PtrTy = PtrArg->getType();
548
550 for (unsigned I = 0; I != PtrArgLoc; ++I)
551 ArgTys.push_back(CI->getArgOperand(I)->getType());
552 ArgTys.push_back(PtrTy);
553
554 Name = Name + "_" + std::to_string(Size);
555 auto *FTy = FunctionType::get(Callee->getReturnType(),
556 ArrayRef<Type *>(ArgTys), false);
557 AMDGPULibFunc NewLibFunc(Name, FTy);
559 if (!F)
560 return false;
561
563 for (unsigned I = 0; I != PtrArgLoc; ++I)
564 Args.push_back(CI->getArgOperand(I));
565 Args.push_back(PtrArg);
566
567 auto *NCI = B.CreateCall(F, Args);
568 NCI->setAttributes(CI->getAttributes());
569 CI->replaceAllUsesWith(NCI);
570 CI->dropAllReferences();
571 CI->eraseFromParent();
572
573 return true;
574}
575
576static bool isKnownIntegral(const Value *V, const DataLayout &DL,
577 FastMathFlags FMF) {
578 if (isa<UndefValue>(V))
579 return true;
580
581 if (const ConstantFP *CF = dyn_cast<ConstantFP>(V))
582 return CF->getValueAPF().isInteger();
583
584 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
585 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
586 Constant *ConstElt = CDV->getElementAsConstant(i);
587 if (isa<UndefValue>(ConstElt))
588 continue;
589 const ConstantFP *CFP = dyn_cast<ConstantFP>(ConstElt);
590 if (!CFP || !CFP->getValue().isInteger())
591 return false;
592 }
593
594 return true;
595 }
596
597 const Instruction *I = dyn_cast<Instruction>(V);
598 if (!I)
599 return false;
600
601 switch (I->getOpcode()) {
602 case Instruction::SIToFP:
603 case Instruction::UIToFP:
604 // TODO: Could check nofpclass(inf) on incoming argument
605 if (FMF.noInfs())
606 return true;
607
608 // Need to check int size cannot produce infinity, which computeKnownFPClass
609 // knows how to do already.
610 return isKnownNeverInfinity(I, /*Depth=*/0, SimplifyQuery(DL));
611 case Instruction::Call: {
612 const CallInst *CI = cast<CallInst>(I);
613 switch (CI->getIntrinsicID()) {
614 case Intrinsic::trunc:
615 case Intrinsic::floor:
616 case Intrinsic::ceil:
617 case Intrinsic::rint:
618 case Intrinsic::nearbyint:
619 case Intrinsic::round:
620 case Intrinsic::roundeven:
621 return (FMF.noInfs() && FMF.noNaNs()) ||
622 isKnownNeverInfOrNaN(I, /*Depth=*/0, SimplifyQuery(DL));
623 default:
624 break;
625 }
626
627 break;
628 }
629 default:
630 break;
631 }
632
633 return false;
634}
635
636// This function returns false if no change; return true otherwise.
638 Function *Callee = CI->getCalledFunction();
639 // Ignore indirect calls.
640 if (!Callee || Callee->isIntrinsic() || CI->isNoBuiltin())
641 return false;
642
643 FuncInfo FInfo;
644 if (!parseFunctionName(Callee->getName(), FInfo))
645 return false;
646
647 // Further check the number of arguments to see if they match.
648 // TODO: Check calling convention matches too
649 if (!FInfo.isCompatibleSignature(CI->getFunctionType()))
650 return false;
651
652 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << '\n');
653
654 if (TDOFold(CI, FInfo))
655 return true;
656
657 IRBuilder<> B(CI);
658
659 if (FPMathOperator *FPOp = dyn_cast<FPMathOperator>(CI)) {
660 // Under unsafe-math, evaluate calls if possible.
661 // According to Brian Sumner, we can do this for all f32 function calls
662 // using host's double function calls.
663 if (canIncreasePrecisionOfConstantFold(FPOp) && evaluateCall(CI, FInfo))
664 return true;
665
666 // Copy fast flags from the original call.
667 FastMathFlags FMF = FPOp->getFastMathFlags();
668 B.setFastMathFlags(FMF);
669
670 // Specialized optimizations for each function call.
671 //
672 // TODO: Handle native functions
673 switch (FInfo.getId()) {
675 if (FMF.none())
676 return false;
677 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp,
678 FMF.approxFunc());
680 if (FMF.none())
681 return false;
682 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp2,
683 FMF.approxFunc());
685 if (FMF.none())
686 return false;
687 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log,
688 FMF.approxFunc());
690 if (FMF.none())
691 return false;
692 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log2,
693 FMF.approxFunc());
695 if (FMF.none())
696 return false;
697 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log10,
698 FMF.approxFunc());
700 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::minnum,
701 true, true);
703 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::maxnum,
704 true, true);
706 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fma, true,
707 true);
709 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fmuladd,
710 true, true);
712 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fabs, true,
713 true, true);
715 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::copysign,
716 true, true, true);
718 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::floor, true,
719 true);
721 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::ceil, true,
722 true);
724 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::trunc, true,
725 true);
727 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::rint, true,
728 true);
730 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::round, true,
731 true);
733 if (!shouldReplaceLibcallWithIntrinsic(CI, true, true))
734 return false;
735
736 Value *Arg1 = CI->getArgOperand(1);
737 if (VectorType *VecTy = dyn_cast<VectorType>(CI->getType());
738 VecTy && !isa<VectorType>(Arg1->getType())) {
739 Value *SplatArg1 = B.CreateVectorSplat(VecTy->getElementCount(), Arg1);
740 CI->setArgOperand(1, SplatArg1);
741 }
742
744 CI->getModule(), Intrinsic::ldexp,
745 {CI->getType(), CI->getArgOperand(1)->getType()}));
746 return true;
747 }
749 Module *M = Callee->getParent();
750 AMDGPULibFunc PowrInfo(AMDGPULibFunc::EI_POWR, FInfo);
751 FunctionCallee PowrFunc = getFunction(M, PowrInfo);
752 CallInst *Call = cast<CallInst>(FPOp);
753
754 // pow(x, y) -> powr(x, y) for x >= -0.0
755 // TODO: Account for flags on current call
756 if (PowrFunc &&
758 FPOp->getOperand(0), /*Depth=*/0,
759 SimplifyQuery(M->getDataLayout(), TLInfo, DT, AC, Call))) {
760 Call->setCalledFunction(PowrFunc);
761 return fold_pow(FPOp, B, PowrInfo) || true;
762 }
763
764 // pow(x, y) -> pown(x, y) for known integral y
765 if (isKnownIntegral(FPOp->getOperand(1), M->getDataLayout(),
766 FPOp->getFastMathFlags())) {
767 FunctionType *PownType = getPownType(CI->getFunctionType());
768 AMDGPULibFunc PownInfo(AMDGPULibFunc::EI_POWN, PownType, true);
769 FunctionCallee PownFunc = getFunction(M, PownInfo);
770 if (PownFunc) {
771 // TODO: If the incoming integral value is an sitofp/uitofp, it won't
772 // fold out without a known range. We can probably take the source
773 // value directly.
774 Value *CastedArg =
775 B.CreateFPToSI(FPOp->getOperand(1), PownType->getParamType(1));
776 // Have to drop any nofpclass attributes on the original call site.
777 Call->removeParamAttrs(
779 Call->setCalledFunction(PownFunc);
780 Call->setArgOperand(1, CastedArg);
781 return fold_pow(FPOp, B, PownInfo) || true;
782 }
783 }
784
785 return fold_pow(FPOp, B, FInfo);
786 }
789 return fold_pow(FPOp, B, FInfo);
791 return fold_rootn(FPOp, B, FInfo);
793 // TODO: Allow with strictfp + constrained intrinsic
794 return tryReplaceLibcallWithSimpleIntrinsic(
795 B, CI, Intrinsic::sqrt, true, true, /*AllowStrictFP=*/false);
798 return fold_sincos(FPOp, B, FInfo);
799 default:
800 break;
801 }
802 } else {
803 // Specialized optimizations for each function call
804 switch (FInfo.getId()) {
809 return fold_read_write_pipe(CI, B, FInfo);
810 default:
811 break;
812 }
813 }
814
815 return false;
816}
817
818bool AMDGPULibCalls::TDOFold(CallInst *CI, const FuncInfo &FInfo) {
819 // Table-Driven optimization
820 const TableRef tr = getOptTable(FInfo.getId());
821 if (tr.empty())
822 return false;
823
824 int const sz = (int)tr.size();
825 Value *opr0 = CI->getArgOperand(0);
826
827 if (getVecSize(FInfo) > 1) {
828 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(opr0)) {
830 for (int eltNo = 0; eltNo < getVecSize(FInfo); ++eltNo) {
831 ConstantFP *eltval = dyn_cast<ConstantFP>(
832 CV->getElementAsConstant((unsigned)eltNo));
833 assert(eltval && "Non-FP arguments in math function!");
834 bool found = false;
835 for (int i=0; i < sz; ++i) {
836 if (eltval->isExactlyValue(tr[i].input)) {
837 DVal.push_back(tr[i].result);
838 found = true;
839 break;
840 }
841 }
842 if (!found) {
843 // This vector constants not handled yet.
844 return false;
845 }
846 }
847 LLVMContext &context = CI->getParent()->getParent()->getContext();
848 Constant *nval;
849 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
851 for (unsigned i = 0; i < DVal.size(); ++i) {
852 FVal.push_back((float)DVal[i]);
853 }
854 ArrayRef<float> tmp(FVal);
855 nval = ConstantDataVector::get(context, tmp);
856 } else { // F64
857 ArrayRef<double> tmp(DVal);
858 nval = ConstantDataVector::get(context, tmp);
859 }
860 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
861 replaceCall(CI, nval);
862 return true;
863 }
864 } else {
865 // Scalar version
866 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) {
867 for (int i = 0; i < sz; ++i) {
868 if (CF->isExactlyValue(tr[i].input)) {
869 Value *nval = ConstantFP::get(CF->getType(), tr[i].result);
870 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
871 replaceCall(CI, nval);
872 return true;
873 }
874 }
875 }
876 }
877
878 return false;
879}
880
881namespace llvm {
882static double log2(double V) {
883#if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
884 return ::log2(V);
885#else
886 return log(V) / numbers::ln2;
887#endif
888}
889}
890
891bool AMDGPULibCalls::fold_pow(FPMathOperator *FPOp, IRBuilder<> &B,
892 const FuncInfo &FInfo) {
893 assert((FInfo.getId() == AMDGPULibFunc::EI_POW ||
894 FInfo.getId() == AMDGPULibFunc::EI_POWR ||
895 FInfo.getId() == AMDGPULibFunc::EI_POWN) &&
896 "fold_pow: encounter a wrong function call");
897
898 Module *M = B.GetInsertBlock()->getModule();
899 Type *eltType = FPOp->getType()->getScalarType();
900 Value *opr0 = FPOp->getOperand(0);
901 Value *opr1 = FPOp->getOperand(1);
902
903 const APFloat *CF = nullptr;
904 const APInt *CINT = nullptr;
905 if (!match(opr1, m_APFloatAllowUndef(CF)))
906 match(opr1, m_APIntAllowUndef(CINT));
907
908 // 0x1111111 means that we don't do anything for this call.
909 int ci_opr1 = (CINT ? (int)CINT->getSExtValue() : 0x1111111);
910
911 if ((CF && CF->isZero()) || (CINT && ci_opr1 == 0)) {
912 // pow/powr/pown(x, 0) == 1
913 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1\n");
914 Constant *cnval = ConstantFP::get(eltType, 1.0);
915 if (getVecSize(FInfo) > 1) {
916 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
917 }
918 replaceCall(FPOp, cnval);
919 return true;
920 }
921 if ((CF && CF->isExactlyValue(1.0)) || (CINT && ci_opr1 == 1)) {
922 // pow/powr/pown(x, 1.0) = x
923 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
924 replaceCall(FPOp, opr0);
925 return true;
926 }
927 if ((CF && CF->isExactlyValue(2.0)) || (CINT && ci_opr1 == 2)) {
928 // pow/powr/pown(x, 2.0) = x*x
929 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << " * "
930 << *opr0 << "\n");
931 Value *nval = B.CreateFMul(opr0, opr0, "__pow2");
932 replaceCall(FPOp, nval);
933 return true;
934 }
935 if ((CF && CF->isExactlyValue(-1.0)) || (CINT && ci_opr1 == -1)) {
936 // pow/powr/pown(x, -1.0) = 1.0/x
937 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1 / " << *opr0 << "\n");
938 Constant *cnval = ConstantFP::get(eltType, 1.0);
939 if (getVecSize(FInfo) > 1) {
940 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
941 }
942 Value *nval = B.CreateFDiv(cnval, opr0, "__powrecip");
943 replaceCall(FPOp, nval);
944 return true;
945 }
946
947 if (CF && (CF->isExactlyValue(0.5) || CF->isExactlyValue(-0.5))) {
948 // pow[r](x, [-]0.5) = sqrt(x)
949 bool issqrt = CF->isExactlyValue(0.5);
950 if (FunctionCallee FPExpr =
951 getFunction(M, AMDGPULibFunc(issqrt ? AMDGPULibFunc::EI_SQRT
953 FInfo))) {
954 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << FInfo.getName()
955 << '(' << *opr0 << ")\n");
956 Value *nval = CreateCallEx(B,FPExpr, opr0, issqrt ? "__pow2sqrt"
957 : "__pow2rsqrt");
958 replaceCall(FPOp, nval);
959 return true;
960 }
961 }
962
963 if (!isUnsafeFiniteOnlyMath(FPOp))
964 return false;
965
966 // Unsafe Math optimization
967
968 // Remember that ci_opr1 is set if opr1 is integral
969 if (CF) {
970 double dval = (getArgType(FInfo) == AMDGPULibFunc::F32)
971 ? (double)CF->convertToFloat()
972 : CF->convertToDouble();
973 int ival = (int)dval;
974 if ((double)ival == dval) {
975 ci_opr1 = ival;
976 } else
977 ci_opr1 = 0x11111111;
978 }
979
980 // pow/powr/pown(x, c) = [1/](x*x*..x); where
981 // trunc(c) == c && the number of x == c && |c| <= 12
982 unsigned abs_opr1 = (ci_opr1 < 0) ? -ci_opr1 : ci_opr1;
983 if (abs_opr1 <= 12) {
984 Constant *cnval;
985 Value *nval;
986 if (abs_opr1 == 0) {
987 cnval = ConstantFP::get(eltType, 1.0);
988 if (getVecSize(FInfo) > 1) {
989 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
990 }
991 nval = cnval;
992 } else {
993 Value *valx2 = nullptr;
994 nval = nullptr;
995 while (abs_opr1 > 0) {
996 valx2 = valx2 ? B.CreateFMul(valx2, valx2, "__powx2") : opr0;
997 if (abs_opr1 & 1) {
998 nval = nval ? B.CreateFMul(nval, valx2, "__powprod") : valx2;
999 }
1000 abs_opr1 >>= 1;
1001 }
1002 }
1003
1004 if (ci_opr1 < 0) {
1005 cnval = ConstantFP::get(eltType, 1.0);
1006 if (getVecSize(FInfo) > 1) {
1007 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
1008 }
1009 nval = B.CreateFDiv(cnval, nval, "__1powprod");
1010 }
1011 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1012 << ((ci_opr1 < 0) ? "1/prod(" : "prod(") << *opr0
1013 << ")\n");
1014 replaceCall(FPOp, nval);
1015 return true;
1016 }
1017
1018 // If we should use the generic intrinsic instead of emitting a libcall
1019 const bool ShouldUseIntrinsic = eltType->isFloatTy() || eltType->isHalfTy();
1020
1021 // powr ---> exp2(y * log2(x))
1022 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
1023 FunctionCallee ExpExpr;
1024 if (ShouldUseIntrinsic)
1025 ExpExpr = Intrinsic::getDeclaration(M, Intrinsic::exp2, {FPOp->getType()});
1026 else {
1027 ExpExpr = getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2, FInfo));
1028 if (!ExpExpr)
1029 return false;
1030 }
1031
1032 bool needlog = false;
1033 bool needabs = false;
1034 bool needcopysign = false;
1035 Constant *cnval = nullptr;
1036 if (getVecSize(FInfo) == 1) {
1037 CF = nullptr;
1038 match(opr0, m_APFloatAllowUndef(CF));
1039
1040 if (CF) {
1041 double V = (getArgType(FInfo) == AMDGPULibFunc::F32)
1042 ? (double)CF->convertToFloat()
1043 : CF->convertToDouble();
1044
1045 V = log2(std::abs(V));
1046 cnval = ConstantFP::get(eltType, V);
1047 needcopysign = (FInfo.getId() != AMDGPULibFunc::EI_POWR) &&
1048 CF->isNegative();
1049 } else {
1050 needlog = true;
1051 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
1052 }
1053 } else {
1054 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr0);
1055
1056 if (!CDV) {
1057 needlog = true;
1058 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
1059 } else {
1060 assert ((int)CDV->getNumElements() == getVecSize(FInfo) &&
1061 "Wrong vector size detected");
1062
1064 for (int i=0; i < getVecSize(FInfo); ++i) {
1065 double V = CDV->getElementAsAPFloat(i).convertToDouble();
1066 if (V < 0.0) needcopysign = true;
1067 V = log2(std::abs(V));
1068 DVal.push_back(V);
1069 }
1070 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1072 for (unsigned i=0; i < DVal.size(); ++i) {
1073 FVal.push_back((float)DVal[i]);
1074 }
1075 ArrayRef<float> tmp(FVal);
1076 cnval = ConstantDataVector::get(M->getContext(), tmp);
1077 } else {
1078 ArrayRef<double> tmp(DVal);
1079 cnval = ConstantDataVector::get(M->getContext(), tmp);
1080 }
1081 }
1082 }
1083
1084 if (needcopysign && (FInfo.getId() == AMDGPULibFunc::EI_POW)) {
1085 // We cannot handle corner cases for a general pow() function, give up
1086 // unless y is a constant integral value. Then proceed as if it were pown.
1087 if (!isKnownIntegral(opr1, M->getDataLayout(), FPOp->getFastMathFlags()))
1088 return false;
1089 }
1090
1091 Value *nval;
1092 if (needabs) {
1093 nval = B.CreateUnaryIntrinsic(Intrinsic::fabs, opr0, nullptr, "__fabs");
1094 } else {
1095 nval = cnval ? cnval : opr0;
1096 }
1097 if (needlog) {
1098 FunctionCallee LogExpr;
1099 if (ShouldUseIntrinsic) {
1100 LogExpr =
1101 Intrinsic::getDeclaration(M, Intrinsic::log2, {FPOp->getType()});
1102 } else {
1103 LogExpr = getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2, FInfo));
1104 if (!LogExpr)
1105 return false;
1106 }
1107
1108 nval = CreateCallEx(B,LogExpr, nval, "__log2");
1109 }
1110
1111 if (FInfo.getId() == AMDGPULibFunc::EI_POWN) {
1112 // convert int(32) to fp(f32 or f64)
1113 opr1 = B.CreateSIToFP(opr1, nval->getType(), "pownI2F");
1114 }
1115 nval = B.CreateFMul(opr1, nval, "__ylogx");
1116 nval = CreateCallEx(B,ExpExpr, nval, "__exp2");
1117
1118 if (needcopysign) {
1119 Value *opr_n;
1120 Type* rTy = opr0->getType();
1121 Type* nTyS = B.getIntNTy(eltType->getPrimitiveSizeInBits());
1122 Type *nTy = nTyS;
1123 if (const auto *vTy = dyn_cast<FixedVectorType>(rTy))
1124 nTy = FixedVectorType::get(nTyS, vTy);
1125 unsigned size = nTy->getScalarSizeInBits();
1126 opr_n = FPOp->getOperand(1);
1127 if (opr_n->getType()->isIntegerTy())
1128 opr_n = B.CreateZExtOrTrunc(opr_n, nTy, "__ytou");
1129 else
1130 opr_n = B.CreateFPToSI(opr1, nTy, "__ytou");
1131
1132 Value *sign = B.CreateShl(opr_n, size-1, "__yeven");
1133 sign = B.CreateAnd(B.CreateBitCast(opr0, nTy), sign, "__pow_sign");
1134 nval = B.CreateOr(B.CreateBitCast(nval, nTy), sign);
1135 nval = B.CreateBitCast(nval, opr0->getType());
1136 }
1137
1138 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1139 << "exp2(" << *opr1 << " * log2(" << *opr0 << "))\n");
1140 replaceCall(FPOp, nval);
1141
1142 return true;
1143}
1144
1145bool AMDGPULibCalls::fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B,
1146 const FuncInfo &FInfo) {
1147 // skip vector function
1148 if (getVecSize(FInfo) != 1)
1149 return false;
1150
1151 Value *opr0 = FPOp->getOperand(0);
1152 Value *opr1 = FPOp->getOperand(1);
1153
1154 ConstantInt *CINT = dyn_cast<ConstantInt>(opr1);
1155 if (!CINT) {
1156 return false;
1157 }
1158 int ci_opr1 = (int)CINT->getSExtValue();
1159 if (ci_opr1 == 1) { // rootn(x, 1) = x
1160 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
1161 replaceCall(FPOp, opr0);
1162 return true;
1163 }
1164
1165 Module *M = B.GetInsertBlock()->getModule();
1166 if (ci_opr1 == 2) { // rootn(x, 2) = sqrt(x)
1167 if (FunctionCallee FPExpr =
1168 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1169 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> sqrt(" << *opr0
1170 << ")\n");
1171 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2sqrt");
1172 replaceCall(FPOp, nval);
1173 return true;
1174 }
1175 } else if (ci_opr1 == 3) { // rootn(x, 3) = cbrt(x)
1176 if (FunctionCallee FPExpr =
1177 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT, FInfo))) {
1178 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> cbrt(" << *opr0
1179 << ")\n");
1180 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2cbrt");
1181 replaceCall(FPOp, nval);
1182 return true;
1183 }
1184 } else if (ci_opr1 == -1) { // rootn(x, -1) = 1.0/x
1185 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1.0 / " << *opr0 << "\n");
1186 Value *nval = B.CreateFDiv(ConstantFP::get(opr0->getType(), 1.0),
1187 opr0,
1188 "__rootn2div");
1189 replaceCall(FPOp, nval);
1190 return true;
1191 } else if (ci_opr1 == -2) { // rootn(x, -2) = rsqrt(x)
1192 if (FunctionCallee FPExpr =
1193 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT, FInfo))) {
1194 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> rsqrt(" << *opr0
1195 << ")\n");
1196 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2rsqrt");
1197 replaceCall(FPOp, nval);
1198 return true;
1199 }
1200 }
1201 return false;
1202}
1203
1204// Get a scalar native builtin single argument FP function
1205FunctionCallee AMDGPULibCalls::getNativeFunction(Module *M,
1206 const FuncInfo &FInfo) {
1207 if (getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()))
1208 return nullptr;
1209 FuncInfo nf = FInfo;
1211 return getFunction(M, nf);
1212}
1213
1214// Some library calls are just wrappers around llvm intrinsics, but compiled
1215// conservatively. Preserve the flags from the original call site by
1216// substituting them with direct calls with all the flags.
1217bool AMDGPULibCalls::shouldReplaceLibcallWithIntrinsic(const CallInst *CI,
1218 bool AllowMinSizeF32,
1219 bool AllowF64,
1220 bool AllowStrictFP) {
1221 Type *FltTy = CI->getType()->getScalarType();
1222 const bool IsF32 = FltTy->isFloatTy();
1223
1224 // f64 intrinsics aren't implemented for most operations.
1225 if (!IsF32 && !FltTy->isHalfTy() && (!AllowF64 || !FltTy->isDoubleTy()))
1226 return false;
1227
1228 // We're implicitly inlining by replacing the libcall with the intrinsic, so
1229 // don't do it for noinline call sites.
1230 if (CI->isNoInline())
1231 return false;
1232
1233 const Function *ParentF = CI->getFunction();
1234 // TODO: Handle strictfp
1235 if (!AllowStrictFP && ParentF->hasFnAttribute(Attribute::StrictFP))
1236 return false;
1237
1238 if (IsF32 && !AllowMinSizeF32 && ParentF->hasMinSize())
1239 return false;
1240 return true;
1241}
1242
1243void AMDGPULibCalls::replaceLibCallWithSimpleIntrinsic(IRBuilder<> &B,
1244 CallInst *CI,
1245 Intrinsic::ID IntrID) {
1246 if (CI->arg_size() == 2) {
1247 Value *Arg0 = CI->getArgOperand(0);
1248 Value *Arg1 = CI->getArgOperand(1);
1249 VectorType *Arg0VecTy = dyn_cast<VectorType>(Arg0->getType());
1250 VectorType *Arg1VecTy = dyn_cast<VectorType>(Arg1->getType());
1251 if (Arg0VecTy && !Arg1VecTy) {
1252 Value *SplatRHS = B.CreateVectorSplat(Arg0VecTy->getElementCount(), Arg1);
1253 CI->setArgOperand(1, SplatRHS);
1254 } else if (!Arg0VecTy && Arg1VecTy) {
1255 Value *SplatLHS = B.CreateVectorSplat(Arg1VecTy->getElementCount(), Arg0);
1256 CI->setArgOperand(0, SplatLHS);
1257 }
1258 }
1259
1261 Intrinsic::getDeclaration(CI->getModule(), IntrID, {CI->getType()}));
1262}
1263
1264bool AMDGPULibCalls::tryReplaceLibcallWithSimpleIntrinsic(
1265 IRBuilder<> &B, CallInst *CI, Intrinsic::ID IntrID, bool AllowMinSizeF32,
1266 bool AllowF64, bool AllowStrictFP) {
1267 if (!shouldReplaceLibcallWithIntrinsic(CI, AllowMinSizeF32, AllowF64,
1268 AllowStrictFP))
1269 return false;
1270 replaceLibCallWithSimpleIntrinsic(B, CI, IntrID);
1271 return true;
1272}
1273
1274std::tuple<Value *, Value *, Value *>
1275AMDGPULibCalls::insertSinCos(Value *Arg, FastMathFlags FMF, IRBuilder<> &B,
1276 FunctionCallee Fsincos) {
1277 DebugLoc DL = B.getCurrentDebugLocation();
1278 Function *F = B.GetInsertBlock()->getParent();
1279 B.SetInsertPointPastAllocas(F);
1280
1281 AllocaInst *Alloc = B.CreateAlloca(Arg->getType(), nullptr, "__sincos_");
1282
1283 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1284 // If the argument is an instruction, it must dominate all uses so put our
1285 // sincos call there. Otherwise, right after the allocas works well enough
1286 // if it's an argument or constant.
1287
1288 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1289
1290 // SetInsertPoint unwelcomely always tries to set the debug loc.
1291 B.SetCurrentDebugLocation(DL);
1292 }
1293
1294 Type *CosPtrTy = Fsincos.getFunctionType()->getParamType(1);
1295
1296 // The allocaInst allocates the memory in private address space. This need
1297 // to be addrspacecasted to point to the address space of cos pointer type.
1298 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1299 Value *CastAlloc = B.CreateAddrSpaceCast(Alloc, CosPtrTy);
1300
1301 CallInst *SinCos = CreateCallEx2(B, Fsincos, Arg, CastAlloc);
1302
1303 // TODO: Is it worth trying to preserve the location for the cos calls for the
1304 // load?
1305
1306 LoadInst *LoadCos = B.CreateLoad(Alloc->getAllocatedType(), Alloc);
1307 return {SinCos, LoadCos, SinCos};
1308}
1309
1310// fold sin, cos -> sincos.
1311bool AMDGPULibCalls::fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B,
1312 const FuncInfo &fInfo) {
1313 assert(fInfo.getId() == AMDGPULibFunc::EI_SIN ||
1314 fInfo.getId() == AMDGPULibFunc::EI_COS);
1315
1316 if ((getArgType(fInfo) != AMDGPULibFunc::F32 &&
1317 getArgType(fInfo) != AMDGPULibFunc::F64) ||
1318 fInfo.getPrefix() != AMDGPULibFunc::NOPFX)
1319 return false;
1320
1321 bool const isSin = fInfo.getId() == AMDGPULibFunc::EI_SIN;
1322
1323 Value *CArgVal = FPOp->getOperand(0);
1324 CallInst *CI = cast<CallInst>(FPOp);
1325
1326 Function *F = B.GetInsertBlock()->getParent();
1327 Module *M = F->getParent();
1328
1329 // Merge the sin and cos. For OpenCL 2.0, there may only be a generic pointer
1330 // implementation. Prefer the private form if available.
1331 AMDGPULibFunc SinCosLibFuncPrivate(AMDGPULibFunc::EI_SINCOS, fInfo);
1332 SinCosLibFuncPrivate.getLeads()[0].PtrKind =
1334
1335 AMDGPULibFunc SinCosLibFuncGeneric(AMDGPULibFunc::EI_SINCOS, fInfo);
1336 SinCosLibFuncGeneric.getLeads()[0].PtrKind =
1338
1339 FunctionCallee FSinCosPrivate = getFunction(M, SinCosLibFuncPrivate);
1340 FunctionCallee FSinCosGeneric = getFunction(M, SinCosLibFuncGeneric);
1341 FunctionCallee FSinCos = FSinCosPrivate ? FSinCosPrivate : FSinCosGeneric;
1342 if (!FSinCos)
1343 return false;
1344
1345 SmallVector<CallInst *> SinCalls;
1346 SmallVector<CallInst *> CosCalls;
1347 SmallVector<CallInst *> SinCosCalls;
1348 FuncInfo PartnerInfo(isSin ? AMDGPULibFunc::EI_COS : AMDGPULibFunc::EI_SIN,
1349 fInfo);
1350 const std::string PairName = PartnerInfo.mangle();
1351
1352 StringRef SinName = isSin ? CI->getCalledFunction()->getName() : PairName;
1353 StringRef CosName = isSin ? PairName : CI->getCalledFunction()->getName();
1354 const std::string SinCosPrivateName = SinCosLibFuncPrivate.mangle();
1355 const std::string SinCosGenericName = SinCosLibFuncGeneric.mangle();
1356
1357 // Intersect the two sets of flags.
1358 FastMathFlags FMF = FPOp->getFastMathFlags();
1359 MDNode *FPMath = CI->getMetadata(LLVMContext::MD_fpmath);
1360
1361 SmallVector<DILocation *> MergeDbgLocs = {CI->getDebugLoc()};
1362
1363 for (User* U : CArgVal->users()) {
1364 CallInst *XI = dyn_cast<CallInst>(U);
1365 if (!XI || XI->getFunction() != F || XI->isNoBuiltin())
1366 continue;
1367
1368 Function *UCallee = XI->getCalledFunction();
1369 if (!UCallee)
1370 continue;
1371
1372 bool Handled = true;
1373
1374 if (UCallee->getName() == SinName)
1375 SinCalls.push_back(XI);
1376 else if (UCallee->getName() == CosName)
1377 CosCalls.push_back(XI);
1378 else if (UCallee->getName() == SinCosPrivateName ||
1379 UCallee->getName() == SinCosGenericName)
1380 SinCosCalls.push_back(XI);
1381 else
1382 Handled = false;
1383
1384 if (Handled) {
1385 MergeDbgLocs.push_back(XI->getDebugLoc());
1386 auto *OtherOp = cast<FPMathOperator>(XI);
1387 FMF &= OtherOp->getFastMathFlags();
1389 FPMath, XI->getMetadata(LLVMContext::MD_fpmath));
1390 }
1391 }
1392
1393 if (SinCalls.empty() || CosCalls.empty())
1394 return false;
1395
1396 B.setFastMathFlags(FMF);
1397 B.setDefaultFPMathTag(FPMath);
1398 DILocation *DbgLoc = DILocation::getMergedLocations(MergeDbgLocs);
1399 B.SetCurrentDebugLocation(DbgLoc);
1400
1401 auto [Sin, Cos, SinCos] = insertSinCos(CArgVal, FMF, B, FSinCos);
1402
1403 auto replaceTrigInsts = [](ArrayRef<CallInst *> Calls, Value *Res) {
1404 for (CallInst *C : Calls)
1405 C->replaceAllUsesWith(Res);
1406
1407 // Leave the other dead instructions to avoid clobbering iterators.
1408 };
1409
1410 replaceTrigInsts(SinCalls, Sin);
1411 replaceTrigInsts(CosCalls, Cos);
1412 replaceTrigInsts(SinCosCalls, SinCos);
1413
1414 // It's safe to delete the original now.
1415 CI->eraseFromParent();
1416 return true;
1417}
1418
1419bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
1420 double &Res1, Constant *copr0,
1421 Constant *copr1) {
1422 // By default, opr0/opr1/opr3 holds values of float/double type.
1423 // If they are not float/double, each function has to its
1424 // operand separately.
1425 double opr0 = 0.0, opr1 = 0.0;
1426 ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0);
1427 ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1);
1428 if (fpopr0) {
1429 opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1430 ? fpopr0->getValueAPF().convertToDouble()
1431 : (double)fpopr0->getValueAPF().convertToFloat();
1432 }
1433
1434 if (fpopr1) {
1435 opr1 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1436 ? fpopr1->getValueAPF().convertToDouble()
1437 : (double)fpopr1->getValueAPF().convertToFloat();
1438 }
1439
1440 switch (FInfo.getId()) {
1441 default : return false;
1442
1444 Res0 = acos(opr0);
1445 return true;
1446
1448 // acosh(x) == log(x + sqrt(x*x - 1))
1449 Res0 = log(opr0 + sqrt(opr0*opr0 - 1.0));
1450 return true;
1451
1453 Res0 = acos(opr0) / MATH_PI;
1454 return true;
1455
1457 Res0 = asin(opr0);
1458 return true;
1459
1461 // asinh(x) == log(x + sqrt(x*x + 1))
1462 Res0 = log(opr0 + sqrt(opr0*opr0 + 1.0));
1463 return true;
1464
1466 Res0 = asin(opr0) / MATH_PI;
1467 return true;
1468
1470 Res0 = atan(opr0);
1471 return true;
1472
1474 // atanh(x) == (log(x+1) - log(x-1))/2;
1475 Res0 = (log(opr0 + 1.0) - log(opr0 - 1.0))/2.0;
1476 return true;
1477
1479 Res0 = atan(opr0) / MATH_PI;
1480 return true;
1481
1483 Res0 = (opr0 < 0.0) ? -pow(-opr0, 1.0/3.0) : pow(opr0, 1.0/3.0);
1484 return true;
1485
1487 Res0 = cos(opr0);
1488 return true;
1489
1491 Res0 = cosh(opr0);
1492 return true;
1493
1495 Res0 = cos(MATH_PI * opr0);
1496 return true;
1497
1499 Res0 = exp(opr0);
1500 return true;
1501
1503 Res0 = pow(2.0, opr0);
1504 return true;
1505
1507 Res0 = pow(10.0, opr0);
1508 return true;
1509
1511 Res0 = log(opr0);
1512 return true;
1513
1515 Res0 = log(opr0) / log(2.0);
1516 return true;
1517
1519 Res0 = log(opr0) / log(10.0);
1520 return true;
1521
1523 Res0 = 1.0 / sqrt(opr0);
1524 return true;
1525
1527 Res0 = sin(opr0);
1528 return true;
1529
1531 Res0 = sinh(opr0);
1532 return true;
1533
1535 Res0 = sin(MATH_PI * opr0);
1536 return true;
1537
1539 Res0 = tan(opr0);
1540 return true;
1541
1543 Res0 = tanh(opr0);
1544 return true;
1545
1547 Res0 = tan(MATH_PI * opr0);
1548 return true;
1549
1550 // two-arg functions
1553 Res0 = pow(opr0, opr1);
1554 return true;
1555
1557 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1558 double val = (double)iopr1->getSExtValue();
1559 Res0 = pow(opr0, val);
1560 return true;
1561 }
1562 return false;
1563 }
1564
1566 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1567 double val = (double)iopr1->getSExtValue();
1568 Res0 = pow(opr0, 1.0 / val);
1569 return true;
1570 }
1571 return false;
1572 }
1573
1574 // with ptr arg
1576 Res0 = sin(opr0);
1577 Res1 = cos(opr0);
1578 return true;
1579 }
1580
1581 return false;
1582}
1583
1584bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) {
1585 int numArgs = (int)aCI->arg_size();
1586 if (numArgs > 3)
1587 return false;
1588
1589 Constant *copr0 = nullptr;
1590 Constant *copr1 = nullptr;
1591 if (numArgs > 0) {
1592 if ((copr0 = dyn_cast<Constant>(aCI->getArgOperand(0))) == nullptr)
1593 return false;
1594 }
1595
1596 if (numArgs > 1) {
1597 if ((copr1 = dyn_cast<Constant>(aCI->getArgOperand(1))) == nullptr) {
1598 if (FInfo.getId() != AMDGPULibFunc::EI_SINCOS)
1599 return false;
1600 }
1601 }
1602
1603 // At this point, all arguments to aCI are constants.
1604
1605 // max vector size is 16, and sincos will generate two results.
1606 double DVal0[16], DVal1[16];
1607 int FuncVecSize = getVecSize(FInfo);
1608 bool hasTwoResults = (FInfo.getId() == AMDGPULibFunc::EI_SINCOS);
1609 if (FuncVecSize == 1) {
1610 if (!evaluateScalarMathFunc(FInfo, DVal0[0], DVal1[0], copr0, copr1)) {
1611 return false;
1612 }
1613 } else {
1614 ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0);
1615 ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1);
1616 for (int i = 0; i < FuncVecSize; ++i) {
1617 Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr;
1618 Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr;
1619 if (!evaluateScalarMathFunc(FInfo, DVal0[i], DVal1[i], celt0, celt1)) {
1620 return false;
1621 }
1622 }
1623 }
1624
1625 LLVMContext &context = aCI->getContext();
1626 Constant *nval0, *nval1;
1627 if (FuncVecSize == 1) {
1628 nval0 = ConstantFP::get(aCI->getType(), DVal0[0]);
1629 if (hasTwoResults)
1630 nval1 = ConstantFP::get(aCI->getType(), DVal1[0]);
1631 } else {
1632 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1633 SmallVector <float, 0> FVal0, FVal1;
1634 for (int i = 0; i < FuncVecSize; ++i)
1635 FVal0.push_back((float)DVal0[i]);
1636 ArrayRef<float> tmp0(FVal0);
1637 nval0 = ConstantDataVector::get(context, tmp0);
1638 if (hasTwoResults) {
1639 for (int i = 0; i < FuncVecSize; ++i)
1640 FVal1.push_back((float)DVal1[i]);
1641 ArrayRef<float> tmp1(FVal1);
1642 nval1 = ConstantDataVector::get(context, tmp1);
1643 }
1644 } else {
1645 ArrayRef<double> tmp0(DVal0);
1646 nval0 = ConstantDataVector::get(context, tmp0);
1647 if (hasTwoResults) {
1648 ArrayRef<double> tmp1(DVal1);
1649 nval1 = ConstantDataVector::get(context, tmp1);
1650 }
1651 }
1652 }
1653
1654 if (hasTwoResults) {
1655 // sincos
1656 assert(FInfo.getId() == AMDGPULibFunc::EI_SINCOS &&
1657 "math function with ptr arg not supported yet");
1658 new StoreInst(nval1, aCI->getArgOperand(1), aCI);
1659 }
1660
1661 replaceCall(aCI, nval0);
1662 return true;
1663}
1664
1667 AMDGPULibCalls Simplifier;
1668 Simplifier.initNativeFuncs();
1669 Simplifier.initFunction(F, AM);
1670
1671 bool Changed = false;
1672
1673 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1674 F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';);
1675
1676 for (auto &BB : F) {
1677 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1678 // Ignore non-calls.
1679 CallInst *CI = dyn_cast<CallInst>(I);
1680 ++I;
1681
1682 if (CI) {
1683 if (Simplifier.fold(CI))
1684 Changed = true;
1685 }
1686 }
1687 }
1688 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1689}
1690
1693 if (UseNative.empty())
1694 return PreservedAnalyses::all();
1695
1696 AMDGPULibCalls Simplifier;
1697 Simplifier.initNativeFuncs();
1698 Simplifier.initFunction(F, AM);
1699
1700 bool Changed = false;
1701 for (auto &BB : F) {
1702 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1703 // Ignore non-calls.
1704 CallInst *CI = dyn_cast<CallInst>(I);
1705 ++I;
1706 if (CI && Simplifier.useNative(CI))
1707 Changed = true;
1708 }
1709 }
1710 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1711}
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")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-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:348
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:519
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:500
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:205
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:164
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: InstrTypes.h:2179
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1703
bool isNoInline() const
Return true if the call should not be inlined.
Definition: InstrTypes.h:2188
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1648
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1653
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1561
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:1646
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1780
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1742
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:2744
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index's element.
Definition: Constants.cpp:3086
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:3049
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:765
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2954
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:2893
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:267
const APFloat & getValue() const
Definition: Constants.h:311
const APFloat & getValueAPF() const
Definition: Constants.h:310
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:79
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:159
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:153
Align getAlignValue() const
Return the constant as an llvm::Align, interpreting 0 as Align(1).
Definition: Constants.h:171
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:200
bool isFast() const
Test if this operation allows all non-strict floating-point transforms.
Definition: Operator.h:271
bool hasNoNaNs() const
Test if this operation's arguments and results are assumed not-NaN.
Definition: Operator.h:287
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition: Operator.h:318
bool hasNoInfs() const
Test if this operation's arguments and results are assumed not-infinite.
Definition: Operator.h:292
bool hasApproxFunc() const
Test if this operation allows approximations of math library functions or intrinsics.
Definition: Operator.h:313
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:677
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:342
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:669
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2649
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:453
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:80
const BasicBlock * getParent() const
Definition: Instruction.h:151
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:84
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:358
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:1164
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
@ 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:1451
apfloat_match m_APFloatAllowUndef(const APFloat *&Res)
Match APFloat while allowing undefs in splat vector constants.
Definition: PatternMatch.h:317
apint_match m_APIntAllowUndef(const APInt *&Res)
Match APInt while allowing undefs in splat vector constants.
Definition: PatternMatch.h:300
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
@ 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:1689
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:1888
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