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