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