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