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