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