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