xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision 5660bb6bc9ac5ed910d95210e43ed437f155212d)
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 "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "llvm/ADT/FloatingPointMode.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/Loads.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/InstVisitor.h"
34 #include "llvm/IR/InstrTypes.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Transforms/Utils/IntegerDivision.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Casting.h"
47 #include <cassert>
48 #include <iterator>
49 
50 #define DEBUG_TYPE "amdgpu-codegenprepare"
51 
52 using namespace llvm;
53 
54 namespace {
55 
56 static cl::opt<bool> WidenLoads(
57   "amdgpu-codegenprepare-widen-constant-loads",
58   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
59   cl::ReallyHidden,
60   cl::init(true));
61 
62 static cl::opt<bool> UseMul24Intrin(
63   "amdgpu-codegenprepare-mul24",
64   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
65   cl::ReallyHidden,
66   cl::init(true));
67 
68 // Legalize 64-bit division by using the generic IR expansion.
69 static cl::opt<bool> ExpandDiv64InIR(
70   "amdgpu-codegenprepare-expand-div64",
71   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
72   cl::ReallyHidden,
73   cl::init(false));
74 
75 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
76 // and is used for testing the legalizer.
77 static cl::opt<bool> DisableIDivExpand(
78   "amdgpu-codegenprepare-disable-idiv-expansion",
79   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
80   cl::ReallyHidden,
81   cl::init(false));
82 
83 class AMDGPUCodeGenPrepare : public FunctionPass,
84                              public InstVisitor<AMDGPUCodeGenPrepare, bool> {
85   const GCNSubtarget *ST = nullptr;
86   AssumptionCache *AC = nullptr;
87   DominatorTree *DT = nullptr;
88   LegacyDivergenceAnalysis *DA = nullptr;
89   Module *Mod = nullptr;
90   const DataLayout *DL = nullptr;
91   bool HasUnsafeFPMath = false;
92   bool HasFP32Denormals = false;
93 
94   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
95   /// binary operation \p V.
96   ///
97   /// \returns Binary operation \p V.
98   /// \returns \p T's base element bit width.
99   unsigned getBaseElementBitWidth(const Type *T) const;
100 
101   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
102   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
103   /// is returned.
104   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
105 
106   /// \returns True if binary operation \p I is a signed binary operation, false
107   /// otherwise.
108   bool isSigned(const BinaryOperator &I) const;
109 
110   /// \returns True if the condition of 'select' operation \p I comes from a
111   /// signed 'icmp' operation, false otherwise.
112   bool isSigned(const SelectInst &I) const;
113 
114   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
115   /// false otherwise.
116   bool needsPromotionToI32(const Type *T) const;
117 
118   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
119   /// operation.
120   ///
121   /// \details \p I's base element bit width must be greater than 1 and less
122   /// than or equal 16. Promotion is done by sign or zero extending operands to
123   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
124   /// truncating the result of 32 bit binary operation back to \p I's original
125   /// type. Division operation is not promoted.
126   ///
127   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
128   /// false otherwise.
129   bool promoteUniformOpToI32(BinaryOperator &I) const;
130 
131   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
132   ///
133   /// \details \p I's base element bit width must be greater than 1 and less
134   /// than or equal 16. Promotion is done by sign or zero extending operands to
135   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
136   ///
137   /// \returns True.
138   bool promoteUniformOpToI32(ICmpInst &I) const;
139 
140   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
141   /// operation.
142   ///
143   /// \details \p I's base element bit width must be greater than 1 and less
144   /// than or equal 16. Promotion is done by sign or zero extending operands to
145   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
146   /// result of 32 bit 'select' operation back to \p I's original type.
147   ///
148   /// \returns True.
149   bool promoteUniformOpToI32(SelectInst &I) const;
150 
151   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
152   /// intrinsic.
153   ///
154   /// \details \p I's base element bit width must be greater than 1 and less
155   /// than or equal 16. Promotion is done by zero extending the operand to 32
156   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
157   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
158   /// shift amount is 32 minus \p I's base element bit width), and truncating
159   /// the result of the shift operation back to \p I's original type.
160   ///
161   /// \returns True.
162   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
163 
164 
165   unsigned numBitsUnsigned(Value *Op, unsigned ScalarSize) const;
166   unsigned numBitsSigned(Value *Op, unsigned ScalarSize) const;
167   bool isI24(Value *V, unsigned ScalarSize) const;
168   bool isU24(Value *V, unsigned ScalarSize) const;
169 
170   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
171   /// SelectionDAG has an issue where an and asserting the bits are known
172   bool replaceMulWithMul24(BinaryOperator &I) const;
173 
174   /// Perform same function as equivalently named function in DAGCombiner. Since
175   /// we expand some divisions here, we need to perform this before obscuring.
176   bool foldBinOpIntoSelect(BinaryOperator &I) const;
177 
178   bool divHasSpecialOptimization(BinaryOperator &I,
179                                  Value *Num, Value *Den) const;
180   int getDivNumBits(BinaryOperator &I,
181                     Value *Num, Value *Den,
182                     unsigned AtLeast, bool Signed) const;
183 
184   /// Expands 24 bit div or rem.
185   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
186                         Value *Num, Value *Den,
187                         bool IsDiv, bool IsSigned) const;
188 
189   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
190                             Value *Num, Value *Den, unsigned NumBits,
191                             bool IsDiv, bool IsSigned) const;
192 
193   /// Expands 32 bit div or rem.
194   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
195                         Value *Num, Value *Den) const;
196 
197   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
198                         Value *Num, Value *Den) const;
199   void expandDivRem64(BinaryOperator &I) const;
200 
201   /// Widen a scalar load.
202   ///
203   /// \details \p Widen scalar load for uniform, small type loads from constant
204   //  memory / to a full 32-bits and then truncate the input to allow a scalar
205   //  load instead of a vector load.
206   //
207   /// \returns True.
208 
209   bool canWidenScalarExtLoad(LoadInst &I) const;
210 
211 public:
212   static char ID;
213 
214   AMDGPUCodeGenPrepare() : FunctionPass(ID) {}
215 
216   bool visitFDiv(BinaryOperator &I);
217 
218   bool visitInstruction(Instruction &I) { return false; }
219   bool visitBinaryOperator(BinaryOperator &I);
220   bool visitLoadInst(LoadInst &I);
221   bool visitICmpInst(ICmpInst &I);
222   bool visitSelectInst(SelectInst &I);
223 
224   bool visitIntrinsicInst(IntrinsicInst &I);
225   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
226 
227   bool doInitialization(Module &M) override;
228   bool runOnFunction(Function &F) override;
229 
230   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
231 
232   void getAnalysisUsage(AnalysisUsage &AU) const override {
233     AU.addRequired<AssumptionCacheTracker>();
234     AU.addRequired<LegacyDivergenceAnalysis>();
235 
236     // FIXME: Division expansion needs to preserve the dominator tree.
237     if (!ExpandDiv64InIR)
238       AU.setPreservesAll();
239  }
240 };
241 
242 } // end anonymous namespace
243 
244 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(const Type *T) const {
245   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
246 
247   if (T->isIntegerTy())
248     return T->getIntegerBitWidth();
249   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
250 }
251 
252 Type *AMDGPUCodeGenPrepare::getI32Ty(IRBuilder<> &B, const Type *T) const {
253   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
254 
255   if (T->isIntegerTy())
256     return B.getInt32Ty();
257   return VectorType::get(B.getInt32Ty(), cast<VectorType>(T)->getNumElements());
258 }
259 
260 bool AMDGPUCodeGenPrepare::isSigned(const BinaryOperator &I) const {
261   return I.getOpcode() == Instruction::AShr ||
262       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
263 }
264 
265 bool AMDGPUCodeGenPrepare::isSigned(const SelectInst &I) const {
266   return isa<ICmpInst>(I.getOperand(0)) ?
267       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
268 }
269 
270 bool AMDGPUCodeGenPrepare::needsPromotionToI32(const Type *T) const {
271   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
272   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
273     return true;
274 
275   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
276     // TODO: The set of packed operations is more limited, so may want to
277     // promote some anyway.
278     if (ST->hasVOP3PInsts())
279       return false;
280 
281     return needsPromotionToI32(VT->getElementType());
282   }
283 
284   return false;
285 }
286 
287 // Return true if the op promoted to i32 should have nsw set.
288 static bool promotedOpIsNSW(const Instruction &I) {
289   switch (I.getOpcode()) {
290   case Instruction::Shl:
291   case Instruction::Add:
292   case Instruction::Sub:
293     return true;
294   case Instruction::Mul:
295     return I.hasNoUnsignedWrap();
296   default:
297     return false;
298   }
299 }
300 
301 // Return true if the op promoted to i32 should have nuw set.
302 static bool promotedOpIsNUW(const Instruction &I) {
303   switch (I.getOpcode()) {
304   case Instruction::Shl:
305   case Instruction::Add:
306   case Instruction::Mul:
307     return true;
308   case Instruction::Sub:
309     return I.hasNoUnsignedWrap();
310   default:
311     return false;
312   }
313 }
314 
315 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(LoadInst &I) const {
316   Type *Ty = I.getType();
317   const DataLayout &DL = Mod->getDataLayout();
318   int TySize = DL.getTypeSizeInBits(Ty);
319   unsigned Align = I.getAlignment() ?
320                    I.getAlignment() : DL.getABITypeAlignment(Ty);
321 
322   return I.isSimple() && TySize < 32 && Align >= 4 && DA->isUniform(&I);
323 }
324 
325 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(BinaryOperator &I) const {
326   assert(needsPromotionToI32(I.getType()) &&
327          "I does not need promotion to i32");
328 
329   if (I.getOpcode() == Instruction::SDiv ||
330       I.getOpcode() == Instruction::UDiv ||
331       I.getOpcode() == Instruction::SRem ||
332       I.getOpcode() == Instruction::URem)
333     return false;
334 
335   IRBuilder<> Builder(&I);
336   Builder.SetCurrentDebugLocation(I.getDebugLoc());
337 
338   Type *I32Ty = getI32Ty(Builder, I.getType());
339   Value *ExtOp0 = nullptr;
340   Value *ExtOp1 = nullptr;
341   Value *ExtRes = nullptr;
342   Value *TruncRes = nullptr;
343 
344   if (isSigned(I)) {
345     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
346     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
347   } else {
348     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
349     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
350   }
351 
352   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
353   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
354     if (promotedOpIsNSW(cast<Instruction>(I)))
355       Inst->setHasNoSignedWrap();
356 
357     if (promotedOpIsNUW(cast<Instruction>(I)))
358       Inst->setHasNoUnsignedWrap();
359 
360     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
361       Inst->setIsExact(ExactOp->isExact());
362   }
363 
364   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
365 
366   I.replaceAllUsesWith(TruncRes);
367   I.eraseFromParent();
368 
369   return true;
370 }
371 
372 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(ICmpInst &I) const {
373   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
374          "I does not need promotion to i32");
375 
376   IRBuilder<> Builder(&I);
377   Builder.SetCurrentDebugLocation(I.getDebugLoc());
378 
379   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
380   Value *ExtOp0 = nullptr;
381   Value *ExtOp1 = nullptr;
382   Value *NewICmp  = nullptr;
383 
384   if (I.isSigned()) {
385     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
386     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
387   } else {
388     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
389     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
390   }
391   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
392 
393   I.replaceAllUsesWith(NewICmp);
394   I.eraseFromParent();
395 
396   return true;
397 }
398 
399 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(SelectInst &I) const {
400   assert(needsPromotionToI32(I.getType()) &&
401          "I does not need promotion to i32");
402 
403   IRBuilder<> Builder(&I);
404   Builder.SetCurrentDebugLocation(I.getDebugLoc());
405 
406   Type *I32Ty = getI32Ty(Builder, I.getType());
407   Value *ExtOp1 = nullptr;
408   Value *ExtOp2 = nullptr;
409   Value *ExtRes = nullptr;
410   Value *TruncRes = nullptr;
411 
412   if (isSigned(I)) {
413     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
414     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
415   } else {
416     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
417     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
418   }
419   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
420   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
421 
422   I.replaceAllUsesWith(TruncRes);
423   I.eraseFromParent();
424 
425   return true;
426 }
427 
428 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32(
429     IntrinsicInst &I) const {
430   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
431          "I must be bitreverse intrinsic");
432   assert(needsPromotionToI32(I.getType()) &&
433          "I does not need promotion to i32");
434 
435   IRBuilder<> Builder(&I);
436   Builder.SetCurrentDebugLocation(I.getDebugLoc());
437 
438   Type *I32Ty = getI32Ty(Builder, I.getType());
439   Function *I32 =
440       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
441   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
442   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
443   Value *LShrOp =
444       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
445   Value *TruncRes =
446       Builder.CreateTrunc(LShrOp, I.getType());
447 
448   I.replaceAllUsesWith(TruncRes);
449   I.eraseFromParent();
450 
451   return true;
452 }
453 
454 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(Value *Op,
455                                                unsigned ScalarSize) const {
456   KnownBits Known = computeKnownBits(Op, *DL, 0, AC);
457   return ScalarSize - Known.countMinLeadingZeros();
458 }
459 
460 unsigned AMDGPUCodeGenPrepare::numBitsSigned(Value *Op,
461                                              unsigned ScalarSize) const {
462   // In order for this to be a signed 24-bit value, bit 23, must
463   // be a sign bit.
464   return ScalarSize - ComputeNumSignBits(Op, *DL, 0, AC);
465 }
466 
467 bool AMDGPUCodeGenPrepare::isI24(Value *V, unsigned ScalarSize) const {
468   return ScalarSize >= 24 && // Types less than 24-bit should be treated
469                                      // as unsigned 24-bit values.
470     numBitsSigned(V, ScalarSize) < 24;
471 }
472 
473 bool AMDGPUCodeGenPrepare::isU24(Value *V, unsigned ScalarSize) const {
474   return numBitsUnsigned(V, ScalarSize) <= 24;
475 }
476 
477 static void extractValues(IRBuilder<> &Builder,
478                           SmallVectorImpl<Value *> &Values, Value *V) {
479   VectorType *VT = dyn_cast<VectorType>(V->getType());
480   if (!VT) {
481     Values.push_back(V);
482     return;
483   }
484 
485   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
486     Values.push_back(Builder.CreateExtractElement(V, I));
487 }
488 
489 static Value *insertValues(IRBuilder<> &Builder,
490                            Type *Ty,
491                            SmallVectorImpl<Value *> &Values) {
492   if (Values.size() == 1)
493     return Values[0];
494 
495   Value *NewVal = UndefValue::get(Ty);
496   for (int I = 0, E = Values.size(); I != E; ++I)
497     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
498 
499   return NewVal;
500 }
501 
502 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(BinaryOperator &I) const {
503   if (I.getOpcode() != Instruction::Mul)
504     return false;
505 
506   Type *Ty = I.getType();
507   unsigned Size = Ty->getScalarSizeInBits();
508   if (Size <= 16 && ST->has16BitInsts())
509     return false;
510 
511   // Prefer scalar if this could be s_mul_i32
512   if (DA->isUniform(&I))
513     return false;
514 
515   Value *LHS = I.getOperand(0);
516   Value *RHS = I.getOperand(1);
517   IRBuilder<> Builder(&I);
518   Builder.SetCurrentDebugLocation(I.getDebugLoc());
519 
520   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
521 
522   // TODO: Should this try to match mulhi24?
523   if (ST->hasMulU24() && isU24(LHS, Size) && isU24(RHS, Size)) {
524     IntrID = Intrinsic::amdgcn_mul_u24;
525   } else if (ST->hasMulI24() && isI24(LHS, Size) && isI24(RHS, Size)) {
526     IntrID = Intrinsic::amdgcn_mul_i24;
527   } else
528     return false;
529 
530   SmallVector<Value *, 4> LHSVals;
531   SmallVector<Value *, 4> RHSVals;
532   SmallVector<Value *, 4> ResultVals;
533   extractValues(Builder, LHSVals, LHS);
534   extractValues(Builder, RHSVals, RHS);
535 
536 
537   IntegerType *I32Ty = Builder.getInt32Ty();
538   FunctionCallee Intrin = Intrinsic::getDeclaration(Mod, IntrID);
539   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
540     Value *LHS, *RHS;
541     if (IntrID == Intrinsic::amdgcn_mul_u24) {
542       LHS = Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
543       RHS = Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
544     } else {
545       LHS = Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty);
546       RHS = Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty);
547     }
548 
549     Value *Result = Builder.CreateCall(Intrin, {LHS, RHS});
550 
551     if (IntrID == Intrinsic::amdgcn_mul_u24) {
552       ResultVals.push_back(Builder.CreateZExtOrTrunc(Result,
553                                                      LHSVals[I]->getType()));
554     } else {
555       ResultVals.push_back(Builder.CreateSExtOrTrunc(Result,
556                                                      LHSVals[I]->getType()));
557     }
558   }
559 
560   Value *NewVal = insertValues(Builder, Ty, ResultVals);
561   NewVal->takeName(&I);
562   I.replaceAllUsesWith(NewVal);
563   I.eraseFromParent();
564 
565   return true;
566 }
567 
568 // Find a select instruction, which may have been casted. This is mostly to deal
569 // with cases where i16 selects were promoted here to i32.
570 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
571   Cast = nullptr;
572   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
573     return Sel;
574 
575   if ((Cast = dyn_cast<CastInst>(V))) {
576     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
577       return Sel;
578   }
579 
580   return nullptr;
581 }
582 
583 bool AMDGPUCodeGenPrepare::foldBinOpIntoSelect(BinaryOperator &BO) const {
584   // Don't do this unless the old select is going away. We want to eliminate the
585   // binary operator, not replace a binop with a select.
586   int SelOpNo = 0;
587 
588   CastInst *CastOp;
589 
590   // TODO: Should probably try to handle some cases with multiple
591   // users. Duplicating the select may be profitable for division.
592   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
593   if (!Sel || !Sel->hasOneUse()) {
594     SelOpNo = 1;
595     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
596   }
597 
598   if (!Sel || !Sel->hasOneUse())
599     return false;
600 
601   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
602   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
603   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
604   if (!CBO || !CT || !CF)
605     return false;
606 
607   if (CastOp) {
608     if (!CastOp->hasOneUse())
609       return false;
610     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
611     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
612   }
613 
614   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
615   // need to handle divisions here.
616   Constant *FoldedT = SelOpNo ?
617     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
618     ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
619   if (isa<ConstantExpr>(FoldedT))
620     return false;
621 
622   Constant *FoldedF = SelOpNo ?
623     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
624     ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
625   if (isa<ConstantExpr>(FoldedF))
626     return false;
627 
628   IRBuilder<> Builder(&BO);
629   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
630   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
631     Builder.setFastMathFlags(FPOp->getFastMathFlags());
632 
633   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
634                                           FoldedT, FoldedF);
635   NewSelect->takeName(&BO);
636   BO.replaceAllUsesWith(NewSelect);
637   BO.eraseFromParent();
638   if (CastOp)
639     CastOp->eraseFromParent();
640   Sel->eraseFromParent();
641   return true;
642 }
643 
644 // Optimize fdiv with rcp:
645 //
646 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
647 //               allowed with unsafe-fp-math or afn.
648 //
649 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
650 static Value *optimizeWithRcp(Value *Num, Value *Den, bool AllowInaccurateRcp,
651                               bool RcpIsAccurate, IRBuilder<> &Builder,
652                               Module *Mod) {
653 
654   if (!AllowInaccurateRcp && !RcpIsAccurate)
655     return nullptr;
656 
657   Type *Ty = Den->getType();
658   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
659     if (AllowInaccurateRcp || RcpIsAccurate) {
660       if (CLHS->isExactlyValue(1.0)) {
661         Function *Decl = Intrinsic::getDeclaration(
662           Mod, Intrinsic::amdgcn_rcp, Ty);
663 
664         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
665         // the CI documentation has a worst case error of 1 ulp.
666         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
667         // use it as long as we aren't trying to use denormals.
668         //
669         // v_rcp_f16 and v_rsq_f16 DO support denormals.
670 
671         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
672         //       insert rsq intrinsic here.
673 
674         // 1.0 / x -> rcp(x)
675         return Builder.CreateCall(Decl, { Den });
676       }
677 
678        // Same as for 1.0, but expand the sign out of the constant.
679       if (CLHS->isExactlyValue(-1.0)) {
680         Function *Decl = Intrinsic::getDeclaration(
681           Mod, Intrinsic::amdgcn_rcp, Ty);
682 
683          // -1.0 / x -> rcp (fneg x)
684          Value *FNeg = Builder.CreateFNeg(Den);
685          return Builder.CreateCall(Decl, { FNeg });
686        }
687     }
688   }
689 
690   if (AllowInaccurateRcp) {
691     Function *Decl = Intrinsic::getDeclaration(
692       Mod, Intrinsic::amdgcn_rcp, Ty);
693 
694     // Turn into multiply by the reciprocal.
695     // x / y -> x * (1.0 / y)
696     Value *Recip = Builder.CreateCall(Decl, { Den });
697     return Builder.CreateFMul(Num, Recip);
698   }
699   return nullptr;
700 }
701 
702 // optimize with fdiv.fast:
703 //
704 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
705 //
706 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
707 //
708 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
709 static Value *optimizeWithFDivFast(Value *Num, Value *Den, float ReqdAccuracy,
710                                    bool HasDenormals, IRBuilder<> &Builder,
711                                    Module *Mod) {
712   // fdiv.fast can achieve 2.5 ULP accuracy.
713   if (ReqdAccuracy < 2.5f)
714     return nullptr;
715 
716   // Only have fdiv.fast for f32.
717   Type *Ty = Den->getType();
718   if (!Ty->isFloatTy())
719     return nullptr;
720 
721   bool NumIsOne = false;
722   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
723     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
724       NumIsOne = true;
725   }
726 
727   // fdiv does not support denormals. But 1.0/x is always fine to use it.
728   if (HasDenormals && !NumIsOne)
729     return nullptr;
730 
731   Function *Decl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_fdiv_fast);
732   return Builder.CreateCall(Decl, { Num, Den });
733 }
734 
735 // Optimizations is performed based on fpmath, fast math flags as well as
736 // denormals to optimize fdiv with either rcp or fdiv.fast.
737 //
738 // With rcp:
739 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
740 //                 allowed with unsafe-fp-math or afn.
741 //
742 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
743 //
744 // With fdiv.fast:
745 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
746 //
747 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
748 //
749 // NOTE: rcp is the preference in cases that both are legal.
750 bool AMDGPUCodeGenPrepare::visitFDiv(BinaryOperator &FDiv) {
751 
752   Type *Ty = FDiv.getType()->getScalarType();
753 
754   // No intrinsic for fdiv16 if target does not support f16.
755   if (Ty->isHalfTy() && !ST->has16BitInsts())
756     return false;
757 
758   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
759   const float ReqdAccuracy =  FPOp->getFPAccuracy();
760 
761   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
762   FastMathFlags FMF = FPOp->getFastMathFlags();
763   const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc();
764 
765   // rcp_f16 is accurate for !fpmath >= 1.0ulp.
766   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
767   // rcp_f64 is never accurate.
768   const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) ||
769             (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f);
770 
771   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
772   Builder.setFastMathFlags(FMF);
773   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
774 
775   Value *Num = FDiv.getOperand(0);
776   Value *Den = FDiv.getOperand(1);
777 
778   Value *NewFDiv = nullptr;
779   if (VectorType *VT = dyn_cast<VectorType>(FDiv.getType())) {
780     NewFDiv = UndefValue::get(VT);
781 
782     // FIXME: Doesn't do the right thing for cases where the vector is partially
783     // constant. This works when the scalarizer pass is run first.
784     for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) {
785       Value *NumEltI = Builder.CreateExtractElement(Num, I);
786       Value *DenEltI = Builder.CreateExtractElement(Den, I);
787       // Try rcp first.
788       Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp,
789                                       RcpIsAccurate, Builder, Mod);
790       if (!NewElt) // Try fdiv.fast.
791         NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy,
792                                       HasFP32Denormals, Builder, Mod);
793       if (!NewElt) // Keep the original.
794         NewElt = Builder.CreateFDiv(NumEltI, DenEltI);
795 
796       NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I);
797     }
798   } else { // Scalar FDiv.
799     // Try rcp first.
800     NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate,
801                               Builder, Mod);
802     if (!NewFDiv) { // Try fdiv.fast.
803       NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals,
804                                      Builder, Mod);
805     }
806   }
807 
808   if (NewFDiv) {
809     FDiv.replaceAllUsesWith(NewFDiv);
810     NewFDiv->takeName(&FDiv);
811     FDiv.eraseFromParent();
812   }
813 
814   return !!NewFDiv;
815 }
816 
817 static bool hasUnsafeFPMath(const Function &F) {
818   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
819   return Attr.getValueAsString() == "true";
820 }
821 
822 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
823                                           Value *LHS, Value *RHS) {
824   Type *I32Ty = Builder.getInt32Ty();
825   Type *I64Ty = Builder.getInt64Ty();
826 
827   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
828   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
829   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
830   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
831   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
832   Hi = Builder.CreateTrunc(Hi, I32Ty);
833   return std::make_pair(Lo, Hi);
834 }
835 
836 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
837   return getMul64(Builder, LHS, RHS).second;
838 }
839 
840 /// Figure out how many bits are really needed for this ddivision. \p AtLeast is
841 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
842 /// first one is insufficient. Returns -1 on failure.
843 int AMDGPUCodeGenPrepare::getDivNumBits(BinaryOperator &I,
844                                         Value *Num, Value *Den,
845                                         unsigned AtLeast, bool IsSigned) const {
846   const DataLayout &DL = Mod->getDataLayout();
847   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
848   if (LHSSignBits < AtLeast)
849     return -1;
850 
851   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
852   if (RHSSignBits < AtLeast)
853     return -1;
854 
855   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
856   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
857   if (IsSigned)
858     ++DivBits;
859   return DivBits;
860 }
861 
862 // The fractional part of a float is enough to accurately represent up to
863 // a 24-bit signed integer.
864 Value *AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder,
865                                             BinaryOperator &I,
866                                             Value *Num, Value *Den,
867                                             bool IsDiv, bool IsSigned) const {
868   int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
869   if (DivBits == -1)
870     return nullptr;
871   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
872 }
873 
874 Value *AMDGPUCodeGenPrepare::expandDivRem24Impl(IRBuilder<> &Builder,
875                                                 BinaryOperator &I,
876                                                 Value *Num, Value *Den,
877                                                 unsigned DivBits,
878                                                 bool IsDiv, bool IsSigned) const {
879   Type *I32Ty = Builder.getInt32Ty();
880   Num = Builder.CreateTrunc(Num, I32Ty);
881   Den = Builder.CreateTrunc(Den, I32Ty);
882 
883   Type *F32Ty = Builder.getFloatTy();
884   ConstantInt *One = Builder.getInt32(1);
885   Value *JQ = One;
886 
887   if (IsSigned) {
888     // char|short jq = ia ^ ib;
889     JQ = Builder.CreateXor(Num, Den);
890 
891     // jq = jq >> (bitsize - 2)
892     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
893 
894     // jq = jq | 0x1
895     JQ = Builder.CreateOr(JQ, One);
896   }
897 
898   // int ia = (int)LHS;
899   Value *IA = Num;
900 
901   // int ib, (int)RHS;
902   Value *IB = Den;
903 
904   // float fa = (float)ia;
905   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
906                        : Builder.CreateUIToFP(IA, F32Ty);
907 
908   // float fb = (float)ib;
909   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
910                        : Builder.CreateUIToFP(IB,F32Ty);
911 
912   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
913                                                 Builder.getFloatTy());
914   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
915   Value *FQM = Builder.CreateFMul(FA, RCP);
916 
917   // fq = trunc(fqm);
918   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
919   FQ->copyFastMathFlags(Builder.getFastMathFlags());
920 
921   // float fqneg = -fq;
922   Value *FQNeg = Builder.CreateFNeg(FQ);
923 
924   // float fr = mad(fqneg, fb, fa);
925   Value *FR = Builder.CreateIntrinsic(Intrinsic::amdgcn_fmad_ftz,
926                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
927 
928   // int iq = (int)fq;
929   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
930                        : Builder.CreateFPToUI(FQ, I32Ty);
931 
932   // fr = fabs(fr);
933   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
934 
935   // fb = fabs(fb);
936   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
937 
938   // int cv = fr >= fb;
939   Value *CV = Builder.CreateFCmpOGE(FR, FB);
940 
941   // jq = (cv ? jq : 0);
942   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
943 
944   // dst = iq + jq;
945   Value *Div = Builder.CreateAdd(IQ, JQ);
946 
947   Value *Res = Div;
948   if (!IsDiv) {
949     // Rem needs compensation, it's easier to recompute it
950     Value *Rem = Builder.CreateMul(Div, Den);
951     Res = Builder.CreateSub(Num, Rem);
952   }
953 
954   if (DivBits != 0 && DivBits < 32) {
955     // Extend in register from the number of bits this divide really is.
956     if (IsSigned) {
957       int InRegBits = 32 - DivBits;
958 
959       Res = Builder.CreateShl(Res, InRegBits);
960       Res = Builder.CreateAShr(Res, InRegBits);
961     } else {
962       ConstantInt *TruncMask
963         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
964       Res = Builder.CreateAnd(Res, TruncMask);
965     }
966   }
967 
968   return Res;
969 }
970 
971 // Try to recognize special cases the DAG will emit special, better expansions
972 // than the general expansion we do here.
973 
974 // TODO: It would be better to just directly handle those optimizations here.
975 bool AMDGPUCodeGenPrepare::divHasSpecialOptimization(
976   BinaryOperator &I, Value *Num, Value *Den) const {
977   if (Constant *C = dyn_cast<Constant>(Den)) {
978     // Arbitrary constants get a better expansion as long as a wider mulhi is
979     // legal.
980     if (C->getType()->getScalarSizeInBits() <= 32)
981       return true;
982 
983     // TODO: Sdiv check for not exact for some reason.
984 
985     // If there's no wider mulhi, there's only a better expansion for powers of
986     // two.
987     // TODO: Should really know for each vector element.
988     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
989       return true;
990 
991     return false;
992   }
993 
994   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
995     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
996     if (BinOpDen->getOpcode() == Instruction::Shl &&
997         isa<Constant>(BinOpDen->getOperand(0)) &&
998         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
999                                0, AC, &I, DT)) {
1000       return true;
1001     }
1002   }
1003 
1004   return false;
1005 }
1006 
1007 Value* AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder,
1008                                             BinaryOperator &I,
1009                                             Value *Num, Value *Den) const {
1010   Instruction::BinaryOps Opc = I.getOpcode();
1011   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1012          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1013 
1014   FastMathFlags FMF;
1015   FMF.setFast();
1016   Builder.setFastMathFlags(FMF);
1017 
1018   if (divHasSpecialOptimization(I, Num, Den))
1019     return nullptr;  // Keep it for later optimization.
1020 
1021   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1022   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1023 
1024   Type *Ty = Num->getType();
1025   Type *I32Ty = Builder.getInt32Ty();
1026   Type *F32Ty = Builder.getFloatTy();
1027 
1028   if (Ty->getScalarSizeInBits() < 32) {
1029     if (IsSigned) {
1030       Num = Builder.CreateSExt(Num, I32Ty);
1031       Den = Builder.CreateSExt(Den, I32Ty);
1032     } else {
1033       Num = Builder.CreateZExt(Num, I32Ty);
1034       Den = Builder.CreateZExt(Den, I32Ty);
1035     }
1036   }
1037 
1038   if (Value *Res = expandDivRem24(Builder, I, Num, Den, IsDiv, IsSigned)) {
1039     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1040                       Builder.CreateZExtOrTrunc(Res, Ty);
1041   }
1042 
1043   ConstantInt *Zero = Builder.getInt32(0);
1044   ConstantInt *One = Builder.getInt32(1);
1045 
1046   Value *Sign = nullptr;
1047   if (IsSigned) {
1048     ConstantInt *K31 = Builder.getInt32(31);
1049     Value *LHSign = Builder.CreateAShr(Num, K31);
1050     Value *RHSign = Builder.CreateAShr(Den, K31);
1051     // Remainder sign is the same as LHS
1052     Sign = IsDiv ? Builder.CreateXor(LHSign, RHSign) : LHSign;
1053 
1054     Num = Builder.CreateAdd(Num, LHSign);
1055     Den = Builder.CreateAdd(Den, RHSign);
1056 
1057     Num = Builder.CreateXor(Num, LHSign);
1058     Den = Builder.CreateXor(Den, RHSign);
1059   }
1060 
1061   // RCP =  URECIP(Den) = 2^32 / Den + e
1062   // e is rounding error.
1063   Value *DEN_F32 = Builder.CreateUIToFP(Den, F32Ty);
1064 
1065   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
1066                                                 Builder.getFloatTy());
1067   Value *RCP_F32 = Builder.CreateCall(RcpDecl, { DEN_F32 });
1068   Constant *UINT_MAX_PLUS_1 = ConstantFP::get(F32Ty, BitsToFloat(0x4f800000));
1069   Value *RCP_SCALE = Builder.CreateFMul(RCP_F32, UINT_MAX_PLUS_1);
1070   Value *RCP = Builder.CreateFPToUI(RCP_SCALE, I32Ty);
1071 
1072   // RCP_LO, RCP_HI = mul(RCP, Den) */
1073   Value *RCP_LO, *RCP_HI;
1074   std::tie(RCP_LO, RCP_HI) = getMul64(Builder, RCP, Den);
1075 
1076   // NEG_RCP_LO = -RCP_LO
1077   Value *NEG_RCP_LO = Builder.CreateNeg(RCP_LO);
1078 
1079   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1080   Value *RCP_HI_0_CC = Builder.CreateICmpEQ(RCP_HI, Zero);
1081   Value *ABS_RCP_LO = Builder.CreateSelect(RCP_HI_0_CC, NEG_RCP_LO, RCP_LO);
1082 
1083   // Calculate the rounding error from the URECIP instruction
1084   // E = mulhu(ABS_RCP_LO, RCP)
1085   Value *E = getMulHu(Builder, ABS_RCP_LO, RCP);
1086 
1087   // RCP_A_E = RCP + E
1088   Value *RCP_A_E = Builder.CreateAdd(RCP, E);
1089 
1090   // RCP_S_E = RCP - E
1091   Value *RCP_S_E = Builder.CreateSub(RCP, E);
1092 
1093   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1094   Value *Tmp0 = Builder.CreateSelect(RCP_HI_0_CC, RCP_A_E, RCP_S_E);
1095 
1096   // Quotient = mulhu(Tmp0, Num)
1097   Value *Quotient = getMulHu(Builder, Tmp0, Num);
1098 
1099   // Num_S_Remainder = Quotient * Den
1100   Value *Num_S_Remainder = Builder.CreateMul(Quotient, Den);
1101 
1102   // Remainder = Num - Num_S_Remainder
1103   Value *Remainder = Builder.CreateSub(Num, Num_S_Remainder);
1104 
1105   // Remainder_GE_Den = Remainder >= Den;
1106   Value *Remainder_GE_Den = Builder.CreateICmpUGE(Remainder, Den);
1107 
1108   // Remainder_GE_Zero = Num >= Num_S_Remainder
1109   Value *Remainder_GE_Zero = Builder.CreateICmpUGE(Num, Num_S_Remainder);
1110 
1111   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1112   Value *Tmp1 = Builder.CreateAnd(Remainder_GE_Den, Remainder_GE_Zero);
1113 
1114   Value *Res;
1115   if (IsDiv) {
1116     // Quotient_A_One = Quotient + 1
1117     Value *Quotient_A_One = Builder.CreateAdd(Quotient, One);
1118 
1119     // Quotient_S_One = Quotient - 1
1120     Value *Quotient_S_One = Builder.CreateSub(Quotient, One);
1121 
1122     // Div = (Tmp1 ? Quotient_A_One : Quotient)
1123     Value *Div = Builder.CreateSelect(Tmp1, Quotient_A_One, Quotient);
1124 
1125     // Div = (Remainder_GE_Zero ? Div : Quotient_S_One)
1126     Res = Builder.CreateSelect(Remainder_GE_Zero, Div, Quotient_S_One);
1127   } else {
1128     // Remainder_S_Den = Remainder - Den
1129     Value *Remainder_S_Den = Builder.CreateSub(Remainder, Den);
1130 
1131     // Remainder_A_Den = Remainder + Den
1132     Value *Remainder_A_Den = Builder.CreateAdd(Remainder, Den);
1133 
1134     // Rem = (Tmp1 ?  Remainder_S_Den : Remainder)
1135     Value *Rem = Builder.CreateSelect(Tmp1, Remainder_S_Den, Remainder);
1136 
1137     // Rem = (Remainder_GE_Zero ? Rem : Remainder_A_Den)
1138     Res = Builder.CreateSelect(Remainder_GE_Zero, Rem, Remainder_A_Den);
1139   }
1140 
1141   if (IsSigned) {
1142     Res = Builder.CreateXor(Res, Sign);
1143     Res = Builder.CreateSub(Res, Sign);
1144   }
1145 
1146   Res = Builder.CreateTrunc(Res, Ty);
1147 
1148   return Res;
1149 }
1150 
1151 Value *AMDGPUCodeGenPrepare::shrinkDivRem64(IRBuilder<> &Builder,
1152                                             BinaryOperator &I,
1153                                             Value *Num, Value *Den) const {
1154   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1155     return nullptr;  // Keep it for later optimization.
1156 
1157   Instruction::BinaryOps Opc = I.getOpcode();
1158 
1159   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1160   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1161 
1162   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1163   if (NumDivBits == -1)
1164     return nullptr;
1165 
1166   Value *Narrowed = nullptr;
1167   if (NumDivBits <= 24) {
1168     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1169                                   IsDiv, IsSigned);
1170   } else if (NumDivBits <= 32) {
1171     Narrowed = expandDivRem32(Builder, I, Num, Den);
1172   }
1173 
1174   if (Narrowed) {
1175     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1176                       Builder.CreateZExt(Narrowed, Num->getType());
1177   }
1178 
1179   return nullptr;
1180 }
1181 
1182 void AMDGPUCodeGenPrepare::expandDivRem64(BinaryOperator &I) const {
1183   Instruction::BinaryOps Opc = I.getOpcode();
1184   // Do the general expansion.
1185   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1186     expandDivisionUpTo64Bits(&I);
1187     return;
1188   }
1189 
1190   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1191     expandRemainderUpTo64Bits(&I);
1192     return;
1193   }
1194 
1195   llvm_unreachable("not a division");
1196 }
1197 
1198 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) {
1199   if (foldBinOpIntoSelect(I))
1200     return true;
1201 
1202   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1203       DA->isUniform(&I) && promoteUniformOpToI32(I))
1204     return true;
1205 
1206   if (UseMul24Intrin && replaceMulWithMul24(I))
1207     return true;
1208 
1209   bool Changed = false;
1210   Instruction::BinaryOps Opc = I.getOpcode();
1211   Type *Ty = I.getType();
1212   Value *NewDiv = nullptr;
1213   unsigned ScalarSize = Ty->getScalarSizeInBits();
1214 
1215   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1216 
1217   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1218        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1219       ScalarSize <= 64 &&
1220       !DisableIDivExpand) {
1221     Value *Num = I.getOperand(0);
1222     Value *Den = I.getOperand(1);
1223     IRBuilder<> Builder(&I);
1224     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1225 
1226     if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
1227       NewDiv = UndefValue::get(VT);
1228 
1229       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1230         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1231         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1232 
1233         Value *NewElt;
1234         if (ScalarSize <= 32) {
1235           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1236           if (!NewElt)
1237             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1238         } else {
1239           // See if this 64-bit division can be shrunk to 32/24-bits before
1240           // producing the general expansion.
1241           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1242           if (!NewElt) {
1243             // The general 64-bit expansion introduces control flow and doesn't
1244             // return the new value. Just insert a scalar copy and defer
1245             // expanding it.
1246             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1247             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1248           }
1249         }
1250 
1251         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1252       }
1253     } else {
1254       if (ScalarSize <= 32)
1255         NewDiv = expandDivRem32(Builder, I, Num, Den);
1256       else {
1257         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1258         if (!NewDiv)
1259           Div64ToExpand.push_back(&I);
1260       }
1261     }
1262 
1263     if (NewDiv) {
1264       I.replaceAllUsesWith(NewDiv);
1265       I.eraseFromParent();
1266       Changed = true;
1267     }
1268   }
1269 
1270   if (ExpandDiv64InIR) {
1271     // TODO: We get much worse code in specially handled constant cases.
1272     for (BinaryOperator *Div : Div64ToExpand) {
1273       expandDivRem64(*Div);
1274       Changed = true;
1275     }
1276   }
1277 
1278   return Changed;
1279 }
1280 
1281 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) {
1282   if (!WidenLoads)
1283     return false;
1284 
1285   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1286        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1287       canWidenScalarExtLoad(I)) {
1288     IRBuilder<> Builder(&I);
1289     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1290 
1291     Type *I32Ty = Builder.getInt32Ty();
1292     Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace());
1293     Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT);
1294     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast);
1295     WidenLoad->copyMetadata(I);
1296 
1297     // If we have range metadata, we need to convert the type, and not make
1298     // assumptions about the high bits.
1299     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1300       ConstantInt *Lower =
1301         mdconst::extract<ConstantInt>(Range->getOperand(0));
1302 
1303       if (Lower->getValue().isNullValue()) {
1304         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1305       } else {
1306         Metadata *LowAndHigh[] = {
1307           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1308           // Don't make assumptions about the high bits.
1309           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1310         };
1311 
1312         WidenLoad->setMetadata(LLVMContext::MD_range,
1313                                MDNode::get(Mod->getContext(), LowAndHigh));
1314       }
1315     }
1316 
1317     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
1318     Type *IntNTy = Builder.getIntNTy(TySize);
1319     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1320     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1321     I.replaceAllUsesWith(ValOrig);
1322     I.eraseFromParent();
1323     return true;
1324   }
1325 
1326   return false;
1327 }
1328 
1329 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) {
1330   bool Changed = false;
1331 
1332   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1333       DA->isUniform(&I))
1334     Changed |= promoteUniformOpToI32(I);
1335 
1336   return Changed;
1337 }
1338 
1339 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) {
1340   bool Changed = false;
1341 
1342   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1343       DA->isUniform(&I))
1344     Changed |= promoteUniformOpToI32(I);
1345 
1346   return Changed;
1347 }
1348 
1349 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) {
1350   switch (I.getIntrinsicID()) {
1351   case Intrinsic::bitreverse:
1352     return visitBitreverseIntrinsicInst(I);
1353   default:
1354     return false;
1355   }
1356 }
1357 
1358 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
1359   bool Changed = false;
1360 
1361   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1362       DA->isUniform(&I))
1363     Changed |= promoteUniformBitreverseToI32(I);
1364 
1365   return Changed;
1366 }
1367 
1368 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
1369   Mod = &M;
1370   DL = &Mod->getDataLayout();
1371   return false;
1372 }
1373 
1374 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
1375   if (skipFunction(F))
1376     return false;
1377 
1378   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1379   if (!TPC)
1380     return false;
1381 
1382   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
1383   ST = &TM.getSubtarget<GCNSubtarget>(F);
1384   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1385   DA = &getAnalysis<LegacyDivergenceAnalysis>();
1386 
1387   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1388   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1389 
1390   HasUnsafeFPMath = hasUnsafeFPMath(F);
1391 
1392   AMDGPU::SIModeRegisterDefaults Mode(F);
1393   HasFP32Denormals = Mode.allFP32Denormals();
1394 
1395   bool MadeChange = false;
1396 
1397   Function::iterator NextBB;
1398   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
1399     BasicBlock *BB = &*FI;
1400     NextBB = std::next(FI);
1401 
1402     BasicBlock::iterator Next;
1403     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; I = Next) {
1404       Next = std::next(I);
1405 
1406       MadeChange |= visit(*I);
1407 
1408       if (Next != E) { // Control flow changed
1409         BasicBlock *NextInstBB = Next->getParent();
1410         if (NextInstBB != BB) {
1411           BB = NextInstBB;
1412           E = BB->end();
1413           FE = F.end();
1414         }
1415       }
1416     }
1417   }
1418 
1419   return MadeChange;
1420 }
1421 
1422 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
1423                       "AMDGPU IR optimizations", false, false)
1424 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1425 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
1426 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
1427                     false, false)
1428 
1429 char AMDGPUCodeGenPrepare::ID = 0;
1430 
1431 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
1432   return new AMDGPUCodeGenPrepare();
1433 }
1434