xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp (revision 55635433a8ca1f3c979b4f4bbba2f97cadda09f3)
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 std::optional<Instruction *>
380 GCNTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
381   Intrinsic::ID IID = II.getIntrinsicID();
382   switch (IID) {
383   case Intrinsic::amdgcn_rcp: {
384     Value *Src = II.getArgOperand(0);
385 
386     // TODO: Move to ConstantFolding/InstSimplify?
387     if (isa<UndefValue>(Src)) {
388       Type *Ty = II.getType();
389       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
390       return IC.replaceInstUsesWith(II, QNaN);
391     }
392 
393     if (II.isStrictFP())
394       break;
395 
396     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
397       const APFloat &ArgVal = C->getValueAPF();
398       APFloat Val(ArgVal.getSemantics(), 1);
399       Val.divide(ArgVal, APFloat::rmNearestTiesToEven);
400 
401       // This is more precise than the instruction may give.
402       //
403       // TODO: The instruction always flushes denormal results (except for f16),
404       // should this also?
405       return IC.replaceInstUsesWith(II, ConstantFP::get(II.getContext(), Val));
406     }
407 
408     break;
409   }
410   case Intrinsic::amdgcn_sqrt:
411   case Intrinsic::amdgcn_rsq: {
412     Value *Src = II.getArgOperand(0);
413 
414     // TODO: Move to ConstantFolding/InstSimplify?
415     if (isa<UndefValue>(Src)) {
416       Type *Ty = II.getType();
417       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
418       return IC.replaceInstUsesWith(II, QNaN);
419     }
420 
421     break;
422   }
423   case Intrinsic::amdgcn_frexp_mant:
424   case Intrinsic::amdgcn_frexp_exp: {
425     Value *Src = II.getArgOperand(0);
426     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
427       int Exp;
428       APFloat Significand =
429           frexp(C->getValueAPF(), Exp, APFloat::rmNearestTiesToEven);
430 
431       if (IID == Intrinsic::amdgcn_frexp_mant) {
432         return IC.replaceInstUsesWith(
433             II, ConstantFP::get(II.getContext(), Significand));
434       }
435 
436       // Match instruction special case behavior.
437       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
438         Exp = 0;
439 
440       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), Exp));
441     }
442 
443     if (isa<UndefValue>(Src)) {
444       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
445     }
446 
447     break;
448   }
449   case Intrinsic::amdgcn_class: {
450     Value *Src0 = II.getArgOperand(0);
451     Value *Src1 = II.getArgOperand(1);
452     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
453     if (CMask) {
454       II.setCalledOperand(Intrinsic::getDeclaration(
455           II.getModule(), Intrinsic::is_fpclass, Src0->getType()));
456 
457       // Clamp any excess bits, as they're illegal for the generic intrinsic.
458       II.setArgOperand(1, ConstantInt::get(Src1->getType(),
459                                            CMask->getZExtValue() & fcAllFlags));
460       return &II;
461     }
462 
463     // Propagate poison.
464     if (isa<PoisonValue>(Src0) || isa<PoisonValue>(Src1))
465       return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
466 
467     // llvm.amdgcn.class(_, undef) -> false
468     if (IC.getSimplifyQuery().isUndefValue(Src1))
469       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), false));
470 
471     // llvm.amdgcn.class(undef, mask) -> mask != 0
472     if (IC.getSimplifyQuery().isUndefValue(Src0)) {
473       Value *CmpMask = IC.Builder.CreateICmpNE(
474           Src1, ConstantInt::getNullValue(Src1->getType()));
475       return IC.replaceInstUsesWith(II, CmpMask);
476     }
477     break;
478   }
479   case Intrinsic::amdgcn_cvt_pkrtz: {
480     Value *Src0 = II.getArgOperand(0);
481     Value *Src1 = II.getArgOperand(1);
482     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
483       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
484         const fltSemantics &HalfSem =
485             II.getType()->getScalarType()->getFltSemantics();
486         bool LosesInfo;
487         APFloat Val0 = C0->getValueAPF();
488         APFloat Val1 = C1->getValueAPF();
489         Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
490         Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
491 
492         Constant *Folded =
493             ConstantVector::get({ConstantFP::get(II.getContext(), Val0),
494                                  ConstantFP::get(II.getContext(), Val1)});
495         return IC.replaceInstUsesWith(II, Folded);
496       }
497     }
498 
499     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
500       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
501     }
502 
503     break;
504   }
505   case Intrinsic::amdgcn_cvt_pknorm_i16:
506   case Intrinsic::amdgcn_cvt_pknorm_u16:
507   case Intrinsic::amdgcn_cvt_pk_i16:
508   case Intrinsic::amdgcn_cvt_pk_u16: {
509     Value *Src0 = II.getArgOperand(0);
510     Value *Src1 = II.getArgOperand(1);
511 
512     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
513       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
514     }
515 
516     break;
517   }
518   case Intrinsic::amdgcn_ubfe:
519   case Intrinsic::amdgcn_sbfe: {
520     // Decompose simple cases into standard shifts.
521     Value *Src = II.getArgOperand(0);
522     if (isa<UndefValue>(Src)) {
523       return IC.replaceInstUsesWith(II, Src);
524     }
525 
526     unsigned Width;
527     Type *Ty = II.getType();
528     unsigned IntSize = Ty->getIntegerBitWidth();
529 
530     ConstantInt *CWidth = dyn_cast<ConstantInt>(II.getArgOperand(2));
531     if (CWidth) {
532       Width = CWidth->getZExtValue();
533       if ((Width & (IntSize - 1)) == 0) {
534         return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(Ty));
535       }
536 
537       // Hardware ignores high bits, so remove those.
538       if (Width >= IntSize) {
539         return IC.replaceOperand(
540             II, 2, ConstantInt::get(CWidth->getType(), Width & (IntSize - 1)));
541       }
542     }
543 
544     unsigned Offset;
545     ConstantInt *COffset = dyn_cast<ConstantInt>(II.getArgOperand(1));
546     if (COffset) {
547       Offset = COffset->getZExtValue();
548       if (Offset >= IntSize) {
549         return IC.replaceOperand(
550             II, 1,
551             ConstantInt::get(COffset->getType(), Offset & (IntSize - 1)));
552       }
553     }
554 
555     bool Signed = IID == Intrinsic::amdgcn_sbfe;
556 
557     if (!CWidth || !COffset)
558       break;
559 
560     // The case of Width == 0 is handled above, which makes this transformation
561     // safe.  If Width == 0, then the ashr and lshr instructions become poison
562     // value since the shift amount would be equal to the bit size.
563     assert(Width != 0);
564 
565     // TODO: This allows folding to undef when the hardware has specific
566     // behavior?
567     if (Offset + Width < IntSize) {
568       Value *Shl = IC.Builder.CreateShl(Src, IntSize - Offset - Width);
569       Value *RightShift = Signed ? IC.Builder.CreateAShr(Shl, IntSize - Width)
570                                  : IC.Builder.CreateLShr(Shl, IntSize - Width);
571       RightShift->takeName(&II);
572       return IC.replaceInstUsesWith(II, RightShift);
573     }
574 
575     Value *RightShift = Signed ? IC.Builder.CreateAShr(Src, Offset)
576                                : IC.Builder.CreateLShr(Src, Offset);
577 
578     RightShift->takeName(&II);
579     return IC.replaceInstUsesWith(II, RightShift);
580   }
581   case Intrinsic::amdgcn_exp:
582   case Intrinsic::amdgcn_exp_row:
583   case Intrinsic::amdgcn_exp_compr: {
584     ConstantInt *En = cast<ConstantInt>(II.getArgOperand(1));
585     unsigned EnBits = En->getZExtValue();
586     if (EnBits == 0xf)
587       break; // All inputs enabled.
588 
589     bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
590     bool Changed = false;
591     for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
592       if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
593           (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
594         Value *Src = II.getArgOperand(I + 2);
595         if (!isa<UndefValue>(Src)) {
596           IC.replaceOperand(II, I + 2, UndefValue::get(Src->getType()));
597           Changed = true;
598         }
599       }
600     }
601 
602     if (Changed) {
603       return &II;
604     }
605 
606     break;
607   }
608   case Intrinsic::amdgcn_fmed3: {
609     // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
610     // for the shader.
611 
612     Value *Src0 = II.getArgOperand(0);
613     Value *Src1 = II.getArgOperand(1);
614     Value *Src2 = II.getArgOperand(2);
615 
616     // Checking for NaN before canonicalization provides better fidelity when
617     // mapping other operations onto fmed3 since the order of operands is
618     // unchanged.
619     CallInst *NewCall = nullptr;
620     if (match(Src0, PatternMatch::m_NaN()) || isa<UndefValue>(Src0)) {
621       NewCall = IC.Builder.CreateMinNum(Src1, Src2);
622     } else if (match(Src1, PatternMatch::m_NaN()) || isa<UndefValue>(Src1)) {
623       NewCall = IC.Builder.CreateMinNum(Src0, Src2);
624     } else if (match(Src2, PatternMatch::m_NaN()) || isa<UndefValue>(Src2)) {
625       NewCall = IC.Builder.CreateMaxNum(Src0, Src1);
626     }
627 
628     if (NewCall) {
629       NewCall->copyFastMathFlags(&II);
630       NewCall->takeName(&II);
631       return IC.replaceInstUsesWith(II, NewCall);
632     }
633 
634     bool Swap = false;
635     // Canonicalize constants to RHS operands.
636     //
637     // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
638     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
639       std::swap(Src0, Src1);
640       Swap = true;
641     }
642 
643     if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
644       std::swap(Src1, Src2);
645       Swap = true;
646     }
647 
648     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
649       std::swap(Src0, Src1);
650       Swap = true;
651     }
652 
653     if (Swap) {
654       II.setArgOperand(0, Src0);
655       II.setArgOperand(1, Src1);
656       II.setArgOperand(2, Src2);
657       return &II;
658     }
659 
660     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
661       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
662         if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
663           APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
664                                        C2->getValueAPF());
665           return IC.replaceInstUsesWith(
666               II, ConstantFP::get(IC.Builder.getContext(), Result));
667         }
668       }
669     }
670 
671     if (!ST->hasMed3_16())
672       break;
673 
674     Value *X, *Y, *Z;
675 
676     // Repeat floating-point width reduction done for minnum/maxnum.
677     // fmed3((fpext X), (fpext Y), (fpext Z)) -> fpext (fmed3(X, Y, Z))
678     if (matchFPExtFromF16(Src0, X) && matchFPExtFromF16(Src1, Y) &&
679         matchFPExtFromF16(Src2, Z)) {
680       Value *NewCall = IC.Builder.CreateIntrinsic(IID, {X->getType()},
681                                                   {X, Y, Z}, &II, II.getName());
682       return new FPExtInst(NewCall, II.getType());
683     }
684 
685     break;
686   }
687   case Intrinsic::amdgcn_icmp:
688   case Intrinsic::amdgcn_fcmp: {
689     const ConstantInt *CC = cast<ConstantInt>(II.getArgOperand(2));
690     // Guard against invalid arguments.
691     int64_t CCVal = CC->getZExtValue();
692     bool IsInteger = IID == Intrinsic::amdgcn_icmp;
693     if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
694                        CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
695         (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
696                         CCVal > CmpInst::LAST_FCMP_PREDICATE)))
697       break;
698 
699     Value *Src0 = II.getArgOperand(0);
700     Value *Src1 = II.getArgOperand(1);
701 
702     if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
703       if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
704         Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
705         if (CCmp->isNullValue()) {
706           return IC.replaceInstUsesWith(
707               II, ConstantExpr::getSExt(CCmp, II.getType()));
708         }
709 
710         // The result of V_ICMP/V_FCMP assembly instructions (which this
711         // intrinsic exposes) is one bit per thread, masked with the EXEC
712         // register (which contains the bitmask of live threads). So a
713         // comparison that always returns true is the same as a read of the
714         // EXEC register.
715         Function *NewF = Intrinsic::getDeclaration(
716             II.getModule(), Intrinsic::read_register, II.getType());
717         Metadata *MDArgs[] = {MDString::get(II.getContext(), "exec")};
718         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
719         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
720         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
721         NewCall->addFnAttr(Attribute::Convergent);
722         NewCall->takeName(&II);
723         return IC.replaceInstUsesWith(II, NewCall);
724       }
725 
726       // Canonicalize constants to RHS.
727       CmpInst::Predicate SwapPred =
728           CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
729       II.setArgOperand(0, Src1);
730       II.setArgOperand(1, Src0);
731       II.setArgOperand(
732           2, ConstantInt::get(CC->getType(), static_cast<int>(SwapPred)));
733       return &II;
734     }
735 
736     if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
737       break;
738 
739     // Canonicalize compare eq with true value to compare != 0
740     // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
741     //   -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
742     // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
743     //   -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
744     Value *ExtSrc;
745     if (CCVal == CmpInst::ICMP_EQ &&
746         ((match(Src1, PatternMatch::m_One()) &&
747           match(Src0, m_ZExt(PatternMatch::m_Value(ExtSrc)))) ||
748          (match(Src1, PatternMatch::m_AllOnes()) &&
749           match(Src0, m_SExt(PatternMatch::m_Value(ExtSrc))))) &&
750         ExtSrc->getType()->isIntegerTy(1)) {
751       IC.replaceOperand(II, 1, ConstantInt::getNullValue(Src1->getType()));
752       IC.replaceOperand(II, 2,
753                         ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
754       return &II;
755     }
756 
757     CmpInst::Predicate SrcPred;
758     Value *SrcLHS;
759     Value *SrcRHS;
760 
761     // Fold compare eq/ne with 0 from a compare result as the predicate to the
762     // intrinsic. The typical use is a wave vote function in the library, which
763     // will be fed from a user code condition compared with 0. Fold in the
764     // redundant compare.
765 
766     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
767     //   -> llvm.amdgcn.[if]cmp(a, b, pred)
768     //
769     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
770     //   -> llvm.amdgcn.[if]cmp(a, b, inv pred)
771     if (match(Src1, PatternMatch::m_Zero()) &&
772         match(Src0, PatternMatch::m_ZExtOrSExt(
773                         m_Cmp(SrcPred, PatternMatch::m_Value(SrcLHS),
774                               PatternMatch::m_Value(SrcRHS))))) {
775       if (CCVal == CmpInst::ICMP_EQ)
776         SrcPred = CmpInst::getInversePredicate(SrcPred);
777 
778       Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred)
779                                  ? Intrinsic::amdgcn_fcmp
780                                  : Intrinsic::amdgcn_icmp;
781 
782       Type *Ty = SrcLHS->getType();
783       if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
784         // Promote to next legal integer type.
785         unsigned Width = CmpType->getBitWidth();
786         unsigned NewWidth = Width;
787 
788         // Don't do anything for i1 comparisons.
789         if (Width == 1)
790           break;
791 
792         if (Width <= 16)
793           NewWidth = 16;
794         else if (Width <= 32)
795           NewWidth = 32;
796         else if (Width <= 64)
797           NewWidth = 64;
798         else if (Width > 64)
799           break; // Can't handle this.
800 
801         if (Width != NewWidth) {
802           IntegerType *CmpTy = IC.Builder.getIntNTy(NewWidth);
803           if (CmpInst::isSigned(SrcPred)) {
804             SrcLHS = IC.Builder.CreateSExt(SrcLHS, CmpTy);
805             SrcRHS = IC.Builder.CreateSExt(SrcRHS, CmpTy);
806           } else {
807             SrcLHS = IC.Builder.CreateZExt(SrcLHS, CmpTy);
808             SrcRHS = IC.Builder.CreateZExt(SrcRHS, CmpTy);
809           }
810         }
811       } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
812         break;
813 
814       Function *NewF = Intrinsic::getDeclaration(
815           II.getModule(), NewIID, {II.getType(), SrcLHS->getType()});
816       Value *Args[] = {SrcLHS, SrcRHS,
817                        ConstantInt::get(CC->getType(), SrcPred)};
818       CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
819       NewCall->takeName(&II);
820       return IC.replaceInstUsesWith(II, NewCall);
821     }
822 
823     break;
824   }
825   case Intrinsic::amdgcn_ballot: {
826     if (auto *Src = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
827       if (Src->isZero()) {
828         // amdgcn.ballot(i1 0) is zero.
829         return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType()));
830       }
831 
832       if (Src->isOne()) {
833         // amdgcn.ballot(i1 1) is exec.
834         const char *RegName = "exec";
835         if (II.getType()->isIntegerTy(32))
836           RegName = "exec_lo";
837         else if (!II.getType()->isIntegerTy(64))
838           break;
839 
840         Function *NewF = Intrinsic::getDeclaration(
841             II.getModule(), Intrinsic::read_register, II.getType());
842         Metadata *MDArgs[] = {MDString::get(II.getContext(), RegName)};
843         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
844         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
845         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
846         NewCall->addFnAttr(Attribute::Convergent);
847         NewCall->takeName(&II);
848         return IC.replaceInstUsesWith(II, NewCall);
849       }
850     }
851     break;
852   }
853   case Intrinsic::amdgcn_wqm_vote: {
854     // wqm_vote is identity when the argument is constant.
855     if (!isa<Constant>(II.getArgOperand(0)))
856       break;
857 
858     return IC.replaceInstUsesWith(II, II.getArgOperand(0));
859   }
860   case Intrinsic::amdgcn_kill: {
861     const ConstantInt *C = dyn_cast<ConstantInt>(II.getArgOperand(0));
862     if (!C || !C->getZExtValue())
863       break;
864 
865     // amdgcn.kill(i1 1) is a no-op
866     return IC.eraseInstFromFunction(II);
867   }
868   case Intrinsic::amdgcn_update_dpp: {
869     Value *Old = II.getArgOperand(0);
870 
871     auto *BC = cast<ConstantInt>(II.getArgOperand(5));
872     auto *RM = cast<ConstantInt>(II.getArgOperand(3));
873     auto *BM = cast<ConstantInt>(II.getArgOperand(4));
874     if (BC->isZeroValue() || RM->getZExtValue() != 0xF ||
875         BM->getZExtValue() != 0xF || isa<UndefValue>(Old))
876       break;
877 
878     // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
879     return IC.replaceOperand(II, 0, UndefValue::get(Old->getType()));
880   }
881   case Intrinsic::amdgcn_permlane16:
882   case Intrinsic::amdgcn_permlanex16: {
883     // Discard vdst_in if it's not going to be read.
884     Value *VDstIn = II.getArgOperand(0);
885     if (isa<UndefValue>(VDstIn))
886       break;
887 
888     ConstantInt *FetchInvalid = cast<ConstantInt>(II.getArgOperand(4));
889     ConstantInt *BoundCtrl = cast<ConstantInt>(II.getArgOperand(5));
890     if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
891       break;
892 
893     return IC.replaceOperand(II, 0, UndefValue::get(VDstIn->getType()));
894   }
895   case Intrinsic::amdgcn_permlane64:
896     // A constant value is trivially uniform.
897     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
898       return IC.replaceInstUsesWith(II, C);
899     }
900     break;
901   case Intrinsic::amdgcn_readfirstlane:
902   case Intrinsic::amdgcn_readlane: {
903     // A constant value is trivially uniform.
904     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
905       return IC.replaceInstUsesWith(II, C);
906     }
907 
908     // The rest of these may not be safe if the exec may not be the same between
909     // the def and use.
910     Value *Src = II.getArgOperand(0);
911     Instruction *SrcInst = dyn_cast<Instruction>(Src);
912     if (SrcInst && SrcInst->getParent() != II.getParent())
913       break;
914 
915     // readfirstlane (readfirstlane x) -> readfirstlane x
916     // readlane (readfirstlane x), y -> readfirstlane x
917     if (match(Src,
918               PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readfirstlane>())) {
919       return IC.replaceInstUsesWith(II, Src);
920     }
921 
922     if (IID == Intrinsic::amdgcn_readfirstlane) {
923       // readfirstlane (readlane x, y) -> readlane x, y
924       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>())) {
925         return IC.replaceInstUsesWith(II, Src);
926       }
927     } else {
928       // readlane (readlane x, y), y -> readlane x, y
929       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>(
930                          PatternMatch::m_Value(),
931                          PatternMatch::m_Specific(II.getArgOperand(1))))) {
932         return IC.replaceInstUsesWith(II, Src);
933       }
934     }
935 
936     break;
937   }
938   case Intrinsic::amdgcn_ldexp: {
939     // FIXME: This doesn't introduce new instructions and belongs in
940     // InstructionSimplify.
941     Type *Ty = II.getType();
942     Value *Op0 = II.getArgOperand(0);
943     Value *Op1 = II.getArgOperand(1);
944 
945     // Folding undef to qnan is safe regardless of the FP mode.
946     if (isa<UndefValue>(Op0)) {
947       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
948       return IC.replaceInstUsesWith(II, QNaN);
949     }
950 
951     const APFloat *C = nullptr;
952     match(Op0, PatternMatch::m_APFloat(C));
953 
954     // FIXME: Should flush denorms depending on FP mode, but that's ignored
955     // everywhere else.
956     //
957     // These cases should be safe, even with strictfp.
958     // ldexp(0.0, x) -> 0.0
959     // ldexp(-0.0, x) -> -0.0
960     // ldexp(inf, x) -> inf
961     // ldexp(-inf, x) -> -inf
962     if (C && (C->isZero() || C->isInfinity())) {
963       return IC.replaceInstUsesWith(II, Op0);
964     }
965 
966     // With strictfp, be more careful about possibly needing to flush denormals
967     // or not, and snan behavior depends on ieee_mode.
968     if (II.isStrictFP())
969       break;
970 
971     if (C && C->isNaN())
972       return IC.replaceInstUsesWith(II, ConstantFP::get(Ty, C->makeQuiet()));
973 
974     // ldexp(x, 0) -> x
975     // ldexp(x, undef) -> x
976     if (isa<UndefValue>(Op1) || match(Op1, PatternMatch::m_ZeroInt())) {
977       return IC.replaceInstUsesWith(II, Op0);
978     }
979 
980     break;
981   }
982   case Intrinsic::amdgcn_fmul_legacy: {
983     Value *Op0 = II.getArgOperand(0);
984     Value *Op1 = II.getArgOperand(1);
985 
986     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
987     // infinity, gives +0.0.
988     // TODO: Move to InstSimplify?
989     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
990         match(Op1, PatternMatch::m_AnyZeroFP()))
991       return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType()));
992 
993     // If we can prove we don't have one of the special cases then we can use a
994     // normal fmul instruction instead.
995     if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
996       auto *FMul = IC.Builder.CreateFMulFMF(Op0, Op1, &II);
997       FMul->takeName(&II);
998       return IC.replaceInstUsesWith(II, FMul);
999     }
1000     break;
1001   }
1002   case Intrinsic::amdgcn_fma_legacy: {
1003     Value *Op0 = II.getArgOperand(0);
1004     Value *Op1 = II.getArgOperand(1);
1005     Value *Op2 = II.getArgOperand(2);
1006 
1007     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
1008     // infinity, gives +0.0.
1009     // TODO: Move to InstSimplify?
1010     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
1011         match(Op1, PatternMatch::m_AnyZeroFP())) {
1012       // It's tempting to just return Op2 here, but that would give the wrong
1013       // result if Op2 was -0.0.
1014       auto *Zero = ConstantFP::getZero(II.getType());
1015       auto *FAdd = IC.Builder.CreateFAddFMF(Zero, Op2, &II);
1016       FAdd->takeName(&II);
1017       return IC.replaceInstUsesWith(II, FAdd);
1018     }
1019 
1020     // If we can prove we don't have one of the special cases then we can use a
1021     // normal fma instead.
1022     if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
1023       II.setCalledOperand(Intrinsic::getDeclaration(
1024           II.getModule(), Intrinsic::fma, II.getType()));
1025       return &II;
1026     }
1027     break;
1028   }
1029   case Intrinsic::amdgcn_is_shared:
1030   case Intrinsic::amdgcn_is_private: {
1031     if (isa<UndefValue>(II.getArgOperand(0)))
1032       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
1033 
1034     if (isa<ConstantPointerNull>(II.getArgOperand(0)))
1035       return IC.replaceInstUsesWith(II, ConstantInt::getFalse(II.getType()));
1036     break;
1037   }
1038   default: {
1039     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
1040             AMDGPU::getImageDimIntrinsicInfo(II.getIntrinsicID())) {
1041       return simplifyAMDGCNImageIntrinsic(ST, ImageDimIntr, II, IC);
1042     }
1043   }
1044   }
1045   return std::nullopt;
1046 }
1047 
1048 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
1049 ///
1050 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have
1051 ///       struct returns.
1052 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC,
1053                                                     IntrinsicInst &II,
1054                                                     APInt DemandedElts,
1055                                                     int DMaskIdx = -1) {
1056 
1057   auto *IIVTy = cast<FixedVectorType>(II.getType());
1058   unsigned VWidth = IIVTy->getNumElements();
1059   if (VWidth == 1)
1060     return nullptr;
1061   Type *EltTy = IIVTy->getElementType();
1062 
1063   IRBuilderBase::InsertPointGuard Guard(IC.Builder);
1064   IC.Builder.SetInsertPoint(&II);
1065 
1066   // Assume the arguments are unchanged and later override them, if needed.
1067   SmallVector<Value *, 16> Args(II.args());
1068 
1069   if (DMaskIdx < 0) {
1070     // Buffer case.
1071 
1072     const unsigned ActiveBits = DemandedElts.getActiveBits();
1073     const unsigned UnusedComponentsAtFront = DemandedElts.countr_zero();
1074 
1075     // Start assuming the prefix of elements is demanded, but possibly clear
1076     // some other bits if there are trailing zeros (unused components at front)
1077     // and update offset.
1078     DemandedElts = (1 << ActiveBits) - 1;
1079 
1080     if (UnusedComponentsAtFront > 0) {
1081       static const unsigned InvalidOffsetIdx = 0xf;
1082 
1083       unsigned OffsetIdx;
1084       switch (II.getIntrinsicID()) {
1085       case Intrinsic::amdgcn_raw_buffer_load:
1086         OffsetIdx = 1;
1087         break;
1088       case Intrinsic::amdgcn_s_buffer_load:
1089         // If resulting type is vec3, there is no point in trimming the
1090         // load with updated offset, as the vec3 would most likely be widened to
1091         // vec4 anyway during lowering.
1092         if (ActiveBits == 4 && UnusedComponentsAtFront == 1)
1093           OffsetIdx = InvalidOffsetIdx;
1094         else
1095           OffsetIdx = 1;
1096         break;
1097       case Intrinsic::amdgcn_struct_buffer_load:
1098         OffsetIdx = 2;
1099         break;
1100       default:
1101         // TODO: handle tbuffer* intrinsics.
1102         OffsetIdx = InvalidOffsetIdx;
1103         break;
1104       }
1105 
1106       if (OffsetIdx != InvalidOffsetIdx) {
1107         // Clear demanded bits and update the offset.
1108         DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
1109         auto *Offset = Args[OffsetIdx];
1110         unsigned SingleComponentSizeInBits =
1111             IC.getDataLayout().getTypeSizeInBits(EltTy);
1112         unsigned OffsetAdd =
1113             UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
1114         auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
1115         Args[OffsetIdx] = IC.Builder.CreateAdd(Offset, OffsetAddVal);
1116       }
1117     }
1118   } else {
1119     // Image case.
1120 
1121     ConstantInt *DMask = cast<ConstantInt>(Args[DMaskIdx]);
1122     unsigned DMaskVal = DMask->getZExtValue() & 0xf;
1123 
1124     // Mask off values that are undefined because the dmask doesn't cover them
1125     DemandedElts &= (1 << llvm::popcount(DMaskVal)) - 1;
1126 
1127     unsigned NewDMaskVal = 0;
1128     unsigned OrigLoadIdx = 0;
1129     for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
1130       const unsigned Bit = 1 << SrcIdx;
1131       if (!!(DMaskVal & Bit)) {
1132         if (!!DemandedElts[OrigLoadIdx])
1133           NewDMaskVal |= Bit;
1134         OrigLoadIdx++;
1135       }
1136     }
1137 
1138     if (DMaskVal != NewDMaskVal)
1139       Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
1140   }
1141 
1142   unsigned NewNumElts = DemandedElts.popcount();
1143   if (!NewNumElts)
1144     return UndefValue::get(IIVTy);
1145 
1146   if (NewNumElts >= VWidth && DemandedElts.isMask()) {
1147     if (DMaskIdx >= 0)
1148       II.setArgOperand(DMaskIdx, Args[DMaskIdx]);
1149     return nullptr;
1150   }
1151 
1152   // Validate function argument and return types, extracting overloaded types
1153   // along the way.
1154   SmallVector<Type *, 6> OverloadTys;
1155   if (!Intrinsic::getIntrinsicSignature(II.getCalledFunction(), OverloadTys))
1156     return nullptr;
1157 
1158   Type *NewTy =
1159       (NewNumElts == 1) ? EltTy : FixedVectorType::get(EltTy, NewNumElts);
1160   OverloadTys[0] = NewTy;
1161 
1162   Function *NewIntrin = Intrinsic::getDeclaration(
1163       II.getModule(), II.getIntrinsicID(), OverloadTys);
1164   CallInst *NewCall = IC.Builder.CreateCall(NewIntrin, Args);
1165   NewCall->takeName(&II);
1166   NewCall->copyMetadata(II);
1167 
1168   if (NewNumElts == 1) {
1169     return IC.Builder.CreateInsertElement(UndefValue::get(IIVTy), NewCall,
1170                                           DemandedElts.countr_zero());
1171   }
1172 
1173   SmallVector<int, 8> EltMask;
1174   unsigned NewLoadIdx = 0;
1175   for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
1176     if (!!DemandedElts[OrigLoadIdx])
1177       EltMask.push_back(NewLoadIdx++);
1178     else
1179       EltMask.push_back(NewNumElts);
1180   }
1181 
1182   Value *Shuffle = IC.Builder.CreateShuffleVector(NewCall, EltMask);
1183 
1184   return Shuffle;
1185 }
1186 
1187 std::optional<Value *> GCNTTIImpl::simplifyDemandedVectorEltsIntrinsic(
1188     InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1189     APInt &UndefElts2, APInt &UndefElts3,
1190     std::function<void(Instruction *, unsigned, APInt, APInt &)>
1191         SimplifyAndSetOp) const {
1192   switch (II.getIntrinsicID()) {
1193   case Intrinsic::amdgcn_buffer_load:
1194   case Intrinsic::amdgcn_buffer_load_format:
1195   case Intrinsic::amdgcn_raw_buffer_load:
1196   case Intrinsic::amdgcn_raw_buffer_load_format:
1197   case Intrinsic::amdgcn_raw_tbuffer_load:
1198   case Intrinsic::amdgcn_s_buffer_load:
1199   case Intrinsic::amdgcn_struct_buffer_load:
1200   case Intrinsic::amdgcn_struct_buffer_load_format:
1201   case Intrinsic::amdgcn_struct_tbuffer_load:
1202   case Intrinsic::amdgcn_tbuffer_load:
1203     return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts);
1204   default: {
1205     if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID())) {
1206       return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, 0);
1207     }
1208     break;
1209   }
1210   }
1211   return std::nullopt;
1212 }
1213