LLVM 24.0.0git
AMDGPUInstCombineIntrinsic.cpp
Go to the documentation of this file.
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"
19#include "GCNSubtarget.h"
20#include "SIDefines.h"
23#include "llvm/ADT/STLExtras.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/IntrinsicsAMDGPU.h"
31#include <optional>
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "AMDGPUtti"
37
38namespace {
39
40struct AMDGPUImageDMaskIntrinsic {
41 unsigned Intr;
42};
43
44#define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
45#include "AMDGPUGenSearchableTables.inc"
46
47} // end anonymous namespace
48
49// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
50//
51// A single NaN input is folded to minnum, so we rely on that folding for
52// handling NaNs.
53static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
54 const APFloat &Src2) {
55 assert(!Src0.isNaN() && !Src1.isNaN() && !Src2.isNaN() &&
56 "nans handled separately");
57 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
58
59 if (Max3.bitwiseIsEqual(Src0))
60 return maxnum(Src1, Src2);
61
62 if (Max3.bitwiseIsEqual(Src1))
63 return maxnum(Src0, Src2);
64
65 return maxnum(Src0, Src1);
66}
67
68// Check if a value can be converted to a 16-bit value without losing precision.
69// The value is expected to be either a float (IsFloat = true) or an unsigned
70// integer (IsFloat = false). When AllowI16SExt is set, a sext from i16 is also
71// accepted: for unsigned addresses sext and zext only differ for a negative
72// i16, which is out of bounds anyway (see caller).
73static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat,
74 bool AllowI16SExt = false) {
75 Type *VTy = V.getType();
76 if (VTy->isHalfTy() || VTy->isIntegerTy(16)) {
77 // The value is already 16-bit, so we don't want to convert to 16-bit again!
78 return false;
79 }
80 if (IsFloat) {
81 if (ConstantFP *ConstFloat = dyn_cast<ConstantFP>(&V)) {
82 // We need to check that if we cast the index down to a half, we do not
83 // lose precision.
84 APFloat FloatValue(ConstFloat->getValueAPF());
85 bool LosesInfo = true;
87 &LosesInfo);
88 return !LosesInfo;
89 }
90 } else {
91 if (ConstantInt *ConstInt = dyn_cast<ConstantInt>(&V)) {
92 // We need to check that if we cast the index down to an i16, we do not
93 // lose precision.
94 APInt IntValue(ConstInt->getValue());
95 return IntValue.getActiveBits() <= 16;
96 }
97 }
98
99 // Coordinates may arrive as extractelement((s|z|fp)ext Vec), Idx. The
100 // widening cast has one use per lane, so it is never sunk into the extract;
101 // strip the extract here so the cast check below is common to scalar and
102 // vector coords.
103 Value *CastCandidate;
104 if (!match(&V, m_ExtractElt(m_Value(CastCandidate), m_Value())))
105 CastCandidate = &V;
106
107 Value *CastSrc;
108 bool IsExt = IsFloat ? match(CastCandidate, m_FPExt(m_Value(CastSrc)))
109 : match(CastCandidate, m_ZExt(m_Value(CastSrc)));
110 if (!IsExt && !IsFloat && AllowI16SExt)
111 IsExt = match(CastCandidate, m_SExt(m_Value(CastSrc)));
112 if (IsExt) {
113 Type *CastSrcTy = CastSrc->getType()->getScalarType();
114 if (CastSrcTy->isHalfTy() || CastSrcTy->isIntegerTy(16))
115 return true;
116 }
117
118 return false;
119}
120
121// Convert a value to 16-bit.
123 Type *VTy = V.getType();
125 return cast<Instruction>(&V)->getOperand(0);
126 // Vector form: extractelement((s|z|fp)ext Vec), Idx -> extractelement(Vec,
127 // Idx), taking the narrow lane directly so the widening cast can be removed.
128 Instruction *VecCast;
129 Value *Idx;
130 if (match(&V, m_ExtractElt(m_Instruction(VecCast), m_Value(Idx))) &&
132 return Builder.CreateExtractElement(VecCast->getOperand(0), Idx);
133 if (VTy->isIntegerTy())
134 return Builder.CreateIntCast(&V, Type::getInt16Ty(V.getContext()), false);
135 if (VTy->isFloatingPointTy())
136 return Builder.CreateFPCast(&V, Type::getHalfTy(V.getContext()));
137
138 llvm_unreachable("Should never be called!");
139}
140
141/// Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with
142/// modified arguments (based on OldIntr) and replaces InstToReplace with
143/// this newly created intrinsic call.
144static std::optional<Instruction *> modifyIntrinsicCall(
145 IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr,
146 InstCombiner &IC,
147 std::function<void(SmallVectorImpl<Value *> &, SmallVectorImpl<Type *> &)>
148 Func) {
149 SmallVector<Type *, 4> OverloadTys;
150 if (!Intrinsic::isSignatureValid(OldIntr.getCalledFunction(), OverloadTys))
151 return std::nullopt;
152
153 SmallVector<Value *, 8> Args(OldIntr.args());
154
155 // Modify arguments and types
156 Func(Args, OverloadTys);
157
158 CallInst *NewCall =
159 IC.Builder.CreateIntrinsicWithoutFolding(NewIntr, OverloadTys, Args);
160 NewCall->takeName(&OldIntr);
161 NewCall->copyMetadata(OldIntr);
162 if (isa<FPMathOperator>(NewCall))
163 NewCall->copyFastMathFlags(&OldIntr);
164 // Copy attributes
165 AttributeList OldAttrList = OldIntr.getAttributes();
166 NewCall->setAttributes(OldAttrList);
167
168 // Erase and replace uses
169 if (!InstToReplace.getType()->isVoidTy())
170 IC.replaceInstUsesWith(InstToReplace, NewCall);
171
172 bool RemoveOldIntr = &OldIntr != &InstToReplace;
173
174 auto *RetValue = IC.eraseInstFromFunction(InstToReplace);
175 if (RemoveOldIntr)
176 IC.eraseInstFromFunction(OldIntr);
177
178 return RetValue;
179}
180
181static std::optional<Instruction *>
183 const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr,
185 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
187
188 // Optimize _L to _LZ when _L is zero
189 if (const auto *LZMappingInfo =
191 if (auto *ConstantLod =
192 dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->LodIndex))) {
193 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
194 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
196 ImageDimIntr->Dim);
197 return modifyIntrinsicCall(
198 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
199 Args.erase(Args.begin() + ImageDimIntr->LodIndex);
200 });
201 }
202 }
203 }
204
205 // Optimize _mip away, when 'lod' is zero
206 if (const auto *MIPMappingInfo =
208 if (auto *ConstantMip =
209 dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->MipIndex))) {
210 if (ConstantMip->isZero()) {
211 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
212 AMDGPU::getImageDimIntrinsicByBaseOpcode(MIPMappingInfo->NONMIP,
213 ImageDimIntr->Dim);
214 return modifyIntrinsicCall(
215 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
216 Args.erase(Args.begin() + ImageDimIntr->MipIndex);
217 });
218 }
219 }
220 }
221
222 // Optimize _bias away when 'bias' is zero
223 if (const auto *BiasMappingInfo =
225 if (auto *ConstantBias =
226 dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->BiasIndex))) {
227 if (ConstantBias->isZero()) {
228 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
229 AMDGPU::getImageDimIntrinsicByBaseOpcode(BiasMappingInfo->NoBias,
230 ImageDimIntr->Dim);
231 return modifyIntrinsicCall(
232 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
233 Args.erase(Args.begin() + ImageDimIntr->BiasIndex);
234 ArgTys.erase(ArgTys.begin() + ImageDimIntr->BiasTyArg);
235 });
236 }
237 }
238 }
239
240 // Optimize _offset away when 'offset' is zero
241 if (const auto *OffsetMappingInfo =
243 if (auto *ConstantOffset =
244 dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->OffsetIndex))) {
245 if (ConstantOffset->isZero()) {
246 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
248 OffsetMappingInfo->NoOffset, ImageDimIntr->Dim);
249 return modifyIntrinsicCall(
250 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
251 Args.erase(Args.begin() + ImageDimIntr->OffsetIndex);
252 });
253 }
254 }
255 }
256
257 // Optimize the arrayed dim away when the array slice is zero, since slice 0
258 // is the base layer. Restricted to non-atomic, non-sampled image loads and
259 // stores for now.
260 const AMDGPU::MIMGDimInfo *DimInfo =
261 AMDGPU::getMIMGDimInfo(ImageDimIntr->Dim);
262 if (!BaseOpcode->Atomic && !BaseOpcode->Sampler && BaseOpcode->Coordinates &&
263 DimInfo->NonArrayDim != ImageDimIntr->Dim) {
264 // Address is [coords..., slice, (fragid)] plus an optional mip operand.
265 // The slice is the last coordinate, so index it from CoordStart.
266 unsigned SliceIndex = ImageDimIntr->CoordStart + DimInfo->NumCoords - 1 -
267 (DimInfo->MSAA ? 1 : 0);
268 auto *ConstantSlice = dyn_cast<ConstantInt>(II.getOperand(SliceIndex));
269 if (ConstantSlice && ConstantSlice->isZero()) {
270 if (const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
272 DimInfo->NonArrayDim)) {
273 return modifyIntrinsicCall(II, II, NewImageDimIntr->Intr, IC,
274 [&](auto &Args, auto &ArgTys) {
275 Args.erase(Args.begin() + SliceIndex);
276 });
277 }
278 }
279 }
280
281 // Try to use D16
282 if (ST->hasD16Images()) {
283 if (BaseOpcode->HasD16) {
284
285 // If the only use of image intrinsic is a fptrunc (with conversion to
286 // half) then both fptrunc and image intrinsic will be replaced with image
287 // intrinsic with D16 flag.
288 if (II.hasOneUse()) {
289 Instruction *User = II.user_back();
290
291 if (User->getOpcode() == Instruction::FPTrunc &&
293
294 return modifyIntrinsicCall(II, *User, ImageDimIntr->Intr, IC,
295 [&](auto &Args, auto &ArgTys) {
296 // Change return type of image intrinsic.
297 // Set it to return type of fptrunc.
298 ArgTys[0] = User->getType();
299 });
300 }
301 }
302
303 // Only perform D16 folding if every user of the image sample is
304 // an ExtractElementInst immediately followed by an FPTrunc to half.
306 ExtractTruncPairs;
307 bool AllHalfExtracts = true;
308
309 for (User *U : II.users()) {
310 auto *Ext = dyn_cast<ExtractElementInst>(U);
311 if (!Ext || !Ext->hasOneUse()) {
312 AllHalfExtracts = false;
313 break;
314 }
315
316 auto *Tr = dyn_cast<FPTruncInst>(*Ext->user_begin());
317 if (!Tr || !Tr->getType()->isHalfTy()) {
318 AllHalfExtracts = false;
319 break;
320 }
321
322 ExtractTruncPairs.emplace_back(Ext, Tr);
323 }
324
325 if (!ExtractTruncPairs.empty() && AllHalfExtracts) {
326 auto *VecTy = cast<VectorType>(II.getType());
327 Type *HalfVecTy =
328 VecTy->getWithNewType(Type::getHalfTy(II.getContext()));
329
330 // Obtain the original image sample intrinsic's signature
331 // and replace its return type with the half-vector for D16 folding
332 SmallVector<Type *, 8> OverloadTys;
333 if (!Intrinsic::isSignatureValid(II.getCalledFunction(), OverloadTys))
334 return std::nullopt;
335
336 OverloadTys[0] = HalfVecTy;
337 Module *M = II.getModule();
339 M, ImageDimIntr->Intr, OverloadTys);
340
341 II.mutateType(HalfVecTy);
342 II.setCalledFunction(HalfDecl);
343
344 IRBuilder<> Builder(*M);
345 for (auto &[Ext, Tr] : ExtractTruncPairs) {
346 Value *Idx = Ext->getIndexOperand();
347
348 Builder.SetInsertPoint(Tr);
349
350 Value *HalfExtract = Builder.CreateExtractElement(&II, Idx);
351 HalfExtract->takeName(Tr);
352
353 Tr->replaceAllUsesWith(HalfExtract);
354 }
355
356 for (auto &[Ext, Tr] : ExtractTruncPairs) {
357 IC.eraseInstFromFunction(*Tr);
358 IC.eraseInstFromFunction(*Ext);
359 }
360
361 return &II;
362 }
363 }
364 }
365
366 // Try to use A16 or G16
367 if (!ST->hasA16() && !ST->hasG16())
368 return std::nullopt;
369
370 // Address is interpreted as float if the instruction has a sampler or as
371 // unsigned int if there is no sampler.
372 bool HasSampler = BaseOpcode->Sampler;
373 bool FloatCoord = false;
374 // true means derivatives can be converted to 16 bit, coordinates not
375 bool OnlyDerivatives = false;
376
377 // Sampler-less addresses are unsigned, so a sext from i16 folds to a16 like a
378 // zext: they only disagree for a negative i16 (>= 0x8000), which is out of
379 // bounds while the max image dimension is <= 0x8000.
380 bool AllowI16SExt = !HasSampler;
381
382 for (unsigned OperandIndex = ImageDimIntr->GradientStart;
383 OperandIndex < ImageDimIntr->VAddrEnd; OperandIndex++) {
384 Value *Coord = II.getOperand(OperandIndex);
385 // If the values are not derived from 16-bit values, we cannot optimize.
386 if (!canSafelyConvertTo16Bit(*Coord, HasSampler, AllowI16SExt)) {
387 if (OperandIndex < ImageDimIntr->CoordStart ||
388 ImageDimIntr->GradientStart == ImageDimIntr->CoordStart) {
389 return std::nullopt;
390 }
391 // All gradients can be converted, so convert only them
392 OnlyDerivatives = true;
393 break;
394 }
395
396 assert(OperandIndex == ImageDimIntr->GradientStart ||
397 FloatCoord == Coord->getType()->isFloatingPointTy());
398 FloatCoord = Coord->getType()->isFloatingPointTy();
399 }
400
401 if (!OnlyDerivatives && !ST->hasA16())
402 OnlyDerivatives = true; // Only supports G16
403
404 // Check if there is a bias parameter and if it can be converted to f16
405 if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
406 Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
407 assert(HasSampler &&
408 "Only image instructions with a sampler can have a bias");
409 if (!canSafelyConvertTo16Bit(*Bias, HasSampler))
410 OnlyDerivatives = true;
411 }
412
413 if (OnlyDerivatives && (!ST->hasG16() || ImageDimIntr->GradientStart ==
414 ImageDimIntr->CoordStart))
415 return std::nullopt;
416
417 Type *CoordType = FloatCoord ? Type::getHalfTy(II.getContext())
418 : Type::getInt16Ty(II.getContext());
419
420 return modifyIntrinsicCall(
421 II, II, II.getIntrinsicID(), IC, [&](auto &Args, auto &ArgTys) {
422 ArgTys[ImageDimIntr->GradientTyArg] = CoordType;
423 if (!OnlyDerivatives) {
424 ArgTys[ImageDimIntr->CoordTyArg] = CoordType;
425
426 // Change the bias type
427 if (ImageDimIntr->NumBiasArgs != 0)
428 ArgTys[ImageDimIntr->BiasTyArg] = Type::getHalfTy(II.getContext());
429 }
430
431 unsigned EndIndex =
432 OnlyDerivatives ? ImageDimIntr->CoordStart : ImageDimIntr->VAddrEnd;
433 for (unsigned OperandIndex = ImageDimIntr->GradientStart;
434 OperandIndex < EndIndex; OperandIndex++) {
435 Args[OperandIndex] =
436 convertTo16Bit(*II.getOperand(OperandIndex), IC.Builder);
437 }
438
439 // Convert the bias
440 if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
441 Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
442 Args[ImageDimIntr->BiasIndex] = convertTo16Bit(*Bias, IC.Builder);
443 }
444 });
445}
446
448 const Value *Op0, const Value *Op1,
449 InstCombiner &IC) const {
450 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
451 // infinity, gives +0.0. If we can prove we don't have one of the special
452 // cases then we can use a normal multiply instead.
454 KnownFPClass Known0 =
456 DenormalMode Mode = I.getFunction()->getDenormalMode(APFloat::IEEEsingle());
457
458 // Bail early if Op0 may be zero and nsz is not set -- Op1 cannot help.
459 if (!Known0.isKnownNeverLogicalZero(Mode) && !I.hasNoSignedZeros())
460 return false;
461
462 KnownFPClass Known1 =
464
465 // Simplify if both operands are known non-zero.
466 if (Known0.isKnownNeverLogicalZero(Mode) &&
467 Known1.isKnownNeverLogicalZero(Mode))
468 return true;
469
470 // With nsz, two additional cases allow simplification:
471 // 1. One operand is not zero or infinity or NaN:
472 // Op0 NeverLogicalZero && NeverInfOrNaN, or symmetric for Op1.
473 // 2. Neither operand is infinity or NaN:
474 // Op0 NeverInfOrNaN && Op1 NeverInfOrNaN.
475 // The following condition captures both cases.
476 if (I.hasNoSignedZeros() &&
477 (Known0.isKnownNeverLogicalZero(Mode) || Known1.isKnownNeverInfOrNaN()) &&
478 (Known1.isKnownNeverLogicalZero(Mode) || Known0.isKnownNeverInfOrNaN()))
479 return true;
480
481 return false;
482}
483
484/// Match an fpext from half to float, or a constant we can convert.
486 Value *Src = nullptr;
487 ConstantFP *CFP = nullptr;
488 if (match(Arg, m_OneUse(m_FPExt(m_Value(Src))))) {
489 if (Src->getType()->isHalfTy())
490 return Src;
491 } else if (match(Arg, m_ConstantFP(CFP))) {
492 bool LosesInfo;
493 APFloat Val(CFP->getValueAPF());
495 if (!LosesInfo)
496 return ConstantFP::get(Type::getHalfTy(Arg->getContext()), Val);
497 }
498 return nullptr;
499}
500
501// Trim all zero components from the end of the vector \p UseV and return
502// an appropriate bitset with known elements.
504 Instruction *I) {
505 auto *VTy = cast<FixedVectorType>(UseV->getType());
506 unsigned VWidth = VTy->getNumElements();
507 APInt DemandedElts = APInt::getAllOnes(VWidth);
508
509 for (int i = VWidth - 1; i > 0; --i) {
510 auto *Elt = findScalarElement(UseV, i);
511 if (!Elt)
512 break;
513
514 if (auto *ConstElt = dyn_cast<Constant>(Elt)) {
515 if (!ConstElt->isNullValue() && !isa<UndefValue>(Elt))
516 break;
517 } else {
518 break;
519 }
520
521 DemandedElts.clearBit(i);
522 }
523
524 return DemandedElts;
525}
526
527// Trim elements of the end of the vector \p V, if they are
528// equal to the first element of the vector.
530 auto *VTy = cast<FixedVectorType>(V->getType());
531 unsigned VWidth = VTy->getNumElements();
532 APInt DemandedElts = APInt::getAllOnes(VWidth);
533 Value *FirstComponent = findScalarElement(V, 0);
534
535 SmallVector<int> ShuffleMask;
536 if (auto *SVI = dyn_cast<ShuffleVectorInst>(V))
537 SVI->getShuffleMask(ShuffleMask);
538
539 for (int I = VWidth - 1; I > 0; --I) {
540 if (ShuffleMask.empty()) {
541 auto *Elt = findScalarElement(V, I);
542 if (!Elt || (Elt != FirstComponent && !isa<UndefValue>(Elt)))
543 break;
544 } else {
545 // Detect identical elements in the shufflevector result, even though
546 // findScalarElement cannot tell us what that element is.
547 if (ShuffleMask[I] != ShuffleMask[0] && ShuffleMask[I] != PoisonMaskElem)
548 break;
549 }
550 DemandedElts.clearBit(I);
551 }
552
553 return DemandedElts;
554}
555
556/// Return true if it's legal to contract llvm.amdgcn.rcp(llvm.sqrt)
557static bool canContractSqrtToRsq(const FPMathOperator *SqrtOp) {
558 return (SqrtOp->getType()->isFloatTy() &&
559 (SqrtOp->hasApproxFunc() || SqrtOp->getFPAccuracy() >= 1.0f)) ||
560 SqrtOp->getType()->isHalfTy();
561}
562
563/// Simplify a lane index operand (e.g. llvm.amdgcn.readlane src1).
564///
565/// The instruction only reads the low 5 bits for wave32, and 6 bits for wave64.
568 unsigned LaneArgIdx) const {
569 unsigned MaskBits = ST->getWavefrontSizeLog2();
570 APInt DemandedMask(32, maskTrailingOnes<unsigned>(MaskBits));
571
572 KnownBits Known(32);
573 if (IC.SimplifyDemandedBits(&II, LaneArgIdx, DemandedMask, Known))
574 return true;
575
576 if (!Known.isConstant())
577 return false;
578
579 // Out of bounds indexes may appear in wave64 code compiled for wave32.
580 // Unlike the DAG version, SimplifyDemandedBits does not change constants, so
581 // manually fix it up.
582
583 Value *LaneArg = II.getArgOperand(LaneArgIdx);
584 Constant *MaskedConst =
585 ConstantInt::get(LaneArg->getType(), Known.getConstant() & DemandedMask);
586 if (MaskedConst != LaneArg) {
587 II.getOperandUse(LaneArgIdx).set(MaskedConst);
588 return true;
589 }
590
591 return false;
592}
593
594/// Simplify the f32 scale operand of a V_CVT_SCALEF32_* conversion, of which
595/// only the exponent field is read.
597 unsigned ScaleArgIdx) {
598 Value *Scale = II.getArgOperand(ScaleArgIdx);
599 Value *StrippedSign = InstCombiner::stripSignOnlyFPOps(Scale);
600 if (StrippedSign != Scale) {
601 IC.replaceOperand(II, ScaleArgIdx, StrippedSign);
602 return true;
603 }
604
605 auto *BC = dyn_cast<BitCastInst>(Scale);
606 if (!BC || !BC->hasOneUse() || !BC->getSrcTy()->isIntegerTy(32))
607 return false;
608
609 KnownBits Known(32);
610 return IC.SimplifyDemandedBits(
612}
613
615 Function &NewCallee, ArrayRef<Value *> Ops) {
617 Old.getOperandBundlesAsDefs(OpBundles);
618
619 CallInst *NewCall = B.CreateCall(&NewCallee, Ops, OpBundles);
620 NewCall->takeName(&Old);
621 return NewCall;
622}
623
624// Return true for sequences of instructions that effectively assign
625// each lane to its thread ID
626static bool isThreadID(const GCNSubtarget &ST, Value *V) {
627 // Case 1:
628 // wave32: mbcnt_lo(-1, 0)
629 // wave64: mbcnt_hi(-1, mbcnt_lo(-1, 0))
635 if (ST.isWave32() && match(V, W32Pred))
636 return true;
637 if (ST.isWave64() && match(V, W64Pred))
638 return true;
639
640 // Case 2:
641 // workitem.id.x & (wavefront size - 1), or bare workitem.id.x when the
642 // workgroup is one wave long or less.
643 auto *I = dyn_cast<Instruction>(V);
644 if (!I || !ST.isWaveSizeKnown())
645 return false;
646
647 const Function &F = *I->getFunction();
648 if (!ST.hasWavefrontsEvenlySplittingXDim(F, /*RequiresUniformYZ=*/true))
649 return false;
650
651 unsigned WaveSize = ST.getWavefrontSize();
653 if (match(V, m_c_And(TidX, m_SpecificInt(WaveSize - 1))))
654 return true;
655
656 return match(V, TidX) && ST.getMaxWorkitemID(F, 0) < WaveSize;
657}
658
661 IntrinsicInst &II) const {
662 const auto IID = II.getIntrinsicID();
663 assert(IID == Intrinsic::amdgcn_readlane ||
664 IID == Intrinsic::amdgcn_readfirstlane ||
665 IID == Intrinsic::amdgcn_permlane64);
666
667 Instruction *OpInst = dyn_cast<Instruction>(II.getOperand(0));
668
669 // Only do this if both instructions are in the same block
670 // (so the exec mask won't change) and the readlane is the only user of its
671 // operand.
672 if (!OpInst || !OpInst->hasOneUser() || OpInst->getParent() != II.getParent())
673 return nullptr;
674
675 const bool IsReadLane = (IID == Intrinsic::amdgcn_readlane);
676
677 // If this is a readlane, check that the second operand is a constant, or is
678 // defined before OpInst so we know it's safe to move this intrinsic higher.
679 Value *LaneID = nullptr;
680 if (IsReadLane) {
681 LaneID = II.getOperand(1);
682
683 // readlane take an extra operand for the lane ID, so we must check if that
684 // LaneID value can be used at the point where we want to move the
685 // intrinsic.
686 if (auto *LaneIDInst = dyn_cast<Instruction>(LaneID)) {
687 if (!IC.getDominatorTree().dominates(LaneIDInst, OpInst))
688 return nullptr;
689 }
690 }
691
692 // Hoist the intrinsic (II) through OpInst.
693 //
694 // (II (OpInst x)) -> (OpInst (II x))
695 const auto DoIt = [&](unsigned OpIdx,
696 Function *NewIntrinsic) -> Instruction * {
697 SmallVector<Value *, 2> Ops{OpInst->getOperand(OpIdx)};
698 if (IsReadLane)
699 Ops.push_back(LaneID);
700
701 // Rewrite the intrinsic call.
702 CallInst *NewII = rewriteCall(IC.Builder, II, *NewIntrinsic, Ops);
703
704 // Rewrite OpInst so it takes the result of the intrinsic now.
705 Instruction &NewOp = *OpInst->clone();
706 NewOp.setOperand(OpIdx, NewII);
707 return &NewOp;
708 };
709
710 // TODO(?): Should we do more with permlane64?
711 if (IID == Intrinsic::amdgcn_permlane64 && !isa<BitCastInst>(OpInst))
712 return nullptr;
713
714 if (isa<UnaryOperator>(OpInst))
715 return DoIt(0, II.getCalledFunction());
716
717 if (isa<CastInst>(OpInst)) {
718 Value *Src = OpInst->getOperand(0);
719 Type *SrcTy = Src->getType();
720 if (!isTypeLegal(SrcTy))
721 return nullptr;
722
723 Function *Remangled =
724 Intrinsic::getOrInsertDeclaration(II.getModule(), IID, {SrcTy});
725 return DoIt(0, Remangled);
726 }
727
728 // We can also hoist through binary operators if the other operand is uniform.
729 if (isa<BinaryOperator>(OpInst)) {
730 // FIXME: If we had access to UniformityInfo here we could just check
731 // if the operand is uniform.
733 return DoIt(1, II.getCalledFunction());
735 return DoIt(0, II.getCalledFunction());
736 }
737
738 return nullptr;
739}
740
741/// Evaluate V as a function of the lane ID and return its value on Lane, or
742/// std::nullopt if V is not a closed-form expression of the lane ID.
743static std::optional<uint64_t> evalLaneExpr(Value *V, unsigned Lane,
744 const GCNSubtarget &ST,
745 const DataLayout &DL,
746 unsigned Depth = 0) {
748 return std::nullopt;
749
750 // Poison/undef in the index expression: bail and let InstCombine fold the
751 // intrinsic the usual way.
752 if (isa<UndefValue>(V))
753 return std::nullopt;
754
755 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
756 return CI->getZExtValue();
757
758 if (isThreadID(ST, V))
759 return Lane;
760
762 if (!BO)
763 return std::nullopt;
764
765 std::optional<uint64_t> LHS =
766 evalLaneExpr(BO->getOperand(0), Lane, ST, DL, Depth + 1);
767 if (!LHS)
768 return std::nullopt;
769 std::optional<uint64_t> RHS =
770 evalLaneExpr(BO->getOperand(1), Lane, ST, DL, Depth + 1);
771 if (!RHS)
772 return std::nullopt;
773
774 Type *Ty = BO->getType();
775 Constant *Ops[] = {ConstantInt::get(Ty, *LHS), ConstantInt::get(Ty, *RHS)};
776 auto *CI =
778 return CI ? std::optional<uint64_t>(CI->getZExtValue()) : std::nullopt;
779}
780
781/// Build the per-lane shuffle map by evaluating Index for every lane in the
782/// wave. Returns false if any lane index is non-constant or out of range.
783static bool tryBuildShuffleMap(Value *Index, const GCNSubtarget &ST,
785 const DataLayout &DL) {
786 unsigned WaveSize = ST.getWavefrontSize();
787 Ids.resize(WaveSize);
788 for (unsigned Lane : seq(WaveSize)) {
789 std::optional<uint64_t> Val = evalLaneExpr(Index, Lane, ST, DL);
790 if (!Val || *Val >= WaveSize)
791 return false;
792 Ids[Lane] = static_cast<uint8_t>(*Val);
793 }
794 return true;
795}
796
797/// Lanes are partitioned into groups of Period; each group is a translated
798/// copy of the first: Ids[I] = Ids[I % Period] + (I & ~(Period - 1)).
799template <unsigned Period>
801 static_assert(isPowerOf2_32(Period), "Period must be a power of two");
802 for (size_t I = Period, E = Ids.size(); I < E; ++I)
803 if (Ids[I] != Ids[I % Period] + (I & ~(Period - 1)))
804 return false;
805 return true;
806}
807
808/// Match an N-lane row pattern: each lane in [0, N) reads from a source lane
809/// in the same N-lane row, and the pattern repeats periodically across rows.
810template <unsigned N> static bool isRowPattern(ArrayRef<uint8_t> Ids) {
811 for (unsigned I = 0; I < N; ++I)
812 if (Ids[I] >= N)
813 return false;
814 return hasPeriodicLayout<N>(Ids);
815}
816
817static constexpr auto isQuadPattern = isRowPattern<4>;
818static constexpr auto isHalfRowPattern = isRowPattern<8>;
819static constexpr auto isFullRowPattern = isRowPattern<16>;
820
821/// Match a 4-lane (quad) permutation, encoded as the v_mov_b32_dpp
822/// QUAD_PERM control word: bits[1:0]=Ids[0], [3:2]=Ids[1], [5:4]=Ids[2],
823/// [7:6]=Ids[3].
824static std::optional<unsigned> matchQuadPermPattern(ArrayRef<uint8_t> Ids) {
825 if (!isQuadPattern(Ids))
826 return std::nullopt;
827 return Ids[3] << 6 | Ids[2] << 4 | Ids[1] << 2 | Ids[0];
828}
829
830/// Match an N-lane reversal (mirror) pattern.
831template <unsigned N> static bool matchMirrorPattern(ArrayRef<uint8_t> Ids) {
832 if (!isRowPattern<N>(Ids))
833 return false;
834 for (unsigned J = 0; J < N; ++J)
835 if (Ids[J] != (N - 1) - J)
836 return false;
837 return true;
838}
839
842
843/// Match a 16-lane cyclic rotation; returns the rotation amount in [1, 15].
844static std::optional<unsigned> matchRowRotatePattern(ArrayRef<uint8_t> Ids) {
845 if (Ids[0] == 0 || !isFullRowPattern(Ids))
846 return std::nullopt;
847 for (unsigned J = 1; J < 16; ++J)
848 if (Ids[J] != (Ids[0] + J) % 16)
849 return std::nullopt;
850 return 16u - Ids[0];
851}
852
853/// Match a row-share pattern: all 16 lanes of each row read the same source
854/// lane. Returns the shared source lane index in [0, 16).
855static std::optional<unsigned> matchRowSharePattern(ArrayRef<uint8_t> Ids) {
856 if (!isFullRowPattern(Ids))
857 return std::nullopt;
858 if (!all_equal(Ids.take_front(16)))
859 return std::nullopt;
860 return Ids[0];
861}
862
863/// Match an XOR mask pattern within each 16-lane row: Ids[J] == Mask ^ J,
864/// with Mask in [1, 15].
865static std::optional<unsigned> matchRowXMaskPattern(ArrayRef<uint8_t> Ids) {
866 unsigned Mask = Ids[0];
867 if (Mask == 0 || !isFullRowPattern(Ids))
868 return std::nullopt;
869 for (unsigned J = 0; J < 16; ++J)
870 if (Ids[J] != (Mask ^ J))
871 return std::nullopt;
872 return Mask;
873}
874
875/// Match an 8-lane arbitrary permutation, encoded as the v_mov_b32_dpp8
876/// 24-bit selector (three bits per output lane).
877static std::optional<unsigned> matchHalfRowPermPattern(ArrayRef<uint8_t> Ids) {
878 if (!isHalfRowPattern(Ids))
879 return std::nullopt;
880 unsigned Selector = 0;
881 for (unsigned J = 0; J < 8; ++J)
882 Selector |= Ids[J] << (J * 3);
883 return Selector;
884}
885
886/// Pack a 16-lane permutation into a single 64-bit value: four bits per output
887/// lane, lane J in bits [J*4 + 3 : J*4]. The caller splits it into the low and
888/// high 32-bit selector operands of v_permlane16 / v_permlanex16.
890 uint64_t Sel = 0;
891 for (unsigned J = 0; J < 16; ++J)
892 Sel |= static_cast<uint64_t>(Ids[J] & 0xF) << (J * 4);
893 return Sel;
894}
895
896/// Match a half-wave swap: lane J reads from lane J ^ 32. Only meaningful on
897/// wave64 targets.
899 if (Ids.size() != 64)
900 return false;
901 for (unsigned J = 0; J < 64; ++J)
902 if (Ids[J] != (J ^ 32))
903 return false;
904 return true;
905}
906
907/// Match a cross-row permutation suitable for v_permlanex16: every lane in
908/// the low 16-lane half reads from the high half of its own row, and vice
909/// versa.
911 if (!hasPeriodicLayout<32>(Ids))
912 return false;
913 for (unsigned J = 0; J < 16; ++J) {
914 if (Ids[J] < 16 || Ids[J] >= 32)
915 return false;
916 if (Ids[J + 16] != Ids[J] - 16)
917 return false;
918 }
919 return true;
920}
921
922/// Match a DS_SWIZZLE bitmask-mode permutation:
923/// dst_lane = ((src_lane & AND) | OR) ^ XOR
924/// with each mask being five bits. Returns the encoded swizzle immediate.
925/// The hardware applies the formula independently within each 32-lane group,
926/// so on wave64 the high group must replicate the low one (translated by 32).
927static std::optional<unsigned>
929 if (!hasPeriodicLayout<32>(Ids))
930 return std::nullopt;
931
932 // The formula is per-bit: output bit B depends only on input bit B. Probe
933 // each bit with src=0 and src=(1<<B); if the output bit flipped, AND[B]=1
934 // and XOR[B] carries the constant offset; otherwise it is a constant bit
935 // encoded in OR (with AND[B]=0, XOR[B]=0).
936 unsigned AndMask = 0, OrMask = 0, XorMask = 0;
937 for (unsigned B = 0; B < 5; ++B) {
938 unsigned Bit0 = (Ids[0] >> B) & 1;
939 unsigned Bit1 = (Ids[1ull << B] >> B) & 1;
940 if (Bit0 != Bit1) {
941 AndMask |= 1u << B;
942 XorMask |= Bit0 << B;
943 } else {
944 OrMask |= Bit0 << B;
945 }
946 }
947
948 // The per-bit derivation assumes bit independence; verify the masks
949 // actually reproduce every lane in the 32-lane group.
950 for (unsigned I : seq(32u)) {
951 unsigned Expected = ((I & AndMask) | OrMask) ^ XorMask;
952 if (Ids[I] != Expected)
953 return std::nullopt;
954 }
955
960}
961
962/// Match a GFX9+ DS_SWIZZLE rotate-mode permutation: a cyclic left-rotation
963/// of all 32 lanes within each 32-lane group by a constant N in [0, 31],
964/// i.e. dst_lane = (src_lane + N) % 32. On wave64, hasPeriodicLayout<32>
965/// ensures both 32-lane groups rotate by the same amount.
966static std::optional<unsigned>
968 if (!hasPeriodicLayout<32>(Ids))
969 return std::nullopt;
970
971 // Determine the rotation amount from lane 0: every lane must read from
972 // lane (I + N) % 32 where N = Ids[0] and 0 <= N <= 31.
973 unsigned N = Ids[0];
974 if (N >= 32)
975 return std::nullopt;
976
977 for (unsigned I = 0; I < 32; ++I)
978 if (Ids[I] != (I + N) % 32)
979 return std::nullopt;
980
983}
984
985/// Emit v_mov_b32_dpp with the given control word, row/bank masks 0xF, and
986/// bound_ctrl=1 so out-of-bounds lanes are well-defined and the DPP mov can
987/// be folded into a consuming VALU op by GCNDPPCombine.
988static Value *createUpdateDpp(IRBuilderBase &B, Value *Val, unsigned Ctrl) {
989 Type *Ty = Val->getType();
990 return B.CreateIntrinsic(Intrinsic::amdgcn_update_dpp, {Ty},
991 {PoisonValue::get(Ty), Val, B.getInt32(Ctrl),
992 B.getInt32(0xF), B.getInt32(0xF), B.getTrue()});
993}
994
995/// Emit v_mov_b32_dpp8 with the given 24-bit lane selector.
996static Value *createMovDpp8(IRBuilderBase &B, Value *Val, unsigned Selector) {
997 return B.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp8, {Val->getType()},
998 {Val, B.getInt32(Selector)});
999}
1000
1001/// Emit v_permlane16 with the precomputed lane-select halves.
1003 uint32_t Hi) {
1004 Type *Ty = Val->getType();
1005 return B.CreateIntrinsic(Intrinsic::amdgcn_permlane16, {Ty},
1006 {PoisonValue::get(Ty), Val, B.getInt32(Lo),
1007 B.getInt32(Hi), B.getFalse(), B.getFalse()});
1008}
1009
1010/// Emit v_permlanex16 with the precomputed lane-select halves. Each output
1011/// lane reads from the other 16-lane half of the same row.
1013 uint32_t Hi) {
1014 Type *Ty = Val->getType();
1015 return B.CreateIntrinsic(Intrinsic::amdgcn_permlanex16, {Ty},
1016 {PoisonValue::get(Ty), Val, B.getInt32(Lo),
1017 B.getInt32(Hi), B.getFalse(), B.getFalse()});
1018}
1019
1020/// Emit ds_swizzle with the given immediate, bitcasting/converting between
1021/// pointer/float types and i32 as required by the intrinsic signature.
1023 const DataLayout &DL) {
1024 Type *OrigTy = Val->getType();
1025 assert(DL.getTypeSizeInBits(OrigTy) == 32 &&
1026 "ds_swizzle only supports 32-bit operands");
1027 IntegerType *I32Ty = B.getInt32Ty();
1028 Value *Src = Val;
1029 if (OrigTy->isPointerTy())
1030 Src = B.CreatePtrToInt(Src, I32Ty);
1031 else if (OrigTy != I32Ty)
1032 Src = B.CreateBitCast(Src, I32Ty);
1033 Value *Result = B.CreateIntrinsic(Intrinsic::amdgcn_ds_swizzle, {},
1034 {Src, B.getInt32(Offset)});
1035 if (OrigTy->isPointerTy())
1036 return B.CreateIntToPtr(Result, OrigTy);
1037 if (OrigTy != I32Ty)
1038 return B.CreateBitCast(Result, OrigTy);
1039 return Result;
1040}
1041
1042/// Emit v_permlane64 (swap of the two 32-lane halves of a wave64).
1044 return B.CreateIntrinsic(Intrinsic::amdgcn_permlane64, {Val->getType()},
1045 {Val});
1046}
1047
1048/// Given a shuffle map, try to emit the best hardware intrinsic.
1051 const GCNSubtarget &ST,
1052 const DataLayout &DL) {
1053 // Identity shuffle (every lane reads itself) folds to the source value.
1054 if (all_of(enumerate(Ids),
1055 [](const auto &E) { return E.value() == E.index(); }))
1056 return Src;
1057
1058 // Uniform shuffle (all lanes read the same value) is handled by cheaper
1059 // broadcast/readlane intrinsics.
1060 if (all_equal(Ids))
1061 return nullptr;
1062
1063 if (std::optional<unsigned> QP = matchQuadPermPattern(Ids)) {
1064 if (ST.hasDPP())
1065 return createUpdateDpp(B, Src, *QP);
1067 }
1068
1069 if (ST.hasDPP()) {
1074 if (std::optional<unsigned> Amt = matchRowRotatePattern(Ids))
1075 return createUpdateDpp(B, Src, AMDGPU::DPP::ROW_ROR_FIRST + *Amt - 1);
1076 }
1077
1078 // row_share is supported on GFX90A and GFX10+; row_xmask is GFX10+ only.
1079 if (ST.hasDPPRowShare()) {
1080 if (std::optional<unsigned> Lane = matchRowSharePattern(Ids))
1081 return createUpdateDpp(B, Src, AMDGPU::DPP::ROW_SHARE_FIRST + *Lane);
1082 }
1083
1084 if (ST.hasDPP() && ST.hasGFX10Insts()) {
1085 if (std::optional<unsigned> Mask = matchRowXMaskPattern(Ids))
1086 return createUpdateDpp(B, Src, AMDGPU::DPP::ROW_XMASK_FIRST + *Mask);
1087 }
1088
1089 if (ST.hasDPP8()) {
1090 if (std::optional<unsigned> Sel = matchHalfRowPermPattern(Ids))
1091 return createMovDpp8(B, Src, *Sel);
1092 }
1093
1094 if (ST.hasPermlane16Insts()) {
1095 if (isFullRowPattern(Ids)) {
1097 return createPermlane16(B, Src, Lo_32(Sel), Hi_32(Sel));
1098 }
1099 // Cross-row shuffles (e.g. XOR 16..31) — covered by permlanex16.
1100 if (isCrossRowPattern(Ids)) {
1102 return createPermlaneX16(B, Src, Lo_32(Sel), Hi_32(Sel));
1103 }
1104 }
1105
1106 // Generic DS_SWIZZLE bitmask-mode fallback: handles any 32-lane shuffle that
1107 // can be expressed as dst = ((src & AND) | OR) ^ XOR with 5-bit masks. This
1108 // is available on every target that has ds_swizzle.
1109 if (std::optional<unsigned> Imm = matchDsSwizzleBitmaskPattern(Ids))
1110 return createDsSwizzle(B, Src, *Imm, DL);
1111
1112 // DS_SWIZZLE rotate mode (GFX9+): handles cyclic 32-lane rotations that
1113 // bitmask mode cannot express (e.g. +1 mod 32 requires inter-bit carry).
1114 if (ST.hasDsSwizzleRotateMode()) {
1115 if (std::optional<unsigned> Imm = matchDsSwizzleRotatePattern(Ids))
1116 return createDsSwizzle(B, Src, *Imm, DL);
1117 }
1118
1119 if (ST.hasPermLane64() && matchHalfWaveSwapPattern(Ids))
1120 return createPermlane64(B, Src);
1121
1122 return nullptr;
1123}
1124
1125/// Try to fold a wave_shuffle/ds_bpermute whose lane index is a constant
1126/// function of the lane ID into a hardware-specific lane permutation intrinsic.
1127static std::optional<Instruction *>
1129 const GCNSubtarget &ST) {
1130 const DataLayout &DL = IC.getDataLayout();
1131 if (DL.getTypeSizeInBits(II.getType()) != 32)
1132 return std::nullopt;
1133
1134 if (!ST.isWaveSizeKnown())
1135 return std::nullopt;
1136
1137 unsigned WaveSize = ST.getWavefrontSize();
1138 bool IsBpermute = II.getIntrinsicID() == Intrinsic::amdgcn_ds_bpermute;
1139 Value *Src = II.getArgOperand(IsBpermute ? 1 : 0);
1140 Value *Index = II.getArgOperand(IsBpermute ? 0 : 1);
1141
1143 if (IsBpermute) {
1144 Ids.resize(WaveSize);
1145 for (unsigned Lane : seq(WaveSize)) {
1146 std::optional<uint64_t> Val = evalLaneExpr(Index, Lane, ST, DL);
1147 if (!Val || (*Val & 3) || (*Val >> 2) >= WaveSize)
1148 return std::nullopt;
1149 Ids[Lane] = static_cast<uint8_t>(*Val >> 2);
1150 }
1151 } else {
1152 if (!tryBuildShuffleMap(Index, ST, Ids, DL))
1153 return std::nullopt;
1154 }
1155
1156 Value *Result = matchShuffleToHWIntrinsic(IC.Builder, Src, Ids, ST, DL);
1157 if (!Result)
1158 return std::nullopt;
1159
1160 return IC.replaceInstUsesWith(II, Result);
1161}
1162
1163/// Try to fold an addition into the accumulator when saturation is disabled.
1165 unsigned AccIdx,
1166 unsigned ClampIdx,
1167 InstCombiner &IC) {
1168 // Reassociating across a saturating accumulation is not valid.
1169 if (!match(II.getArgOperand(ClampIdx), m_Zero()) || !II.hasOneUse())
1170 return nullptr;
1171
1172 const APInt *Acc = nullptr;
1173 if (!match(II.getArgOperand(AccIdx), m_APInt(Acc)))
1174 return nullptr;
1175
1176 auto *AccumUser = dyn_cast<BinaryOperator>(II.user_back());
1177 if (!AccumUser)
1178 return nullptr;
1179
1180 Value *AccumDelta = nullptr;
1181 if (!match(AccumUser, m_c_Add(m_Specific(&II), m_Value(AccumDelta))))
1182 return nullptr;
1183
1184 Value *NewAcc = nullptr;
1185 const APInt *AccumDeltaC = nullptr;
1186 if (Acc->isZero())
1187 NewAcc = AccumDelta;
1188 else if (match(AccumDelta, m_APInt(AccumDeltaC)))
1189 NewAcc = ConstantInt::get(II.getType(), *Acc + *AccumDeltaC);
1190 else
1191 return nullptr;
1192
1193 Instruction *NewII =
1194 IC.InsertNewInstWith(II.clone(), AccumUser->getIterator());
1195 NewII->setOperand(AccIdx, NewAcc);
1198 IC.replaceInstUsesWith(*AccumUser, NewII);
1199 IC.eraseInstFromFunction(*AccumUser);
1200 return &II;
1201}
1202
1203std::optional<Instruction *>
1205 Intrinsic::ID IID = II.getIntrinsicID();
1206 switch (IID) {
1207 case Intrinsic::amdgcn_implicitarg_ptr: {
1208 if (II.getFunction()->hasFnAttribute("amdgpu-no-implicitarg-ptr"))
1209 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
1210 uint64_t ImplicitArgBytes = ST->getImplicitArgNumBytes(*II.getFunction());
1211
1212 uint64_t CurrentOrNullBytes =
1213 II.getAttributes().getRetDereferenceableOrNullBytes();
1214 if (CurrentOrNullBytes != 0) {
1215 // Refine "dereferenceable (A) meets dereferenceable_or_null(B)"
1216 // into dereferenceable(max(A, B))
1217 uint64_t NewBytes = std::max(CurrentOrNullBytes, ImplicitArgBytes);
1218 II.addRetAttr(
1219 Attribute::getWithDereferenceableBytes(II.getContext(), NewBytes));
1220 II.removeRetAttr(Attribute::DereferenceableOrNull);
1221 return &II;
1222 }
1223
1224 uint64_t CurrentBytes = II.getAttributes().getRetDereferenceableBytes();
1225 uint64_t NewBytes = std::max(CurrentBytes, ImplicitArgBytes);
1226 if (NewBytes != CurrentBytes) {
1227 II.addRetAttr(
1228 Attribute::getWithDereferenceableBytes(II.getContext(), NewBytes));
1229 return &II;
1230 }
1231
1232 return std::nullopt;
1233 }
1234 case Intrinsic::amdgcn_rcp: {
1235 Value *Src = II.getArgOperand(0);
1236 if (isa<PoisonValue>(Src))
1237 return IC.replaceInstUsesWith(II, Src);
1238
1239 // TODO: Move to ConstantFolding/InstSimplify?
1240 if (isa<UndefValue>(Src)) {
1241 Type *Ty = II.getType();
1242 auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
1243 return IC.replaceInstUsesWith(II, QNaN);
1244 }
1245
1246 if (II.isStrictFP())
1247 break;
1248
1249 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
1250 std::optional<APFloat> Val = AMDGPU::evaluateRcp(C->getValueAPF());
1251 if (!Val)
1252 break;
1253
1254 return IC.replaceInstUsesWith(II, ConstantFP::get(II.getContext(), *Val));
1255 }
1256
1257 FastMathFlags FMF = cast<FPMathOperator>(II).getFastMathFlags();
1258 if (!FMF.allowContract())
1259 break;
1260 auto *SrcCI = dyn_cast<IntrinsicInst>(Src);
1261 if (!SrcCI)
1262 break;
1263
1264 auto IID = SrcCI->getIntrinsicID();
1265 // llvm.amdgcn.rcp(llvm.amdgcn.sqrt(x)) -> llvm.amdgcn.rsq(x) if contractable
1266 //
1267 // llvm.amdgcn.rcp(llvm.sqrt(x)) -> llvm.amdgcn.rsq(x) if contractable and
1268 // relaxed.
1269 if (IID == Intrinsic::amdgcn_sqrt || IID == Intrinsic::sqrt) {
1270 const FPMathOperator *SqrtOp = cast<FPMathOperator>(SrcCI);
1271 FastMathFlags InnerFMF = SqrtOp->getFastMathFlags();
1272 if (!InnerFMF.allowContract() || !SrcCI->hasOneUse())
1273 break;
1274
1275 if (IID == Intrinsic::sqrt && !canContractSqrtToRsq(SqrtOp))
1276 break;
1277
1279 SrcCI->getModule(), Intrinsic::amdgcn_rsq, {SrcCI->getType()});
1280
1281 InnerFMF |= FMF;
1282 II.setFastMathFlags(InnerFMF);
1283
1284 II.setCalledFunction(NewDecl);
1285 return IC.replaceOperand(II, 0, SrcCI->getArgOperand(0));
1286 }
1287
1288 break;
1289 }
1290 case Intrinsic::amdgcn_sqrt:
1291 case Intrinsic::amdgcn_rsq:
1292 case Intrinsic::amdgcn_tanh: {
1293 Value *Src = II.getArgOperand(0);
1294 if (isa<PoisonValue>(Src))
1295 return IC.replaceInstUsesWith(II, Src);
1296
1297 // TODO: Move to ConstantFolding/InstSimplify?
1298 if (isa<UndefValue>(Src)) {
1299 Type *Ty = II.getType();
1300 auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
1301 return IC.replaceInstUsesWith(II, QNaN);
1302 }
1303
1304 // f16 amdgcn.sqrt is identical to regular sqrt.
1305 if (IID == Intrinsic::amdgcn_sqrt && Src->getType()->isHalfTy()) {
1307 II.getModule(), Intrinsic::sqrt, {II.getType()});
1308 II.setCalledFunction(NewDecl);
1309 return &II;
1310 }
1311
1312 break;
1313 }
1314 case Intrinsic::amdgcn_log:
1315 case Intrinsic::amdgcn_exp2: {
1316 const bool IsLog = IID == Intrinsic::amdgcn_log;
1317 const bool IsExp = IID == Intrinsic::amdgcn_exp2;
1318 Value *Src = II.getArgOperand(0);
1319 Type *Ty = II.getType();
1320
1321 if (isa<PoisonValue>(Src))
1322 return IC.replaceInstUsesWith(II, Src);
1323
1324 if (IC.getSimplifyQuery().isUndefValue(Src))
1326
1327 if (ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
1328 if (C->isInfinity()) {
1329 // exp2(+inf) -> +inf
1330 // log2(+inf) -> +inf
1331 if (!C->isNegative())
1332 return IC.replaceInstUsesWith(II, C);
1333
1334 // exp2(-inf) -> 0
1335 if (IsExp && C->isNegative())
1337 }
1338
1339 if (II.isStrictFP())
1340 break;
1341
1342 if (C->isNaN()) {
1343 Constant *Quieted = ConstantFP::get(Ty, C->getValue().makeQuiet());
1344 return IC.replaceInstUsesWith(II, Quieted);
1345 }
1346
1347 // f32 instruction doesn't handle denormals, f16 does.
1348 if (C->isZero() || (C->getValue().isDenormal() && Ty->isFloatTy())) {
1349 Constant *FoldedValue = IsLog ? ConstantFP::getInfinity(Ty, true)
1350 : ConstantFP::get(Ty, 1.0);
1351 return IC.replaceInstUsesWith(II, FoldedValue);
1352 }
1353
1354 if (IsLog && C->isNegative())
1356
1357 // TODO: Full constant folding matching hardware behavior.
1358 }
1359
1360 break;
1361 }
1362 case Intrinsic::amdgcn_frexp_mant:
1363 case Intrinsic::amdgcn_frexp_exp: {
1364 Value *Src = II.getArgOperand(0);
1365 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
1366 int Exp;
1367 APFloat Significand =
1368 frexp(C->getValueAPF(), Exp, APFloat::rmNearestTiesToEven);
1369
1370 if (IID == Intrinsic::amdgcn_frexp_mant) {
1371 return IC.replaceInstUsesWith(
1372 II, ConstantFP::get(II.getContext(), Significand));
1373 }
1374
1375 // Match instruction special case behavior.
1376 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
1377 Exp = 0;
1378
1379 return IC.replaceInstUsesWith(II,
1380 ConstantInt::getSigned(II.getType(), Exp));
1381 }
1382
1383 if (isa<PoisonValue>(Src))
1384 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
1385
1386 if (isa<UndefValue>(Src)) {
1387 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
1388 }
1389
1390 break;
1391 }
1392 case Intrinsic::amdgcn_class: {
1393 Value *Src0 = II.getArgOperand(0);
1394 Value *Src1 = II.getArgOperand(1);
1395 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
1396 if (CMask) {
1397 II.setCalledOperand(Intrinsic::getOrInsertDeclaration(
1398 II.getModule(), Intrinsic::is_fpclass, Src0->getType()));
1399
1400 // Clamp any excess bits, as they're illegal for the generic intrinsic.
1401 II.setArgOperand(1, ConstantInt::get(Src1->getType(),
1402 CMask->getZExtValue() & fcAllFlags));
1403 return &II;
1404 }
1405
1406 // Propagate poison.
1407 if (isa<PoisonValue>(Src0) || isa<PoisonValue>(Src1))
1408 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
1409
1410 // llvm.amdgcn.class(_, undef) -> false
1411 if (IC.getSimplifyQuery().isUndefValue(Src1))
1412 return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), false));
1413
1414 // llvm.amdgcn.class(undef, mask) -> mask != 0
1415 if (IC.getSimplifyQuery().isUndefValue(Src0)) {
1416 Value *CmpMask = IC.Builder.CreateICmpNE(
1417 Src1, ConstantInt::getNullValue(Src1->getType()));
1418 return IC.replaceInstUsesWith(II, CmpMask);
1419 }
1420 break;
1421 }
1422 case Intrinsic::amdgcn_cvt_pkrtz: {
1423 auto foldFPTruncToF16RTZ = [](Value *Arg) -> Value * {
1424 Type *HalfTy = Type::getHalfTy(Arg->getContext());
1425
1426 if (isa<PoisonValue>(Arg))
1427 return PoisonValue::get(HalfTy);
1428 if (isa<UndefValue>(Arg))
1429 return UndefValue::get(HalfTy);
1430
1431 ConstantFP *CFP = nullptr;
1432 if (match(Arg, m_ConstantFP(CFP))) {
1433 bool LosesInfo;
1434 APFloat Val(CFP->getValueAPF());
1436 return ConstantFP::get(HalfTy, Val);
1437 }
1438
1439 Value *Src = nullptr;
1440 if (match(Arg, m_FPExt(m_Value(Src)))) {
1441 if (Src->getType()->isHalfTy())
1442 return Src;
1443 }
1444
1445 return nullptr;
1446 };
1447
1448 if (Value *Src0 = foldFPTruncToF16RTZ(II.getArgOperand(0))) {
1449 if (Value *Src1 = foldFPTruncToF16RTZ(II.getArgOperand(1))) {
1450 Value *V = PoisonValue::get(II.getType());
1451 V = IC.Builder.CreateInsertElement(V, Src0, (uint64_t)0);
1452 V = IC.Builder.CreateInsertElement(V, Src1, (uint64_t)1);
1453 return IC.replaceInstUsesWith(II, V);
1454 }
1455 }
1456
1457 break;
1458 }
1459 case Intrinsic::amdgcn_cvt_pknorm_i16:
1460 case Intrinsic::amdgcn_cvt_pknorm_u16:
1461 case Intrinsic::amdgcn_cvt_pk_i16:
1462 case Intrinsic::amdgcn_cvt_pk_u16: {
1463 Value *Src0 = II.getArgOperand(0);
1464 Value *Src1 = II.getArgOperand(1);
1465
1466 // TODO: Replace call with scalar operation if only one element is poison.
1467 if (isa<PoisonValue>(Src0) && isa<PoisonValue>(Src1))
1468 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
1469
1470 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
1471 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
1472 }
1473
1474 break;
1475 }
1476 case Intrinsic::amdgcn_cvt_off_f32_i4: {
1477 Value* Arg = II.getArgOperand(0);
1478 Type *Ty = II.getType();
1479
1480 if (isa<PoisonValue>(Arg))
1481 return IC.replaceInstUsesWith(II, PoisonValue::get(Ty));
1482
1483 if(IC.getSimplifyQuery().isUndefValue(Arg))
1485
1486 ConstantInt *CArg = dyn_cast<ConstantInt>(II.getArgOperand(0));
1487 if (!CArg)
1488 break;
1489
1490 // Tabulated 0.0625 * (sext (CArg & 0xf)).
1491 constexpr size_t ResValsSize = 16;
1492 static constexpr float ResVals[ResValsSize] = {
1493 0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375,
1494 -0.5, -0.4375, -0.375, -0.3125, -0.25, -0.1875, -0.125, -0.0625};
1495 Constant *Res =
1496 ConstantFP::get(Ty, ResVals[CArg->getZExtValue() & (ResValsSize - 1)]);
1497 return IC.replaceInstUsesWith(II, Res);
1498 }
1499 case Intrinsic::amdgcn_ubfe:
1500 case Intrinsic::amdgcn_sbfe: {
1501 // Decompose simple cases into standard shifts.
1502 Value *Src = II.getArgOperand(0);
1503 if (isa<UndefValue>(Src)) {
1504 return IC.replaceInstUsesWith(II, Src);
1505 }
1506
1507 uint64_t Width;
1508 Type *Ty = II.getType();
1509 unsigned IntSize = Ty->getIntegerBitWidth();
1510
1511 ConstantInt *CWidth = dyn_cast<ConstantInt>(II.getArgOperand(2));
1512 if (CWidth) {
1513 Width = CWidth->getZExtValue();
1514 if ((Width & (IntSize - 1)) == 0) {
1516 }
1517
1518 // Hardware ignores high bits, so remove those.
1519 if (Width >= IntSize) {
1520 return IC.replaceOperand(
1521 II, 2, ConstantInt::get(CWidth->getType(), Width & (IntSize - 1)));
1522 }
1523 }
1524
1525 uint64_t Offset;
1526 ConstantInt *COffset = dyn_cast<ConstantInt>(II.getArgOperand(1));
1527 if (COffset) {
1528 Offset = COffset->getZExtValue();
1529 if (Offset >= IntSize) {
1530 return IC.replaceOperand(
1531 II, 1,
1532 ConstantInt::get(COffset->getType(), Offset & (IntSize - 1)));
1533 }
1534 }
1535
1536 bool Signed = IID == Intrinsic::amdgcn_sbfe;
1537
1538 if (!CWidth || !COffset)
1539 break;
1540
1541 // The case of Width == 0 is handled above, which makes this transformation
1542 // safe. If Width == 0, then the ashr and lshr instructions become poison
1543 // value since the shift amount would be equal to the bit size.
1544 assert(Width != 0);
1545
1546 // TODO: This allows folding to undef when the hardware has specific
1547 // behavior?
1548 if (Offset + Width < IntSize) {
1549 Value *Shl = IC.Builder.CreateShl(Src, IntSize - Offset - Width);
1550 Value *RightShift = Signed ? IC.Builder.CreateAShr(Shl, IntSize - Width)
1551 : IC.Builder.CreateLShr(Shl, IntSize - Width);
1552 RightShift->takeName(&II);
1553 return IC.replaceInstUsesWith(II, RightShift);
1554 }
1555
1556 Value *RightShift = Signed ? IC.Builder.CreateAShr(Src, Offset)
1557 : IC.Builder.CreateLShr(Src, Offset);
1558
1559 RightShift->takeName(&II);
1560 return IC.replaceInstUsesWith(II, RightShift);
1561 }
1562 case Intrinsic::amdgcn_exp:
1563 case Intrinsic::amdgcn_exp_row:
1564 case Intrinsic::amdgcn_exp_compr: {
1565 ConstantInt *En = cast<ConstantInt>(II.getArgOperand(1));
1566 uint64_t EnBits = En->getZExtValue();
1567 if (EnBits == 0xf)
1568 break; // All inputs enabled.
1569
1570 bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
1571 bool Changed = false;
1572 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
1573 if ((!IsCompr && (EnBits & (1ULL << I)) == 0) ||
1574 (IsCompr && ((EnBits & (0x3ULL << (2 * I))) == 0))) {
1575 Value *Src = II.getArgOperand(I + 2);
1576 if (!isa<PoisonValue>(Src)) {
1577 IC.replaceOperand(II, I + 2, PoisonValue::get(Src->getType()));
1578 Changed = true;
1579 }
1580 }
1581 }
1582
1583 if (Changed) {
1584 return &II;
1585 }
1586
1587 break;
1588 }
1589 case Intrinsic::amdgcn_fmed3: {
1590 Value *Src0 = II.getArgOperand(0);
1591 Value *Src1 = II.getArgOperand(1);
1592 Value *Src2 = II.getArgOperand(2);
1593
1594 for (Value *Src : {Src0, Src1, Src2}) {
1595 if (isa<PoisonValue>(Src))
1596 return IC.replaceInstUsesWith(II, Src);
1597 }
1598
1599 if (II.isStrictFP())
1600 break;
1601
1602 // med3 with a nan input acts like
1603 // v_min_f32(v_min_f32(s0, s1), s2)
1604 //
1605 // Signalingness is ignored with ieee=0, so we fold to
1606 // minimumnum/maximumnum. With ieee=1, the v_min_f32 acts like llvm.minnum
1607 // with signaling nan handling. With ieee=0, like llvm.minimumnum except a
1608 // returned signaling nan will not be quieted.
1609
1610 // ieee=1
1611 // s0 snan: s2
1612 // s1 snan: s2
1613 // s2 snan: qnan
1614
1615 // s0 qnan: min(s1, s2)
1616 // s1 qnan: min(s0, s2)
1617 // s2 qnan: min(s0, s1)
1618
1619 // ieee=0
1620 // s0 _nan: min(s1, s2)
1621 // s1 _nan: min(s0, s2)
1622 // s2 _nan: min(s0, s1)
1623
1624 // med3 behavior with infinity
1625 // s0 +inf: max(s1, s2)
1626 // s1 +inf: max(s0, s2)
1627 // s2 +inf: max(s0, s1)
1628 // s0 -inf: min(s1, s2)
1629 // s1 -inf: min(s0, s2)
1630 // s2 -inf: min(s0, s1)
1631
1632 // Checking for NaN before canonicalization provides better fidelity when
1633 // mapping other operations onto fmed3 since the order of operands is
1634 // unchanged.
1635 Value *V = nullptr;
1636 const APFloat *ConstSrc0 = nullptr;
1637 const APFloat *ConstSrc1 = nullptr;
1638 const APFloat *ConstSrc2 = nullptr;
1639
1640 if ((match(Src0, m_APFloat(ConstSrc0)) &&
1641 (ConstSrc0->isNaN() || ConstSrc0->isInfinity())) ||
1642 isa<UndefValue>(Src0)) {
1643 const bool IsPosInfinity = ConstSrc0 && ConstSrc0->isPosInfinity();
1644 switch (fpenvIEEEMode(II)) {
1645 case KnownIEEEMode::On:
1646 // TODO: If Src2 is snan, does it need quieting?
1647 if (ConstSrc0 && ConstSrc0->isNaN() && ConstSrc0->isSignaling())
1648 return IC.replaceInstUsesWith(II, Src2);
1649
1650 V = IsPosInfinity ? IC.Builder.CreateMaxNum(Src1, Src2)
1651 : IC.Builder.CreateMinNum(Src1, Src2);
1652 break;
1653 case KnownIEEEMode::Off:
1654 V = IsPosInfinity ? IC.Builder.CreateMaximumNum(Src1, Src2)
1655 : IC.Builder.CreateMinimumNum(Src1, Src2);
1656 break;
1658 break;
1659 }
1660 } else if ((match(Src1, m_APFloat(ConstSrc1)) &&
1661 (ConstSrc1->isNaN() || ConstSrc1->isInfinity())) ||
1662 isa<UndefValue>(Src1)) {
1663 const bool IsPosInfinity = ConstSrc1 && ConstSrc1->isPosInfinity();
1664 switch (fpenvIEEEMode(II)) {
1665 case KnownIEEEMode::On:
1666 // TODO: If Src2 is snan, does it need quieting?
1667 if (ConstSrc1 && ConstSrc1->isNaN() && ConstSrc1->isSignaling())
1668 return IC.replaceInstUsesWith(II, Src2);
1669
1670 V = IsPosInfinity ? IC.Builder.CreateMaxNum(Src0, Src2)
1671 : IC.Builder.CreateMinNum(Src0, Src2);
1672 break;
1673 case KnownIEEEMode::Off:
1674 V = IsPosInfinity ? IC.Builder.CreateMaximumNum(Src0, Src2)
1675 : IC.Builder.CreateMinimumNum(Src0, Src2);
1676 break;
1678 break;
1679 }
1680 } else if ((match(Src2, m_APFloat(ConstSrc2)) &&
1681 (ConstSrc2->isNaN() || ConstSrc2->isInfinity())) ||
1682 isa<UndefValue>(Src2)) {
1683 switch (fpenvIEEEMode(II)) {
1684 case KnownIEEEMode::On:
1685 if (ConstSrc2 && ConstSrc2->isNaN() && ConstSrc2->isSignaling()) {
1686 auto *Quieted = ConstantFP::get(II.getType(), ConstSrc2->makeQuiet());
1687 return IC.replaceInstUsesWith(II, Quieted);
1688 }
1689
1690 V = (ConstSrc2 && ConstSrc2->isPosInfinity())
1691 ? IC.Builder.CreateMaxNum(Src0, Src1)
1692 : IC.Builder.CreateMinNum(Src0, Src1);
1693 break;
1694 case KnownIEEEMode::Off:
1695 V = (ConstSrc2 && ConstSrc2->isPosInfinity())
1696 ? IC.Builder.CreateMaximumNum(Src0, Src1)
1697 : IC.Builder.CreateMinimumNum(Src0, Src1);
1698 break;
1700 break;
1701 }
1702 }
1703
1704 if (V) {
1705 if (auto *CI = dyn_cast<CallInst>(V)) {
1706 CI->copyFastMathFlags(&II);
1707 CI->takeName(&II);
1708 }
1709 return IC.replaceInstUsesWith(II, V);
1710 }
1711
1712 bool Swap = false;
1713 // Canonicalize constants to RHS operands.
1714 //
1715 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
1716 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
1717 std::swap(Src0, Src1);
1718 Swap = true;
1719 }
1720
1721 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
1722 std::swap(Src1, Src2);
1723 Swap = true;
1724 }
1725
1726 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
1727 std::swap(Src0, Src1);
1728 Swap = true;
1729 }
1730
1731 if (Swap) {
1732 II.setArgOperand(0, Src0);
1733 II.setArgOperand(1, Src1);
1734 II.setArgOperand(2, Src2);
1735 return &II;
1736 }
1737
1738 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
1739 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
1740 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
1741 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
1742 C2->getValueAPF());
1743 return IC.replaceInstUsesWith(II,
1744 ConstantFP::get(II.getType(), Result));
1745 }
1746 }
1747 }
1748
1749 if (!ST->hasMed3_16())
1750 break;
1751
1752 // Repeat floating-point width reduction done for minnum/maxnum.
1753 // fmed3((fpext X), (fpext Y), (fpext Z)) -> fpext (fmed3(X, Y, Z))
1754 if (Value *X = matchFPExtFromF16(Src0)) {
1755 if (Value *Y = matchFPExtFromF16(Src1)) {
1756 if (Value *Z = matchFPExtFromF16(Src2)) {
1757 Value *NewCall = IC.Builder.CreateIntrinsic(
1758 IID, {X->getType()}, {X, Y, Z}, &II, II.getName());
1759 return new FPExtInst(NewCall, II.getType());
1760 }
1761 }
1762 }
1763
1764 break;
1765 }
1766 case Intrinsic::amdgcn_mbcnt_hi:
1767 // exec_hi is all 0, so this is just a copy.
1768 if (ST->isWave32())
1769 return IC.replaceInstUsesWith(II, II.getArgOperand(1));
1770 [[fallthrough]];
1771 case Intrinsic::amdgcn_mbcnt_lo: {
1772 ConstantRange AccRange =
1773 computeConstantRange(II.getArgOperand(1),
1774 /*ForSigned=*/false, IC.getSimplifyQuery());
1775 if (AccRange.isFullSet())
1776 return nullptr;
1777
1778 // TODO: Can raise lower bound by inspecting first argument.
1779 // Wave64 mbcnt_lo adds at most 32. Otherwise these add at most 31.
1780 unsigned MaxCount =
1781 IID == Intrinsic::amdgcn_mbcnt_lo && ST->isWave64() ? 32 : 31;
1782 ConstantRange MbcntRange(APInt(32, 0), APInt(32, MaxCount + 1));
1783 ConstantRange ComputedRange = AccRange.add(MbcntRange);
1784 if (ComputedRange.isFullSet())
1785 return nullptr;
1786
1787 if (std::optional<ConstantRange> ExistingRange = II.getRange()) {
1788 ComputedRange = ComputedRange.intersectWith(*ExistingRange);
1789 if (ComputedRange == *ExistingRange)
1790 return nullptr;
1791 }
1792
1793 II.addRangeRetAttr(ComputedRange);
1794 return nullptr;
1795 }
1796 case Intrinsic::amdgcn_ballot: {
1797 Value *Arg = II.getArgOperand(0);
1798 if (isa<PoisonValue>(Arg))
1799 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
1800
1801 if (auto *Src = dyn_cast<ConstantInt>(Arg)) {
1802 if (Src->isZero()) {
1803 // amdgcn.ballot(i1 0) is zero.
1804 return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType()));
1805 }
1806 }
1807 if (ST->isWave32() && II.getType()->getIntegerBitWidth() == 64) {
1808 // %b64 = call i64 ballot.i64(...)
1809 // =>
1810 // %b32 = call i32 ballot.i32(...)
1811 // %b64 = zext i32 %b32 to i64
1813 IC.Builder.CreateIntrinsic(Intrinsic::amdgcn_ballot,
1814 {IC.Builder.getInt32Ty()},
1815 {II.getArgOperand(0)}),
1816 II.getType());
1817 Call->takeName(&II);
1818 return IC.replaceInstUsesWith(II, Call);
1819 }
1820 break;
1821 }
1822 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
1823 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
1824 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
1825 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id: {
1826 const Function &F = *II.getFunction();
1827
1829 if (!ClusterDims.isFixedDims())
1830 break;
1831
1832 const auto &Dims = ClusterDims.getDims();
1833 if (Dims[0] == 0 || Dims[1] == 0 || Dims[2] == 0)
1834 break;
1835
1836 unsigned MaxID;
1837 switch (IID) {
1838 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
1839 MaxID = Dims[0] - 1;
1840 break;
1841 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
1842 MaxID = Dims[1] - 1;
1843 break;
1844 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
1845 MaxID = Dims[2] - 1;
1846 break;
1847 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
1848 MaxID = Dims[0] * Dims[1] * Dims[2] - 1;
1849 break;
1850 default:
1851 llvm_unreachable("Unexpected cluster size intrinsic");
1852 }
1853
1854 return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), MaxID));
1855 }
1856 case Intrinsic::amdgcn_wavefrontsize: {
1857 if (ST->isWaveSizeKnown())
1858 return IC.replaceInstUsesWith(
1859 II, ConstantInt::get(II.getType(), ST->getWavefrontSize()));
1860 break;
1861 }
1862 case Intrinsic::amdgcn_wqm_vote: {
1863 // wqm_vote is identity when the argument is constant.
1864 if (!isa<Constant>(II.getArgOperand(0)))
1865 break;
1866
1867 return IC.replaceInstUsesWith(II, II.getArgOperand(0));
1868 }
1869 case Intrinsic::amdgcn_kill: {
1870 const ConstantInt *C = dyn_cast<ConstantInt>(II.getArgOperand(0));
1871 if (!C || !C->getZExtValue())
1872 break;
1873
1874 // amdgcn.kill(i1 1) is a no-op
1875 return IC.eraseInstFromFunction(II);
1876 }
1877 case Intrinsic::amdgcn_s_sendmsg:
1878 case Intrinsic::amdgcn_s_sendmsghalt: {
1879 // The second operand is copied to m0, but is only actually used for
1880 // certain message types. For message types that are known to not use m0,
1881 // fold it to poison.
1882 using namespace AMDGPU::SendMsg;
1883
1884 Value *M0Val = II.getArgOperand(1);
1885 if (isa<PoisonValue>(M0Val))
1886 break;
1887
1888 auto *MsgImm = cast<ConstantInt>(II.getArgOperand(0));
1889 uint16_t MsgId, OpId, StreamId;
1890 decodeMsg(static_cast<unsigned>(MsgImm->getZExtValue()), MsgId, OpId,
1891 StreamId, *ST);
1892
1893 if (!msgDoesNotUseM0(MsgId, *ST))
1894 break;
1895
1896 // Drop UB-implying attributes since we're replacing with poison.
1897 II.dropUBImplyingAttrsAndMetadata();
1898 IC.replaceOperand(II, 1, PoisonValue::get(M0Val->getType()));
1899 return nullptr;
1900 }
1901 case Intrinsic::amdgcn_update_dpp: {
1902 Value *Old = II.getArgOperand(0);
1903
1904 auto *BC = cast<ConstantInt>(II.getArgOperand(5));
1905 auto *RM = cast<ConstantInt>(II.getArgOperand(3));
1906 auto *BM = cast<ConstantInt>(II.getArgOperand(4));
1907 if (BC->isNullValue() || RM->getZExtValue() != 0xF ||
1908 BM->getZExtValue() != 0xF || isa<PoisonValue>(Old))
1909 break;
1910
1911 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
1912 return IC.replaceOperand(II, 0, PoisonValue::get(Old->getType()));
1913 }
1914 case Intrinsic::amdgcn_permlane16:
1915 case Intrinsic::amdgcn_permlane16_var:
1916 case Intrinsic::amdgcn_permlanex16:
1917 case Intrinsic::amdgcn_permlanex16_var: {
1918 // Discard vdst_in if it's not going to be read.
1919 Value *VDstIn = II.getArgOperand(0);
1920 if (isa<PoisonValue>(VDstIn))
1921 break;
1922
1923 // FetchInvalid operand idx.
1924 unsigned int FiIdx = (IID == Intrinsic::amdgcn_permlane16 ||
1925 IID == Intrinsic::amdgcn_permlanex16)
1926 ? 4 /* for permlane16 and permlanex16 */
1927 : 3; /* for permlane16_var and permlanex16_var */
1928
1929 // BoundCtrl operand idx.
1930 // For permlane16 and permlanex16 it should be 5
1931 // For Permlane16_var and permlanex16_var it should be 4
1932 unsigned int BcIdx = FiIdx + 1;
1933
1934 ConstantInt *FetchInvalid = cast<ConstantInt>(II.getArgOperand(FiIdx));
1935 ConstantInt *BoundCtrl = cast<ConstantInt>(II.getArgOperand(BcIdx));
1936 if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
1937 break;
1938
1939 return IC.replaceOperand(II, 0, PoisonValue::get(VDstIn->getType()));
1940 }
1941 case Intrinsic::amdgcn_wave_shuffle:
1942 return tryOptimizeShufflePattern(IC, II, *ST);
1943 case Intrinsic::amdgcn_permlane64:
1944 case Intrinsic::amdgcn_readfirstlane:
1945 case Intrinsic::amdgcn_readlane:
1946 case Intrinsic::amdgcn_ds_bpermute: {
1947 // If the data argument is uniform these intrinsics return it unchanged.
1948 unsigned SrcIdx = IID == Intrinsic::amdgcn_ds_bpermute ? 1 : 0;
1949 const Use &Src = II.getArgOperandUse(SrcIdx);
1951 return IC.replaceInstUsesWith(II, Src.get());
1952
1953 if (IID == Intrinsic::amdgcn_readlane &&
1955 return &II;
1956
1957 // If the lane argument of bpermute is uniform, change it to readlane. This
1958 // generates better code and can enable further optimizations because
1959 // readlane is AlwaysUniform.
1960 if (IID == Intrinsic::amdgcn_ds_bpermute) {
1961 const Use &Lane = II.getArgOperandUse(0);
1962 if (AMDGPU::isTriviallyUniform(Lane)) {
1963 Value *NewLane = IC.Builder.CreateLShr(Lane, 2);
1965 II.getModule(), Intrinsic::amdgcn_readlane, II.getType());
1966 II.setCalledFunction(NewDecl);
1967 II.setOperand(0, Src);
1968 II.setOperand(1, NewLane);
1969 return &II;
1970 }
1971 }
1972
1973 if (IID == Intrinsic::amdgcn_ds_bpermute)
1974 return tryOptimizeShufflePattern(IC, II, *ST);
1975
1977 return Res;
1978
1979 return std::nullopt;
1980 }
1981 case Intrinsic::amdgcn_wave_match_b32: {
1982 const Use &Src0 = II.getArgOperandUse(0);
1983 const Use &Src1 = II.getArgOperandUse(1);
1984 if (Src0.get() == Src1.get() && AMDGPU::isTriviallyUniform(Src0)) {
1986 II.getModule(), Intrinsic::amdgcn_ballot, II.getType());
1987 CallInst *NewCall =
1988 IC.Builder.CreateCall(NewF, {IC.Builder.getInt1(true)});
1989 return IC.replaceInstUsesWith(II, NewCall);
1990 }
1991 break;
1992 }
1993 case Intrinsic::amdgcn_writelane: {
1994 // TODO: Fold bitcast like readlane.
1995 if (simplifyDemandedLaneMaskArg(IC, II, 1))
1996 return &II;
1997 return std::nullopt;
1998 }
1999 case Intrinsic::amdgcn_trig_preop: {
2000 // The intrinsic is declared with name mangling, but currently the
2001 // instruction only exists for f64
2002 if (!II.getType()->isDoubleTy())
2003 break;
2004
2005 Value *Src = II.getArgOperand(0);
2006 Value *Segment = II.getArgOperand(1);
2007 if (isa<PoisonValue>(Src) || isa<PoisonValue>(Segment))
2008 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
2009
2010 if (isa<UndefValue>(Segment))
2011 return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType()));
2012
2013 // Sign bit is not used.
2014 Value *StrippedSign = InstCombiner::stripSignOnlyFPOps(Src);
2015 if (StrippedSign != Src)
2016 return IC.replaceOperand(II, 0, StrippedSign);
2017
2018 if (II.isStrictFP())
2019 break;
2020
2021 const ConstantFP *CSrc = dyn_cast<ConstantFP>(Src);
2022 if (!CSrc && !isa<UndefValue>(Src))
2023 break;
2024
2025 // The instruction ignores special cases, and literally just extracts the
2026 // exponents. Fold undef to nan, and index the table as normal.
2027 APInt FSrcInt = CSrc ? CSrc->getValueAPF().bitcastToAPInt()
2028 : APFloat::getQNaN(II.getType()->getFltSemantics())
2029 .bitcastToAPInt();
2030
2031 const ConstantInt *Cseg = dyn_cast<ConstantInt>(Segment);
2032 if (!Cseg) {
2033 if (isa<UndefValue>(Src))
2034 return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType()));
2035 break;
2036 }
2037
2038 unsigned Exponent =
2039 static_cast<unsigned>(FSrcInt.extractBitsAsZExtValue(11, 52));
2040 unsigned SegmentVal =
2041 static_cast<unsigned>(Cseg->getValue().trunc(5).getZExtValue());
2042 unsigned Shift = SegmentVal * 53;
2043 if (Exponent > 1077)
2044 Shift += Exponent - 1077;
2045
2046 // 2.0/PI table.
2047 static const uint32_t TwoByPi[] = {
2048 0xa2f9836e, 0x4e441529, 0xfc2757d1, 0xf534ddc0, 0xdb629599, 0x3c439041,
2049 0xfe5163ab, 0xdebbc561, 0xb7246e3a, 0x424dd2e0, 0x06492eea, 0x09d1921c,
2050 0xfe1deb1c, 0xb129a73e, 0xe88235f5, 0x2ebb4484, 0xe99c7026, 0xb45f7e41,
2051 0x3991d639, 0x835339f4, 0x9c845f8b, 0xbdf9283b, 0x1ff897ff, 0xde05980f,
2052 0xef2f118b, 0x5a0a6d1f, 0x6d367ecf, 0x27cb09b7, 0x4f463f66, 0x9e5fea2d,
2053 0x7527bac7, 0xebe5f17b, 0x3d0739f7, 0x8a5292ea, 0x6bfb5fb1, 0x1f8d5d08,
2054 0x56033046};
2055
2056 // Return 0 for outbound segment (hardware behavior).
2057 unsigned Idx = Shift >> 5;
2058 if (Idx + 2 >= std::size(TwoByPi)) {
2059 APFloat Zero = APFloat::getZero(II.getType()->getFltSemantics());
2060 return IC.replaceInstUsesWith(II, ConstantFP::get(II.getType(), Zero));
2061 }
2062
2063 unsigned BShift = Shift & 0x1f;
2064 uint64_t Thi = Make_64(TwoByPi[Idx], TwoByPi[Idx + 1]);
2065 uint64_t Tlo = Make_64(TwoByPi[Idx + 2], 0);
2066 if (BShift)
2067 Thi = (Thi << BShift) | (Tlo >> (64 - BShift));
2068 Thi = Thi >> 11;
2069 APFloat Result = APFloat((double)Thi);
2070
2071 int Scale = -53 - Shift;
2072 if (Exponent >= 1968)
2073 Scale += 128;
2074
2075 Result = scalbn(Result, Scale, RoundingMode::NearestTiesToEven);
2076 return IC.replaceInstUsesWith(II, ConstantFP::get(Src->getType(), Result));
2077 }
2078 case Intrinsic::amdgcn_sdot2:
2079 case Intrinsic::amdgcn_udot2:
2080 case Intrinsic::amdgcn_sdot4:
2081 case Intrinsic::amdgcn_udot4:
2082 case Intrinsic::amdgcn_sdot8:
2083 case Intrinsic::amdgcn_udot8: {
2084 Value *Src0 = II.getArgOperand(0);
2085 Value *Src1 = II.getArgOperand(1);
2086
2087 // Canonicalize the constant multiplicand to Src1.
2088 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2089 II.setArgOperand(0, Src1);
2090 II.setArgOperand(1, Src0);
2091 return &II;
2092 }
2093
2094 if (match(Src1, m_Zero()))
2095 return IC.replaceInstUsesWith(II, II.getArgOperand(2));
2096
2097 if (Instruction *I = foldAddIntoDotAccumulator(II, 2, 3, IC))
2098 return I;
2099
2100 break;
2101 }
2102 case Intrinsic::amdgcn_sudot4:
2103 case Intrinsic::amdgcn_sudot8: {
2104 Value *Src0 = II.getArgOperand(1);
2105 Value *Src1 = II.getArgOperand(3);
2106
2107 // Canonicalize the constant multiplicand to Src1, moving its sign flag with
2108 // it.
2109 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2110 Value *Sign0 = II.getArgOperand(0);
2111 Value *Sign1 = II.getArgOperand(2);
2112 II.setArgOperand(0, Sign1);
2113 II.setArgOperand(1, Src1);
2114 II.setArgOperand(2, Sign0);
2115 II.setArgOperand(3, Src0);
2116 return &II;
2117 }
2118
2119 if (match(Src1, m_Zero()))
2120 return IC.replaceInstUsesWith(II, II.getArgOperand(4));
2121
2122 if (Instruction *I = foldAddIntoDotAccumulator(II, 4, 5, IC))
2123 return I;
2124
2125 break;
2126 }
2127 case Intrinsic::amdgcn_fmul_legacy: {
2128 Value *Op0 = II.getArgOperand(0);
2129 Value *Op1 = II.getArgOperand(1);
2130
2131 for (Value *Src : {Op0, Op1}) {
2132 if (isa<PoisonValue>(Src))
2133 return IC.replaceInstUsesWith(II, Src);
2134 }
2135
2136 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
2137 // infinity, gives +0.0.
2138 // TODO: Move to InstSimplify?
2139 if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
2141 return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType()));
2142
2143 // If we can prove we don't have one of the special cases then we can use a
2144 // normal fmul instruction instead.
2145 if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
2146 auto *FMul = IC.Builder.CreateFMulFMF(Op0, Op1, &II);
2147 FMul->takeName(&II);
2148 return IC.replaceInstUsesWith(II, FMul);
2149 }
2150 break;
2151 }
2152 case Intrinsic::amdgcn_fma_legacy: {
2153 Value *Op0 = II.getArgOperand(0);
2154 Value *Op1 = II.getArgOperand(1);
2155 Value *Op2 = II.getArgOperand(2);
2156
2157 for (Value *Src : {Op0, Op1, Op2}) {
2158 if (isa<PoisonValue>(Src))
2159 return IC.replaceInstUsesWith(II, Src);
2160 }
2161
2162 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
2163 // infinity, gives +0.0.
2164 // TODO: Move to InstSimplify?
2165 if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
2167 // It's tempting to just return Op2 here, but that would give the wrong
2168 // result if Op2 was -0.0.
2169 auto *Zero = ConstantFP::getZero(II.getType());
2170 auto *FAdd = IC.Builder.CreateFAddFMF(Zero, Op2, &II);
2171 FAdd->takeName(&II);
2172 return IC.replaceInstUsesWith(II, FAdd);
2173 }
2174
2175 // If we can prove we don't have one of the special cases then we can use a
2176 // normal fma instead.
2177 if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) {
2178 II.setCalledOperand(Intrinsic::getOrInsertDeclaration(
2179 II.getModule(), Intrinsic::fma, II.getType()));
2180 return &II;
2181 }
2182 break;
2183 }
2184 case Intrinsic::amdgcn_is_shared:
2185 case Intrinsic::amdgcn_is_private: {
2186 Value *Src = II.getArgOperand(0);
2187 if (isa<PoisonValue>(Src))
2188 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
2189 if (isa<UndefValue>(Src))
2190 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
2191
2192 if (isa<ConstantPointerNull>(II.getArgOperand(0)))
2193 return IC.replaceInstUsesWith(II, ConstantInt::getFalse(II.getType()));
2194 break;
2195 }
2196 case Intrinsic::amdgcn_make_buffer_rsrc: {
2197 Value *Src = II.getArgOperand(0);
2198 if (isa<PoisonValue>(Src))
2199 return IC.replaceInstUsesWith(II, PoisonValue::get(II.getType()));
2200
2201 // Normalize num_records to the correct width.
2202 std::optional<unsigned> Width = ST->getBufferResourceNumRecordsWidth();
2203 if (!Width)
2204 return std::nullopt;
2205 Type *NumRecordsTy = IC.Builder.getIntNTy(*Width);
2206 if (II.getArgOperand(2)->getType() == NumRecordsTy)
2207 return std::nullopt;
2208 SmallVector<Value *, 4> Args(II.args());
2209 Args[2] = IC.Builder.CreateZExtOrTrunc(Args[2], NumRecordsTy);
2211 Intrinsic::amdgcn_make_buffer_rsrc,
2212 {II.getType(), Src->getType(), NumRecordsTy}, Args);
2213 NewCall->copyMetadata(II);
2214 NewCall->setTailCallKind(II.getTailCallKind());
2215 // Copy over all attributes except those on num_records, which may no longer
2216 // be valid.
2217 NewCall->setAttributes(
2218 II.getAttributes().removeParamAttributes(II.getContext(), 2));
2219 NewCall->takeName(&II);
2220 return IC.replaceInstUsesWith(II, NewCall);
2221 }
2222 case Intrinsic::amdgcn_raw_buffer_store_format:
2223 case Intrinsic::amdgcn_raw_ptr_buffer_store_format:
2224 case Intrinsic::amdgcn_struct_buffer_store_format:
2225 case Intrinsic::amdgcn_struct_ptr_buffer_store_format:
2226 case Intrinsic::amdgcn_raw_tbuffer_store:
2227 case Intrinsic::amdgcn_raw_ptr_tbuffer_store:
2228 case Intrinsic::amdgcn_struct_tbuffer_store:
2229 case Intrinsic::amdgcn_struct_ptr_tbuffer_store:
2230 case Intrinsic::amdgcn_image_store_1d:
2231 case Intrinsic::amdgcn_image_store_1darray:
2232 case Intrinsic::amdgcn_image_store_2d:
2233 case Intrinsic::amdgcn_image_store_2darray:
2234 case Intrinsic::amdgcn_image_store_2darraymsaa:
2235 case Intrinsic::amdgcn_image_store_2dmsaa:
2236 case Intrinsic::amdgcn_image_store_3d:
2237 case Intrinsic::amdgcn_image_store_cube:
2238 case Intrinsic::amdgcn_image_store_mip_1d:
2239 case Intrinsic::amdgcn_image_store_mip_1darray:
2240 case Intrinsic::amdgcn_image_store_mip_2d:
2241 case Intrinsic::amdgcn_image_store_mip_2darray:
2242 case Intrinsic::amdgcn_image_store_mip_3d:
2243 case Intrinsic::amdgcn_image_store_mip_cube: {
2244 if (!isa<FixedVectorType>(II.getArgOperand(0)->getType()))
2245 break;
2246
2247 APInt DemandedElts;
2248 if (ST->hasDefaultComponentBroadcast())
2249 DemandedElts = defaultComponentBroadcast(II.getArgOperand(0));
2250 else if (ST->hasDefaultComponentZero())
2251 DemandedElts = trimTrailingZerosInVector(IC, II.getArgOperand(0), &II);
2252 else
2253 break;
2254
2255 if (simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts))
2256 return IC.eraseInstFromFunction(II);
2257
2258 break;
2259 }
2260 case Intrinsic::amdgcn_prng_b32: {
2261 auto *Src = II.getArgOperand(0);
2262 if (isa<UndefValue>(Src)) {
2263 return IC.replaceInstUsesWith(II, Src);
2264 }
2265 return std::nullopt;
2266 }
2267 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
2268 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
2269 Value *Src0 = II.getArgOperand(0);
2270 Value *Src1 = II.getArgOperand(1);
2271 uint64_t CBSZ = cast<ConstantInt>(II.getArgOperand(3))->getZExtValue();
2272 uint64_t BLGP = cast<ConstantInt>(II.getArgOperand(4))->getZExtValue();
2273 auto *Src0Ty = cast<FixedVectorType>(Src0->getType());
2274 auto *Src1Ty = cast<FixedVectorType>(Src1->getType());
2275
2276 auto getFormatNumRegs = [](uint64_t FormatVal) {
2277 switch (FormatVal) {
2280 return 6u;
2282 return 4u;
2285 return 8u;
2286 default:
2287 llvm_unreachable("invalid format value");
2288 }
2289 };
2290
2291 bool MadeChange = false;
2292 unsigned Src0NumElts = getFormatNumRegs(CBSZ);
2293 unsigned Src1NumElts = getFormatNumRegs(BLGP);
2294
2295 // Depending on the used format, fewer registers are required so shrink the
2296 // vector type.
2297 if (Src0Ty->getNumElements() > Src0NumElts) {
2298 Src0 = IC.Builder.CreateExtractVector(
2299 FixedVectorType::get(Src0Ty->getElementType(), Src0NumElts), Src0,
2300 uint64_t(0));
2301 MadeChange = true;
2302 }
2303
2304 if (Src1Ty->getNumElements() > Src1NumElts) {
2305 Src1 = IC.Builder.CreateExtractVector(
2306 FixedVectorType::get(Src1Ty->getElementType(), Src1NumElts), Src1,
2307 uint64_t(0));
2308 MadeChange = true;
2309 }
2310
2311 if (!MadeChange)
2312 return std::nullopt;
2313
2314 SmallVector<Value *, 10> Args(II.args());
2315 Args[0] = Src0;
2316 Args[1] = Src1;
2317
2318 Value *NewII = IC.Builder.CreateIntrinsic(
2319 IID, {Src0->getType(), Src1->getType()}, Args, &II);
2320 NewII->takeName(&II);
2321 return IC.replaceInstUsesWith(II, NewII);
2322 }
2323 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
2324 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
2325 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
2326 Value *Src0 = II.getArgOperand(1);
2327 Value *Src1 = II.getArgOperand(3);
2328 unsigned FmtA = cast<ConstantInt>(II.getArgOperand(0))->getZExtValue();
2329 uint64_t FmtB = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
2330 auto *Src0Ty = cast<FixedVectorType>(Src0->getType());
2331 auto *Src1Ty = cast<FixedVectorType>(Src1->getType());
2332
2333 bool MadeChange = false;
2334 unsigned Src0NumElts = AMDGPU::wmmaScaleF8F6F4FormatToNumRegs(FmtA);
2335 unsigned Src1NumElts = AMDGPU::wmmaScaleF8F6F4FormatToNumRegs(FmtB);
2336
2337 // Depending on the used format, fewer registers are required so shrink the
2338 // vector type.
2339 if (Src0Ty->getNumElements() > Src0NumElts) {
2340 Src0 = IC.Builder.CreateExtractVector(
2341 FixedVectorType::get(Src0Ty->getElementType(), Src0NumElts), Src0,
2342 IC.Builder.getInt64(0));
2343 MadeChange = true;
2344 }
2345
2346 if (Src1Ty->getNumElements() > Src1NumElts) {
2347 Src1 = IC.Builder.CreateExtractVector(
2348 FixedVectorType::get(Src1Ty->getElementType(), Src1NumElts), Src1,
2349 IC.Builder.getInt64(0));
2350 MadeChange = true;
2351 }
2352
2353 if (!MadeChange)
2354 return std::nullopt;
2355
2356 SmallVector<Value *, 13> Args(II.args());
2357 Args[1] = Src0;
2358 Args[3] = Src1;
2359
2360 Value *NewII = IC.Builder.CreateIntrinsic(
2361 IID, {II.getArgOperand(5)->getType(), Src0->getType(), Src1->getType()},
2362 Args, &II);
2363 NewII->takeName(&II);
2364 return IC.replaceInstUsesWith(II, NewII);
2365 }
2366 }
2367 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
2368 AMDGPU::getImageDimIntrinsicInfo(II.getIntrinsicID())) {
2369 return simplifyAMDGCNImageIntrinsic(ST, ImageDimIntr, II, IC);
2370 }
2371 if (std::optional<unsigned> ScaleArgIdx =
2373 if (simplifyExponentOnlyScaleArg(IC, II, *ScaleArgIdx))
2374 return &II;
2375 }
2376 return std::nullopt;
2377}
2378
2379/// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
2380///
2381/// The result of simplifying amdgcn image and buffer store intrinsics is updating
2382/// definitions of the intrinsics vector argument, not Uses of the result like
2383/// image and buffer loads.
2384/// Note: This only supports non-TFE/LWE image intrinsic calls; those have
2385/// struct returns.
2387 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts) const {
2388 // Only stores return void here; image stores take the dmask after the
2389 // stored value.
2390 const bool IsLoad = !II.getType()->isVoidTy();
2391 int DMaskIdx = -1;
2392 if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID()))
2393 DMaskIdx = IsLoad ? 0 : 1;
2394
2395 auto *IIVTy = cast<FixedVectorType>(IsLoad ? II.getType()
2396 : II.getOperand(0)->getType());
2397 unsigned VWidth = IIVTy->getNumElements();
2398 if (VWidth == 1)
2399 return nullptr;
2400 Type *EltTy = IIVTy->getElementType();
2401
2404
2405 // Assume the arguments are unchanged and later override them, if needed.
2406 SmallVector<Value *, 16> Args(II.args());
2407 uint64_t OffsetAdd = 0;
2408
2409 if (DMaskIdx < 0) {
2410 // Buffer case.
2411
2412 const unsigned ActiveBits = DemandedElts.getActiveBits();
2413 const unsigned UnusedComponentsAtFront = DemandedElts.countr_zero();
2414
2415 // Start assuming the prefix of elements is demanded, but possibly clear
2416 // some other bits if there are trailing zeros (unused components at front)
2417 // and update offset.
2418 DemandedElts = (1 << ActiveBits) - 1;
2419
2420 if (UnusedComponentsAtFront > 0) {
2421 const AMDGPU::BufferIntrinsicInfo *BufInfo =
2422 AMDGPU::lookupBufferIntrinsic(II.getIntrinsicID());
2423 // buffer_load_format takes its format from the resource, which is
2424 // unknown here.
2425 bool CanAdjustOffset = BufInfo &&
2426 (BufInfo->Kind == AMDGPU::BufferKindLoad ||
2427 BufInfo->Kind == AMDGPU::BufferKindSLoad) &&
2428 !BufInfo->isFormatFromRsrc();
2429 // If resulting type is vec3, there is no point in trimming the scalar
2430 // load with updated offset, as the vec3 would most likely be widened to
2431 // vec4 anyway during lowering.
2432 if (CanAdjustOffset && BufInfo->Kind == AMDGPU::BufferKindSLoad &&
2433 ActiveBits == 4 && UnusedComponentsAtFront == 1)
2434 CanAdjustOffset = false;
2435
2436 // Set for tbuffer loads, whose component size comes from the format.
2437 unsigned FormatBitsPerComp = 0;
2438 if (CanAdjustOffset && BufInfo->isTyped()) {
2439 const unsigned FormatIdx = *BufInfo->getFormatArg();
2440 // The format describes the whole element, so also drop the leading
2441 // components from it to keep the element ending at the same byte.
2442 // Lanes past the end of the format are filled in by the hardware
2443 // rather than loaded; leave such loads alone.
2444 const AMDGPU::GcnBufferFormatInfo *OldFormat =
2446 cast<ConstantInt>(Args[FormatIdx])->getZExtValue(), *ST);
2447 const AMDGPU::GcnBufferFormatInfo *NewFormat = nullptr;
2448 if (OldFormat && ActiveBits <= OldFormat->NumComponents)
2450 OldFormat->BitsPerComp,
2451 OldFormat->NumComponents - UnusedComponentsAtFront,
2452 OldFormat->NumFormat, *ST);
2453 if (NewFormat) {
2454 Args[FormatIdx] =
2455 ConstantInt::get(Args[FormatIdx]->getType(), NewFormat->Format);
2456 FormatBitsPerComp = OldFormat->BitsPerComp;
2457 } else {
2458 CanAdjustOffset = false;
2459 }
2460 }
2461
2462 if (CanAdjustOffset) {
2463 unsigned OffsetIdx = BufInfo->getOffsetArg();
2464 // Clear demanded bits and update the offset.
2465 DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
2466 auto *Offset = Args[OffsetIdx];
2467 uint64_t SingleComponentSizeInBits =
2468 FormatBitsPerComp
2469 ? FormatBitsPerComp
2471 OffsetAdd = UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
2472 auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
2473 Args[OffsetIdx] = IC.Builder.CreateAdd(Offset, OffsetAddVal);
2474 }
2475 }
2476 } else {
2477 // Image case.
2478
2479 ConstantInt *DMask = cast<ConstantInt>(Args[DMaskIdx]);
2480 unsigned DMaskVal = DMask->getZExtValue() & 0xf;
2481
2482 // dmask 0 has special semantics, do not simplify.
2483 if (DMaskVal == 0)
2484 return nullptr;
2485
2486 if (!IsLoad && !isMask_32(DMaskVal))
2487 return nullptr;
2488
2489 // Mask off values that are undefined because the dmask doesn't cover them
2490 DemandedElts &= (1 << llvm::popcount(DMaskVal)) - 1;
2491
2492 unsigned NewDMaskVal = 0;
2493 unsigned OrigLdStIdx = 0;
2494 for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
2495 const unsigned Bit = 1 << SrcIdx;
2496 if (!!(DMaskVal & Bit)) {
2497 if (!!DemandedElts[OrigLdStIdx])
2498 NewDMaskVal |= Bit;
2499 OrigLdStIdx++;
2500 }
2501 }
2502
2503 if (DMaskVal != NewDMaskVal)
2504 Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
2505 }
2506
2507 unsigned NewNumElts = DemandedElts.popcount();
2508 if (!NewNumElts)
2509 return PoisonValue::get(IIVTy);
2510
2511 if (NewNumElts >= VWidth && DemandedElts.isMask()) {
2512 if (DMaskIdx >= 0)
2513 II.setArgOperand(DMaskIdx, Args[DMaskIdx]);
2514 return nullptr;
2515 }
2516
2517 // Validate function argument and return types, extracting overloaded types
2518 // along the way.
2519 SmallVector<Type *, 6> OverloadTys;
2520 if (!Intrinsic::isSignatureValid(II.getCalledFunction(), OverloadTys))
2521 return nullptr;
2522
2523 Type *NewTy =
2524 (NewNumElts == 1) ? EltTy : FixedVectorType::get(EltTy, NewNumElts);
2525 OverloadTys[0] = NewTy;
2526
2527 if (!IsLoad) {
2528 SmallVector<int, 8> EltMask;
2529 for (unsigned OrigStoreIdx = 0; OrigStoreIdx < VWidth; ++OrigStoreIdx)
2530 if (DemandedElts[OrigStoreIdx])
2531 EltMask.push_back(OrigStoreIdx);
2532
2533 if (NewNumElts == 1)
2534 Args[0] = IC.Builder.CreateExtractElement(II.getOperand(0), EltMask[0]);
2535 else
2536 Args[0] = IC.Builder.CreateShuffleVector(II.getOperand(0), EltMask);
2537 }
2538
2540 II.getIntrinsicID(), OverloadTys, Args);
2541 NewCall->takeName(&II);
2542 NewCall->copyMetadata(II);
2543 AttributeList OldAttrList = II.getAttributes();
2544 NewCall->setAttributes(OldAttrList);
2545
2546 if (OffsetAdd != 0) {
2547 unsigned RsrcArg =
2548 AMDGPU::lookupRsrcIntrinsic(II.getIntrinsicID())->RsrcArg;
2549 if (MaybeAlign RsrcAlign = NewCall->getParamAlign(RsrcArg)) {
2550 NewCall->removeParamAttr(RsrcArg, Attribute::Alignment);
2551 NewCall->addParamAttr(
2552 RsrcArg,
2554 commonAlignment(*RsrcAlign, OffsetAdd)));
2555 }
2556 }
2557
2558 if (IsLoad) {
2559 if (NewNumElts == 1) {
2560 return IC.Builder.CreateInsertElement(PoisonValue::get(IIVTy), NewCall,
2561 DemandedElts.countr_zero());
2562 }
2563
2564 SmallVector<int, 8> EltMask;
2565 unsigned NewLoadIdx = 0;
2566 for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
2567 if (!!DemandedElts[OrigLoadIdx])
2568 EltMask.push_back(NewLoadIdx++);
2569 else
2570 EltMask.push_back(NewNumElts);
2571 }
2572
2573 auto *Shuffle = IC.Builder.CreateShuffleVector(NewCall, EltMask);
2574
2575 return Shuffle;
2576 }
2577
2578 return NewCall;
2579}
2580
2582 InstCombiner &IC, IntrinsicInst &II, const APInt &DemandedElts,
2583 APInt &UndefElts) const {
2584 auto *VT = dyn_cast<FixedVectorType>(II.getType());
2585 if (!VT)
2586 return nullptr;
2587
2588 const unsigned FirstElt = DemandedElts.countr_zero();
2589 const unsigned LastElt = DemandedElts.getActiveBits() - 1;
2590 const unsigned MaskLen = LastElt - FirstElt + 1;
2591
2592 unsigned OldNumElts = VT->getNumElements();
2593 if (MaskLen == OldNumElts && MaskLen != 1)
2594 return nullptr;
2595
2596 Type *EltTy = VT->getElementType();
2597 Type *NewVT = MaskLen == 1 ? EltTy : FixedVectorType::get(EltTy, MaskLen);
2598
2599 // Theoretically we should support these intrinsics for any legal type. Avoid
2600 // introducing cases that aren't direct register types like v3i16.
2601 if (!isTypeLegal(NewVT))
2602 return nullptr;
2603
2604 Value *Src = II.getArgOperand(0);
2605
2606 // Make sure convergence tokens are preserved.
2607 // TODO: CreateIntrinsic should allow directly copying bundles
2609 II.getOperandBundlesAsDefs(OpBundles);
2610
2611 Module *M = IC.Builder.getModule();
2612 Function *Remangled =
2613 Intrinsic::getOrInsertDeclaration(M, II.getIntrinsicID(), {NewVT});
2614
2615 if (MaskLen == 1) {
2616 Value *Extract = IC.Builder.CreateExtractElement(Src, FirstElt);
2617
2618 // TODO: Preserve callsite attributes?
2619 CallInst *NewCall = IC.Builder.CreateCall(Remangled, {Extract}, OpBundles);
2620
2621 return IC.Builder.CreateInsertElement(PoisonValue::get(II.getType()),
2622 NewCall, FirstElt);
2623 }
2624
2625 SmallVector<int> ExtractMask(MaskLen, -1);
2626 for (unsigned I = 0; I != MaskLen; ++I) {
2627 if (DemandedElts[FirstElt + I])
2628 ExtractMask[I] = FirstElt + I;
2629 }
2630
2631 Value *Extract = IC.Builder.CreateShuffleVector(Src, ExtractMask);
2632
2633 // TODO: Preserve callsite attributes?
2634 CallInst *NewCall = IC.Builder.CreateCall(Remangled, {Extract}, OpBundles);
2635
2636 SmallVector<int> InsertMask(OldNumElts, -1);
2637 for (unsigned I = 0; I != MaskLen; ++I) {
2638 if (DemandedElts[FirstElt + I])
2639 InsertMask[FirstElt + I] = I;
2640 }
2641
2642 // FIXME: If the call has a convergence bundle, we end up leaving the dead
2643 // call behind.
2644 return IC.Builder.CreateShuffleVector(NewCall, InsertMask);
2645}
2646
2648 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
2649 APInt &UndefElts2, APInt &UndefElts3,
2650 std::function<void(Instruction *, unsigned, APInt, APInt &)>
2651 SimplifyAndSetOp) const {
2652 switch (II.getIntrinsicID()) {
2653 case Intrinsic::amdgcn_readfirstlane:
2654 SimplifyAndSetOp(&II, 0, DemandedElts, UndefElts);
2655 return simplifyAMDGCNLaneIntrinsicDemanded(IC, II, DemandedElts, UndefElts);
2656 default:
2657 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
2658 AMDGPU::lookupBufferIntrinsic(II.getIntrinsicID());
2659 BufInfo && (BufInfo->Kind == AMDGPU::BufferKindLoad ||
2660 BufInfo->Kind == AMDGPU::BufferKindSLoad))
2661 return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts);
2662 if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID()))
2663 return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts);
2664 break;
2665 }
2666 return std::nullopt;
2667}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static Value * createPermlane16(IRBuilderBase &B, Value *Val, uint32_t Lo, uint32_t Hi)
Emit v_permlane16 with the precomputed lane-select halves.
static std::optional< unsigned > matchRowSharePattern(ArrayRef< uint8_t > Ids)
Match a row-share pattern: all 16 lanes of each row read the same source lane.
static bool matchMirrorPattern(ArrayRef< uint8_t > Ids)
Match an N-lane reversal (mirror) pattern.
static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat, bool AllowI16SExt=false)
static bool tryBuildShuffleMap(Value *Index, const GCNSubtarget &ST, SmallVectorImpl< uint8_t > &Ids, const DataLayout &DL)
Build the per-lane shuffle map by evaluating Index for every lane in the wave.
static std::optional< unsigned > matchQuadPermPattern(ArrayRef< uint8_t > Ids)
Match a 4-lane (quad) permutation, encoded as the v_mov_b32_dpp QUAD_PERM control word: bits[1:0]=Ids...
static std::optional< unsigned > matchDsSwizzleRotatePattern(ArrayRef< uint8_t > Ids)
Match a GFX9+ DS_SWIZZLE rotate-mode permutation: a cyclic left-rotation of all 32 lanes within each ...
static std::optional< unsigned > matchHalfRowPermPattern(ArrayRef< uint8_t > Ids)
Match an 8-lane arbitrary permutation, encoded as the v_mov_b32_dpp8 24-bit selector (three bits per ...
static std::optional< unsigned > matchRowXMaskPattern(ArrayRef< uint8_t > Ids)
Match an XOR mask pattern within each 16-lane row: Ids[J] == Mask ^ J, with Mask in [1,...
static constexpr auto matchHalfRowMirrorPattern
static Value * createPermlaneX16(IRBuilderBase &B, Value *Val, uint32_t Lo, uint32_t Hi)
Emit v_permlanex16 with the precomputed lane-select halves.
static bool isRowPattern(ArrayRef< uint8_t > Ids)
Match an N-lane row pattern: each lane in [0, N) reads from a source lane in the same N-lane row,...
static bool canContractSqrtToRsq(const FPMathOperator *SqrtOp)
Return true if it's legal to contract llvm.amdgcn.rcp(llvm.sqrt)
static CallInst * rewriteCall(IRBuilderBase &B, CallInst &Old, Function &NewCallee, ArrayRef< Value * > Ops)
static Value * convertTo16Bit(Value &V, InstCombiner::BuilderTy &Builder)
static constexpr auto isFullRowPattern
static constexpr auto isQuadPattern
static APInt trimTrailingZerosInVector(InstCombiner &IC, Value *UseV, Instruction *I)
static uint64_t computePermlane16Masks(ArrayRef< uint8_t > Ids)
Pack a 16-lane permutation into a single 64-bit value: four bits per output lane, lane J in bits [J*4...
static bool matchHalfWaveSwapPattern(ArrayRef< uint8_t > Ids)
Match a half-wave swap: lane J reads from lane J ^ 32.
static bool hasPeriodicLayout(ArrayRef< uint8_t > Ids)
Lanes are partitioned into groups of Period; each group is a translated copy of the first: Ids[I] = I...
static std::optional< uint64_t > evalLaneExpr(Value *V, unsigned Lane, const GCNSubtarget &ST, const DataLayout &DL, unsigned Depth=0)
Evaluate V as a function of the lane ID and return its value on Lane, or std::nullopt if V is not a c...
static std::optional< Instruction * > tryOptimizeShufflePattern(InstCombiner &IC, IntrinsicInst &II, const GCNSubtarget &ST)
Try to fold a wave_shuffle/ds_bpermute whose lane index is a constant function of the lane ID into a ...
static constexpr auto isHalfRowPattern
static APInt defaultComponentBroadcast(Value *V)
static std::optional< unsigned > matchDsSwizzleBitmaskPattern(ArrayRef< uint8_t > Ids)
Match a DS_SWIZZLE bitmask-mode permutation: dst_lane = ((src_lane & AND) | OR) ^ XOR with each mask ...
static Value * createDsSwizzle(IRBuilderBase &B, Value *Val, unsigned Offset, const DataLayout &DL)
Emit ds_swizzle with the given immediate, bitcasting/converting between pointer/float types and i32 a...
static std::optional< Instruction * > modifyIntrinsicCall(IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr, InstCombiner &IC, std::function< void(SmallVectorImpl< Value * > &, SmallVectorImpl< Type * > &)> Func)
Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with modified arguments (based on ...
static Value * matchShuffleToHWIntrinsic(IRBuilderBase &B, Value *Src, ArrayRef< uint8_t > Ids, const GCNSubtarget &ST, const DataLayout &DL)
Given a shuffle map, try to emit the best hardware intrinsic.
static std::optional< unsigned > matchRowRotatePattern(ArrayRef< uint8_t > Ids)
Match a 16-lane cyclic rotation; returns the rotation amount in [1, 15].
static bool isCrossRowPattern(ArrayRef< uint8_t > Ids)
Match a cross-row permutation suitable for v_permlanex16: every lane in the low 16-lane half reads fr...
static bool isThreadID(const GCNSubtarget &ST, Value *V)
static Value * createUpdateDpp(IRBuilderBase &B, Value *Val, unsigned Ctrl)
Emit v_mov_b32_dpp with the given control word, row/bank masks 0xF, and bound_ctrl=1 so out-of-bounds...
static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, const APFloat &Src2)
static std::optional< Instruction * > simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST, const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr, IntrinsicInst &II, InstCombiner &IC)
static Value * createMovDpp8(IRBuilderBase &B, Value *Val, unsigned Selector)
Emit v_mov_b32_dpp8 with the given 24-bit lane selector.
static Instruction * foldAddIntoDotAccumulator(IntrinsicInst &II, unsigned AccIdx, unsigned ClampIdx, InstCombiner &IC)
Try to fold an addition into the accumulator when saturation is disabled.
static Value * matchFPExtFromF16(Value *Arg)
Match an fpext from half to float, or a constant we can convert.
static constexpr auto matchFullRowMirrorPattern
static bool simplifyExponentOnlyScaleArg(InstCombiner &IC, IntrinsicInst &II, unsigned ScaleArgIdx)
Simplify the f32 scale operand of a V_CVT_SCALEF32_* conversion, of which only the exponent field is ...
static Value * createPermlane64(IRBuilderBase &B, Value *Val)
Emit v_permlane64 (swap of the two 32-lane halves of a wave64).
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
This file a TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
AMD GCN specific subclass of TargetSubtarget.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
int64_t C1
int64_t C0
MachineInstr *& Lo
This file contains some templates that are useful if you are working with the STL at all.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
static ClusterDimsAttr get(const Function &F)
const std::array< unsigned, 3 > & getDims() const
static constexpr roundingMode rmTowardZero
Definition APFloat.h:384
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:380
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:305
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1253
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6101
bool bitwiseIsEqual(const APFloat &RHS) const
Definition APFloat.h:1577
bool isPosInfinity() const
Definition APFloat.h:1625
APFloat makeQuiet() const
Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
Definition APFloat.h:1449
bool isNaN() const
Definition APFloat.h:1610
bool isSignaling() const
Definition APFloat.h:1614
APInt bitcastToAPInt() const
Definition APFloat.h:1504
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1212
bool isInfinity() const
Definition APFloat.h:1609
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:517
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
bool isMask(unsigned numBits) const
Definition APInt.h:484
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
bool isTypeLegal(Type *Ty) const override
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Removes the attribute from the given argument.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
void setAttributes(AttributeList A)
Set the attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:794
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Tagged union holding either a T or a Error.
Definition Error.h:485
This class represents an extension of floating point types.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition Operator.h:291
bool hasApproxFunc() const
Test if this operation allows approximations of math library functions or intrinsics.
Definition Operator.h:288
LLVM_ABI float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool allowContract() const
Definition FMF.h:69
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
bool simplifyDemandedLaneMaskArg(InstCombiner &IC, IntrinsicInst &II, unsigned LaneAgIdx) const
Simplify a lane index operand (e.g.
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
Instruction * hoistLaneIntrinsicThroughOperand(InstCombiner &IC, IntrinsicInst &II) const
Value * simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts) const
Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const override
KnownIEEEMode fpenvIEEEMode(const Instruction &I) const
Return KnownIEEEMode::On if we know if the use context can assume "amdgpu-ieee"="true" and KnownIEEEM...
Value * simplifyAMDGCNLaneIntrinsicDemanded(InstCombiner &IC, IntrinsicInst &II, const APInt &DemandedElts, APInt &UndefElts) const
bool canSimplifyLegacyMulToMul(const Instruction &I, const Value *Op0, const Value *Op1, InstCombiner &IC) const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:446
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:541
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1114
Module * getModule() const
Get the module.
Definition IRBuilder.h:190
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2462
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
Value * CreateMaxNum(Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create call to the maxnum intrinsic.
Definition IRBuilder.h:1045
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateMaximumNum(Value *LHS, Value *RHS, const Twine &Name="")
Create call to the maximum intrinsic.
Definition IRBuilder.h:1073
Value * CreateMinNum(Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create call to the minnum intrinsic.
Definition IRBuilder.h:1033
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateFAddFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1643
Value * CreateMinimumNum(Value *LHS, Value *RHS, const Twine &Name="")
Create call to the minimumnum intrinsic.
Definition IRBuilder.h:1067
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1553
Value * CreateFMulFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1681
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
The core instruction combiner logic.
const DataLayout & getDataLayout() const
virtual Instruction * eraseInstFromFunction(Instruction &I)=0
Combiner aware instruction erasure.
DominatorTree & getDominatorTree() const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
virtual bool SimplifyDemandedBits(Instruction *I, unsigned OpNo, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)=0
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
static Value * stripSignOnlyFPOps(Value *Val)
Ignore all operations which only change the sign of a value, returning the underlying magnitude value...
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
void dropPoisonGeneratingAnnotations()
Drops flags, attributes and metadata that may generate poison.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:293
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:269
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:158
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
APInt getExponentOnlyScaleDemandedBits()
LLVM_READONLY const MIMGOffsetMappingInfo * getMIMGOffsetMappingInfo(unsigned Offset)
uint8_t wmmaScaleF8F6F4FormatToNumRegs(unsigned Fmt)
const ImageDimIntrinsicInfo * getImageDimIntrinsicByBaseOpcode(unsigned BaseOpcode, unsigned Dim)
std::optional< unsigned > getExponentOnlyScaleArgIdx(unsigned IntrID)
LLVM_READONLY const MIMGMIPMappingInfo * getMIMGMIPMappingInfo(unsigned MIP)
bool isTriviallyUniform(const Value *V, const Instruction *CtxI)
Return true if we can easily prove that V is uniform at CtxI.
const BufferIntrinsicInfo * lookupBufferIntrinsic(unsigned Intr)
LLVM_READONLY const MIMGBiasMappingInfo * getMIMGBiasMappingInfo(unsigned Bias)
std::optional< APFloat > evaluateRcp(const APFloat &Val)
Evaluate the constant-folded result of v_rcp for Val, accounting for the hardware's denormal flushing...
LLVM_READONLY const MIMGLZMappingInfo * getMIMGLZMappingInfo(unsigned L)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfo(unsigned DimEnum)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
const RsrcIntrinsic * lookupRsrcIntrinsic(unsigned Intr)
const GcnBufferFormatInfo * getGcnBufferFormatInfo(uint8_t BitsPerComp, uint8_t NumComponents, uint8_t NumFormat, const MCSubtargetInfo &STI)
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_ConstantFP()
Match an arbitrary ConstantFP and ignore it.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:256
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1757
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1800
constexpr unsigned MaxAnalysisRecursionDepth
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1745
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
@ FMul
Product of floats.
@ FAdd
Sum of floats.
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
@ NearestTiesToEven
roundTiesToEven.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition MathExtras.h:161
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
The argument layout of a buffer intrinsic.
bool isFormatFromRsrc() const
Whether the data is converted according to the format in the resource.
unsigned getOffsetArg() const
The main offset: the voffset if there is one, and the soffset otherwise.
std::optional< unsigned > getFormatArg() const
Represent subnormal handling kind for floating point instruction inputs and outputs.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
SimplifyQuery getWithInstruction(const Instruction *I) const
LLVM_ABI bool isUndefValue(Value *V) const
If CanUseUndef is true, returns whether V is undef.