xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision b3b3cb2d2f7c650a63e19db12cccc9317a534b39)
1 //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This pass does misc. AMDGPU optimizations on IR before instruction
11 /// selection.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "SIModeRegisterDefaults.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/UniformityAnalysis.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/TargetPassConfig.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InstVisitor.h"
26 #include "llvm/IR/IntrinsicsAMDGPU.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/KnownBits.h"
30 #include "llvm/Transforms/Utils/IntegerDivision.h"
31 
32 #define DEBUG_TYPE "amdgpu-codegenprepare"
33 
34 using namespace llvm;
35 
36 namespace {
37 
38 static cl::opt<bool> WidenLoads(
39   "amdgpu-codegenprepare-widen-constant-loads",
40   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
41   cl::ReallyHidden,
42   cl::init(false));
43 
44 static cl::opt<bool> Widen16BitOps(
45   "amdgpu-codegenprepare-widen-16-bit-ops",
46   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
47   cl::ReallyHidden,
48   cl::init(true));
49 
50 static cl::opt<bool>
51     ScalarizeLargePHIs("amdgpu-codegenprepare-break-large-phis",
52                        cl::desc("Break large PHI nodes for DAGISel"),
53                        cl::ReallyHidden, cl::init(true));
54 
55 static cl::opt<bool>
56     ForceScalarizeLargePHIs("amdgpu-codegenprepare-force-break-large-phis",
57                             cl::desc("For testing purposes, always break large "
58                                      "PHIs even if it isn't profitable."),
59                             cl::ReallyHidden, cl::init(false));
60 
61 static cl::opt<unsigned> ScalarizeLargePHIsThreshold(
62     "amdgpu-codegenprepare-break-large-phis-threshold",
63     cl::desc("Minimum type size in bits for breaking large PHI nodes"),
64     cl::ReallyHidden, cl::init(32));
65 
66 static cl::opt<bool> UseMul24Intrin(
67   "amdgpu-codegenprepare-mul24",
68   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
69   cl::ReallyHidden,
70   cl::init(true));
71 
72 // Legalize 64-bit division by using the generic IR expansion.
73 static cl::opt<bool> ExpandDiv64InIR(
74   "amdgpu-codegenprepare-expand-div64",
75   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
76   cl::ReallyHidden,
77   cl::init(false));
78 
79 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
80 // and is used for testing the legalizer.
81 static cl::opt<bool> DisableIDivExpand(
82   "amdgpu-codegenprepare-disable-idiv-expansion",
83   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
84   cl::ReallyHidden,
85   cl::init(false));
86 
87 class AMDGPUCodeGenPrepare : public FunctionPass,
88                              public InstVisitor<AMDGPUCodeGenPrepare, bool> {
89   const GCNSubtarget *ST = nullptr;
90   AssumptionCache *AC = nullptr;
91   DominatorTree *DT = nullptr;
92   UniformityInfo *UA = nullptr;
93   Module *Mod = nullptr;
94   const DataLayout *DL = nullptr;
95   bool HasUnsafeFPMath = false;
96   bool HasFP32Denormals = false;
97 
98   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
99   /// binary operation \p V.
100   ///
101   /// \returns Binary operation \p V.
102   /// \returns \p T's base element bit width.
103   unsigned getBaseElementBitWidth(const Type *T) const;
104 
105   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
106   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
107   /// is returned.
108   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
109 
110   /// \returns True if binary operation \p I is a signed binary operation, false
111   /// otherwise.
112   bool isSigned(const BinaryOperator &I) const;
113 
114   /// \returns True if the condition of 'select' operation \p I comes from a
115   /// signed 'icmp' operation, false otherwise.
116   bool isSigned(const SelectInst &I) const;
117 
118   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
119   /// false otherwise.
120   bool needsPromotionToI32(const Type *T) const;
121 
122   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
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 equivalent 32 bit binary operation, and
128   /// truncating the result of 32 bit binary operation back to \p I's original
129   /// type. Division operation is not promoted.
130   ///
131   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
132   /// false otherwise.
133   bool promoteUniformOpToI32(BinaryOperator &I) const;
134 
135   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
136   ///
137   /// \details \p I's base element bit width must be greater than 1 and less
138   /// than or equal 16. Promotion is done by sign or zero extending operands to
139   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
140   ///
141   /// \returns True.
142   bool promoteUniformOpToI32(ICmpInst &I) const;
143 
144   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
145   /// operation.
146   ///
147   /// \details \p I's base element bit width must be greater than 1 and less
148   /// than or equal 16. Promotion is done by sign or zero extending operands to
149   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
150   /// result of 32 bit 'select' operation back to \p I's original type.
151   ///
152   /// \returns True.
153   bool promoteUniformOpToI32(SelectInst &I) const;
154 
155   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
156   /// intrinsic.
157   ///
158   /// \details \p I's base element bit width must be greater than 1 and less
159   /// than or equal 16. Promotion is done by zero extending the operand to 32
160   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
161   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
162   /// shift amount is 32 minus \p I's base element bit width), and truncating
163   /// the result of the shift operation back to \p I's original type.
164   ///
165   /// \returns True.
166   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
167 
168   /// \returns The minimum number of bits needed to store the value of \Op as an
169   /// unsigned integer. Truncating to this size and then zero-extending to
170   /// the original will not change the value.
171   unsigned numBitsUnsigned(Value *Op) const;
172 
173   /// \returns The minimum number of bits needed to store the value of \Op as a
174   /// signed integer. Truncating to this size and then sign-extending to
175   /// the original size will not change the value.
176   unsigned numBitsSigned(Value *Op) const;
177 
178   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
179   /// SelectionDAG has an issue where an and asserting the bits are known
180   bool replaceMulWithMul24(BinaryOperator &I) const;
181 
182   /// Perform same function as equivalently named function in DAGCombiner. Since
183   /// we expand some divisions here, we need to perform this before obscuring.
184   bool foldBinOpIntoSelect(BinaryOperator &I) const;
185 
186   bool divHasSpecialOptimization(BinaryOperator &I,
187                                  Value *Num, Value *Den) const;
188   int getDivNumBits(BinaryOperator &I,
189                     Value *Num, Value *Den,
190                     unsigned AtLeast, bool Signed) const;
191 
192   /// Expands 24 bit div or rem.
193   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
194                         Value *Num, Value *Den,
195                         bool IsDiv, bool IsSigned) const;
196 
197   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
198                             Value *Num, Value *Den, unsigned NumBits,
199                             bool IsDiv, bool IsSigned) const;
200 
201   /// Expands 32 bit div or rem.
202   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
203                         Value *Num, Value *Den) const;
204 
205   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
206                         Value *Num, Value *Den) const;
207   void expandDivRem64(BinaryOperator &I) const;
208 
209   /// Widen a scalar load.
210   ///
211   /// \details \p Widen scalar load for uniform, small type loads from constant
212   //  memory / to a full 32-bits and then truncate the input to allow a scalar
213   //  load instead of a vector load.
214   //
215   /// \returns True.
216 
217   bool canWidenScalarExtLoad(LoadInst &I) const;
218 
219 public:
220   static char ID;
221 
222   AMDGPUCodeGenPrepare() : FunctionPass(ID) {}
223 
224   bool visitFDiv(BinaryOperator &I);
225   bool visitXor(BinaryOperator &I);
226 
227   bool visitInstruction(Instruction &I) { return false; }
228   bool visitBinaryOperator(BinaryOperator &I);
229   bool visitLoadInst(LoadInst &I);
230   bool visitICmpInst(ICmpInst &I);
231   bool visitSelectInst(SelectInst &I);
232   bool visitPHINode(PHINode &I);
233 
234   bool visitIntrinsicInst(IntrinsicInst &I);
235   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
236 
237   bool doInitialization(Module &M) override;
238   bool runOnFunction(Function &F) override;
239 
240   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
241 
242   void getAnalysisUsage(AnalysisUsage &AU) const override {
243     AU.addRequired<AssumptionCacheTracker>();
244     AU.addRequired<UniformityInfoWrapperPass>();
245 
246     // FIXME: Division expansion needs to preserve the dominator tree.
247     if (!ExpandDiv64InIR)
248       AU.setPreservesAll();
249  }
250 };
251 
252 } // end anonymous namespace
253 
254 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(const Type *T) const {
255   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
256 
257   if (T->isIntegerTy())
258     return T->getIntegerBitWidth();
259   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
260 }
261 
262 Type *AMDGPUCodeGenPrepare::getI32Ty(IRBuilder<> &B, const Type *T) const {
263   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
264 
265   if (T->isIntegerTy())
266     return B.getInt32Ty();
267   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
268 }
269 
270 bool AMDGPUCodeGenPrepare::isSigned(const BinaryOperator &I) const {
271   return I.getOpcode() == Instruction::AShr ||
272       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
273 }
274 
275 bool AMDGPUCodeGenPrepare::isSigned(const SelectInst &I) const {
276   return isa<ICmpInst>(I.getOperand(0)) ?
277       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
278 }
279 
280 bool AMDGPUCodeGenPrepare::needsPromotionToI32(const Type *T) const {
281   if (!Widen16BitOps)
282     return false;
283 
284   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
285   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
286     return true;
287 
288   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
289     // TODO: The set of packed operations is more limited, so may want to
290     // promote some anyway.
291     if (ST->hasVOP3PInsts())
292       return false;
293 
294     return needsPromotionToI32(VT->getElementType());
295   }
296 
297   return false;
298 }
299 
300 // Return true if the op promoted to i32 should have nsw set.
301 static bool promotedOpIsNSW(const Instruction &I) {
302   switch (I.getOpcode()) {
303   case Instruction::Shl:
304   case Instruction::Add:
305   case Instruction::Sub:
306     return true;
307   case Instruction::Mul:
308     return I.hasNoUnsignedWrap();
309   default:
310     return false;
311   }
312 }
313 
314 // Return true if the op promoted to i32 should have nuw set.
315 static bool promotedOpIsNUW(const Instruction &I) {
316   switch (I.getOpcode()) {
317   case Instruction::Shl:
318   case Instruction::Add:
319   case Instruction::Mul:
320     return true;
321   case Instruction::Sub:
322     return I.hasNoUnsignedWrap();
323   default:
324     return false;
325   }
326 }
327 
328 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(LoadInst &I) const {
329   Type *Ty = I.getType();
330   const DataLayout &DL = Mod->getDataLayout();
331   int TySize = DL.getTypeSizeInBits(Ty);
332   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
333 
334   return I.isSimple() && TySize < 32 && Alignment >= 4 && UA->isUniform(&I);
335 }
336 
337 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(BinaryOperator &I) const {
338   assert(needsPromotionToI32(I.getType()) &&
339          "I does not need promotion to i32");
340 
341   if (I.getOpcode() == Instruction::SDiv ||
342       I.getOpcode() == Instruction::UDiv ||
343       I.getOpcode() == Instruction::SRem ||
344       I.getOpcode() == Instruction::URem)
345     return false;
346 
347   IRBuilder<> Builder(&I);
348   Builder.SetCurrentDebugLocation(I.getDebugLoc());
349 
350   Type *I32Ty = getI32Ty(Builder, I.getType());
351   Value *ExtOp0 = nullptr;
352   Value *ExtOp1 = nullptr;
353   Value *ExtRes = nullptr;
354   Value *TruncRes = nullptr;
355 
356   if (isSigned(I)) {
357     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
358     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
359   } else {
360     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
361     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
362   }
363 
364   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
365   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
366     if (promotedOpIsNSW(cast<Instruction>(I)))
367       Inst->setHasNoSignedWrap();
368 
369     if (promotedOpIsNUW(cast<Instruction>(I)))
370       Inst->setHasNoUnsignedWrap();
371 
372     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
373       Inst->setIsExact(ExactOp->isExact());
374   }
375 
376   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
377 
378   I.replaceAllUsesWith(TruncRes);
379   I.eraseFromParent();
380 
381   return true;
382 }
383 
384 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(ICmpInst &I) const {
385   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
386          "I does not need promotion to i32");
387 
388   IRBuilder<> Builder(&I);
389   Builder.SetCurrentDebugLocation(I.getDebugLoc());
390 
391   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
392   Value *ExtOp0 = nullptr;
393   Value *ExtOp1 = nullptr;
394   Value *NewICmp  = nullptr;
395 
396   if (I.isSigned()) {
397     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
398     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
399   } else {
400     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
401     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
402   }
403   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
404 
405   I.replaceAllUsesWith(NewICmp);
406   I.eraseFromParent();
407 
408   return true;
409 }
410 
411 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(SelectInst &I) const {
412   assert(needsPromotionToI32(I.getType()) &&
413          "I does not need promotion to i32");
414 
415   IRBuilder<> Builder(&I);
416   Builder.SetCurrentDebugLocation(I.getDebugLoc());
417 
418   Type *I32Ty = getI32Ty(Builder, I.getType());
419   Value *ExtOp1 = nullptr;
420   Value *ExtOp2 = nullptr;
421   Value *ExtRes = nullptr;
422   Value *TruncRes = nullptr;
423 
424   if (isSigned(I)) {
425     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
426     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
427   } else {
428     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
429     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
430   }
431   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
432   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
433 
434   I.replaceAllUsesWith(TruncRes);
435   I.eraseFromParent();
436 
437   return true;
438 }
439 
440 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32(
441     IntrinsicInst &I) const {
442   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
443          "I must be bitreverse intrinsic");
444   assert(needsPromotionToI32(I.getType()) &&
445          "I does not need promotion to i32");
446 
447   IRBuilder<> Builder(&I);
448   Builder.SetCurrentDebugLocation(I.getDebugLoc());
449 
450   Type *I32Ty = getI32Ty(Builder, I.getType());
451   Function *I32 =
452       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
453   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
454   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
455   Value *LShrOp =
456       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
457   Value *TruncRes =
458       Builder.CreateTrunc(LShrOp, I.getType());
459 
460   I.replaceAllUsesWith(TruncRes);
461   I.eraseFromParent();
462 
463   return true;
464 }
465 
466 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(Value *Op) const {
467   return computeKnownBits(Op, *DL, 0, AC).countMaxActiveBits();
468 }
469 
470 unsigned AMDGPUCodeGenPrepare::numBitsSigned(Value *Op) const {
471   return ComputeMaxSignificantBits(Op, *DL, 0, AC);
472 }
473 
474 static void extractValues(IRBuilder<> &Builder,
475                           SmallVectorImpl<Value *> &Values, Value *V) {
476   auto *VT = dyn_cast<FixedVectorType>(V->getType());
477   if (!VT) {
478     Values.push_back(V);
479     return;
480   }
481 
482   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
483     Values.push_back(Builder.CreateExtractElement(V, I));
484 }
485 
486 static Value *insertValues(IRBuilder<> &Builder,
487                            Type *Ty,
488                            SmallVectorImpl<Value *> &Values) {
489   if (!Ty->isVectorTy()) {
490     assert(Values.size() == 1);
491     return Values[0];
492   }
493 
494   Value *NewVal = PoisonValue::get(Ty);
495   for (int I = 0, E = Values.size(); I != E; ++I)
496     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
497 
498   return NewVal;
499 }
500 
501 // Returns 24-bit or 48-bit (as per `NumBits` and `Size`) mul of `LHS` and
502 // `RHS`. `NumBits` is the number of KnownBits of the result and `Size` is the
503 // width of the original destination.
504 static Value *getMul24(IRBuilder<> &Builder, Value *LHS, Value *RHS,
505                        unsigned Size, unsigned NumBits, bool IsSigned) {
506   if (Size <= 32 || NumBits <= 32) {
507     Intrinsic::ID ID =
508         IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
509     return Builder.CreateIntrinsic(ID, {}, {LHS, RHS});
510   }
511 
512   assert(NumBits <= 48);
513 
514   Intrinsic::ID LoID =
515       IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
516   Intrinsic::ID HiID =
517       IsSigned ? Intrinsic::amdgcn_mulhi_i24 : Intrinsic::amdgcn_mulhi_u24;
518 
519   Value *Lo = Builder.CreateIntrinsic(LoID, {}, {LHS, RHS});
520   Value *Hi = Builder.CreateIntrinsic(HiID, {}, {LHS, RHS});
521 
522   IntegerType *I64Ty = Builder.getInt64Ty();
523   Lo = Builder.CreateZExtOrTrunc(Lo, I64Ty);
524   Hi = Builder.CreateZExtOrTrunc(Hi, I64Ty);
525 
526   return Builder.CreateOr(Lo, Builder.CreateShl(Hi, 32));
527 }
528 
529 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(BinaryOperator &I) const {
530   if (I.getOpcode() != Instruction::Mul)
531     return false;
532 
533   Type *Ty = I.getType();
534   unsigned Size = Ty->getScalarSizeInBits();
535   if (Size <= 16 && ST->has16BitInsts())
536     return false;
537 
538   // Prefer scalar if this could be s_mul_i32
539   if (UA->isUniform(&I))
540     return false;
541 
542   Value *LHS = I.getOperand(0);
543   Value *RHS = I.getOperand(1);
544   IRBuilder<> Builder(&I);
545   Builder.SetCurrentDebugLocation(I.getDebugLoc());
546 
547   unsigned LHSBits = 0, RHSBits = 0;
548   bool IsSigned = false;
549 
550   if (ST->hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
551       (RHSBits = numBitsUnsigned(RHS)) <= 24) {
552     IsSigned = false;
553 
554   } else if (ST->hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
555              (RHSBits = numBitsSigned(RHS)) <= 24) {
556     IsSigned = true;
557 
558   } else
559     return false;
560 
561   SmallVector<Value *, 4> LHSVals;
562   SmallVector<Value *, 4> RHSVals;
563   SmallVector<Value *, 4> ResultVals;
564   extractValues(Builder, LHSVals, LHS);
565   extractValues(Builder, RHSVals, RHS);
566 
567   IntegerType *I32Ty = Builder.getInt32Ty();
568   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
569     Value *LHS, *RHS;
570     if (IsSigned) {
571       LHS = Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty);
572       RHS = Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty);
573     } else {
574       LHS = Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
575       RHS = Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
576     }
577 
578     Value *Result =
579         getMul24(Builder, LHS, RHS, Size, LHSBits + RHSBits, IsSigned);
580 
581     if (IsSigned) {
582       ResultVals.push_back(
583           Builder.CreateSExtOrTrunc(Result, LHSVals[I]->getType()));
584     } else {
585       ResultVals.push_back(
586           Builder.CreateZExtOrTrunc(Result, LHSVals[I]->getType()));
587     }
588   }
589 
590   Value *NewVal = insertValues(Builder, Ty, ResultVals);
591   NewVal->takeName(&I);
592   I.replaceAllUsesWith(NewVal);
593   I.eraseFromParent();
594 
595   return true;
596 }
597 
598 // Find a select instruction, which may have been casted. This is mostly to deal
599 // with cases where i16 selects were promoted here to i32.
600 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
601   Cast = nullptr;
602   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
603     return Sel;
604 
605   if ((Cast = dyn_cast<CastInst>(V))) {
606     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
607       return Sel;
608   }
609 
610   return nullptr;
611 }
612 
613 bool AMDGPUCodeGenPrepare::foldBinOpIntoSelect(BinaryOperator &BO) const {
614   // Don't do this unless the old select is going away. We want to eliminate the
615   // binary operator, not replace a binop with a select.
616   int SelOpNo = 0;
617 
618   CastInst *CastOp;
619 
620   // TODO: Should probably try to handle some cases with multiple
621   // users. Duplicating the select may be profitable for division.
622   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
623   if (!Sel || !Sel->hasOneUse()) {
624     SelOpNo = 1;
625     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
626   }
627 
628   if (!Sel || !Sel->hasOneUse())
629     return false;
630 
631   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
632   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
633   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
634   if (!CBO || !CT || !CF)
635     return false;
636 
637   if (CastOp) {
638     if (!CastOp->hasOneUse())
639       return false;
640     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
641     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
642   }
643 
644   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
645   // need to handle divisions here.
646   Constant *FoldedT = SelOpNo ?
647     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
648     ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
649   if (!FoldedT || isa<ConstantExpr>(FoldedT))
650     return false;
651 
652   Constant *FoldedF = SelOpNo ?
653     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
654     ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
655   if (!FoldedF || isa<ConstantExpr>(FoldedF))
656     return false;
657 
658   IRBuilder<> Builder(&BO);
659   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
660   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
661     Builder.setFastMathFlags(FPOp->getFastMathFlags());
662 
663   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
664                                           FoldedT, FoldedF);
665   NewSelect->takeName(&BO);
666   BO.replaceAllUsesWith(NewSelect);
667   BO.eraseFromParent();
668   if (CastOp)
669     CastOp->eraseFromParent();
670   Sel->eraseFromParent();
671   return true;
672 }
673 
674 // Optimize fdiv with rcp:
675 //
676 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
677 //               allowed with unsafe-fp-math or afn.
678 //
679 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
680 static Value *optimizeWithRcp(Value *Num, Value *Den, bool AllowInaccurateRcp,
681                               bool RcpIsAccurate, IRBuilder<> &Builder,
682                               Module *Mod) {
683 
684   if (!AllowInaccurateRcp && !RcpIsAccurate)
685     return nullptr;
686 
687   Type *Ty = Den->getType();
688   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
689     if (AllowInaccurateRcp || RcpIsAccurate) {
690       if (CLHS->isExactlyValue(1.0)) {
691         Function *Decl = Intrinsic::getDeclaration(
692           Mod, Intrinsic::amdgcn_rcp, Ty);
693 
694         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
695         // the CI documentation has a worst case error of 1 ulp.
696         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
697         // use it as long as we aren't trying to use denormals.
698         //
699         // v_rcp_f16 and v_rsq_f16 DO support denormals.
700 
701         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
702         //       insert rsq intrinsic here.
703 
704         // 1.0 / x -> rcp(x)
705         return Builder.CreateCall(Decl, { Den });
706       }
707 
708        // Same as for 1.0, but expand the sign out of the constant.
709       if (CLHS->isExactlyValue(-1.0)) {
710         Function *Decl = Intrinsic::getDeclaration(
711           Mod, Intrinsic::amdgcn_rcp, Ty);
712 
713          // -1.0 / x -> rcp (fneg x)
714          Value *FNeg = Builder.CreateFNeg(Den);
715          return Builder.CreateCall(Decl, { FNeg });
716        }
717     }
718   }
719 
720   if (AllowInaccurateRcp) {
721     Function *Decl = Intrinsic::getDeclaration(
722       Mod, Intrinsic::amdgcn_rcp, Ty);
723 
724     // Turn into multiply by the reciprocal.
725     // x / y -> x * (1.0 / y)
726     Value *Recip = Builder.CreateCall(Decl, { Den });
727     return Builder.CreateFMul(Num, Recip);
728   }
729   return nullptr;
730 }
731 
732 // optimize with fdiv.fast:
733 //
734 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
735 //
736 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
737 //
738 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
739 static Value *optimizeWithFDivFast(Value *Num, Value *Den, float ReqdAccuracy,
740                                    bool HasDenormals, IRBuilder<> &Builder,
741                                    Module *Mod) {
742   // fdiv.fast can achieve 2.5 ULP accuracy.
743   if (ReqdAccuracy < 2.5f)
744     return nullptr;
745 
746   // Only have fdiv.fast for f32.
747   Type *Ty = Den->getType();
748   if (!Ty->isFloatTy())
749     return nullptr;
750 
751   bool NumIsOne = false;
752   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
753     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
754       NumIsOne = true;
755   }
756 
757   // fdiv does not support denormals. But 1.0/x is always fine to use it.
758   if (HasDenormals && !NumIsOne)
759     return nullptr;
760 
761   Function *Decl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_fdiv_fast);
762   return Builder.CreateCall(Decl, { Num, Den });
763 }
764 
765 // Optimizations is performed based on fpmath, fast math flags as well as
766 // denormals to optimize fdiv with either rcp or fdiv.fast.
767 //
768 // With rcp:
769 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
770 //                 allowed with unsafe-fp-math or afn.
771 //
772 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
773 //
774 // With fdiv.fast:
775 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
776 //
777 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
778 //
779 // NOTE: rcp is the preference in cases that both are legal.
780 bool AMDGPUCodeGenPrepare::visitFDiv(BinaryOperator &FDiv) {
781 
782   Type *Ty = FDiv.getType()->getScalarType();
783 
784   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
785   // expansion around them in codegen.
786   if (Ty->isDoubleTy())
787     return false;
788 
789   // No intrinsic for fdiv16 if target does not support f16.
790   if (Ty->isHalfTy() && !ST->has16BitInsts())
791     return false;
792 
793   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
794   const float ReqdAccuracy =  FPOp->getFPAccuracy();
795 
796   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
797   FastMathFlags FMF = FPOp->getFastMathFlags();
798   const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc();
799 
800   // rcp_f16 is accurate for !fpmath >= 1.0ulp.
801   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
802   // rcp_f64 is never accurate.
803   const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) ||
804             (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f);
805 
806   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
807   Builder.setFastMathFlags(FMF);
808   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
809 
810   Value *Num = FDiv.getOperand(0);
811   Value *Den = FDiv.getOperand(1);
812 
813   Value *NewFDiv = nullptr;
814   if (auto *VT = dyn_cast<FixedVectorType>(FDiv.getType())) {
815     NewFDiv = PoisonValue::get(VT);
816 
817     // FIXME: Doesn't do the right thing for cases where the vector is partially
818     // constant. This works when the scalarizer pass is run first.
819     for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) {
820       Value *NumEltI = Builder.CreateExtractElement(Num, I);
821       Value *DenEltI = Builder.CreateExtractElement(Den, I);
822       // Try rcp first.
823       Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp,
824                                       RcpIsAccurate, Builder, Mod);
825       if (!NewElt) // Try fdiv.fast.
826         NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy,
827                                       HasFP32Denormals, Builder, Mod);
828       if (!NewElt) // Keep the original.
829         NewElt = Builder.CreateFDiv(NumEltI, DenEltI);
830 
831       NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I);
832     }
833   } else { // Scalar FDiv.
834     // Try rcp first.
835     NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate,
836                               Builder, Mod);
837     if (!NewFDiv) { // Try fdiv.fast.
838       NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals,
839                                      Builder, Mod);
840     }
841   }
842 
843   if (NewFDiv) {
844     FDiv.replaceAllUsesWith(NewFDiv);
845     NewFDiv->takeName(&FDiv);
846     FDiv.eraseFromParent();
847   }
848 
849   return !!NewFDiv;
850 }
851 
852 bool AMDGPUCodeGenPrepare::visitXor(BinaryOperator &I) {
853   // Match the Xor instruction, its type and its operands
854   IntrinsicInst *IntrinsicCall = dyn_cast<IntrinsicInst>(I.getOperand(0));
855   ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1));
856   if (!RHS || !IntrinsicCall || RHS->getSExtValue() != -1)
857     return visitBinaryOperator(I);
858 
859   // Check if the Call is an intrinsic instruction to amdgcn_class intrinsic
860   // has only one use
861   if (IntrinsicCall->getIntrinsicID() != Intrinsic::amdgcn_class ||
862       !IntrinsicCall->hasOneUse())
863     return visitBinaryOperator(I);
864 
865   // "Not" the second argument of the intrinsic call
866   ConstantInt *Arg = dyn_cast<ConstantInt>(IntrinsicCall->getOperand(1));
867   if (!Arg)
868     return visitBinaryOperator(I);
869 
870   IntrinsicCall->setOperand(
871       1, ConstantInt::get(Arg->getType(), Arg->getZExtValue() ^ 0x3ff));
872   I.replaceAllUsesWith(IntrinsicCall);
873   I.eraseFromParent();
874   return true;
875 }
876 
877 static bool hasUnsafeFPMath(const Function &F) {
878   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
879   return Attr.getValueAsBool();
880 }
881 
882 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
883                                           Value *LHS, Value *RHS) {
884   Type *I32Ty = Builder.getInt32Ty();
885   Type *I64Ty = Builder.getInt64Ty();
886 
887   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
888   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
889   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
890   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
891   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
892   Hi = Builder.CreateTrunc(Hi, I32Ty);
893   return std::pair(Lo, Hi);
894 }
895 
896 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
897   return getMul64(Builder, LHS, RHS).second;
898 }
899 
900 /// Figure out how many bits are really needed for this division. \p AtLeast is
901 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
902 /// first one is insufficient. Returns -1 on failure.
903 int AMDGPUCodeGenPrepare::getDivNumBits(BinaryOperator &I,
904                                         Value *Num, Value *Den,
905                                         unsigned AtLeast, bool IsSigned) const {
906   const DataLayout &DL = Mod->getDataLayout();
907   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
908   if (LHSSignBits < AtLeast)
909     return -1;
910 
911   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
912   if (RHSSignBits < AtLeast)
913     return -1;
914 
915   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
916   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
917   if (IsSigned)
918     ++DivBits;
919   return DivBits;
920 }
921 
922 // The fractional part of a float is enough to accurately represent up to
923 // a 24-bit signed integer.
924 Value *AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder,
925                                             BinaryOperator &I,
926                                             Value *Num, Value *Den,
927                                             bool IsDiv, bool IsSigned) const {
928   int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
929   if (DivBits == -1)
930     return nullptr;
931   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
932 }
933 
934 Value *AMDGPUCodeGenPrepare::expandDivRem24Impl(IRBuilder<> &Builder,
935                                                 BinaryOperator &I,
936                                                 Value *Num, Value *Den,
937                                                 unsigned DivBits,
938                                                 bool IsDiv, bool IsSigned) const {
939   Type *I32Ty = Builder.getInt32Ty();
940   Num = Builder.CreateTrunc(Num, I32Ty);
941   Den = Builder.CreateTrunc(Den, I32Ty);
942 
943   Type *F32Ty = Builder.getFloatTy();
944   ConstantInt *One = Builder.getInt32(1);
945   Value *JQ = One;
946 
947   if (IsSigned) {
948     // char|short jq = ia ^ ib;
949     JQ = Builder.CreateXor(Num, Den);
950 
951     // jq = jq >> (bitsize - 2)
952     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
953 
954     // jq = jq | 0x1
955     JQ = Builder.CreateOr(JQ, One);
956   }
957 
958   // int ia = (int)LHS;
959   Value *IA = Num;
960 
961   // int ib, (int)RHS;
962   Value *IB = Den;
963 
964   // float fa = (float)ia;
965   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
966                        : Builder.CreateUIToFP(IA, F32Ty);
967 
968   // float fb = (float)ib;
969   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
970                        : Builder.CreateUIToFP(IB,F32Ty);
971 
972   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
973                                                 Builder.getFloatTy());
974   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
975   Value *FQM = Builder.CreateFMul(FA, RCP);
976 
977   // fq = trunc(fqm);
978   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
979   FQ->copyFastMathFlags(Builder.getFastMathFlags());
980 
981   // float fqneg = -fq;
982   Value *FQNeg = Builder.CreateFNeg(FQ);
983 
984   // float fr = mad(fqneg, fb, fa);
985   auto FMAD = !ST->hasMadMacF32Insts()
986                   ? Intrinsic::fma
987                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
988   Value *FR = Builder.CreateIntrinsic(FMAD,
989                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
990 
991   // int iq = (int)fq;
992   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
993                        : Builder.CreateFPToUI(FQ, I32Ty);
994 
995   // fr = fabs(fr);
996   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
997 
998   // fb = fabs(fb);
999   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
1000 
1001   // int cv = fr >= fb;
1002   Value *CV = Builder.CreateFCmpOGE(FR, FB);
1003 
1004   // jq = (cv ? jq : 0);
1005   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
1006 
1007   // dst = iq + jq;
1008   Value *Div = Builder.CreateAdd(IQ, JQ);
1009 
1010   Value *Res = Div;
1011   if (!IsDiv) {
1012     // Rem needs compensation, it's easier to recompute it
1013     Value *Rem = Builder.CreateMul(Div, Den);
1014     Res = Builder.CreateSub(Num, Rem);
1015   }
1016 
1017   if (DivBits != 0 && DivBits < 32) {
1018     // Extend in register from the number of bits this divide really is.
1019     if (IsSigned) {
1020       int InRegBits = 32 - DivBits;
1021 
1022       Res = Builder.CreateShl(Res, InRegBits);
1023       Res = Builder.CreateAShr(Res, InRegBits);
1024     } else {
1025       ConstantInt *TruncMask
1026         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
1027       Res = Builder.CreateAnd(Res, TruncMask);
1028     }
1029   }
1030 
1031   return Res;
1032 }
1033 
1034 // Try to recognize special cases the DAG will emit special, better expansions
1035 // than the general expansion we do here.
1036 
1037 // TODO: It would be better to just directly handle those optimizations here.
1038 bool AMDGPUCodeGenPrepare::divHasSpecialOptimization(
1039   BinaryOperator &I, Value *Num, Value *Den) const {
1040   if (Constant *C = dyn_cast<Constant>(Den)) {
1041     // Arbitrary constants get a better expansion as long as a wider mulhi is
1042     // legal.
1043     if (C->getType()->getScalarSizeInBits() <= 32)
1044       return true;
1045 
1046     // TODO: Sdiv check for not exact for some reason.
1047 
1048     // If there's no wider mulhi, there's only a better expansion for powers of
1049     // two.
1050     // TODO: Should really know for each vector element.
1051     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
1052       return true;
1053 
1054     return false;
1055   }
1056 
1057   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1058     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1059     if (BinOpDen->getOpcode() == Instruction::Shl &&
1060         isa<Constant>(BinOpDen->getOperand(0)) &&
1061         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
1062                                0, AC, &I, DT)) {
1063       return true;
1064     }
1065   }
1066 
1067   return false;
1068 }
1069 
1070 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
1071   // Check whether the sign can be determined statically.
1072   KnownBits Known = computeKnownBits(V, *DL);
1073   if (Known.isNegative())
1074     return Constant::getAllOnesValue(V->getType());
1075   if (Known.isNonNegative())
1076     return Constant::getNullValue(V->getType());
1077   return Builder.CreateAShr(V, Builder.getInt32(31));
1078 }
1079 
1080 Value *AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder,
1081                                             BinaryOperator &I, Value *X,
1082                                             Value *Y) const {
1083   Instruction::BinaryOps Opc = I.getOpcode();
1084   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1085          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1086 
1087   FastMathFlags FMF;
1088   FMF.setFast();
1089   Builder.setFastMathFlags(FMF);
1090 
1091   if (divHasSpecialOptimization(I, X, Y))
1092     return nullptr;  // Keep it for later optimization.
1093 
1094   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1095   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1096 
1097   Type *Ty = X->getType();
1098   Type *I32Ty = Builder.getInt32Ty();
1099   Type *F32Ty = Builder.getFloatTy();
1100 
1101   if (Ty->getScalarSizeInBits() < 32) {
1102     if (IsSigned) {
1103       X = Builder.CreateSExt(X, I32Ty);
1104       Y = Builder.CreateSExt(Y, I32Ty);
1105     } else {
1106       X = Builder.CreateZExt(X, I32Ty);
1107       Y = Builder.CreateZExt(Y, I32Ty);
1108     }
1109   }
1110 
1111   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
1112     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1113                       Builder.CreateZExtOrTrunc(Res, Ty);
1114   }
1115 
1116   ConstantInt *Zero = Builder.getInt32(0);
1117   ConstantInt *One = Builder.getInt32(1);
1118 
1119   Value *Sign = nullptr;
1120   if (IsSigned) {
1121     Value *SignX = getSign32(X, Builder, DL);
1122     Value *SignY = getSign32(Y, Builder, DL);
1123     // Remainder sign is the same as LHS
1124     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1125 
1126     X = Builder.CreateAdd(X, SignX);
1127     Y = Builder.CreateAdd(Y, SignY);
1128 
1129     X = Builder.CreateXor(X, SignX);
1130     Y = Builder.CreateXor(Y, SignY);
1131   }
1132 
1133   // The algorithm here is based on ideas from "Software Integer Division", Tom
1134   // Rodeheffer, August 2008.
1135   //
1136   // unsigned udiv(unsigned x, unsigned y) {
1137   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1138   //   // that this is a lower bound on inv(y), even if some of the calculations
1139   //   // round up.
1140   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1141   //
1142   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1143   //   // Empirically this is guaranteed to give a "two-y" lower bound on
1144   //   // inv(y).
1145   //   z += umulh(z, -y * z);
1146   //
1147   //   // Quotient/remainder estimate.
1148   //   unsigned q = umulh(x, z);
1149   //   unsigned r = x - q * y;
1150   //
1151   //   // Two rounds of quotient/remainder refinement.
1152   //   if (r >= y) {
1153   //     ++q;
1154   //     r -= y;
1155   //   }
1156   //   if (r >= y) {
1157   //     ++q;
1158   //     r -= y;
1159   //   }
1160   //
1161   //   return q;
1162   // }
1163 
1164   // Initial estimate of inv(y).
1165   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1166   Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
1167   Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
1168   Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
1169   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1170   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1171 
1172   // One round of UNR.
1173   Value *NegY = Builder.CreateSub(Zero, Y);
1174   Value *NegYZ = Builder.CreateMul(NegY, Z);
1175   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1176 
1177   // Quotient/remainder estimate.
1178   Value *Q = getMulHu(Builder, X, Z);
1179   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1180 
1181   // First quotient/remainder refinement.
1182   Value *Cond = Builder.CreateICmpUGE(R, Y);
1183   if (IsDiv)
1184     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1185   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1186 
1187   // Second quotient/remainder refinement.
1188   Cond = Builder.CreateICmpUGE(R, Y);
1189   Value *Res;
1190   if (IsDiv)
1191     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1192   else
1193     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1194 
1195   if (IsSigned) {
1196     Res = Builder.CreateXor(Res, Sign);
1197     Res = Builder.CreateSub(Res, Sign);
1198   }
1199 
1200   Res = Builder.CreateTrunc(Res, Ty);
1201 
1202   return Res;
1203 }
1204 
1205 Value *AMDGPUCodeGenPrepare::shrinkDivRem64(IRBuilder<> &Builder,
1206                                             BinaryOperator &I,
1207                                             Value *Num, Value *Den) const {
1208   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1209     return nullptr;  // Keep it for later optimization.
1210 
1211   Instruction::BinaryOps Opc = I.getOpcode();
1212 
1213   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1214   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1215 
1216   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1217   if (NumDivBits == -1)
1218     return nullptr;
1219 
1220   Value *Narrowed = nullptr;
1221   if (NumDivBits <= 24) {
1222     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1223                                   IsDiv, IsSigned);
1224   } else if (NumDivBits <= 32) {
1225     Narrowed = expandDivRem32(Builder, I, Num, Den);
1226   }
1227 
1228   if (Narrowed) {
1229     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1230                       Builder.CreateZExt(Narrowed, Num->getType());
1231   }
1232 
1233   return nullptr;
1234 }
1235 
1236 void AMDGPUCodeGenPrepare::expandDivRem64(BinaryOperator &I) const {
1237   Instruction::BinaryOps Opc = I.getOpcode();
1238   // Do the general expansion.
1239   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1240     expandDivisionUpTo64Bits(&I);
1241     return;
1242   }
1243 
1244   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1245     expandRemainderUpTo64Bits(&I);
1246     return;
1247   }
1248 
1249   llvm_unreachable("not a division");
1250 }
1251 
1252 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) {
1253   if (foldBinOpIntoSelect(I))
1254     return true;
1255 
1256   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1257       UA->isUniform(&I) && promoteUniformOpToI32(I))
1258     return true;
1259 
1260   if (UseMul24Intrin && replaceMulWithMul24(I))
1261     return true;
1262 
1263   bool Changed = false;
1264   Instruction::BinaryOps Opc = I.getOpcode();
1265   Type *Ty = I.getType();
1266   Value *NewDiv = nullptr;
1267   unsigned ScalarSize = Ty->getScalarSizeInBits();
1268 
1269   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1270 
1271   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1272        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1273       ScalarSize <= 64 &&
1274       !DisableIDivExpand) {
1275     Value *Num = I.getOperand(0);
1276     Value *Den = I.getOperand(1);
1277     IRBuilder<> Builder(&I);
1278     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1279 
1280     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1281       NewDiv = PoisonValue::get(VT);
1282 
1283       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1284         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1285         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1286 
1287         Value *NewElt;
1288         if (ScalarSize <= 32) {
1289           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1290           if (!NewElt)
1291             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1292         } else {
1293           // See if this 64-bit division can be shrunk to 32/24-bits before
1294           // producing the general expansion.
1295           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1296           if (!NewElt) {
1297             // The general 64-bit expansion introduces control flow and doesn't
1298             // return the new value. Just insert a scalar copy and defer
1299             // expanding it.
1300             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1301             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1302           }
1303         }
1304 
1305         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1306       }
1307     } else {
1308       if (ScalarSize <= 32)
1309         NewDiv = expandDivRem32(Builder, I, Num, Den);
1310       else {
1311         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1312         if (!NewDiv)
1313           Div64ToExpand.push_back(&I);
1314       }
1315     }
1316 
1317     if (NewDiv) {
1318       I.replaceAllUsesWith(NewDiv);
1319       I.eraseFromParent();
1320       Changed = true;
1321     }
1322   }
1323 
1324   if (ExpandDiv64InIR) {
1325     // TODO: We get much worse code in specially handled constant cases.
1326     for (BinaryOperator *Div : Div64ToExpand) {
1327       expandDivRem64(*Div);
1328       Changed = true;
1329     }
1330   }
1331 
1332   return Changed;
1333 }
1334 
1335 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) {
1336   if (!WidenLoads)
1337     return false;
1338 
1339   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1340        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1341       canWidenScalarExtLoad(I)) {
1342     IRBuilder<> Builder(&I);
1343     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1344 
1345     Type *I32Ty = Builder.getInt32Ty();
1346     Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace());
1347     Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT);
1348     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast);
1349     WidenLoad->copyMetadata(I);
1350 
1351     // If we have range metadata, we need to convert the type, and not make
1352     // assumptions about the high bits.
1353     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1354       ConstantInt *Lower =
1355         mdconst::extract<ConstantInt>(Range->getOperand(0));
1356 
1357       if (Lower->isNullValue()) {
1358         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1359       } else {
1360         Metadata *LowAndHigh[] = {
1361           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1362           // Don't make assumptions about the high bits.
1363           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1364         };
1365 
1366         WidenLoad->setMetadata(LLVMContext::MD_range,
1367                                MDNode::get(Mod->getContext(), LowAndHigh));
1368       }
1369     }
1370 
1371     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
1372     Type *IntNTy = Builder.getIntNTy(TySize);
1373     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1374     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1375     I.replaceAllUsesWith(ValOrig);
1376     I.eraseFromParent();
1377     return true;
1378   }
1379 
1380   return false;
1381 }
1382 
1383 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) {
1384   bool Changed = false;
1385 
1386   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1387       UA->isUniform(&I))
1388     Changed |= promoteUniformOpToI32(I);
1389 
1390   return Changed;
1391 }
1392 
1393 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) {
1394   bool Changed = false;
1395 
1396   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1397       UA->isUniform(&I))
1398     Changed |= promoteUniformOpToI32(I);
1399 
1400   return Changed;
1401 }
1402 
1403 // Helper for breaking large PHIs that returns true when an extractelement on V
1404 // is likely to be folded away by the DAG combiner.
1405 static bool isInterestingPHIIncomingValue(Value *V, FixedVectorType *FVT) {
1406   InsertElementInst *IE = dyn_cast<InsertElementInst>(V);
1407 
1408   // Constants & InsertElements chains are interesting.
1409   if (!IE)
1410     return isa<Constant>(V);
1411 
1412   // Check if this is a simple chain of insertelement that fills the vector. If
1413   // that's the case, we can break up this PHI node profitably because the
1414   // extractelement we will insert will get folded out.
1415   BasicBlock *BB = IE->getParent();
1416   BitVector EltsCovered(FVT->getNumElements());
1417   InsertElementInst *Next = IE;
1418   while (Next && !EltsCovered.all()) {
1419     ConstantInt *Idx = dyn_cast<ConstantInt>(Next->getOperand(2));
1420 
1421     // Non constant index/out of bounds index -> folding is unlikely.
1422     // Note that this is more of a sanity check - canonical IR should
1423     // already have replaced those with poison.
1424     if (!Idx || Idx->getSExtValue() >= FVT->getNumElements())
1425       return false;
1426 
1427     EltsCovered.set(Idx->getSExtValue());
1428 
1429     // If the insertelement chain ends with a constant, it's fine.
1430     if (isa<Constant>(Next->getOperand(0)))
1431       return true;
1432 
1433     Next = dyn_cast<InsertElementInst>(Next->getOperand(0));
1434 
1435     // If the chain is spread across basic blocks, the DAG combiner
1436     // won't see it in its entirety and is unlikely to be able to fold
1437     // evevrything away.
1438     if (Next && Next->getParent() != BB)
1439       return false;
1440   }
1441 
1442   // All elements covered, all of the extract elements will likely be
1443   // combined.
1444   return EltsCovered.all();
1445 }
1446 
1447 bool AMDGPUCodeGenPrepare::visitPHINode(PHINode &I) {
1448   // Break-up fixed-vector PHIs into smaller pieces.
1449   // Default threshold is 32, so it breaks up any vector that's >32 bits into
1450   // its elements, or into 32-bit pieces (for 8/16 bit elts).
1451   //
1452   // This is only helpful for DAGISel because it doesn't handle large PHIs as
1453   // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
1454   // With large, odd-sized PHIs we may end up needing many `build_vector`
1455   // operations with most elements being "undef". This inhibits a lot of
1456   // optimization opportunities and can result in unreasonably high register
1457   // pressure and the inevitable stack spilling.
1458   if (!ScalarizeLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
1459     return false;
1460 
1461   FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
1462   if (!FVT || DL->getTypeSizeInBits(FVT) <= ScalarizeLargePHIsThreshold)
1463     return false;
1464 
1465   // Try to avoid unprofitable cases:
1466   // - Don't break PHIs that have no interesting incoming values. That is, where
1467   // there is no clear opportunity to fold the "extractelement" instructions we
1468   // would add.
1469   //   - Note: IC does not run after this pass, so we're only interested in the
1470   //     folding that the DAG combiner can do.
1471   // - For simplicity, don't break PHIs that are used by other PHIs because it'd
1472   // require us to determine if the whole "chain" can be converted or not. e.g.
1473   // if we broke this PHI but not its user, we would actually make things worse.
1474   if (!ForceScalarizeLargePHIs) {
1475     if (none_of(
1476             I.incoming_values(),
1477             [&](Value *V) { return isInterestingPHIIncomingValue(V, FVT); }) ||
1478         any_of(I.users(), [&](User *U) { return isa<PHINode>(U); })) {
1479       return false;
1480     }
1481   }
1482 
1483   struct VectorSlice {
1484     Type *Ty = nullptr;
1485     unsigned Idx = 0;
1486     unsigned NumElts = 0;
1487     std::vector<Value *> IncomingValues = {};
1488     PHINode *NewPHI = nullptr;
1489   };
1490 
1491   std::vector<VectorSlice> Slices;
1492 
1493   Type *EltTy = FVT->getElementType();
1494   {
1495     unsigned Idx = 0;
1496     // For 8/16 bits type, don't scalarize fully but break it up into as many
1497     // 32-bit slices as we can, and scalarize the tail.
1498     const unsigned EltSize = DL->getTypeSizeInBits(EltTy);
1499     const unsigned NumElts = FVT->getNumElements();
1500     if (EltSize == 8 || EltSize == 16) {
1501       const unsigned SubVecSize = (32 / EltSize);
1502       Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
1503       for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
1504            Idx += SubVecSize)
1505         Slices.push_back(VectorSlice{SubVecTy, Idx, SubVecSize});
1506     }
1507 
1508     // Scalarize all remaining elements.
1509     for (; Idx < NumElts; ++Idx)
1510       Slices.push_back(VectorSlice{EltTy, Idx, 1});
1511   }
1512 
1513   if (Slices.size() == 1)
1514     return false;
1515 
1516   // Break up this PHI's incoming values.
1517   for (unsigned Idx = 0; Idx < I.getNumIncomingValues(); ++Idx) {
1518     Value *Inc = I.getIncomingValue(Idx);
1519 
1520     IRBuilder<> B(I.getIncomingBlock(Idx)->getTerminator());
1521     if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
1522       B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1523 
1524     unsigned NameSuffix = 0;
1525     for (VectorSlice &S : Slices) {
1526       const auto ValName =
1527           "largephi.extractslice" + std::to_string(NameSuffix++);
1528       if (S.NumElts > 1) {
1529         SmallVector<int, 4> Mask;
1530         for (unsigned K = S.Idx; K < (S.Idx + S.NumElts); ++K)
1531           Mask.push_back(K);
1532         S.IncomingValues.push_back(B.CreateShuffleVector(Inc, Mask, ValName));
1533       } else
1534         S.IncomingValues.push_back(B.CreateExtractElement(Inc, S.Idx, ValName));
1535     }
1536   }
1537 
1538   // Now create one PHI per vector piece.
1539   IRBuilder<> B(I.getParent()->getFirstNonPHI());
1540   B.SetCurrentDebugLocation(I.getDebugLoc());
1541 
1542   for (VectorSlice &S : Slices) {
1543     S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
1544     for (const auto &[Idx, BB] : enumerate(I.blocks()))
1545       S.NewPHI->addIncoming(S.IncomingValues[Idx], BB);
1546   }
1547 
1548   // And replace this PHI with a vector of all the previous PHI values.
1549   Value *Vec = PoisonValue::get(FVT);
1550   unsigned NameSuffix = 0;
1551   for (VectorSlice &S : Slices) {
1552     const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
1553     if (S.NumElts > 1)
1554       Vec =
1555           B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
1556     else
1557       Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
1558   }
1559 
1560   I.replaceAllUsesWith(Vec);
1561   I.eraseFromParent();
1562   return true;
1563 }
1564 
1565 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) {
1566   switch (I.getIntrinsicID()) {
1567   case Intrinsic::bitreverse:
1568     return visitBitreverseIntrinsicInst(I);
1569   default:
1570     return false;
1571   }
1572 }
1573 
1574 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
1575   bool Changed = false;
1576 
1577   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1578       UA->isUniform(&I))
1579     Changed |= promoteUniformBitreverseToI32(I);
1580 
1581   return Changed;
1582 }
1583 
1584 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
1585   Mod = &M;
1586   DL = &Mod->getDataLayout();
1587   return false;
1588 }
1589 
1590 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
1591   if (skipFunction(F))
1592     return false;
1593 
1594   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1595   if (!TPC)
1596     return false;
1597 
1598   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
1599   ST = &TM.getSubtarget<GCNSubtarget>(F);
1600   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1601   UA = &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
1602 
1603   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1604   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1605 
1606   HasUnsafeFPMath = hasUnsafeFPMath(F);
1607 
1608   SIModeRegisterDefaults Mode(F);
1609   HasFP32Denormals = Mode.allFP32Denormals();
1610 
1611   bool MadeChange = false;
1612 
1613   Function::iterator NextBB;
1614   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
1615     BasicBlock *BB = &*FI;
1616     NextBB = std::next(FI);
1617 
1618     BasicBlock::iterator Next;
1619     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; I = Next) {
1620       Next = std::next(I);
1621 
1622       MadeChange |= visit(*I);
1623 
1624       if (Next != E) { // Control flow changed
1625         BasicBlock *NextInstBB = Next->getParent();
1626         if (NextInstBB != BB) {
1627           BB = NextInstBB;
1628           E = BB->end();
1629           FE = F.end();
1630         }
1631       }
1632     }
1633   }
1634 
1635   return MadeChange;
1636 }
1637 
1638 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
1639                       "AMDGPU IR optimizations", false, false)
1640 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1641 INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
1642 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
1643                     false, false)
1644 
1645 char AMDGPUCodeGenPrepare::ID = 0;
1646 
1647 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
1648   return new AMDGPUCodeGenPrepare();
1649 }
1650