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