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