xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp (revision 10717f92941d318b59bb6ac4c63f53723cf370d4)
1 //===- AMDGPInstCombineIntrinsic.cpp - AMDGPU specific InstCombine pass ---===//
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 file implements a TargetTransformInfo analysis pass specific to the
11 // AMDGPU target machine. It uses the target's detailed information to provide
12 // more precise answers to certain TTI queries, while letting the target
13 // independent and default TTI implementations handle the rest.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUTargetTransformInfo.h"
19 #include "GCNSubtarget.h"
20 #include "llvm/ADT/FloatingPointMode.h"
21 #include "llvm/IR/IntrinsicsAMDGPU.h"
22 #include "llvm/Transforms/InstCombine/InstCombiner.h"
23 #include <optional>
24 
25 using namespace llvm;
26 using namespace llvm::PatternMatch;
27 
28 #define DEBUG_TYPE "AMDGPUtti"
29 
30 namespace {
31 
32 struct AMDGPUImageDMaskIntrinsic {
33   unsigned Intr;
34 };
35 
36 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
37 #include "InstCombineTables.inc"
38 
39 } // end anonymous namespace
40 
41 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
42 //
43 // A single NaN input is folded to minnum, so we rely on that folding for
44 // handling NaNs.
45 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
46                            const APFloat &Src2) {
47   APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
48 
49   APFloat::cmpResult Cmp0 = Max3.compare(Src0);
50   assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
51   if (Cmp0 == APFloat::cmpEqual)
52     return maxnum(Src1, Src2);
53 
54   APFloat::cmpResult Cmp1 = Max3.compare(Src1);
55   assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
56   if (Cmp1 == APFloat::cmpEqual)
57     return maxnum(Src0, Src2);
58 
59   return maxnum(Src0, Src1);
60 }
61 
62 // Check if a value can be converted to a 16-bit value without losing
63 // precision.
64 // The value is expected to be either a float (IsFloat = true) or an unsigned
65 // integer (IsFloat = false).
66 static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat) {
67   Type *VTy = V.getType();
68   if (VTy->isHalfTy() || VTy->isIntegerTy(16)) {
69     // The value is already 16-bit, so we don't want to convert to 16-bit again!
70     return false;
71   }
72   if (IsFloat) {
73     if (ConstantFP *ConstFloat = dyn_cast<ConstantFP>(&V)) {
74       // We need to check that if we cast the index down to a half, we do not
75       // lose precision.
76       APFloat FloatValue(ConstFloat->getValueAPF());
77       bool LosesInfo = true;
78       FloatValue.convert(APFloat::IEEEhalf(), APFloat::rmTowardZero,
79                          &LosesInfo);
80       return !LosesInfo;
81     }
82   } else {
83     if (ConstantInt *ConstInt = dyn_cast<ConstantInt>(&V)) {
84       // We need to check that if we cast the index down to an i16, we do not
85       // lose precision.
86       APInt IntValue(ConstInt->getValue());
87       return IntValue.getActiveBits() <= 16;
88     }
89   }
90 
91   Value *CastSrc;
92   bool IsExt = IsFloat ? match(&V, m_FPExt(PatternMatch::m_Value(CastSrc)))
93                        : match(&V, m_ZExt(PatternMatch::m_Value(CastSrc)));
94   if (IsExt) {
95     Type *CastSrcTy = CastSrc->getType();
96     if (CastSrcTy->isHalfTy() || CastSrcTy->isIntegerTy(16))
97       return true;
98   }
99 
100   return false;
101 }
102 
103 // Convert a value to 16-bit.
104 static Value *convertTo16Bit(Value &V, InstCombiner::BuilderTy &Builder) {
105   Type *VTy = V.getType();
106   if (isa<FPExtInst>(&V) || isa<SExtInst>(&V) || isa<ZExtInst>(&V))
107     return cast<Instruction>(&V)->getOperand(0);
108   if (VTy->isIntegerTy())
109     return Builder.CreateIntCast(&V, Type::getInt16Ty(V.getContext()), false);
110   if (VTy->isFloatingPointTy())
111     return Builder.CreateFPCast(&V, Type::getHalfTy(V.getContext()));
112 
113   llvm_unreachable("Should never be called!");
114 }
115 
116 /// Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with
117 /// modified arguments (based on OldIntr) and replaces InstToReplace with
118 /// this newly created intrinsic call.
119 static std::optional<Instruction *> modifyIntrinsicCall(
120     IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr,
121     InstCombiner &IC,
122     std::function<void(SmallVectorImpl<Value *> &, SmallVectorImpl<Type *> &)>
123         Func) {
124   SmallVector<Type *, 4> ArgTys;
125   if (!Intrinsic::getIntrinsicSignature(OldIntr.getCalledFunction(), ArgTys))
126     return std::nullopt;
127 
128   SmallVector<Value *, 8> Args(OldIntr.args());
129 
130   // Modify arguments and types
131   Func(Args, ArgTys);
132 
133   Function *I = Intrinsic::getDeclaration(OldIntr.getModule(), NewIntr, ArgTys);
134 
135   CallInst *NewCall = IC.Builder.CreateCall(I, Args);
136   NewCall->takeName(&OldIntr);
137   NewCall->copyMetadata(OldIntr);
138   if (isa<FPMathOperator>(NewCall))
139     NewCall->copyFastMathFlags(&OldIntr);
140 
141   // Erase and replace uses
142   if (!InstToReplace.getType()->isVoidTy())
143     IC.replaceInstUsesWith(InstToReplace, NewCall);
144 
145   bool RemoveOldIntr = &OldIntr != &InstToReplace;
146 
147   auto RetValue = IC.eraseInstFromFunction(InstToReplace);
148   if (RemoveOldIntr)
149     IC.eraseInstFromFunction(OldIntr);
150 
151   return RetValue;
152 }
153 
154 static std::optional<Instruction *>
155 simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST,
156                              const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr,
157                              IntrinsicInst &II, InstCombiner &IC) {
158   // Optimize _L to _LZ when _L is zero
159   if (const auto *LZMappingInfo =
160           AMDGPU::getMIMGLZMappingInfo(ImageDimIntr->BaseOpcode)) {
161     if (auto *ConstantLod =
162             dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->LodIndex))) {
163       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
164         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
165             AMDGPU::getImageDimIntrinsicByBaseOpcode(LZMappingInfo->LZ,
166                                                      ImageDimIntr->Dim);
167         return modifyIntrinsicCall(
168             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
169               Args.erase(Args.begin() + ImageDimIntr->LodIndex);
170             });
171       }
172     }
173   }
174 
175   // Optimize _mip away, when 'lod' is zero
176   if (const auto *MIPMappingInfo =
177           AMDGPU::getMIMGMIPMappingInfo(ImageDimIntr->BaseOpcode)) {
178     if (auto *ConstantMip =
179             dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->MipIndex))) {
180       if (ConstantMip->isZero()) {
181         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
182             AMDGPU::getImageDimIntrinsicByBaseOpcode(MIPMappingInfo->NONMIP,
183                                                      ImageDimIntr->Dim);
184         return modifyIntrinsicCall(
185             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
186               Args.erase(Args.begin() + ImageDimIntr->MipIndex);
187             });
188       }
189     }
190   }
191 
192   // Optimize _bias away when 'bias' is zero
193   if (const auto *BiasMappingInfo =
194           AMDGPU::getMIMGBiasMappingInfo(ImageDimIntr->BaseOpcode)) {
195     if (auto *ConstantBias =
196             dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->BiasIndex))) {
197       if (ConstantBias->isZero()) {
198         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
199             AMDGPU::getImageDimIntrinsicByBaseOpcode(BiasMappingInfo->NoBias,
200                                                      ImageDimIntr->Dim);
201         return modifyIntrinsicCall(
202             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
203               Args.erase(Args.begin() + ImageDimIntr->BiasIndex);
204               ArgTys.erase(ArgTys.begin() + ImageDimIntr->BiasTyArg);
205             });
206       }
207     }
208   }
209 
210   // Optimize _offset away when 'offset' is zero
211   if (const auto *OffsetMappingInfo =
212           AMDGPU::getMIMGOffsetMappingInfo(ImageDimIntr->BaseOpcode)) {
213     if (auto *ConstantOffset =
214             dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->OffsetIndex))) {
215       if (ConstantOffset->isZero()) {
216         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
217             AMDGPU::getImageDimIntrinsicByBaseOpcode(
218                 OffsetMappingInfo->NoOffset, ImageDimIntr->Dim);
219         return modifyIntrinsicCall(
220             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
221               Args.erase(Args.begin() + ImageDimIntr->OffsetIndex);
222             });
223       }
224     }
225   }
226 
227   // Try to use D16
228   if (ST->hasD16Images()) {
229 
230     const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
231         AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode);
232 
233     if (BaseOpcode->HasD16) {
234 
235       // If the only use of image intrinsic is a fptrunc (with conversion to
236       // half) then both fptrunc and image intrinsic will be replaced with image
237       // intrinsic with D16 flag.
238       if (II.hasOneUse()) {
239         Instruction *User = II.user_back();
240 
241         if (User->getOpcode() == Instruction::FPTrunc &&
242             User->getType()->getScalarType()->isHalfTy()) {
243 
244           return modifyIntrinsicCall(II, *User, ImageDimIntr->Intr, IC,
245                                      [&](auto &Args, auto &ArgTys) {
246                                        // Change return type of image intrinsic.
247                                        // Set it to return type of fptrunc.
248                                        ArgTys[0] = User->getType();
249                                      });
250         }
251       }
252     }
253   }
254 
255   // Try to use A16 or G16
256   if (!ST->hasA16() && !ST->hasG16())
257     return std::nullopt;
258 
259   // Address is interpreted as float if the instruction has a sampler or as
260   // unsigned int if there is no sampler.
261   bool HasSampler =
262       AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode)->Sampler;
263   bool FloatCoord = false;
264   // true means derivatives can be converted to 16 bit, coordinates not
265   bool OnlyDerivatives = false;
266 
267   for (unsigned OperandIndex = ImageDimIntr->GradientStart;
268        OperandIndex < ImageDimIntr->VAddrEnd; OperandIndex++) {
269     Value *Coord = II.getOperand(OperandIndex);
270     // If the values are not derived from 16-bit values, we cannot optimize.
271     if (!canSafelyConvertTo16Bit(*Coord, HasSampler)) {
272       if (OperandIndex < ImageDimIntr->CoordStart ||
273           ImageDimIntr->GradientStart == ImageDimIntr->CoordStart) {
274         return std::nullopt;
275       }
276       // All gradients can be converted, so convert only them
277       OnlyDerivatives = true;
278       break;
279     }
280 
281     assert(OperandIndex == ImageDimIntr->GradientStart ||
282            FloatCoord == Coord->getType()->isFloatingPointTy());
283     FloatCoord = Coord->getType()->isFloatingPointTy();
284   }
285 
286   if (!OnlyDerivatives && !ST->hasA16())
287     OnlyDerivatives = true; // Only supports G16
288 
289   // Check if there is a bias parameter and if it can be converted to f16
290   if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
291     Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
292     assert(HasSampler &&
293            "Only image instructions with a sampler can have a bias");
294     if (!canSafelyConvertTo16Bit(*Bias, HasSampler))
295       OnlyDerivatives = true;
296   }
297 
298   if (OnlyDerivatives && (!ST->hasG16() || ImageDimIntr->GradientStart ==
299                                                ImageDimIntr->CoordStart))
300     return std::nullopt;
301 
302   Type *CoordType = FloatCoord ? Type::getHalfTy(II.getContext())
303                                : Type::getInt16Ty(II.getContext());
304 
305   return modifyIntrinsicCall(
306       II, II, II.getIntrinsicID(), IC, [&](auto &Args, auto &ArgTys) {
307         ArgTys[ImageDimIntr->GradientTyArg] = CoordType;
308         if (!OnlyDerivatives) {
309           ArgTys[ImageDimIntr->CoordTyArg] = CoordType;
310 
311           // Change the bias type
312           if (ImageDimIntr->NumBiasArgs != 0)
313             ArgTys[ImageDimIntr->BiasTyArg] = Type::getHalfTy(II.getContext());
314         }
315 
316         unsigned EndIndex =
317             OnlyDerivatives ? ImageDimIntr->CoordStart : ImageDimIntr->VAddrEnd;
318         for (unsigned OperandIndex = ImageDimIntr->GradientStart;
319              OperandIndex < EndIndex; OperandIndex++) {
320           Args[OperandIndex] =
321               convertTo16Bit(*II.getOperand(OperandIndex), IC.Builder);
322         }
323 
324         // Convert the bias
325         if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
326           Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
327           Args[ImageDimIntr->BiasIndex] = convertTo16Bit(*Bias, IC.Builder);
328         }
329       });
330 }
331 
332 bool GCNTTIImpl::canSimplifyLegacyMulToMul(const Instruction &I,
333                                            const Value *Op0, const Value *Op1,
334                                            InstCombiner &IC) const {
335   // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
336   // infinity, gives +0.0. If we can prove we don't have one of the special
337   // cases then we can use a normal multiply instead.
338   // TODO: Create and use isKnownFiniteNonZero instead of just matching
339   // constants here.
340   if (match(Op0, PatternMatch::m_FiniteNonZero()) ||
341       match(Op1, PatternMatch::m_FiniteNonZero())) {
342     // One operand is not zero or infinity or NaN.
343     return true;
344   }
345 
346   auto *TLI = &IC.getTargetLibraryInfo();
347   if (isKnownNeverInfOrNaN(Op0, IC.getDataLayout(), TLI, 0,
348                            &IC.getAssumptionCache(), &I,
349                            &IC.getDominatorTree()) &&
350       isKnownNeverInfOrNaN(Op1, IC.getDataLayout(), TLI, 0,
351                            &IC.getAssumptionCache(), &I,
352                            &IC.getDominatorTree())) {
353     // Neither operand is infinity or NaN.
354     return true;
355   }
356   return false;
357 }
358 
359 /// Match an fpext from half to float, or a constant we can convert.
360 static bool matchFPExtFromF16(Value *Arg, Value *&FPExtSrc) {
361   if (match(Arg, m_OneUse(m_FPExt(m_Value(FPExtSrc)))))
362     return FPExtSrc->getType()->isHalfTy();
363 
364   ConstantFP *CFP;
365   if (match(Arg, m_ConstantFP(CFP))) {
366     bool LosesInfo;
367     APFloat Val(CFP->getValueAPF());
368     Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &LosesInfo);
369     if (LosesInfo)
370       return false;
371 
372     FPExtSrc = ConstantFP::get(Type::getHalfTy(Arg->getContext()), Val);
373     return true;
374   }
375 
376   return false;
377 }
378 
379 // Trim all zero components from the end of the vector \p UseV and return
380 // an appropriate bitset with known elements.
381 static APInt trimTrailingZerosInVector(InstCombiner &IC, Value *UseV,
382                                        Instruction *I) {
383   auto *VTy = cast<FixedVectorType>(UseV->getType());
384   unsigned VWidth = VTy->getNumElements();
385   APInt DemandedElts = APInt::getAllOnes(VWidth);
386 
387   for (int i = VWidth - 1; i > 0; --i) {
388     APInt DemandOneElt = APInt::getOneBitSet(VWidth, i);
389     KnownFPClass KnownFPClass =
390         computeKnownFPClass(UseV, DemandOneElt, IC.getDataLayout(),
391                             /*InterestedClasses=*/fcAllFlags,
392                             /*Depth=*/0, &IC.getTargetLibraryInfo(),
393                             &IC.getAssumptionCache(), I,
394                             &IC.getDominatorTree());
395     if (KnownFPClass.KnownFPClasses != fcPosZero)
396       break;
397     DemandedElts.clearBit(i);
398   }
399   return DemandedElts;
400 }
401 
402 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC,
403                                                     IntrinsicInst &II,
404                                                     APInt DemandedElts,
405                                                     int DMaskIdx = -1,
406                                                     bool IsLoad = true);
407 
408 std::optional<Instruction *>
409 GCNTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
410   Intrinsic::ID IID = II.getIntrinsicID();
411   switch (IID) {
412   case Intrinsic::amdgcn_rcp: {
413     Value *Src = II.getArgOperand(0);
414 
415     // TODO: Move to ConstantFolding/InstSimplify?
416     if (isa<UndefValue>(Src)) {
417       Type *Ty = II.getType();
418       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
419       return IC.replaceInstUsesWith(II, QNaN);
420     }
421 
422     if (II.isStrictFP())
423       break;
424 
425     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
426       const APFloat &ArgVal = C->getValueAPF();
427       APFloat Val(ArgVal.getSemantics(), 1);
428       Val.divide(ArgVal, APFloat::rmNearestTiesToEven);
429 
430       // This is more precise than the instruction may give.
431       //
432       // TODO: The instruction always flushes denormal results (except for f16),
433       // should this also?
434       return IC.replaceInstUsesWith(II, ConstantFP::get(II.getContext(), Val));
435     }
436 
437     break;
438   }
439   case Intrinsic::amdgcn_sqrt:
440   case Intrinsic::amdgcn_rsq: {
441     Value *Src = II.getArgOperand(0);
442 
443     // TODO: Move to ConstantFolding/InstSimplify?
444     if (isa<UndefValue>(Src)) {
445       Type *Ty = II.getType();
446       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
447       return IC.replaceInstUsesWith(II, QNaN);
448     }
449 
450     break;
451   }
452   case Intrinsic::amdgcn_log: {
453     Value *Src = II.getArgOperand(0);
454     Type *Ty = II.getType();
455 
456     if (isa<PoisonValue>(Src))
457       return IC.replaceInstUsesWith(II, Src);
458 
459     if (IC.getSimplifyQuery().isUndefValue(Src))
460       return IC.replaceInstUsesWith(II, ConstantFP::getNaN(Ty));
461 
462     if (ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
463       if (C->isInfinity() && !C->isNegative())
464         return IC.replaceInstUsesWith(II, C);
465 
466       if (II.isStrictFP())
467         break;
468 
469       if (C->isNaN()) {
470         Constant *Quieted = ConstantFP::get(Ty, C->getValue().makeQuiet());
471         return IC.replaceInstUsesWith(II, Quieted);
472       }
473 
474       // f32 instruction doesn't handle denormals, f16 does.
475       if (C->isZero() || (C->getValue().isDenormal() && Ty->isFloatTy()))
476         return IC.replaceInstUsesWith(II, ConstantFP::getInfinity(Ty, true));
477 
478       if (C->isNegative())
479         return IC.replaceInstUsesWith(II, ConstantFP::getNaN(Ty));
480 
481       // TODO: Full constant folding matching hardware behavior.
482     }
483 
484     break;
485   }
486   case Intrinsic::amdgcn_frexp_mant:
487   case Intrinsic::amdgcn_frexp_exp: {
488     Value *Src = II.getArgOperand(0);
489     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
490       int Exp;
491       APFloat Significand =
492           frexp(C->getValueAPF(), Exp, APFloat::rmNearestTiesToEven);
493 
494       if (IID == Intrinsic::amdgcn_frexp_mant) {
495         return IC.replaceInstUsesWith(
496             II, ConstantFP::get(II.getContext(), Significand));
497       }
498 
499       // Match instruction special case behavior.
500       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
501         Exp = 0;
502 
503       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), Exp));
504     }
505 
506     if (isa<UndefValue>(Src)) {
507       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
508     }
509 
510     break;
511   }
512   case Intrinsic::amdgcn_class: {
513     Value *Src0 = II.getArgOperand(0);
514     Value *Src1 = II.getArgOperand(1);
515     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
516     if (CMask) {
517       II.setCalledOperand(Intrinsic::getDeclaration(
518           II.getModule(), Intrinsic::is_fpclass, Src0->getType()));
519 
520       // Clamp any excess bits, as they're illegal for the generic intrinsic.
521       II.setArgOperand(1, ConstantInt::get(Src1->getType(),
522                                            CMask->getZExtValue() & fcAllFlags));
523       return &II;
524     }
525 
526     // Propagate poison.
527     if (isa<PoisonValue>(Src0) || isa<PoisonValue>(Src1))
528       return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
529 
530     // llvm.amdgcn.class(_, undef) -> false
531     if (IC.getSimplifyQuery().isUndefValue(Src1))
532       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), false));
533 
534     // llvm.amdgcn.class(undef, mask) -> mask != 0
535     if (IC.getSimplifyQuery().isUndefValue(Src0)) {
536       Value *CmpMask = IC.Builder.CreateICmpNE(
537           Src1, ConstantInt::getNullValue(Src1->getType()));
538       return IC.replaceInstUsesWith(II, CmpMask);
539     }
540     break;
541   }
542   case Intrinsic::amdgcn_cvt_pkrtz: {
543     Value *Src0 = II.getArgOperand(0);
544     Value *Src1 = II.getArgOperand(1);
545     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
546       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
547         const fltSemantics &HalfSem =
548             II.getType()->getScalarType()->getFltSemantics();
549         bool LosesInfo;
550         APFloat Val0 = C0->getValueAPF();
551         APFloat Val1 = C1->getValueAPF();
552         Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
553         Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
554 
555         Constant *Folded =
556             ConstantVector::get({ConstantFP::get(II.getContext(), Val0),
557                                  ConstantFP::get(II.getContext(), Val1)});
558         return IC.replaceInstUsesWith(II, Folded);
559       }
560     }
561 
562     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
563       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
564     }
565 
566     break;
567   }
568   case Intrinsic::amdgcn_cvt_pknorm_i16:
569   case Intrinsic::amdgcn_cvt_pknorm_u16:
570   case Intrinsic::amdgcn_cvt_pk_i16:
571   case Intrinsic::amdgcn_cvt_pk_u16: {
572     Value *Src0 = II.getArgOperand(0);
573     Value *Src1 = II.getArgOperand(1);
574 
575     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
576       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
577     }
578 
579     break;
580   }
581   case Intrinsic::amdgcn_ubfe:
582   case Intrinsic::amdgcn_sbfe: {
583     // Decompose simple cases into standard shifts.
584     Value *Src = II.getArgOperand(0);
585     if (isa<UndefValue>(Src)) {
586       return IC.replaceInstUsesWith(II, Src);
587     }
588 
589     unsigned Width;
590     Type *Ty = II.getType();
591     unsigned IntSize = Ty->getIntegerBitWidth();
592 
593     ConstantInt *CWidth = dyn_cast<ConstantInt>(II.getArgOperand(2));
594     if (CWidth) {
595       Width = CWidth->getZExtValue();
596       if ((Width & (IntSize - 1)) == 0) {
597         return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(Ty));
598       }
599 
600       // Hardware ignores high bits, so remove those.
601       if (Width >= IntSize) {
602         return IC.replaceOperand(
603             II, 2, ConstantInt::get(CWidth->getType(), Width & (IntSize - 1)));
604       }
605     }
606 
607     unsigned Offset;
608     ConstantInt *COffset = dyn_cast<ConstantInt>(II.getArgOperand(1));
609     if (COffset) {
610       Offset = COffset->getZExtValue();
611       if (Offset >= IntSize) {
612         return IC.replaceOperand(
613             II, 1,
614             ConstantInt::get(COffset->getType(), Offset & (IntSize - 1)));
615       }
616     }
617 
618     bool Signed = IID == Intrinsic::amdgcn_sbfe;
619 
620     if (!CWidth || !COffset)
621       break;
622 
623     // The case of Width == 0 is handled above, which makes this transformation
624     // safe.  If Width == 0, then the ashr and lshr instructions become poison
625     // value since the shift amount would be equal to the bit size.
626     assert(Width != 0);
627 
628     // TODO: This allows folding to undef when the hardware has specific
629     // behavior?
630     if (Offset + Width < IntSize) {
631       Value *Shl = IC.Builder.CreateShl(Src, IntSize - Offset - Width);
632       Value *RightShift = Signed ? IC.Builder.CreateAShr(Shl, IntSize - Width)
633                                  : IC.Builder.CreateLShr(Shl, IntSize - Width);
634       RightShift->takeName(&II);
635       return IC.replaceInstUsesWith(II, RightShift);
636     }
637 
638     Value *RightShift = Signed ? IC.Builder.CreateAShr(Src, Offset)
639                                : IC.Builder.CreateLShr(Src, Offset);
640 
641     RightShift->takeName(&II);
642     return IC.replaceInstUsesWith(II, RightShift);
643   }
644   case Intrinsic::amdgcn_exp:
645   case Intrinsic::amdgcn_exp_row:
646   case Intrinsic::amdgcn_exp_compr: {
647     ConstantInt *En = cast<ConstantInt>(II.getArgOperand(1));
648     unsigned EnBits = En->getZExtValue();
649     if (EnBits == 0xf)
650       break; // All inputs enabled.
651 
652     bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
653     bool Changed = false;
654     for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
655       if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
656           (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
657         Value *Src = II.getArgOperand(I + 2);
658         if (!isa<UndefValue>(Src)) {
659           IC.replaceOperand(II, I + 2, UndefValue::get(Src->getType()));
660           Changed = true;
661         }
662       }
663     }
664 
665     if (Changed) {
666       return &II;
667     }
668 
669     break;
670   }
671   case Intrinsic::amdgcn_fmed3: {
672     // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
673     // for the shader.
674 
675     Value *Src0 = II.getArgOperand(0);
676     Value *Src1 = II.getArgOperand(1);
677     Value *Src2 = II.getArgOperand(2);
678 
679     // Checking for NaN before canonicalization provides better fidelity when
680     // mapping other operations onto fmed3 since the order of operands is
681     // unchanged.
682     CallInst *NewCall = nullptr;
683     if (match(Src0, PatternMatch::m_NaN()) || isa<UndefValue>(Src0)) {
684       NewCall = IC.Builder.CreateMinNum(Src1, Src2);
685     } else if (match(Src1, PatternMatch::m_NaN()) || isa<UndefValue>(Src1)) {
686       NewCall = IC.Builder.CreateMinNum(Src0, Src2);
687     } else if (match(Src2, PatternMatch::m_NaN()) || isa<UndefValue>(Src2)) {
688       NewCall = IC.Builder.CreateMaxNum(Src0, Src1);
689     }
690 
691     if (NewCall) {
692       NewCall->copyFastMathFlags(&II);
693       NewCall->takeName(&II);
694       return IC.replaceInstUsesWith(II, NewCall);
695     }
696 
697     bool Swap = false;
698     // Canonicalize constants to RHS operands.
699     //
700     // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
701     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
702       std::swap(Src0, Src1);
703       Swap = true;
704     }
705 
706     if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
707       std::swap(Src1, Src2);
708       Swap = true;
709     }
710 
711     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
712       std::swap(Src0, Src1);
713       Swap = true;
714     }
715 
716     if (Swap) {
717       II.setArgOperand(0, Src0);
718       II.setArgOperand(1, Src1);
719       II.setArgOperand(2, Src2);
720       return &II;
721     }
722 
723     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
724       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
725         if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
726           APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
727                                        C2->getValueAPF());
728           return IC.replaceInstUsesWith(
729               II, ConstantFP::get(IC.Builder.getContext(), Result));
730         }
731       }
732     }
733 
734     if (!ST->hasMed3_16())
735       break;
736 
737     Value *X, *Y, *Z;
738 
739     // Repeat floating-point width reduction done for minnum/maxnum.
740     // fmed3((fpext X), (fpext Y), (fpext Z)) -> fpext (fmed3(X, Y, Z))
741     if (matchFPExtFromF16(Src0, X) && matchFPExtFromF16(Src1, Y) &&
742         matchFPExtFromF16(Src2, Z)) {
743       Value *NewCall = IC.Builder.CreateIntrinsic(IID, {X->getType()},
744                                                   {X, Y, Z}, &II, II.getName());
745       return new FPExtInst(NewCall, II.getType());
746     }
747 
748     break;
749   }
750   case Intrinsic::amdgcn_icmp:
751   case Intrinsic::amdgcn_fcmp: {
752     const ConstantInt *CC = cast<ConstantInt>(II.getArgOperand(2));
753     // Guard against invalid arguments.
754     int64_t CCVal = CC->getZExtValue();
755     bool IsInteger = IID == Intrinsic::amdgcn_icmp;
756     if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
757                        CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
758         (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
759                         CCVal > CmpInst::LAST_FCMP_PREDICATE)))
760       break;
761 
762     Value *Src0 = II.getArgOperand(0);
763     Value *Src1 = II.getArgOperand(1);
764 
765     if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
766       if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
767         Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
768         if (CCmp->isNullValue()) {
769           return IC.replaceInstUsesWith(
770               II, ConstantExpr::getSExt(CCmp, II.getType()));
771         }
772 
773         // The result of V_ICMP/V_FCMP assembly instructions (which this
774         // intrinsic exposes) is one bit per thread, masked with the EXEC
775         // register (which contains the bitmask of live threads). So a
776         // comparison that always returns true is the same as a read of the
777         // EXEC register.
778         Function *NewF = Intrinsic::getDeclaration(
779             II.getModule(), Intrinsic::read_register, II.getType());
780         Metadata *MDArgs[] = {MDString::get(II.getContext(), "exec")};
781         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
782         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
783         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
784         NewCall->addFnAttr(Attribute::Convergent);
785         NewCall->takeName(&II);
786         return IC.replaceInstUsesWith(II, NewCall);
787       }
788 
789       // Canonicalize constants to RHS.
790       CmpInst::Predicate SwapPred =
791           CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
792       II.setArgOperand(0, Src1);
793       II.setArgOperand(1, Src0);
794       II.setArgOperand(
795           2, ConstantInt::get(CC->getType(), static_cast<int>(SwapPred)));
796       return &II;
797     }
798 
799     if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
800       break;
801 
802     // Canonicalize compare eq with true value to compare != 0
803     // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
804     //   -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
805     // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
806     //   -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
807     Value *ExtSrc;
808     if (CCVal == CmpInst::ICMP_EQ &&
809         ((match(Src1, PatternMatch::m_One()) &&
810           match(Src0, m_ZExt(PatternMatch::m_Value(ExtSrc)))) ||
811          (match(Src1, PatternMatch::m_AllOnes()) &&
812           match(Src0, m_SExt(PatternMatch::m_Value(ExtSrc))))) &&
813         ExtSrc->getType()->isIntegerTy(1)) {
814       IC.replaceOperand(II, 1, ConstantInt::getNullValue(Src1->getType()));
815       IC.replaceOperand(II, 2,
816                         ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
817       return &II;
818     }
819 
820     CmpInst::Predicate SrcPred;
821     Value *SrcLHS;
822     Value *SrcRHS;
823 
824     // Fold compare eq/ne with 0 from a compare result as the predicate to the
825     // intrinsic. The typical use is a wave vote function in the library, which
826     // will be fed from a user code condition compared with 0. Fold in the
827     // redundant compare.
828 
829     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
830     //   -> llvm.amdgcn.[if]cmp(a, b, pred)
831     //
832     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
833     //   -> llvm.amdgcn.[if]cmp(a, b, inv pred)
834     if (match(Src1, PatternMatch::m_Zero()) &&
835         match(Src0, PatternMatch::m_ZExtOrSExt(
836                         m_Cmp(SrcPred, PatternMatch::m_Value(SrcLHS),
837                               PatternMatch::m_Value(SrcRHS))))) {
838       if (CCVal == CmpInst::ICMP_EQ)
839         SrcPred = CmpInst::getInversePredicate(SrcPred);
840 
841       Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred)
842                                  ? Intrinsic::amdgcn_fcmp
843                                  : Intrinsic::amdgcn_icmp;
844 
845       Type *Ty = SrcLHS->getType();
846       if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
847         // Promote to next legal integer type.
848         unsigned Width = CmpType->getBitWidth();
849         unsigned NewWidth = Width;
850 
851         // Don't do anything for i1 comparisons.
852         if (Width == 1)
853           break;
854 
855         if (Width <= 16)
856           NewWidth = 16;
857         else if (Width <= 32)
858           NewWidth = 32;
859         else if (Width <= 64)
860           NewWidth = 64;
861         else if (Width > 64)
862           break; // Can't handle this.
863 
864         if (Width != NewWidth) {
865           IntegerType *CmpTy = IC.Builder.getIntNTy(NewWidth);
866           if (CmpInst::isSigned(SrcPred)) {
867             SrcLHS = IC.Builder.CreateSExt(SrcLHS, CmpTy);
868             SrcRHS = IC.Builder.CreateSExt(SrcRHS, CmpTy);
869           } else {
870             SrcLHS = IC.Builder.CreateZExt(SrcLHS, CmpTy);
871             SrcRHS = IC.Builder.CreateZExt(SrcRHS, CmpTy);
872           }
873         }
874       } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
875         break;
876 
877       Function *NewF = Intrinsic::getDeclaration(
878           II.getModule(), NewIID, {II.getType(), SrcLHS->getType()});
879       Value *Args[] = {SrcLHS, SrcRHS,
880                        ConstantInt::get(CC->getType(), SrcPred)};
881       CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
882       NewCall->takeName(&II);
883       return IC.replaceInstUsesWith(II, NewCall);
884     }
885 
886     break;
887   }
888   case Intrinsic::amdgcn_ballot: {
889     if (auto *Src = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
890       if (Src->isZero()) {
891         // amdgcn.ballot(i1 0) is zero.
892         return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType()));
893       }
894 
895       if (Src->isOne()) {
896         // amdgcn.ballot(i1 1) is exec.
897         const char *RegName = "exec";
898         if (II.getType()->isIntegerTy(32))
899           RegName = "exec_lo";
900         else if (!II.getType()->isIntegerTy(64))
901           break;
902 
903         Function *NewF = Intrinsic::getDeclaration(
904             II.getModule(), Intrinsic::read_register, II.getType());
905         Metadata *MDArgs[] = {MDString::get(II.getContext(), RegName)};
906         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
907         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
908         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
909         NewCall->addFnAttr(Attribute::Convergent);
910         NewCall->takeName(&II);
911         return IC.replaceInstUsesWith(II, NewCall);
912       }
913     }
914     break;
915   }
916   case Intrinsic::amdgcn_wqm_vote: {
917     // wqm_vote is identity when the argument is constant.
918     if (!isa<Constant>(II.getArgOperand(0)))
919       break;
920 
921     return IC.replaceInstUsesWith(II, II.getArgOperand(0));
922   }
923   case Intrinsic::amdgcn_kill: {
924     const ConstantInt *C = dyn_cast<ConstantInt>(II.getArgOperand(0));
925     if (!C || !C->getZExtValue())
926       break;
927 
928     // amdgcn.kill(i1 1) is a no-op
929     return IC.eraseInstFromFunction(II);
930   }
931   case Intrinsic::amdgcn_update_dpp: {
932     Value *Old = II.getArgOperand(0);
933 
934     auto *BC = cast<ConstantInt>(II.getArgOperand(5));
935     auto *RM = cast<ConstantInt>(II.getArgOperand(3));
936     auto *BM = cast<ConstantInt>(II.getArgOperand(4));
937     if (BC->isZeroValue() || RM->getZExtValue() != 0xF ||
938         BM->getZExtValue() != 0xF || isa<UndefValue>(Old))
939       break;
940 
941     // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
942     return IC.replaceOperand(II, 0, UndefValue::get(Old->getType()));
943   }
944   case Intrinsic::amdgcn_permlane16:
945   case Intrinsic::amdgcn_permlanex16: {
946     // Discard vdst_in if it's not going to be read.
947     Value *VDstIn = II.getArgOperand(0);
948     if (isa<UndefValue>(VDstIn))
949       break;
950 
951     ConstantInt *FetchInvalid = cast<ConstantInt>(II.getArgOperand(4));
952     ConstantInt *BoundCtrl = cast<ConstantInt>(II.getArgOperand(5));
953     if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
954       break;
955 
956     return IC.replaceOperand(II, 0, UndefValue::get(VDstIn->getType()));
957   }
958   case Intrinsic::amdgcn_permlane64:
959     // A constant value is trivially uniform.
960     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
961       return IC.replaceInstUsesWith(II, C);
962     }
963     break;
964   case Intrinsic::amdgcn_readfirstlane:
965   case Intrinsic::amdgcn_readlane: {
966     // A constant value is trivially uniform.
967     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
968       return IC.replaceInstUsesWith(II, C);
969     }
970 
971     // The rest of these may not be safe if the exec may not be the same between
972     // the def and use.
973     Value *Src = II.getArgOperand(0);
974     Instruction *SrcInst = dyn_cast<Instruction>(Src);
975     if (SrcInst && SrcInst->getParent() != II.getParent())
976       break;
977 
978     // readfirstlane (readfirstlane x) -> readfirstlane x
979     // readlane (readfirstlane x), y -> readfirstlane x
980     if (match(Src,
981               PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readfirstlane>())) {
982       return IC.replaceInstUsesWith(II, Src);
983     }
984 
985     if (IID == Intrinsic::amdgcn_readfirstlane) {
986       // readfirstlane (readlane x, y) -> readlane x, y
987       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>())) {
988         return IC.replaceInstUsesWith(II, Src);
989       }
990     } else {
991       // readlane (readlane x, y), y -> readlane x, y
992       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>(
993                          PatternMatch::m_Value(),
994                          PatternMatch::m_Specific(II.getArgOperand(1))))) {
995         return IC.replaceInstUsesWith(II, Src);
996       }
997     }
998 
999     break;
1000   }
1001   case Intrinsic::amdgcn_ldexp: {
1002     // FIXME: This doesn't introduce new instructions and belongs in
1003     // InstructionSimplify.
1004     Type *Ty = II.getType();
1005     Value *Op0 = II.getArgOperand(0);
1006     Value *Op1 = II.getArgOperand(1);
1007 
1008     // Folding undef to qnan is safe regardless of the FP mode.
1009     if (isa<UndefValue>(Op0)) {
1010       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
1011       return IC.replaceInstUsesWith(II, QNaN);
1012     }
1013 
1014     const APFloat *C = nullptr;
1015     match(Op0, PatternMatch::m_APFloat(C));
1016 
1017     // FIXME: Should flush denorms depending on FP mode, but that's ignored
1018     // everywhere else.
1019     //
1020     // These cases should be safe, even with strictfp.
1021     // ldexp(0.0, x) -> 0.0
1022     // ldexp(-0.0, x) -> -0.0
1023     // ldexp(inf, x) -> inf
1024     // ldexp(-inf, x) -> -inf
1025     if (C && (C->isZero() || C->isInfinity())) {
1026       return IC.replaceInstUsesWith(II, Op0);
1027     }
1028 
1029     // With strictfp, be more careful about possibly needing to flush denormals
1030     // or not, and snan behavior depends on ieee_mode.
1031     if (II.isStrictFP())
1032       break;
1033 
1034     if (C && C->isNaN())
1035       return IC.replaceInstUsesWith(II, ConstantFP::get(Ty, C->makeQuiet()));
1036 
1037     // ldexp(x, 0) -> x
1038     // ldexp(x, undef) -> x
1039     if (isa<UndefValue>(Op1) || match(Op1, PatternMatch::m_ZeroInt())) {
1040       return IC.replaceInstUsesWith(II, Op0);
1041     }
1042 
1043     break;
1044   }
1045   case Intrinsic::amdgcn_fmul_legacy: {
1046     Value *Op0 = II.getArgOperand(0);
1047     Value *Op1 = II.getArgOperand(1);
1048 
1049     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
1050     // infinity, gives +0.0.
1051     // TODO: Move to InstSimplify?
1052     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
1053         match(Op1, PatternMatch::m_AnyZeroFP()))
1054       return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType()));
1055 
1056     // If we can prove we don't have one of the special cases then we can use a
1057     // normal fmul instruction instead.
1058     if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
1059       auto *FMul = IC.Builder.CreateFMulFMF(Op0, Op1, &II);
1060       FMul->takeName(&II);
1061       return IC.replaceInstUsesWith(II, FMul);
1062     }
1063     break;
1064   }
1065   case Intrinsic::amdgcn_fma_legacy: {
1066     Value *Op0 = II.getArgOperand(0);
1067     Value *Op1 = II.getArgOperand(1);
1068     Value *Op2 = II.getArgOperand(2);
1069 
1070     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
1071     // infinity, gives +0.0.
1072     // TODO: Move to InstSimplify?
1073     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
1074         match(Op1, PatternMatch::m_AnyZeroFP())) {
1075       // It's tempting to just return Op2 here, but that would give the wrong
1076       // result if Op2 was -0.0.
1077       auto *Zero = ConstantFP::getZero(II.getType());
1078       auto *FAdd = IC.Builder.CreateFAddFMF(Zero, Op2, &II);
1079       FAdd->takeName(&II);
1080       return IC.replaceInstUsesWith(II, FAdd);
1081     }
1082 
1083     // If we can prove we don't have one of the special cases then we can use a
1084     // normal fma instead.
1085     if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
1086       II.setCalledOperand(Intrinsic::getDeclaration(
1087           II.getModule(), Intrinsic::fma, II.getType()));
1088       return &II;
1089     }
1090     break;
1091   }
1092   case Intrinsic::amdgcn_is_shared:
1093   case Intrinsic::amdgcn_is_private: {
1094     if (isa<UndefValue>(II.getArgOperand(0)))
1095       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
1096 
1097     if (isa<ConstantPointerNull>(II.getArgOperand(0)))
1098       return IC.replaceInstUsesWith(II, ConstantInt::getFalse(II.getType()));
1099     break;
1100   }
1101   case Intrinsic::amdgcn_buffer_store_format:
1102   case Intrinsic::amdgcn_raw_buffer_store_format:
1103   case Intrinsic::amdgcn_struct_buffer_store_format:
1104   case Intrinsic::amdgcn_raw_tbuffer_store:
1105   case Intrinsic::amdgcn_struct_tbuffer_store:
1106   case Intrinsic::amdgcn_tbuffer_store:
1107   case Intrinsic::amdgcn_image_store_1d:
1108   case Intrinsic::amdgcn_image_store_1darray:
1109   case Intrinsic::amdgcn_image_store_2d:
1110   case Intrinsic::amdgcn_image_store_2darray:
1111   case Intrinsic::amdgcn_image_store_2darraymsaa:
1112   case Intrinsic::amdgcn_image_store_2dmsaa:
1113   case Intrinsic::amdgcn_image_store_3d:
1114   case Intrinsic::amdgcn_image_store_cube:
1115   case Intrinsic::amdgcn_image_store_mip_1d:
1116   case Intrinsic::amdgcn_image_store_mip_1darray:
1117   case Intrinsic::amdgcn_image_store_mip_2d:
1118   case Intrinsic::amdgcn_image_store_mip_2darray:
1119   case Intrinsic::amdgcn_image_store_mip_3d:
1120   case Intrinsic::amdgcn_image_store_mip_cube: {
1121     if (!isa<FixedVectorType>(II.getArgOperand(0)->getType()))
1122       break;
1123 
1124     APInt DemandedElts =
1125         trimTrailingZerosInVector(IC, II.getArgOperand(0), &II);
1126 
1127     int DMaskIdx = getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID()) ? 1 : -1;
1128     if (simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, DMaskIdx,
1129                                               false)) {
1130       return IC.eraseInstFromFunction(II);
1131     }
1132 
1133     break;
1134   }
1135   }
1136   if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
1137             AMDGPU::getImageDimIntrinsicInfo(II.getIntrinsicID())) {
1138     return simplifyAMDGCNImageIntrinsic(ST, ImageDimIntr, II, IC);
1139   }
1140   return std::nullopt;
1141 }
1142 
1143 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
1144 ///
1145 /// The result of simplifying amdgcn image and buffer store intrinsics is updating
1146 /// definitions of the intrinsics vector argument, not Uses of the result like
1147 /// image and buffer loads.
1148 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have
1149 ///       struct returns.
1150 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC,
1151                                                     IntrinsicInst &II,
1152                                                     APInt DemandedElts,
1153                                                     int DMaskIdx, bool IsLoad) {
1154 
1155   auto *IIVTy = cast<FixedVectorType>(IsLoad ? II.getType()
1156                                              : II.getOperand(0)->getType());
1157   unsigned VWidth = IIVTy->getNumElements();
1158   if (VWidth == 1)
1159     return nullptr;
1160   Type *EltTy = IIVTy->getElementType();
1161 
1162   IRBuilderBase::InsertPointGuard Guard(IC.Builder);
1163   IC.Builder.SetInsertPoint(&II);
1164 
1165   // Assume the arguments are unchanged and later override them, if needed.
1166   SmallVector<Value *, 16> Args(II.args());
1167 
1168   if (DMaskIdx < 0) {
1169     // Buffer case.
1170 
1171     const unsigned ActiveBits = DemandedElts.getActiveBits();
1172     const unsigned UnusedComponentsAtFront = DemandedElts.countr_zero();
1173 
1174     // Start assuming the prefix of elements is demanded, but possibly clear
1175     // some other bits if there are trailing zeros (unused components at front)
1176     // and update offset.
1177     DemandedElts = (1 << ActiveBits) - 1;
1178 
1179     if (UnusedComponentsAtFront > 0) {
1180       static const unsigned InvalidOffsetIdx = 0xf;
1181 
1182       unsigned OffsetIdx;
1183       switch (II.getIntrinsicID()) {
1184       case Intrinsic::amdgcn_raw_buffer_load:
1185       case Intrinsic::amdgcn_raw_ptr_buffer_load:
1186         OffsetIdx = 1;
1187         break;
1188       case Intrinsic::amdgcn_s_buffer_load:
1189         // If resulting type is vec3, there is no point in trimming the
1190         // load with updated offset, as the vec3 would most likely be widened to
1191         // vec4 anyway during lowering.
1192         if (ActiveBits == 4 && UnusedComponentsAtFront == 1)
1193           OffsetIdx = InvalidOffsetIdx;
1194         else
1195           OffsetIdx = 1;
1196         break;
1197       case Intrinsic::amdgcn_struct_buffer_load:
1198       case Intrinsic::amdgcn_struct_ptr_buffer_load:
1199         OffsetIdx = 2;
1200         break;
1201       default:
1202         // TODO: handle tbuffer* intrinsics.
1203         OffsetIdx = InvalidOffsetIdx;
1204         break;
1205       }
1206 
1207       if (OffsetIdx != InvalidOffsetIdx) {
1208         // Clear demanded bits and update the offset.
1209         DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
1210         auto *Offset = Args[OffsetIdx];
1211         unsigned SingleComponentSizeInBits =
1212             IC.getDataLayout().getTypeSizeInBits(EltTy);
1213         unsigned OffsetAdd =
1214             UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
1215         auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
1216         Args[OffsetIdx] = IC.Builder.CreateAdd(Offset, OffsetAddVal);
1217       }
1218     }
1219   } else {
1220     // Image case.
1221 
1222     ConstantInt *DMask = cast<ConstantInt>(Args[DMaskIdx]);
1223     unsigned DMaskVal = DMask->getZExtValue() & 0xf;
1224 
1225     // Mask off values that are undefined because the dmask doesn't cover them
1226     DemandedElts &= (1 << llvm::popcount(DMaskVal)) - 1;
1227 
1228     unsigned NewDMaskVal = 0;
1229     unsigned OrigLdStIdx = 0;
1230     for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
1231       const unsigned Bit = 1 << SrcIdx;
1232       if (!!(DMaskVal & Bit)) {
1233         if (!!DemandedElts[OrigLdStIdx])
1234           NewDMaskVal |= Bit;
1235         OrigLdStIdx++;
1236       }
1237     }
1238 
1239     if (DMaskVal != NewDMaskVal)
1240       Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
1241   }
1242 
1243   unsigned NewNumElts = DemandedElts.popcount();
1244   if (!NewNumElts)
1245     return UndefValue::get(IIVTy);
1246 
1247   if (NewNumElts >= VWidth && DemandedElts.isMask()) {
1248     if (DMaskIdx >= 0)
1249       II.setArgOperand(DMaskIdx, Args[DMaskIdx]);
1250     return nullptr;
1251   }
1252 
1253   // Validate function argument and return types, extracting overloaded types
1254   // along the way.
1255   SmallVector<Type *, 6> OverloadTys;
1256   if (!Intrinsic::getIntrinsicSignature(II.getCalledFunction(), OverloadTys))
1257     return nullptr;
1258 
1259   Type *NewTy =
1260       (NewNumElts == 1) ? EltTy : FixedVectorType::get(EltTy, NewNumElts);
1261   OverloadTys[0] = NewTy;
1262 
1263   if (!IsLoad) {
1264     SmallVector<int, 8> EltMask;
1265     for (unsigned OrigStoreIdx = 0; OrigStoreIdx < VWidth; ++OrigStoreIdx)
1266       if (DemandedElts[OrigStoreIdx])
1267         EltMask.push_back(OrigStoreIdx);
1268 
1269     if (NewNumElts == 1)
1270       Args[0] = IC.Builder.CreateExtractElement(II.getOperand(0), EltMask[0]);
1271     else
1272       Args[0] = IC.Builder.CreateShuffleVector(II.getOperand(0), EltMask);
1273   }
1274 
1275   Function *NewIntrin = Intrinsic::getDeclaration(
1276       II.getModule(), II.getIntrinsicID(), OverloadTys);
1277   CallInst *NewCall = IC.Builder.CreateCall(NewIntrin, Args);
1278   NewCall->takeName(&II);
1279   NewCall->copyMetadata(II);
1280 
1281   if (IsLoad) {
1282     if (NewNumElts == 1) {
1283       return IC.Builder.CreateInsertElement(UndefValue::get(IIVTy), NewCall,
1284                                             DemandedElts.countr_zero());
1285     }
1286 
1287     SmallVector<int, 8> EltMask;
1288     unsigned NewLoadIdx = 0;
1289     for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
1290       if (!!DemandedElts[OrigLoadIdx])
1291         EltMask.push_back(NewLoadIdx++);
1292       else
1293         EltMask.push_back(NewNumElts);
1294     }
1295 
1296     auto *Shuffle = IC.Builder.CreateShuffleVector(NewCall, EltMask);
1297 
1298     return Shuffle;
1299   }
1300 
1301   return NewCall;
1302 }
1303 
1304 std::optional<Value *> GCNTTIImpl::simplifyDemandedVectorEltsIntrinsic(
1305     InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1306     APInt &UndefElts2, APInt &UndefElts3,
1307     std::function<void(Instruction *, unsigned, APInt, APInt &)>
1308         SimplifyAndSetOp) const {
1309   switch (II.getIntrinsicID()) {
1310   case Intrinsic::amdgcn_buffer_load:
1311   case Intrinsic::amdgcn_buffer_load_format:
1312   case Intrinsic::amdgcn_raw_buffer_load:
1313   case Intrinsic::amdgcn_raw_ptr_buffer_load:
1314   case Intrinsic::amdgcn_raw_buffer_load_format:
1315   case Intrinsic::amdgcn_raw_ptr_buffer_load_format:
1316   case Intrinsic::amdgcn_raw_tbuffer_load:
1317   case Intrinsic::amdgcn_raw_ptr_tbuffer_load:
1318   case Intrinsic::amdgcn_s_buffer_load:
1319   case Intrinsic::amdgcn_struct_buffer_load:
1320   case Intrinsic::amdgcn_struct_ptr_buffer_load:
1321   case Intrinsic::amdgcn_struct_buffer_load_format:
1322   case Intrinsic::amdgcn_struct_ptr_buffer_load_format:
1323   case Intrinsic::amdgcn_struct_tbuffer_load:
1324   case Intrinsic::amdgcn_struct_ptr_tbuffer_load:
1325   case Intrinsic::amdgcn_tbuffer_load:
1326     return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts);
1327   default: {
1328     if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID())) {
1329       return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, 0);
1330     }
1331     break;
1332   }
1333   }
1334   return std::nullopt;
1335 }
1336