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