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