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