xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision 509893b58ff444a6f080946bd368e9bde7668f13)
1 //===-- AMDGPUCodeGenPrepare.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 pass does misc. AMDGPU optimizations on IR before instruction
11 /// selection.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "SIModeRegisterDefaults.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/UniformityAnalysis.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InstVisitor.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Transforms/Utils/IntegerDivision.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 
35 #define DEBUG_TYPE "amdgpu-codegenprepare"
36 
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 namespace {
41 
42 static cl::opt<bool> WidenLoads(
43   "amdgpu-codegenprepare-widen-constant-loads",
44   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
45   cl::ReallyHidden,
46   cl::init(false));
47 
48 static cl::opt<bool> Widen16BitOps(
49   "amdgpu-codegenprepare-widen-16-bit-ops",
50   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
51   cl::ReallyHidden,
52   cl::init(true));
53 
54 static cl::opt<bool>
55     BreakLargePHIs("amdgpu-codegenprepare-break-large-phis",
56                    cl::desc("Break large PHI nodes for DAGISel"),
57                    cl::ReallyHidden, cl::init(true));
58 
59 static cl::opt<bool>
60     ForceBreakLargePHIs("amdgpu-codegenprepare-force-break-large-phis",
61                         cl::desc("For testing purposes, always break large "
62                                  "PHIs even if it isn't profitable."),
63                         cl::ReallyHidden, cl::init(false));
64 
65 static cl::opt<unsigned> BreakLargePHIsThreshold(
66     "amdgpu-codegenprepare-break-large-phis-threshold",
67     cl::desc("Minimum type size in bits for breaking large PHI nodes"),
68     cl::ReallyHidden, cl::init(32));
69 
70 static cl::opt<bool> UseMul24Intrin(
71   "amdgpu-codegenprepare-mul24",
72   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
73   cl::ReallyHidden,
74   cl::init(true));
75 
76 // Legalize 64-bit division by using the generic IR expansion.
77 static cl::opt<bool> ExpandDiv64InIR(
78   "amdgpu-codegenprepare-expand-div64",
79   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
80   cl::ReallyHidden,
81   cl::init(false));
82 
83 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
84 // and is used for testing the legalizer.
85 static cl::opt<bool> DisableIDivExpand(
86   "amdgpu-codegenprepare-disable-idiv-expansion",
87   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
88   cl::ReallyHidden,
89   cl::init(false));
90 
91 // Disable processing of fdiv so we can better test the backend implementations.
92 static cl::opt<bool> DisableFDivExpand(
93   "amdgpu-codegenprepare-disable-fdiv-expansion",
94   cl::desc("Prevent expanding floating point division in AMDGPUCodeGenPrepare"),
95   cl::ReallyHidden,
96   cl::init(false));
97 
98 static bool hasUnsafeFPMath(const Function &F) {
99   return F.getFnAttribute("unsafe-fp-math").getValueAsBool();
100 }
101 
102 class AMDGPUCodeGenPrepareImpl
103     : public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
104 public:
105   Function &F;
106   const GCNSubtarget &ST;
107   const AMDGPUTargetMachine &TM;
108   const TargetLibraryInfo *TLI;
109   AssumptionCache *AC;
110   const DominatorTree *DT;
111   const UniformityInfo &UA;
112   const DataLayout &DL;
113   const bool HasUnsafeFPMath;
114   const bool HasFP32DenormalFlush;
115   bool FlowChanged = false;
116   mutable Function *SqrtF32 = nullptr;
117   mutable Function *LdexpF32 = nullptr;
118 
119   DenseMap<const PHINode *, bool> BreakPhiNodesCache;
120 
121   AMDGPUCodeGenPrepareImpl(Function &F, const AMDGPUTargetMachine &TM,
122                            const TargetLibraryInfo *TLI, AssumptionCache *AC,
123                            const DominatorTree *DT, const UniformityInfo &UA)
124       : F(F), ST(TM.getSubtarget<GCNSubtarget>(F)), TM(TM), TLI(TLI), AC(AC),
125         DT(DT), UA(UA), DL(F.getDataLayout()),
126         HasUnsafeFPMath(hasUnsafeFPMath(F)),
127         HasFP32DenormalFlush(SIModeRegisterDefaults(F, ST).FP32Denormals ==
128                              DenormalMode::getPreserveSign()) {}
129 
130   Function *getSqrtF32() const {
131     if (SqrtF32)
132       return SqrtF32;
133 
134     LLVMContext &Ctx = F.getContext();
135     SqrtF32 = Intrinsic::getOrInsertDeclaration(
136         F.getParent(), Intrinsic::amdgcn_sqrt, {Type::getFloatTy(Ctx)});
137     return SqrtF32;
138   }
139 
140   Function *getLdexpF32() const {
141     if (LdexpF32)
142       return LdexpF32;
143 
144     LLVMContext &Ctx = F.getContext();
145     LdexpF32 = Intrinsic::getOrInsertDeclaration(
146         F.getParent(), Intrinsic::ldexp,
147         {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
148     return LdexpF32;
149   }
150 
151   bool canBreakPHINode(const PHINode &I);
152 
153   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
154   /// binary operation \p V.
155   ///
156   /// \returns Binary operation \p V.
157   /// \returns \p T's base element bit width.
158   unsigned getBaseElementBitWidth(const Type *T) const;
159 
160   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
161   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
162   /// is returned.
163   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
164 
165   /// \returns True if binary operation \p I is a signed binary operation, false
166   /// otherwise.
167   bool isSigned(const BinaryOperator &I) const;
168 
169   /// \returns True if the condition of 'select' operation \p I comes from a
170   /// signed 'icmp' operation, false otherwise.
171   bool isSigned(const SelectInst &I) const;
172 
173   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
174   /// false otherwise.
175   bool needsPromotionToI32(const Type *T) const;
176 
177   /// Return true if \p T is a legal scalar floating point type.
178   bool isLegalFloatingTy(const Type *T) const;
179 
180   /// Wrapper to pass all the arguments to computeKnownFPClass
181   KnownFPClass computeKnownFPClass(const Value *V, FPClassTest Interested,
182                                    const Instruction *CtxI) const {
183     return llvm::computeKnownFPClass(V, DL, Interested, 0, TLI, AC, CtxI, DT);
184   }
185 
186   bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
187     return HasFP32DenormalFlush ||
188            computeKnownFPClass(V, fcSubnormal, CtxI).isKnownNeverSubnormal();
189   }
190 
191   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
192   /// operation.
193   ///
194   /// \details \p I's base element bit width must be greater than 1 and less
195   /// than or equal 16. Promotion is done by sign or zero extending operands to
196   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
197   /// truncating the result of 32 bit binary operation back to \p I's original
198   /// type. Division operation is not promoted.
199   ///
200   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
201   /// false otherwise.
202   bool promoteUniformOpToI32(BinaryOperator &I) const;
203 
204   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
205   ///
206   /// \details \p I's base element bit width must be greater than 1 and less
207   /// than or equal 16. Promotion is done by sign or zero extending operands to
208   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
209   ///
210   /// \returns True.
211   bool promoteUniformOpToI32(ICmpInst &I) const;
212 
213   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
214   /// operation.
215   ///
216   /// \details \p I's base element bit width must be greater than 1 and less
217   /// than or equal 16. Promotion is done by sign or zero extending operands to
218   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
219   /// result of 32 bit 'select' operation back to \p I's original type.
220   ///
221   /// \returns True.
222   bool promoteUniformOpToI32(SelectInst &I) const;
223 
224   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
225   /// intrinsic.
226   ///
227   /// \details \p I's base element bit width must be greater than 1 and less
228   /// than or equal 16. Promotion is done by zero extending the operand to 32
229   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
230   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
231   /// shift amount is 32 minus \p I's base element bit width), and truncating
232   /// the result of the shift operation back to \p I's original type.
233   ///
234   /// \returns True.
235   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
236 
237   /// \returns The minimum number of bits needed to store the value of \Op as an
238   /// unsigned integer. Truncating to this size and then zero-extending to
239   /// the original will not change the value.
240   unsigned numBitsUnsigned(Value *Op) const;
241 
242   /// \returns The minimum number of bits needed to store the value of \Op as a
243   /// signed integer. Truncating to this size and then sign-extending to
244   /// the original size will not change the value.
245   unsigned numBitsSigned(Value *Op) const;
246 
247   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
248   /// SelectionDAG has an issue where an and asserting the bits are known
249   bool replaceMulWithMul24(BinaryOperator &I) const;
250 
251   /// Perform same function as equivalently named function in DAGCombiner. Since
252   /// we expand some divisions here, we need to perform this before obscuring.
253   bool foldBinOpIntoSelect(BinaryOperator &I) const;
254 
255   bool divHasSpecialOptimization(BinaryOperator &I,
256                                  Value *Num, Value *Den) const;
257   int getDivNumBits(BinaryOperator &I,
258                     Value *Num, Value *Den,
259                     unsigned AtLeast, bool Signed) const;
260 
261   /// Expands 24 bit div or rem.
262   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
263                         Value *Num, Value *Den,
264                         bool IsDiv, bool IsSigned) const;
265 
266   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
267                             Value *Num, Value *Den, unsigned NumBits,
268                             bool IsDiv, bool IsSigned) const;
269 
270   /// Expands 32 bit div or rem.
271   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
272                         Value *Num, Value *Den) const;
273 
274   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
275                         Value *Num, Value *Den) const;
276   void expandDivRem64(BinaryOperator &I) const;
277 
278   /// Widen a scalar load.
279   ///
280   /// \details \p Widen scalar load for uniform, small type loads from constant
281   //  memory / to a full 32-bits and then truncate the input to allow a scalar
282   //  load instead of a vector load.
283   //
284   /// \returns True.
285 
286   bool canWidenScalarExtLoad(LoadInst &I) const;
287 
288   Value *matchFractPat(IntrinsicInst &I);
289   Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
290 
291   bool canOptimizeWithRsq(const FPMathOperator *SqrtOp, FastMathFlags DivFMF,
292                           FastMathFlags SqrtFMF) const;
293 
294   Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
295                          FastMathFlags DivFMF, FastMathFlags SqrtFMF,
296                          const Instruction *CtxI) const;
297 
298   Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
299                          FastMathFlags FMF, const Instruction *CtxI) const;
300   Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
301                               float ReqdAccuracy) const;
302 
303   Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
304                           FastMathFlags DivFMF, FastMathFlags SqrtFMF,
305                           Value *RsqOp, const Instruction *FDiv,
306                           float ReqdAccuracy) const;
307 
308   std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
309                                               Value *Src) const;
310 
311   Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
312                          bool IsNegative) const;
313   Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
314                       FastMathFlags FMF) const;
315   Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
316                           FastMathFlags FMF) const;
317 
318 public:
319   bool visitFDiv(BinaryOperator &I);
320 
321   bool visitInstruction(Instruction &I) { return false; }
322   bool visitBinaryOperator(BinaryOperator &I);
323   bool visitLoadInst(LoadInst &I);
324   bool visitICmpInst(ICmpInst &I);
325   bool visitSelectInst(SelectInst &I);
326   bool visitPHINode(PHINode &I);
327   bool visitAddrSpaceCastInst(AddrSpaceCastInst &I);
328 
329   bool visitIntrinsicInst(IntrinsicInst &I);
330   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
331   bool visitMinNum(IntrinsicInst &I);
332   bool visitSqrt(IntrinsicInst &I);
333   bool run();
334 };
335 
336 class AMDGPUCodeGenPrepare : public FunctionPass {
337 public:
338   static char ID;
339   AMDGPUCodeGenPrepare() : FunctionPass(ID) {
340     initializeAMDGPUCodeGenPreparePass(*PassRegistry::getPassRegistry());
341   }
342   void getAnalysisUsage(AnalysisUsage &AU) const override {
343     AU.addRequired<AssumptionCacheTracker>();
344     AU.addRequired<UniformityInfoWrapperPass>();
345     AU.addRequired<TargetLibraryInfoWrapperPass>();
346 
347     // FIXME: Division expansion needs to preserve the dominator tree.
348     if (!ExpandDiv64InIR)
349       AU.setPreservesAll();
350   }
351   bool runOnFunction(Function &F) override;
352   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
353 };
354 
355 } // end anonymous namespace
356 
357 bool AMDGPUCodeGenPrepareImpl::run() {
358   BreakPhiNodesCache.clear();
359   bool MadeChange = false;
360 
361   Function::iterator NextBB;
362   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
363     BasicBlock *BB = &*FI;
364     NextBB = std::next(FI);
365 
366     BasicBlock::iterator Next;
367     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
368          I = Next) {
369       Next = std::next(I);
370 
371       MadeChange |= visit(*I);
372 
373       if (Next != E) { // Control flow changed
374         BasicBlock *NextInstBB = Next->getParent();
375         if (NextInstBB != BB) {
376           BB = NextInstBB;
377           E = BB->end();
378           FE = F.end();
379         }
380       }
381     }
382   }
383   return MadeChange;
384 }
385 
386 unsigned AMDGPUCodeGenPrepareImpl::getBaseElementBitWidth(const Type *T) const {
387   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
388 
389   if (T->isIntegerTy())
390     return T->getIntegerBitWidth();
391   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
392 }
393 
394 Type *AMDGPUCodeGenPrepareImpl::getI32Ty(IRBuilder<> &B, const Type *T) const {
395   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
396 
397   if (T->isIntegerTy())
398     return B.getInt32Ty();
399   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
400 }
401 
402 bool AMDGPUCodeGenPrepareImpl::isSigned(const BinaryOperator &I) const {
403   return I.getOpcode() == Instruction::AShr ||
404       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
405 }
406 
407 bool AMDGPUCodeGenPrepareImpl::isSigned(const SelectInst &I) const {
408   return isa<ICmpInst>(I.getOperand(0)) ?
409       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
410 }
411 
412 bool AMDGPUCodeGenPrepareImpl::needsPromotionToI32(const Type *T) const {
413   if (!Widen16BitOps)
414     return false;
415 
416   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
417   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
418     return true;
419 
420   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
421     // TODO: The set of packed operations is more limited, so may want to
422     // promote some anyway.
423     if (ST.hasVOP3PInsts())
424       return false;
425 
426     return needsPromotionToI32(VT->getElementType());
427   }
428 
429   return false;
430 }
431 
432 bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
433   return Ty->isFloatTy() || Ty->isDoubleTy() ||
434          (Ty->isHalfTy() && ST.has16BitInsts());
435 }
436 
437 // Return true if the op promoted to i32 should have nsw set.
438 static bool promotedOpIsNSW(const Instruction &I) {
439   switch (I.getOpcode()) {
440   case Instruction::Shl:
441   case Instruction::Add:
442   case Instruction::Sub:
443     return true;
444   case Instruction::Mul:
445     return I.hasNoUnsignedWrap();
446   default:
447     return false;
448   }
449 }
450 
451 // Return true if the op promoted to i32 should have nuw set.
452 static bool promotedOpIsNUW(const Instruction &I) {
453   switch (I.getOpcode()) {
454   case Instruction::Shl:
455   case Instruction::Add:
456   case Instruction::Mul:
457     return true;
458   case Instruction::Sub:
459     return I.hasNoUnsignedWrap();
460   default:
461     return false;
462   }
463 }
464 
465 bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
466   Type *Ty = I.getType();
467   int TySize = DL.getTypeSizeInBits(Ty);
468   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
469 
470   return I.isSimple() && TySize < 32 && Alignment >= 4 && UA.isUniform(&I);
471 }
472 
473 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(BinaryOperator &I) const {
474   assert(needsPromotionToI32(I.getType()) &&
475          "I does not need promotion to i32");
476 
477   if (I.getOpcode() == Instruction::SDiv ||
478       I.getOpcode() == Instruction::UDiv ||
479       I.getOpcode() == Instruction::SRem ||
480       I.getOpcode() == Instruction::URem)
481     return false;
482 
483   IRBuilder<> Builder(&I);
484   Builder.SetCurrentDebugLocation(I.getDebugLoc());
485 
486   Type *I32Ty = getI32Ty(Builder, I.getType());
487   Value *ExtOp0 = nullptr;
488   Value *ExtOp1 = nullptr;
489   Value *ExtRes = nullptr;
490   Value *TruncRes = nullptr;
491 
492   if (isSigned(I)) {
493     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
494     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
495   } else {
496     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
497     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
498   }
499 
500   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
501   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
502     if (promotedOpIsNSW(cast<Instruction>(I)))
503       Inst->setHasNoSignedWrap();
504 
505     if (promotedOpIsNUW(cast<Instruction>(I)))
506       Inst->setHasNoUnsignedWrap();
507 
508     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
509       Inst->setIsExact(ExactOp->isExact());
510   }
511 
512   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
513 
514   I.replaceAllUsesWith(TruncRes);
515   I.eraseFromParent();
516 
517   return true;
518 }
519 
520 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(ICmpInst &I) const {
521   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
522          "I does not need promotion to i32");
523 
524   IRBuilder<> Builder(&I);
525   Builder.SetCurrentDebugLocation(I.getDebugLoc());
526 
527   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
528   Value *ExtOp0 = nullptr;
529   Value *ExtOp1 = nullptr;
530   Value *NewICmp  = nullptr;
531 
532   if (I.isSigned()) {
533     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
534     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
535   } else {
536     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
537     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
538   }
539   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
540 
541   I.replaceAllUsesWith(NewICmp);
542   I.eraseFromParent();
543 
544   return true;
545 }
546 
547 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(SelectInst &I) const {
548   assert(needsPromotionToI32(I.getType()) &&
549          "I does not need promotion to i32");
550 
551   IRBuilder<> Builder(&I);
552   Builder.SetCurrentDebugLocation(I.getDebugLoc());
553 
554   Type *I32Ty = getI32Ty(Builder, I.getType());
555   Value *ExtOp1 = nullptr;
556   Value *ExtOp2 = nullptr;
557   Value *ExtRes = nullptr;
558   Value *TruncRes = nullptr;
559 
560   if (isSigned(I)) {
561     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
562     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
563   } else {
564     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
565     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
566   }
567   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
568   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
569 
570   I.replaceAllUsesWith(TruncRes);
571   I.eraseFromParent();
572 
573   return true;
574 }
575 
576 bool AMDGPUCodeGenPrepareImpl::promoteUniformBitreverseToI32(
577     IntrinsicInst &I) const {
578   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
579          "I must be bitreverse intrinsic");
580   assert(needsPromotionToI32(I.getType()) &&
581          "I does not need promotion to i32");
582 
583   IRBuilder<> Builder(&I);
584   Builder.SetCurrentDebugLocation(I.getDebugLoc());
585 
586   Type *I32Ty = getI32Ty(Builder, I.getType());
587   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
588   Value *ExtRes =
589       Builder.CreateIntrinsic(Intrinsic::bitreverse, {I32Ty}, {ExtOp});
590   Value *LShrOp =
591       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
592   Value *TruncRes =
593       Builder.CreateTrunc(LShrOp, I.getType());
594 
595   I.replaceAllUsesWith(TruncRes);
596   I.eraseFromParent();
597 
598   return true;
599 }
600 
601 unsigned AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op) const {
602   return computeKnownBits(Op, DL, 0, AC).countMaxActiveBits();
603 }
604 
605 unsigned AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op) const {
606   return ComputeMaxSignificantBits(Op, DL, 0, AC);
607 }
608 
609 static void extractValues(IRBuilder<> &Builder,
610                           SmallVectorImpl<Value *> &Values, Value *V) {
611   auto *VT = dyn_cast<FixedVectorType>(V->getType());
612   if (!VT) {
613     Values.push_back(V);
614     return;
615   }
616 
617   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
618     Values.push_back(Builder.CreateExtractElement(V, I));
619 }
620 
621 static Value *insertValues(IRBuilder<> &Builder,
622                            Type *Ty,
623                            SmallVectorImpl<Value *> &Values) {
624   if (!Ty->isVectorTy()) {
625     assert(Values.size() == 1);
626     return Values[0];
627   }
628 
629   Value *NewVal = PoisonValue::get(Ty);
630   for (int I = 0, E = Values.size(); I != E; ++I)
631     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
632 
633   return NewVal;
634 }
635 
636 bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
637   if (I.getOpcode() != Instruction::Mul)
638     return false;
639 
640   Type *Ty = I.getType();
641   unsigned Size = Ty->getScalarSizeInBits();
642   if (Size <= 16 && ST.has16BitInsts())
643     return false;
644 
645   // Prefer scalar if this could be s_mul_i32
646   if (UA.isUniform(&I))
647     return false;
648 
649   Value *LHS = I.getOperand(0);
650   Value *RHS = I.getOperand(1);
651   IRBuilder<> Builder(&I);
652   Builder.SetCurrentDebugLocation(I.getDebugLoc());
653 
654   unsigned LHSBits = 0, RHSBits = 0;
655   bool IsSigned = false;
656 
657   if (ST.hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
658       (RHSBits = numBitsUnsigned(RHS)) <= 24) {
659     IsSigned = false;
660 
661   } else if (ST.hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
662              (RHSBits = numBitsSigned(RHS)) <= 24) {
663     IsSigned = true;
664 
665   } else
666     return false;
667 
668   SmallVector<Value *, 4> LHSVals;
669   SmallVector<Value *, 4> RHSVals;
670   SmallVector<Value *, 4> ResultVals;
671   extractValues(Builder, LHSVals, LHS);
672   extractValues(Builder, RHSVals, RHS);
673 
674   IntegerType *I32Ty = Builder.getInt32Ty();
675   IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
676   Type *DstTy = LHSVals[0]->getType();
677 
678   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
679     Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
680                           : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
681     Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
682                           : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
683     Intrinsic::ID ID =
684         IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
685     Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
686     Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
687                       : Builder.CreateZExtOrTrunc(Result, DstTy);
688     ResultVals.push_back(Result);
689   }
690 
691   Value *NewVal = insertValues(Builder, Ty, ResultVals);
692   NewVal->takeName(&I);
693   I.replaceAllUsesWith(NewVal);
694   I.eraseFromParent();
695 
696   return true;
697 }
698 
699 // Find a select instruction, which may have been casted. This is mostly to deal
700 // with cases where i16 selects were promoted here to i32.
701 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
702   Cast = nullptr;
703   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
704     return Sel;
705 
706   if ((Cast = dyn_cast<CastInst>(V))) {
707     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
708       return Sel;
709   }
710 
711   return nullptr;
712 }
713 
714 bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
715   // Don't do this unless the old select is going away. We want to eliminate the
716   // binary operator, not replace a binop with a select.
717   int SelOpNo = 0;
718 
719   CastInst *CastOp;
720 
721   // TODO: Should probably try to handle some cases with multiple
722   // users. Duplicating the select may be profitable for division.
723   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
724   if (!Sel || !Sel->hasOneUse()) {
725     SelOpNo = 1;
726     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
727   }
728 
729   if (!Sel || !Sel->hasOneUse())
730     return false;
731 
732   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
733   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
734   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
735   if (!CBO || !CT || !CF)
736     return false;
737 
738   if (CastOp) {
739     if (!CastOp->hasOneUse())
740       return false;
741     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), DL);
742     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), DL);
743   }
744 
745   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
746   // need to handle divisions here.
747   Constant *FoldedT =
748       SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, DL)
749               : ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, DL);
750   if (!FoldedT || isa<ConstantExpr>(FoldedT))
751     return false;
752 
753   Constant *FoldedF =
754       SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, DL)
755               : ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, DL);
756   if (!FoldedF || isa<ConstantExpr>(FoldedF))
757     return false;
758 
759   IRBuilder<> Builder(&BO);
760   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
761   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
762     Builder.setFastMathFlags(FPOp->getFastMathFlags());
763 
764   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
765                                           FoldedT, FoldedF);
766   NewSelect->takeName(&BO);
767   BO.replaceAllUsesWith(NewSelect);
768   BO.eraseFromParent();
769   if (CastOp)
770     CastOp->eraseFromParent();
771   Sel->eraseFromParent();
772   return true;
773 }
774 
775 std::pair<Value *, Value *>
776 AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
777                                           Value *Src) const {
778   Type *Ty = Src->getType();
779   Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
780                                          {Ty, Builder.getInt32Ty()}, Src);
781   Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
782 
783   // Bypass the bug workaround for the exponent result since it doesn't matter.
784   // TODO: Does the bug workaround even really need to consider the exponent
785   // result? It's unspecified by the spec.
786 
787   Value *FrexpExp =
788       ST.hasFractBug()
789           ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
790                                     {Builder.getInt32Ty(), Ty}, Src)
791           : Builder.CreateExtractValue(Frexp, {1});
792   return {FrexpMant, FrexpExp};
793 }
794 
795 /// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
796 Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
797                                                  Value *Src,
798                                                  bool IsNegative) const {
799   // Same as for 1.0, but expand the sign out of the constant.
800   // -1.0 / x -> rcp (fneg x)
801   if (IsNegative)
802     Src = Builder.CreateFNeg(Src);
803 
804   // The rcp instruction doesn't support denormals, so scale the input
805   // out of the denormal range and convert at the end.
806   //
807   // Expand as 2^-n * (1.0 / (x * 2^n))
808 
809   // TODO: Skip scaling if input is known never denormal and the input
810   // range won't underflow to denormal. The hard part is knowing the
811   // result. We need a range check, the result could be denormal for
812   // 0x1p+126 < den <= 0x1p+127.
813   auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
814   Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
815   Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
816   return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
817 }
818 
819 /// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
820 Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
821                                               Value *RHS,
822                                               FastMathFlags FMF) const {
823   // If we have have to work around the fract/frexp bug, we're worse off than
824   // using the fdiv.fast expansion. The full safe expansion is faster if we have
825   // fast FMA.
826   if (HasFP32DenormalFlush && ST.hasFractBug() && !ST.hasFastFMAF32() &&
827       (!FMF.noNaNs() || !FMF.noInfs()))
828     return nullptr;
829 
830   // We're scaling the LHS to avoid a denormal input, and scale the denominator
831   // to avoid large values underflowing the result.
832   auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
833 
834   Value *Rcp =
835       Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
836 
837   auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
838   Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
839 
840   // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
841   // result.
842   Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
843   return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
844 }
845 
846 /// Emit a sqrt that handles denormals and is accurate to 2ulp.
847 Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
848                                                   Value *Src,
849                                                   FastMathFlags FMF) const {
850   Type *Ty = Src->getType();
851   APFloat SmallestNormal =
852       APFloat::getSmallestNormalized(Ty->getFltSemantics());
853   Value *NeedScale =
854       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
855 
856   ConstantInt *Zero = Builder.getInt32(0);
857   Value *InputScaleFactor =
858       Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
859 
860   Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
861 
862   Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
863 
864   Value *OutputScaleFactor =
865       Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
866   return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
867 }
868 
869 /// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
870 static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
871                               bool IsNegative) {
872   // bool need_scale = x < 0x1p-126f;
873   // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
874   // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
875   // rsq(x * input_scale) * output_scale;
876 
877   Type *Ty = Src->getType();
878   APFloat SmallestNormal =
879       APFloat::getSmallestNormalized(Ty->getFltSemantics());
880   Value *NeedScale =
881       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
882   Constant *One = ConstantFP::get(Ty, 1.0);
883   Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
884   Constant *OutputScale =
885       ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
886 
887   Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
888 
889   Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
890   Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
891   Value *OutputScaleFactor = Builder.CreateSelect(
892       NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
893 
894   return Builder.CreateFMul(Rsq, OutputScaleFactor);
895 }
896 
897 bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(const FPMathOperator *SqrtOp,
898                                                   FastMathFlags DivFMF,
899                                                   FastMathFlags SqrtFMF) const {
900   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
901   if (!DivFMF.allowContract() || !SqrtFMF.allowContract())
902     return false;
903 
904   // v_rsq_f32 gives 1ulp
905   return SqrtFMF.approxFunc() || HasUnsafeFPMath ||
906          SqrtOp->getFPAccuracy() >= 1.0f;
907 }
908 
909 Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
910     IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
911     const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
912   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
913   assert(DivFMF.allowContract() && SqrtFMF.allowContract());
914 
915   // rsq_f16 is accurate to 0.51 ulp.
916   // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
917   // rsq_f64 is never accurate.
918   const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
919   if (!CLHS)
920     return nullptr;
921 
922   assert(Den->getType()->isFloatTy());
923 
924   bool IsNegative = false;
925 
926   // TODO: Handle other numerator values with arcp.
927   if (CLHS->isExactlyValue(1.0) || (IsNegative = CLHS->isExactlyValue(-1.0))) {
928     // Add in the sqrt flags.
929     IRBuilder<>::FastMathFlagGuard Guard(Builder);
930     Builder.setFastMathFlags(DivFMF | SqrtFMF);
931 
932     if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) || HasUnsafeFPMath ||
933         canIgnoreDenormalInput(Den, CtxI)) {
934       Value *Result = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
935       // -1.0 / sqrt(x) -> fneg(rsq(x))
936       return IsNegative ? Builder.CreateFNeg(Result) : Result;
937     }
938 
939     return emitRsqIEEE1ULP(Builder, Den, IsNegative);
940   }
941 
942   return nullptr;
943 }
944 
945 // Optimize fdiv with rcp:
946 //
947 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
948 //               allowed with unsafe-fp-math or afn.
949 //
950 // a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
951 Value *
952 AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
953                                           Value *Den, FastMathFlags FMF,
954                                           const Instruction *CtxI) const {
955   // rcp_f16 is accurate to 0.51 ulp.
956   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
957   // rcp_f64 is never accurate.
958   assert(Den->getType()->isFloatTy());
959 
960   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
961     bool IsNegative = false;
962     if (CLHS->isExactlyValue(1.0) ||
963         (IsNegative = CLHS->isExactlyValue(-1.0))) {
964       Value *Src = Den;
965 
966       if (HasFP32DenormalFlush || FMF.approxFunc()) {
967         // -1.0 / x -> 1.0 / fneg(x)
968         if (IsNegative)
969           Src = Builder.CreateFNeg(Src);
970 
971         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
972         // the CI documentation has a worst case error of 1 ulp.
973         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
974         // to use it as long as we aren't trying to use denormals.
975         //
976         // v_rcp_f16 and v_rsq_f16 DO support denormals.
977 
978         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
979         //       insert rsq intrinsic here.
980 
981         // 1.0 / x -> rcp(x)
982         return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
983       }
984 
985       // TODO: If the input isn't denormal, and we know the input exponent isn't
986       // big enough to introduce a denormal we can avoid the scaling.
987       return emitRcpIEEE1ULP(Builder, Src, IsNegative);
988     }
989   }
990 
991   if (FMF.allowReciprocal()) {
992     // x / y -> x * (1.0 / y)
993 
994     // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
995     // will never underflow.
996     if (HasFP32DenormalFlush || FMF.approxFunc()) {
997       Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
998       return Builder.CreateFMul(Num, Recip);
999     }
1000 
1001     Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
1002     return Builder.CreateFMul(Num, Recip);
1003   }
1004 
1005   return nullptr;
1006 }
1007 
1008 // optimize with fdiv.fast:
1009 //
1010 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
1011 //
1012 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
1013 //
1014 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
1015 Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
1016     IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
1017   // fdiv.fast can achieve 2.5 ULP accuracy.
1018   if (ReqdAccuracy < 2.5f)
1019     return nullptr;
1020 
1021   // Only have fdiv.fast for f32.
1022   assert(Den->getType()->isFloatTy());
1023 
1024   bool NumIsOne = false;
1025   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
1026     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
1027       NumIsOne = true;
1028   }
1029 
1030   // fdiv does not support denormals. But 1.0/x is always fine to use it.
1031   //
1032   // TODO: This works for any value with a specific known exponent range, don't
1033   // just limit to constant 1.
1034   if (!HasFP32DenormalFlush && !NumIsOne)
1035     return nullptr;
1036 
1037   return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {}, {Num, Den});
1038 }
1039 
1040 Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
1041     IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
1042     FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
1043     float ReqdDivAccuracy) const {
1044   if (RsqOp) {
1045     Value *Rsq =
1046         optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
1047     if (Rsq)
1048       return Rsq;
1049   }
1050 
1051   Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
1052   if (Rcp)
1053     return Rcp;
1054 
1055   // In the basic case fdiv_fast has the same instruction count as the frexp div
1056   // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
1057   // potentially be fused into a user. Also, materialization of the constants
1058   // can be reused for multiple instances.
1059   Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
1060   if (FDivFast)
1061     return FDivFast;
1062 
1063   return emitFrexpDiv(Builder, Num, Den, DivFMF);
1064 }
1065 
1066 // Optimizations is performed based on fpmath, fast math flags as well as
1067 // denormals to optimize fdiv with either rcp or fdiv.fast.
1068 //
1069 // With rcp:
1070 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
1071 //                 allowed with unsafe-fp-math or afn.
1072 //
1073 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
1074 //
1075 // With fdiv.fast:
1076 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
1077 //
1078 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
1079 //
1080 // NOTE: rcp is the preference in cases that both are legal.
1081 bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
1082   if (DisableFDivExpand)
1083     return false;
1084 
1085   Type *Ty = FDiv.getType()->getScalarType();
1086   if (!Ty->isFloatTy())
1087     return false;
1088 
1089   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
1090   // expansion around them in codegen. f16 is good enough to always use.
1091 
1092   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
1093   const FastMathFlags DivFMF = FPOp->getFastMathFlags();
1094   const float ReqdAccuracy = FPOp->getFPAccuracy();
1095 
1096   FastMathFlags SqrtFMF;
1097 
1098   Value *Num = FDiv.getOperand(0);
1099   Value *Den = FDiv.getOperand(1);
1100 
1101   Value *RsqOp = nullptr;
1102   auto *DenII = dyn_cast<IntrinsicInst>(Den);
1103   if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
1104       DenII->hasOneUse()) {
1105     const auto *SqrtOp = cast<FPMathOperator>(DenII);
1106     SqrtFMF = SqrtOp->getFastMathFlags();
1107     if (canOptimizeWithRsq(SqrtOp, DivFMF, SqrtFMF))
1108       RsqOp = SqrtOp->getOperand(0);
1109   }
1110 
1111   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
1112   //
1113   // Defer to codegen to handle this.
1114   //
1115   // TODO: Decide on an interpretation for interactions between afn + arcp +
1116   // !fpmath, and make it consistent between here and codegen. For now, defer
1117   // expansion of afn to codegen. The current interpretation is so aggressive we
1118   // don't need any pre-consideration here when we have better information. A
1119   // more conservative interpretation could use handling here.
1120   const bool AllowInaccurateRcp = HasUnsafeFPMath || DivFMF.approxFunc();
1121   if (!RsqOp && AllowInaccurateRcp)
1122     return false;
1123 
1124   // Defer the correct implementations to codegen.
1125   if (ReqdAccuracy < 1.0f)
1126     return false;
1127 
1128   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
1129   Builder.setFastMathFlags(DivFMF);
1130   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
1131 
1132   SmallVector<Value *, 4> NumVals;
1133   SmallVector<Value *, 4> DenVals;
1134   SmallVector<Value *, 4> RsqDenVals;
1135   extractValues(Builder, NumVals, Num);
1136   extractValues(Builder, DenVals, Den);
1137 
1138   if (RsqOp)
1139     extractValues(Builder, RsqDenVals, RsqOp);
1140 
1141   SmallVector<Value *, 4> ResultVals(NumVals.size());
1142   for (int I = 0, E = NumVals.size(); I != E; ++I) {
1143     Value *NumElt = NumVals[I];
1144     Value *DenElt = DenVals[I];
1145     Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
1146 
1147     Value *NewElt =
1148         visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
1149                          cast<Instruction>(FPOp), ReqdAccuracy);
1150     if (!NewElt) {
1151       // Keep the original, but scalarized.
1152 
1153       // This has the unfortunate side effect of sometimes scalarizing when
1154       // we're not going to do anything.
1155       NewElt = Builder.CreateFDiv(NumElt, DenElt);
1156       if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
1157         NewEltInst->copyMetadata(FDiv);
1158     }
1159 
1160     ResultVals[I] = NewElt;
1161   }
1162 
1163   Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
1164 
1165   if (NewVal) {
1166     FDiv.replaceAllUsesWith(NewVal);
1167     NewVal->takeName(&FDiv);
1168     RecursivelyDeleteTriviallyDeadInstructions(&FDiv, TLI);
1169   }
1170 
1171   return true;
1172 }
1173 
1174 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
1175                                           Value *LHS, Value *RHS) {
1176   Type *I32Ty = Builder.getInt32Ty();
1177   Type *I64Ty = Builder.getInt64Ty();
1178 
1179   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
1180   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
1181   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
1182   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
1183   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
1184   Hi = Builder.CreateTrunc(Hi, I32Ty);
1185   return std::pair(Lo, Hi);
1186 }
1187 
1188 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
1189   return getMul64(Builder, LHS, RHS).second;
1190 }
1191 
1192 /// Figure out how many bits are really needed for this division. \p AtLeast is
1193 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
1194 /// first one is insufficient. Returns -1 on failure.
1195 int AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
1196                                             Value *Den, unsigned AtLeast,
1197                                             bool IsSigned) const {
1198   if (IsSigned) {
1199     unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
1200     if (RHSSignBits < AtLeast)
1201       return -1;
1202 
1203     unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
1204     if (LHSSignBits < AtLeast)
1205       return -1;
1206 
1207     unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1208     unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
1209     return DivBits + 1; // a SignBit need to be reserved for shrinking
1210   }
1211 
1212   // All bits are used for unsigned division for Num or Den in range
1213   // (SignedMax, UnsignedMax].
1214   KnownBits Known = computeKnownBits(Den, DL, 0, AC, &I);
1215   if (Known.isNegative() || !Known.isNonNegative())
1216     return -1;
1217   unsigned RHSSignBits = Known.countMinLeadingZeros();
1218 
1219   Known = computeKnownBits(Num, DL, 0, AC, &I);
1220   if (Known.isNegative() || !Known.isNonNegative())
1221     return -1;
1222   unsigned LHSSignBits = Known.countMinLeadingZeros();
1223 
1224   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1225   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
1226   return DivBits;
1227 }
1228 
1229 // The fractional part of a float is enough to accurately represent up to
1230 // a 24-bit signed integer.
1231 Value *AMDGPUCodeGenPrepareImpl::expandDivRem24(IRBuilder<> &Builder,
1232                                                 BinaryOperator &I, Value *Num,
1233                                                 Value *Den, bool IsDiv,
1234                                                 bool IsSigned) const {
1235   unsigned SSBits = Num->getType()->getScalarSizeInBits();
1236   // If Num bits <= 24, assume 0 signbits.
1237   unsigned AtLeast = (SSBits <= 24) ? 0 : (SSBits - 24 + IsSigned);
1238   int DivBits = getDivNumBits(I, Num, Den, AtLeast, IsSigned);
1239   if (DivBits == -1)
1240     return nullptr;
1241   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
1242 }
1243 
1244 Value *AMDGPUCodeGenPrepareImpl::expandDivRem24Impl(
1245     IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
1246     unsigned DivBits, bool IsDiv, bool IsSigned) const {
1247   Type *I32Ty = Builder.getInt32Ty();
1248   Num = Builder.CreateTrunc(Num, I32Ty);
1249   Den = Builder.CreateTrunc(Den, I32Ty);
1250 
1251   Type *F32Ty = Builder.getFloatTy();
1252   ConstantInt *One = Builder.getInt32(1);
1253   Value *JQ = One;
1254 
1255   if (IsSigned) {
1256     // char|short jq = ia ^ ib;
1257     JQ = Builder.CreateXor(Num, Den);
1258 
1259     // jq = jq >> (bitsize - 2)
1260     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
1261 
1262     // jq = jq | 0x1
1263     JQ = Builder.CreateOr(JQ, One);
1264   }
1265 
1266   // int ia = (int)LHS;
1267   Value *IA = Num;
1268 
1269   // int ib, (int)RHS;
1270   Value *IB = Den;
1271 
1272   // float fa = (float)ia;
1273   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
1274                        : Builder.CreateUIToFP(IA, F32Ty);
1275 
1276   // float fb = (float)ib;
1277   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
1278                        : Builder.CreateUIToFP(IB,F32Ty);
1279 
1280   Value *RCP = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp,
1281                                        Builder.getFloatTy(), {FB});
1282   Value *FQM = Builder.CreateFMul(FA, RCP);
1283 
1284   // fq = trunc(fqm);
1285   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
1286   FQ->copyFastMathFlags(Builder.getFastMathFlags());
1287 
1288   // float fqneg = -fq;
1289   Value *FQNeg = Builder.CreateFNeg(FQ);
1290 
1291   // float fr = mad(fqneg, fb, fa);
1292   auto FMAD = !ST.hasMadMacF32Insts()
1293                   ? Intrinsic::fma
1294                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
1295   Value *FR = Builder.CreateIntrinsic(FMAD,
1296                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
1297 
1298   // int iq = (int)fq;
1299   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
1300                        : Builder.CreateFPToUI(FQ, I32Ty);
1301 
1302   // fr = fabs(fr);
1303   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
1304 
1305   // fb = fabs(fb);
1306   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
1307 
1308   // int cv = fr >= fb;
1309   Value *CV = Builder.CreateFCmpOGE(FR, FB);
1310 
1311   // jq = (cv ? jq : 0);
1312   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
1313 
1314   // dst = iq + jq;
1315   Value *Div = Builder.CreateAdd(IQ, JQ);
1316 
1317   Value *Res = Div;
1318   if (!IsDiv) {
1319     // Rem needs compensation, it's easier to recompute it
1320     Value *Rem = Builder.CreateMul(Div, Den);
1321     Res = Builder.CreateSub(Num, Rem);
1322   }
1323 
1324   if (DivBits != 0 && DivBits < 32) {
1325     // Extend in register from the number of bits this divide really is.
1326     if (IsSigned) {
1327       int InRegBits = 32 - DivBits;
1328 
1329       Res = Builder.CreateShl(Res, InRegBits);
1330       Res = Builder.CreateAShr(Res, InRegBits);
1331     } else {
1332       ConstantInt *TruncMask
1333         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
1334       Res = Builder.CreateAnd(Res, TruncMask);
1335     }
1336   }
1337 
1338   return Res;
1339 }
1340 
1341 // Try to recognize special cases the DAG will emit special, better expansions
1342 // than the general expansion we do here.
1343 
1344 // TODO: It would be better to just directly handle those optimizations here.
1345 bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
1346                                                          Value *Num,
1347                                                          Value *Den) const {
1348   if (Constant *C = dyn_cast<Constant>(Den)) {
1349     // Arbitrary constants get a better expansion as long as a wider mulhi is
1350     // legal.
1351     if (C->getType()->getScalarSizeInBits() <= 32)
1352       return true;
1353 
1354     // TODO: Sdiv check for not exact for some reason.
1355 
1356     // If there's no wider mulhi, there's only a better expansion for powers of
1357     // two.
1358     // TODO: Should really know for each vector element.
1359     if (isKnownToBeAPowerOfTwo(C, DL, true, 0, AC, &I, DT))
1360       return true;
1361 
1362     return false;
1363   }
1364 
1365   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1366     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1367     if (BinOpDen->getOpcode() == Instruction::Shl &&
1368         isa<Constant>(BinOpDen->getOperand(0)) &&
1369         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), DL, true, 0, AC, &I,
1370                                DT)) {
1371       return true;
1372     }
1373   }
1374 
1375   return false;
1376 }
1377 
1378 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout DL) {
1379   // Check whether the sign can be determined statically.
1380   KnownBits Known = computeKnownBits(V, DL);
1381   if (Known.isNegative())
1382     return Constant::getAllOnesValue(V->getType());
1383   if (Known.isNonNegative())
1384     return Constant::getNullValue(V->getType());
1385   return Builder.CreateAShr(V, Builder.getInt32(31));
1386 }
1387 
1388 Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
1389                                                 BinaryOperator &I, Value *X,
1390                                                 Value *Y) const {
1391   Instruction::BinaryOps Opc = I.getOpcode();
1392   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1393          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1394 
1395   FastMathFlags FMF;
1396   FMF.setFast();
1397   Builder.setFastMathFlags(FMF);
1398 
1399   if (divHasSpecialOptimization(I, X, Y))
1400     return nullptr;  // Keep it for later optimization.
1401 
1402   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1403   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1404 
1405   Type *Ty = X->getType();
1406   Type *I32Ty = Builder.getInt32Ty();
1407   Type *F32Ty = Builder.getFloatTy();
1408 
1409   if (Ty->getScalarSizeInBits() != 32) {
1410     if (IsSigned) {
1411       X = Builder.CreateSExtOrTrunc(X, I32Ty);
1412       Y = Builder.CreateSExtOrTrunc(Y, I32Ty);
1413     } else {
1414       X = Builder.CreateZExtOrTrunc(X, I32Ty);
1415       Y = Builder.CreateZExtOrTrunc(Y, I32Ty);
1416     }
1417   }
1418 
1419   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
1420     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1421                       Builder.CreateZExtOrTrunc(Res, Ty);
1422   }
1423 
1424   ConstantInt *Zero = Builder.getInt32(0);
1425   ConstantInt *One = Builder.getInt32(1);
1426 
1427   Value *Sign = nullptr;
1428   if (IsSigned) {
1429     Value *SignX = getSign32(X, Builder, DL);
1430     Value *SignY = getSign32(Y, Builder, DL);
1431     // Remainder sign is the same as LHS
1432     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1433 
1434     X = Builder.CreateAdd(X, SignX);
1435     Y = Builder.CreateAdd(Y, SignY);
1436 
1437     X = Builder.CreateXor(X, SignX);
1438     Y = Builder.CreateXor(Y, SignY);
1439   }
1440 
1441   // The algorithm here is based on ideas from "Software Integer Division", Tom
1442   // Rodeheffer, August 2008.
1443   //
1444   // unsigned udiv(unsigned x, unsigned y) {
1445   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1446   //   // that this is a lower bound on inv(y), even if some of the calculations
1447   //   // round up.
1448   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1449   //
1450   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1451   //   // Empirically this is guaranteed to give a "two-y" lower bound on
1452   //   // inv(y).
1453   //   z += umulh(z, -y * z);
1454   //
1455   //   // Quotient/remainder estimate.
1456   //   unsigned q = umulh(x, z);
1457   //   unsigned r = x - q * y;
1458   //
1459   //   // Two rounds of quotient/remainder refinement.
1460   //   if (r >= y) {
1461   //     ++q;
1462   //     r -= y;
1463   //   }
1464   //   if (r >= y) {
1465   //     ++q;
1466   //     r -= y;
1467   //   }
1468   //
1469   //   return q;
1470   // }
1471 
1472   // Initial estimate of inv(y).
1473   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1474   Value *RcpY = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp, F32Ty, {FloatY});
1475   Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
1476   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1477   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1478 
1479   // One round of UNR.
1480   Value *NegY = Builder.CreateSub(Zero, Y);
1481   Value *NegYZ = Builder.CreateMul(NegY, Z);
1482   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1483 
1484   // Quotient/remainder estimate.
1485   Value *Q = getMulHu(Builder, X, Z);
1486   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1487 
1488   // First quotient/remainder refinement.
1489   Value *Cond = Builder.CreateICmpUGE(R, Y);
1490   if (IsDiv)
1491     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1492   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1493 
1494   // Second quotient/remainder refinement.
1495   Cond = Builder.CreateICmpUGE(R, Y);
1496   Value *Res;
1497   if (IsDiv)
1498     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1499   else
1500     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1501 
1502   if (IsSigned) {
1503     Res = Builder.CreateXor(Res, Sign);
1504     Res = Builder.CreateSub(Res, Sign);
1505     Res = Builder.CreateSExtOrTrunc(Res, Ty);
1506   } else {
1507     Res = Builder.CreateZExtOrTrunc(Res, Ty);
1508   }
1509   return Res;
1510 }
1511 
1512 Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
1513                                                 BinaryOperator &I, Value *Num,
1514                                                 Value *Den) const {
1515   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1516     return nullptr;  // Keep it for later optimization.
1517 
1518   Instruction::BinaryOps Opc = I.getOpcode();
1519 
1520   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1521   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1522 
1523   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1524   if (NumDivBits == -1)
1525     return nullptr;
1526 
1527   Value *Narrowed = nullptr;
1528   if (NumDivBits <= 24) {
1529     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1530                                   IsDiv, IsSigned);
1531   } else if (NumDivBits <= 32) {
1532     Narrowed = expandDivRem32(Builder, I, Num, Den);
1533   }
1534 
1535   if (Narrowed) {
1536     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1537                       Builder.CreateZExt(Narrowed, Num->getType());
1538   }
1539 
1540   return nullptr;
1541 }
1542 
1543 void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
1544   Instruction::BinaryOps Opc = I.getOpcode();
1545   // Do the general expansion.
1546   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1547     expandDivisionUpTo64Bits(&I);
1548     return;
1549   }
1550 
1551   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1552     expandRemainderUpTo64Bits(&I);
1553     return;
1554   }
1555 
1556   llvm_unreachable("not a division");
1557 }
1558 
1559 bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
1560   if (foldBinOpIntoSelect(I))
1561     return true;
1562 
1563   if (ST.has16BitInsts() && needsPromotionToI32(I.getType()) &&
1564       UA.isUniform(&I) && promoteUniformOpToI32(I))
1565     return true;
1566 
1567   if (UseMul24Intrin && replaceMulWithMul24(I))
1568     return true;
1569 
1570   bool Changed = false;
1571   Instruction::BinaryOps Opc = I.getOpcode();
1572   Type *Ty = I.getType();
1573   Value *NewDiv = nullptr;
1574   unsigned ScalarSize = Ty->getScalarSizeInBits();
1575 
1576   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1577 
1578   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1579        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1580       ScalarSize <= 64 &&
1581       !DisableIDivExpand) {
1582     Value *Num = I.getOperand(0);
1583     Value *Den = I.getOperand(1);
1584     IRBuilder<> Builder(&I);
1585     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1586 
1587     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1588       NewDiv = PoisonValue::get(VT);
1589 
1590       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1591         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1592         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1593 
1594         Value *NewElt;
1595         if (ScalarSize <= 32) {
1596           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1597           if (!NewElt)
1598             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1599         } else {
1600           // See if this 64-bit division can be shrunk to 32/24-bits before
1601           // producing the general expansion.
1602           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1603           if (!NewElt) {
1604             // The general 64-bit expansion introduces control flow and doesn't
1605             // return the new value. Just insert a scalar copy and defer
1606             // expanding it.
1607             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1608             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1609           }
1610         }
1611 
1612         if (auto *NewEltI = dyn_cast<Instruction>(NewElt))
1613           NewEltI->copyIRFlags(&I);
1614 
1615         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1616       }
1617     } else {
1618       if (ScalarSize <= 32)
1619         NewDiv = expandDivRem32(Builder, I, Num, Den);
1620       else {
1621         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1622         if (!NewDiv)
1623           Div64ToExpand.push_back(&I);
1624       }
1625     }
1626 
1627     if (NewDiv) {
1628       I.replaceAllUsesWith(NewDiv);
1629       I.eraseFromParent();
1630       Changed = true;
1631     }
1632   }
1633 
1634   if (ExpandDiv64InIR) {
1635     // TODO: We get much worse code in specially handled constant cases.
1636     for (BinaryOperator *Div : Div64ToExpand) {
1637       expandDivRem64(*Div);
1638       FlowChanged = true;
1639       Changed = true;
1640     }
1641   }
1642 
1643   return Changed;
1644 }
1645 
1646 bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
1647   if (!WidenLoads)
1648     return false;
1649 
1650   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1651        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1652       canWidenScalarExtLoad(I)) {
1653     IRBuilder<> Builder(&I);
1654     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1655 
1656     Type *I32Ty = Builder.getInt32Ty();
1657     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
1658     WidenLoad->copyMetadata(I);
1659 
1660     // If we have range metadata, we need to convert the type, and not make
1661     // assumptions about the high bits.
1662     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1663       ConstantInt *Lower =
1664         mdconst::extract<ConstantInt>(Range->getOperand(0));
1665 
1666       if (Lower->isNullValue()) {
1667         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1668       } else {
1669         Metadata *LowAndHigh[] = {
1670           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1671           // Don't make assumptions about the high bits.
1672           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1673         };
1674 
1675         WidenLoad->setMetadata(LLVMContext::MD_range,
1676                                MDNode::get(F.getContext(), LowAndHigh));
1677       }
1678     }
1679 
1680     int TySize = DL.getTypeSizeInBits(I.getType());
1681     Type *IntNTy = Builder.getIntNTy(TySize);
1682     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1683     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1684     I.replaceAllUsesWith(ValOrig);
1685     I.eraseFromParent();
1686     return true;
1687   }
1688 
1689   return false;
1690 }
1691 
1692 bool AMDGPUCodeGenPrepareImpl::visitICmpInst(ICmpInst &I) {
1693   bool Changed = false;
1694 
1695   if (ST.has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1696       UA.isUniform(&I))
1697     Changed |= promoteUniformOpToI32(I);
1698 
1699   return Changed;
1700 }
1701 
1702 bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
1703   Value *Cond = I.getCondition();
1704   Value *TrueVal = I.getTrueValue();
1705   Value *FalseVal = I.getFalseValue();
1706   Value *CmpVal;
1707   FCmpInst::Predicate Pred;
1708 
1709   if (ST.has16BitInsts() && needsPromotionToI32(I.getType())) {
1710     if (UA.isUniform(&I))
1711       return promoteUniformOpToI32(I);
1712     return false;
1713   }
1714 
1715   // Match fract pattern with nan check.
1716   if (!match(Cond, m_FCmp(Pred, m_Value(CmpVal), m_NonNaN())))
1717     return false;
1718 
1719   FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
1720   if (!FPOp)
1721     return false;
1722 
1723   IRBuilder<> Builder(&I);
1724   Builder.setFastMathFlags(FPOp->getFastMathFlags());
1725 
1726   auto *IITrue = dyn_cast<IntrinsicInst>(TrueVal);
1727   auto *IIFalse = dyn_cast<IntrinsicInst>(FalseVal);
1728 
1729   Value *Fract = nullptr;
1730   if (Pred == FCmpInst::FCMP_UNO && TrueVal == CmpVal && IIFalse &&
1731       CmpVal == matchFractPat(*IIFalse)) {
1732     // isnan(x) ? x : fract(x)
1733     Fract = applyFractPat(Builder, CmpVal);
1734   } else if (Pred == FCmpInst::FCMP_ORD && FalseVal == CmpVal && IITrue &&
1735              CmpVal == matchFractPat(*IITrue)) {
1736     // !isnan(x) ? fract(x) : x
1737     Fract = applyFractPat(Builder, CmpVal);
1738   } else
1739     return false;
1740 
1741   Fract->takeName(&I);
1742   I.replaceAllUsesWith(Fract);
1743   RecursivelyDeleteTriviallyDeadInstructions(&I, TLI);
1744   return true;
1745 }
1746 
1747 static bool areInSameBB(const Value *A, const Value *B) {
1748   const auto *IA = dyn_cast<Instruction>(A);
1749   const auto *IB = dyn_cast<Instruction>(B);
1750   return IA && IB && IA->getParent() == IB->getParent();
1751 }
1752 
1753 // Helper for breaking large PHIs that returns true when an extractelement on V
1754 // is likely to be folded away by the DAG combiner.
1755 static bool isInterestingPHIIncomingValue(const Value *V) {
1756   const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
1757   if (!FVT)
1758     return false;
1759 
1760   const Value *CurVal = V;
1761 
1762   // Check for insertelements, keeping track of the elements covered.
1763   BitVector EltsCovered(FVT->getNumElements());
1764   while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
1765     const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
1766 
1767     // Non constant index/out of bounds index -> folding is unlikely.
1768     // The latter is more of a sanity check because canonical IR should just
1769     // have replaced those with poison.
1770     if (!Idx || Idx->getZExtValue() >= FVT->getNumElements())
1771       return false;
1772 
1773     const auto *VecSrc = IE->getOperand(0);
1774 
1775     // If the vector source is another instruction, it must be in the same basic
1776     // block. Otherwise, the DAGCombiner won't see the whole thing and is
1777     // unlikely to be able to do anything interesting here.
1778     if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
1779       return false;
1780 
1781     CurVal = VecSrc;
1782     EltsCovered.set(Idx->getZExtValue());
1783 
1784     // All elements covered.
1785     if (EltsCovered.all())
1786       return true;
1787   }
1788 
1789   // We either didn't find a single insertelement, or the insertelement chain
1790   // ended before all elements were covered. Check for other interesting values.
1791 
1792   // Constants are always interesting because we can just constant fold the
1793   // extractelements.
1794   if (isa<Constant>(CurVal))
1795     return true;
1796 
1797   // shufflevector is likely to be profitable if either operand is a constant,
1798   // or if either source is in the same block.
1799   // This is because shufflevector is most often lowered as a series of
1800   // insert/extract elements anyway.
1801   if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
1802     return isa<Constant>(SV->getOperand(1)) ||
1803            areInSameBB(SV, SV->getOperand(0)) ||
1804            areInSameBB(SV, SV->getOperand(1));
1805   }
1806 
1807   return false;
1808 }
1809 
1810 static void collectPHINodes(const PHINode &I,
1811                             SmallPtrSet<const PHINode *, 8> &SeenPHIs) {
1812   const auto [It, Inserted] = SeenPHIs.insert(&I);
1813   if (!Inserted)
1814     return;
1815 
1816   for (const Value *Inc : I.incoming_values()) {
1817     if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
1818       collectPHINodes(*PhiInc, SeenPHIs);
1819   }
1820 
1821   for (const User *U : I.users()) {
1822     if (const auto *PhiU = dyn_cast<PHINode>(U))
1823       collectPHINodes(*PhiU, SeenPHIs);
1824   }
1825 }
1826 
1827 bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
1828   // Check in the cache first.
1829   if (const auto It = BreakPhiNodesCache.find(&I);
1830       It != BreakPhiNodesCache.end())
1831     return It->second;
1832 
1833   // We consider PHI nodes as part of "chains", so given a PHI node I, we
1834   // recursively consider all its users and incoming values that are also PHI
1835   // nodes. We then make a decision about all of those PHIs at once. Either they
1836   // all get broken up, or none of them do. That way, we avoid cases where a
1837   // single PHI is/is not broken and we end up reforming/exploding a vector
1838   // multiple times, or even worse, doing it in a loop.
1839   SmallPtrSet<const PHINode *, 8> WorkList;
1840   collectPHINodes(I, WorkList);
1841 
1842 #ifndef NDEBUG
1843   // Check that none of the PHI nodes in the worklist are in the map. If some of
1844   // them are, it means we're not good enough at collecting related PHIs.
1845   for (const PHINode *WLP : WorkList) {
1846     assert(BreakPhiNodesCache.count(WLP) == 0);
1847   }
1848 #endif
1849 
1850   // To consider a PHI profitable to break, we need to see some interesting
1851   // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
1852   // must have one to consider all PHIs breakable.
1853   //
1854   // This threshold has been determined through performance testing.
1855   //
1856   // Note that the computation below is equivalent to
1857   //
1858   //    (unsigned)ceil((K / 3.0) * 2)
1859   //
1860   // It's simply written this way to avoid mixing integral/FP arithmetic.
1861   const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
1862   unsigned NumBreakablePHIs = 0;
1863   bool CanBreak = false;
1864   for (const PHINode *Cur : WorkList) {
1865     // Don't break PHIs that have no interesting incoming values. That is, where
1866     // there is no clear opportunity to fold the "extractelement" instructions
1867     // we would add.
1868     //
1869     // Note: IC does not run after this pass, so we're only interested in the
1870     // foldings that the DAG combiner can do.
1871     if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
1872       if (++NumBreakablePHIs >= Threshold) {
1873         CanBreak = true;
1874         break;
1875       }
1876     }
1877   }
1878 
1879   for (const PHINode *Cur : WorkList)
1880     BreakPhiNodesCache[Cur] = CanBreak;
1881 
1882   return CanBreak;
1883 }
1884 
1885 /// Helper class for "break large PHIs" (visitPHINode).
1886 ///
1887 /// This represents a slice of a PHI's incoming value, which is made up of:
1888 ///   - The type of the slice (Ty)
1889 ///   - The index in the incoming value's vector where the slice starts (Idx)
1890 ///   - The number of elements in the slice (NumElts).
1891 /// It also keeps track of the NewPHI node inserted for this particular slice.
1892 ///
1893 /// Slice examples:
1894 ///   <4 x i64> -> Split into four i64 slices.
1895 ///     -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
1896 ///   <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
1897 ///     -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
1898 class VectorSlice {
1899 public:
1900   VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
1901       : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
1902 
1903   Type *Ty = nullptr;
1904   unsigned Idx = 0;
1905   unsigned NumElts = 0;
1906   PHINode *NewPHI = nullptr;
1907 
1908   /// Slice \p Inc according to the information contained within this slice.
1909   /// This is cached, so if called multiple times for the same \p BB & \p Inc
1910   /// pair, it returns the same Sliced value as well.
1911   ///
1912   /// Note this *intentionally* does not return the same value for, say,
1913   /// [%bb.0, %0] & [%bb.1, %0] as:
1914   ///   - It could cause issues with dominance (e.g. if bb.1 is seen first, then
1915   ///   the value in bb.1 may not be reachable from bb.0 if it's its
1916   ///   predecessor.)
1917   ///   - We also want to make our extract instructions as local as possible so
1918   ///   the DAG has better chances of folding them out. Duplicating them like
1919   ///   that is beneficial in that regard.
1920   ///
1921   /// This is both a minor optimization to avoid creating duplicate
1922   /// instructions, but also a requirement for correctness. It is not forbidden
1923   /// for a PHI node to have the same [BB, Val] pair multiple times. If we
1924   /// returned a new value each time, those previously identical pairs would all
1925   /// have different incoming values (from the same block) and it'd cause a "PHI
1926   /// node has multiple entries for the same basic block with different incoming
1927   /// values!" verifier error.
1928   Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
1929     Value *&Res = SlicedVals[{BB, Inc}];
1930     if (Res)
1931       return Res;
1932 
1933     IRBuilder<> B(BB->getTerminator());
1934     if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
1935       B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1936 
1937     if (NumElts > 1) {
1938       SmallVector<int, 4> Mask;
1939       for (unsigned K = Idx; K < (Idx + NumElts); ++K)
1940         Mask.push_back(K);
1941       Res = B.CreateShuffleVector(Inc, Mask, NewValName);
1942     } else
1943       Res = B.CreateExtractElement(Inc, Idx, NewValName);
1944 
1945     return Res;
1946   }
1947 
1948 private:
1949   SmallDenseMap<std::pair<BasicBlock *, Value *>, Value *> SlicedVals;
1950 };
1951 
1952 bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
1953   // Break-up fixed-vector PHIs into smaller pieces.
1954   // Default threshold is 32, so it breaks up any vector that's >32 bits into
1955   // its elements, or into 32-bit pieces (for 8/16 bit elts).
1956   //
1957   // This is only helpful for DAGISel because it doesn't handle large PHIs as
1958   // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
1959   // With large, odd-sized PHIs we may end up needing many `build_vector`
1960   // operations with most elements being "undef". This inhibits a lot of
1961   // optimization opportunities and can result in unreasonably high register
1962   // pressure and the inevitable stack spilling.
1963   if (!BreakLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
1964     return false;
1965 
1966   FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
1967   if (!FVT || FVT->getNumElements() == 1 ||
1968       DL.getTypeSizeInBits(FVT) <= BreakLargePHIsThreshold)
1969     return false;
1970 
1971   if (!ForceBreakLargePHIs && !canBreakPHINode(I))
1972     return false;
1973 
1974   std::vector<VectorSlice> Slices;
1975 
1976   Type *EltTy = FVT->getElementType();
1977   {
1978     unsigned Idx = 0;
1979     // For 8/16 bits type, don't scalarize fully but break it up into as many
1980     // 32-bit slices as we can, and scalarize the tail.
1981     const unsigned EltSize = DL.getTypeSizeInBits(EltTy);
1982     const unsigned NumElts = FVT->getNumElements();
1983     if (EltSize == 8 || EltSize == 16) {
1984       const unsigned SubVecSize = (32 / EltSize);
1985       Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
1986       for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
1987            Idx += SubVecSize)
1988         Slices.emplace_back(SubVecTy, Idx, SubVecSize);
1989     }
1990 
1991     // Scalarize all remaining elements.
1992     for (; Idx < NumElts; ++Idx)
1993       Slices.emplace_back(EltTy, Idx, 1);
1994   }
1995 
1996   assert(Slices.size() > 1);
1997 
1998   // Create one PHI per vector piece. The "VectorSlice" class takes care of
1999   // creating the necessary instruction to extract the relevant slices of each
2000   // incoming value.
2001   IRBuilder<> B(I.getParent());
2002   B.SetCurrentDebugLocation(I.getDebugLoc());
2003 
2004   unsigned IncNameSuffix = 0;
2005   for (VectorSlice &S : Slices) {
2006     // We need to reset the build on each iteration, because getSlicedVal may
2007     // have inserted something into I's BB.
2008     B.SetInsertPoint(I.getParent()->getFirstNonPHIIt());
2009     S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
2010 
2011     for (const auto &[Idx, BB] : enumerate(I.blocks())) {
2012       S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
2013                                            "largephi.extractslice" +
2014                                                std::to_string(IncNameSuffix++)),
2015                             BB);
2016     }
2017   }
2018 
2019   // And replace this PHI with a vector of all the previous PHI values.
2020   Value *Vec = PoisonValue::get(FVT);
2021   unsigned NameSuffix = 0;
2022   for (VectorSlice &S : Slices) {
2023     const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
2024     if (S.NumElts > 1)
2025       Vec =
2026           B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
2027     else
2028       Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
2029   }
2030 
2031   I.replaceAllUsesWith(Vec);
2032   I.eraseFromParent();
2033   return true;
2034 }
2035 
2036 /// \param V  Value to check
2037 /// \param DL DataLayout
2038 /// \param TM TargetMachine (TODO: remove once DL contains nullptr values)
2039 /// \param AS Target Address Space
2040 /// \return true if \p V cannot be the null value of \p AS, false otherwise.
2041 static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL,
2042                                 const AMDGPUTargetMachine &TM, unsigned AS) {
2043   // Pointer cannot be null if it's a block address, GV or alloca.
2044   // NOTE: We don't support extern_weak, but if we did, we'd need to check for
2045   // it as the symbol could be null in such cases.
2046   if (isa<BlockAddress>(V) || isa<GlobalValue>(V) || isa<AllocaInst>(V))
2047     return true;
2048 
2049   // Check nonnull arguments.
2050   if (const auto *Arg = dyn_cast<Argument>(V); Arg && Arg->hasNonNullAttr())
2051     return true;
2052 
2053   // getUnderlyingObject may have looked through another addrspacecast, although
2054   // the optimizable situations most likely folded out by now.
2055   if (AS != cast<PointerType>(V->getType())->getAddressSpace())
2056     return false;
2057 
2058   // TODO: Calls that return nonnull?
2059 
2060   // For all other things, use KnownBits.
2061   // We either use 0 or all bits set to indicate null, so check whether the
2062   // value can be zero or all ones.
2063   //
2064   // TODO: Use ValueTracking's isKnownNeverNull if it becomes aware that some
2065   // address spaces have non-zero null values.
2066   auto SrcPtrKB = computeKnownBits(V, DL);
2067   const auto NullVal = TM.getNullPointerValue(AS);
2068 
2069   assert(SrcPtrKB.getBitWidth() == DL.getPointerSizeInBits(AS));
2070   assert((NullVal == 0 || NullVal == -1) &&
2071          "don't know how to check for this null value!");
2072   return NullVal ? !SrcPtrKB.getMaxValue().isAllOnes() : SrcPtrKB.isNonZero();
2073 }
2074 
2075 bool AMDGPUCodeGenPrepareImpl::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2076   // Intrinsic doesn't support vectors, also it seems that it's often difficult
2077   // to prove that a vector cannot have any nulls in it so it's unclear if it's
2078   // worth supporting.
2079   if (I.getType()->isVectorTy())
2080     return false;
2081 
2082   // Check if this can be lowered to a amdgcn.addrspacecast.nonnull.
2083   // This is only worthwhile for casts from/to priv/local to flat.
2084   const unsigned SrcAS = I.getSrcAddressSpace();
2085   const unsigned DstAS = I.getDestAddressSpace();
2086 
2087   bool CanLower = false;
2088   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
2089     CanLower = (DstAS == AMDGPUAS::LOCAL_ADDRESS ||
2090                 DstAS == AMDGPUAS::PRIVATE_ADDRESS);
2091   else if (DstAS == AMDGPUAS::FLAT_ADDRESS)
2092     CanLower = (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
2093                 SrcAS == AMDGPUAS::PRIVATE_ADDRESS);
2094   if (!CanLower)
2095     return false;
2096 
2097   SmallVector<const Value *, 4> WorkList;
2098   getUnderlyingObjects(I.getOperand(0), WorkList);
2099   if (!all_of(WorkList, [&](const Value *V) {
2100         return isPtrKnownNeverNull(V, DL, TM, SrcAS);
2101       }))
2102     return false;
2103 
2104   IRBuilder<> B(&I);
2105   auto *Intrin = B.CreateIntrinsic(
2106       I.getType(), Intrinsic::amdgcn_addrspacecast_nonnull, {I.getOperand(0)});
2107   I.replaceAllUsesWith(Intrin);
2108   I.eraseFromParent();
2109   return true;
2110 }
2111 
2112 bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
2113   switch (I.getIntrinsicID()) {
2114   case Intrinsic::bitreverse:
2115     return visitBitreverseIntrinsicInst(I);
2116   case Intrinsic::minnum:
2117     return visitMinNum(I);
2118   case Intrinsic::sqrt:
2119     return visitSqrt(I);
2120   default:
2121     return false;
2122   }
2123 }
2124 
2125 bool AMDGPUCodeGenPrepareImpl::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
2126   bool Changed = false;
2127 
2128   if (ST.has16BitInsts() && needsPromotionToI32(I.getType()) &&
2129       UA.isUniform(&I))
2130     Changed |= promoteUniformBitreverseToI32(I);
2131 
2132   return Changed;
2133 }
2134 
2135 /// Match non-nan fract pattern.
2136 ///   minnum(fsub(x, floor(x)), nextafter(1.0, -1.0)
2137 ///
2138 /// If fract is a useful instruction for the subtarget. Does not account for the
2139 /// nan handling; the instruction has a nan check on the input value.
2140 Value *AMDGPUCodeGenPrepareImpl::matchFractPat(IntrinsicInst &I) {
2141   if (ST.hasFractBug())
2142     return nullptr;
2143 
2144   if (I.getIntrinsicID() != Intrinsic::minnum)
2145     return nullptr;
2146 
2147   Type *Ty = I.getType();
2148   if (!isLegalFloatingTy(Ty->getScalarType()))
2149     return nullptr;
2150 
2151   Value *Arg0 = I.getArgOperand(0);
2152   Value *Arg1 = I.getArgOperand(1);
2153 
2154   const APFloat *C;
2155   if (!match(Arg1, m_APFloat(C)))
2156     return nullptr;
2157 
2158   APFloat One(1.0);
2159   bool LosesInfo;
2160   One.convert(C->getSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
2161 
2162   // Match nextafter(1.0, -1)
2163   One.next(true);
2164   if (One != *C)
2165     return nullptr;
2166 
2167   Value *FloorSrc;
2168   if (match(Arg0, m_FSub(m_Value(FloorSrc),
2169                          m_Intrinsic<Intrinsic::floor>(m_Deferred(FloorSrc)))))
2170     return FloorSrc;
2171   return nullptr;
2172 }
2173 
2174 Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
2175                                                Value *FractArg) {
2176   SmallVector<Value *, 4> FractVals;
2177   extractValues(Builder, FractVals, FractArg);
2178 
2179   SmallVector<Value *, 4> ResultVals(FractVals.size());
2180 
2181   Type *Ty = FractArg->getType()->getScalarType();
2182   for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
2183     ResultVals[I] =
2184         Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
2185   }
2186 
2187   return insertValues(Builder, FractArg->getType(), ResultVals);
2188 }
2189 
2190 bool AMDGPUCodeGenPrepareImpl::visitMinNum(IntrinsicInst &I) {
2191   Value *FractArg = matchFractPat(I);
2192   if (!FractArg)
2193     return false;
2194 
2195   // Match pattern for fract intrinsic in contexts where the nan check has been
2196   // optimized out (and hope the knowledge the source can't be nan wasn't lost).
2197   if (!I.hasNoNaNs() &&
2198       !isKnownNeverNaN(FractArg, /*Depth=*/0, SimplifyQuery(DL, TLI)))
2199     return false;
2200 
2201   IRBuilder<> Builder(&I);
2202   FastMathFlags FMF = I.getFastMathFlags();
2203   FMF.setNoNaNs();
2204   Builder.setFastMathFlags(FMF);
2205 
2206   Value *Fract = applyFractPat(Builder, FractArg);
2207   Fract->takeName(&I);
2208   I.replaceAllUsesWith(Fract);
2209 
2210   RecursivelyDeleteTriviallyDeadInstructions(&I, TLI);
2211   return true;
2212 }
2213 
2214 static bool isOneOrNegOne(const Value *Val) {
2215   const APFloat *C;
2216   return match(Val, m_APFloat(C)) && C->getExactLog2Abs() == 0;
2217 }
2218 
2219 // Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
2220 bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
2221   Type *Ty = Sqrt.getType()->getScalarType();
2222   if (!Ty->isFloatTy() && (!Ty->isHalfTy() || ST.has16BitInsts()))
2223     return false;
2224 
2225   const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
2226   FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
2227 
2228   // We're trying to handle the fast-but-not-that-fast case only. The lowering
2229   // of fast llvm.sqrt will give the raw instruction anyway.
2230   if (SqrtFMF.approxFunc() || HasUnsafeFPMath)
2231     return false;
2232 
2233   const float ReqdAccuracy = FPOp->getFPAccuracy();
2234 
2235   // Defer correctly rounded expansion to codegen.
2236   if (ReqdAccuracy < 1.0f)
2237     return false;
2238 
2239   // FIXME: This is an ugly hack for this pass using forward iteration instead
2240   // of reverse. If it worked like a normal combiner, the rsq would form before
2241   // we saw a sqrt call.
2242   auto *FDiv =
2243       dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
2244   if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
2245       FDiv->getFPAccuracy() >= 1.0f &&
2246       canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
2247       // TODO: We should also handle the arcp case for the fdiv with non-1 value
2248       isOneOrNegOne(FDiv->getOperand(0)))
2249     return false;
2250 
2251   Value *SrcVal = Sqrt.getOperand(0);
2252   bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
2253 
2254   // The raw instruction is 1 ulp, but the correction for denormal handling
2255   // brings it to 2.
2256   if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
2257     return false;
2258 
2259   IRBuilder<> Builder(&Sqrt);
2260   SmallVector<Value *, 4> SrcVals;
2261   extractValues(Builder, SrcVals, SrcVal);
2262 
2263   SmallVector<Value *, 4> ResultVals(SrcVals.size());
2264   for (int I = 0, E = SrcVals.size(); I != E; ++I) {
2265     if (CanTreatAsDAZ)
2266       ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
2267     else
2268       ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
2269   }
2270 
2271   Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
2272   NewSqrt->takeName(&Sqrt);
2273   Sqrt.replaceAllUsesWith(NewSqrt);
2274   Sqrt.eraseFromParent();
2275   return true;
2276 }
2277 
2278 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
2279   if (skipFunction(F))
2280     return false;
2281 
2282   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
2283   if (!TPC)
2284     return false;
2285 
2286   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2287   const TargetLibraryInfo *TLI =
2288       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2289   AssumptionCache *AC =
2290       &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2291   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2292   const DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
2293   const UniformityInfo &UA =
2294       getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
2295   return AMDGPUCodeGenPrepareImpl(F, TM, TLI, AC, DT, UA).run();
2296 }
2297 
2298 PreservedAnalyses AMDGPUCodeGenPreparePass::run(Function &F,
2299                                                 FunctionAnalysisManager &FAM) {
2300   const AMDGPUTargetMachine &ATM = static_cast<const AMDGPUTargetMachine &>(TM);
2301   const TargetLibraryInfo *TLI = &FAM.getResult<TargetLibraryAnalysis>(F);
2302   AssumptionCache *AC = &FAM.getResult<AssumptionAnalysis>(F);
2303   const DominatorTree *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2304   const UniformityInfo &UA = FAM.getResult<UniformityInfoAnalysis>(F);
2305   AMDGPUCodeGenPrepareImpl Impl(F, ATM, TLI, AC, DT, UA);
2306   if (!Impl.run())
2307     return PreservedAnalyses::all();
2308   PreservedAnalyses PA = PreservedAnalyses::none();
2309   if (!Impl.FlowChanged)
2310     PA.preserveSet<CFGAnalyses>();
2311   return PA;
2312 }
2313 
2314 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
2315                       "AMDGPU IR optimizations", false, false)
2316 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2317 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2318 INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
2319 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
2320                     false, false)
2321 
2322 char AMDGPUCodeGenPrepare::ID = 0;
2323 
2324 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
2325   return new AMDGPUCodeGenPrepare();
2326 }
2327