1 //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This pass does misc. AMDGPU optimizations on IR before instruction
11 /// selection.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/TargetPassConfig.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/InstVisitor.h"
24 #include "llvm/IR/IntrinsicsAMDGPU.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/KnownBits.h"
29 #include "llvm/Transforms/Utils/IntegerDivision.h"
30 
31 #define DEBUG_TYPE "amdgpu-codegenprepare"
32 
33 using namespace llvm;
34 
35 namespace {
36 
37 static cl::opt<bool> WidenLoads(
38   "amdgpu-codegenprepare-widen-constant-loads",
39   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
40   cl::ReallyHidden,
41   cl::init(false));
42 
43 static cl::opt<bool> Widen16BitOps(
44   "amdgpu-codegenprepare-widen-16-bit-ops",
45   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
46   cl::ReallyHidden,
47   cl::init(true));
48 
49 static cl::opt<bool> UseMul24Intrin(
50   "amdgpu-codegenprepare-mul24",
51   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
52   cl::ReallyHidden,
53   cl::init(true));
54 
55 // Legalize 64-bit division by using the generic IR expansion.
56 static cl::opt<bool> ExpandDiv64InIR(
57   "amdgpu-codegenprepare-expand-div64",
58   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
59   cl::ReallyHidden,
60   cl::init(false));
61 
62 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
63 // and is used for testing the legalizer.
64 static cl::opt<bool> DisableIDivExpand(
65   "amdgpu-codegenprepare-disable-idiv-expansion",
66   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
67   cl::ReallyHidden,
68   cl::init(false));
69 
70 class AMDGPUCodeGenPrepare : public FunctionPass,
71                              public InstVisitor<AMDGPUCodeGenPrepare, bool> {
72   const GCNSubtarget *ST = nullptr;
73   AssumptionCache *AC = nullptr;
74   DominatorTree *DT = nullptr;
75   LegacyDivergenceAnalysis *DA = nullptr;
76   Module *Mod = nullptr;
77   const DataLayout *DL = nullptr;
78   bool HasUnsafeFPMath = false;
79   bool HasFP32Denormals = false;
80 
81   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
82   /// binary operation \p V.
83   ///
84   /// \returns Binary operation \p V.
85   /// \returns \p T's base element bit width.
86   unsigned getBaseElementBitWidth(const Type *T) const;
87 
88   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
89   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
90   /// is returned.
91   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
92 
93   /// \returns True if binary operation \p I is a signed binary operation, false
94   /// otherwise.
95   bool isSigned(const BinaryOperator &I) const;
96 
97   /// \returns True if the condition of 'select' operation \p I comes from a
98   /// signed 'icmp' operation, false otherwise.
99   bool isSigned(const SelectInst &I) const;
100 
101   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
102   /// false otherwise.
103   bool needsPromotionToI32(const Type *T) const;
104 
105   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
106   /// operation.
107   ///
108   /// \details \p I's base element bit width must be greater than 1 and less
109   /// than or equal 16. Promotion is done by sign or zero extending operands to
110   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
111   /// truncating the result of 32 bit binary operation back to \p I's original
112   /// type. Division operation is not promoted.
113   ///
114   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
115   /// false otherwise.
116   bool promoteUniformOpToI32(BinaryOperator &I) const;
117 
118   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
119   ///
120   /// \details \p I's base element bit width must be greater than 1 and less
121   /// than or equal 16. Promotion is done by sign or zero extending operands to
122   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
123   ///
124   /// \returns True.
125   bool promoteUniformOpToI32(ICmpInst &I) const;
126 
127   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
128   /// operation.
129   ///
130   /// \details \p I's base element bit width must be greater than 1 and less
131   /// than or equal 16. Promotion is done by sign or zero extending operands to
132   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
133   /// result of 32 bit 'select' operation back to \p I's original type.
134   ///
135   /// \returns True.
136   bool promoteUniformOpToI32(SelectInst &I) const;
137 
138   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
139   /// intrinsic.
140   ///
141   /// \details \p I's base element bit width must be greater than 1 and less
142   /// than or equal 16. Promotion is done by zero extending the operand to 32
143   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
144   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
145   /// shift amount is 32 minus \p I's base element bit width), and truncating
146   /// the result of the shift operation back to \p I's original type.
147   ///
148   /// \returns True.
149   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
150 
151 
152   unsigned numBitsUnsigned(Value *Op, unsigned ScalarSize) const;
153   unsigned numBitsSigned(Value *Op, unsigned ScalarSize) const;
154   bool isI24(Value *V, unsigned ScalarSize) const;
155   bool isU24(Value *V, unsigned ScalarSize) const;
156 
157   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
158   /// SelectionDAG has an issue where an and asserting the bits are known
159   bool replaceMulWithMul24(BinaryOperator &I) const;
160 
161   /// Perform same function as equivalently named function in DAGCombiner. Since
162   /// we expand some divisions here, we need to perform this before obscuring.
163   bool foldBinOpIntoSelect(BinaryOperator &I) const;
164 
165   bool divHasSpecialOptimization(BinaryOperator &I,
166                                  Value *Num, Value *Den) const;
167   int getDivNumBits(BinaryOperator &I,
168                     Value *Num, Value *Den,
169                     unsigned AtLeast, bool Signed) const;
170 
171   /// Expands 24 bit div or rem.
172   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
173                         Value *Num, Value *Den,
174                         bool IsDiv, bool IsSigned) const;
175 
176   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
177                             Value *Num, Value *Den, unsigned NumBits,
178                             bool IsDiv, bool IsSigned) const;
179 
180   /// Expands 32 bit div or rem.
181   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
182                         Value *Num, Value *Den) const;
183 
184   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
185                         Value *Num, Value *Den) const;
186   void expandDivRem64(BinaryOperator &I) const;
187 
188   /// Widen a scalar load.
189   ///
190   /// \details \p Widen scalar load for uniform, small type loads from constant
191   //  memory / to a full 32-bits and then truncate the input to allow a scalar
192   //  load instead of a vector load.
193   //
194   /// \returns True.
195 
196   bool canWidenScalarExtLoad(LoadInst &I) const;
197 
198 public:
199   static char ID;
200 
201   AMDGPUCodeGenPrepare() : FunctionPass(ID) {}
202 
203   bool visitFDiv(BinaryOperator &I);
204   bool visitXor(BinaryOperator &I);
205 
206   bool visitInstruction(Instruction &I) { return false; }
207   bool visitBinaryOperator(BinaryOperator &I);
208   bool visitLoadInst(LoadInst &I);
209   bool visitICmpInst(ICmpInst &I);
210   bool visitSelectInst(SelectInst &I);
211 
212   bool visitIntrinsicInst(IntrinsicInst &I);
213   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
214 
215   bool doInitialization(Module &M) override;
216   bool runOnFunction(Function &F) override;
217 
218   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
219 
220   void getAnalysisUsage(AnalysisUsage &AU) const override {
221     AU.addRequired<AssumptionCacheTracker>();
222     AU.addRequired<LegacyDivergenceAnalysis>();
223 
224     // FIXME: Division expansion needs to preserve the dominator tree.
225     if (!ExpandDiv64InIR)
226       AU.setPreservesAll();
227  }
228 };
229 
230 } // end anonymous namespace
231 
232 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(const Type *T) const {
233   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
234 
235   if (T->isIntegerTy())
236     return T->getIntegerBitWidth();
237   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
238 }
239 
240 Type *AMDGPUCodeGenPrepare::getI32Ty(IRBuilder<> &B, const Type *T) const {
241   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
242 
243   if (T->isIntegerTy())
244     return B.getInt32Ty();
245   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
246 }
247 
248 bool AMDGPUCodeGenPrepare::isSigned(const BinaryOperator &I) const {
249   return I.getOpcode() == Instruction::AShr ||
250       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
251 }
252 
253 bool AMDGPUCodeGenPrepare::isSigned(const SelectInst &I) const {
254   return isa<ICmpInst>(I.getOperand(0)) ?
255       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
256 }
257 
258 bool AMDGPUCodeGenPrepare::needsPromotionToI32(const Type *T) const {
259   if (!Widen16BitOps)
260     return false;
261 
262   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
263   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
264     return true;
265 
266   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
267     // TODO: The set of packed operations is more limited, so may want to
268     // promote some anyway.
269     if (ST->hasVOP3PInsts())
270       return false;
271 
272     return needsPromotionToI32(VT->getElementType());
273   }
274 
275   return false;
276 }
277 
278 // Return true if the op promoted to i32 should have nsw set.
279 static bool promotedOpIsNSW(const Instruction &I) {
280   switch (I.getOpcode()) {
281   case Instruction::Shl:
282   case Instruction::Add:
283   case Instruction::Sub:
284     return true;
285   case Instruction::Mul:
286     return I.hasNoUnsignedWrap();
287   default:
288     return false;
289   }
290 }
291 
292 // Return true if the op promoted to i32 should have nuw set.
293 static bool promotedOpIsNUW(const Instruction &I) {
294   switch (I.getOpcode()) {
295   case Instruction::Shl:
296   case Instruction::Add:
297   case Instruction::Mul:
298     return true;
299   case Instruction::Sub:
300     return I.hasNoUnsignedWrap();
301   default:
302     return false;
303   }
304 }
305 
306 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(LoadInst &I) const {
307   Type *Ty = I.getType();
308   const DataLayout &DL = Mod->getDataLayout();
309   int TySize = DL.getTypeSizeInBits(Ty);
310   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
311 
312   return I.isSimple() && TySize < 32 && Alignment >= 4 && DA->isUniform(&I);
313 }
314 
315 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(BinaryOperator &I) const {
316   assert(needsPromotionToI32(I.getType()) &&
317          "I does not need promotion to i32");
318 
319   if (I.getOpcode() == Instruction::SDiv ||
320       I.getOpcode() == Instruction::UDiv ||
321       I.getOpcode() == Instruction::SRem ||
322       I.getOpcode() == Instruction::URem)
323     return false;
324 
325   IRBuilder<> Builder(&I);
326   Builder.SetCurrentDebugLocation(I.getDebugLoc());
327 
328   Type *I32Ty = getI32Ty(Builder, I.getType());
329   Value *ExtOp0 = nullptr;
330   Value *ExtOp1 = nullptr;
331   Value *ExtRes = nullptr;
332   Value *TruncRes = nullptr;
333 
334   if (isSigned(I)) {
335     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
336     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
337   } else {
338     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
339     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
340   }
341 
342   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
343   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
344     if (promotedOpIsNSW(cast<Instruction>(I)))
345       Inst->setHasNoSignedWrap();
346 
347     if (promotedOpIsNUW(cast<Instruction>(I)))
348       Inst->setHasNoUnsignedWrap();
349 
350     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
351       Inst->setIsExact(ExactOp->isExact());
352   }
353 
354   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
355 
356   I.replaceAllUsesWith(TruncRes);
357   I.eraseFromParent();
358 
359   return true;
360 }
361 
362 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(ICmpInst &I) const {
363   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
364          "I does not need promotion to i32");
365 
366   IRBuilder<> Builder(&I);
367   Builder.SetCurrentDebugLocation(I.getDebugLoc());
368 
369   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
370   Value *ExtOp0 = nullptr;
371   Value *ExtOp1 = nullptr;
372   Value *NewICmp  = nullptr;
373 
374   if (I.isSigned()) {
375     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
376     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
377   } else {
378     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
379     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
380   }
381   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
382 
383   I.replaceAllUsesWith(NewICmp);
384   I.eraseFromParent();
385 
386   return true;
387 }
388 
389 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(SelectInst &I) const {
390   assert(needsPromotionToI32(I.getType()) &&
391          "I does not need promotion to i32");
392 
393   IRBuilder<> Builder(&I);
394   Builder.SetCurrentDebugLocation(I.getDebugLoc());
395 
396   Type *I32Ty = getI32Ty(Builder, I.getType());
397   Value *ExtOp1 = nullptr;
398   Value *ExtOp2 = nullptr;
399   Value *ExtRes = nullptr;
400   Value *TruncRes = nullptr;
401 
402   if (isSigned(I)) {
403     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
404     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
405   } else {
406     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
407     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
408   }
409   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
410   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
411 
412   I.replaceAllUsesWith(TruncRes);
413   I.eraseFromParent();
414 
415   return true;
416 }
417 
418 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32(
419     IntrinsicInst &I) const {
420   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
421          "I must be bitreverse intrinsic");
422   assert(needsPromotionToI32(I.getType()) &&
423          "I does not need promotion to i32");
424 
425   IRBuilder<> Builder(&I);
426   Builder.SetCurrentDebugLocation(I.getDebugLoc());
427 
428   Type *I32Ty = getI32Ty(Builder, I.getType());
429   Function *I32 =
430       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
431   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
432   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
433   Value *LShrOp =
434       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
435   Value *TruncRes =
436       Builder.CreateTrunc(LShrOp, I.getType());
437 
438   I.replaceAllUsesWith(TruncRes);
439   I.eraseFromParent();
440 
441   return true;
442 }
443 
444 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(Value *Op,
445                                                unsigned ScalarSize) const {
446   KnownBits Known = computeKnownBits(Op, *DL, 0, AC);
447   return ScalarSize - Known.countMinLeadingZeros();
448 }
449 
450 unsigned AMDGPUCodeGenPrepare::numBitsSigned(Value *Op,
451                                              unsigned ScalarSize) const {
452   // In order for this to be a signed 24-bit value, bit 23, must
453   // be a sign bit.
454   return ScalarSize - ComputeNumSignBits(Op, *DL, 0, AC);
455 }
456 
457 bool AMDGPUCodeGenPrepare::isI24(Value *V, unsigned ScalarSize) const {
458   return ScalarSize >= 24 && // Types less than 24-bit should be treated
459                                      // as unsigned 24-bit values.
460     numBitsSigned(V, ScalarSize) < 24;
461 }
462 
463 bool AMDGPUCodeGenPrepare::isU24(Value *V, unsigned ScalarSize) const {
464   return numBitsUnsigned(V, ScalarSize) <= 24;
465 }
466 
467 static void extractValues(IRBuilder<> &Builder,
468                           SmallVectorImpl<Value *> &Values, Value *V) {
469   auto *VT = dyn_cast<FixedVectorType>(V->getType());
470   if (!VT) {
471     Values.push_back(V);
472     return;
473   }
474 
475   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
476     Values.push_back(Builder.CreateExtractElement(V, I));
477 }
478 
479 static Value *insertValues(IRBuilder<> &Builder,
480                            Type *Ty,
481                            SmallVectorImpl<Value *> &Values) {
482   if (Values.size() == 1)
483     return Values[0];
484 
485   Value *NewVal = UndefValue::get(Ty);
486   for (int I = 0, E = Values.size(); I != E; ++I)
487     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
488 
489   return NewVal;
490 }
491 
492 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(BinaryOperator &I) const {
493   if (I.getOpcode() != Instruction::Mul)
494     return false;
495 
496   Type *Ty = I.getType();
497   unsigned Size = Ty->getScalarSizeInBits();
498   if (Size <= 16 && ST->has16BitInsts())
499     return false;
500 
501   // Prefer scalar if this could be s_mul_i32
502   if (DA->isUniform(&I))
503     return false;
504 
505   Value *LHS = I.getOperand(0);
506   Value *RHS = I.getOperand(1);
507   IRBuilder<> Builder(&I);
508   Builder.SetCurrentDebugLocation(I.getDebugLoc());
509 
510   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
511 
512   // TODO: Should this try to match mulhi24?
513   if (ST->hasMulU24() && isU24(LHS, Size) && isU24(RHS, Size)) {
514     // The 24-bit mul intrinsics yields the low-order 32 bits. The result's bit
515     // width should not exceed 32 if `Size` > 32.
516     if (Size > 32 &&
517         numBitsUnsigned(LHS, Size) + numBitsUnsigned(RHS, Size) > 32) {
518       return false;
519     }
520 
521     IntrID = Intrinsic::amdgcn_mul_u24;
522   } else if (ST->hasMulI24() && isI24(LHS, Size) && isI24(RHS, Size)) {
523     if (Size > 32 && numBitsSigned(LHS, Size) + numBitsSigned(RHS, Size) > 31) {
524       return false;
525     }
526 
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   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
756   // expansion around them in codegen.
757   if (Ty->isDoubleTy())
758     return false;
759 
760   // No intrinsic for fdiv16 if target does not support f16.
761   if (Ty->isHalfTy() && !ST->has16BitInsts())
762     return false;
763 
764   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
765   const float ReqdAccuracy =  FPOp->getFPAccuracy();
766 
767   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
768   FastMathFlags FMF = FPOp->getFastMathFlags();
769   const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc();
770 
771   // rcp_f16 is accurate for !fpmath >= 1.0ulp.
772   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
773   // rcp_f64 is never accurate.
774   const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) ||
775             (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f);
776 
777   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
778   Builder.setFastMathFlags(FMF);
779   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
780 
781   Value *Num = FDiv.getOperand(0);
782   Value *Den = FDiv.getOperand(1);
783 
784   Value *NewFDiv = nullptr;
785   if (auto *VT = dyn_cast<FixedVectorType>(FDiv.getType())) {
786     NewFDiv = UndefValue::get(VT);
787 
788     // FIXME: Doesn't do the right thing for cases where the vector is partially
789     // constant. This works when the scalarizer pass is run first.
790     for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) {
791       Value *NumEltI = Builder.CreateExtractElement(Num, I);
792       Value *DenEltI = Builder.CreateExtractElement(Den, I);
793       // Try rcp first.
794       Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp,
795                                       RcpIsAccurate, Builder, Mod);
796       if (!NewElt) // Try fdiv.fast.
797         NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy,
798                                       HasFP32Denormals, Builder, Mod);
799       if (!NewElt) // Keep the original.
800         NewElt = Builder.CreateFDiv(NumEltI, DenEltI);
801 
802       NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I);
803     }
804   } else { // Scalar FDiv.
805     // Try rcp first.
806     NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate,
807                               Builder, Mod);
808     if (!NewFDiv) { // Try fdiv.fast.
809       NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals,
810                                      Builder, Mod);
811     }
812   }
813 
814   if (NewFDiv) {
815     FDiv.replaceAllUsesWith(NewFDiv);
816     NewFDiv->takeName(&FDiv);
817     FDiv.eraseFromParent();
818   }
819 
820   return !!NewFDiv;
821 }
822 
823 bool AMDGPUCodeGenPrepare::visitXor(BinaryOperator &I) {
824   // Match the Xor instruction, its type and its operands
825   IntrinsicInst *IntrinsicCall = dyn_cast<IntrinsicInst>(I.getOperand(0));
826   ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1));
827   if (!RHS || !IntrinsicCall || RHS->getSExtValue() != -1)
828     return visitBinaryOperator(I);
829 
830   // Check if the Call is an intrinsic instruction to amdgcn_class intrinsic
831   // has only one use
832   if (IntrinsicCall->getIntrinsicID() != Intrinsic::amdgcn_class ||
833       !IntrinsicCall->hasOneUse())
834     return visitBinaryOperator(I);
835 
836   // "Not" the second argument of the intrinsic call
837   ConstantInt *Arg = dyn_cast<ConstantInt>(IntrinsicCall->getOperand(1));
838   if (!Arg)
839     return visitBinaryOperator(I);
840 
841   IntrinsicCall->setOperand(
842       1, ConstantInt::get(Arg->getType(), Arg->getZExtValue() ^ 0x3ff));
843   I.replaceAllUsesWith(IntrinsicCall);
844   I.eraseFromParent();
845   return true;
846 }
847 
848 static bool hasUnsafeFPMath(const Function &F) {
849   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
850   return Attr.getValueAsBool();
851 }
852 
853 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
854                                           Value *LHS, Value *RHS) {
855   Type *I32Ty = Builder.getInt32Ty();
856   Type *I64Ty = Builder.getInt64Ty();
857 
858   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
859   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
860   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
861   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
862   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
863   Hi = Builder.CreateTrunc(Hi, I32Ty);
864   return std::make_pair(Lo, Hi);
865 }
866 
867 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
868   return getMul64(Builder, LHS, RHS).second;
869 }
870 
871 /// Figure out how many bits are really needed for this ddivision. \p AtLeast is
872 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
873 /// first one is insufficient. Returns -1 on failure.
874 int AMDGPUCodeGenPrepare::getDivNumBits(BinaryOperator &I,
875                                         Value *Num, Value *Den,
876                                         unsigned AtLeast, bool IsSigned) const {
877   const DataLayout &DL = Mod->getDataLayout();
878   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
879   if (LHSSignBits < AtLeast)
880     return -1;
881 
882   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
883   if (RHSSignBits < AtLeast)
884     return -1;
885 
886   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
887   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
888   if (IsSigned)
889     ++DivBits;
890   return DivBits;
891 }
892 
893 // The fractional part of a float is enough to accurately represent up to
894 // a 24-bit signed integer.
895 Value *AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder,
896                                             BinaryOperator &I,
897                                             Value *Num, Value *Den,
898                                             bool IsDiv, bool IsSigned) const {
899   int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
900   if (DivBits == -1)
901     return nullptr;
902   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
903 }
904 
905 Value *AMDGPUCodeGenPrepare::expandDivRem24Impl(IRBuilder<> &Builder,
906                                                 BinaryOperator &I,
907                                                 Value *Num, Value *Den,
908                                                 unsigned DivBits,
909                                                 bool IsDiv, bool IsSigned) const {
910   Type *I32Ty = Builder.getInt32Ty();
911   Num = Builder.CreateTrunc(Num, I32Ty);
912   Den = Builder.CreateTrunc(Den, I32Ty);
913 
914   Type *F32Ty = Builder.getFloatTy();
915   ConstantInt *One = Builder.getInt32(1);
916   Value *JQ = One;
917 
918   if (IsSigned) {
919     // char|short jq = ia ^ ib;
920     JQ = Builder.CreateXor(Num, Den);
921 
922     // jq = jq >> (bitsize - 2)
923     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
924 
925     // jq = jq | 0x1
926     JQ = Builder.CreateOr(JQ, One);
927   }
928 
929   // int ia = (int)LHS;
930   Value *IA = Num;
931 
932   // int ib, (int)RHS;
933   Value *IB = Den;
934 
935   // float fa = (float)ia;
936   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
937                        : Builder.CreateUIToFP(IA, F32Ty);
938 
939   // float fb = (float)ib;
940   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
941                        : Builder.CreateUIToFP(IB,F32Ty);
942 
943   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
944                                                 Builder.getFloatTy());
945   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
946   Value *FQM = Builder.CreateFMul(FA, RCP);
947 
948   // fq = trunc(fqm);
949   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
950   FQ->copyFastMathFlags(Builder.getFastMathFlags());
951 
952   // float fqneg = -fq;
953   Value *FQNeg = Builder.CreateFNeg(FQ);
954 
955   // float fr = mad(fqneg, fb, fa);
956   auto FMAD = !ST->hasMadMacF32Insts()
957                   ? Intrinsic::fma
958                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
959   Value *FR = Builder.CreateIntrinsic(FMAD,
960                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
961 
962   // int iq = (int)fq;
963   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
964                        : Builder.CreateFPToUI(FQ, I32Ty);
965 
966   // fr = fabs(fr);
967   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
968 
969   // fb = fabs(fb);
970   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
971 
972   // int cv = fr >= fb;
973   Value *CV = Builder.CreateFCmpOGE(FR, FB);
974 
975   // jq = (cv ? jq : 0);
976   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
977 
978   // dst = iq + jq;
979   Value *Div = Builder.CreateAdd(IQ, JQ);
980 
981   Value *Res = Div;
982   if (!IsDiv) {
983     // Rem needs compensation, it's easier to recompute it
984     Value *Rem = Builder.CreateMul(Div, Den);
985     Res = Builder.CreateSub(Num, Rem);
986   }
987 
988   if (DivBits != 0 && DivBits < 32) {
989     // Extend in register from the number of bits this divide really is.
990     if (IsSigned) {
991       int InRegBits = 32 - DivBits;
992 
993       Res = Builder.CreateShl(Res, InRegBits);
994       Res = Builder.CreateAShr(Res, InRegBits);
995     } else {
996       ConstantInt *TruncMask
997         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
998       Res = Builder.CreateAnd(Res, TruncMask);
999     }
1000   }
1001 
1002   return Res;
1003 }
1004 
1005 // Try to recognize special cases the DAG will emit special, better expansions
1006 // than the general expansion we do here.
1007 
1008 // TODO: It would be better to just directly handle those optimizations here.
1009 bool AMDGPUCodeGenPrepare::divHasSpecialOptimization(
1010   BinaryOperator &I, Value *Num, Value *Den) const {
1011   if (Constant *C = dyn_cast<Constant>(Den)) {
1012     // Arbitrary constants get a better expansion as long as a wider mulhi is
1013     // legal.
1014     if (C->getType()->getScalarSizeInBits() <= 32)
1015       return true;
1016 
1017     // TODO: Sdiv check for not exact for some reason.
1018 
1019     // If there's no wider mulhi, there's only a better expansion for powers of
1020     // two.
1021     // TODO: Should really know for each vector element.
1022     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
1023       return true;
1024 
1025     return false;
1026   }
1027 
1028   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1029     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1030     if (BinOpDen->getOpcode() == Instruction::Shl &&
1031         isa<Constant>(BinOpDen->getOperand(0)) &&
1032         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
1033                                0, AC, &I, DT)) {
1034       return true;
1035     }
1036   }
1037 
1038   return false;
1039 }
1040 
1041 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
1042   // Check whether the sign can be determined statically.
1043   KnownBits Known = computeKnownBits(V, *DL);
1044   if (Known.isNegative())
1045     return Constant::getAllOnesValue(V->getType());
1046   if (Known.isNonNegative())
1047     return Constant::getNullValue(V->getType());
1048   return Builder.CreateAShr(V, Builder.getInt32(31));
1049 }
1050 
1051 Value *AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder,
1052                                             BinaryOperator &I, Value *X,
1053                                             Value *Y) const {
1054   Instruction::BinaryOps Opc = I.getOpcode();
1055   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1056          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1057 
1058   FastMathFlags FMF;
1059   FMF.setFast();
1060   Builder.setFastMathFlags(FMF);
1061 
1062   if (divHasSpecialOptimization(I, X, Y))
1063     return nullptr;  // Keep it for later optimization.
1064 
1065   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1066   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1067 
1068   Type *Ty = X->getType();
1069   Type *I32Ty = Builder.getInt32Ty();
1070   Type *F32Ty = Builder.getFloatTy();
1071 
1072   if (Ty->getScalarSizeInBits() < 32) {
1073     if (IsSigned) {
1074       X = Builder.CreateSExt(X, I32Ty);
1075       Y = Builder.CreateSExt(Y, I32Ty);
1076     } else {
1077       X = Builder.CreateZExt(X, I32Ty);
1078       Y = Builder.CreateZExt(Y, I32Ty);
1079     }
1080   }
1081 
1082   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
1083     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1084                       Builder.CreateZExtOrTrunc(Res, Ty);
1085   }
1086 
1087   ConstantInt *Zero = Builder.getInt32(0);
1088   ConstantInt *One = Builder.getInt32(1);
1089 
1090   Value *Sign = nullptr;
1091   if (IsSigned) {
1092     Value *SignX = getSign32(X, Builder, DL);
1093     Value *SignY = getSign32(Y, Builder, DL);
1094     // Remainder sign is the same as LHS
1095     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1096 
1097     X = Builder.CreateAdd(X, SignX);
1098     Y = Builder.CreateAdd(Y, SignY);
1099 
1100     X = Builder.CreateXor(X, SignX);
1101     Y = Builder.CreateXor(Y, SignY);
1102   }
1103 
1104   // The algorithm here is based on ideas from "Software Integer Division", Tom
1105   // Rodeheffer, August 2008.
1106   //
1107   // unsigned udiv(unsigned x, unsigned y) {
1108   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1109   //   // that this is a lower bound on inv(y), even if some of the calculations
1110   //   // round up.
1111   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1112   //
1113   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1114   //   // Empirically this is guaranteed to give a "two-y" lower bound on
1115   //   // inv(y).
1116   //   z += umulh(z, -y * z);
1117   //
1118   //   // Quotient/remainder estimate.
1119   //   unsigned q = umulh(x, z);
1120   //   unsigned r = x - q * y;
1121   //
1122   //   // Two rounds of quotient/remainder refinement.
1123   //   if (r >= y) {
1124   //     ++q;
1125   //     r -= y;
1126   //   }
1127   //   if (r >= y) {
1128   //     ++q;
1129   //     r -= y;
1130   //   }
1131   //
1132   //   return q;
1133   // }
1134 
1135   // Initial estimate of inv(y).
1136   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1137   Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
1138   Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
1139   Constant *Scale = ConstantFP::get(F32Ty, BitsToFloat(0x4F7FFFFE));
1140   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1141   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1142 
1143   // One round of UNR.
1144   Value *NegY = Builder.CreateSub(Zero, Y);
1145   Value *NegYZ = Builder.CreateMul(NegY, Z);
1146   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1147 
1148   // Quotient/remainder estimate.
1149   Value *Q = getMulHu(Builder, X, Z);
1150   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1151 
1152   // First quotient/remainder refinement.
1153   Value *Cond = Builder.CreateICmpUGE(R, Y);
1154   if (IsDiv)
1155     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1156   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1157 
1158   // Second quotient/remainder refinement.
1159   Cond = Builder.CreateICmpUGE(R, Y);
1160   Value *Res;
1161   if (IsDiv)
1162     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1163   else
1164     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1165 
1166   if (IsSigned) {
1167     Res = Builder.CreateXor(Res, Sign);
1168     Res = Builder.CreateSub(Res, Sign);
1169   }
1170 
1171   Res = Builder.CreateTrunc(Res, Ty);
1172 
1173   return Res;
1174 }
1175 
1176 Value *AMDGPUCodeGenPrepare::shrinkDivRem64(IRBuilder<> &Builder,
1177                                             BinaryOperator &I,
1178                                             Value *Num, Value *Den) const {
1179   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1180     return nullptr;  // Keep it for later optimization.
1181 
1182   Instruction::BinaryOps Opc = I.getOpcode();
1183 
1184   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1185   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1186 
1187   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1188   if (NumDivBits == -1)
1189     return nullptr;
1190 
1191   Value *Narrowed = nullptr;
1192   if (NumDivBits <= 24) {
1193     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1194                                   IsDiv, IsSigned);
1195   } else if (NumDivBits <= 32) {
1196     Narrowed = expandDivRem32(Builder, I, Num, Den);
1197   }
1198 
1199   if (Narrowed) {
1200     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1201                       Builder.CreateZExt(Narrowed, Num->getType());
1202   }
1203 
1204   return nullptr;
1205 }
1206 
1207 void AMDGPUCodeGenPrepare::expandDivRem64(BinaryOperator &I) const {
1208   Instruction::BinaryOps Opc = I.getOpcode();
1209   // Do the general expansion.
1210   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1211     expandDivisionUpTo64Bits(&I);
1212     return;
1213   }
1214 
1215   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1216     expandRemainderUpTo64Bits(&I);
1217     return;
1218   }
1219 
1220   llvm_unreachable("not a division");
1221 }
1222 
1223 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) {
1224   if (foldBinOpIntoSelect(I))
1225     return true;
1226 
1227   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1228       DA->isUniform(&I) && promoteUniformOpToI32(I))
1229     return true;
1230 
1231   if (UseMul24Intrin && replaceMulWithMul24(I))
1232     return true;
1233 
1234   bool Changed = false;
1235   Instruction::BinaryOps Opc = I.getOpcode();
1236   Type *Ty = I.getType();
1237   Value *NewDiv = nullptr;
1238   unsigned ScalarSize = Ty->getScalarSizeInBits();
1239 
1240   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1241 
1242   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1243        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1244       ScalarSize <= 64 &&
1245       !DisableIDivExpand) {
1246     Value *Num = I.getOperand(0);
1247     Value *Den = I.getOperand(1);
1248     IRBuilder<> Builder(&I);
1249     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1250 
1251     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1252       NewDiv = UndefValue::get(VT);
1253 
1254       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1255         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1256         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1257 
1258         Value *NewElt;
1259         if (ScalarSize <= 32) {
1260           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1261           if (!NewElt)
1262             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1263         } else {
1264           // See if this 64-bit division can be shrunk to 32/24-bits before
1265           // producing the general expansion.
1266           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1267           if (!NewElt) {
1268             // The general 64-bit expansion introduces control flow and doesn't
1269             // return the new value. Just insert a scalar copy and defer
1270             // expanding it.
1271             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1272             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1273           }
1274         }
1275 
1276         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1277       }
1278     } else {
1279       if (ScalarSize <= 32)
1280         NewDiv = expandDivRem32(Builder, I, Num, Den);
1281       else {
1282         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1283         if (!NewDiv)
1284           Div64ToExpand.push_back(&I);
1285       }
1286     }
1287 
1288     if (NewDiv) {
1289       I.replaceAllUsesWith(NewDiv);
1290       I.eraseFromParent();
1291       Changed = true;
1292     }
1293   }
1294 
1295   if (ExpandDiv64InIR) {
1296     // TODO: We get much worse code in specially handled constant cases.
1297     for (BinaryOperator *Div : Div64ToExpand) {
1298       expandDivRem64(*Div);
1299       Changed = true;
1300     }
1301   }
1302 
1303   return Changed;
1304 }
1305 
1306 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) {
1307   if (!WidenLoads)
1308     return false;
1309 
1310   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1311        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1312       canWidenScalarExtLoad(I)) {
1313     IRBuilder<> Builder(&I);
1314     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1315 
1316     Type *I32Ty = Builder.getInt32Ty();
1317     Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace());
1318     Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT);
1319     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast);
1320     WidenLoad->copyMetadata(I);
1321 
1322     // If we have range metadata, we need to convert the type, and not make
1323     // assumptions about the high bits.
1324     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1325       ConstantInt *Lower =
1326         mdconst::extract<ConstantInt>(Range->getOperand(0));
1327 
1328       if (Lower->isNullValue()) {
1329         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1330       } else {
1331         Metadata *LowAndHigh[] = {
1332           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1333           // Don't make assumptions about the high bits.
1334           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1335         };
1336 
1337         WidenLoad->setMetadata(LLVMContext::MD_range,
1338                                MDNode::get(Mod->getContext(), LowAndHigh));
1339       }
1340     }
1341 
1342     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
1343     Type *IntNTy = Builder.getIntNTy(TySize);
1344     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1345     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1346     I.replaceAllUsesWith(ValOrig);
1347     I.eraseFromParent();
1348     return true;
1349   }
1350 
1351   return false;
1352 }
1353 
1354 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) {
1355   bool Changed = false;
1356 
1357   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1358       DA->isUniform(&I))
1359     Changed |= promoteUniformOpToI32(I);
1360 
1361   return Changed;
1362 }
1363 
1364 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) {
1365   bool Changed = false;
1366 
1367   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1368       DA->isUniform(&I))
1369     Changed |= promoteUniformOpToI32(I);
1370 
1371   return Changed;
1372 }
1373 
1374 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) {
1375   switch (I.getIntrinsicID()) {
1376   case Intrinsic::bitreverse:
1377     return visitBitreverseIntrinsicInst(I);
1378   default:
1379     return false;
1380   }
1381 }
1382 
1383 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
1384   bool Changed = false;
1385 
1386   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1387       DA->isUniform(&I))
1388     Changed |= promoteUniformBitreverseToI32(I);
1389 
1390   return Changed;
1391 }
1392 
1393 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
1394   Mod = &M;
1395   DL = &Mod->getDataLayout();
1396   return false;
1397 }
1398 
1399 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
1400   if (skipFunction(F))
1401     return false;
1402 
1403   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1404   if (!TPC)
1405     return false;
1406 
1407   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
1408   ST = &TM.getSubtarget<GCNSubtarget>(F);
1409   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1410   DA = &getAnalysis<LegacyDivergenceAnalysis>();
1411 
1412   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1413   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1414 
1415   HasUnsafeFPMath = hasUnsafeFPMath(F);
1416 
1417   AMDGPU::SIModeRegisterDefaults Mode(F);
1418   HasFP32Denormals = Mode.allFP32Denormals();
1419 
1420   bool MadeChange = false;
1421 
1422   Function::iterator NextBB;
1423   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
1424     BasicBlock *BB = &*FI;
1425     NextBB = std::next(FI);
1426 
1427     BasicBlock::iterator Next;
1428     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; I = Next) {
1429       Next = std::next(I);
1430 
1431       MadeChange |= visit(*I);
1432 
1433       if (Next != E) { // Control flow changed
1434         BasicBlock *NextInstBB = Next->getParent();
1435         if (NextInstBB != BB) {
1436           BB = NextInstBB;
1437           E = BB->end();
1438           FE = F.end();
1439         }
1440       }
1441     }
1442   }
1443 
1444   return MadeChange;
1445 }
1446 
1447 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
1448                       "AMDGPU IR optimizations", false, false)
1449 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1450 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
1451 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
1452                     false, false)
1453 
1454 char AMDGPUCodeGenPrepare::ID = 0;
1455 
1456 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
1457   return new AMDGPUCodeGenPrepare();
1458 }
1459