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