LLVM 24.0.0git
AMDGPUAsmParser.cpp
Go to the documentation of this file.
1//===- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ----------===//
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#include "AMDKernelCodeT.h"
16#include "SIDefines.h"
17#include "SIInstrInfo.h"
22#include "llvm/ADT/APFloat.h"
24#include "llvm/ADT/Twine.h"
27#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCExpr.h"
30#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstrDesc.h"
37#include "llvm/MC/MCSymbol.h"
46#include <optional>
47
48using namespace llvm;
49using namespace llvm::AMDGPU;
50using namespace llvm::amdhsa;
51
52namespace {
53
54class AMDGPUAsmParser;
55
56enum RegisterKind {
57 IS_UNKNOWN,
58 IS_VGPR,
59 IS_SGPR,
60 IS_AGPR,
61 IS_TTMP,
62 IS_SPECIAL
63};
64
65//===----------------------------------------------------------------------===//
66// Operand
67//===----------------------------------------------------------------------===//
68
69class AMDGPUOperand : public MCParsedAsmOperand {
70 enum KindTy { Token, Immediate, Register, Expression } Kind;
71
72 SMLoc StartLoc, EndLoc;
73 const AMDGPUAsmParser *AsmParser;
74
75public:
76 AMDGPUOperand(KindTy Kind_, const AMDGPUAsmParser *AsmParser_)
77 : Kind(Kind_), AsmParser(AsmParser_) {}
78
79 using Ptr = std::unique_ptr<AMDGPUOperand>;
80
81 struct Modifiers {
82 bool Abs = false;
83 bool Neg = false;
84 bool Sext = false;
85 LitModifier Lit = LitModifier::None;
86
87 bool hasFPModifiers() const { return Abs || Neg; }
88 bool hasIntModifiers() const { return Sext; }
89 bool hasModifiers() const { return hasFPModifiers() || hasIntModifiers(); }
90 bool isForcedLit() const { return Lit == LitModifier::Lit; }
91 bool isForcedLit64() const { return Lit == LitModifier::Lit64; }
92
93 int64_t getFPModifiersOperand() const {
94 int64_t Operand = 0;
95 Operand |= Abs ? SISrcMods::ABS : 0u;
96 Operand |= Neg ? SISrcMods::NEG : 0u;
97 return Operand;
98 }
99
100 int64_t getIntModifiersOperand() const {
101 int64_t Operand = 0;
102 Operand |= Sext ? SISrcMods::SEXT : 0u;
103 return Operand;
104 }
105
106 int64_t getModifiersOperand() const {
107 assert(!(hasFPModifiers() && hasIntModifiers()) &&
108 "fp and int modifiers should not be used simultaneously");
109 if (hasFPModifiers())
110 return getFPModifiersOperand();
111 if (hasIntModifiers())
112 return getIntModifiersOperand();
113 return 0;
114 }
115
116 friend raw_ostream &operator<<(raw_ostream &OS,
117 AMDGPUOperand::Modifiers Mods);
118 };
119
120 enum ImmTy {
121 ImmTyNone,
122 ImmTyGDS,
123 ImmTyLDS,
124 ImmTyOffen,
125 ImmTyIdxen,
126 ImmTyAddr64,
127 ImmTyOffset,
128 ImmTyInstOffset,
129 ImmTyOffset0,
130 ImmTyOffset1,
131 ImmTySMEMOffsetMod,
132 ImmTyCPol,
133 ImmTyTFE,
134 ImmTyIsAsync,
135 ImmTyD16,
136 ImmTyClamp,
137 ImmTyOModSI,
138 ImmTySDWADstSel,
139 ImmTySDWASrc0Sel,
140 ImmTySDWASrc1Sel,
141 ImmTySDWADstUnused,
142 ImmTyDMask,
143 ImmTyDim,
144 ImmTyUNorm,
145 ImmTyDA,
146 ImmTyR128A16,
147 ImmTyA16,
148 ImmTyLWE,
149 ImmTyExpTgt,
150 ImmTyExpCompr,
151 ImmTyExpVM,
152 ImmTyDone,
153 ImmTyRowEn,
154 ImmTyFormat,
155 ImmTyFormatOp,
156 ImmTyHwreg,
157 ImmTyOff,
158 ImmTySendMsg,
159 ImmTyWaitEvent,
160 ImmTyInterpSlot,
161 ImmTyInterpAttr,
162 ImmTyInterpAttrChan,
163 ImmTyOpSel,
164 ImmTyOpSelHi,
165 ImmTyNegLo,
166 ImmTyNegHi,
167 ImmTyIndexKey8bit,
168 ImmTyIndexKey16bit,
169 ImmTyIndexKey32bit,
170 ImmTyDPP8,
171 ImmTyDppCtrl,
172 ImmTyDppRowMask,
173 ImmTyDppBankMask,
174 ImmTyDppBoundCtrl,
175 ImmTyDppFI,
176 ImmTySwizzle,
177 ImmTyGprIdxMode,
178 ImmTyHigh,
179 ImmTyBLGP,
180 ImmTyCBSZ,
181 ImmTyABID,
182 ImmTyEndpgm,
183 ImmTyWaitVDST,
184 ImmTyWaitEXP,
185 ImmTyWaitVAVDst,
186 ImmTyWaitVMVSrc,
187 ImmTyBitOp3,
188 ImmTyMatrixAFMT,
189 ImmTyMatrixBFMT,
190 ImmTyMatrixAScale,
191 ImmTyMatrixBScale,
192 ImmTyMatrixAScaleFmt,
193 ImmTyMatrixBScaleFmt,
194 ImmTyMatrixAReuse,
195 ImmTyMatrixBReuse,
196 ImmTyScaleSel,
197 ImmTyByteSel,
198 };
199
200private:
201 struct TokOp {
202 const char *Data;
203 unsigned Length;
204 };
205
206 struct ImmOp {
207 int64_t Val;
208 ImmTy Type;
209 bool IsFPImm;
210 Modifiers Mods;
211 };
212
213 struct RegOp {
214 MCRegister RegNo;
215 Modifiers Mods;
216 };
217
218 union {
219 TokOp Tok;
220 ImmOp Imm;
221 RegOp Reg;
222 const MCExpr *Expr;
223 };
224
225 // The index of the associated MCInst operand.
226 mutable int MCOpIdx = -1;
227
228public:
229 bool isToken() const override { return Kind == Token; }
230
231 bool isSymbolRefExpr() const {
232 return isExpr() && Expr && isa<MCSymbolRefExpr>(Expr);
233 }
234
235 bool hasSymbolSpecifier() const {
236 return isSymbolRefExpr() &&
239 }
240
241 bool isImm() const override { return Kind == Immediate; }
242
243 bool isInlinableImm(MVT type) const;
244 bool isLiteralImm(MVT type) const;
245
246 bool isRegKind() const { return Kind == Register; }
247
248 bool isReg() const override { return isRegKind() && !hasModifiers(); }
249
250 bool isRegOrInline(unsigned RCID, MVT type) const {
251 return isRegClass(RCID) || isInlinableImm(type);
252 }
253
254 bool isRegOrInlineTarget(unsigned TargetRCIdx, MVT type) const {
255 return isRegClassTarget(TargetRCIdx) || isInlinableImm(type);
256 }
257
258 bool isRegOrImmWithInputMods(unsigned RCID, MVT type) const {
259 return isRegOrInline(RCID, type) || isLiteralImm(type);
260 }
261
262 bool isRegOrImmWithInputModsTarget(unsigned TargetRCIdx, MVT type) const {
263 return isRegOrInlineTarget(TargetRCIdx, type) || isLiteralImm(type);
264 }
265
266 template <bool IsFake16> bool isRegOrImmWithIntT16InputMods() const {
268 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::i16);
269 }
270
271 bool isRegOrImmWithInt32InputMods() const {
272 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::i32);
273 }
274
275 template <bool IsFake16> bool isRegOrInlineImmWithIntT16InputMods() const {
276 return isRegOrInline(
277 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::i16);
278 }
279
280 bool isRegOrInlineImmWithInt32InputMods() const {
281 return isRegOrInline(AMDGPU::VS_32RegClassID, MVT::i32);
282 }
283
284 bool isRegOrImmWithInt64InputMods() const {
285 return isRegOrImmWithInputModsTarget(AMDGPU::VS_64_AlignTarget, MVT::i64);
286 }
287
288 bool isRegOrImmWithFP16InputMods() const {
289 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::f16);
290 }
291
292 template <bool IsFake16> bool isRegOrImmWithFPT16InputMods() const {
294 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::f16);
295 }
296
297 bool isRegOrImmWithFPT16_LO16InputMods() const {
298 return isRegOrImmWithInputMods(AMDGPU::VS_16_LO16RegClassID, MVT::f16);
299 }
300
301 bool isRegOrImmWithFP32InputMods() const {
302 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::f32);
303 }
304
305 bool isRegOrImmWithFP64InputMods() const {
306 return isRegOrImmWithInputModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
307 }
308
309 template <bool IsFake16> bool isRegOrInlineImmWithFP16InputMods() const {
310 return isRegOrInline(
311 IsFake16 ? AMDGPU::VS_32RegClassID : AMDGPU::VS_16RegClassID, MVT::f16);
312 }
313
314 bool isRegOrInlineImmWithFP32InputMods() const {
315 return isRegOrInline(AMDGPU::VS_32RegClassID, MVT::f32);
316 }
317
318 bool isRegOrInlineImmWithFP64InputMods() const {
319 return isRegOrInlineTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
320 }
321
322 bool isVRegWithInputMods(unsigned RCID) const { return isRegClass(RCID); }
323
324 bool isVRegWithFP32InputMods() const {
325 return isVRegWithInputMods(AMDGPU::VGPR_32RegClassID);
326 }
327
328 bool isVRegWithFP64InputMods() const {
329 return isRegClassTarget(AMDGPU::VReg_64_AlignTarget);
330 }
331
332 bool isPackedFP16InputMods() const {
333 return isRegOrImmWithInputMods(AMDGPU::VS_32RegClassID, MVT::v2f16);
334 }
335
336 bool isPackedVGPRFP32InputMods() const {
337 return isRegOrImmWithInputMods(AMDGPU::VReg_64RegClassID, MVT::v2f32);
338 }
339
340 bool isVReg32() const { return isRegClass(AMDGPU::VGPR_32RegClassID); }
341
342 bool isVReg32OrOff() const { return isOff() || isVReg32(); }
343
344 bool isRsrcReg32() const { return isRegClass(AMDGPU::RsrcReg32RegClassID); }
345
346 bool isNull() const { return isRegKind() && getReg() == AMDGPU::SGPR_NULL; }
347
348 bool isAV_LdSt_32_Align2_RegOp() const {
349 return isRegClass(AMDGPU::VGPR_32RegClassID) ||
350 isRegClass(AMDGPU::AGPR_32RegClassID);
351 }
352
353 bool isVRegWithInputMods() const;
354 template <bool IsFake16> bool isT16_Lo128VRegWithInputMods() const;
355 template <bool IsFake16> bool isT16VRegWithInputMods() const;
356 bool isT16_LO16VRegWithInputMods() const;
357
358 bool isSDWAOperand(MVT type) const;
359 bool isSDWAFP16Operand() const;
360 bool isSDWAFP32Operand() const;
361 bool isSDWAInt16Operand() const;
362 bool isSDWAInt32Operand() const;
363
364 bool isImmTy(ImmTy ImmT) const { return isImm() && Imm.Type == ImmT; }
365
366 template <ImmTy Ty> bool isImmTy() const { return isImmTy(Ty); }
367
368 bool isImmLiteral() const { return isImmTy(ImmTyNone); }
369
370 bool isImmModifier() const { return isImm() && Imm.Type != ImmTyNone; }
371
372 bool isOModSI() const { return isImmTy(ImmTyOModSI); }
373 bool isDim() const { return isImmTy(ImmTyDim); }
374 bool isR128A16() const { return isImmTy(ImmTyR128A16); }
375 bool isOff() const { return isImmTy(ImmTyOff); }
376 bool isExpTgt() const { return isImmTy(ImmTyExpTgt); }
377 bool isOffen() const { return isImmTy(ImmTyOffen); }
378 bool isIdxen() const { return isImmTy(ImmTyIdxen); }
379 bool isAddr64() const { return isImmTy(ImmTyAddr64); }
380 bool isSMEMOffsetMod() const { return isImmTy(ImmTySMEMOffsetMod); }
381 bool isFlatOffset() const {
382 return isImmTy(ImmTyOffset) || isImmTy(ImmTyInstOffset);
383 }
384 bool isGDS() const { return isImmTy(ImmTyGDS); }
385 bool isLDS() const { return isImmTy(ImmTyLDS); }
386 bool isCPol() const { return isImmTy(ImmTyCPol); }
387 bool isIndexKey8bit() const { return isImmTy(ImmTyIndexKey8bit); }
388 bool isIndexKey16bit() const { return isImmTy(ImmTyIndexKey16bit); }
389 bool isIndexKey32bit() const { return isImmTy(ImmTyIndexKey32bit); }
390 bool isMatrixAFMT() const { return isImmTy(ImmTyMatrixAFMT); }
391 bool isMatrixBFMT() const { return isImmTy(ImmTyMatrixBFMT); }
392 bool isMatrixAScale() const { return isImmTy(ImmTyMatrixAScale); }
393 bool isMatrixBScale() const { return isImmTy(ImmTyMatrixBScale); }
394 bool isMatrixAScaleFmt() const { return isImmTy(ImmTyMatrixAScaleFmt); }
395 bool isMatrixBScaleFmt() const { return isImmTy(ImmTyMatrixBScaleFmt); }
396 bool isTFE() const { return isImmTy(ImmTyTFE); }
397 bool isFormat() const { return isImmTy(ImmTyFormat) && isUInt<7>(getImm()); }
398 bool isFormatOp() const {
399 return isImmTy(ImmTyFormatOp) && isUInt<7>(getImm());
400 }
401 bool isDppFI() const { return isImmTy(ImmTyDppFI); }
402 bool isSDWADstSel() const { return isImmTy(ImmTySDWADstSel); }
403 bool isSDWASrc0Sel() const { return isImmTy(ImmTySDWASrc0Sel); }
404 bool isSDWASrc1Sel() const { return isImmTy(ImmTySDWASrc1Sel); }
405 bool isSDWADstUnused() const { return isImmTy(ImmTySDWADstUnused); }
406 bool isInterpSlot() const { return isImmTy(ImmTyInterpSlot); }
407 bool isInterpAttr() const { return isImmTy(ImmTyInterpAttr); }
408 bool isInterpAttrChan() const { return isImmTy(ImmTyInterpAttrChan); }
409 bool isOpSel() const { return isImmTy(ImmTyOpSel); }
410 bool isOpSelHi() const { return isImmTy(ImmTyOpSelHi); }
411 bool isNegLo() const { return isImmTy(ImmTyNegLo); }
412 bool isNegHi() const { return isImmTy(ImmTyNegHi); }
413
414 bool isRegOrImm() const { return isReg() || isImm(); }
415
416 bool isRegClass(unsigned RCID) const;
417
418 // Check the register against the HwMode-resolved operand class.
419 bool isRegClassTarget(unsigned TargetRCIdx) const;
420
421 bool isInlineValue() const;
422
423 bool isRegOrInlineNoMods(unsigned RCID, MVT type) const {
424 return isRegOrInline(RCID, type) && !hasModifiers();
425 }
426
427 bool isRegOrInlineNoModsTarget(unsigned TargetRCIdx, MVT type) const {
428 return isRegOrInlineTarget(TargetRCIdx, type) && !hasModifiers();
429 }
430
431 bool isSCSrcB16() const {
432 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i16);
433 }
434
435 bool isSCSrc_b32() const {
436 return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i32);
437 }
438
439 bool isSCSrc_b64() const {
440 return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::i64);
441 }
442
443 bool isBoolReg() const;
444
445 bool isSSrc_b32() const {
446 return isSCSrc_b32() || isLiteralImm(MVT::i32) || isExpr();
447 }
448
449 bool isSSrc_b16() const { return isSCSrcB16() || isLiteralImm(MVT::i16); }
450
451 bool isSSrc_b64() const {
452 // TODO: Find out how SALU supports extension of 32-bit literals to 64 bits.
453 // See isVSrc64().
454 return isSCSrc_b64() || isLiteralImm(MVT::i64) ||
455 (((const MCTargetAsmParser *)AsmParser)
456 ->getAvailableFeatures()[AMDGPU::Feature64BitLiterals] &&
457 isExpr());
458 }
459
460 bool isSSrc_f32() const {
461 return isSCSrc_b32() || isLiteralImm(MVT::f32) || isExpr();
462 }
463
464 bool isSSrc_bf16() const { return isSCSrcB16() || isLiteralImm(MVT::bf16); }
465
466 bool isSSrc_f16() const { return isSCSrcB16() || isLiteralImm(MVT::f16); }
467
468 bool isSSrc_NoInline_f16() const { return isSSrc_f16(); }
469
470 bool isSSrcOrLds_b32() const {
471 return isRegOrInlineNoMods(AMDGPU::SRegOrLds_32RegClassID, MVT::i32) ||
472 isLiteralImm(MVT::i32) || isExpr();
473 }
474
475 bool isVCSrc_b32() const {
476 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i32);
477 }
478
479 bool isVCSrc_b32_Lo256() const {
480 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo256RegClassID, MVT::i32);
481 }
482
483 bool isVCSrc_b64_Lo256() const {
484 return isRegOrInlineNoMods(AMDGPU::VS_64_Lo256RegClassID, MVT::i64);
485 }
486
487 bool isVCSrc_b64() const {
488 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::i64);
489 }
490
491 bool isVCSrcT_b16() const {
492 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::i16);
493 }
494
495 bool isVCSrcTB16_Lo128() const {
496 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::i16);
497 }
498
499 bool isVCSrcFake16B16_Lo128() const {
500 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::i16);
501 }
502
503 bool isVCSrc_b16() const {
504 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i16);
505 }
506
507 bool isVCSrc_v2b16() const { return isVCSrc_b16(); }
508
509 bool isVCSrc_f32() const {
510 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f32);
511 }
512
513 bool isVCSrc_f64() const {
514 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64);
515 }
516
517 bool isVCSrcTBF16() const {
518 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::bf16);
519 }
520
521 bool isVCSrcT_f16() const {
522 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::f16);
523 }
524
525 bool isVCSrcT_bf16() const {
526 return isRegOrInlineNoMods(AMDGPU::VS_16RegClassID, MVT::f16);
527 }
528
529 bool isVCSrcTF16_LO16() const {
530 return isRegOrInlineNoMods(AMDGPU::VS_16_LO16RegClassID, MVT::f16);
531 }
532
533 bool isVCSrcTBF16_Lo128() const {
534 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::bf16);
535 }
536
537 bool isVCSrcTF16_Lo128() const {
538 return isRegOrInlineNoMods(AMDGPU::VS_16_Lo128RegClassID, MVT::f16);
539 }
540
541 bool isVCSrcFake16BF16_Lo128() const {
542 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::bf16);
543 }
544
545 bool isVCSrcFake16F16_Lo128() const {
546 return isRegOrInlineNoMods(AMDGPU::VS_32_Lo128RegClassID, MVT::f16);
547 }
548
549 bool isVCSrc_bf16() const {
550 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::bf16);
551 }
552
553 bool isVCSrc_f16() const {
554 return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f16);
555 }
556
557 bool isVCSrc_v2bf16() const { return isVCSrc_bf16(); }
558
559 bool isVCSrc_v2f16() const { return isVCSrc_f16(); }
560
561 bool isVSrc_b32() const {
562 return isVCSrc_f32() || isLiteralImm(MVT::i32) || isExpr();
563 }
564
565 bool isVSrc_b64() const { return isVCSrc_f64() || isLiteralImm(MVT::i64); }
566
567 bool isVSrc_v2b64() const {
568 return isRegOrInlineNoModsTarget(AMDGPU::VS_128_AlignTarget, MVT::i64) ||
569 isLiteralImm(MVT::i64);
570 }
571
572 bool isVSrc_v2f64() const {
573 return isRegOrInlineNoModsTarget(AMDGPU::VS_128_AlignTarget, MVT::f64) ||
574 isLiteralImm(MVT::f64);
575 }
576
577 bool isVSrcT_b16() const { return isVCSrcT_b16() || isLiteralImm(MVT::i16); }
578
579 bool isVSrcT_b16_Lo128() const {
580 return isVCSrcTB16_Lo128() || isLiteralImm(MVT::i16);
581 }
582
583 bool isVSrcFake16_b16_Lo128() const {
584 return isVCSrcFake16B16_Lo128() || isLiteralImm(MVT::i16);
585 }
586
587 bool isVSrc_b16() const { return isVCSrc_b16() || isLiteralImm(MVT::i16); }
588
589 bool isVSrc_v2b16() const { return isVSrc_b16() || isLiteralImm(MVT::v2i16); }
590
591 bool isVSrc_v2f32() const { return isVSrc_f64() || isLiteralImm(MVT::v2f32); }
592
593 bool isVCSrc_v2b32() const { return isVCSrc_b64(); }
594
595 bool isVSrc_v2b32() const { return isVSrc_b64() || isLiteralImm(MVT::v2i32); }
596
597 bool isVSrc_f32() const {
598 return isVCSrc_f32() || isLiteralImm(MVT::f32) || isExpr();
599 }
600
601 bool isVSrc_f64() const {
602 return isRegOrInlineNoModsTarget(AMDGPU::VS_64_AlignTarget, MVT::f64) ||
603 isLiteralImm(MVT::f64);
604 }
605
606 bool isVSrcT_bf16() const {
607 return isVCSrcTBF16() || isLiteralImm(MVT::bf16);
608 }
609
610 bool isVSrcT_f16() const { return isVCSrcT_f16() || isLiteralImm(MVT::f16); }
611
612 bool isVSrcT_f16_LO16() const {
613 return isVCSrcTF16_LO16() || isLiteralImm(MVT::f16);
614 }
615
616 bool isVSrcT_bf16_Lo128() const {
617 return isVCSrcTBF16_Lo128() || isLiteralImm(MVT::bf16);
618 }
619
620 bool isVSrcT_f16_Lo128() const {
621 return isVCSrcTF16_Lo128() || isLiteralImm(MVT::f16);
622 }
623
624 bool isVSrcFake16_bf16_Lo128() const {
625 return isVCSrcFake16BF16_Lo128() || isLiteralImm(MVT::bf16);
626 }
627
628 bool isVSrcFake16_f16_Lo128() const {
629 return isVCSrcFake16F16_Lo128() || isLiteralImm(MVT::f16);
630 }
631
632 bool isVSrc_bf16() const { return isVCSrc_bf16() || isLiteralImm(MVT::bf16); }
633
634 bool isVSrc_f16() const { return isVCSrc_f16() || isLiteralImm(MVT::f16); }
635
636 bool isVSrc_v2bf16() const {
637 return isVSrc_bf16() || isLiteralImm(MVT::v2bf16);
638 }
639
640 bool isVSrc_v2f16() const { return isVSrc_f16() || isLiteralImm(MVT::v2f16); }
641
642 bool isVSrc_v2f16_splat() const { return isVSrc_v2f16(); }
643
644 bool isVSrc_NoInline_v2f16() const { return isVSrc_v2f16(); }
645
646 bool isVISrc_64_bf16() const {
647 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::bf16);
648 }
649
650 bool isVISrc_64_f16() const {
651 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::f16);
652 }
653
654 bool isVISrc_64_b32() const {
655 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::i32);
656 }
657
658 bool isVISrc_64_f64() const {
659 return isRegOrInlineNoModsTarget(AMDGPU::VReg_64_AlignTarget, MVT::f64);
660 }
661
662 bool isVISrc_256_b32() const {
663 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::i32);
664 }
665
666 bool isVISrc_256_f32() const {
667 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::f32);
668 }
669
670 bool isVISrc_256_f64() const {
671 return isRegOrInlineNoModsTarget(AMDGPU::VReg_256_AlignTarget, MVT::f64);
672 }
673
674 bool isVISrc_512_f64() const {
675 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::f64);
676 }
677
678 bool isVISrc_128_b32() const {
679 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::i32);
680 }
681
682 bool isVISrc_128_f32() const {
683 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::f32);
684 }
685
686 bool isVISrc_512_b32() const {
687 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::i32);
688 }
689
690 bool isVISrc_512_f32() const {
691 return isRegOrInlineNoModsTarget(AMDGPU::VReg_512_AlignTarget, MVT::f32);
692 }
693
694 bool isVISrc_1024_b32() const {
695 return isRegOrInlineNoModsTarget(AMDGPU::VReg_1024_AlignTarget, MVT::i32);
696 }
697
698 bool isVISrc_1024_f32() const {
699 return isRegOrInlineNoModsTarget(AMDGPU::VReg_1024_AlignTarget, MVT::f32);
700 }
701
702 bool isAISrc_64_f64() const {
703 return isRegOrInlineNoModsTarget(AMDGPU::AReg_64_AlignTarget, MVT::f64);
704 }
705
706 bool isAISrc_128_b32() const {
707 return isRegOrInlineNoModsTarget(AMDGPU::AReg_128_AlignTarget, MVT::i32);
708 }
709
710 bool isAISrc_128_f32() const {
711 return isRegOrInlineNoModsTarget(AMDGPU::AReg_128_AlignTarget, MVT::f32);
712 }
713
714 bool isVISrc_128_bf16() const {
715 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::bf16);
716 }
717
718 bool isVISrc_128_f16() const {
719 return isRegOrInlineNoModsTarget(AMDGPU::VReg_128_AlignTarget, MVT::f16);
720 }
721
722 bool isAISrc_256_f64() const {
723 return isRegOrInlineNoModsTarget(AMDGPU::AReg_256_AlignTarget, MVT::f64);
724 }
725
726 bool isAISrc_512_b32() const {
727 return isRegOrInlineNoModsTarget(AMDGPU::AReg_512_AlignTarget, MVT::i32);
728 }
729
730 bool isAISrc_512_f32() const {
731 return isRegOrInlineNoModsTarget(AMDGPU::AReg_512_AlignTarget, MVT::f32);
732 }
733
734 bool isAISrc_1024_b32() const {
735 return isRegOrInlineNoModsTarget(AMDGPU::AReg_1024_AlignTarget, MVT::i32);
736 }
737
738 bool isAISrc_1024_f32() const {
739 return isRegOrInlineNoModsTarget(AMDGPU::AReg_1024_AlignTarget, MVT::f32);
740 }
741
742 bool isKImmFP32() const { return isLiteralImm(MVT::f32); }
743
744 bool isKImmFP16() const { return isLiteralImm(MVT::f16); }
745
746 bool isKImmFP64() const { return isLiteralImm(MVT::f64); }
747
748 bool isMem() const override { return false; }
749
750 bool isExpr() const { return Kind == Expression; }
751
752 bool isSOPPBrTarget() const { return isExpr() || isImm(); }
753
754 bool isSMEMOffsetPCRel() const { return isExpr() || isImm(); }
755
756 bool isSWaitCnt() const;
757 bool isDepCtr() const;
758 bool isSDelayALU() const;
759 bool isHwreg() const;
760 bool isSendMsg() const;
761 bool isWaitEvent() const;
762 bool isSplitBarrier() const;
763 bool isSwizzle() const;
764 bool isSMRDOffset8() const;
765 bool isSMEMOffset() const;
766 bool isSMRDLiteralOffset() const;
767 bool isDPP8() const;
768 bool isDPPCtrl() const;
769 bool isBLGP() const;
770 bool isGPRIdxMode() const;
771 bool isS16Imm() const;
772 bool isU16Imm() const;
773 bool isEndpgm() const;
774
775 auto getPredicate(std::function<bool(const AMDGPUOperand &Op)> P) const {
776 return [this, P]() { return P(*this); };
777 }
778
779 StringRef getToken() const {
780 assert(isToken());
781 return StringRef(Tok.Data, Tok.Length);
782 }
783
784 int64_t getImm() const {
785 assert(isImm());
786 return Imm.Val;
787 }
788
789 ImmTy getImmTy() const {
790 assert(isImm());
791 return Imm.Type;
792 }
793
794 MCRegister getReg() const override {
795 assert(isRegKind());
796 return Reg.RegNo;
797 }
798
799 SMLoc getStartLoc() const override { return StartLoc; }
800
801 SMLoc getEndLoc() const override { return EndLoc; }
802
803 int getMCOpIdx() const { return MCOpIdx; }
804
805 Modifiers getModifiers() const {
806 assert(isRegKind() || isImmTy(ImmTyNone));
807 return isRegKind() ? Reg.Mods : Imm.Mods;
808 }
809
810 void setModifiers(Modifiers Mods) {
811 assert(isRegKind() || isImmTy(ImmTyNone));
812 if (isRegKind())
813 Reg.Mods = Mods;
814 else
815 Imm.Mods = Mods;
816 }
817
818 bool hasModifiers() const { return getModifiers().hasModifiers(); }
819
820 bool hasFPModifiers() const { return getModifiers().hasFPModifiers(); }
821
822 bool hasIntModifiers() const { return getModifiers().hasIntModifiers(); }
823
824 bool isForcedLit() const {
825 return isImmLiteral() && getModifiers().isForcedLit();
826 }
827
828 bool isForcedLit64() const {
829 return isImmLiteral() && getModifiers().isForcedLit64();
830 }
831
832 uint64_t applyInputFPModifiers(uint64_t Val, unsigned Size) const;
833
834 void addImmOperands(MCInst &Inst, unsigned N,
835 bool ApplyModifiers = true) const;
836
837 void addLiteralImmOperand(MCInst &Inst, int64_t Val,
838 bool ApplyModifiers) const;
839
840 void addRegOperands(MCInst &Inst, unsigned N) const;
841
842 void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
843 if (isRegKind())
844 addRegOperands(Inst, N);
845 else
846 addImmOperands(Inst, N);
847 }
848
849 void addRegOrImmWithInputModsOperands(MCInst &Inst, unsigned N) const {
850 Modifiers Mods = getModifiers();
851 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
852 if (isRegKind()) {
853 addRegOperands(Inst, N);
854 } else {
855 addImmOperands(Inst, N, false);
856 }
857 }
858
859 void addRegOrImmWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
860 assert(!hasIntModifiers());
861 addRegOrImmWithInputModsOperands(Inst, N);
862 }
863
864 void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
865 Modifiers Mods = getModifiers();
866 Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
867 assert(isRegKind());
868 addRegOperands(Inst, N);
869 }
870
871 void addRegWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
872 assert(!hasIntModifiers());
873 addRegWithInputModsOperands(Inst, N);
874 }
875
876 static void printImmTy(raw_ostream &OS, ImmTy Type) {
877 // clang-format off
878 switch (Type) {
879 case ImmTyNone: OS << "None"; break;
880 case ImmTyGDS: OS << "GDS"; break;
881 case ImmTyLDS: OS << "LDS"; break;
882 case ImmTyOffen: OS << "Offen"; break;
883 case ImmTyIdxen: OS << "Idxen"; break;
884 case ImmTyAddr64: OS << "Addr64"; break;
885 case ImmTyOffset: OS << "Offset"; break;
886 case ImmTyInstOffset: OS << "InstOffset"; break;
887 case ImmTyOffset0: OS << "Offset0"; break;
888 case ImmTyOffset1: OS << "Offset1"; break;
889 case ImmTySMEMOffsetMod: OS << "SMEMOffsetMod"; break;
890 case ImmTyCPol: OS << "CPol"; break;
891 case ImmTyIndexKey8bit: OS << "index_key"; break;
892 case ImmTyIndexKey16bit: OS << "index_key"; break;
893 case ImmTyIndexKey32bit: OS << "index_key"; break;
894 case ImmTyTFE: OS << "TFE"; break;
895 case ImmTyIsAsync: OS << "IsAsync"; break;
896 case ImmTyD16: OS << "D16"; break;
897 case ImmTyFormat: OS << "Format"; break;
898 case ImmTyFormatOp: OS << "FormatOp"; break;
899 case ImmTyClamp: OS << "Clamp"; break;
900 case ImmTyOModSI: OS << "OModSI"; break;
901 case ImmTyDPP8: OS << "DPP8"; break;
902 case ImmTyDppCtrl: OS << "DppCtrl"; break;
903 case ImmTyDppRowMask: OS << "DppRowMask"; break;
904 case ImmTyDppBankMask: OS << "DppBankMask"; break;
905 case ImmTyDppBoundCtrl: OS << "DppBoundCtrl"; break;
906 case ImmTyDppFI: OS << "DppFI"; break;
907 case ImmTySDWADstSel: OS << "SDWADstSel"; break;
908 case ImmTySDWASrc0Sel: OS << "SDWASrc0Sel"; break;
909 case ImmTySDWASrc1Sel: OS << "SDWASrc1Sel"; break;
910 case ImmTySDWADstUnused: OS << "SDWADstUnused"; break;
911 case ImmTyDMask: OS << "DMask"; break;
912 case ImmTyDim: OS << "Dim"; break;
913 case ImmTyUNorm: OS << "UNorm"; break;
914 case ImmTyDA: OS << "DA"; break;
915 case ImmTyR128A16: OS << "R128A16"; break;
916 case ImmTyA16: OS << "A16"; break;
917 case ImmTyLWE: OS << "LWE"; break;
918 case ImmTyOff: OS << "Off"; break;
919 case ImmTyExpTgt: OS << "ExpTgt"; break;
920 case ImmTyExpCompr: OS << "ExpCompr"; break;
921 case ImmTyExpVM: OS << "ExpVM"; break;
922 case ImmTyDone: OS << "Done"; break;
923 case ImmTyRowEn: OS << "RowEn"; break;
924 case ImmTyHwreg: OS << "Hwreg"; break;
925 case ImmTySendMsg: OS << "SendMsg"; break;
926 case ImmTyWaitEvent: OS << "WaitEvent"; break;
927 case ImmTyInterpSlot: OS << "InterpSlot"; break;
928 case ImmTyInterpAttr: OS << "InterpAttr"; break;
929 case ImmTyInterpAttrChan: OS << "InterpAttrChan"; break;
930 case ImmTyOpSel: OS << "OpSel"; break;
931 case ImmTyOpSelHi: OS << "OpSelHi"; break;
932 case ImmTyNegLo: OS << "NegLo"; break;
933 case ImmTyNegHi: OS << "NegHi"; break;
934 case ImmTySwizzle: OS << "Swizzle"; break;
935 case ImmTyGprIdxMode: OS << "GprIdxMode"; break;
936 case ImmTyHigh: OS << "High"; break;
937 case ImmTyBLGP: OS << "BLGP"; break;
938 case ImmTyCBSZ: OS << "CBSZ"; break;
939 case ImmTyABID: OS << "ABID"; break;
940 case ImmTyEndpgm: OS << "Endpgm"; break;
941 case ImmTyWaitVDST: OS << "WaitVDST"; break;
942 case ImmTyWaitEXP: OS << "WaitEXP"; break;
943 case ImmTyWaitVAVDst: OS << "WaitVAVDst"; break;
944 case ImmTyWaitVMVSrc: OS << "WaitVMVSrc"; break;
945 case ImmTyBitOp3: OS << "BitOp3"; break;
946 case ImmTyMatrixAFMT: OS << "ImmTyMatrixAFMT"; break;
947 case ImmTyMatrixBFMT: OS << "ImmTyMatrixBFMT"; break;
948 case ImmTyMatrixAScale: OS << "ImmTyMatrixAScale"; break;
949 case ImmTyMatrixBScale: OS << "ImmTyMatrixBScale"; break;
950 case ImmTyMatrixAScaleFmt: OS << "ImmTyMatrixAScaleFmt"; break;
951 case ImmTyMatrixBScaleFmt: OS << "ImmTyMatrixBScaleFmt"; break;
952 case ImmTyMatrixAReuse: OS << "ImmTyMatrixAReuse"; break;
953 case ImmTyMatrixBReuse: OS << "ImmTyMatrixBReuse"; break;
954 case ImmTyScaleSel: OS << "ScaleSel" ; break;
955 case ImmTyByteSel: OS << "ByteSel" ; break;
956 }
957 // clang-format on
958 }
959
960 void print(raw_ostream &OS, const MCAsmInfo &MAI) const override {
961 switch (Kind) {
962 case Register:
963 OS << "<register " << AMDGPUInstPrinter::getRegisterName(getReg())
964 << " mods: " << Reg.Mods << '>';
965 break;
966 case Immediate:
967 OS << '<' << getImm();
968 if (getImmTy() != ImmTyNone) {
969 OS << " type: ";
970 printImmTy(OS, getImmTy());
971 }
972 OS << " mods: " << Imm.Mods << '>';
973 break;
974 case Token:
975 OS << '\'' << getToken() << '\'';
976 break;
977 case Expression:
978 OS << "<expr ";
979 MAI.printExpr(OS, *Expr);
980 OS << '>';
981 break;
982 }
983 }
984
985 static AMDGPUOperand::Ptr CreateImm(const AMDGPUAsmParser *AsmParser,
986 int64_t Val, SMLoc Loc,
987 ImmTy Type = ImmTyNone,
988 bool IsFPImm = false) {
989 auto Op = std::make_unique<AMDGPUOperand>(Immediate, AsmParser);
990 Op->Imm.Val = Val;
991 Op->Imm.IsFPImm = IsFPImm;
992 Op->Imm.Type = Type;
993 Op->Imm.Mods = Modifiers();
994 Op->StartLoc = Loc;
995 Op->EndLoc = Loc;
996 return Op;
997 }
998
999 static AMDGPUOperand::Ptr CreateToken(const AMDGPUAsmParser *AsmParser,
1000 StringRef Str, SMLoc Loc,
1001 bool HasExplicitEncodingSize = true) {
1002 auto Res = std::make_unique<AMDGPUOperand>(Token, AsmParser);
1003 Res->Tok.Data = Str.data();
1004 Res->Tok.Length = Str.size();
1005 Res->StartLoc = Loc;
1006 Res->EndLoc = Loc;
1007 return Res;
1008 }
1009
1010 static AMDGPUOperand::Ptr CreateReg(const AMDGPUAsmParser *AsmParser,
1011 MCRegister Reg, SMLoc S, SMLoc E) {
1012 auto Op = std::make_unique<AMDGPUOperand>(Register, AsmParser);
1013 Op->Reg.RegNo = Reg;
1014 Op->Reg.Mods = Modifiers();
1015 Op->StartLoc = S;
1016 Op->EndLoc = E;
1017 return Op;
1018 }
1019
1020 static AMDGPUOperand::Ptr CreateExpr(const AMDGPUAsmParser *AsmParser,
1021 const class MCExpr *Expr, SMLoc S) {
1022 auto Op = std::make_unique<AMDGPUOperand>(Expression, AsmParser);
1023 Op->Expr = Expr;
1024 Op->StartLoc = S;
1025 Op->EndLoc = S;
1026 return Op;
1027 }
1028};
1029
1030raw_ostream &operator<<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods) {
1031 OS << "abs:" << Mods.Abs << " neg: " << Mods.Neg << " sext:" << Mods.Sext;
1032 return OS;
1033}
1034
1035//===----------------------------------------------------------------------===//
1036// AsmParser
1037//===----------------------------------------------------------------------===//
1038
1039// TODO: define GET_SUBTARGET_FEATURE_NAME
1040#define GET_REGISTER_MATCHER
1041#include "AMDGPUGenAsmMatcher.inc"
1042#undef GET_REGISTER_MATCHER
1043#undef GET_SUBTARGET_FEATURE_NAME
1044
1045// Holds info related to the current kernel, e.g. count of SGPRs used.
1046// Kernel scope begins at .amdgpu_hsa_kernel directive, ends at next
1047// .amdgpu_hsa_kernel or at EOF.
1048class KernelScopeInfo {
1049 int SgprIndexUnusedMin = -1;
1050 int VgprIndexUnusedMin = -1;
1051 int AgprIndexUnusedMin = -1;
1052 MCContext *Ctx = nullptr;
1053 MCSubtargetInfo const *MSTI = nullptr;
1054
1055 void usesSgprAt(int i) {
1056 if (i >= SgprIndexUnusedMin) {
1057 SgprIndexUnusedMin = ++i;
1058 if (Ctx) {
1059 MCSymbol *const Sym =
1060 Ctx->getOrCreateSymbol(Twine(".kernel.sgpr_count"));
1061 Sym->setVariableValue(MCConstantExpr::create(SgprIndexUnusedMin, *Ctx));
1062 }
1063 }
1064 }
1065
1066 void usesVgprAt(int i) {
1067 if (i >= VgprIndexUnusedMin) {
1068 VgprIndexUnusedMin = ++i;
1069 if (Ctx) {
1070 MCSymbol *const Sym =
1071 Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
1072 int totalVGPR =
1073 getTotalNumVGPRs(isGFX90A(*MSTI), std::max(AgprIndexUnusedMin, 0),
1074 VgprIndexUnusedMin);
1075 Sym->setVariableValue(MCConstantExpr::create(totalVGPR, *Ctx));
1076 }
1077 }
1078 }
1079
1080 void usesAgprAt(int i) {
1081 // Instruction will error in AMDGPUAsmParser::matchAndEmitInstruction
1082 if (!hasMAIInsts(*MSTI))
1083 return;
1084
1085 if (i >= AgprIndexUnusedMin) {
1086 AgprIndexUnusedMin = ++i;
1087 if (Ctx) {
1088 MCSymbol *const Sym =
1089 Ctx->getOrCreateSymbol(Twine(".kernel.agpr_count"));
1090 Sym->setVariableValue(MCConstantExpr::create(AgprIndexUnusedMin, *Ctx));
1091
1092 // Also update vgpr_count (dependent on agpr_count for gfx908/gfx90a)
1093 MCSymbol *const vSym =
1094 Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
1095 int totalVGPR =
1096 getTotalNumVGPRs(isGFX90A(*MSTI), std::max(AgprIndexUnusedMin, 0),
1097 VgprIndexUnusedMin);
1098 vSym->setVariableValue(MCConstantExpr::create(totalVGPR, *Ctx));
1099 }
1100 }
1101 }
1102
1103public:
1104 KernelScopeInfo() = default;
1105
1106 void initialize(MCContext &Context) {
1107 Ctx = &Context;
1108 MSTI = Ctx->getSubtargetInfo();
1109
1110 usesSgprAt(SgprIndexUnusedMin = -1);
1111 usesVgprAt(VgprIndexUnusedMin = -1);
1112 if (hasMAIInsts(*MSTI)) {
1113 usesAgprAt(AgprIndexUnusedMin = -1);
1114 }
1115 }
1116
1117 void usesRegister(RegisterKind RegKind, unsigned DwordRegIndex,
1118 unsigned RegWidth) {
1119 switch (RegKind) {
1120 case IS_SGPR:
1121 usesSgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1122 break;
1123 case IS_AGPR:
1124 usesAgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1125 break;
1126 case IS_VGPR:
1127 usesVgprAt(DwordRegIndex + divideCeil(RegWidth, 32) - 1);
1128 break;
1129 default:
1130 break;
1131 }
1132 }
1133};
1134
1135class AMDGPUAsmParser : public MCTargetAsmParser {
1136 MCAsmParser &Parser;
1137
1138 unsigned ForcedEncodingSize = 0;
1139 bool ForcedDPP = false;
1140 bool ForcedSDWA = false;
1141 KernelScopeInfo KernelScope;
1142 const unsigned HwMode;
1143 const AMDGPU::GPUKind Gfx;
1144 const AMDGPU::IsaVersion ISA;
1145
1146 /// @name Auto-generated Match Functions
1147 /// {
1148
1149#define GET_ASSEMBLER_HEADER
1150#include "AMDGPUGenAsmMatcher.inc"
1151
1152 /// }
1153
1154 /// Get size of register operand
1155 unsigned getRegOperandSize(const MCInstrDesc &Desc, unsigned OpNo) const {
1156 assert(OpNo < Desc.NumOperands);
1157 int16_t RCID = MII.getOpRegClassID(Desc.operands()[OpNo], HwMode);
1158 return getRegBitWidth(RCID) / 8;
1159 }
1160
1161 std::optional<AMDGPU::InfoSectionData> InfoData;
1162
1163 /// State for checking that every kernel named in a .amdhsa_kernel directive
1164 /// begins with the required prologue instruction sequence. Because the
1165 /// directive may appear either before or after the kernel's label (it is
1166 /// normally emitted after the function body, in .rodata), validation is
1167 /// deferred to onEndOfFile(). We record an order-independent timeline of
1168 /// parsed labels and emitted instruction opcodes, plus the set of symbols
1169 /// named by .amdhsa_kernel directives, and match them up at end of file.
1170 SmallVector<unsigned> OpcodeStream;
1172 OpcodeStreamSymbols;
1173 SmallPtrSet<const MCSymbol *, 8> AMDHSAKernelSymbols;
1174
1175 /// Verify recorded kernel prologues.
1176 void checkKernelPrologues();
1177
1178private:
1179 void createConstantSymbol(StringRef Id, int64_t Val);
1180
1181 bool ParseAsAbsoluteExpression(uint32_t &Ret);
1182 bool OutOfRangeError(SMRange Range);
1183 /// Calculate VGPR/SGPR blocks required for given target, reserved
1184 /// registers, and user-specified NextFreeXGPR values.
1185 ///
1186 /// \param Features [in] Target features, used for bug corrections.
1187 /// \param VCCUsed [in] Whether VCC special SGPR is reserved.
1188 /// \param FlatScrUsed [in] Whether FLAT_SCRATCH special SGPR is reserved.
1189 /// \param XNACKUsed [in] Whether XNACK_MASK special SGPR is reserved.
1190 /// \param EnableWavefrontSize32 [in] Value of ENABLE_WAVEFRONT_SIZE32 kernel
1191 /// descriptor field, if valid.
1192 /// \param NextFreeVGPR [in] Max VGPR number referenced, plus one.
1193 /// \param VGPRRange [in] Token range, used for VGPR diagnostics.
1194 /// \param NextFreeSGPR [in] Max SGPR number referenced, plus one.
1195 /// \param SGPRRange [in] Token range, used for SGPR diagnostics.
1196 /// \param VGPRBlocks [out] Result VGPR block count.
1197 /// \param SGPRBlocks [out] Result SGPR block count.
1198 bool calculateGPRBlocks(const FeatureBitset &Features, const MCExpr *VCCUsed,
1199 const MCExpr *FlatScrUsed, bool XNACKUsed,
1200 std::optional<bool> EnableWavefrontSize32,
1201 const MCExpr *NextFreeVGPR, SMRange VGPRRange,
1202 const MCExpr *NextFreeSGPR, SMRange SGPRRange,
1203 const MCExpr *&VGPRBlocks, const MCExpr *&SGPRBlocks);
1204 bool ParseDirectiveAMDGCNTarget();
1205 bool ParseDirectiveAMDHSACodeObjectVersion();
1206 bool ParseDirectiveAMDHSAKernel();
1207 bool ParseAMDKernelCodeTValue(StringRef ID, AMDGPUMCKernelCodeT &Header);
1208 bool ParseDirectiveAMDKernelCodeT();
1209 // TODO: Possibly make subtargetHasRegister const.
1210 bool subtargetHasRegister(const MCRegisterInfo &MRI, MCRegister Reg);
1211 bool ParseDirectiveAMDGPUHsaKernel();
1212
1213 bool ParseDirectiveISAVersion();
1214 bool ParseDirectiveHSAMetadata();
1215 bool ParseDirectivePALMetadataBegin();
1216 bool ParseDirectivePALMetadata();
1217 bool ParseDirectiveAMDGPULDS();
1218 bool ParseDirectiveAMDGPUInfo();
1219
1220 /// Common code to parse out a block of text (typically YAML) between start
1221 /// and end directives.
1222 bool ParseToEndDirective(const char *AssemblerDirectiveBegin,
1223 const char *AssemblerDirectiveEnd,
1224 std::string &CollectString);
1225
1226 bool AddNextRegisterToList(MCRegister &Reg, unsigned &RegWidth,
1227 RegisterKind RegKind, MCRegister Reg1,
1228 RegisterKind RegKind1, SMLoc Loc);
1229 bool ParseAMDGPURegister(RegisterKind &RegKind, MCRegister &Reg,
1230 unsigned &RegNum, unsigned &RegWidth,
1231 bool RestoreOnFailure = false);
1232 bool ParseAMDGPURegister(RegisterKind &RegKind, MCRegister &Reg,
1233 unsigned &RegNum, unsigned &RegWidth,
1234 SmallVectorImpl<AsmToken> &Tokens);
1235 MCRegister ParseRegularReg(RegisterKind &RegKind, unsigned &RegNum,
1236 unsigned &RegWidth,
1237 SmallVectorImpl<AsmToken> &Tokens);
1238 MCRegister ParseSpecialReg(RegisterKind &RegKind, unsigned &RegNum,
1239 unsigned &RegWidth,
1240 SmallVectorImpl<AsmToken> &Tokens);
1241 MCRegister ParseRegList(RegisterKind &RegKind, unsigned &RegNum,
1242 unsigned &RegWidth,
1243 SmallVectorImpl<AsmToken> &Tokens);
1244 bool ParseRegRange(unsigned &Num, unsigned &Width, unsigned &SubReg);
1245 MCRegister getRegularReg(RegisterKind RegKind, unsigned RegNum,
1246 unsigned SubReg, unsigned RegWidth, SMLoc Loc);
1247
1248 bool isRegister();
1249 bool isRegister(const AsmToken &Token, const AsmToken &NextToken) const;
1250 std::optional<StringRef> getGprCountSymbolName(RegisterKind RegKind);
1251 void initializeGprCountSymbol(RegisterKind RegKind);
1252 bool updateGprCountSymbols(RegisterKind RegKind, unsigned DwordRegIndex,
1253 unsigned RegWidth);
1254 void cvtMubufImpl(MCInst &Inst, const OperandVector &Operands, bool IsAtomic);
1255
1256public:
1257 enum OperandMode {
1258 OperandMode_Default,
1259 OperandMode_NSA,
1260 };
1261
1262 using OptionalImmIndexMap = std::map<AMDGPUOperand::ImmTy, unsigned>;
1263
1264 AMDGPUAsmParser(const MCSubtargetInfo &STI, MCAsmParser &_Parser,
1265 const MCInstrInfo &MII)
1266 : MCTargetAsmParser(STI, MII), Parser(_Parser),
1267 HwMode(STI.getHwMode(MCSubtargetInfo::HwMode_RegInfo)),
1268 Gfx(AMDGPU::parseArchAMDGCN(STI.getCPU())),
1269 ISA(AMDGPU::getIsaVersion(STI.getCPU())) {
1271
1272 setAvailableFeatures(ComputeAvailableFeatures(getFeatureBits()));
1273
1274 if (ISA.Major >= 6 && isHsaAbi(getSTI())) {
1275 createConstantSymbol(".amdgcn.gfx_generation_number", ISA.Major);
1276 createConstantSymbol(".amdgcn.gfx_generation_minor", ISA.Minor);
1277 createConstantSymbol(".amdgcn.gfx_generation_stepping", ISA.Stepping);
1278 } else {
1279 createConstantSymbol(".option.machine_version_major", ISA.Major);
1280 createConstantSymbol(".option.machine_version_minor", ISA.Minor);
1281 createConstantSymbol(".option.machine_version_stepping", ISA.Stepping);
1282 }
1283 if (ISA.Major >= 6 && isHsaAbi(getSTI())) {
1284 initializeGprCountSymbol(IS_VGPR);
1285 initializeGprCountSymbol(IS_SGPR);
1286 } else
1287 KernelScope.initialize(getContext());
1288
1289 for (auto [Symbol, Code] : AMDGPU::UCVersion::getGFXVersions())
1290 createConstantSymbol(Symbol, Code);
1291
1292 createConstantSymbol("UC_VERSION_W64_BIT", 0x2000);
1293 createConstantSymbol("UC_VERSION_W32_BIT", 0x4000);
1294 createConstantSymbol("UC_VERSION_MDP_BIT", 0x8000);
1295 }
1296
1297 bool hasMIMG_R128() const { return AMDGPU::hasMIMG_R128(getSTI()); }
1298
1299 bool hasPackedD16() const { return AMDGPU::hasPackedD16(getSTI()); }
1300
1301 bool hasA16() const { return AMDGPU::hasA16(getSTI()); }
1302
1303 bool hasG16() const { return AMDGPU::hasG16(getSTI()); }
1304
1305 bool hasGDS() const { return AMDGPU::hasGDS(getSTI()); }
1306
1307 bool isSI() const { return AMDGPU::isSI(getSTI()); }
1308
1309 bool isCI() const { return AMDGPU::isCI(getSTI()); }
1310
1311 bool isVI() const { return AMDGPU::isVI(getSTI()); }
1312
1313 bool isGFX9() const { return AMDGPU::isGFX9(getSTI()); }
1314
1315 // TODO: isGFX90A is also true for GFX940. We need to clean it.
1316 bool isGFX90A() const { return AMDGPU::isGFX90A(getSTI()); }
1317
1318 bool isGFX940() const { return AMDGPU::isGFX940(getSTI()); }
1319
1320 bool isGFX9Plus() const { return AMDGPU::isGFX9Plus(getSTI()); }
1321
1322 bool isGFX10Plus() const { return AMDGPU::isGFX10Plus(getSTI()); }
1323
1324 bool isGFX11() const { return AMDGPU::isGFX11(getSTI()); }
1325
1326 bool isGFX11Plus() const { return AMDGPU::isGFX11Plus(getSTI()); }
1327
1328 bool isGFX12() const { return AMDGPU::isGFX12(getSTI()); }
1329
1330 bool isGFX12Plus() const { return AMDGPU::isGFX12Plus(getSTI()); }
1331
1332 bool isGFX1250Plus() const { return AMDGPU::isGFX1250Plus(getSTI()); }
1333
1334 bool hasBVHRayTracingInsts() const {
1335 return getFeatureBits()[AMDGPU::FeatureBVHRayTracingInsts];
1336 }
1337
1338 bool isWave32() const { return getAvailableFeatures()[Feature_isWave32Bit]; }
1339
1340 bool isWave64() const { return getAvailableFeatures()[Feature_isWave64Bit]; }
1341
1342 bool hasInv2PiInlineImm() const {
1343 return getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm];
1344 }
1345
1346 bool has64BitLiterals() const {
1347 return getFeatureBits()[AMDGPU::Feature64BitLiterals];
1348 }
1349
1350 bool hasFlatOffsets() const {
1351 return getFeatureBits()[AMDGPU::FeatureFlatInstOffsets];
1352 }
1353
1354 bool hasTrue16Insts() const {
1355 return getFeatureBits()[AMDGPU::FeatureTrue16BitInsts];
1356 }
1357
1358 bool hasArchitectedFlatScratch() const {
1359 return getFeatureBits()[AMDGPU::FeatureArchitectedFlatScratch];
1360 }
1361
1362 bool hasSGPR102_SGPR103() const { return !isVI() && !isGFX9(); }
1363
1364 bool hasSGPR104_SGPR105() const { return isGFX10Plus(); }
1365
1366 bool hasIntClamp() const { return getFeatureBits()[AMDGPU::FeatureIntClamp]; }
1367
1368 bool hasPartialNSAEncoding() const {
1369 return getFeatureBits()[AMDGPU::FeaturePartialNSAEncoding];
1370 }
1371
1372 bool hasGloballyAddressableScratch() const {
1373 return getFeatureBits()[AMDGPU::FeatureGloballyAddressableScratch];
1374 }
1375
1376 bool hasScaleOffset() const {
1377 return getFeatureBits()[AMDGPU::FeatureScaleOffset];
1378 }
1379
1380 bool hasCacheFillSize() const {
1381 return getFeatureBits()[AMDGPU::FeatureCacheFillSize];
1382 }
1383
1384 unsigned getNSAMaxSize(bool HasSampler = false) const {
1385 return AMDGPU::getNSAMaxSize(getSTI(), HasSampler);
1386 }
1387
1388 unsigned getMaxNumUserSGPRs() const {
1389 return AMDGPU::getMaxNumUserSGPRs(getSTI());
1390 }
1391
1392 bool hasKernargPreload() const { return AMDGPU::hasKernargPreload(getSTI()); }
1393
1394 AMDGPUTargetStreamer &getTargetStreamer() {
1395 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
1396 return static_cast<AMDGPUTargetStreamer &>(TS);
1397 }
1398
1399 MCContext &getContext() const {
1400 // We need this const_cast because for some reason getContext() is not const
1401 // in MCAsmParser.
1402 return const_cast<AMDGPUAsmParser *>(this)->MCTargetAsmParser::getContext();
1403 }
1404
1405 const MCRegisterInfo *getMRI() const {
1406 return getContext().getRegisterInfo();
1407 }
1408
1409 const MCInstrInfo *getMII() const { return &MII; }
1410
1411 // Resolve a RegClassByHwModeUses index to a register class id for the active
1412 // HwMode; -1 if the mode has no entry.
1413 int16_t getTargetRegClass(unsigned TargetRCIdx) const {
1414 return MII.getRegClassByHwModeTable(HwMode)[TargetRCIdx];
1415 }
1416
1417 // FIXME: This should not be used. Instead, should use queries derived from
1418 // getAvailableFeatures().
1419 const FeatureBitset &getFeatureBits() const {
1420 return getSTI().getFeatureBits();
1421 }
1422
1423 void setForcedEncodingSize(unsigned Size) { ForcedEncodingSize = Size; }
1424 void setForcedDPP(bool ForceDPP_) { ForcedDPP = ForceDPP_; }
1425 void setForcedSDWA(bool ForceSDWA_) { ForcedSDWA = ForceSDWA_; }
1426
1427 unsigned getForcedEncodingSize() const { return ForcedEncodingSize; }
1428 bool isForcedVOP3() const { return ForcedEncodingSize == 64; }
1429 bool isForcedDPP() const { return ForcedDPP; }
1430 bool isForcedSDWA() const { return ForcedSDWA; }
1431 ArrayRef<unsigned> getMatchedVariants() const;
1432 StringRef getMatchedVariantName() const;
1433
1434 std::unique_ptr<AMDGPUOperand> parseRegister(bool RestoreOnFailure = false);
1435 bool ParseRegister(MCRegister &RegNo, SMLoc &StartLoc, SMLoc &EndLoc,
1436 bool RestoreOnFailure);
1437 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
1438 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1439 SMLoc &EndLoc) override;
1440 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
1441 unsigned validateTargetOperandClass(const MCParsedAsmOperand &Op,
1442 unsigned Kind) override;
1443 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1444 OperandVector &Operands, MCStreamer &Out,
1445 uint64_t &ErrorInfo,
1446 bool MatchingInlineAsm) override;
1447 bool ParseDirective(AsmToken DirectiveID) override;
1448 void doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) override;
1449 void onEndOfFile() override;
1450 ParseStatus parseOperand(OperandVector &Operands, StringRef Mnemonic,
1451 OperandMode Mode = OperandMode_Default);
1452 StringRef parseMnemonicSuffix(StringRef Name);
1453 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
1454 SMLoc NameLoc, OperandVector &Operands) override;
1455 // bool ProcessInstruction(MCInst &Inst);
1456
1457 ParseStatus parseTokenOp(StringRef Name, OperandVector &Operands);
1458
1459 ParseStatus parseIntWithPrefix(const char *Prefix, int64_t &Int);
1460
1461 ParseStatus
1462 parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
1463 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1464 std::function<bool(int64_t &)> ConvertResult = nullptr);
1465
1466 ParseStatus parseOperandArrayWithPrefix(
1467 const char *Prefix, OperandVector &Operands,
1468 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1469 bool (*ConvertResult)(int64_t &) = nullptr);
1470
1471 ParseStatus
1472 parseNamedBit(StringRef Name, OperandVector &Operands,
1473 AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
1474 bool IgnoreNegative = false);
1475 unsigned getCPolKind(StringRef Id, StringRef Mnemo, bool &Disabling) const;
1476 ParseStatus parseCPol(OperandVector &Operands);
1477 ParseStatus parseScope(OperandVector &Operands, int64_t &Scope);
1478 ParseStatus parseTH(OperandVector &Operands, int64_t &TH);
1479 ParseStatus parseCFS(OperandVector &Operands, int64_t &CFS);
1480 ParseStatus parseStringWithPrefix(StringRef Prefix, StringRef &Value,
1481 SMLoc &StringLoc);
1482 ParseStatus parseStringOrIntWithPrefix(OperandVector &Operands,
1483 StringRef Name,
1484 ArrayRef<const char *> Ids,
1485 int64_t &IntVal);
1486 ParseStatus parseStringOrIntWithPrefix(OperandVector &Operands,
1487 StringRef Name,
1488 ArrayRef<const char *> Ids,
1489 AMDGPUOperand::ImmTy Type);
1490
1491 bool isModifier();
1492 bool isOperandModifier(const AsmToken &Token,
1493 const AsmToken &NextToken) const;
1494 bool isRegOrOperandModifier(const AsmToken &Token,
1495 const AsmToken &NextToken) const;
1496 bool isNamedOperandModifier(const AsmToken &Token,
1497 const AsmToken &NextToken) const;
1498 bool isOpcodeModifierWithVal(const AsmToken &Token,
1499 const AsmToken &NextToken) const;
1500 bool parseSP3NegModifier();
1501 ParseStatus parseImm(OperandVector &Operands, bool HasSP3AbsModifier = false,
1502 LitModifier Lit = LitModifier::None);
1503 ParseStatus parseReg(OperandVector &Operands);
1504 ParseStatus parseRegOrImm(OperandVector &Operands, bool HasSP3AbsMod = false,
1505 LitModifier Lit = LitModifier::None);
1506 ParseStatus parseRegOrImmWithFPInputMods(OperandVector &Operands,
1507 bool AllowImm = true);
1508 ParseStatus parseRegOrImmWithIntInputMods(OperandVector &Operands,
1509 bool AllowImm = true);
1510 ParseStatus parseRegWithFPInputMods(OperandVector &Operands);
1511 ParseStatus parseRegWithIntInputMods(OperandVector &Operands);
1512 ParseStatus parseRsrcReg(OperandVector &Operands);
1513 ParseStatus parseVReg32OrOff(OperandVector &Operands);
1514 ParseStatus tryParseIndexKey(OperandVector &Operands,
1515 AMDGPUOperand::ImmTy ImmTy);
1516 ParseStatus parseIndexKey8bit(OperandVector &Operands);
1517 ParseStatus parseIndexKey16bit(OperandVector &Operands);
1518 ParseStatus parseIndexKey32bit(OperandVector &Operands);
1519 ParseStatus tryParseMatrixFMT(OperandVector &Operands, StringRef Name,
1520 AMDGPUOperand::ImmTy Type);
1521 ParseStatus parseMatrixAFMT(OperandVector &Operands);
1522 ParseStatus parseMatrixBFMT(OperandVector &Operands);
1523 ParseStatus tryParseMatrixScale(OperandVector &Operands, StringRef Name,
1524 AMDGPUOperand::ImmTy Type);
1525 ParseStatus parseMatrixAScale(OperandVector &Operands);
1526 ParseStatus parseMatrixBScale(OperandVector &Operands);
1527 ParseStatus tryParseMatrixScaleFmt(OperandVector &Operands, StringRef Name,
1528 AMDGPUOperand::ImmTy Type);
1529 ParseStatus parseMatrixAScaleFmt(OperandVector &Operands);
1530 ParseStatus parseMatrixBScaleFmt(OperandVector &Operands);
1531
1532 ParseStatus parseDfmtNfmt(int64_t &Format);
1533 ParseStatus parseUfmt(int64_t &Format);
1534 ParseStatus parseSymbolicSplitFormat(StringRef FormatStr, SMLoc Loc,
1535 int64_t &Format);
1536 ParseStatus parseSymbolicUnifiedFormat(StringRef FormatStr, SMLoc Loc,
1537 int64_t &Format);
1538 ParseStatus parseFormat(OperandVector &Operands);
1539 ParseStatus parseFormatOp(OperandVector &Operands);
1540 ParseStatus parseSymbolicOrNumericFormat(int64_t &Format);
1541 ParseStatus parseNumericFormat(int64_t &Format);
1542 ParseStatus parseFlatOffset(OperandVector &Operands);
1543 ParseStatus parseR128A16(OperandVector &Operands);
1544 ParseStatus parseBLGP(OperandVector &Operands);
1545 ParseStatus tryParseFmt(const char *Pref, int64_t MaxVal, int64_t &Fmt);
1546 bool matchDfmtNfmt(int64_t &Dfmt, int64_t &Nfmt, StringRef FormatStr,
1547 SMLoc Loc);
1548
1549 void cvtExp(MCInst &Inst, const OperandVector &Operands);
1550
1551 bool parseCnt(int64_t &IntVal);
1552 ParseStatus parseSWaitCnt(OperandVector &Operands);
1553
1554 bool parseDepCtr(int64_t &IntVal, unsigned &Mask);
1555 void depCtrError(SMLoc Loc, int ErrorId, StringRef DepCtrName);
1556 ParseStatus parseDepCtr(OperandVector &Operands);
1557
1558 bool parseDelay(int64_t &Delay);
1559 ParseStatus parseSDelayALU(OperandVector &Operands);
1560
1561 ParseStatus parseHwreg(OperandVector &Operands);
1562
1563private:
1564 struct OperandInfoTy {
1565 SMLoc Loc;
1566 int64_t Val;
1567 bool IsSymbolic = false;
1568 bool IsDefined = false;
1569
1570 constexpr OperandInfoTy(int64_t Val) : Val(Val) {}
1571 };
1572
1573 struct StructuredOpField : OperandInfoTy {
1574 StringLiteral Id;
1575 StringLiteral Desc;
1576 unsigned Width;
1577 bool IsDefined = false;
1578
1579 constexpr StructuredOpField(StringLiteral Id, StringLiteral Desc,
1580 unsigned Width, int64_t Default)
1581 : OperandInfoTy(Default), Id(Id), Desc(Desc), Width(Width) {}
1582 virtual ~StructuredOpField() = default;
1583
1584 bool Error(AMDGPUAsmParser &Parser, const Twine &Err) const {
1585 Parser.Error(Loc, "invalid " + Desc + ": " + Err);
1586 return false;
1587 }
1588
1589 virtual bool validate(AMDGPUAsmParser &Parser) const {
1590 if (IsSymbolic && Val == OPR_ID_UNSUPPORTED)
1591 return Error(Parser, "not supported on this GPU");
1592 if (!isUIntN(Width, Val))
1593 return Error(Parser, "only " + Twine(Width) + "-bit values are legal");
1594 return true;
1595 }
1596 };
1597
1598 ParseStatus parseStructuredOpFields(ArrayRef<StructuredOpField *> Fields);
1599 bool validateStructuredOpFields(ArrayRef<const StructuredOpField *> Fields);
1600
1601 bool parseSendMsgBody(OperandInfoTy &Msg, OperandInfoTy &Op,
1602 OperandInfoTy &Stream);
1603 bool validateSendMsg(const OperandInfoTy &Msg, const OperandInfoTy &Op,
1604 const OperandInfoTy &Stream);
1605
1606 ParseStatus parseHwregFunc(OperandInfoTy &HwReg, OperandInfoTy &Offset,
1607 OperandInfoTy &Width);
1608
1609 const AMDGPUOperand &findMCOperand(const OperandVector &Operands,
1610 int MCOpIdx) const;
1611
1612 static SMLoc getLaterLoc(SMLoc a, SMLoc b);
1613
1614 SMLoc getFlatOffsetLoc(const OperandVector &Operands) const;
1615 SMLoc getSMEMOffsetLoc(const OperandVector &Operands) const;
1616 SMLoc getBLGPLoc(const OperandVector &Operands) const;
1617
1618 SMLoc getOperandLoc(const OperandVector &Operands, int MCOpIdx) const;
1619 SMLoc getOperandLoc(std::function<bool(const AMDGPUOperand &)> Test,
1620 const OperandVector &Operands) const;
1621 SMLoc getImmLoc(AMDGPUOperand::ImmTy Type,
1622 const OperandVector &Operands) const;
1623 SMLoc getInstLoc(const OperandVector &Operands) const;
1624
1625 bool validateInstruction(const MCInst &Inst, SMLoc IDLoc,
1626 const OperandVector &Operands);
1627 bool validateOffset(const MCInst &Inst, const OperandVector &Operands);
1628 bool validateFlatOffset(const MCInst &Inst, const OperandVector &Operands);
1629 bool validateSMEMOffset(const MCInst &Inst, const OperandVector &Operands);
1630 bool validateSMEMSData(const MCInst &Inst, const OperandVector &Operands);
1631 bool validateBF16InlineConst(const MCInst &Inst,
1632 const OperandVector &Operands);
1633 bool validateSOPLiteral(const MCInst &Inst, const OperandVector &Operands);
1634 bool validateConstantBusLimitations(const MCInst &Inst,
1635 const OperandVector &Operands);
1636 std::optional<unsigned> checkVOPDRegBankConstraints(const MCInst &Inst,
1637 bool AsVOPD3);
1638 bool validateVOPD(const MCInst &Inst, const OperandVector &Operands);
1639 bool tryVOPD(const MCInst &Inst);
1640 bool tryVOPD3(const MCInst &Inst);
1641 bool tryAnotherVOPDEncoding(const MCInst &Inst);
1642
1643 bool validateIntClampSupported(const MCInst &Inst);
1644 bool validateMIMGAtomicDMask(const MCInst &Inst);
1645 bool validateMIMGGatherDMask(const MCInst &Inst);
1646 bool validateMovrels(const MCInst &Inst, const OperandVector &Operands);
1647 bool validateMIMGDataSize(const MCInst &Inst, SMLoc IDLoc);
1648 bool validateMIMGAddrSize(const MCInst &Inst, SMLoc IDLoc);
1649 bool validateMIMGD16(const MCInst &Inst);
1650 bool validateMIMGDim(const MCInst &Inst, const OperandVector &Operands);
1651 bool validateTensorR128(const MCInst &Inst);
1652 bool validateMIMGMSAA(const MCInst &Inst);
1653 bool validateOpSel(const MCInst &Inst);
1654 bool validateTrue16OpSel(const MCInst &Inst);
1655 bool validateNeg(const MCInst &Inst, AMDGPU::OpName OpName);
1656 bool validateDPP(const MCInst &Inst, const OperandVector &Operands);
1657 bool validateVccOperand(MCRegister Reg) const;
1658 bool validateVOPLiteral(const MCInst &Inst, const OperandVector &Operands);
1659 bool validateMAIAccWrite(const MCInst &Inst, const OperandVector &Operands);
1660 bool validateMAISrc2(const MCInst &Inst, const OperandVector &Operands);
1661 bool validateMFMA(const MCInst &Inst, const OperandVector &Operands);
1662 bool validateAGPRLdSt(const MCInst &Inst) const;
1663 bool validateVGPRAlign(const MCInst &Inst) const;
1664 bool validateBLGP(const MCInst &Inst, const OperandVector &Operands);
1665 bool validateDS(const MCInst &Inst, const OperandVector &Operands);
1666 bool validateGWS(const MCInst &Inst, const OperandVector &Operands);
1667 bool validateDivScale(const MCInst &Inst);
1668 bool validateWaitCnt(const MCInst &Inst, const OperandVector &Operands);
1669 bool validateCoherencyBits(const MCInst &Inst, const OperandVector &Operands,
1670 SMLoc IDLoc);
1671 bool validateTHAndScopeBits(const MCInst &Inst, const OperandVector &Operands,
1672 const unsigned CPol);
1673 bool validateCFSBits(const MCInst &Inst, const OperandVector &Operands);
1674 bool validateTFE(const MCInst &Inst, const OperandVector &Operands);
1675 bool validateLdsDirect(const MCInst &Inst, const OperandVector &Operands);
1676 bool validateWMMA(const MCInst &Inst, const OperandVector &Operands);
1677 bool validateMonitorSleep(const MCInst &Inst, const OperandVector &Operands);
1678 bool validateClusterBarrierIsFirst(const MCInst &Inst,
1679 const OperandVector &Operands);
1680 bool validateScaleSel(const MCInst &Inst, const OperandVector &Operands);
1681 unsigned getConstantBusLimit(unsigned Opcode) const;
1682 bool usesConstantBus(const MCInst &Inst, unsigned OpIdx);
1683 bool isInlineConstant(const MCInst &Inst, unsigned OpIdx) const;
1684 MCRegister findImplicitSGPRReadInVOP(const MCInst &Inst) const;
1685
1686 bool isSupportedMnemo(StringRef Mnemo, const FeatureBitset &FBS);
1687 bool isSupportedMnemo(StringRef Mnemo, const FeatureBitset &FBS,
1688 ArrayRef<unsigned> Variants);
1689 bool checkUnsupportedInstruction(StringRef Name, SMLoc IDLoc);
1690
1691 bool isId(const StringRef Id) const;
1692 bool isId(const AsmToken &Token, const StringRef Id) const;
1693 bool isToken(const AsmToken::TokenKind Kind) const;
1694 StringRef getId() const;
1695 bool trySkipId(const StringRef Id);
1696 bool trySkipId(const StringRef Pref, const StringRef Id);
1697 bool trySkipId(const StringRef Id, const AsmToken::TokenKind Kind);
1698 bool trySkipToken(const AsmToken::TokenKind Kind);
1699 bool skipToken(const AsmToken::TokenKind Kind, const StringRef ErrMsg);
1700 bool parseString(StringRef &Val,
1701 const StringRef ErrMsg = "expected a string");
1702 bool parseId(StringRef &Val, const StringRef ErrMsg = "");
1703
1704 void peekTokens(MutableArrayRef<AsmToken> Tokens);
1705 AsmToken::TokenKind getTokenKind() const;
1706 bool parseExpr(int64_t &Imm, StringRef Expected = "");
1708 StringRef getTokenStr() const;
1709 AsmToken peekToken(bool ShouldSkipSpace = true);
1710 AsmToken getToken() const;
1711 SMLoc getLoc() const;
1712 void lex();
1713
1714public:
1715 void onBeginOfFile() override;
1716 /// Emit the deferred leading .amdgcn_target directive if it has not been
1717 /// emitted yet. Called before emitting the first instruction or kernel
1718 /// descriptor, so that any leading .amdgcn_target/.amd_amdgpu_isa directive
1719 /// in the source has had a chance to update the target ID first.
1720 void emitTargetDirective();
1721 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
1722
1723 ParseStatus parseCustomOperand(OperandVector &Operands, unsigned MCK);
1724
1725 ParseStatus parseExpTgt(OperandVector &Operands);
1726 ParseStatus parseSendMsg(OperandVector &Operands);
1727 ParseStatus parseWaitEvent(OperandVector &Operands);
1728 ParseStatus parseInterpSlot(OperandVector &Operands);
1729 ParseStatus parseInterpAttr(OperandVector &Operands);
1730 ParseStatus parseSOPPBrTarget(OperandVector &Operands);
1731 ParseStatus parseSMEMOffsetPCRel(OperandVector &Operands);
1732 ParseStatus parseBoolReg(OperandVector &Operands);
1733
1734 bool parseSwizzleOperand(int64_t &Op, const unsigned MinVal,
1735 const unsigned MaxVal, const Twine &ErrMsg,
1736 SMLoc &Loc);
1737 bool parseSwizzleOperands(const unsigned OpNum, int64_t *Op,
1738 const unsigned MinVal, const unsigned MaxVal,
1739 const StringRef ErrMsg);
1740 ParseStatus parseSwizzle(OperandVector &Operands);
1741 bool parseSwizzleOffset(int64_t &Imm);
1742 bool parseSwizzleMacro(int64_t &Imm);
1743 bool parseSwizzleQuadPerm(int64_t &Imm);
1744 bool parseSwizzleBitmaskPerm(int64_t &Imm);
1745 bool parseSwizzleBroadcast(int64_t &Imm);
1746 bool parseSwizzleSwap(int64_t &Imm);
1747 bool parseSwizzleReverse(int64_t &Imm);
1748 bool parseSwizzleFFT(int64_t &Imm);
1749 bool parseSwizzleRotate(int64_t &Imm);
1750
1751 ParseStatus parseGPRIdxMode(OperandVector &Operands);
1752 int64_t parseGPRIdxMacro();
1753
1754 void cvtMubuf(MCInst &Inst, const OperandVector &Operands) {
1755 cvtMubufImpl(Inst, Operands, false);
1756 }
1757 void cvtMubufAtomic(MCInst &Inst, const OperandVector &Operands) {
1758 cvtMubufImpl(Inst, Operands, true);
1759 }
1760
1761 ParseStatus parseOModSI(OperandVector &Operands);
1762
1763 void cvtVOP3(MCInst &Inst, const OperandVector &Operands,
1764 OptionalImmIndexMap &OptionalIdx);
1765 void cvtScaledMFMA(MCInst &Inst, const OperandVector &Operands);
1766 void cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands);
1767 void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
1768 void cvtVOP3P(MCInst &Inst, const OperandVector &Operands);
1769 void cvtSWMMAC(MCInst &Inst, const OperandVector &Operands);
1770
1771 void cvtVOPD(MCInst &Inst, const OperandVector &Operands);
1772 void cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands,
1773 OptionalImmIndexMap &OptionalIdx);
1774 void cvtVOP3P(MCInst &Inst, const OperandVector &Operands,
1775 OptionalImmIndexMap &OptionalIdx);
1776
1777 void cvtVOP3Interp(MCInst &Inst, const OperandVector &Operands);
1778 void cvtVINTERP(MCInst &Inst, const OperandVector &Operands);
1779 void cvtOpSelHelper(MCInst &Inst, unsigned OpSel);
1780
1781 bool parseDimId(unsigned &Encoding);
1782 ParseStatus parseDim(OperandVector &Operands);
1783 bool convertDppBoundCtrl(int64_t &BoundCtrl);
1784 ParseStatus parseDPP8(OperandVector &Operands);
1785 ParseStatus parseDPPCtrl(OperandVector &Operands);
1786 bool isSupportedDPPCtrl(StringRef Ctrl, const OperandVector &Operands);
1787 int64_t parseDPPCtrlSel(StringRef Ctrl);
1788 int64_t parseDPPCtrlPerm();
1789 void cvtDPP(MCInst &Inst, const OperandVector &Operands, bool IsDPP8 = false);
1790 void cvtDPP8(MCInst &Inst, const OperandVector &Operands) {
1791 cvtDPP(Inst, Operands, true);
1792 }
1793 void cvtVOP3DPP(MCInst &Inst, const OperandVector &Operands,
1794 bool IsDPP8 = false);
1795 void cvtVOP3DPP8(MCInst &Inst, const OperandVector &Operands) {
1796 cvtVOP3DPP(Inst, Operands, true);
1797 }
1798
1799 ParseStatus parseSDWASel(OperandVector &Operands, StringRef Prefix,
1800 AMDGPUOperand::ImmTy Type);
1801 ParseStatus parseSDWADstUnused(OperandVector &Operands);
1802 void cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands);
1803 void cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands);
1804 void cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands);
1805 void cvtSdwaVOP2e(MCInst &Inst, const OperandVector &Operands);
1806 void cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands);
1807
1808 enum class SDWAInstType : unsigned { VOP1 = 0, VOP2 = 1, VOPC = 2 };
1809
1810 void cvtSDWA(MCInst &Inst, const OperandVector &Operands,
1811 SDWAInstType BasicInstType, bool SkipDstVcc = false,
1812 bool SkipSrcVcc = false);
1813
1814 ParseStatus parseEndpgm(OperandVector &Operands);
1815
1816 ParseStatus parseVOPD(OperandVector &Operands);
1817};
1818
1819} // end anonymous namespace
1820
1821// May be called with integer type with equivalent bitwidth.
1822static const fltSemantics *getFltSemantics(unsigned Size) {
1823 switch (Size) {
1824 case 4:
1825 return &APFloat::IEEEsingle();
1826 case 8:
1827 return &APFloat::IEEEdouble();
1828 case 2:
1829 return &APFloat::IEEEhalf();
1830 default:
1831 llvm_unreachable("unsupported fp type");
1832 }
1833}
1834
1836 return getFltSemantics(VT.getScalarSizeInBits() / 8);
1837}
1838
1840 switch (OperandType) {
1841 // When floating-point immediate is used as operand of type i16, the 32-bit
1842 // representation of the constant truncated to the 16 LSBs should be used.
1857 return &APFloat::IEEEsingle();
1866 return &APFloat::IEEEdouble();
1875 return &APFloat::IEEEhalf();
1880 return &APFloat::BFloat();
1881 default:
1882 llvm_unreachable("unsupported fp type");
1883 }
1884}
1885
1886//===----------------------------------------------------------------------===//
1887// Operand
1888//===----------------------------------------------------------------------===//
1889
1890static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT) {
1891 bool Lost;
1892
1893 // Convert literal to single precision
1894 APFloat::opStatus Status = FPLiteral.convert(
1896 // We allow precision lost but not overflow or underflow
1897 if (Status != APFloat::opOK && Lost &&
1898 ((Status & APFloat::opOverflow) != 0 ||
1899 (Status & APFloat::opUnderflow) != 0)) {
1900 return false;
1901 }
1902
1903 return true;
1904}
1905
1906static bool isSafeTruncation(int64_t Val, unsigned Size) {
1907 return isUIntN(Size, Val) || isIntN(Size, Val);
1908}
1909
1910static bool isInlineableLiteralOp16(int64_t Val, MVT VT, bool HasInv2Pi) {
1911 if (VT.getScalarType() == MVT::i16)
1912 return isInlinableLiteral32(Val, HasInv2Pi);
1913
1914 if (VT.getScalarType() == MVT::f16)
1915 return AMDGPU::isInlinableLiteralFP16(Val, HasInv2Pi);
1916
1917 assert(VT.getScalarType() == MVT::bf16);
1918
1919 return AMDGPU::isInlinableLiteralBF16(Val, HasInv2Pi);
1920}
1921
1922bool AMDGPUOperand::isInlinableImm(MVT type) const {
1923
1924 // This is a hack to enable named inline values like
1925 // shared_base with both 32-bit and 64-bit operands.
1926 // Note that these values are defined as
1927 // 32-bit operands only.
1928 if (isInlineValue()) {
1929 return true;
1930 }
1931
1932 if (!isImmTy(ImmTyNone)) {
1933 // Only plain immediates are inlinable (e.g. "clamp" attribute is not)
1934 return false;
1935 }
1936
1937 if (getModifiers().Lit != LitModifier::None)
1938 return false;
1939
1940 // TODO: We should avoid using host float here. It would be better to
1941 // check the float bit values which is what a few other places do.
1942 // We've had bot failures before due to weird NaN support on mips hosts.
1943
1944 APInt Literal(64, Imm.Val);
1945
1946 if (Imm.IsFPImm) { // We got fp literal token
1947 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1949 AsmParser->hasInv2PiInlineImm());
1950 }
1951
1952 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
1953 if (!canLosslesslyConvertToFPType(FPLiteral, type))
1954 return false;
1955
1956 if (type.getScalarSizeInBits() == 16) {
1957 bool Lost = false;
1958 switch (type.getScalarType().SimpleTy) {
1959 default:
1960 llvm_unreachable("unknown 16-bit type");
1961 case MVT::bf16:
1962 FPLiteral.convert(APFloatBase::BFloat(), APFloat::rmNearestTiesToEven,
1963 &Lost);
1964 break;
1965 case MVT::f16:
1966 FPLiteral.convert(APFloatBase::IEEEhalf(), APFloat::rmNearestTiesToEven,
1967 &Lost);
1968 break;
1969 case MVT::i16:
1970 FPLiteral.convert(APFloatBase::IEEEsingle(),
1971 APFloat::rmNearestTiesToEven, &Lost);
1972 break;
1973 }
1974 // We need to use 32-bit representation here because when a floating-point
1975 // inline constant is used as an i16 operand, its 32-bit representation
1976 // representation will be used. We will need the 32-bit value to check if
1977 // it is FP inline constant.
1978 uint32_t ImmVal = FPLiteral.bitcastToAPInt().getZExtValue();
1979 return isInlineableLiteralOp16(ImmVal, type,
1980 AsmParser->hasInv2PiInlineImm());
1981 }
1982
1983 // Check if single precision literal is inlinable
1985 static_cast<int32_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
1986 AsmParser->hasInv2PiInlineImm());
1987 }
1988
1989 // We got int literal token.
1990 if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
1992 AsmParser->hasInv2PiInlineImm());
1993 }
1994
1995 if (!isSafeTruncation(Imm.Val, type.getScalarSizeInBits())) {
1996 return false;
1997 }
1998
1999 if (type.getScalarSizeInBits() == 16) {
2001 static_cast<int16_t>(Literal.getLoBits(16).getSExtValue()), type,
2002 AsmParser->hasInv2PiInlineImm());
2003 }
2004
2006 static_cast<int32_t>(Literal.getLoBits(32).getZExtValue()),
2007 AsmParser->hasInv2PiInlineImm());
2008}
2009
2010bool AMDGPUOperand::isLiteralImm(MVT type) const {
2011 // Check that this immediate can be added as literal
2012 if (!isImmTy(ImmTyNone)) {
2013 return false;
2014 }
2015
2016 bool Allow64Bit =
2017 (type == MVT::i64 || type == MVT::f64) && AsmParser->has64BitLiterals();
2018
2019 if (!Imm.IsFPImm) {
2020 // We got int literal token.
2021
2022 if (type == MVT::f64 && hasFPModifiers()) {
2023 // Cannot apply fp modifiers to int literals preserving the same semantics
2024 // for VOP1/2/C and VOP3 because of integer truncation. To avoid
2025 // ambiguity, disable these cases.
2026 return false;
2027 }
2028
2029 unsigned Size = type.getSizeInBits();
2030 if (Size == 64) {
2031 if (Allow64Bit && !AMDGPU::isValid32BitLiteral(Imm.Val, false))
2032 return true;
2033 Size = 32;
2034 }
2035
2036 // FIXME: 64-bit operands can zero extend, sign extend, or pad zeroes for FP
2037 // types.
2038 return isSafeTruncation(Imm.Val, Size);
2039 }
2040
2041 // We got fp literal token
2042 if (type == MVT::f64) { // Expected 64-bit fp operand
2043 // We would set low 64-bits of literal to zeroes but we accept this literals
2044 return true;
2045 }
2046
2047 if (type == MVT::i64) { // Expected 64-bit int operand
2048 // We don't allow fp literals in 64-bit integer instructions. It is
2049 // unclear how we should encode them.
2050 return false;
2051 }
2052
2053 // We allow fp literals with f16x2 operands assuming that the specified
2054 // literal goes into the lower half and the upper half is zero. We also
2055 // require that the literal may be losslessly converted to f16.
2056 //
2057 // For i16x2 operands, we assume that the specified literal is encoded as a
2058 // single-precision float. This is pretty odd, but it matches SP3 and what
2059 // happens in hardware.
2060 MVT ExpectedType = (type == MVT::v2f16) ? MVT::f16
2061 : (type == MVT::v2i16) ? MVT::f32
2062 : (type == MVT::v2f32) ? MVT::f32
2063 : type;
2064
2065 APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
2066 return canLosslesslyConvertToFPType(FPLiteral, ExpectedType);
2067}
2068
2069bool AMDGPUOperand::isRegClassTarget(unsigned TargetRCIdx) const {
2070 if (!isRegKind())
2071 return false;
2072 int16_t RCID = AsmParser->getTargetRegClass(TargetRCIdx);
2073 return RCID >= 0 && isRegClass(RCID);
2074}
2075
2076bool AMDGPUOperand::isRegClass(unsigned RCID) const {
2077 return isRegKind() &&
2078 AsmParser->getMRI()->getRegClass(RCID).contains(getReg());
2079}
2080
2081bool AMDGPUOperand::isVRegWithInputMods() const {
2082 return isRegClass(AMDGPU::VGPR_32RegClassID) ||
2083 // GFX90A allows DPP on 64-bit operands.
2084 (AsmParser->getFeatureBits()[AMDGPU::FeatureDPALU_DPP] &&
2085 isRegClassTarget(AMDGPU::VReg_64_AlignTarget));
2086}
2087
2088template <bool IsFake16>
2089bool AMDGPUOperand::isT16_Lo128VRegWithInputMods() const {
2090 return isRegClass(IsFake16 ? AMDGPU::VGPR_32_Lo128RegClassID
2091 : AMDGPU::VGPR_16_Lo128RegClassID);
2092}
2093
2094template <bool IsFake16> bool AMDGPUOperand::isT16VRegWithInputMods() const {
2095 return isRegClass(IsFake16 ? AMDGPU::VGPR_32RegClassID
2096 : AMDGPU::VGPR_16RegClassID);
2097}
2098
2099bool AMDGPUOperand::isT16_LO16VRegWithInputMods() const {
2100 return isRegClass(AMDGPU::VGPR_16_LO16RegClassID);
2101}
2102
2103bool AMDGPUOperand::isSDWAOperand(MVT type) const {
2104 if (AsmParser->isVI())
2105 return isVReg32();
2106 if (AsmParser->isGFX9Plus())
2107 return isRegClass(AMDGPU::VS_32RegClassID) || isInlinableImm(type);
2108 return false;
2109}
2110
2111bool AMDGPUOperand::isSDWAFP16Operand() const {
2112 return isSDWAOperand(MVT::f16);
2113}
2114
2115bool AMDGPUOperand::isSDWAFP32Operand() const {
2116 return isSDWAOperand(MVT::f32);
2117}
2118
2119bool AMDGPUOperand::isSDWAInt16Operand() const {
2120 return isSDWAOperand(MVT::i16);
2121}
2122
2123bool AMDGPUOperand::isSDWAInt32Operand() const {
2124 return isSDWAOperand(MVT::i32);
2125}
2126
2127bool AMDGPUOperand::isBoolReg() const {
2128 return isReg() && ((AsmParser->isWave64() && isSCSrc_b64()) ||
2129 (AsmParser->isWave32() && isSCSrc_b32()));
2130}
2131
2132uint64_t AMDGPUOperand::applyInputFPModifiers(uint64_t Val,
2133 unsigned Size) const {
2134 assert(isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
2135 assert(Size == 2 || Size == 4 || Size == 8);
2136
2137 const uint64_t FpSignMask = (1ULL << (Size * 8 - 1));
2138
2139 if (Imm.Mods.Abs) {
2140 Val &= ~FpSignMask;
2141 }
2142 if (Imm.Mods.Neg) {
2143 Val ^= FpSignMask;
2144 }
2145
2146 return Val;
2147}
2148
2149void AMDGPUOperand::addImmOperands(MCInst &Inst, unsigned N,
2150 bool ApplyModifiers) const {
2151 MCOpIdx = Inst.getNumOperands();
2152
2153 if (isExpr()) {
2155 return;
2156 }
2157
2158 if (AMDGPU::isSISrcOperand(AsmParser->getMII()->get(Inst.getOpcode()),
2159 Inst.getNumOperands())) {
2160 addLiteralImmOperand(Inst, Imm.Val,
2161 ApplyModifiers & isImmTy(ImmTyNone) &&
2162 Imm.Mods.hasFPModifiers());
2163 } else {
2164 assert(!isImmTy(ImmTyNone) || !hasModifiers());
2166 }
2167}
2168
2169void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, int64_t Val,
2170 bool ApplyModifiers) const {
2171 const auto &InstDesc = AsmParser->getMII()->get(Inst.getOpcode());
2172 auto OpNum = Inst.getNumOperands();
2173 // Check that this operand accepts literals
2174 assert(AMDGPU::isSISrcOperand(InstDesc, OpNum));
2175
2176 if (ApplyModifiers) {
2177 assert(AMDGPU::isSISrcFPOperand(InstDesc, OpNum));
2178 const unsigned Size =
2179 Imm.IsFPImm ? sizeof(double) : getOperandSize(InstDesc, OpNum);
2180 Val = applyInputFPModifiers(Val, Size);
2181 }
2182
2183 APInt Literal(64, Val);
2184 uint8_t OpTy = InstDesc.operands()[OpNum].OperandType;
2185
2186 bool CanUse64BitLiterals =
2187 AsmParser->has64BitLiterals() && !SIInstrFlags::isVOP3Like(InstDesc);
2188 LitModifier Lit = getModifiers().Lit;
2189 MCContext &Ctx = AsmParser->getContext();
2190
2191 if (Imm.IsFPImm) { // We got fp literal token
2192 switch (OpTy) {
2200 if (Lit == LitModifier::None &&
2202 AsmParser->hasInv2PiInlineImm())) {
2203 Inst.addOperand(MCOperand::createImm(Literal.getZExtValue()));
2204 return;
2205 }
2206
2207 // Non-inlineable
2208 if (AMDGPU::isSISrcFPOperand(InstDesc,
2209 OpNum)) { // Expected 64-bit fp operand
2210 bool HasMandatoryLiteral =
2211 AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::imm);
2212 // For fp operands we check if low 32 bits are zeros
2213 if (Literal.getLoBits(32) != 0 &&
2214 (InstDesc.getSize() != 4 || !AsmParser->has64BitLiterals()) &&
2215 !HasMandatoryLiteral) {
2216 const_cast<AMDGPUAsmParser *>(AsmParser)->Warning(
2217 Inst.getLoc(),
2218 "Can't encode literal as exact 64-bit floating-point operand. "
2219 "Low 32-bits will be set to zero");
2220 Val &= 0xffffffff00000000u;
2221 }
2222
2223 if ((OpTy == AMDGPU::OPERAND_REG_IMM_FP64 ||
2226 if (CanUse64BitLiterals && Lit == LitModifier::None &&
2227 (isInt<32>(Val) || isUInt<32>(Val))) {
2228 // The floating-point operand will be verbalized as an
2229 // integer one. If that integer happens to fit 32 bits, on
2230 // re-assembling it will be intepreted as the high half of
2231 // the actual value, so we have to wrap it into lit64().
2232 Lit = LitModifier::Lit64;
2233 } else if (Lit == LitModifier::Lit) {
2234 // For FP64 operands lit() specifies the high half of the value.
2235 Val = Hi_32(Val);
2236 }
2237 }
2238 break;
2239 }
2240
2241 // We don't allow fp literals in 64-bit integer instructions. It is
2242 // unclear how we should encode them. This case should be checked earlier
2243 // in predicate methods (isLiteralImm())
2244 llvm_unreachable("fp literal in 64-bit integer instruction.");
2245
2247 if (CanUse64BitLiterals && Lit == LitModifier::None &&
2248 (isInt<32>(Val) || isUInt<32>(Val)))
2249 Lit = LitModifier::Lit64;
2250 break;
2251
2256 if (Lit == LitModifier::None && AsmParser->hasInv2PiInlineImm() &&
2257 Literal == 0x3fc45f306725feed) {
2258 // This is the 1/(2*pi) which is going to be truncated to bf16 with the
2259 // loss of precision. The constant represents idiomatic fp32 value of
2260 // 1/(2*pi) = 0.15915494 since bf16 is in fact fp32 with cleared low 16
2261 // bits. Prevent rounding below.
2262 Inst.addOperand(MCOperand::createImm(0x3e22));
2263 return;
2264 }
2265 [[fallthrough]];
2266
2289 bool lost;
2290 APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
2291 // Convert literal to single precision
2292 FPLiteral.convert(*getOpFltSemantics(OpTy), APFloat::rmNearestTiesToEven,
2293 &lost);
2294 // We allow precision lost but not overflow or underflow. This should be
2295 // checked earlier in isLiteralImm()
2296
2297 Val = FPLiteral.bitcastToAPInt().getZExtValue();
2298
2299 // On GFX11+, an f16 inline constant for a V2FP16_SPLAT operand should be
2300 // replicated into both halves.
2302 Lit == LitModifier::None && AsmParser->isGFX11Plus() &&
2303 AMDGPU::isInlinableLiteralFP16(static_cast<int16_t>(Val),
2304 AsmParser->hasInv2PiInlineImm()))
2305 Val = (Val << 16) | Val;
2306 break;
2307 }
2308 default:
2309 llvm_unreachable("invalid operand size");
2310 }
2311
2312 if (Lit != LitModifier::None) {
2313 Inst.addOperand(
2315 } else {
2317 }
2318 return;
2319 }
2320
2321 // We got int literal token.
2322 // Only sign extend inline immediates.
2323 switch (OpTy) {
2338 break;
2339
2343 if (Lit == LitModifier::None &&
2344 AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
2346 return;
2347 }
2348
2349 // When the 32 MSBs are not zero (effectively means it can't be safely
2350 // truncated to uint32_t), if the target doesn't support 64-bit literals, or
2351 // the lit modifier is explicitly used, we need to truncate it to the 32
2352 // LSBs.
2353 if (!AsmParser->has64BitLiterals() || Lit == LitModifier::Lit)
2354 Val = Lo_32(Val);
2355 break;
2356
2361 if (Lit == LitModifier::None &&
2362 AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
2364 return;
2365 }
2366
2367 // If the target doesn't support 64-bit literals, we need to use the
2368 // constant as the high 32 MSBs of a double-precision floating point value.
2369 if (!AsmParser->has64BitLiterals()) {
2370 Val = static_cast<uint64_t>(Val) << 32;
2371 } else {
2372 // Now the target does support 64-bit literals, there are two cases
2373 // where we still want to use src_literal encoding:
2374 // 1) explicitly forced by using lit modifier;
2375 // 2) the value is a valid 32-bit representation (signed or unsigned),
2376 // meanwhile not forced by lit64 modifier.
2377 if (Lit == LitModifier::Lit ||
2378 (Lit != LitModifier::Lit64 && (isInt<32>(Val) || isUInt<32>(Val))))
2379 Val = static_cast<uint64_t>(Val) << 32;
2380 }
2381
2382 // For FP64 operands lit() specifies the high half of the value.
2383 if (Lit == LitModifier::Lit)
2384 Val = Hi_32(Val);
2385 break;
2386
2399 break;
2400
2402 if ((isInt<32>(Val) || isUInt<32>(Val)) && Lit != LitModifier::Lit64)
2403 Val <<= 32;
2404 break;
2405
2406 default:
2407 llvm_unreachable("invalid operand type");
2408 }
2409
2410 if (Lit != LitModifier::None) {
2411 Inst.addOperand(
2413 } else {
2415 }
2416}
2417
2418void AMDGPUOperand::addRegOperands(MCInst &Inst, unsigned N) const {
2419 MCOpIdx = Inst.getNumOperands();
2420 Inst.addOperand(
2421 MCOperand::createReg(AMDGPU::getMCReg(getReg(), AsmParser->getSTI())));
2422}
2423
2424bool AMDGPUOperand::isInlineValue() const {
2425 return isRegKind() && ::isInlineValue(getReg());
2426}
2427
2428//===----------------------------------------------------------------------===//
2429// AsmParser
2430//===----------------------------------------------------------------------===//
2431
2432void AMDGPUAsmParser::createConstantSymbol(StringRef Id, int64_t Val) {
2433 // TODO: make those pre-defined variables read-only.
2434 // Currently there is none suitable machinery in the core llvm-mc for this.
2435 // MCSymbol::isRedefinable is intended for another purpose, and
2436 // AsmParser::parseDirectiveSet() cannot be specialized for specific target.
2437 MCContext &Ctx = getContext();
2438 MCSymbol *Sym = Ctx.getOrCreateSymbol(Id);
2440}
2441
2442static int getRegClass(RegisterKind Is, unsigned RegWidth) {
2443 if (Is == IS_VGPR) {
2444 switch (RegWidth) {
2445 default:
2446 return -1;
2447 case 32:
2448 return AMDGPU::VGPR_32RegClassID;
2449 case 64:
2450 return AMDGPU::VReg_64RegClassID;
2451 case 96:
2452 return AMDGPU::VReg_96RegClassID;
2453 case 128:
2454 return AMDGPU::VReg_128RegClassID;
2455 case 160:
2456 return AMDGPU::VReg_160RegClassID;
2457 case 192:
2458 return AMDGPU::VReg_192RegClassID;
2459 case 224:
2460 return AMDGPU::VReg_224RegClassID;
2461 case 256:
2462 return AMDGPU::VReg_256RegClassID;
2463 case 288:
2464 return AMDGPU::VReg_288RegClassID;
2465 case 320:
2466 return AMDGPU::VReg_320RegClassID;
2467 case 352:
2468 return AMDGPU::VReg_352RegClassID;
2469 case 384:
2470 return AMDGPU::VReg_384RegClassID;
2471 case 512:
2472 return AMDGPU::VReg_512RegClassID;
2473 case 1024:
2474 return AMDGPU::VReg_1024RegClassID;
2475 }
2476 } else if (Is == IS_TTMP) {
2477 switch (RegWidth) {
2478 default:
2479 return -1;
2480 case 32:
2481 return AMDGPU::TTMP_32RegClassID;
2482 case 64:
2483 return AMDGPU::TTMP_64RegClassID;
2484 case 128:
2485 return AMDGPU::TTMP_128RegClassID;
2486 case 256:
2487 return AMDGPU::TTMP_256RegClassID;
2488 case 512:
2489 return AMDGPU::TTMP_512RegClassID;
2490 }
2491 } else if (Is == IS_SGPR) {
2492 switch (RegWidth) {
2493 default:
2494 return -1;
2495 case 32:
2496 return AMDGPU::SGPR_32RegClassID;
2497 case 64:
2498 return AMDGPU::SGPR_64RegClassID;
2499 case 96:
2500 return AMDGPU::SGPR_96RegClassID;
2501 case 128:
2502 return AMDGPU::SGPR_128RegClassID;
2503 case 160:
2504 return AMDGPU::SGPR_160RegClassID;
2505 case 192:
2506 return AMDGPU::SGPR_192RegClassID;
2507 case 224:
2508 return AMDGPU::SGPR_224RegClassID;
2509 case 256:
2510 return AMDGPU::SGPR_256RegClassID;
2511 case 288:
2512 return AMDGPU::SGPR_288RegClassID;
2513 case 320:
2514 return AMDGPU::SGPR_320RegClassID;
2515 case 352:
2516 return AMDGPU::SGPR_352RegClassID;
2517 case 384:
2518 return AMDGPU::SGPR_384RegClassID;
2519 case 512:
2520 return AMDGPU::SGPR_512RegClassID;
2521 }
2522 } else if (Is == IS_AGPR) {
2523 switch (RegWidth) {
2524 default:
2525 return -1;
2526 case 32:
2527 return AMDGPU::AGPR_32RegClassID;
2528 case 64:
2529 return AMDGPU::AReg_64RegClassID;
2530 case 96:
2531 return AMDGPU::AReg_96RegClassID;
2532 case 128:
2533 return AMDGPU::AReg_128RegClassID;
2534 case 160:
2535 return AMDGPU::AReg_160RegClassID;
2536 case 192:
2537 return AMDGPU::AReg_192RegClassID;
2538 case 224:
2539 return AMDGPU::AReg_224RegClassID;
2540 case 256:
2541 return AMDGPU::AReg_256RegClassID;
2542 case 288:
2543 return AMDGPU::AReg_288RegClassID;
2544 case 320:
2545 return AMDGPU::AReg_320RegClassID;
2546 case 352:
2547 return AMDGPU::AReg_352RegClassID;
2548 case 384:
2549 return AMDGPU::AReg_384RegClassID;
2550 case 512:
2551 return AMDGPU::AReg_512RegClassID;
2552 case 1024:
2553 return AMDGPU::AReg_1024RegClassID;
2554 }
2555 }
2556 return -1;
2557}
2558
2561 .Case("exec", AMDGPU::EXEC)
2562 .Case("vcc", AMDGPU::VCC)
2563 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2564 .Case("xnack_mask", AMDGPU::XNACK_MASK)
2565 .Case("shared_base", AMDGPU::SRC_SHARED_BASE)
2566 .Case("src_shared_base", AMDGPU::SRC_SHARED_BASE)
2567 .Case("shared_limit", AMDGPU::SRC_SHARED_LIMIT)
2568 .Case("src_shared_limit", AMDGPU::SRC_SHARED_LIMIT)
2569 .Case("private_base", AMDGPU::SRC_PRIVATE_BASE)
2570 .Case("src_private_base", AMDGPU::SRC_PRIVATE_BASE)
2571 .Case("private_limit", AMDGPU::SRC_PRIVATE_LIMIT)
2572 .Case("src_private_limit", AMDGPU::SRC_PRIVATE_LIMIT)
2573 .Case("src_flat_scratch_base_lo", AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)
2574 .Case("src_flat_scratch_base_hi", AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)
2575 .Case("pops_exiting_wave_id", AMDGPU::SRC_POPS_EXITING_WAVE_ID)
2576 .Case("src_pops_exiting_wave_id", AMDGPU::SRC_POPS_EXITING_WAVE_ID)
2577 .Case("lds_direct", AMDGPU::LDS_DIRECT)
2578 .Case("src_lds_direct", AMDGPU::LDS_DIRECT)
2579 .Case("m0", AMDGPU::M0)
2580 .Case("vccz", AMDGPU::SRC_VCCZ)
2581 .Case("src_vccz", AMDGPU::SRC_VCCZ)
2582 .Case("execz", AMDGPU::SRC_EXECZ)
2583 .Case("src_execz", AMDGPU::SRC_EXECZ)
2584 .Case("scc", AMDGPU::SRC_SCC)
2585 .Case("src_scc", AMDGPU::SRC_SCC)
2586 .Case("tba", AMDGPU::TBA)
2587 .Case("tma", AMDGPU::TMA)
2588 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2589 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2590 .Case("xnack_mask_lo", AMDGPU::XNACK_MASK_LO)
2591 .Case("xnack_mask_hi", AMDGPU::XNACK_MASK_HI)
2592 .Case("vcc_lo", AMDGPU::VCC_LO)
2593 .Case("vcc_hi", AMDGPU::VCC_HI)
2594 .Case("exec_lo", AMDGPU::EXEC_LO)
2595 .Case("exec_hi", AMDGPU::EXEC_HI)
2596 .Case("tma_lo", AMDGPU::TMA_LO)
2597 .Case("tma_hi", AMDGPU::TMA_HI)
2598 .Case("tba_lo", AMDGPU::TBA_LO)
2599 .Case("tba_hi", AMDGPU::TBA_HI)
2600 .Case("pc", AMDGPU::PC_REG)
2601 .Case("null", AMDGPU::SGPR_NULL)
2602 .Default(AMDGPU::NoRegister);
2603}
2604
2605bool AMDGPUAsmParser::ParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
2606 SMLoc &EndLoc, bool RestoreOnFailure) {
2607 auto R = parseRegister();
2608 if (!R)
2609 return true;
2610 assert(R->isReg());
2611 RegNo = R->getReg();
2612 StartLoc = R->getStartLoc();
2613 EndLoc = R->getEndLoc();
2614 return false;
2615}
2616
2617bool AMDGPUAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
2618 SMLoc &EndLoc) {
2619 return ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/false);
2620}
2621
2622ParseStatus AMDGPUAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
2623 SMLoc &EndLoc) {
2624 bool Result = ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/true);
2625 bool PendingErrors = getParser().hasPendingError();
2626 getParser().clearPendingErrors();
2627 if (PendingErrors)
2628 return ParseStatus::Failure;
2629 if (Result)
2630 return ParseStatus::NoMatch;
2631 return ParseStatus::Success;
2632}
2633
2634bool AMDGPUAsmParser::AddNextRegisterToList(MCRegister &Reg, unsigned &RegWidth,
2635 RegisterKind RegKind,
2636 MCRegister Reg1,
2637 RegisterKind RegKind1, SMLoc Loc) {
2638 // Allow VCC_LO/HI at the end of SGPR lists.
2639 if (RegKind == IS_SGPR) {
2640 unsigned RegIdx = (Reg - AMDGPU::SGPR0) + RegWidth / 32;
2641 if ((RegIdx == 106 && Reg1 == AMDGPU::VCC_LO) ||
2642 (RegIdx == 107 && Reg1 == AMDGPU::VCC_HI)) {
2643 RegWidth += 32;
2644 return true;
2645 }
2646 }
2647
2648 if (RegKind != RegKind1) {
2649 Error(Loc, "registers in a list must be of the same kind");
2650 return false;
2651 }
2652
2653 switch (RegKind) {
2654 case IS_SPECIAL:
2655 if (Reg == AMDGPU::EXEC_LO && Reg1 == AMDGPU::EXEC_HI) {
2656 Reg = AMDGPU::EXEC;
2657 RegWidth = 64;
2658 return true;
2659 }
2660 if (Reg == AMDGPU::FLAT_SCR_LO && Reg1 == AMDGPU::FLAT_SCR_HI) {
2661 Reg = AMDGPU::FLAT_SCR;
2662 RegWidth = 64;
2663 return true;
2664 }
2665 if (Reg == AMDGPU::XNACK_MASK_LO && Reg1 == AMDGPU::XNACK_MASK_HI) {
2666 Reg = AMDGPU::XNACK_MASK;
2667 RegWidth = 64;
2668 return true;
2669 }
2670 if (Reg == AMDGPU::VCC_LO && Reg1 == AMDGPU::VCC_HI) {
2671 Reg = AMDGPU::VCC;
2672 RegWidth = 64;
2673 return true;
2674 }
2675 if (Reg == AMDGPU::TBA_LO && Reg1 == AMDGPU::TBA_HI) {
2676 Reg = AMDGPU::TBA;
2677 RegWidth = 64;
2678 return true;
2679 }
2680 if (Reg == AMDGPU::TMA_LO && Reg1 == AMDGPU::TMA_HI) {
2681 Reg = AMDGPU::TMA;
2682 RegWidth = 64;
2683 return true;
2684 }
2685 Error(Loc, "register does not fit in the list");
2686 return false;
2687 case IS_VGPR:
2688 case IS_SGPR:
2689 case IS_AGPR:
2690 case IS_TTMP:
2691 if (Reg1 != Reg + RegWidth / 32) {
2692 Error(Loc, "registers in a list must have consecutive indices");
2693 return false;
2694 }
2695 RegWidth += 32;
2696 return true;
2697 default:
2698 llvm_unreachable("unexpected register kind");
2699 }
2700}
2701
2702struct RegInfo {
2704 RegisterKind Kind;
2705};
2706
2707static constexpr RegInfo RegularRegisters[] = {
2708 {{"v"}, IS_VGPR}, {{"s"}, IS_SGPR}, {{"ttmp"}, IS_TTMP},
2709 {{"acc"}, IS_AGPR}, {{"a"}, IS_AGPR},
2710};
2711
2712static bool isRegularReg(RegisterKind Kind) {
2713 return Kind == IS_VGPR || Kind == IS_SGPR || Kind == IS_TTMP ||
2714 Kind == IS_AGPR;
2715}
2716
2718 for (const RegInfo &Reg : RegularRegisters)
2719 if (Str.starts_with(Reg.Name))
2720 return &Reg;
2721 return nullptr;
2722}
2723
2724static bool getRegNum(StringRef Str, unsigned &Num) {
2725 return !Str.getAsInteger(10, Num);
2726}
2727
2728bool AMDGPUAsmParser::isRegister(const AsmToken &Token,
2729 const AsmToken &NextToken) const {
2730
2731 // A list of consecutive registers: [s0,s1,s2,s3]
2732 if (Token.is(AsmToken::LBrac))
2733 return true;
2734
2735 if (!Token.is(AsmToken::Identifier))
2736 return false;
2737
2738 // A single register like s0 or a range of registers like s[0:1]
2739
2740 StringRef Str = Token.getString();
2741 const RegInfo *Reg = getRegularRegInfo(Str);
2742 if (Reg) {
2743 StringRef RegName = Reg->Name;
2744 StringRef RegSuffix = Str.substr(RegName.size());
2745 if (!RegSuffix.empty()) {
2746 RegSuffix.consume_back(".l");
2747 RegSuffix.consume_back(".h");
2748 unsigned Num;
2749 // A single register with an index: rXX
2750 if (getRegNum(RegSuffix, Num))
2751 return true;
2752 } else {
2753 // A range of registers: r[XX:YY].
2754 if (NextToken.is(AsmToken::LBrac))
2755 return true;
2756 }
2757 }
2758
2759 return getSpecialRegForName(Str).isValid();
2760}
2761
2762bool AMDGPUAsmParser::isRegister() {
2763 return isRegister(getToken(), peekToken());
2764}
2765
2766MCRegister AMDGPUAsmParser::getRegularReg(RegisterKind RegKind, unsigned RegNum,
2767 unsigned SubReg, unsigned RegWidth,
2768 SMLoc Loc) {
2769 assert(isRegularReg(RegKind));
2770
2771 unsigned AlignSize = 1;
2772 if (RegKind == IS_SGPR || RegKind == IS_TTMP) {
2773 // SGPR and TTMP registers must be aligned.
2774 // Max required alignment is 4 dwords.
2775 AlignSize = std::min(llvm::bit_ceil(RegWidth / 32), 4u);
2776 }
2777
2778 if (RegNum % AlignSize != 0) {
2779 Error(Loc, "invalid register alignment");
2780 return MCRegister();
2781 }
2782
2783 unsigned RegIdx = RegNum / AlignSize;
2784 int RCID = getRegClass(RegKind, RegWidth);
2785 if (RCID == -1) {
2786 Error(Loc, "invalid or unsupported register size");
2787 return MCRegister();
2788 }
2789
2790 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
2791 const MCRegisterClass &RC = TRI->getRegClass(RCID);
2792 if (RegIdx >= RC.getNumRegs() || (RegKind == IS_VGPR && RegIdx > 255)) {
2793 Error(Loc, "register index is out of range");
2794 return AMDGPU::NoRegister;
2795 }
2796
2797 if (RegKind == IS_VGPR && !isGFX1250Plus() && RegIdx + RegWidth / 32 > 256) {
2798 Error(Loc, "register index is out of range");
2799 return MCRegister();
2800 }
2801
2802 MCRegister Reg = RC.getRegister(RegIdx);
2803
2804 if (SubReg) {
2805 Reg = TRI->getSubReg(Reg, SubReg);
2806
2807 if (!Reg)
2808 Error(Loc, "invalid subregister");
2809 }
2810
2811 return Reg;
2812}
2813
2814bool AMDGPUAsmParser::ParseRegRange(unsigned &Num, unsigned &RegWidth,
2815 unsigned &SubReg) {
2816 int64_t RegLo, RegHi;
2817 if (!skipToken(AsmToken::LBrac, "missing register index"))
2818 return false;
2819
2820 SMLoc FirstIdxLoc = getLoc();
2821 SMLoc SecondIdxLoc;
2822
2823 if (!parseExpr(RegLo))
2824 return false;
2825
2826 if (trySkipToken(AsmToken::Colon)) {
2827 SecondIdxLoc = getLoc();
2828 if (!parseExpr(RegHi))
2829 return false;
2830 } else {
2831 RegHi = RegLo;
2832 }
2833
2834 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
2835 return false;
2836
2837 if (!isUInt<32>(RegLo)) {
2838 Error(FirstIdxLoc, "invalid register index");
2839 return false;
2840 }
2841
2842 if (!isUInt<32>(RegHi)) {
2843 Error(SecondIdxLoc, "invalid register index");
2844 return false;
2845 }
2846
2847 if (RegLo > RegHi) {
2848 Error(FirstIdxLoc, "first register index should not exceed second index");
2849 return false;
2850 }
2851
2852 if (RegHi == RegLo) {
2853 StringRef RegSuffix = getTokenStr();
2854 if (RegSuffix == ".l") {
2855 SubReg = AMDGPU::lo16;
2856 lex();
2857 } else if (RegSuffix == ".h") {
2858 SubReg = AMDGPU::hi16;
2859 lex();
2860 }
2861 }
2862
2863 Num = static_cast<unsigned>(RegLo);
2864 RegWidth = 32 * ((RegHi - RegLo) + 1);
2865
2866 return true;
2867}
2868
2869MCRegister AMDGPUAsmParser::ParseSpecialReg(RegisterKind &RegKind,
2870 unsigned &RegNum,
2871 unsigned &RegWidth,
2872 SmallVectorImpl<AsmToken> &Tokens) {
2873 assert(isToken(AsmToken::Identifier));
2874 MCRegister Reg = getSpecialRegForName(getTokenStr());
2875 if (Reg) {
2876 RegNum = 0;
2877 RegWidth = 32;
2878 RegKind = IS_SPECIAL;
2879 Tokens.push_back(getToken());
2880 lex(); // skip register name
2881 }
2882 return Reg;
2883}
2884
2885MCRegister AMDGPUAsmParser::ParseRegularReg(RegisterKind &RegKind,
2886 unsigned &RegNum,
2887 unsigned &RegWidth,
2888 SmallVectorImpl<AsmToken> &Tokens) {
2889 assert(isToken(AsmToken::Identifier));
2890 StringRef RegName = getTokenStr();
2891 auto Loc = getLoc();
2892
2893 const RegInfo *RI = getRegularRegInfo(RegName);
2894 if (!RI) {
2895 Error(Loc, "invalid register name");
2896 return MCRegister();
2897 }
2898
2899 Tokens.push_back(getToken());
2900 lex(); // skip register name
2901
2902 RegKind = RI->Kind;
2903 StringRef RegSuffix = RegName.substr(RI->Name.size());
2904 unsigned SubReg = NoSubRegister;
2905 bool IsRange = false;
2906 if (!RegSuffix.empty()) {
2907 if (RegSuffix.consume_back(".l"))
2908 SubReg = AMDGPU::lo16;
2909 else if (RegSuffix.consume_back(".h"))
2910 SubReg = AMDGPU::hi16;
2911
2912 // Single 32-bit register: vXX.
2913 if (!getRegNum(RegSuffix, RegNum)) {
2914 Error(Loc, "invalid register index");
2915 return MCRegister();
2916 }
2917 RegWidth = 32;
2918 } else {
2919 // Range of registers: v[XX:YY]. ":YY" is optional.
2920 IsRange = true;
2921 if (!ParseRegRange(RegNum, RegWidth, SubReg))
2922 return MCRegister();
2923 }
2924
2925 // Do not allow vcc_lo/hi be referred as s106/107.
2926 MCRegister Reg = getRegularReg(RegKind, RegNum, SubReg, RegWidth, Loc);
2927 const MCRegisterInfo &TRI = *getContext().getRegisterInfo();
2928 if (RegKind == IS_SGPR && IsRange
2929 ? (TRI.isSubRegister(Reg, VCC_LO) || TRI.isSubRegister(Reg, VCC_HI))
2930 : (Reg == VCC_LO || Reg == VCC_HI)) {
2931 Error(Loc, "register index is out of range");
2932 return MCRegister();
2933 }
2934
2935 return Reg;
2936}
2937
2938MCRegister AMDGPUAsmParser::ParseRegList(RegisterKind &RegKind,
2939 unsigned &RegNum, unsigned &RegWidth,
2940 SmallVectorImpl<AsmToken> &Tokens) {
2941 MCRegister Reg;
2942 auto ListLoc = getLoc();
2943
2944 if (!skipToken(AsmToken::LBrac,
2945 "expected a register or a list of registers")) {
2946 return MCRegister();
2947 }
2948
2949 // List of consecutive registers, e.g.: [s0,s1,s2,s3]
2950
2951 auto Loc = getLoc();
2952 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth))
2953 return MCRegister();
2954 if (RegWidth != 32) {
2955 Error(Loc, "expected a single 32-bit register");
2956 return MCRegister();
2957 }
2958
2959 for (; trySkipToken(AsmToken::Comma);) {
2960 RegisterKind NextRegKind;
2961 MCRegister NextReg;
2962 unsigned NextRegNum, NextRegWidth;
2963 Loc = getLoc();
2964
2965 if (!ParseAMDGPURegister(NextRegKind, NextReg, NextRegNum, NextRegWidth,
2966 Tokens)) {
2967 return MCRegister();
2968 }
2969 if (NextRegWidth != 32) {
2970 Error(Loc, "expected a single 32-bit register");
2971 return MCRegister();
2972 }
2973 if (!AddNextRegisterToList(Reg, RegWidth, RegKind, NextReg, NextRegKind,
2974 Loc))
2975 return MCRegister();
2976 }
2977
2978 if (!skipToken(AsmToken::RBrac,
2979 "expected a comma or a closing square bracket")) {
2980 return MCRegister();
2981 }
2982
2983 if (isRegularReg(RegKind))
2984 Reg = getRegularReg(RegKind, RegNum, NoSubRegister, RegWidth, ListLoc);
2985
2986 return Reg;
2987}
2988
2989bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind,
2990 MCRegister &Reg, unsigned &RegNum,
2991 unsigned &RegWidth,
2992 SmallVectorImpl<AsmToken> &Tokens) {
2993 auto Loc = getLoc();
2994 Reg = MCRegister();
2995
2996 if (isToken(AsmToken::Identifier)) {
2997 Reg = ParseSpecialReg(RegKind, RegNum, RegWidth, Tokens);
2998 if (!Reg)
2999 Reg = ParseRegularReg(RegKind, RegNum, RegWidth, Tokens);
3000 } else {
3001 Reg = ParseRegList(RegKind, RegNum, RegWidth, Tokens);
3002 }
3003
3004 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
3005 if (!Reg) {
3006 assert(Parser.hasPendingError());
3007 return false;
3008 }
3009
3010 if (!subtargetHasRegister(*TRI, Reg)) {
3011 if (Reg == AMDGPU::SGPR_NULL) {
3012 Error(Loc, "'null' operand is not supported on this GPU");
3013 } else {
3015 " register not available on this GPU");
3016 }
3017 return false;
3018 }
3019
3020 return true;
3021}
3022
3023bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind,
3024 MCRegister &Reg, unsigned &RegNum,
3025 unsigned &RegWidth,
3026 bool RestoreOnFailure /*=false*/) {
3027 Reg = MCRegister();
3028
3030 if (ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, Tokens)) {
3031 if (RestoreOnFailure) {
3032 while (!Tokens.empty()) {
3033 getLexer().UnLex(Tokens.pop_back_val());
3034 }
3035 }
3036 return true;
3037 }
3038 return false;
3039}
3040
3041std::optional<StringRef>
3042AMDGPUAsmParser::getGprCountSymbolName(RegisterKind RegKind) {
3043 switch (RegKind) {
3044 case IS_VGPR:
3045 return StringRef(".amdgcn.next_free_vgpr");
3046 case IS_SGPR:
3047 return StringRef(".amdgcn.next_free_sgpr");
3048 default:
3049 return std::nullopt;
3050 }
3051}
3052
3053void AMDGPUAsmParser::initializeGprCountSymbol(RegisterKind RegKind) {
3054 auto SymbolName = getGprCountSymbolName(RegKind);
3055 assert(SymbolName && "initializing invalid register kind");
3056 MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
3058 Sym->setRedefinable(true);
3059}
3060
3061bool AMDGPUAsmParser::updateGprCountSymbols(RegisterKind RegKind,
3062 unsigned DwordRegIndex,
3063 unsigned RegWidth) {
3064 // Symbols are only defined for GCN targets
3065 if (ISA.Major < 6)
3066 return true;
3067
3068 auto SymbolName = getGprCountSymbolName(RegKind);
3069 if (!SymbolName)
3070 return true;
3071 MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
3072
3073 int64_t NewMax = DwordRegIndex + divideCeil(RegWidth, 32) - 1;
3074 int64_t OldCount;
3075
3076 if (!Sym->isVariable())
3077 return !Error(getLoc(),
3078 ".amdgcn.next_free_{v,s}gpr symbols must be variable");
3079 if (!Sym->getVariableValue()->evaluateAsAbsolute(OldCount))
3080 return !Error(
3081 getLoc(),
3082 ".amdgcn.next_free_{v,s}gpr symbols must be absolute expressions");
3083
3084 if (OldCount <= NewMax)
3086
3087 return true;
3088}
3089
3090std::unique_ptr<AMDGPUOperand>
3091AMDGPUAsmParser::parseRegister(bool RestoreOnFailure) {
3092 const auto &Tok = getToken();
3093 SMLoc StartLoc = Tok.getLoc();
3094 SMLoc EndLoc = Tok.getEndLoc();
3095 RegisterKind RegKind;
3096 MCRegister Reg;
3097 unsigned RegNum, RegWidth;
3098
3099 if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth)) {
3100 return nullptr;
3101 }
3102 if (isHsaAbi(getSTI())) {
3103 if (!updateGprCountSymbols(RegKind, RegNum, RegWidth))
3104 return nullptr;
3105 } else
3106 KernelScope.usesRegister(RegKind, RegNum, RegWidth);
3107 return AMDGPUOperand::CreateReg(this, Reg, StartLoc, EndLoc);
3108}
3109
3110ParseStatus AMDGPUAsmParser::parseImm(OperandVector &Operands,
3111 bool HasSP3AbsModifier, LitModifier Lit) {
3112 // TODO: add syntactic sugar for 1/(2*PI)
3113
3114 if (isRegister() || isModifier())
3115 return ParseStatus::NoMatch;
3116
3117 if (Lit == LitModifier::None) {
3118 if (trySkipId("lit"))
3119 Lit = LitModifier::Lit;
3120 else if (trySkipId("lit64"))
3121 Lit = LitModifier::Lit64;
3122
3123 if (Lit != LitModifier::None) {
3124 if (!skipToken(AsmToken::LParen, "expected left paren after lit"))
3125 return ParseStatus::Failure;
3126 ParseStatus S = parseImm(Operands, HasSP3AbsModifier, Lit);
3127 if (S.isSuccess() &&
3128 !skipToken(AsmToken::RParen, "expected closing parentheses"))
3129 return ParseStatus::Failure;
3130 return S;
3131 }
3132 }
3133
3134 const auto &Tok = getToken();
3135 const auto &NextTok = peekToken();
3136 bool IsReal = Tok.is(AsmToken::Real);
3137 SMLoc S = getLoc();
3138 bool Negate = false;
3139
3140 if (!IsReal && Tok.is(AsmToken::Minus) && NextTok.is(AsmToken::Real)) {
3141 lex();
3142 IsReal = true;
3143 Negate = true;
3144 }
3145
3146 AMDGPUOperand::Modifiers Mods;
3147 Mods.Lit = Lit;
3148
3149 if (IsReal) {
3150 // Floating-point expressions are not supported.
3151 // Can only allow floating-point literals with an
3152 // optional sign.
3153
3154 StringRef Num = getTokenStr();
3155 lex();
3156
3157 APFloat RealVal(APFloat::IEEEdouble());
3158 auto roundMode = APFloat::rmNearestTiesToEven;
3159 if (errorToBool(RealVal.convertFromString(Num, roundMode).takeError()))
3160 return ParseStatus::Failure;
3161 if (Negate)
3162 RealVal.changeSign();
3163
3164 Operands.push_back(
3165 AMDGPUOperand::CreateImm(this, RealVal.bitcastToAPInt().getZExtValue(),
3166 S, AMDGPUOperand::ImmTyNone, true));
3167 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3168 Op.setModifiers(Mods);
3169
3170 return ParseStatus::Success;
3171
3172 } else {
3173 int64_t IntVal;
3174 const MCExpr *Expr;
3175 SMLoc S = getLoc();
3176
3177 if (HasSP3AbsModifier) {
3178 // This is a workaround for handling expressions
3179 // as arguments of SP3 'abs' modifier, for example:
3180 // |1.0|
3181 // |-1|
3182 // |1+x|
3183 // This syntax is not compatible with syntax of standard
3184 // MC expressions (due to the trailing '|').
3185 SMLoc EndLoc;
3186 if (getParser().parsePrimaryExpr(Expr, EndLoc, nullptr))
3187 return ParseStatus::Failure;
3188 } else {
3189 if (Parser.parseExpression(Expr))
3190 return ParseStatus::Failure;
3191 }
3192
3193 if (Expr->evaluateAsAbsolute(IntVal)) {
3194 if (Lit == LitModifier::Lit && !isInt<32>(IntVal) && !isUInt<32>(IntVal))
3195 return Error(S, "literal value out of range");
3196 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
3197 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3198 Op.setModifiers(Mods);
3199 } else {
3200 if (Lit != LitModifier::None)
3201 return ParseStatus::NoMatch;
3202 Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
3203 }
3204
3205 return ParseStatus::Success;
3206 }
3207
3208 return ParseStatus::NoMatch;
3209}
3210
3211ParseStatus AMDGPUAsmParser::parseReg(OperandVector &Operands) {
3212 if (!isRegister())
3213 return ParseStatus::NoMatch;
3214
3215 if (auto R = parseRegister()) {
3216 assert(R->isReg());
3217 Operands.push_back(std::move(R));
3218 return ParseStatus::Success;
3219 }
3220 return ParseStatus::Failure;
3221}
3222
3223ParseStatus AMDGPUAsmParser::parseRegOrImm(OperandVector &Operands,
3224 bool HasSP3AbsMod, LitModifier Lit) {
3225 ParseStatus Res = parseReg(Operands);
3226 if (!Res.isNoMatch())
3227 return Res;
3228 if (isModifier())
3229 return ParseStatus::NoMatch;
3230 return parseImm(Operands, HasSP3AbsMod, Lit);
3231}
3232
3233bool AMDGPUAsmParser::isNamedOperandModifier(const AsmToken &Token,
3234 const AsmToken &NextToken) const {
3235 if (Token.is(AsmToken::Identifier) && NextToken.is(AsmToken::LParen)) {
3236 const auto &str = Token.getString();
3237 return str == "abs" || str == "neg" || str == "sext";
3238 }
3239 return false;
3240}
3241
3242bool AMDGPUAsmParser::isOpcodeModifierWithVal(const AsmToken &Token,
3243 const AsmToken &NextToken) const {
3244 return Token.is(AsmToken::Identifier) && NextToken.is(AsmToken::Colon);
3245}
3246
3247bool AMDGPUAsmParser::isOperandModifier(const AsmToken &Token,
3248 const AsmToken &NextToken) const {
3249 return isNamedOperandModifier(Token, NextToken) || Token.is(AsmToken::Pipe);
3250}
3251
3252bool AMDGPUAsmParser::isRegOrOperandModifier(const AsmToken &Token,
3253 const AsmToken &NextToken) const {
3254 return isRegister(Token, NextToken) || isOperandModifier(Token, NextToken);
3255}
3256
3257// Check if this is an operand modifier or an opcode modifier
3258// which may look like an expression but it is not. We should
3259// avoid parsing these modifiers as expressions. Currently
3260// recognized sequences are:
3261// |...|
3262// abs(...)
3263// neg(...)
3264// sext(...)
3265// -reg
3266// -|...|
3267// -abs(...)
3268// name:...
3269// "name ::" is the VOPD separator, not an opcode modifier.
3270//
3271bool AMDGPUAsmParser::isModifier() {
3272
3273 AsmToken Tok = getToken();
3274 AsmToken NextToken[2];
3275 peekTokens(NextToken);
3276
3277 // "name:value" is an opcode modifier. The second colon of "::" is the
3278 // VOPD separator, so a symbol written immediately before "::" is a literal.
3279 bool IsOpcodeModifier = isOpcodeModifierWithVal(Tok, NextToken[0]) &&
3280 !NextToken[1].is(AsmToken::Colon);
3281
3282 return isOperandModifier(Tok, NextToken[0]) ||
3283 (Tok.is(AsmToken::Minus) &&
3284 isRegOrOperandModifier(NextToken[0], NextToken[1])) ||
3285 IsOpcodeModifier;
3286}
3287
3288// Check if the current token is an SP3 'neg' modifier.
3289// Currently this modifier is allowed in the following context:
3290//
3291// 1. Before a register, e.g. "-v0", "-v[...]" or "-[v0,v1]".
3292// 2. Before an 'abs' modifier: -abs(...)
3293// 3. Before an SP3 'abs' modifier: -|...|
3294//
3295// In all other cases "-" is handled as a part
3296// of an expression that follows the sign.
3297//
3298// Note: When "-" is followed by an integer literal,
3299// this is interpreted as integer negation rather
3300// than a floating-point NEG modifier applied to N.
3301// Beside being contr-intuitive, such use of floating-point
3302// NEG modifier would have resulted in different meaning
3303// of integer literals used with VOP1/2/C and VOP3,
3304// for example:
3305// v_exp_f32_e32 v5, -1 // VOP1: src0 = 0xFFFFFFFF
3306// v_exp_f32_e64 v5, -1 // VOP3: src0 = 0x80000001
3307// Negative fp literals with preceding "-" are
3308// handled likewise for uniformity
3309//
3310bool AMDGPUAsmParser::parseSP3NegModifier() {
3311
3312 AsmToken NextToken[2];
3313 peekTokens(NextToken);
3314
3315 if (isToken(AsmToken::Minus) &&
3316 (isRegister(NextToken[0], NextToken[1]) ||
3317 NextToken[0].is(AsmToken::Pipe) || isId(NextToken[0], "abs"))) {
3318 lex();
3319 return true;
3320 }
3321
3322 return false;
3323}
3324
3325ParseStatus
3326AMDGPUAsmParser::parseRegOrImmWithFPInputMods(OperandVector &Operands,
3327 bool AllowImm) {
3328 bool Neg, SP3Neg;
3329 bool Abs, SP3Abs;
3330 SMLoc Loc;
3331
3332 // Disable ambiguous constructs like '--1' etc. Should use neg(-1) instead.
3333 if (isToken(AsmToken::Minus) && peekToken().is(AsmToken::Minus))
3334 return Error(getLoc(), "invalid syntax, expected 'neg' modifier");
3335
3336 SP3Neg = parseSP3NegModifier();
3337
3338 Loc = getLoc();
3339 Neg = trySkipId("neg");
3340 if (Neg && SP3Neg)
3341 return Error(Loc, "expected register or immediate");
3342 if (Neg && !skipToken(AsmToken::LParen, "expected left paren after neg"))
3343 return ParseStatus::Failure;
3344
3345 Abs = trySkipId("abs");
3346 if (Abs && !skipToken(AsmToken::LParen, "expected left paren after abs"))
3347 return ParseStatus::Failure;
3348
3349 LitModifier Lit = LitModifier::None;
3350 if (trySkipId("lit")) {
3351 Lit = LitModifier::Lit;
3352 if (!skipToken(AsmToken::LParen, "expected left paren after lit"))
3353 return ParseStatus::Failure;
3354 } else if (trySkipId("lit64")) {
3355 Lit = LitModifier::Lit64;
3356 if (!skipToken(AsmToken::LParen, "expected left paren after lit64"))
3357 return ParseStatus::Failure;
3358 if (!has64BitLiterals())
3359 return Error(Loc, "lit64 is not supported on this GPU");
3360 }
3361
3362 Loc = getLoc();
3363 SP3Abs = trySkipToken(AsmToken::Pipe);
3364 if (Abs && SP3Abs)
3365 return Error(Loc, "expected register or immediate");
3366
3367 ParseStatus Res;
3368 if (AllowImm) {
3369 Res = parseRegOrImm(Operands, SP3Abs, Lit);
3370 } else {
3371 Res = parseReg(Operands);
3372 }
3373 if (!Res.isSuccess())
3374 return (SP3Neg || Neg || SP3Abs || Abs || Lit != LitModifier::None)
3376 : Res;
3377
3378 if (Lit != LitModifier::None && !Operands.back()->isImm())
3379 Error(Loc, "expected immediate with lit modifier");
3380
3381 if (SP3Abs && !skipToken(AsmToken::Pipe, "expected vertical bar"))
3382 return ParseStatus::Failure;
3383 if (Abs && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3384 return ParseStatus::Failure;
3385 if (Neg && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3386 return ParseStatus::Failure;
3387 if (Lit != LitModifier::None &&
3388 !skipToken(AsmToken::RParen, "expected closing parentheses"))
3389 return ParseStatus::Failure;
3390
3391 AMDGPUOperand::Modifiers Mods;
3392 Mods.Abs = Abs || SP3Abs;
3393 Mods.Neg = Neg || SP3Neg;
3394 Mods.Lit = Lit;
3395
3396 if (Mods.hasFPModifiers() || Lit != LitModifier::None) {
3397 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3398 if (Op.isExpr())
3399 return Error(Op.getStartLoc(), "expected an absolute expression");
3400 Op.setModifiers(Mods);
3401 }
3402 return ParseStatus::Success;
3403}
3404
3405ParseStatus
3406AMDGPUAsmParser::parseRegOrImmWithIntInputMods(OperandVector &Operands,
3407 bool AllowImm) {
3408 bool Sext = trySkipId("sext");
3409 if (Sext && !skipToken(AsmToken::LParen, "expected left paren after sext"))
3410 return ParseStatus::Failure;
3411
3412 ParseStatus Res;
3413 if (AllowImm) {
3414 Res = parseRegOrImm(Operands);
3415 } else {
3416 Res = parseReg(Operands);
3417 }
3418 if (!Res.isSuccess())
3419 return Sext ? ParseStatus::Failure : Res;
3420
3421 if (Sext && !skipToken(AsmToken::RParen, "expected closing parentheses"))
3422 return ParseStatus::Failure;
3423
3424 AMDGPUOperand::Modifiers Mods;
3425 Mods.Sext = Sext;
3426
3427 if (Mods.hasIntModifiers()) {
3428 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
3429 if (Op.isExpr())
3430 return Error(Op.getStartLoc(), "expected an absolute expression");
3431 Op.setModifiers(Mods);
3432 }
3433
3434 return ParseStatus::Success;
3435}
3436
3437ParseStatus AMDGPUAsmParser::parseRegWithFPInputMods(OperandVector &Operands) {
3438 return parseRegOrImmWithFPInputMods(Operands, false);
3439}
3440
3441ParseStatus AMDGPUAsmParser::parseRegWithIntInputMods(OperandVector &Operands) {
3442 return parseRegOrImmWithIntInputMods(Operands, false);
3443}
3444
3445ParseStatus AMDGPUAsmParser::parseRsrcReg(OperandVector &Operands) {
3446 // Without the marker, fall back to plain register parsing so the legacy
3447 // bare-register form (e.g. `s8`, `v8`) still assembles for indexed
3448 // buffer/image instructions.
3449 if (!trySkipId("rsrcidx"))
3450 return parseReg(Operands);
3451
3452 if (!skipToken(AsmToken::LParen, "expected left paren after rsrcidx"))
3453 return ParseStatus::Failure;
3454
3455 SMLoc RegLoc = getLoc();
3456 std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
3457 if (!Reg)
3458 return ParseStatus::Failure;
3459
3460 // Enforce that the inner register is a valid index register. The matcher
3461 // predicate alone is not sufficient: if it fails, the matcher will fall back
3462 // to a non-indexed instruction variant whose resource operand happens to
3463 // accept the same register, silently dropping the `rsrcidx` intent.
3464 if (!Reg->isRsrcReg32())
3465 return Error(RegLoc, "rsrcidx operand must be a 32-bit SGPR or VGPR");
3466
3467 if (!skipToken(AsmToken::RParen, "expected closing parenthesis"))
3468 return ParseStatus::Failure;
3469
3470 Operands.push_back(std::move(Reg));
3471 return ParseStatus::Success;
3472}
3473
3474ParseStatus AMDGPUAsmParser::parseVReg32OrOff(OperandVector &Operands) {
3475 auto Loc = getLoc();
3476 if (trySkipId("off")) {
3477 Operands.push_back(
3478 AMDGPUOperand::CreateImm(this, 0, Loc, AMDGPUOperand::ImmTyOff, false));
3479 return ParseStatus::Success;
3480 }
3481
3482 if (!isRegister())
3483 return ParseStatus::NoMatch;
3484
3485 std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
3486 if (Reg) {
3487 Operands.push_back(std::move(Reg));
3488 return ParseStatus::Success;
3489 }
3490
3491 return ParseStatus::Failure;
3492}
3493
3494unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3495 if ((getForcedEncodingSize() == 32 && SIInstrFlags::isVOP3(MII, Inst)) ||
3496 (getForcedEncodingSize() == 64 && !SIInstrFlags::isVOP3(MII, Inst)) ||
3497 (isForcedDPP() && !SIInstrFlags::isDPP(MII, Inst)) ||
3498 (isForcedSDWA() && !SIInstrFlags::isSDWA(MII, Inst)))
3499 return Match_InvalidOperand;
3500
3501 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
3502 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
3503 // v_mac_f32/16 allow only dst_sel == DWORD;
3504 auto OpNum =
3505 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::dst_sel);
3506 const auto &Op = Inst.getOperand(OpNum);
3507 if (!Op.isImm() || Op.getImm() != AMDGPU::SDWA::SdwaSel::DWORD) {
3508 return Match_InvalidOperand;
3509 }
3510 }
3511
3512 // Asm can first try to match VOPD or VOPD3. By failing early here with
3513 // Match_InvalidOperand, the parser will retry parsing as VOPD3 or VOPD.
3514 // Checking later during validateInstruction does not give a chance to retry
3515 // parsing as a different encoding.
3516 if (tryAnotherVOPDEncoding(Inst))
3517 return Match_InvalidOperand;
3518
3519 return Match_Success;
3520}
3521
3530
3531// What asm variants we should check
3532ArrayRef<unsigned> AMDGPUAsmParser::getMatchedVariants() const {
3533 if (isForcedDPP() && isForcedVOP3()) {
3534 static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3_DPP};
3535 return ArrayRef(Variants);
3536 }
3537 if (getForcedEncodingSize() == 32) {
3538 static const unsigned Variants[] = {AMDGPUAsmVariants::DEFAULT};
3539 return ArrayRef(Variants);
3540 }
3541
3542 if (isForcedVOP3()) {
3543 static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3};
3544 return ArrayRef(Variants);
3545 }
3546
3547 if (isForcedSDWA()) {
3548 static const unsigned Variants[] = {AMDGPUAsmVariants::SDWA,
3550 return ArrayRef(Variants);
3551 }
3552
3553 if (isForcedDPP()) {
3554 static const unsigned Variants[] = {AMDGPUAsmVariants::DPP};
3555 return ArrayRef(Variants);
3556 }
3557
3558 return getAllVariants();
3559}
3560
3561StringRef AMDGPUAsmParser::getMatchedVariantName() const {
3562 if (isForcedDPP() && isForcedVOP3())
3563 return "e64_dpp";
3564
3565 if (getForcedEncodingSize() == 32)
3566 return "e32";
3567
3568 if (isForcedVOP3())
3569 return "e64";
3570
3571 if (isForcedSDWA())
3572 return "sdwa";
3573
3574 if (isForcedDPP())
3575 return "dpp";
3576
3577 return "";
3578}
3579
3580MCRegister
3581AMDGPUAsmParser::findImplicitSGPRReadInVOP(const MCInst &Inst) const {
3582 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3583 for (MCPhysReg Reg : Desc.implicit_uses()) {
3584 switch (Reg) {
3585 case AMDGPU::FLAT_SCR:
3586 case AMDGPU::VCC:
3587 case AMDGPU::VCC_LO:
3588 case AMDGPU::VCC_HI:
3589 case AMDGPU::M0:
3590 return Reg;
3591 default:
3592 break;
3593 }
3594 }
3595 return MCRegister();
3596}
3597
3598// NB: This code is correct only when used to check constant
3599// bus limitations because GFX7 support no f16 inline constants.
3600// Note that there are no cases when a GFX7 opcode violates
3601// constant bus limitations due to the use of an f16 constant.
3602bool AMDGPUAsmParser::isInlineConstant(const MCInst &Inst,
3603 unsigned OpIdx) const {
3604 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
3605
3606 if (!AMDGPU::isSISrcOperand(Desc, OpIdx) ||
3607 AMDGPU::isKImmOperand(Desc, OpIdx)) {
3608 return false;
3609 }
3610
3611 const MCOperand &MO = Inst.getOperand(OpIdx);
3612
3613 int64_t Val = MO.isImm() ? MO.getImm() : getLitValue(MO.getExpr());
3614 auto OpSize = AMDGPU::getOperandSize(Desc, OpIdx);
3615
3616 switch (OpSize) { // expected operand size
3617 case 8:
3618 return AMDGPU::isInlinableLiteral64(Val, hasInv2PiInlineImm());
3619 case 4:
3620 return AMDGPU::isInlinableLiteral32(Val, hasInv2PiInlineImm());
3621 case 2: {
3622 const unsigned OperandType = Desc.operands()[OpIdx].OperandType;
3625 return AMDGPU::isInlinableLiteralI16(Val, hasInv2PiInlineImm());
3626
3630
3634
3637
3641
3644 return AMDGPU::isInlinableLiteralFP16(Val, hasInv2PiInlineImm());
3645
3648 return AMDGPU::isInlinableLiteralBF16(Val, hasInv2PiInlineImm());
3649
3652 return false;
3653
3654 llvm_unreachable("invalid operand type");
3655 }
3656 default:
3657 llvm_unreachable("invalid operand size");
3658 }
3659}
3660
3661unsigned AMDGPUAsmParser::getConstantBusLimit(unsigned Opcode) const {
3662 if (!isGFX10Plus())
3663 return 1;
3664
3665 switch (Opcode) {
3666 // 64-bit shift instructions can use only one scalar value input
3667 case AMDGPU::V_LSHLREV_B64_e64:
3668 case AMDGPU::V_LSHLREV_B64_gfx10:
3669 case AMDGPU::V_LSHLREV_B64_e64_gfx11:
3670 case AMDGPU::V_LSHLREV_B64_e32_gfx12:
3671 case AMDGPU::V_LSHLREV_B64_e64_gfx12:
3672 case AMDGPU::V_LSHRREV_B64_e64:
3673 case AMDGPU::V_LSHRREV_B64_gfx10:
3674 case AMDGPU::V_LSHRREV_B64_e64_gfx11:
3675 case AMDGPU::V_LSHRREV_B64_e64_gfx12:
3676 case AMDGPU::V_ASHRREV_I64_e64:
3677 case AMDGPU::V_ASHRREV_I64_gfx10:
3678 case AMDGPU::V_ASHRREV_I64_e64_gfx11:
3679 case AMDGPU::V_ASHRREV_I64_e64_gfx12:
3680 case AMDGPU::V_LSHL_B64_e64:
3681 case AMDGPU::V_LSHR_B64_e64:
3682 case AMDGPU::V_ASHR_I64_e64:
3683 return 1;
3684 default:
3685 return 2;
3686 }
3687}
3688
3689constexpr unsigned MAX_SRC_OPERANDS_NUM = 6;
3691
3692// Get regular operand indices in the same order as specified
3693// in the instruction (but append mandatory literals to the end).
3695 bool AddMandatoryLiterals = false) {
3696
3697 int16_t ImmIdx =
3698 AddMandatoryLiterals ? getNamedOperandIdx(Opcode, OpName::imm) : -1;
3699
3700 if (isVOPD(Opcode)) {
3701 int16_t ImmXIdx =
3702 AddMandatoryLiterals ? getNamedOperandIdx(Opcode, OpName::immX) : -1;
3703
3704 return {getNamedOperandIdx(Opcode, OpName::src0X),
3705 getNamedOperandIdx(Opcode, OpName::vsrc1X),
3706 getNamedOperandIdx(Opcode, OpName::vsrc2X),
3707 getNamedOperandIdx(Opcode, OpName::src0Y),
3708 getNamedOperandIdx(Opcode, OpName::vsrc1Y),
3709 getNamedOperandIdx(Opcode, OpName::vsrc2Y),
3710 ImmXIdx,
3711 ImmIdx};
3712 }
3713
3714 return {getNamedOperandIdx(Opcode, OpName::src0),
3715 getNamedOperandIdx(Opcode, OpName::src1),
3716 getNamedOperandIdx(Opcode, OpName::src2), ImmIdx};
3717}
3718
3719bool AMDGPUAsmParser::usesConstantBus(const MCInst &Inst, unsigned OpIdx) {
3720 const MCOperand &MO = Inst.getOperand(OpIdx);
3721 if (MO.isImm())
3722 return !isInlineConstant(Inst, OpIdx);
3723 if (MO.isReg()) {
3724 auto Reg = MO.getReg();
3725 if (!Reg)
3726 return false;
3727 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
3728 auto PReg = mc2PseudoReg(Reg);
3729 return isSGPR(PReg, TRI) && PReg != SGPR_NULL;
3730 }
3731 return true;
3732}
3733
3734// Based on the comment for `AMDGPUInstructionSelector::selectWritelane`:
3735// Writelane is special in that it can use SGPR and M0 (which would normally
3736// count as using the constant bus twice - but in this case it is allowed since
3737// the lane selector doesn't count as a use of the constant bus). However, it is
3738// still required to abide by the 1 SGPR rule.
3739static bool checkWriteLane(const MCInst &Inst) {
3740 const unsigned Opcode = Inst.getOpcode();
3741 if (Opcode != V_WRITELANE_B32_gfx6_gfx7 && Opcode != V_WRITELANE_B32_vi)
3742 return false;
3743 const MCOperand &LaneSelOp = Inst.getOperand(2);
3744 if (!LaneSelOp.isReg())
3745 return false;
3746 auto LaneSelReg = mc2PseudoReg(LaneSelOp.getReg());
3747 return LaneSelReg == M0 || LaneSelReg == M0_gfxpre11;
3748}
3749
3750bool AMDGPUAsmParser::validateConstantBusLimitations(
3751 const MCInst &Inst, const OperandVector &Operands) {
3752 const unsigned Opcode = Inst.getOpcode();
3753 const MCInstrDesc &Desc = MII.get(Opcode);
3754 MCRegister LastSGPR;
3755 unsigned ConstantBusUseCount = 0;
3756 unsigned NumLiterals = 0;
3757 unsigned LiteralSize;
3758
3761 !SIInstrFlags::isSDWA(Desc) && !isVOPD(Opcode))
3762 return true;
3763
3764 if (checkWriteLane(Inst))
3765 return true;
3766
3767 // Check special imm operands (used by madmk, etc)
3768 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::imm)) {
3769 ++NumLiterals;
3770 LiteralSize = 4;
3771 }
3772
3773 SmallDenseSet<MCRegister> SGPRsUsed;
3774 MCRegister SGPRUsed = findImplicitSGPRReadInVOP(Inst);
3775 if (SGPRUsed) {
3776 SGPRsUsed.insert(SGPRUsed);
3777 ++ConstantBusUseCount;
3778 }
3779
3780 OperandIndices OpIndices = getSrcOperandIndices(Opcode);
3781
3782 unsigned ConstantBusLimit = getConstantBusLimit(Opcode);
3783
3784 for (int OpIdx : OpIndices) {
3785 if (OpIdx == -1)
3786 continue;
3787
3788 const MCOperand &MO = Inst.getOperand(OpIdx);
3789 if (usesConstantBus(Inst, OpIdx)) {
3790 if (MO.isReg()) {
3791 LastSGPR = mc2PseudoReg(MO.getReg());
3792 // Pairs of registers with a partial intersections like these
3793 // s0, s[0:1]
3794 // flat_scratch_lo, flat_scratch
3795 // flat_scratch_lo, flat_scratch_hi
3796 // are theoretically valid but they are disabled anyway.
3797 // Note that this code mimics SIInstrInfo::verifyInstruction
3798 if (SGPRsUsed.insert(LastSGPR).second) {
3799 ++ConstantBusUseCount;
3800 }
3801 } else { // Expression or a literal
3802
3803 if (Desc.operands()[OpIdx].OperandType == MCOI::OPERAND_IMMEDIATE)
3804 continue; // special operand like VINTERP attr_chan
3805
3806 // An instruction may use only one literal.
3807 // This has been validated on the previous step.
3808 // See validateVOPLiteral.
3809 // This literal may be used as more than one operand.
3810 // If all these operands are of the same size,
3811 // this literal counts as one scalar value.
3812 // Otherwise it counts as 2 scalar values.
3813 // See "GFX10 Shader Programming", section 3.6.2.3.
3814
3815 unsigned Size = AMDGPU::getOperandSize(Desc, OpIdx);
3816 if (Size < 4)
3817 Size = 4;
3818
3819 if (NumLiterals == 0) {
3820 NumLiterals = 1;
3821 LiteralSize = Size;
3822 } else if (LiteralSize != Size) {
3823 NumLiterals = 2;
3824 }
3825 }
3826 }
3827
3828 if (ConstantBusUseCount + NumLiterals > ConstantBusLimit) {
3829 Error(getOperandLoc(Operands, OpIdx),
3830 "invalid operand (violates constant bus restrictions)");
3831 return false;
3832 }
3833 }
3834 return true;
3835}
3836
3837std::optional<unsigned>
3838AMDGPUAsmParser::checkVOPDRegBankConstraints(const MCInst &Inst, bool AsVOPD3) {
3839
3840 const unsigned Opcode = Inst.getOpcode();
3841 if (!isVOPD(Opcode))
3842 return {};
3843
3844 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
3845
3846 auto getVRegIdx = [&](unsigned, unsigned OperandIdx) {
3847 const MCOperand &Opr = Inst.getOperand(OperandIdx);
3848 return (Opr.isReg() && !isSGPR(mc2PseudoReg(Opr.getReg()), TRI))
3849 ? Opr.getReg()
3850 : MCRegister();
3851 };
3852
3853 // On GFX1170+ if both OpX and OpY are V_MOV_B32 then OPY uses SRC2
3854 // source-cache.
3855 bool SkipSrc =
3856 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx1170 ||
3857 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx12 ||
3858 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx1250 ||
3859 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_gfx13 ||
3860 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_e96_gfx1250 ||
3861 Opcode == AMDGPU::V_DUAL_MOV_B32_e32_X_MOV_B32_e32_e96_gfx13;
3862 bool AllowSameVGPR = isGFX12Plus();
3863
3864 if (AsVOPD3) { // Literal constants are not allowed with VOPD3.
3865 for (auto OpName : {OpName::src0X, OpName::src0Y}) {
3866 int I = getNamedOperandIdx(Opcode, OpName);
3867 const MCOperand &Op = Inst.getOperand(I);
3868 if (!Op.isImm())
3869 continue;
3870 int64_t Imm = Op.getImm();
3871 if (!AMDGPU::isInlinableLiteral32(Imm, hasInv2PiInlineImm()) &&
3872 !AMDGPU::isInlinableLiteral64(Imm, hasInv2PiInlineImm()))
3873 return (unsigned)I;
3874 }
3875
3876 for (auto OpName : {OpName::vsrc1X, OpName::vsrc1Y, OpName::vsrc2X,
3877 OpName::vsrc2Y, OpName::imm}) {
3878 int I = getNamedOperandIdx(Opcode, OpName);
3879 if (I == -1)
3880 continue;
3881 const MCOperand &Op = Inst.getOperand(I);
3882 if (Op.isImm())
3883 return (unsigned)I;
3884 }
3885 }
3886
3887 const auto &InstInfo = getVOPDInstInfo(Opcode, &MII);
3888 auto InvalidCompOprIdx = InstInfo.getInvalidCompOperandIndex(
3889 getVRegIdx, *TRI, SkipSrc, AllowSameVGPR, AsVOPD3);
3890
3891 return InvalidCompOprIdx;
3892}
3893
3894bool AMDGPUAsmParser::validateVOPD(const MCInst &Inst,
3895 const OperandVector &Operands) {
3896
3897 unsigned Opcode = Inst.getOpcode();
3898 bool AsVOPD3 = SIInstrFlags::isVOPD3(MII, Inst);
3899
3900 if (AsVOPD3) {
3901 for (const std::unique_ptr<MCParsedAsmOperand> &Operand : Operands) {
3902 AMDGPUOperand &Op = (AMDGPUOperand &)*Operand;
3903 if ((Op.isRegKind() || Op.isImmTy(AMDGPUOperand::ImmTyNone)) &&
3904 (Op.getModifiers().getFPModifiersOperand() & SISrcMods::ABS))
3905 Error(Op.getStartLoc(), "ABS not allowed in VOPD3 instructions");
3906 }
3907 }
3908
3909 auto InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, AsVOPD3);
3910 if (!InvalidCompOprIdx.has_value())
3911 return true;
3912
3913 auto CompOprIdx = *InvalidCompOprIdx;
3914 const auto &InstInfo = getVOPDInstInfo(Opcode, &MII);
3915 auto ParsedIdx =
3916 std::max(InstInfo[VOPD::X].getIndexInParsedOperands(CompOprIdx),
3917 InstInfo[VOPD::Y].getIndexInParsedOperands(CompOprIdx));
3918 assert(ParsedIdx > 0 && ParsedIdx < Operands.size());
3919
3920 auto Loc = ((AMDGPUOperand &)*Operands[ParsedIdx]).getStartLoc();
3921 if (CompOprIdx == VOPD::Component::DST) {
3922 if (AsVOPD3)
3923 Error(Loc, "dst registers must be distinct");
3924 else
3925 Error(Loc, "one dst register must be even and the other odd");
3926 } else {
3927 auto CompSrcIdx = CompOprIdx - VOPD::Component::DST_NUM;
3928 Error(Loc, Twine("src") + Twine(CompSrcIdx) +
3929 " operands must use different VGPR banks");
3930 }
3931
3932 return false;
3933}
3934
3935// \returns true if \p Inst does not satisfy VOPD constraints, but can be
3936// potentially used as VOPD3 with the same operands.
3937bool AMDGPUAsmParser::tryVOPD3(const MCInst &Inst) {
3938 // First check if it fits VOPD
3939 auto InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, false);
3940 if (!InvalidCompOprIdx.has_value())
3941 return false;
3942
3943 // Then if it fits VOPD3
3944 InvalidCompOprIdx = checkVOPDRegBankConstraints(Inst, true);
3945 if (InvalidCompOprIdx.has_value()) {
3946 // If failed operand is dst it is better to show error about VOPD3
3947 // instruction as it has more capabilities and error message will be
3948 // more informative. If the dst is not legal for VOPD3, then it is not
3949 // legal for VOPD either.
3950 if (*InvalidCompOprIdx == VOPD::Component::DST)
3951 return true;
3952
3953 // Otherwise prefer VOPD as we may find ourselves in an awkward situation
3954 // with a conflict in tied implicit src2 of fmac and no asm operand to
3955 // to point to.
3956 return false;
3957 }
3958 return true;
3959}
3960
3961// \returns true is a VOPD3 instruction can be also represented as a shorter
3962// VOPD encoding.
3963bool AMDGPUAsmParser::tryVOPD(const MCInst &Inst) {
3964 const unsigned Opcode = Inst.getOpcode();
3965 const auto &II = getVOPDInstInfo(Opcode, &MII);
3966 unsigned EncodingFamily = AMDGPU::getVOPDEncodingFamily(getSTI());
3967 if (!getCanBeVOPD(II[VOPD::X].getOpcode(), EncodingFamily, false).X ||
3968 !getCanBeVOPD(II[VOPD::Y].getOpcode(), EncodingFamily, false).Y)
3969 return false;
3970
3971 // This is an awkward exception, VOPD3 variant of V_DUAL_CNDMASK_B32 has
3972 // explicit src2 even if it is vcc_lo. If it was parsed as VOPD3 it cannot
3973 // be parsed as VOPD which does not accept src2.
3974 if (II[VOPD::X].getOpcode() == AMDGPU::V_CNDMASK_B32_e32 ||
3975 II[VOPD::Y].getOpcode() == AMDGPU::V_CNDMASK_B32_e32)
3976 return false;
3977
3978 // If any modifiers are set this cannot be VOPD.
3979 for (auto OpName : {OpName::src0X_modifiers, OpName::src0Y_modifiers,
3980 OpName::vsrc1X_modifiers, OpName::vsrc1Y_modifiers,
3981 OpName::vsrc2X_modifiers, OpName::vsrc2Y_modifiers}) {
3982 int I = getNamedOperandIdx(Opcode, OpName);
3983 if (I == -1)
3984 continue;
3985 if (Inst.getOperand(I).getImm())
3986 return false;
3987 }
3988
3989 return !tryVOPD3(Inst);
3990}
3991
3992// VOPD3 has more relaxed register constraints than VOPD. We prefer shorter VOPD
3993// form but switch to VOPD3 otherwise.
3994bool AMDGPUAsmParser::tryAnotherVOPDEncoding(const MCInst &Inst) {
3995 if (!isGFX1250Plus() || !isVOPD(Inst.getOpcode()))
3996 return false;
3997
3998 if (SIInstrFlags::isVOPD3(MII, Inst))
3999 return tryVOPD(Inst);
4000 return tryVOPD3(Inst);
4001}
4002
4003bool AMDGPUAsmParser::validateIntClampSupported(const MCInst &Inst) {
4004
4005 const unsigned Opc = Inst.getOpcode();
4006
4007 if (SIInstrFlags::hasIntClamp(MII, Inst) && !hasIntClamp()) {
4008 int ClampIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp);
4009 assert(ClampIdx != -1);
4010 return Inst.getOperand(ClampIdx).getImm() == 0;
4011 }
4012
4013 return true;
4014}
4015
4016bool AMDGPUAsmParser::validateMIMGDataSize(const MCInst &Inst, SMLoc IDLoc) {
4017
4018 const unsigned Opc = Inst.getOpcode();
4019 const MCInstrDesc &Desc = MII.get(Opc);
4020
4021 if ((SIInstrFlags::isImage(Desc)) == 0)
4022 return true;
4023
4024 int VDataIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
4025 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4026 int TFEIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::tfe);
4027
4028 if (VDataIdx == -1 && isGFX10Plus()) // no return image_sample
4029 return true;
4030
4031 if ((DMaskIdx == -1 || TFEIdx == -1) &&
4032 hasBVHRayTracingInsts()) // intersect_ray
4033 return true;
4034
4035 unsigned VDataSize = getRegOperandSize(Desc, VDataIdx);
4036 unsigned TFESize = (TFEIdx != -1 && Inst.getOperand(TFEIdx).getImm()) ? 1 : 0;
4037 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4038 if (DMask == 0)
4039 DMask = 1;
4040
4041 bool IsPackedD16 = false;
4042 unsigned DataSize = SIInstrFlags::isGather4(Desc) ? 4 : llvm::popcount(DMask);
4043 if (hasPackedD16()) {
4044 int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
4045 IsPackedD16 = D16Idx >= 0;
4046 if (IsPackedD16 && Inst.getOperand(D16Idx).getImm())
4047 DataSize = (DataSize + 1) / 2;
4048 }
4049
4050 if ((VDataSize / 4) == DataSize + TFESize)
4051 return true;
4052
4053 StringRef Modifiers;
4054 if (isGFX90A())
4055 Modifiers = IsPackedD16 ? "dmask and d16" : "dmask";
4056 else
4057 Modifiers = IsPackedD16 ? "dmask, d16 and tfe" : "dmask and tfe";
4058
4059 Error(IDLoc, Twine("image data size does not match ") + Modifiers);
4060 return false;
4061}
4062
4063bool AMDGPUAsmParser::validateMIMGAddrSize(const MCInst &Inst, SMLoc IDLoc) {
4064 const unsigned Opc = Inst.getOpcode();
4065 const MCInstrDesc &Desc = MII.get(Opc);
4066
4068 return true;
4069
4070 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
4071
4072 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4074 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
4075 AMDGPU::OpName RSrcOpName =
4076 SIInstrFlags::isMIMG(Desc) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
4077 int SrsrcIdx = AMDGPU::getNamedOperandIdx(Opc, RSrcOpName);
4078 int DimIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dim);
4079 int A16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::a16);
4080
4081 assert(VAddr0Idx != -1);
4082 assert(SrsrcIdx != -1);
4083 assert(SrsrcIdx > VAddr0Idx);
4084
4085 bool IsA16 = (A16Idx != -1 && Inst.getOperand(A16Idx).getImm());
4086 if (BaseOpcode->BVH) {
4087 if (IsA16 == BaseOpcode->A16)
4088 return true;
4089 Error(IDLoc, "image address size does not match a16");
4090 return false;
4091 }
4092
4093 unsigned Dim = Inst.getOperand(DimIdx).getImm();
4094 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByEncoding(Dim);
4095 bool IsNSA = SrsrcIdx - VAddr0Idx > 1;
4096 unsigned ActualAddrSize =
4097 IsNSA ? SrsrcIdx - VAddr0Idx : getRegOperandSize(Desc, VAddr0Idx) / 4;
4098
4099 unsigned ExpectedAddrSize =
4100 AMDGPU::getAddrSizeMIMGOp(BaseOpcode, DimInfo, IsA16, hasG16());
4101
4102 if (IsNSA) {
4103 if (hasPartialNSAEncoding() &&
4104 ExpectedAddrSize > getNSAMaxSize(SIInstrFlags::isVSAMPLE(Desc))) {
4105 int VAddrLastIdx = SrsrcIdx - 1;
4106 unsigned VAddrLastSize = getRegOperandSize(Desc, VAddrLastIdx) / 4;
4107
4108 ActualAddrSize = VAddrLastIdx - VAddr0Idx + VAddrLastSize;
4109 }
4110 } else {
4111 if (ExpectedAddrSize > 12)
4112 ExpectedAddrSize = 16;
4113
4114 // Allow oversized 8 VGPR vaddr when only 5/6/7 VGPRs are required.
4115 // This provides backward compatibility for assembly created
4116 // before 160b/192b/224b types were directly supported.
4117 if (ActualAddrSize == 8 && (ExpectedAddrSize >= 5 && ExpectedAddrSize <= 7))
4118 return true;
4119 }
4120
4121 if (ActualAddrSize == ExpectedAddrSize)
4122 return true;
4123
4124 Error(IDLoc, "image address size does not match dim and a16");
4125 return false;
4126}
4127
4128bool AMDGPUAsmParser::validateMIMGAtomicDMask(const MCInst &Inst) {
4129
4130 const unsigned Opc = Inst.getOpcode();
4131 const MCInstrDesc &Desc = MII.get(Opc);
4132
4133 if ((SIInstrFlags::isImage(Desc)) == 0)
4134 return true;
4135 if (!Desc.mayLoad() || !Desc.mayStore())
4136 return true; // Not atomic
4137
4138 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4139 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4140
4141 // This is an incomplete check because image_atomic_cmpswap
4142 // may only use 0x3 and 0xf while other atomic operations
4143 // may use 0x1 and 0x3. However these limitations are
4144 // verified when we check that dmask matches dst size.
4145 return DMask == 0x1 || DMask == 0x3 || DMask == 0xf;
4146}
4147
4148bool AMDGPUAsmParser::validateMIMGGatherDMask(const MCInst &Inst) {
4149
4150 const unsigned Opc = Inst.getOpcode();
4151
4152 if (!SIInstrFlags::isGather4(MII, Inst))
4153 return true;
4154
4155 int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
4156 unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
4157
4158 // GATHER4 instructions use dmask in a different fashion compared to
4159 // other MIMG instructions. The only useful DMASK values are
4160 // 1=red, 2=green, 4=blue, 8=alpha. (e.g. 1 returns
4161 // (red,red,red,red) etc.) The ISA document doesn't mention
4162 // this.
4163 return DMask == 0x1 || DMask == 0x2 || DMask == 0x4 || DMask == 0x8;
4164}
4165
4166bool AMDGPUAsmParser::validateMIMGDim(const MCInst &Inst,
4167 const OperandVector &Operands) {
4168 if (!isGFX10Plus())
4169 return true;
4170
4171 const unsigned Opc = Inst.getOpcode();
4172
4173 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4174 return true;
4175
4176 // image_bvh_intersect_ray instructions do not have dim
4178 return true;
4179
4180 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
4181 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4182 if (Op.isDim())
4183 return true;
4184 }
4185 return false;
4186}
4187
4188bool AMDGPUAsmParser::validateMIMGMSAA(const MCInst &Inst) {
4189 const unsigned Opc = Inst.getOpcode();
4190
4191 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4192 return true;
4193
4194 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
4195 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4197
4198 if (!BaseOpcode->MSAA)
4199 return true;
4200
4201 int DimIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dim);
4202 assert(DimIdx != -1);
4203
4204 unsigned Dim = Inst.getOperand(DimIdx).getImm();
4205 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByEncoding(Dim);
4206
4207 return DimInfo->MSAA;
4208}
4209
4210static bool IsMovrelsSDWAOpcode(const unsigned Opcode) {
4211 switch (Opcode) {
4212 case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
4213 case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
4214 case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
4215 return true;
4216 default:
4217 return false;
4218 }
4219}
4220
4221// movrels* opcodes should only allow VGPRS as src0.
4222// This is specified in .td description for vop1/vop3,
4223// but sdwa is handled differently. See isSDWAOperand.
4224bool AMDGPUAsmParser::validateMovrels(const MCInst &Inst,
4225 const OperandVector &Operands) {
4226
4227 const unsigned Opc = Inst.getOpcode();
4228
4229 if (!SIInstrFlags::isSDWA(MII, Inst) || !IsMovrelsSDWAOpcode(Opc))
4230 return true;
4231
4232 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4233 assert(Src0Idx != -1);
4234
4235 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4236 if (Src0.isReg()) {
4237 auto Reg = mc2PseudoReg(Src0.getReg());
4238 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4239 if (!isSGPR(Reg, TRI))
4240 return true;
4241 }
4242
4243 Error(getOperandLoc(Operands, Src0Idx), "source operand must be a VGPR");
4244 return false;
4245}
4246
4247bool AMDGPUAsmParser::validateMAIAccWrite(const MCInst &Inst,
4248 const OperandVector &Operands) {
4249
4250 const unsigned Opc = Inst.getOpcode();
4251
4252 if (Opc != AMDGPU::V_ACCVGPR_WRITE_B32_vi)
4253 return true;
4254
4255 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4256 assert(Src0Idx != -1);
4257
4258 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4259 if (!Src0.isReg())
4260 return true;
4261
4262 auto Reg = mc2PseudoReg(Src0.getReg());
4263 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4264 if (!isGFX90A() && isSGPR(Reg, TRI)) {
4265 Error(getOperandLoc(Operands, Src0Idx),
4266 "source operand must be either a VGPR or an inline constant");
4267 return false;
4268 }
4269
4270 return true;
4271}
4272
4273bool AMDGPUAsmParser::validateMAISrc2(const MCInst &Inst,
4274 const OperandVector &Operands) {
4275 unsigned Opcode = Inst.getOpcode();
4276
4277 if (!SIInstrFlags::isMAI(MII, Inst) ||
4278 !getFeatureBits()[FeatureMFMAInlineLiteralBug])
4279 return true;
4280
4281 const int Src2Idx = getNamedOperandIdx(Opcode, OpName::src2);
4282 if (Src2Idx == -1)
4283 return true;
4284
4285 if (Inst.getOperand(Src2Idx).isImm() && isInlineConstant(Inst, Src2Idx)) {
4286 Error(getOperandLoc(Operands, Src2Idx),
4287 "inline constants are not allowed for this operand");
4288 return false;
4289 }
4290
4291 return true;
4292}
4293
4294bool AMDGPUAsmParser::validateMFMA(const MCInst &Inst,
4295 const OperandVector &Operands) {
4296 const unsigned Opc = Inst.getOpcode();
4297 const MCInstrDesc &Desc = MII.get(Opc);
4298
4300 return true;
4301
4302 int BlgpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
4303 if (BlgpIdx != -1) {
4304 if (const MFMA_F8F6F4_Info *Info = AMDGPU::isMFMA_F8F6F4(Opc)) {
4305 int CbszIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::cbsz);
4306
4307 unsigned CBSZ = Inst.getOperand(CbszIdx).getImm();
4308 unsigned BLGP = Inst.getOperand(BlgpIdx).getImm();
4309
4310 // Validate the correct register size was used for the floating point
4311 // format operands
4312
4313 bool Success = true;
4314 if (Info->NumRegsSrcA != mfmaScaleF8F6F4FormatToNumRegs(CBSZ)) {
4315 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4316 Error(getOperandLoc(Operands, Src0Idx),
4317 "wrong register tuple size for cbsz value " + Twine(CBSZ));
4318 Success = false;
4319 }
4320
4321 if (Info->NumRegsSrcB != mfmaScaleF8F6F4FormatToNumRegs(BLGP)) {
4322 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4323 Error(getOperandLoc(Operands, Src1Idx),
4324 "wrong register tuple size for blgp value " + Twine(BLGP));
4325 Success = false;
4326 }
4327
4328 return Success;
4329 }
4330 }
4331
4332 const int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
4333 if (Src2Idx == -1)
4334 return true;
4335
4336 const MCOperand &Src2 = Inst.getOperand(Src2Idx);
4337 if (!Src2.isReg())
4338 return true;
4339
4340 MCRegister Src2Reg = Src2.getReg();
4341 MCRegister DstReg = Inst.getOperand(0).getReg();
4342 if (Src2Reg == DstReg)
4343 return true;
4344
4345 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4346 if (TRI->getRegClass(MII.getOpRegClassID(Desc.operands()[0], HwMode))
4347 .getSizeInBits() <= 128)
4348 return true;
4349
4350 if (TRI->regsOverlap(Src2Reg, DstReg)) {
4351 Error(getOperandLoc(Operands, Src2Idx),
4352 "source 2 operand must not partially overlap with dst");
4353 return false;
4354 }
4355
4356 return true;
4357}
4358
4359bool AMDGPUAsmParser::validateDivScale(const MCInst &Inst) {
4360 switch (Inst.getOpcode()) {
4361 default:
4362 return true;
4363 case V_DIV_SCALE_F32_gfx6_gfx7:
4364 case V_DIV_SCALE_F32_vi:
4365 case V_DIV_SCALE_F32_gfx10:
4366 case V_DIV_SCALE_F64_gfx6_gfx7:
4367 case V_DIV_SCALE_F64_vi:
4368 case V_DIV_SCALE_F64_gfx10:
4369 break;
4370 }
4371
4372 // TODO: Check that src0 = src1 or src2.
4373
4374 for (auto Name :
4375 {AMDGPU::OpName::src0_modifiers, AMDGPU::OpName::src2_modifiers,
4376 AMDGPU::OpName::src2_modifiers}) {
4377 if (Inst.getOperand(AMDGPU::getNamedOperandIdx(Inst.getOpcode(), Name))
4378 .getImm() &
4380 return false;
4381 }
4382 }
4383
4384 return true;
4385}
4386
4387bool AMDGPUAsmParser::validateMIMGD16(const MCInst &Inst) {
4388
4389 const unsigned Opc = Inst.getOpcode();
4390
4391 if ((SIInstrFlags::isImage(MII, Inst)) == 0)
4392 return true;
4393
4394 int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
4395 if (D16Idx >= 0 && Inst.getOperand(D16Idx).getImm()) {
4396 if (isCI() || isSI())
4397 return false;
4398 }
4399
4400 return true;
4401}
4402
4403bool AMDGPUAsmParser::validateTensorR128(const MCInst &Inst) {
4404 const unsigned Opc = Inst.getOpcode();
4405
4406 if (!SIInstrFlags::usesTENSOR_CNT(MII, Inst))
4407 return true;
4408
4409 int R128Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::r128);
4410
4411 return R128Idx < 0 || !Inst.getOperand(R128Idx).getImm();
4412}
4413
4414static bool IsRevOpcode(const unsigned Opcode) {
4415 switch (Opcode) {
4416 case AMDGPU::V_SUBREV_F32_e32:
4417 case AMDGPU::V_SUBREV_F32_e64:
4418 case AMDGPU::V_SUBREV_F32_e32_gfx10:
4419 case AMDGPU::V_SUBREV_F32_e32_gfx6_gfx7:
4420 case AMDGPU::V_SUBREV_F32_e32_vi:
4421 case AMDGPU::V_SUBREV_F32_e64_gfx10:
4422 case AMDGPU::V_SUBREV_F32_e64_gfx6_gfx7:
4423 case AMDGPU::V_SUBREV_F32_e64_vi:
4424
4425 case AMDGPU::V_SUBREV_CO_U32_e32:
4426 case AMDGPU::V_SUBREV_CO_U32_e64:
4427 case AMDGPU::V_SUBREV_I32_e32_gfx6_gfx7:
4428 case AMDGPU::V_SUBREV_I32_e64_gfx6_gfx7:
4429
4430 case AMDGPU::V_SUBBREV_U32_e32:
4431 case AMDGPU::V_SUBBREV_U32_e64:
4432 case AMDGPU::V_SUBBREV_U32_e32_gfx6_gfx7:
4433 case AMDGPU::V_SUBBREV_U32_e32_vi:
4434 case AMDGPU::V_SUBBREV_U32_e64_gfx6_gfx7:
4435 case AMDGPU::V_SUBBREV_U32_e64_vi:
4436
4437 case AMDGPU::V_SUBREV_U32_e32:
4438 case AMDGPU::V_SUBREV_U32_e64:
4439 case AMDGPU::V_SUBREV_U32_e32_gfx9:
4440 case AMDGPU::V_SUBREV_U32_e32_vi:
4441 case AMDGPU::V_SUBREV_U32_e64_gfx9:
4442 case AMDGPU::V_SUBREV_U32_e64_vi:
4443
4444 case AMDGPU::V_SUBREV_F16_e32:
4445 case AMDGPU::V_SUBREV_F16_e64:
4446 case AMDGPU::V_SUBREV_F16_e32_gfx10:
4447 case AMDGPU::V_SUBREV_F16_e32_vi:
4448 case AMDGPU::V_SUBREV_F16_e64_gfx10:
4449 case AMDGPU::V_SUBREV_F16_e64_vi:
4450
4451 case AMDGPU::V_SUBREV_U16_e32:
4452 case AMDGPU::V_SUBREV_U16_e64:
4453 case AMDGPU::V_SUBREV_U16_e32_vi:
4454 case AMDGPU::V_SUBREV_U16_e64_vi:
4455
4456 case AMDGPU::V_SUBREV_CO_U32_e32_gfx9:
4457 case AMDGPU::V_SUBREV_CO_U32_e64_gfx10:
4458 case AMDGPU::V_SUBREV_CO_U32_e64_gfx9:
4459
4460 case AMDGPU::V_SUBBREV_CO_U32_e32_gfx9:
4461 case AMDGPU::V_SUBBREV_CO_U32_e64_gfx9:
4462
4463 case AMDGPU::V_SUBREV_NC_U32_e32_gfx10:
4464 case AMDGPU::V_SUBREV_NC_U32_e64_gfx10:
4465
4466 case AMDGPU::V_SUBREV_CO_CI_U32_e32_gfx10:
4467 case AMDGPU::V_SUBREV_CO_CI_U32_e64_gfx10:
4468
4469 case AMDGPU::V_LSHRREV_B32_e32:
4470 case AMDGPU::V_LSHRREV_B32_e64:
4471 case AMDGPU::V_LSHRREV_B32_e32_gfx6_gfx7:
4472 case AMDGPU::V_LSHRREV_B32_e64_gfx6_gfx7:
4473 case AMDGPU::V_LSHRREV_B32_e32_vi:
4474 case AMDGPU::V_LSHRREV_B32_e64_vi:
4475 case AMDGPU::V_LSHRREV_B32_e32_gfx10:
4476 case AMDGPU::V_LSHRREV_B32_e64_gfx10:
4477
4478 case AMDGPU::V_ASHRREV_I32_e32:
4479 case AMDGPU::V_ASHRREV_I32_e64:
4480 case AMDGPU::V_ASHRREV_I32_e32_gfx10:
4481 case AMDGPU::V_ASHRREV_I32_e32_gfx6_gfx7:
4482 case AMDGPU::V_ASHRREV_I32_e32_vi:
4483 case AMDGPU::V_ASHRREV_I32_e64_gfx10:
4484 case AMDGPU::V_ASHRREV_I32_e64_gfx6_gfx7:
4485 case AMDGPU::V_ASHRREV_I32_e64_vi:
4486
4487 case AMDGPU::V_LSHLREV_B32_e32:
4488 case AMDGPU::V_LSHLREV_B32_e64:
4489 case AMDGPU::V_LSHLREV_B32_e32_gfx10:
4490 case AMDGPU::V_LSHLREV_B32_e32_gfx6_gfx7:
4491 case AMDGPU::V_LSHLREV_B32_e32_vi:
4492 case AMDGPU::V_LSHLREV_B32_e64_gfx10:
4493 case AMDGPU::V_LSHLREV_B32_e64_gfx6_gfx7:
4494 case AMDGPU::V_LSHLREV_B32_e64_vi:
4495
4496 case AMDGPU::V_LSHLREV_B16_e32:
4497 case AMDGPU::V_LSHLREV_B16_e64:
4498 case AMDGPU::V_LSHLREV_B16_e32_vi:
4499 case AMDGPU::V_LSHLREV_B16_e64_vi:
4500 case AMDGPU::V_LSHLREV_B16_gfx10:
4501
4502 case AMDGPU::V_LSHRREV_B16_e32:
4503 case AMDGPU::V_LSHRREV_B16_e64:
4504 case AMDGPU::V_LSHRREV_B16_e32_vi:
4505 case AMDGPU::V_LSHRREV_B16_e64_vi:
4506 case AMDGPU::V_LSHRREV_B16_gfx10:
4507
4508 case AMDGPU::V_ASHRREV_I16_e32:
4509 case AMDGPU::V_ASHRREV_I16_e64:
4510 case AMDGPU::V_ASHRREV_I16_e32_vi:
4511 case AMDGPU::V_ASHRREV_I16_e64_vi:
4512 case AMDGPU::V_ASHRREV_I16_gfx10:
4513
4514 case AMDGPU::V_LSHLREV_B64_e64:
4515 case AMDGPU::V_LSHLREV_B64_gfx10:
4516 case AMDGPU::V_LSHLREV_B64_vi:
4517
4518 case AMDGPU::V_LSHRREV_B64_e64:
4519 case AMDGPU::V_LSHRREV_B64_gfx10:
4520 case AMDGPU::V_LSHRREV_B64_vi:
4521
4522 case AMDGPU::V_ASHRREV_I64_e64:
4523 case AMDGPU::V_ASHRREV_I64_gfx10:
4524 case AMDGPU::V_ASHRREV_I64_vi:
4525
4526 case AMDGPU::V_PK_LSHLREV_B16:
4527 case AMDGPU::V_PK_LSHLREV_B16_gfx10:
4528 case AMDGPU::V_PK_LSHLREV_B16_vi:
4529
4530 case AMDGPU::V_PK_LSHRREV_B16:
4531 case AMDGPU::V_PK_LSHRREV_B16_gfx10:
4532 case AMDGPU::V_PK_LSHRREV_B16_vi:
4533 case AMDGPU::V_PK_ASHRREV_I16:
4534 case AMDGPU::V_PK_ASHRREV_I16_gfx10:
4535 case AMDGPU::V_PK_ASHRREV_I16_vi:
4536 return true;
4537 default:
4538 return false;
4539 }
4540}
4541
4542bool AMDGPUAsmParser::validateLdsDirect(const MCInst &Inst,
4543 const OperandVector &Operands) {
4544 const unsigned Opcode = Inst.getOpcode();
4545
4546 // lds_direct register is defined so that it can be used
4547 // with 9-bit operands only. Ignore encodings which do not accept these.
4548 if (!SIInstrFlags::isVOP1(MII, Inst) && !SIInstrFlags::isVOP2(MII, Inst) &&
4549 !SIInstrFlags::isVOP3Like(MII, Inst) &&
4550 !SIInstrFlags::isVOPC(MII, Inst) && !SIInstrFlags::isSDWA(MII, Inst))
4551 return true;
4552
4553 for (auto SrcName : {OpName::src0, OpName::src1, OpName::src2}) {
4554 auto SrcIdx = getNamedOperandIdx(Opcode, SrcName);
4555 if (SrcIdx == -1)
4556 break;
4557 const auto &Src = Inst.getOperand(SrcIdx);
4558 if (Src.isReg() && Src.getReg() == LDS_DIRECT) {
4559
4560 if (isGFX90A() || isGFX11Plus()) {
4561 Error(getOperandLoc(Operands, SrcIdx),
4562 "lds_direct is not supported on this GPU");
4563 return false;
4564 }
4565
4566 if (IsRevOpcode(Opcode) || SIInstrFlags::isSDWA(MII, Inst)) {
4567 Error(getOperandLoc(Operands, SrcIdx),
4568 "lds_direct cannot be used with this instruction");
4569 return false;
4570 }
4571
4572 if (SrcName != OpName::src0) {
4573 Error(getOperandLoc(Operands, SrcIdx),
4574 "lds_direct may be used as src0 only");
4575 return false;
4576 }
4577 }
4578 }
4579
4580 return true;
4581}
4582
4583SMLoc AMDGPUAsmParser::getFlatOffsetLoc(const OperandVector &Operands) const {
4584 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
4585 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4586 if (Op.isFlatOffset())
4587 return Op.getStartLoc();
4588 }
4589 return getLoc();
4590}
4591
4592bool AMDGPUAsmParser::validateOffset(const MCInst &Inst,
4593 const OperandVector &Operands) {
4594 auto Opcode = Inst.getOpcode();
4595 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4596 if (OpNum == -1)
4597 return true;
4598
4599 if (SIInstrFlags::isFLAT(MII, Inst))
4600 return validateFlatOffset(Inst, Operands);
4601
4602 if (SIInstrFlags::isSMRD(MII, Inst))
4603 return validateSMEMOffset(Inst, Operands);
4604
4605 const auto &Op = Inst.getOperand(OpNum);
4606 // GFX12+ buffer ops: InstOffset is signed 24, but must not be a negative.
4607 if (isGFX12Plus() && SIInstrFlags::isBuffer(MII, Inst)) {
4608 const unsigned OffsetSize = 24;
4609 if (!isUIntN(OffsetSize - 1, Op.getImm())) {
4610 Error(getFlatOffsetLoc(Operands),
4611 Twine("expected a ") + Twine(OffsetSize - 1) +
4612 "-bit unsigned offset for buffer ops");
4613 return false;
4614 }
4615 } else {
4616 const unsigned OffsetSize = 16;
4617 if (!isUIntN(OffsetSize, Op.getImm())) {
4618 Error(getFlatOffsetLoc(Operands),
4619 Twine("expected a ") + Twine(OffsetSize) + "-bit unsigned offset");
4620 return false;
4621 }
4622 }
4623 return true;
4624}
4625
4626bool AMDGPUAsmParser::validateFlatOffset(const MCInst &Inst,
4627 const OperandVector &Operands) {
4628 if (!SIInstrFlags::isFLAT(MII, Inst))
4629 return true;
4630
4631 auto Opcode = Inst.getOpcode();
4632 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4633 assert(OpNum != -1);
4634
4635 const auto &Op = Inst.getOperand(OpNum);
4636 if (!hasFlatOffsets() && Op.getImm() != 0) {
4637 Error(getFlatOffsetLoc(Operands),
4638 "flat offset modifier is not supported on this GPU");
4639 return false;
4640 }
4641
4642 // For pre-GFX12 FLAT instructions the offset must be positive;
4643 // MSB is ignored and forced to zero.
4644 unsigned OffsetSize = AMDGPU::getNumFlatOffsetBits(getSTI());
4645 bool AllowNegative =
4647 if (!isIntN(OffsetSize, Op.getImm()) || (!AllowNegative && Op.getImm() < 0)) {
4648 Error(getFlatOffsetLoc(Operands),
4649 Twine("expected a ") +
4650 (AllowNegative ? Twine(OffsetSize) + "-bit signed offset"
4651 : Twine(OffsetSize - 1) + "-bit unsigned offset"));
4652 return false;
4653 }
4654
4655 return true;
4656}
4657
4658SMLoc AMDGPUAsmParser::getSMEMOffsetLoc(const OperandVector &Operands) const {
4659 // Start with second operand because SMEM Offset cannot be dst or src0.
4660 for (unsigned i = 2, e = Operands.size(); i != e; ++i) {
4661 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
4662 if (Op.isSMEMOffset() || Op.isSMEMOffsetMod())
4663 return Op.getStartLoc();
4664 }
4665 return getLoc();
4666}
4667
4668bool AMDGPUAsmParser::validateSMEMOffset(const MCInst &Inst,
4669 const OperandVector &Operands) {
4670 if (isCI() || isSI())
4671 return true;
4672
4673 if (!SIInstrFlags::isSMRD(MII, Inst))
4674 return true;
4675
4676 auto Opcode = Inst.getOpcode();
4677 auto OpNum = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::offset);
4678 if (OpNum == -1)
4679 return true;
4680
4681 const auto &Op = Inst.getOperand(OpNum);
4682 if (!Op.isImm())
4683 return true;
4684
4685 uint64_t Offset = Op.getImm();
4686 bool IsBuffer = AMDGPU::getSMEMIsBuffer(Opcode);
4689 return true;
4690
4691 Error(getSMEMOffsetLoc(Operands),
4692 isGFX12Plus() && IsBuffer
4693 ? "expected a 23-bit unsigned offset for buffer ops"
4694 : isGFX12Plus() ? "expected a 24-bit signed offset"
4695 : (isVI() || IsBuffer) ? "expected a 20-bit unsigned offset"
4696 : "expected a 21-bit signed offset");
4697
4698 return false;
4699}
4700
4701// GFX12+ SMEM prefetches and probes encode an immediate sdata in 5 bits.
4702bool AMDGPUAsmParser::validateSMEMSData(const MCInst &Inst,
4703 const OperandVector &Operands) {
4704 if (!isGFX12Plus())
4705 return true;
4706
4707 int OpNum =
4708 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::sdata);
4709 if (OpNum == -1 || !Inst.getOperand(OpNum).isImm() ||
4710 isUInt<5>(Inst.getOperand(OpNum).getImm()))
4711 return true;
4712
4713 Error(getOperandLoc(Operands, OpNum), "expected a 5-bit unsigned immediate");
4714 return false;
4715}
4716
4717// On subtargets with FeatureBF16InlineConstFromUpperFP32 the hardware generates
4718// a bf16 inline constant in the high half of the corresponding fp32 inline
4719// constant. A VOP1 bf16 opcode (v_cvt_f32_bf16 and the bf16 transcendentals)
4720// reads the low half of its source, so it must use the VOP3 encoding with
4721// op_sel[0] set in order to see the constant at all.
4722bool AMDGPUAsmParser::validateBF16InlineConst(const MCInst &Inst,
4723 const OperandVector &Operands) {
4724 if (!getFeatureBits()[AMDGPU::FeatureBF16InlineConstFromUpperFP32])
4725 return true;
4726
4727 const unsigned Opc = Inst.getOpcode();
4728 const MCInstrDesc &Desc = MII.get(Opc);
4729 const bool IsVOP3 =
4731 if (!SIInstrFlags::isVOP1(Desc) && !IsVOP3)
4732 return true;
4733
4734 // Only the single-source VOP1 bf16 opcodes are affected. Multi-source and
4735 // packed bf16 instructions such as v_fma_mix*_bf16 are not.
4736 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src1))
4737 return true;
4738
4739 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4740 if (Src0Idx == -1)
4741 return true;
4742
4743 const MCOperandInfo &Src0Info = Desc.operands()[Src0Idx];
4744 if (!AMDGPU::isBF16SrcOperand(Src0Info))
4745 return true;
4746
4747 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4748 if (!Src0.isImm() ||
4749 !AMDGPU::isInlinableLiteralBF16(static_cast<int16_t>(Src0.getImm()),
4750 hasInv2PiInlineImm()))
4751 return true;
4752
4753 if (IsVOP3) {
4754 const int ModsIdx =
4755 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
4756 if (ModsIdx != -1 &&
4757 (Inst.getOperand(ModsIdx).getImm() & SISrcMods::OP_SEL_0))
4758 return true;
4759 }
4760
4761 Error(getOperandLoc(Operands, Src0Idx),
4762 "bf16 inline constant is read from the high half of the fp32 inline "
4763 "constant on this GPU; use the e64 encoding with op_sel:[1,0]");
4764 return false;
4765}
4766
4767bool AMDGPUAsmParser::validateSOPLiteral(const MCInst &Inst,
4768 const OperandVector &Operands) {
4769 unsigned Opcode = Inst.getOpcode();
4770 const MCInstrDesc &Desc = MII.get(Opcode);
4772 return true;
4773
4774 const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4775 const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
4776
4777 const int OpIndices[] = {Src0Idx, Src1Idx};
4778
4779 unsigned NumExprs = 0;
4780 unsigned NumLiterals = 0;
4781 int64_t LiteralValue;
4782
4783 for (int OpIdx : OpIndices) {
4784 if (OpIdx == -1)
4785 break;
4786
4787 const MCOperand &MO = Inst.getOperand(OpIdx);
4788 // Exclude special imm operands (like that used by s_set_gpr_idx_on)
4789 if (AMDGPU::isSISrcOperand(Desc, OpIdx)) {
4790 bool IsLit = false;
4791 std::optional<int64_t> Imm;
4792 if (MO.isImm()) {
4793 Imm = MO.getImm();
4794 } else if (MO.isExpr()) {
4795 if (isLitExpr(MO.getExpr())) {
4796 IsLit = true;
4797 Imm = getLitValue(MO.getExpr());
4798 }
4799 } else {
4800 continue;
4801 }
4802
4803 if (!Imm.has_value()) {
4804 ++NumExprs;
4805 } else if (!isInlineConstant(Inst, OpIdx)) {
4806 auto OpType = static_cast<AMDGPU::OperandType>(
4807 Desc.operands()[OpIdx].OperandType);
4808 int64_t Value = encode32BitLiteral(*Imm, OpType, IsLit);
4809 if (NumLiterals == 0 || LiteralValue != Value) {
4811 ++NumLiterals;
4812 }
4813 }
4814 }
4815 }
4816
4817 if (NumLiterals + NumExprs <= 1)
4818 return true;
4819
4820 Error(getOperandLoc(Operands, Src1Idx),
4821 "only one unique literal operand is allowed");
4822 return false;
4823}
4824
4825bool AMDGPUAsmParser::validateOpSel(const MCInst &Inst) {
4826 const unsigned Opc = Inst.getOpcode();
4827 if (isPermlane16(Opc)) {
4828 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4829 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4830
4831 if (OpSel & ~3)
4832 return false;
4833 }
4834
4835 if (isGFX940() && SIInstrFlags::isDOT(MII, Inst)) {
4836 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4837 if (OpSelIdx != -1) {
4838 if (Inst.getOperand(OpSelIdx).getImm() != 0)
4839 return false;
4840 }
4841 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
4842 if (OpSelHiIdx != -1) {
4843 if (Inst.getOperand(OpSelHiIdx).getImm() != -1)
4844 return false;
4845 }
4846 }
4847
4848 // op_sel[0:1] must be 0 for v_dot2_bf16_bf16 and v_dot2_f16_f16 (VOP3 Dot).
4849 if (isGFX11Plus() && SIInstrFlags::isDOT(MII, Inst) &&
4850 SIInstrFlags::isVOP3(MII, Inst) && !SIInstrFlags::isVOP3P(MII, Inst)) {
4851 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4852 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4853 if (OpSel & 3)
4854 return false;
4855 }
4856
4857 // gfx950 v_pk_add/mul/fma_f32 have several invalid op_sel encodings
4858 if (getFeatureBits()[AMDGPU::FeatureGFX950Insts] &&
4859 (Opc == AMDGPU::V_PK_ADD_F32_vi || Opc == AMDGPU::V_PK_MUL_F32_vi ||
4860 Opc == AMDGPU::V_PK_FMA_F32_vi)) {
4861 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4862 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4863
4864 // op_sel[2:1] == 2'b01, 2'b10, or 2'b11 for v_pk_fma.
4865 if (Opc == AMDGPU::V_PK_FMA_F32_vi &&
4866 (((OpSel >> 1) & 1) || ((OpSel >> 2) & 1)))
4867 return false;
4868 // op_sel[1:0] == 2'b10 for v_pk_add/mul_f32.
4869 else if ((OpSel & 3) == 2)
4870 return false;
4871 }
4872
4873 // Packed math FP32 instructions typically accept SGPRs or VGPRs as source
4874 // operands. On gfx12+, if a source operand uses SGPRs, the HW can only read
4875 // the first SGPR and use it for both the low and high operations.
4877 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4878 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4879 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4880 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
4881
4882 const MCOperand &Src0 = Inst.getOperand(Src0Idx);
4883 const MCOperand &Src1 = Inst.getOperand(Src1Idx);
4884 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
4885 unsigned OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
4886
4887 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
4888
4889 auto VerifyOneSGPR = [OpSel, OpSelHi](unsigned Index) -> bool {
4890 unsigned Mask = 1U << Index;
4891 return ((OpSel & Mask) == 0) && ((OpSelHi & Mask) == 0);
4892 };
4893
4894 if (Src0.isReg() && isSGPR(Src0.getReg(), TRI) &&
4895 !VerifyOneSGPR(/*Index=*/0))
4896 return false;
4897 if (Src1.isReg() && isSGPR(Src1.getReg(), TRI) &&
4898 !VerifyOneSGPR(/*Index=*/1))
4899 return false;
4900
4901 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
4902 if (Src2Idx != -1) {
4903 const MCOperand &Src2 = Inst.getOperand(Src2Idx);
4904 if (Src2.isReg() && isSGPR(Src2.getReg(), TRI) &&
4905 !VerifyOneSGPR(/*Index=*/2))
4906 return false;
4907 }
4908 }
4909
4910 return true;
4911}
4912
4913bool AMDGPUAsmParser::validateTrue16OpSel(const MCInst &Inst) {
4914 if (!hasTrue16Insts())
4915 return true;
4916 const MCRegisterInfo *MRI = getMRI();
4917 const unsigned Opc = Inst.getOpcode();
4918 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
4919 if (OpSelIdx == -1)
4920 return true;
4921 unsigned OpSelOpValue = Inst.getOperand(OpSelIdx).getImm();
4922 // If the value is 0 we could have a default OpSel Operand, so conservatively
4923 // allow it.
4924 if (OpSelOpValue == 0)
4925 return true;
4926 unsigned OpCount = 0;
4927 for (AMDGPU::OpName OpName : {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
4928 AMDGPU::OpName::src2, AMDGPU::OpName::vdst}) {
4929 int OpIdx = AMDGPU::getNamedOperandIdx(Inst.getOpcode(), OpName);
4930 if (OpIdx == -1)
4931 continue;
4932 const MCOperand &Op = Inst.getOperand(OpIdx);
4933 if (Op.isReg() &&
4934 MRI->getRegClass(AMDGPU::VGPR_16RegClassID).contains(Op.getReg())) {
4935 bool VGPRSuffixIsHi = AMDGPU::isHi16Reg(Op.getReg(), *MRI);
4936 bool OpSelOpIsHi = ((OpSelOpValue & (1 << OpCount)) != 0);
4937 if (OpSelOpIsHi != VGPRSuffixIsHi)
4938 return false;
4939 }
4940 ++OpCount;
4941 }
4942
4943 return true;
4944}
4945
4946bool AMDGPUAsmParser::validateNeg(const MCInst &Inst, AMDGPU::OpName OpName) {
4947 assert(OpName == AMDGPU::OpName::neg_lo || OpName == AMDGPU::OpName::neg_hi);
4948
4949 const unsigned Opc = Inst.getOpcode();
4950
4951 // v_dot4 fp8/bf8 neg_lo/neg_hi not allowed on src0 and src1 (allowed on src2)
4952 // v_wmma iu4/iu8 neg_lo not allowed on src2 (allowed on src0, src1)
4953 // v_swmmac f16/bf16 neg_lo/neg_hi not allowed on src2 (allowed on src0, src1)
4954 // other wmma/swmmac instructions don't have neg_lo/neg_hi operand.
4955 if (!SIInstrFlags::isDOT(MII, Inst) && !SIInstrFlags::isWMMA(MII, Inst) &&
4956 !SIInstrFlags::isSWMMAC(MII, Inst))
4957 return true;
4958
4959 int NegIdx = AMDGPU::getNamedOperandIdx(Opc, OpName);
4960 if (NegIdx == -1)
4961 return true;
4962
4963 unsigned Neg = Inst.getOperand(NegIdx).getImm();
4964
4965 // Instructions that have neg_lo or neg_hi operand but neg modifier is allowed
4966 // on some src operands but not allowed on other.
4967 // It is convenient that such instructions don't have src_modifiers operand
4968 // for src operands that don't allow neg because they also don't allow opsel.
4969
4970 const AMDGPU::OpName SrcMods[3] = {AMDGPU::OpName::src0_modifiers,
4971 AMDGPU::OpName::src1_modifiers,
4972 AMDGPU::OpName::src2_modifiers};
4973
4974 for (unsigned i = 0; i < 3; ++i) {
4975 if (!AMDGPU::hasNamedOperand(Opc, SrcMods[i])) {
4976 if (Neg & (1 << i))
4977 return false;
4978 }
4979 }
4980
4981 return true;
4982}
4983
4984bool AMDGPUAsmParser::validateDPP(const MCInst &Inst,
4985 const OperandVector &Operands) {
4986 const unsigned Opc = Inst.getOpcode();
4987 int DppCtrlIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dpp_ctrl);
4988 if (DppCtrlIdx >= 0) {
4989 unsigned DppCtrl = Inst.getOperand(DppCtrlIdx).getImm();
4990
4991 if (!AMDGPU::isLegalDPALU_DPPControl(getSTI(), DppCtrl) &&
4992 getSTI().hasFeature(AMDGPU::FeatureDPALU_DPP) &&
4993 AMDGPU::isDPALU_DPP(MII.get(Opc), MII, getSTI())) {
4994 // DP ALU DPP is supported for row_newbcast only on GFX9* and row_share
4995 // only on GFX12.
4996 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyDppCtrl, Operands);
4997 Error(S, isGFX12() ? "DP ALU dpp only supports row_share"
4998 : "DP ALU dpp only supports row_newbcast");
4999 return false;
5000 }
5001 }
5002
5003 int Dpp8Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dpp8);
5004 bool IsDPP = DppCtrlIdx >= 0 || Dpp8Idx >= 0;
5005
5006 if (IsDPP && (!hasDPPSrc1SGPR(getSTI()) ||
5007 AMDGPU::isVOP3DPPSrc1RevOpc(getSTI(), Opc))) {
5008 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5009 if (Src1Idx >= 0) {
5010 const MCOperand &Src1 = Inst.getOperand(Src1Idx);
5011 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
5012 if (Src1.isReg() && isSGPR(mc2PseudoReg(Src1.getReg()), TRI)) {
5013 Error(getOperandLoc(Operands, Src1Idx),
5014 "invalid operand for instruction");
5015 return false;
5016 }
5017 if (Src1.isImm()) {
5018 Error(getInstLoc(Operands),
5019 "src1 immediate operand invalid for instruction");
5020 return false;
5021 }
5022 }
5023 }
5024
5025 return true;
5026}
5027
5028// Check if VCC register matches wavefront size
5029bool AMDGPUAsmParser::validateVccOperand(MCRegister Reg) const {
5030 return (Reg == AMDGPU::VCC && isWave64()) ||
5031 (Reg == AMDGPU::VCC_LO && isWave32());
5032}
5033
5034// One unique literal can be used. VOP3 literal is only allowed in GFX10+
5035bool AMDGPUAsmParser::validateVOPLiteral(const MCInst &Inst,
5036 const OperandVector &Operands) {
5037 unsigned Opcode = Inst.getOpcode();
5038 const MCInstrDesc &Desc = MII.get(Opcode);
5039 bool HasMandatoryLiteral = getNamedOperandIdx(Opcode, OpName::imm) != -1;
5040 if (!SIInstrFlags::isVOP3Like(Desc) && !HasMandatoryLiteral &&
5041 !isVOPD(Opcode))
5042 return true;
5043
5044 OperandIndices OpIndices = getSrcOperandIndices(Opcode, HasMandatoryLiteral);
5045
5046 std::optional<unsigned> LiteralOpIdx;
5047 std::optional<uint64_t> LiteralValue;
5048
5049 for (int OpIdx : OpIndices) {
5050 if (OpIdx == -1)
5051 continue;
5052
5053 const MCOperand &MO = Inst.getOperand(OpIdx);
5054 if (!MO.isImm() && !MO.isExpr())
5055 continue;
5056 if (!isSISrcOperand(Desc, OpIdx))
5057 continue;
5058
5059 std::optional<int64_t> Imm;
5060 if (MO.isImm())
5061 Imm = MO.getImm();
5062 else if (MO.isExpr() && isLitExpr(MO.getExpr()))
5063 Imm = getLitValue(MO.getExpr());
5064
5065 bool IsAnotherLiteral = false;
5066 bool IsForcedLit = findMCOperand(Operands, OpIdx).isForcedLit();
5067 bool IsForcedLit64 = findMCOperand(Operands, OpIdx).isForcedLit64();
5068 if (!Imm.has_value()) {
5069 // Literal value not known, so we conservately assume it's different.
5070 IsAnotherLiteral = true;
5071 } else if (IsForcedLit || IsForcedLit64 || !isInlineConstant(Inst, OpIdx)) {
5072 uint64_t Value = *Imm;
5073 bool IsForcedFP64 =
5074 Desc.operands()[OpIdx].OperandType == AMDGPU::OPERAND_KIMM64 ||
5075 (Desc.operands()[OpIdx].OperandType == AMDGPU::OPERAND_REG_IMM_FP64 &&
5076 HasMandatoryLiteral);
5077 AMDGPU::OperandType OpTy =
5078 static_cast<AMDGPU::OperandType>(Desc.operands()[OpIdx].OperandType);
5079 bool IsFP64 =
5080 (IsForcedFP64 || (AMDGPU::isSISrcFPOperand(Desc, OpIdx) &&
5082 AMDGPU::getOperandSize(Desc.operands()[OpIdx]) == 8;
5083 bool IsValid32Op =
5084 IsForcedLit || AMDGPU::isValid32BitLiteral(Value, IsFP64);
5085
5086 if (((!IsValid32Op && !isInt<32>(Value) && !isUInt<32>(Value) &&
5087 !IsForcedFP64) ||
5088 (IsForcedLit64 && !HasMandatoryLiteral)) &&
5089 (!has64BitLiterals() || Desc.getSize() != 4)) {
5090 Error(getOperandLoc(Operands, OpIdx),
5091 "invalid operand for instruction");
5092 return false;
5093 }
5094
5095 // Only src0 can use lit64 in VOP* encoding.
5096 if (!IsForcedFP64 && (IsForcedLit64 || !IsValid32Op) &&
5097 OpIdx != getNamedOperandIdx(Opcode, OpName::src0)) {
5098 Error(getOperandLoc(Operands, OpIdx),
5099 "invalid operand for instruction");
5100 return false;
5101 }
5102
5103 // Compare values using the word encoded by a 32-bit literal.
5104 if (IsValid32Op && !IsForcedFP64 && !IsForcedLit64) {
5105 Value = static_cast<uint32_t>(
5106 AMDGPU::encode32BitLiteral(Value, OpTy, IsForcedLit));
5107 }
5108
5109 IsAnotherLiteral = !LiteralValue || *LiteralValue != Value;
5111 }
5112
5113 if (IsAnotherLiteral && !HasMandatoryLiteral &&
5114 !getFeatureBits()[FeatureVOP3Literal]) {
5115 Error(getOperandLoc(Operands, OpIdx),
5116 "literal operands are not supported");
5117 return false;
5118 }
5119
5120 if (LiteralOpIdx && IsAnotherLiteral) {
5121 Error(getLaterLoc(getOperandLoc(Operands, OpIdx),
5122 getOperandLoc(Operands, *LiteralOpIdx)),
5123 "only one unique literal operand is allowed");
5124 return false;
5125 }
5126
5127 if (IsAnotherLiteral)
5128 LiteralOpIdx = OpIdx;
5129 }
5130
5131 return true;
5132}
5133
5134// Returns -1 if not a register, 0 if VGPR and 1 if AGPR.
5135static int IsAGPROperand(const MCInst &Inst, AMDGPU::OpName Name,
5136 const MCRegisterInfo *MRI) {
5137 int OpIdx = AMDGPU::getNamedOperandIdx(Inst.getOpcode(), Name);
5138 if (OpIdx < 0)
5139 return -1;
5140
5141 const MCOperand &Op = Inst.getOperand(OpIdx);
5142 if (!Op.isReg())
5143 return -1;
5144
5145 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5146 auto Reg = Sub ? Sub : Op.getReg();
5147 const MCRegisterClass &AGPR32 = MRI->getRegClass(AMDGPU::AGPR_32RegClassID);
5148 return AGPR32.contains(Reg) ? 1 : 0;
5149}
5150
5151bool AMDGPUAsmParser::validateAGPRLdSt(const MCInst &Inst) const {
5152 if (!SIInstrFlags::isFLAT(MII, Inst) && !SIInstrFlags::isBuffer(MII, Inst) &&
5153 !SIInstrFlags::isMIMG(MII, Inst) && !SIInstrFlags::isDS(MII, Inst))
5154 return true;
5155
5156 AMDGPU::OpName DataName = SIInstrFlags::isDS(MII, Inst)
5157 ? AMDGPU::OpName::data0
5158 : AMDGPU::OpName::vdata;
5159
5160 const MCRegisterInfo *MRI = getMRI();
5161 int DstAreg = IsAGPROperand(Inst, AMDGPU::OpName::vdst, MRI);
5162 int DataAreg = IsAGPROperand(Inst, DataName, MRI);
5163
5164 if (SIInstrFlags::isDS(MII, Inst) && DataAreg >= 0) {
5165 int Data2Areg = IsAGPROperand(Inst, AMDGPU::OpName::data1, MRI);
5166 if (Data2Areg >= 0 && Data2Areg != DataAreg)
5167 return false;
5168 }
5169
5170 auto FB = getFeatureBits();
5171 if (FB[AMDGPU::FeatureGFX90AInsts]) {
5172 if (DataAreg < 0 || DstAreg < 0)
5173 return true;
5174 return DstAreg == DataAreg;
5175 }
5176
5177 return DstAreg < 1 && DataAreg < 1;
5178}
5179
5180bool AMDGPUAsmParser::validateVGPRAlign(const MCInst &Inst) const {
5181 auto FB = getFeatureBits();
5182 if (!FB[AMDGPU::FeatureRequiresAlignedVGPRs])
5183 return true;
5184
5185 unsigned Opc = Inst.getOpcode();
5186 const MCRegisterInfo *MRI = getMRI();
5187 // DS_READ_B96_TR_B6 is the only DS instruction in GFX950, that allows
5188 // unaligned VGPR. All others only allow even aligned VGPRs.
5189 if (FB[AMDGPU::FeatureGFX90AInsts] && Opc == AMDGPU::DS_READ_B96_TR_B6_vi)
5190 return true;
5191
5192 if (FB[AMDGPU::FeatureGFX1250Insts]) {
5193 switch (Opc) {
5194 default:
5195 break;
5196 case AMDGPU::DS_LOAD_TR6_B96:
5197 case AMDGPU::DS_LOAD_TR6_B96_gfx12:
5198 // DS_LOAD_TR6_B96 is the only DS instruction in GFX1250, that
5199 // allows unaligned VGPR. All others only allow even aligned VGPRs.
5200 return true;
5201 case AMDGPU::GLOBAL_LOAD_TR6_B96:
5202 case AMDGPU::GLOBAL_LOAD_TR6_B96_gfx1250: {
5203 // GLOBAL_LOAD_TR6_B96 is the only GLOBAL instruction in GFX1250, that
5204 // allows unaligned VGPR for vdst, but other operands still only allow
5205 // even aligned VGPRs.
5206 int VAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5207 if (VAddrIdx != -1) {
5208 const MCOperand &Op = Inst.getOperand(VAddrIdx);
5209 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5210 if ((Sub - AMDGPU::VGPR0) & 1)
5211 return false;
5212 }
5213 return true;
5214 }
5215 case AMDGPU::GLOBAL_LOAD_TR6_B96_SADDR:
5216 case AMDGPU::GLOBAL_LOAD_TR6_B96_SADDR_gfx1250:
5217 return true;
5218 }
5219 }
5220
5221 const MCRegisterClass &VGPR32 = MRI->getRegClass(AMDGPU::VGPR_32RegClassID);
5222 const MCRegisterClass &AGPR32 = MRI->getRegClass(AMDGPU::AGPR_32RegClassID);
5223 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
5224 const MCOperand &Op = Inst.getOperand(I);
5225 if (!Op.isReg())
5226 continue;
5227
5228 MCRegister Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
5229 if (!Sub)
5230 continue;
5231
5232 if (VGPR32.contains(Sub) && ((Sub - AMDGPU::VGPR0) & 1))
5233 return false;
5234 if (AGPR32.contains(Sub) && ((Sub - AMDGPU::AGPR0) & 1))
5235 return false;
5236 }
5237
5238 return true;
5239}
5240
5241SMLoc AMDGPUAsmParser::getBLGPLoc(const OperandVector &Operands) const {
5242 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
5243 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
5244 if (Op.isBLGP())
5245 return Op.getStartLoc();
5246 }
5247 return SMLoc();
5248}
5249
5250bool AMDGPUAsmParser::validateBLGP(const MCInst &Inst,
5251 const OperandVector &Operands) {
5252 unsigned Opc = Inst.getOpcode();
5253 int BlgpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
5254 if (BlgpIdx == -1)
5255 return true;
5256 SMLoc BLGPLoc = getBLGPLoc(Operands);
5257 if (!BLGPLoc.isValid())
5258 return true;
5259 bool IsNeg = StringRef(BLGPLoc.getPointer()).starts_with("neg:");
5260 auto FB = getFeatureBits();
5261 bool UsesNeg = false;
5262 if (FB[AMDGPU::FeatureGFX940Insts]) {
5263 switch (Opc) {
5264 case AMDGPU::V_MFMA_F64_16X16X4F64_gfx940_acd:
5265 case AMDGPU::V_MFMA_F64_16X16X4F64_gfx940_vcd:
5266 case AMDGPU::V_MFMA_F64_4X4X4F64_gfx940_acd:
5267 case AMDGPU::V_MFMA_F64_4X4X4F64_gfx940_vcd:
5268 UsesNeg = true;
5269 }
5270 }
5271
5272 if (IsNeg == UsesNeg)
5273 return true;
5274
5275 Error(BLGPLoc, UsesNeg ? "invalid modifier: blgp is not supported"
5276 : "invalid modifier: neg is not supported");
5277
5278 return false;
5279}
5280
5281bool AMDGPUAsmParser::validateWaitCnt(const MCInst &Inst,
5282 const OperandVector &Operands) {
5283 if (!isGFX11Plus())
5284 return true;
5285
5286 unsigned Opc = Inst.getOpcode();
5287 if (Opc != AMDGPU::S_WAITCNT_EXPCNT_gfx11 &&
5288 Opc != AMDGPU::S_WAITCNT_LGKMCNT_gfx11 &&
5289 Opc != AMDGPU::S_WAITCNT_VMCNT_gfx11 &&
5290 Opc != AMDGPU::S_WAITCNT_VSCNT_gfx11)
5291 return true;
5292
5293 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
5294 assert(Src0Idx >= 0 && Inst.getOperand(Src0Idx).isReg());
5295 auto Reg = mc2PseudoReg(Inst.getOperand(Src0Idx).getReg());
5296 if (Reg == AMDGPU::SGPR_NULL)
5297 return true;
5298
5299 Error(getOperandLoc(Operands, Src0Idx), "src0 must be null");
5300 return false;
5301}
5302
5303bool AMDGPUAsmParser::validateDS(const MCInst &Inst,
5304 const OperandVector &Operands) {
5305 if (!SIInstrFlags::isDS(MII, Inst))
5306 return true;
5307 if (SIInstrFlags::isGWS(MII, Inst))
5308 return validateGWS(Inst, Operands);
5309 // Only validate GDS for non-GWS instructions.
5310 if (hasGDS())
5311 return true;
5312 int GDSIdx =
5313 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::gds);
5314 if (GDSIdx < 0)
5315 return true;
5316 unsigned GDS = Inst.getOperand(GDSIdx).getImm();
5317 if (GDS) {
5318 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyGDS, Operands);
5319 Error(S, "gds modifier is not supported on this GPU");
5320 return false;
5321 }
5322 return true;
5323}
5324
5325// gfx90a has an undocumented limitation:
5326// DS_GWS opcodes must use even aligned registers.
5327bool AMDGPUAsmParser::validateGWS(const MCInst &Inst,
5328 const OperandVector &Operands) {
5329 if (!getFeatureBits()[AMDGPU::FeatureGFX90AInsts])
5330 return true;
5331
5332 int Opc = Inst.getOpcode();
5333 if (Opc != AMDGPU::DS_GWS_INIT_vi && Opc != AMDGPU::DS_GWS_BARRIER_vi &&
5334 Opc != AMDGPU::DS_GWS_SEMA_BR_vi)
5335 return true;
5336
5337 const MCRegisterInfo *MRI = getMRI();
5338 const MCRegisterClass &VGPR32 = MRI->getRegClass(AMDGPU::VGPR_32RegClassID);
5339 int Data0Pos =
5340 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0);
5341 assert(Data0Pos != -1);
5342 auto Reg = Inst.getOperand(Data0Pos).getReg();
5343 auto RegIdx = Reg - (VGPR32.contains(Reg) ? AMDGPU::VGPR0 : AMDGPU::AGPR0);
5344 if (RegIdx & 1) {
5345 Error(getOperandLoc(Operands, Data0Pos), "vgpr must be even aligned");
5346 return false;
5347 }
5348
5349 return true;
5350}
5351
5352bool AMDGPUAsmParser::validateCoherencyBits(const MCInst &Inst,
5353 const OperandVector &Operands,
5354 SMLoc IDLoc) {
5355 int CPolPos =
5356 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::cpol);
5357 if (CPolPos == -1)
5358 return true;
5359
5360 unsigned CPol = Inst.getOperand(CPolPos).getImm();
5361
5362 if (CPol & CPol::CFS) {
5363 if (!hasCacheFillSize()) {
5364 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5365 StringRef CStr(S.getPointer());
5366 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("cfs")]);
5367 Error(S, "Cache fill size is not supported on this GPU");
5368 } else if (!validateCFSBits(Inst, Operands)) {
5369 return false;
5370 }
5371 }
5372
5373 if (!hasScaleOffset() && (CPol & CPol::SCAL)) {
5374 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5375 StringRef CStr(S.getPointer());
5376 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scale_offset")]);
5377 Error(S, "scale_offset is not supported on this GPU");
5378 }
5379
5380 if (!isGFX1250Plus() && (CPol & CPol::NV)) {
5381 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5382 StringRef CStr(S.getPointer());
5383 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("nv")]);
5384 Error(S, "nv is not supported on this GPU");
5385 }
5386
5387 if ((CPol & CPol::SCAL) && !supportsScaleOffset(MII, Inst.getOpcode())) {
5388 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5389 StringRef CStr(S.getPointer());
5390 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scale_offset")]);
5391 Error(S, "scale_offset is not supported for this instruction");
5392 }
5393
5394 if (isGFX12Plus())
5395 return validateTHAndScopeBits(Inst, Operands, CPol);
5396
5397 if (SIInstrFlags::isSMRD(MII, Inst)) {
5398 if (CPol && (isSI() || isCI())) {
5399 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5400 Error(S, "cache policy is not supported for SMRD instructions");
5401 return false;
5402 }
5403 if (CPol & ~(AMDGPU::CPol::GLC | AMDGPU::CPol::DLC)) {
5404 Error(IDLoc, "invalid cache policy for SMEM instruction");
5405 return false;
5406 }
5407 }
5408
5409 if (isGFX90A() && !isGFX940() && (CPol & CPol::SCC)) {
5410 if (!SIInstrFlags::isVMEM(MII, Inst)) {
5411 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5412 StringRef CStr(S.getPointer());
5413 S = SMLoc::getFromPointer(&CStr.data()[CStr.find("scc")]);
5414 Error(S,
5415 "scc modifier is not supported for this instruction on this GPU");
5416 return false;
5417 }
5418 }
5419
5420 if (!SIInstrFlags::isAtomic(MII, Inst))
5421 return true;
5422
5423 if (SIInstrFlags::isAtomicRet(MII, Inst)) {
5424 if (!SIInstrFlags::isMIMG(MII, Inst) && !(CPol & CPol::GLC)) {
5425 Error(IDLoc, isGFX940() ? "instruction must use sc0"
5426 : "instruction must use glc");
5427 return false;
5428 }
5429 } else {
5430 if (CPol & CPol::GLC) {
5431 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5432 StringRef CStr(S.getPointer());
5434 &CStr.data()[CStr.find(isGFX940() ? "sc0" : "glc")]);
5435 Error(S, isGFX940() ? "instruction must not use sc0"
5436 : "instruction must not use glc");
5437 return false;
5438 }
5439 }
5440
5441 return true;
5442}
5443
5444bool AMDGPUAsmParser::validateTHAndScopeBits(const MCInst &Inst,
5445 const OperandVector &Operands,
5446 const unsigned CPol) {
5447 const unsigned TH = CPol & AMDGPU::CPol::TH;
5448 const unsigned Scope = CPol & AMDGPU::CPol::SCOPE;
5449
5450 auto PrintError = [&](StringRef Msg) {
5451 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5452 Error(S, Msg);
5453 return false;
5454 };
5455
5456 if ((TH & AMDGPU::CPol::TH_ATOMIC_RETURN) &&
5457 SIInstrFlags::isAtomicNoRet(MII, Inst))
5458 return PrintError("th:TH_ATOMIC_RETURN requires a destination operand");
5459
5460 if (SIInstrFlags::isAtomicRet(MII, Inst) &&
5461 (SIInstrFlags::isFLAT(MII, Inst) || SIInstrFlags::isMUBUF(MII, Inst)) &&
5463 return PrintError("instruction must use th:TH_ATOMIC_RETURN");
5464
5465 if (TH == 0)
5466 return true;
5467
5468 if (SIInstrFlags::isSMRD(MII, Inst) &&
5469 ((TH == AMDGPU::CPol::TH_NT_RT) || (TH == AMDGPU::CPol::TH_RT_NT) ||
5470 (TH == AMDGPU::CPol::TH_NT_HT)))
5471 return PrintError("invalid th value for SMEM instruction");
5472
5473 if (TH == AMDGPU::CPol::TH_BYPASS) {
5474 if ((Scope != AMDGPU::CPol::SCOPE_SYS &&
5476 (Scope == AMDGPU::CPol::SCOPE_SYS &&
5478 return PrintError("scope and th combination is not valid");
5479 }
5480
5481 unsigned THType = AMDGPU::getTemporalHintType(MII.get(Inst.getOpcode()));
5482 if (THType == AMDGPU::CPol::TH_TYPE_ATOMIC) {
5483 if (!(CPol & AMDGPU::CPol::TH_TYPE_ATOMIC))
5484 return PrintError("invalid th value for atomic instructions");
5485 } else if (THType == AMDGPU::CPol::TH_TYPE_STORE) {
5486 if (!(CPol & AMDGPU::CPol::TH_TYPE_STORE))
5487 return PrintError("invalid th value for store instructions");
5488 } else {
5489 if (!(CPol & AMDGPU::CPol::TH_TYPE_LOAD))
5490 return PrintError("invalid th value for load instructions");
5491 }
5492
5493 return true;
5494}
5495
5496bool AMDGPUAsmParser::validateCFSBits(const MCInst &Inst,
5497 const OperandVector &Operands) {
5498 const unsigned Opcode = Inst.getOpcode();
5499 const MCInstrDesc &Desc = MII.get(Opcode);
5500
5501 auto PrintError = [&](StringRef Msg) {
5502 SMLoc S = getImmLoc(AMDGPUOperand::ImmTyCPol, Operands);
5503 Error(S, Msg);
5504 return false;
5505 };
5506
5508 return true;
5509
5510 return PrintError("Cache fill size is only supported for VC operations");
5511}
5512
5513bool AMDGPUAsmParser::validateTFE(const MCInst &Inst,
5514 const OperandVector &Operands) {
5515 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
5516 if (Desc.mayStore() && SIInstrFlags::isBuffer(Desc)) {
5517 SMLoc Loc = getImmLoc(AMDGPUOperand::ImmTyTFE, Operands);
5518 if (Loc != getInstLoc(Operands)) {
5519 Error(Loc, "TFE modifier has no meaning for store instructions");
5520 return false;
5521 }
5522 }
5523
5524 return true;
5525}
5526
5527bool AMDGPUAsmParser::validateWMMA(const MCInst &Inst,
5528 const OperandVector &Operands) {
5529 unsigned Opc = Inst.getOpcode();
5530 const MCRegisterInfo *TRI = getContext().getRegisterInfo();
5531 const MCInstrDesc &Desc = MII.get(Opc);
5532
5533 int AFmtIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_fmt);
5534 if (AFmtIdx == -1)
5535 return true;
5536 unsigned AFmt = Inst.getOperand(AFmtIdx).getImm();
5537 int BFmtIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_fmt);
5538 unsigned BFmt = Inst.getOperand(BFmtIdx).getImm();
5539
5540 auto validateFmt = [&](unsigned Fmt, AMDGPU::OpName SrcOp) -> bool {
5541 int SrcIdx = AMDGPU::getNamedOperandIdx(Opc, SrcOp);
5542 unsigned RegSize =
5543 TRI->getRegClass(MII.getOpRegClassID(Desc.operands()[SrcIdx], HwMode))
5544 .getSizeInBits();
5545
5547 return true;
5548
5549 Error(getOperandLoc(Operands, SrcIdx),
5550 "wrong register tuple size for " +
5551 Twine(WMMAMods::ModMatrixFmt[Fmt]));
5552 return false;
5553 };
5554
5555 if (!validateFmt(AFmt, AMDGPU::OpName::src0) ||
5556 !validateFmt(BFmt, AMDGPU::OpName::src1))
5557 return false;
5558
5559 int AScaleIdx =
5560 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale_fmt);
5561 if (AScaleIdx == -1)
5562 return true;
5563 unsigned AScale = Inst.getOperand(AScaleIdx).getImm();
5564 int BScaleIdx =
5565 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale_fmt);
5566 unsigned BScale = Inst.getOperand(BScaleIdx).getImm();
5567 if (!isValidWMMAScaleFmtCombination(AFmt, AScale, BFmt, BScale)) {
5568 Error(getImmLoc(AMDGPUOperand::ImmTyMatrixAFMT, Operands),
5569 "invalid matrix and scale format combination");
5570 return false;
5571 }
5572
5573 return true;
5574}
5575
5576bool AMDGPUAsmParser::validateMonitorSleep(const MCInst &Inst,
5577 const OperandVector &Operands) {
5578 unsigned Opc = Inst.getOpcode();
5579 if (Opc != AMDGPU::S_MONITOR_SLEEP_gfx12 ||
5580 !getSTI().hasFeature(AMDGPU::FeatureNoSleepForever))
5581 return true;
5582
5583 int ImmIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::simm16);
5584 if (Inst.getOperand(ImmIdx).getImm() & 0x8000) {
5585 Error(getOperandLoc(Operands, ImmIdx),
5586 "sleep forever is unsupported on the target");
5587 return false;
5588 }
5589
5590 return true;
5591}
5592
5593bool AMDGPUAsmParser::validateClusterBarrierIsFirst(
5594 const MCInst &Inst, const OperandVector &Operands) {
5595 unsigned Opc = Inst.getOpcode();
5596 if (Opc != AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM_gfx12 &&
5597 Opc != AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM_gfx13)
5598 return true;
5599
5600 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5601 int BarrierID = Inst.getOperand(Src0Idx).getImm();
5602 if (BarrierID != AMDGPU::Barrier::CLUSTER)
5603 return true;
5604
5605 Error(
5606 getOperandLoc(Operands, Src0Idx),
5607 "s_barrier_signal_isfirst does not support user_cluster_barrier_id (-3)");
5608 return false;
5609}
5610
5611bool AMDGPUAsmParser::validateScaleSel(const MCInst &Inst,
5612 const OperandVector &Operands) {
5613 unsigned Opc = Inst.getOpcode();
5614 int ScaleSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::scale_sel);
5615 if (ScaleSelIdx == -1)
5616 return true;
5617 int MaxSel = 0;
5618 switch (Opc) {
5619 case AMDGPU::V_CVT_SCALE_PK16_F16_FP6_e64_gfx1250:
5620 case AMDGPU::V_CVT_SCALE_PK16_BF16_FP6_e64_gfx1250:
5621 case AMDGPU::V_CVT_SCALE_PK16_F16_BF6_e64_gfx1250:
5622 case AMDGPU::V_CVT_SCALE_PK16_BF16_BF6_e64_gfx1250:
5623 case AMDGPU::V_CVT_SCALE_PK16_F32_FP6_e64_gfx1250:
5624 case AMDGPU::V_CVT_SCALE_PK16_F32_BF6_e64_gfx1250:
5625 case AMDGPU::V_CVT_SCALE_PK8_F16_FP4_e64_gfx1250:
5626 case AMDGPU::V_CVT_SCALE_PK8_BF16_FP4_e64_gfx1250:
5627 case AMDGPU::V_CVT_SCALE_PK8_F32_FP4_e64_gfx1250:
5628 MaxSel = 4;
5629 break;
5630 case AMDGPU::V_CVT_SCALE_PK8_F16_FP8_e64_gfx1250:
5631 case AMDGPU::V_CVT_SCALE_PK8_BF16_FP8_e64_gfx1250:
5632 case AMDGPU::V_CVT_SCALE_PK8_F16_BF8_e64_gfx1250:
5633 case AMDGPU::V_CVT_SCALE_PK8_BF16_BF8_e64_gfx1250:
5634 case AMDGPU::V_CVT_SCALE_PK8_F32_FP8_e64_gfx1250:
5635 case AMDGPU::V_CVT_SCALE_PK8_F32_BF8_e64_gfx1250:
5636 MaxSel = 8;
5637 break;
5638 default:
5639 return true;
5640 }
5641
5642 if (getSTI().hasFeature(AMDGPU::FeatureBlock16ConversionScaleInsts))
5643 MaxSel *= 2;
5644
5645 int ScaleSel = Inst.getOperand(ScaleSelIdx).getImm();
5646 if (ScaleSel < MaxSel)
5647 return true;
5648
5649 Error(getOperandLoc(Operands, ScaleSelIdx),
5650 "scale_sel maximum supported value is " + Twine(MaxSel - 1));
5651 return false;
5652}
5653
5654bool AMDGPUAsmParser::validateInstruction(const MCInst &Inst, SMLoc IDLoc,
5655 const OperandVector &Operands) {
5656 if (!validateLdsDirect(Inst, Operands))
5657 return false;
5658 if (!validateTrue16OpSel(Inst)) {
5659 Error(getImmLoc(AMDGPUOperand::ImmTyOpSel, Operands),
5660 "op_sel operand conflicts with 16-bit operand suffix");
5661 return false;
5662 }
5663 if (!validateSOPLiteral(Inst, Operands))
5664 return false;
5665 if (!validateVOPLiteral(Inst, Operands)) {
5666 return false;
5667 }
5668 if (!validateConstantBusLimitations(Inst, Operands)) {
5669 return false;
5670 }
5671 if (!validateVOPD(Inst, Operands)) {
5672 return false;
5673 }
5674 if (!validateIntClampSupported(Inst)) {
5675 Error(getImmLoc(AMDGPUOperand::ImmTyClamp, Operands),
5676 "integer clamping is not supported on this GPU");
5677 return false;
5678 }
5679 if (!validateOpSel(Inst)) {
5680 Error(getImmLoc(AMDGPUOperand::ImmTyOpSel, Operands),
5681 "invalid op_sel operand");
5682 return false;
5683 }
5684 if (!validateNeg(Inst, AMDGPU::OpName::neg_lo)) {
5685 Error(getImmLoc(AMDGPUOperand::ImmTyNegLo, Operands),
5686 "invalid neg_lo operand");
5687 return false;
5688 }
5689 if (!validateNeg(Inst, AMDGPU::OpName::neg_hi)) {
5690 Error(getImmLoc(AMDGPUOperand::ImmTyNegHi, Operands),
5691 "invalid neg_hi operand");
5692 return false;
5693 }
5694 if (!validateDPP(Inst, Operands)) {
5695 return false;
5696 }
5697 // For MUBUF/MTBUF d16 is a part of opcode, so there is nothing to validate.
5698 if (!validateMIMGD16(Inst)) {
5699 Error(getImmLoc(AMDGPUOperand::ImmTyD16, Operands),
5700 "d16 modifier is not supported on this GPU");
5701 return false;
5702 }
5703 if (!validateMIMGDim(Inst, Operands)) {
5704 Error(IDLoc, "missing dim operand");
5705 return false;
5706 }
5707 if (!validateTensorR128(Inst)) {
5708 Error(getImmLoc(AMDGPUOperand::ImmTyD16, Operands),
5709 "instruction must set modifier r128=0");
5710 return false;
5711 }
5712 if (!validateMIMGMSAA(Inst)) {
5713 Error(getImmLoc(AMDGPUOperand::ImmTyDim, Operands),
5714 "invalid dim; must be MSAA type");
5715 return false;
5716 }
5717 if (!validateMIMGDataSize(Inst, IDLoc)) {
5718 return false;
5719 }
5720 if (!validateMIMGAddrSize(Inst, IDLoc))
5721 return false;
5722 if (!validateMIMGAtomicDMask(Inst)) {
5723 Error(getImmLoc(AMDGPUOperand::ImmTyDMask, Operands),
5724 "invalid atomic image dmask");
5725 return false;
5726 }
5727 if (!validateMIMGGatherDMask(Inst)) {
5728 Error(getImmLoc(AMDGPUOperand::ImmTyDMask, Operands),
5729 "invalid image_gather dmask: only one bit must be set");
5730 return false;
5731 }
5732 if (!validateMovrels(Inst, Operands)) {
5733 return false;
5734 }
5735 if (!validateOffset(Inst, Operands)) {
5736 return false;
5737 }
5738 if (!validateSMEMSData(Inst, Operands))
5739 return false;
5740 if (!validateBF16InlineConst(Inst, Operands)) {
5741 return false;
5742 }
5743 if (!validateMAIAccWrite(Inst, Operands)) {
5744 return false;
5745 }
5746 if (!validateMAISrc2(Inst, Operands)) {
5747 return false;
5748 }
5749 if (!validateMFMA(Inst, Operands)) {
5750 return false;
5751 }
5752 if (!validateCoherencyBits(Inst, Operands, IDLoc)) {
5753 return false;
5754 }
5755
5756 if (!validateAGPRLdSt(Inst)) {
5757 Error(
5758 IDLoc,
5759 getFeatureBits()[AMDGPU::FeatureGFX90AInsts]
5760 ? "invalid register class: data and dst should be all VGPR or AGPR"
5761 : "invalid register class: agpr loads and stores not supported on "
5762 "this GPU");
5763 return false;
5764 }
5765 if (!validateVGPRAlign(Inst)) {
5766 Error(IDLoc, "invalid register class: vgpr tuples must be 64 bit aligned");
5767 return false;
5768 }
5769 if (!validateDS(Inst, Operands)) {
5770 return false;
5771 }
5772
5773 if (!validateBLGP(Inst, Operands)) {
5774 return false;
5775 }
5776
5777 if (!validateDivScale(Inst)) {
5778 Error(IDLoc, "ABS not allowed in VOP3B instructions");
5779 return false;
5780 }
5781 if (!validateWaitCnt(Inst, Operands)) {
5782 return false;
5783 }
5784 if (!validateTFE(Inst, Operands)) {
5785 return false;
5786 }
5787 if (!validateWMMA(Inst, Operands)) {
5788 return false;
5789 }
5790 if (!validateMonitorSleep(Inst, Operands)) {
5791 return false;
5792 }
5793 if (!validateClusterBarrierIsFirst(Inst, Operands)) {
5794 return false;
5795 }
5796 if (!validateScaleSel(Inst, Operands)) {
5797 return false;
5798 }
5799
5800 return true;
5801}
5802
5804 const FeatureBitset &FBS,
5805 unsigned VariantID = 0);
5806
5807static bool AMDGPUCheckMnemonic(StringRef Mnemonic,
5808 const FeatureBitset &AvailableFeatures,
5809 unsigned VariantID);
5810
5811bool AMDGPUAsmParser::isSupportedMnemo(StringRef Mnemo,
5812 const FeatureBitset &FBS) {
5813 return isSupportedMnemo(Mnemo, FBS, getAllVariants());
5814}
5815
5816bool AMDGPUAsmParser::isSupportedMnemo(StringRef Mnemo,
5817 const FeatureBitset &FBS,
5818 ArrayRef<unsigned> Variants) {
5819 for (auto Variant : Variants) {
5820 if (AMDGPUCheckMnemonic(Mnemo, FBS, Variant))
5821 return true;
5822 }
5823
5824 return false;
5825}
5826
5827bool AMDGPUAsmParser::checkUnsupportedInstruction(StringRef Mnemo,
5828 SMLoc IDLoc) {
5829 FeatureBitset FBS = ComputeAvailableFeatures(getFeatureBits());
5830
5831 // Check if requested instruction variant is supported.
5832 if (isSupportedMnemo(Mnemo, FBS, getMatchedVariants()))
5833 return false;
5834
5835 // This instruction is not supported.
5836 // Clear any other pending errors because they are no longer relevant.
5837 getParser().clearPendingErrors();
5838
5839 // Requested instruction variant is not supported.
5840 // Check if any other variants are supported.
5841 StringRef VariantName = getMatchedVariantName();
5842 if (!VariantName.empty() && isSupportedMnemo(Mnemo, FBS)) {
5843 return Error(IDLoc, Twine(VariantName,
5844 " variant of this instruction is not supported"));
5845 }
5846
5847 // Check if this instruction may be used with a different wavesize.
5848 if (isGFX10Plus() && getFeatureBits()[AMDGPU::FeatureWavefrontSize64] &&
5849 !getFeatureBits()[AMDGPU::FeatureWavefrontSize32]) {
5850 // FIXME: Use getAvailableFeatures, and do not manually recompute
5851 FeatureBitset FeaturesWS32 = getFeatureBits();
5852 FeaturesWS32.flip(AMDGPU::FeatureWavefrontSize64)
5853 .flip(AMDGPU::FeatureWavefrontSize32);
5854 FeatureBitset AvailableFeaturesWS32 =
5855 ComputeAvailableFeatures(FeaturesWS32);
5856
5857 if (isSupportedMnemo(Mnemo, AvailableFeaturesWS32, getMatchedVariants()))
5858 return Error(IDLoc, "instruction requires wavesize=32");
5859 }
5860
5861 // Finally check if this instruction is supported on any other GPU.
5862 if (isSupportedMnemo(Mnemo, FeatureBitset().set())) {
5863 return Error(IDLoc, "instruction not supported on this GPU (" +
5864 getSTI().getCPU() + ")" + ": " + Mnemo);
5865 }
5866
5867 // Instruction not supported on any GPU. Probably a typo.
5868 std::string Suggestion = AMDGPUMnemonicSpellCheck(Mnemo, FBS);
5869 return Error(IDLoc, "invalid instruction" + Suggestion);
5870}
5871
5873 uint64_t InvalidOprIdx) {
5874 assert(InvalidOprIdx < Operands.size());
5875 const auto &Op = ((AMDGPUOperand &)*Operands[InvalidOprIdx]);
5876 if (Op.isToken() && InvalidOprIdx > 1) {
5877 const auto &PrevOp = ((AMDGPUOperand &)*Operands[InvalidOprIdx - 1]);
5878 return PrevOp.isToken() && PrevOp.getToken() == "::";
5879 }
5880 return false;
5881}
5882
5883bool AMDGPUAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
5885 MCStreamer &Out,
5886 uint64_t &ErrorInfo,
5887 bool MatchingInlineAsm) {
5888 MCInst Inst;
5889 Inst.setLoc(IDLoc);
5890 unsigned Result = Match_Success;
5891
5892 // Order match statuses from least to most specific and keep the most
5893 // specific one:
5894 // Match_MnemonicFail < Match_InvalidOperand < Match_MissingFeature
5895 auto atLeastAsSpecific = [](unsigned New, unsigned Cur) {
5896 auto rank = [](unsigned M) {
5897 return M == Match_MnemonicFail ? 1
5898 : M == Match_InvalidOperand ? 2
5899 : M == Match_MissingFeature ? 3
5900 : 0; // Match_Success sentinel
5901 };
5902 return rank(New) >= rank(Cur);
5903 };
5904
5905 for (auto Variant : getMatchedVariants()) {
5906 uint64_t EI;
5907 auto R =
5908 MatchInstructionImpl(Operands, Inst, EI, MatchingInlineAsm, Variant);
5909 if (R == Match_Success || atLeastAsSpecific(R, Result)) {
5910 Result = R;
5911 ErrorInfo = EI;
5912 }
5913 if (R == Match_Success)
5914 break;
5915 }
5916
5917 if (Result == Match_Success) {
5918 if (!validateInstruction(Inst, IDLoc, Operands)) {
5919 return true;
5920 }
5921 emitTargetDirective();
5922 Out.emitInstruction(Inst, getSTI());
5923 // Record for kernel prologue checking.
5924 OpcodeStream.push_back(Inst.getOpcode());
5925 return false;
5926 }
5927
5928 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
5929 if (checkUnsupportedInstruction(Mnemo, IDLoc)) {
5930 return true;
5931 }
5932
5933 switch (Result) {
5934 default:
5935 break;
5936 case Match_MissingFeature:
5937 // It has been verified that the specified instruction
5938 // mnemonic is valid. A match was found but it requires
5939 // features which are not supported on this GPU.
5940 return Error(IDLoc, "operands are not valid for this GPU or mode");
5941
5942 case Match_InvalidOperand: {
5943 SMLoc ErrorLoc = IDLoc;
5944 if (ErrorInfo != ~0ULL) {
5945 if (ErrorInfo >= Operands.size()) {
5946 return Error(IDLoc, "too few operands for instruction");
5947 }
5948 AMDGPUOperand &ErrorOp = (AMDGPUOperand &)*Operands[ErrorInfo];
5949 ErrorLoc = ErrorOp.getStartLoc();
5950 if (ErrorLoc == SMLoc())
5951 ErrorLoc = IDLoc;
5952
5953 if (isInvalidVOPDY(Operands, ErrorInfo))
5954 return Error(ErrorLoc, "invalid VOPDY instruction");
5955 }
5956 return Error(ErrorLoc, "invalid operand for instruction");
5957 }
5958
5959 case Match_MnemonicFail:
5960 llvm_unreachable("Invalid instructions should have been handled already");
5961 }
5962 llvm_unreachable("Implement any new match types added!");
5963}
5964
5965bool AMDGPUAsmParser::ParseAsAbsoluteExpression(uint32_t &Ret) {
5966 int64_t Tmp = -1;
5967 if (!isToken(AsmToken::Integer) && !isToken(AsmToken::Identifier)) {
5968 return true;
5969 }
5970 if (getParser().parseAbsoluteExpression(Tmp)) {
5971 return true;
5972 }
5973 Ret = static_cast<uint32_t>(Tmp);
5974 return false;
5975}
5976
5977bool AMDGPUAsmParser::ParseDirectiveAMDGCNTarget() {
5978 if (!getSTI().getTargetTriple().isAMDGCN())
5979 return TokError("directive only supported for amdgcn architecture");
5980
5981 std::string TargetIDDirective;
5982 SMLoc TargetStart = getTok().getLoc();
5983 if (getParser().parseEscapedString(TargetIDDirective))
5984 return true;
5985
5986 std::optional<AMDGPU::TargetID> MaybeParsed =
5987 AMDGPU::TargetID::parseTargetIDString(TargetIDDirective);
5988 if (!MaybeParsed)
5989 return getParser().Error(TargetStart,
5990 "malformed target id '" + TargetIDDirective + "'");
5991
5992 const AMDGPU::TargetID &ParsedTargetID = *MaybeParsed;
5993 const Triple &TT = getSTI().getTargetTriple();
5994
5995 // The processor named in the target id must be covered by the triple's
5996 // subarch.
5997 if (!AMDGPU::isCPUValidForSubArch(TT.getSubArch(),
5998 ParsedTargetID.getGPUKind())) {
5999 return getParser().Error(
6000 TargetStart, "target id '" + TargetIDDirective +
6001 "' specifies a processor that is not valid for "
6002 "subarch '" +
6003 TT.getArchName() + "'");
6004 }
6005
6006 const std::optional<AMDGPU::TargetID> &CurrentTargetID =
6007 getTargetStreamer().getTargetID();
6008
6009 Triple DirectiveTriple(ParsedTargetID.getTargetTripleString());
6010 const Triple &STITriple = getSTI().getTargetTriple();
6011 if (!DirectiveTriple.isCompatibleWith(STITriple)) {
6012 return getParser().Error(
6013 TargetStart, ".amdgcn_target " + Twine(ParsedTargetID.toString()) +
6014 " is incompatible with " +
6015 Twine(CurrentTargetID->toString()));
6016 }
6017
6018 // Error if the ISA version doesn't match
6019 StringRef DirectiveProcessor =
6020 AMDGPU::getArchNameAMDGCN(ParsedTargetID.getGPUKind());
6021 AMDGPU::IsaVersion DirectiveISA = AMDGPU::getIsaVersion(DirectiveProcessor);
6022 if (DirectiveISA != ISA) {
6023 return getParser().Error(TargetStart,
6024 ".amdgcn_target directive processor " +
6025 Twine(DirectiveProcessor) +
6026 " does not match the specified processor " +
6027 Twine(getSTI().getCPU()));
6028 }
6029
6030 // Warn if sramecc or xnack mismatch. These do not change the encoding.
6032 ParsedTargetID.getXnackSetting(),
6033 CurrentTargetID->getXnackSetting())) {
6034 Warning(TargetStart,
6035 ".amdgcn_target directive has conflicting xnack settings");
6036 }
6038 ParsedTargetID.getSramEccSetting(),
6039 CurrentTargetID->getSramEccSetting())) {
6040 Warning(TargetStart,
6041 ".amdgcn_target directive has conflicting sramecc settings");
6042 }
6043
6044 // Update the target streamer's TargetID with settings from the directive.
6045 // We don't update the MCSubtargetInfo because we've already validated
6046 // that the directive matches the command-line CPU.
6047 getTargetStreamer().getTargetID()->setXnackSetting(
6048 ParsedTargetID.getXnackSetting());
6049 getTargetStreamer().getTargetID()->setSramEccSetting(
6050 ParsedTargetID.getSramEccSetting());
6051
6052 return false;
6053}
6054
6055bool AMDGPUAsmParser::OutOfRangeError(SMRange Range) {
6056 return Error(Range.Start, "value out of range", Range);
6057}
6058
6059bool AMDGPUAsmParser::calculateGPRBlocks(
6060 const FeatureBitset &Features, const MCExpr *VCCUsed,
6061 const MCExpr *FlatScrUsed, bool XNACKUsed,
6062 std::optional<bool> EnableWavefrontSize32, const MCExpr *NextFreeVGPR,
6063 SMRange VGPRRange, const MCExpr *NextFreeSGPR, SMRange SGPRRange,
6064 const MCExpr *&VGPRBlocks, const MCExpr *&SGPRBlocks) {
6065 // TODO(scott.linder): These calculations are duplicated from
6066 // AMDGPUAsmPrinter::getSIProgramInfo and could be unified.
6067 MCContext &Ctx = getContext();
6068
6069 const MCExpr *NumSGPRs = NextFreeSGPR;
6070 int64_t EvaluatedSGPRs;
6071
6072 if (ISA.Major >= 10)
6074 else {
6075 unsigned MaxAddressableNumSGPRs = AMDGPU::getAddressableNumSGPRs(Gfx);
6076
6077 if (NumSGPRs->evaluateAsAbsolute(EvaluatedSGPRs) && ISA.Major >= 8 &&
6078 !Features.test(FeatureSGPRInitBug) &&
6079 static_cast<uint64_t>(EvaluatedSGPRs) > MaxAddressableNumSGPRs)
6080 return OutOfRangeError(SGPRRange);
6081
6082 const MCExpr *ExtraSGPRs =
6083 AMDGPUMCExpr::createExtraSGPRs(VCCUsed, FlatScrUsed, XNACKUsed, Ctx);
6084 NumSGPRs = MCBinaryExpr::createAdd(NumSGPRs, ExtraSGPRs, Ctx);
6085
6086 if (NumSGPRs->evaluateAsAbsolute(EvaluatedSGPRs) &&
6087 (ISA.Major <= 7 || Features.test(FeatureSGPRInitBug)) &&
6088 static_cast<uint64_t>(EvaluatedSGPRs) > MaxAddressableNumSGPRs)
6089 return OutOfRangeError(SGPRRange);
6090
6091 if (Features.test(FeatureSGPRInitBug))
6092 NumSGPRs =
6094 }
6095
6096 // The MCExpr equivalent of getNumSGPRBlocks/getNumVGPRBlocks:
6097 // (alignTo(max(1u, NumGPR), GPREncodingGranule) / GPREncodingGranule) - 1
6098 auto GetNumGPRBlocks = [&Ctx](const MCExpr *NumGPR,
6099 unsigned Granule) -> const MCExpr * {
6100 const MCExpr *OneConst = MCConstantExpr::create(1ul, Ctx);
6101 const MCExpr *GranuleConst = MCConstantExpr::create(Granule, Ctx);
6102 const MCExpr *MaxNumGPR = AMDGPUMCExpr::createMax({NumGPR, OneConst}, Ctx);
6103 const MCExpr *AlignToGPR =
6104 AMDGPUMCExpr::createAlignTo(MaxNumGPR, GranuleConst, Ctx);
6105 const MCExpr *DivGPR =
6106 MCBinaryExpr::createDiv(AlignToGPR, GranuleConst, Ctx);
6107 const MCExpr *SubGPR = MCBinaryExpr::createSub(DivGPR, OneConst, Ctx);
6108 return SubGPR;
6109 };
6110
6111 VGPRBlocks = GetNumGPRBlocks(
6112 NextFreeVGPR,
6113 IsaInfo::getVGPREncodingGranule(getSTI(), EnableWavefrontSize32));
6114 SGPRBlocks =
6115 GetNumGPRBlocks(NumSGPRs, IsaInfo::getSGPREncodingGranule(getSTI()));
6116
6117 return false;
6118}
6119
6120bool AMDGPUAsmParser::ParseDirectiveAMDHSAKernel() {
6121 if (!getSTI().getTargetTriple().isAMDGCN())
6122 return TokError("directive only supported for amdgcn architecture");
6123
6124 if (!isHsaAbi(getSTI()))
6125 return TokError("directive only supported for amdhsa OS");
6126
6127 StringRef KernelName;
6128 if (getParser().parseIdentifier(KernelName))
6129 return true;
6130
6131 // Remember the kernel name so its prologue can be checked at end of file.
6132 // The matching label may have been parsed already or may follow later.
6133 AMDHSAKernelSymbols.insert(getContext().getOrCreateSymbol(KernelName));
6134
6135 AMDGPU::MCKernelDescriptor KD =
6137 &getSTI(), getContext());
6138
6139 StringSet<> Seen;
6140
6141 const MCExpr *ZeroExpr = MCConstantExpr::create(0, getContext());
6142 const MCExpr *OneExpr = MCConstantExpr::create(1, getContext());
6143
6144 SMRange VGPRRange;
6145 const MCExpr *NextFreeVGPR = ZeroExpr;
6146 const MCExpr *AccumOffset = MCConstantExpr::create(0, getContext());
6147 const MCExpr *NamedBarCnt = ZeroExpr;
6148 uint64_t SharedVGPRCount = 0;
6149 uint64_t PreloadLength = 0;
6150 uint64_t PreloadOffset = 0;
6151 SMRange SGPRRange;
6152 const MCExpr *NextFreeSGPR = ZeroExpr;
6153
6154 // Count the number of user SGPRs implied from the enabled feature bits.
6155 unsigned ImpliedUserSGPRCount = 0;
6156
6157 // Track if the asm explicitly contains the directive for the user SGPR
6158 // count.
6159 std::optional<unsigned> ExplicitUserSGPRCount;
6160 const MCExpr *ReserveVCC = OneExpr;
6161 const MCExpr *ReserveFlatScr = OneExpr;
6162 std::optional<bool> EnableWavefrontSize32;
6163
6164 while (true) {
6165 while (trySkipToken(AsmToken::EndOfStatement))
6166 ;
6167
6168 StringRef ID;
6169 SMRange IDRange = getTok().getLocRange();
6170 if (!parseId(ID, "expected .amdhsa_ directive or .end_amdhsa_kernel"))
6171 return true;
6172
6173 if (ID == ".end_amdhsa_kernel")
6174 break;
6175
6176 if (!Seen.insert(ID).second)
6177 return TokError(".amdhsa_ directives cannot be repeated");
6178
6179 SMLoc ValStart = getLoc();
6180 const MCExpr *ExprVal;
6181 if (getParser().parseExpression(ExprVal))
6182 return true;
6183 SMLoc ValEnd = getLoc();
6184 SMRange ValRange = SMRange(ValStart, ValEnd);
6185
6186 int64_t IVal = 0;
6187 uint64_t Val = IVal;
6188 bool EvaluatableExpr;
6189 if ((EvaluatableExpr = ExprVal->evaluateAsAbsolute(IVal))) {
6190 if (IVal < 0)
6191 return OutOfRangeError(ValRange);
6192 Val = IVal;
6193 }
6194
6195#define PARSE_BITS_ENTRY(FIELD, ENTRY, VALUE, RANGE) \
6196 if (!isUInt<ENTRY##_WIDTH>(Val)) \
6197 return OutOfRangeError(RANGE); \
6198 AMDGPU::MCKernelDescriptor::bits_set(FIELD, VALUE, ENTRY##_SHIFT, ENTRY, \
6199 getContext());
6200
6201// Some fields use the parsed value immediately which requires the expression to
6202// be solvable.
6203#define EXPR_RESOLVE_OR_ERROR(RESOLVED) \
6204 if (!(RESOLVED)) \
6205 return Error(IDRange.Start, "directive should have resolvable expression", \
6206 IDRange);
6207
6208 if (ID == ".amdhsa_group_segment_fixed_size") {
6210 CHAR_BIT>(Val))
6211 return OutOfRangeError(ValRange);
6212 KD.group_segment_fixed_size = ExprVal;
6213 } else if (ID == ".amdhsa_private_segment_fixed_size") {
6215 CHAR_BIT>(Val))
6216 return OutOfRangeError(ValRange);
6217 KD.private_segment_fixed_size = ExprVal;
6218 } else if (ID == ".amdhsa_kernarg_size") {
6219 if (!isUInt<sizeof(kernel_descriptor_t::kernarg_size) * CHAR_BIT>(Val))
6220 return OutOfRangeError(ValRange);
6221 KD.kernarg_size = ExprVal;
6222 } else if (ID == ".amdhsa_user_sgpr_count") {
6223 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6224 ExplicitUserSGPRCount = Val;
6225 } else if (ID == ".amdhsa_user_sgpr_private_segment_buffer") {
6226 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6228 return Error(IDRange.Start,
6229 "directive is not supported with architected flat scratch",
6230 IDRange);
6232 KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER,
6233 ExprVal, ValRange);
6234 if (Val)
6235 ImpliedUserSGPRCount += 4;
6236 } else if (ID == ".amdhsa_user_sgpr_kernarg_preload_length") {
6237 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6238 if (!hasKernargPreload())
6239 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6240
6241 if (Val > getMaxNumUserSGPRs())
6242 return OutOfRangeError(ValRange);
6243 PARSE_BITS_ENTRY(KD.kernarg_preload, KERNARG_PRELOAD_SPEC_LENGTH, ExprVal,
6244 ValRange);
6245 if (Val) {
6246 ImpliedUserSGPRCount += Val;
6247 PreloadLength = Val;
6248 }
6249 } else if (ID == ".amdhsa_user_sgpr_kernarg_preload_offset") {
6250 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6251 if (!hasKernargPreload())
6252 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6253
6254 if (Val >= 1024)
6255 return OutOfRangeError(ValRange);
6256 PARSE_BITS_ENTRY(KD.kernarg_preload, KERNARG_PRELOAD_SPEC_OFFSET, ExprVal,
6257 ValRange);
6258 if (Val)
6259 PreloadOffset = Val;
6260 } else if (ID == ".amdhsa_user_sgpr_dispatch_ptr") {
6261 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6263 KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR, ExprVal,
6264 ValRange);
6265 if (Val)
6266 ImpliedUserSGPRCount += 2;
6267 } else if (ID == ".amdhsa_user_sgpr_queue_ptr") {
6268 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6270 KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR, ExprVal,
6271 ValRange);
6272 if (Val)
6273 ImpliedUserSGPRCount += 2;
6274 } else if (ID == ".amdhsa_user_sgpr_kernarg_segment_ptr") {
6275 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6277 KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR,
6278 ExprVal, ValRange);
6279 if (Val)
6280 ImpliedUserSGPRCount += 2;
6281 } else if (ID == ".amdhsa_user_sgpr_dispatch_id") {
6282 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6284 KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID, ExprVal,
6285 ValRange);
6286 if (Val)
6287 ImpliedUserSGPRCount += 2;
6288 } else if (ID == ".amdhsa_user_sgpr_flat_scratch_init") {
6290 return Error(IDRange.Start,
6291 "directive is not supported with architected flat scratch",
6292 IDRange);
6293 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6295 KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT,
6296 ExprVal, ValRange);
6297 if (Val)
6298 ImpliedUserSGPRCount += 2;
6299 } else if (ID == ".amdhsa_user_sgpr_private_segment_size") {
6300 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6302 KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE,
6303 ExprVal, ValRange);
6304 if (Val)
6305 ImpliedUserSGPRCount += 1;
6306 } else if (ID == ".amdhsa_wavefront_size32") {
6307 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6308 if (ISA.Major < 10)
6309 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6310 EnableWavefrontSize32 = Val;
6312 KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32, ExprVal,
6313 ValRange);
6314 } else if (ID == ".amdhsa_uses_dynamic_stack") {
6316 KERNEL_CODE_PROPERTY_USES_DYNAMIC_STACK, ExprVal,
6317 ValRange);
6318 } else if (ID == ".amdhsa_system_sgpr_private_segment_wavefront_offset") {
6320 return Error(IDRange.Start,
6321 "directive is not supported with architected flat scratch",
6322 IDRange);
6324 COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT, ExprVal,
6325 ValRange);
6326 } else if (ID == ".amdhsa_enable_private_segment") {
6328 return Error(
6329 IDRange.Start,
6330 "directive is not supported without architected flat scratch",
6331 IDRange);
6333 COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT, ExprVal,
6334 ValRange);
6335 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_x") {
6337 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_X, ExprVal,
6338 ValRange);
6339 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_y") {
6341 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Y, ExprVal,
6342 ValRange);
6343 } else if (ID == ".amdhsa_system_sgpr_workgroup_id_z") {
6345 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Z, ExprVal,
6346 ValRange);
6347 } else if (ID == ".amdhsa_system_sgpr_workgroup_info") {
6349 COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_INFO, ExprVal,
6350 ValRange);
6351 } else if (ID == ".amdhsa_system_vgpr_workitem_id") {
6353 COMPUTE_PGM_RSRC2_ENABLE_VGPR_WORKITEM_ID, ExprVal,
6354 ValRange);
6355 } else if (ID == ".amdhsa_next_free_vgpr") {
6356 VGPRRange = ValRange;
6357 NextFreeVGPR = ExprVal;
6358 } else if (ID == ".amdhsa_next_free_sgpr") {
6359 SGPRRange = ValRange;
6360 NextFreeSGPR = ExprVal;
6361 } else if (ID == ".amdhsa_accum_offset") {
6362 if (!isGFX90A())
6363 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6364 AccumOffset = ExprVal;
6365 } else if (ID == ".amdhsa_named_barrier_count") {
6366 if (!isGFX1250Plus())
6367 return Error(IDRange.Start, "directive requires gfx1250+", IDRange);
6368 NamedBarCnt = ExprVal;
6369 } else if (ID == ".amdhsa_reserve_vcc") {
6370 if (EvaluatableExpr && !isUInt<1>(Val))
6371 return OutOfRangeError(ValRange);
6372 ReserveVCC = ExprVal;
6373 } else if (ID == ".amdhsa_reserve_flat_scratch") {
6374 if (ISA.Major < 7)
6375 return Error(IDRange.Start, "directive requires gfx7+", IDRange);
6377 return Error(IDRange.Start,
6378 "directive is not supported with architected flat scratch",
6379 IDRange);
6380 if (EvaluatableExpr && !isUInt<1>(Val))
6381 return OutOfRangeError(ValRange);
6382 ReserveFlatScr = ExprVal;
6383 } else if (ID == ".amdhsa_reserve_xnack_mask") {
6384 if (ISA.Major < 8)
6385 return Error(IDRange.Start, "directive requires gfx8+", IDRange);
6386 if (!isUInt<1>(Val))
6387 return OutOfRangeError(ValRange);
6388 bool XnackOn = getTargetStreamer().getTargetID()->isXnackOnOrAny();
6389 if (Val != XnackOn) {
6390 return getParser().Error(
6391 IDRange.Start,
6392 ".amdhsa_reserve_xnack_mask does not match target id", IDRange);
6393 }
6394 } else if (ID == ".amdhsa_float_round_mode_32") {
6396 COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_32, ExprVal,
6397 ValRange);
6398 } else if (ID == ".amdhsa_float_round_mode_16_64") {
6400 COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_16_64, ExprVal,
6401 ValRange);
6402 } else if (ID == ".amdhsa_float_denorm_mode_32") {
6404 COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_32, ExprVal,
6405 ValRange);
6406 } else if (ID == ".amdhsa_float_denorm_mode_16_64") {
6408 COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_16_64, ExprVal,
6409 ValRange);
6410 } else if (ID == ".amdhsa_dx10_clamp") {
6411 if (!getSTI().hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode))
6412 return Error(IDRange.Start, "directive unsupported on gfx1170+",
6413 IDRange);
6415 COMPUTE_PGM_RSRC1_GFX6_GFX11_ENABLE_DX10_CLAMP, ExprVal,
6416 ValRange);
6417 } else if (ID == ".amdhsa_ieee_mode") {
6418 if (!getSTI().hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode))
6419 return Error(IDRange.Start, "directive unsupported on gfx1170+",
6420 IDRange);
6422 COMPUTE_PGM_RSRC1_GFX6_GFX11_ENABLE_IEEE_MODE, ExprVal,
6423 ValRange);
6424 } else if (ID == ".amdhsa_fp16_overflow") {
6425 if (ISA.Major < 9)
6426 return Error(IDRange.Start, "directive requires gfx9+", IDRange);
6428 COMPUTE_PGM_RSRC1_GFX9_PLUS_FP16_OVFL, ExprVal,
6429 ValRange);
6430 } else if (ID == ".amdhsa_tg_split") {
6431 if (!isGFX90A())
6432 return Error(IDRange.Start, "directive requires gfx90a+", IDRange);
6433 PARSE_BITS_ENTRY(KD.compute_pgm_rsrc3, COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
6434 ExprVal, ValRange);
6435 } else if (ID == ".amdhsa_workgroup_processor_mode") {
6436 if (!supportsWGP(getSTI()))
6437 return Error(IDRange.Start,
6438 "directive unsupported on " + getSTI().getCPU(), IDRange);
6440 COMPUTE_PGM_RSRC1_GFX10_PLUS_WGP_MODE, ExprVal,
6441 ValRange);
6442 } else if (ID == ".amdhsa_memory_ordered") {
6443 if (ISA.Major < 10)
6444 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6446 COMPUTE_PGM_RSRC1_GFX10_PLUS_MEM_ORDERED, ExprVal,
6447 ValRange);
6448 } else if (ID == ".amdhsa_forward_progress") {
6449 if (ISA.Major < 10)
6450 return Error(IDRange.Start, "directive requires gfx10+", IDRange);
6452 COMPUTE_PGM_RSRC1_GFX10_PLUS_FWD_PROGRESS, ExprVal,
6453 ValRange);
6454 } else if (ID == ".amdhsa_shared_vgpr_count") {
6455 EXPR_RESOLVE_OR_ERROR(EvaluatableExpr);
6456 if (ISA.Major < 10 || ISA.Major >= 12)
6457 return Error(IDRange.Start, "directive requires gfx10 or gfx11",
6458 IDRange);
6459 SharedVGPRCount = Val;
6461 COMPUTE_PGM_RSRC3_GFX10_GFX11_SHARED_VGPR_COUNT, ExprVal,
6462 ValRange);
6463 } else if (ID == ".amdhsa_inst_pref_size") {
6464 if (ISA.Major < 11)
6465 return Error(IDRange.Start, "directive requires gfx11+", IDRange);
6466 if (ISA.Major == 11) {
6468 COMPUTE_PGM_RSRC3_GFX11_INST_PREF_SIZE, ExprVal,
6469 ValRange);
6470 } else {
6472 COMPUTE_PGM_RSRC3_GFX12_PLUS_INST_PREF_SIZE, ExprVal,
6473 ValRange);
6474 }
6475 } else if (ID == ".amdhsa_exception_fp_ieee_invalid_op") {
6478 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION,
6479 ExprVal, ValRange);
6480 } else if (ID == ".amdhsa_exception_fp_denorm_src") {
6482 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE,
6483 ExprVal, ValRange);
6484 } else if (ID == ".amdhsa_exception_fp_ieee_div_zero") {
6487 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO,
6488 ExprVal, ValRange);
6489 } else if (ID == ".amdhsa_exception_fp_ieee_overflow") {
6491 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW,
6492 ExprVal, ValRange);
6493 } else if (ID == ".amdhsa_exception_fp_ieee_underflow") {
6495 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW,
6496 ExprVal, ValRange);
6497 } else if (ID == ".amdhsa_exception_fp_ieee_inexact") {
6499 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT,
6500 ExprVal, ValRange);
6501 } else if (ID == ".amdhsa_exception_int_div_zero") {
6503 COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_INT_DIVIDE_BY_ZERO,
6504 ExprVal, ValRange);
6505 } else if (ID == ".amdhsa_round_robin_scheduling") {
6506 if (ISA.Major < 12)
6507 return Error(IDRange.Start, "directive requires gfx12+", IDRange);
6509 COMPUTE_PGM_RSRC1_GFX12_PLUS_ENABLE_WG_RR_EN, ExprVal,
6510 ValRange);
6511 } else {
6512 return Error(IDRange.Start, "unknown .amdhsa_kernel directive", IDRange);
6513 }
6514
6515#undef PARSE_BITS_ENTRY
6516 }
6517
6518 if (!Seen.contains(".amdhsa_next_free_vgpr"))
6519 return TokError(".amdhsa_next_free_vgpr directive is required");
6520
6521 if (!Seen.contains(".amdhsa_next_free_sgpr"))
6522 return TokError(".amdhsa_next_free_sgpr directive is required");
6523
6524 unsigned UserSGPRCount = ExplicitUserSGPRCount.value_or(ImpliedUserSGPRCount);
6525 if (UserSGPRCount > getMaxNumUserSGPRs())
6526 return TokError("too many user SGPRs enabled, found " +
6527 Twine(UserSGPRCount) + ", but only " +
6528 Twine(getMaxNumUserSGPRs()) + " are supported.");
6529
6530 // Consider the case where the total number of UserSGPRs with trailing
6531 // allocated preload SGPRs, is greater than the number of explicitly
6532 // referenced SGPRs.
6533 if (PreloadLength) {
6534 MCContext &Ctx = getContext();
6535 NextFreeSGPR = AMDGPUMCExpr::createMax(
6536 {NextFreeSGPR, MCConstantExpr::create(UserSGPRCount, Ctx)}, Ctx);
6537 }
6538
6539 const MCExpr *VGPRBlocks;
6540 const MCExpr *SGPRBlocks;
6541 if (calculateGPRBlocks(getFeatureBits(), ReserveVCC, ReserveFlatScr,
6542 getTargetStreamer().getTargetID()->isXnackOnOrAny(),
6543 EnableWavefrontSize32, NextFreeVGPR, VGPRRange,
6544 NextFreeSGPR, SGPRRange, VGPRBlocks, SGPRBlocks))
6545 return true;
6546
6547 int64_t EvaluatedVGPRBlocks;
6548 bool VGPRBlocksEvaluatable =
6549 VGPRBlocks->evaluateAsAbsolute(EvaluatedVGPRBlocks);
6550 if (VGPRBlocksEvaluatable &&
6552 static_cast<uint64_t>(EvaluatedVGPRBlocks))) {
6553 return OutOfRangeError(VGPRRange);
6554 }
6556 KD.compute_pgm_rsrc1, VGPRBlocks,
6557 COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT_SHIFT,
6558 COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT, getContext());
6559
6560 int64_t EvaluatedSGPRBlocks;
6561 if (SGPRBlocks->evaluateAsAbsolute(EvaluatedSGPRBlocks) &&
6563 static_cast<uint64_t>(EvaluatedSGPRBlocks)))
6564 return OutOfRangeError(SGPRRange);
6566 KD.compute_pgm_rsrc1, SGPRBlocks,
6567 COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT_SHIFT,
6568 COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT, getContext());
6569
6570 if (ExplicitUserSGPRCount && ImpliedUserSGPRCount > *ExplicitUserSGPRCount)
6571 return TokError("amdgpu_user_sgpr_count smaller than implied by "
6572 "enabled user SGPRs");
6573
6574 if (isGFX1250Plus()) {
6577 MCConstantExpr::create(UserSGPRCount, getContext()),
6578 COMPUTE_PGM_RSRC2_GFX125_USER_SGPR_COUNT_SHIFT,
6579 COMPUTE_PGM_RSRC2_GFX125_USER_SGPR_COUNT, getContext());
6580 } else {
6583 MCConstantExpr::create(UserSGPRCount, getContext()),
6584 COMPUTE_PGM_RSRC2_GFX6_GFX120_USER_SGPR_COUNT_SHIFT,
6585 COMPUTE_PGM_RSRC2_GFX6_GFX120_USER_SGPR_COUNT, getContext());
6586 }
6587
6588 int64_t IVal = 0;
6589 if (!KD.kernarg_size->evaluateAsAbsolute(IVal))
6590 return TokError("Kernarg size should be resolvable");
6591 uint64_t kernarg_size = IVal;
6592 if (PreloadLength && kernarg_size &&
6593 (PreloadLength * 4 + PreloadOffset * 4 > kernarg_size))
6594 return TokError("Kernarg preload length + offset is larger than the "
6595 "kernarg segment size");
6596
6597 if (isGFX90A()) {
6598 if (!Seen.contains(".amdhsa_accum_offset"))
6599 return TokError(".amdhsa_accum_offset directive is required");
6600 int64_t EvaluatedAccum;
6601 bool AccumEvaluatable = AccumOffset->evaluateAsAbsolute(EvaluatedAccum);
6602 uint64_t UEvaluatedAccum = EvaluatedAccum;
6603 if (AccumEvaluatable &&
6604 (UEvaluatedAccum < 4 || UEvaluatedAccum > 256 || (UEvaluatedAccum & 3)))
6605 return TokError("accum_offset should be in range [4..256] in "
6606 "increments of 4");
6607
6608 int64_t EvaluatedNumVGPR;
6609 if (NextFreeVGPR->evaluateAsAbsolute(EvaluatedNumVGPR) &&
6610 AccumEvaluatable &&
6611 UEvaluatedAccum >
6612 alignTo(std::max((uint64_t)1, (uint64_t)EvaluatedNumVGPR), 4))
6613 return TokError("accum_offset exceeds total VGPR allocation");
6614 const MCExpr *AdjustedAccum = MCBinaryExpr::createSub(
6616 AccumOffset, MCConstantExpr::create(4, getContext()), getContext()),
6619 COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET_SHIFT,
6620 COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
6621 getContext());
6622 }
6623
6624 if (isGFX1250Plus())
6626 COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT_SHIFT,
6627 COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT,
6628 getContext());
6629
6630 if (ISA.Major >= 10 && ISA.Major < 12) {
6631 // SharedVGPRCount < 16 checked by PARSE_ENTRY_BITS
6632 if (SharedVGPRCount && EnableWavefrontSize32 && *EnableWavefrontSize32) {
6633 return TokError("shared_vgpr_count directive not valid on "
6634 "wavefront size 32");
6635 }
6636
6637 if (VGPRBlocksEvaluatable &&
6638 (SharedVGPRCount * 2 + static_cast<uint64_t>(EvaluatedVGPRBlocks) >
6639 63)) {
6640 return TokError("shared_vgpr_count*2 + "
6641 "compute_pgm_rsrc1.GRANULATED_WORKITEM_VGPR_COUNT cannot "
6642 "exceed 63\n");
6643 }
6644 }
6645
6646 emitTargetDirective();
6647 getTargetStreamer().EmitAmdhsaKernelDescriptor(getSTI(), KernelName, KD,
6648 NextFreeVGPR, NextFreeSGPR,
6649 ReserveVCC, ReserveFlatScr);
6650 return false;
6651}
6652
6653bool AMDGPUAsmParser::ParseDirectiveAMDHSACodeObjectVersion() {
6654 uint32_t Version;
6655 if (ParseAsAbsoluteExpression(Version))
6656 return true;
6657
6658 getTargetStreamer().EmitDirectiveAMDHSACodeObjectVersion(Version);
6659 emitTargetDirective();
6660 return false;
6661}
6662
6663bool AMDGPUAsmParser::ParseAMDKernelCodeTValue(StringRef ID,
6664 AMDGPUMCKernelCodeT &C) {
6665 // max_scratch_backing_memory_byte_size is deprecated. Ignore it while parsing
6666 // assembly for backwards compatibility.
6667 if (ID == "max_scratch_backing_memory_byte_size") {
6668 Parser.eatToEndOfStatement();
6669 return false;
6670 }
6671
6672 SmallString<40> ErrStr;
6673 raw_svector_ostream Err(ErrStr);
6674 if (!C.ParseKernelCodeT(ID, getParser(), Err)) {
6675 return TokError(Err.str());
6676 }
6677 Lex();
6678
6679 if (ID == "enable_wavefront_size32") {
6680 if (C.code_properties & AMD_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32) {
6681 if (!isGFX10Plus())
6682 return TokError("enable_wavefront_size32=1 is only allowed on GFX10+");
6683 if (!isWave32())
6684 return TokError("enable_wavefront_size32=1 requires +WavefrontSize32");
6685 } else {
6686 if (!isWave64())
6687 return TokError("enable_wavefront_size32=0 requires +WavefrontSize64");
6688 }
6689 }
6690
6691 if (ID == "wavefront_size") {
6692 if (C.wavefront_size == 5) {
6693 if (!isGFX10Plus())
6694 return TokError("wavefront_size=5 is only allowed on GFX10+");
6695 if (!isWave32())
6696 return TokError("wavefront_size=5 requires +WavefrontSize32");
6697 } else if (C.wavefront_size == 6) {
6698 if (!isWave64())
6699 return TokError("wavefront_size=6 requires +WavefrontSize64");
6700 }
6701 }
6702
6703 return false;
6704}
6705
6706bool AMDGPUAsmParser::ParseDirectiveAMDKernelCodeT() {
6707 AMDGPUMCKernelCodeT KernelCode;
6708 KernelCode.initDefault(getSTI(), getContext());
6709
6710 while (true) {
6711 // Lex EndOfStatement. This is in a while loop, because lexing a comment
6712 // will set the current token to EndOfStatement.
6713 while (trySkipToken(AsmToken::EndOfStatement))
6714 ;
6715
6716 StringRef ID;
6717 if (!parseId(ID, "expected value identifier or .end_amd_kernel_code_t"))
6718 return true;
6719
6720 if (ID == ".end_amd_kernel_code_t")
6721 break;
6722
6723 if (ParseAMDKernelCodeTValue(ID, KernelCode))
6724 return true;
6725 }
6726
6727 KernelCode.validate(&getSTI(), getContext());
6728 getTargetStreamer().EmitAMDKernelCodeT(KernelCode);
6729
6730 return false;
6731}
6732
6733bool AMDGPUAsmParser::ParseDirectiveAMDGPUHsaKernel() {
6734 StringRef KernelName;
6735 if (!parseId(KernelName, "expected symbol name"))
6736 return true;
6737
6738 getTargetStreamer().EmitAMDGPUSymbolType(KernelName,
6740
6741 KernelScope.initialize(getContext());
6742 return false;
6743}
6744
6745bool AMDGPUAsmParser::ParseDirectiveISAVersion() {
6746 if (!getSTI().getTargetTriple().isAMDGCN()) {
6747 return Error(getLoc(),
6748 ".amd_amdgpu_isa directive is not available on non-amdgcn "
6749 "architectures");
6750 }
6751
6752 StringRef TargetIDDirective = getLexer().getTok().getStringContents();
6753
6754 std::optional<AMDGPU::TargetID> MaybeParsed =
6755 AMDGPU::TargetID::parseTargetIDString(TargetIDDirective);
6756 if (!MaybeParsed)
6757 return Error(getParser().getTok().getLoc(),
6758 "malformed target id '" + TargetIDDirective + "'");
6759
6760 const AMDGPU::TargetID &ParsedTargetID = *MaybeParsed;
6761 const Triple &TT = getSTI().getTargetTriple();
6762
6763 // The processor named in the target id must be covered by the triple's
6764 // subarch.
6765 if (!AMDGPU::isCPUValidForSubArch(TT.getSubArch(),
6766 ParsedTargetID.getGPUKind())) {
6767 return Error(getParser().getTok().getLoc(),
6768 "target id '" + TargetIDDirective +
6769 "' specifies a processor that is not valid for subarch '" +
6770 TT.getArchName() + "'");
6771 }
6772
6773 const std::optional<AMDGPU::TargetID> &CurrentTargetID =
6774 getTargetStreamer().getTargetID();
6775
6776 Triple DirectiveTriple(ParsedTargetID.getTargetTripleString());
6777 const Triple &STITriple = getSTI().getTargetTriple();
6778 if (!DirectiveTriple.isCompatibleWith(STITriple)) {
6779 return Error(getParser().getTok().getLoc(),
6780 ".amd_amdgpu_isa " + Twine(ParsedTargetID.toString()) +
6781 " is incompatible with " +
6782 Twine(CurrentTargetID->toString()));
6783 }
6784
6785 // Error if the ISA version doesn't match
6786 StringRef DirectiveProcessor =
6787 AMDGPU::getArchNameAMDGCN(ParsedTargetID.getGPUKind());
6788 AMDGPU::IsaVersion DirectiveISA = AMDGPU::getIsaVersion(DirectiveProcessor);
6789 if (DirectiveISA != ISA) {
6790 return Error(getParser().getTok().getLoc(),
6791 ".amd_amdgpu_isa directive processor " +
6792 Twine(DirectiveProcessor) +
6793 " does not match the specified processor " +
6794 Twine(getSTI().getCPU()));
6795 }
6796
6797 getTargetStreamer().EmitISAVersion();
6798 Lex();
6799
6800 return false;
6801}
6802
6803bool AMDGPUAsmParser::ParseDirectiveHSAMetadata() {
6804 assert(isHsaAbi(getSTI()));
6805
6806 std::string HSAMetadataString;
6807 if (ParseToEndDirective(HSAMD::V3::AssemblerDirectiveBegin,
6808 HSAMD::V3::AssemblerDirectiveEnd, HSAMetadataString))
6809 return true;
6810
6811 if (!getTargetStreamer().EmitHSAMetadataV3(HSAMetadataString))
6812 return Error(getLoc(), "invalid HSA metadata");
6813
6814 return false;
6815}
6816
6817/// Common code to parse out a block of text (typically YAML) between start and
6818/// end directives.
6819bool AMDGPUAsmParser::ParseToEndDirective(const char *AssemblerDirectiveBegin,
6820 const char *AssemblerDirectiveEnd,
6821 std::string &CollectString) {
6822
6823 raw_string_ostream CollectStream(CollectString);
6824
6825 getLexer().setSkipSpace(false);
6826
6827 bool FoundEnd = false;
6828 while (!isToken(AsmToken::Eof)) {
6829 while (isToken(AsmToken::Space)) {
6830 CollectStream << getTokenStr();
6831 Lex();
6832 }
6833
6834 if (trySkipId(AssemblerDirectiveEnd)) {
6835 FoundEnd = true;
6836 break;
6837 }
6838
6839 CollectStream << Parser.parseStringToEndOfStatement()
6840 << getContext().getAsmInfo().getSeparatorString();
6841
6842 Parser.eatToEndOfStatement();
6843 }
6844
6845 getLexer().setSkipSpace(true);
6846
6847 if (isToken(AsmToken::Eof) && !FoundEnd) {
6848 return TokError(Twine("expected directive ") +
6849 Twine(AssemblerDirectiveEnd) + Twine(" not found"));
6850 }
6851
6852 return false;
6853}
6854
6855/// Parse the assembler directive for new MsgPack-format PAL metadata.
6856bool AMDGPUAsmParser::ParseDirectivePALMetadataBegin() {
6857 std::string String;
6858 if (ParseToEndDirective(AMDGPU::PALMD::AssemblerDirectiveBegin,
6860 return true;
6861
6862 auto *PALMetadata = getTargetStreamer().getPALMetadata();
6863 if (!PALMetadata->setFromString(String))
6864 return Error(getLoc(), "invalid PAL metadata");
6865 return false;
6866}
6867
6868/// Parse the assembler directive for old linear-format PAL metadata.
6869bool AMDGPUAsmParser::ParseDirectivePALMetadata() {
6870 if (getSTI().getTargetTriple().getOS() != Triple::AMDPAL) {
6871 return Error(getLoc(), (Twine(PALMD::AssemblerDirective) +
6872 Twine(" directive is "
6873 "not available on non-amdpal OSes"))
6874 .str());
6875 }
6876
6877 auto *PALMetadata = getTargetStreamer().getPALMetadata();
6878 PALMetadata->setLegacy();
6879 for (;;) {
6880 uint32_t Key, Value;
6881 if (ParseAsAbsoluteExpression(Key)) {
6882 return TokError(Twine("invalid value in ") +
6884 }
6885 if (!trySkipToken(AsmToken::Comma)) {
6886 return TokError(Twine("expected an even number of values in ") +
6888 }
6889 if (ParseAsAbsoluteExpression(Value)) {
6890 return TokError(Twine("invalid value in ") +
6892 }
6893 PALMetadata->setRegister(Key, Value);
6894 if (!trySkipToken(AsmToken::Comma))
6895 break;
6896 }
6897 return false;
6898}
6899
6900/// ParseDirectiveAMDGPULDS
6901/// ::= .amdgpu_lds identifier ',' size_expression [',' align_expression]
6902bool AMDGPUAsmParser::ParseDirectiveAMDGPULDS() {
6903 if (getParser().checkForValidSection())
6904 return true;
6905
6906 StringRef Name;
6907 SMLoc NameLoc = getLoc();
6908 if (getParser().parseIdentifier(Name))
6909 return TokError("expected identifier in directive");
6910
6911 MCSymbol *Symbol = getContext().getOrCreateSymbol(Name);
6912 if (getParser().parseComma())
6913 return true;
6914
6915 unsigned LocalMemorySize = AMDGPU::IsaInfo::getLocalMemorySize(getSTI());
6916
6917 int64_t Size;
6918 SMLoc SizeLoc = getLoc();
6919 if (getParser().parseAbsoluteExpression(Size))
6920 return true;
6921 if (Size < 0)
6922 return Error(SizeLoc, "size must be non-negative");
6923 if (Size > LocalMemorySize)
6924 return Error(SizeLoc, "size is too large");
6925
6926 int64_t Alignment = 4;
6927 if (trySkipToken(AsmToken::Comma)) {
6928 SMLoc AlignLoc = getLoc();
6929 if (getParser().parseAbsoluteExpression(Alignment))
6930 return true;
6931 if (Alignment < 0 || !isPowerOf2_64(Alignment))
6932 return Error(AlignLoc, "alignment must be a power of two");
6933
6934 // Alignment larger than the size of LDS is possible in theory, as long
6935 // as the linker manages to place to symbol at address 0, but we do want
6936 // to make sure the alignment fits nicely into a 32-bit integer.
6937 if (Alignment >= 1u << 31)
6938 return Error(AlignLoc, "alignment is too large");
6939 }
6940
6941 if (parseEOL())
6942 return true;
6943
6944 Symbol->redefineIfPossible();
6945 if (!Symbol->isUndefined())
6946 return Error(NameLoc, "invalid symbol redefinition");
6947
6948 getTargetStreamer().emitAMDGPULDS(Symbol, Size, Align(Alignment));
6949 return false;
6950}
6951
6952bool AMDGPUAsmParser::ParseDirectiveAMDGPUInfo() {
6953 if (getParser().checkForValidSection())
6954 return true;
6955
6956 StringRef FuncName;
6957 if (getParser().parseIdentifier(FuncName))
6958 return TokError("expected symbol name after .amdgpu_info");
6959
6960 MCSymbol *FuncSym = getContext().getOrCreateSymbol(FuncName);
6961 AMDGPU::InfoSectionData ParsedInfoData;
6962 AMDGPU::FuncInfo FI;
6963 FI.Sym = FuncSym;
6964 bool HasScalarAttrs = false;
6965
6966 while (true) {
6967 while (trySkipToken(AsmToken::EndOfStatement))
6968 ;
6969
6970 StringRef ID;
6971 SMLoc IDLoc = getLoc();
6972 if (!parseId(ID, "expected directive or .end_amdgpu_info"))
6973 return true;
6974
6975 if (ID == ".end_amdgpu_info")
6976 break;
6977
6978 // Every per-entry directive shares the `.amdgpu_` namespace prefix; strip
6979 // it once and dispatch on the distinguishing suffix below. The unstripped
6980 // ID is preserved for diagnostics.
6981 StringRef Dir = ID;
6982 if (!Dir.consume_front(".amdgpu_"))
6983 return Error(IDLoc, "unknown .amdgpu_info directive '" + ID + "'");
6984
6985 if (Dir == "flags") {
6986 int64_t Val;
6987 if (getParser().parseAbsoluteExpression(Val))
6988 return true;
6989 auto Flags = static_cast<AMDGPU::FuncInfoFlags>(Val);
6990 FI.UsesVCC = !!(Flags & AMDGPU::FuncInfoFlags::FUNC_USES_VCC);
6991 FI.UsesFlatScratch =
6992 !!(Flags & AMDGPU::FuncInfoFlags::FUNC_USES_FLAT_SCRATCH);
6993 FI.HasDynStack = !!(Flags & AMDGPU::FuncInfoFlags::FUNC_HAS_DYN_STACK);
6994 HasScalarAttrs = true;
6995 } else if (Dir == "num_sgpr") {
6996 int64_t Val;
6997 if (getParser().parseAbsoluteExpression(Val))
6998 return true;
6999 FI.NumSGPR = static_cast<uint32_t>(Val);
7000 HasScalarAttrs = true;
7001 } else if (Dir == "num_vgpr") {
7002 int64_t Val;
7003 if (getParser().parseAbsoluteExpression(Val))
7004 return true;
7005 FI.NumArchVGPR = static_cast<uint32_t>(Val);
7006 HasScalarAttrs = true;
7007 } else if (Dir == "num_agpr") {
7008 int64_t Val;
7009 if (getParser().parseAbsoluteExpression(Val))
7010 return true;
7011 FI.NumAccVGPR = static_cast<uint32_t>(Val);
7012 HasScalarAttrs = true;
7013 } else if (Dir == "private_segment_size") {
7014 int64_t Val;
7015 if (getParser().parseAbsoluteExpression(Val))
7016 return true;
7017 FI.PrivateSegmentSize = static_cast<uint32_t>(Val);
7018 HasScalarAttrs = true;
7019 } else if (Dir == "use") {
7020 StringRef ResName;
7021 if (getParser().parseIdentifier(ResName))
7022 return TokError("expected resource symbol for .amdgpu_use");
7023 ParsedInfoData.Uses.push_back(
7024 {FuncSym, getContext().getOrCreateSymbol(ResName)});
7025 } else if (Dir == "call") {
7026 StringRef DstName;
7027 if (getParser().parseIdentifier(DstName))
7028 return TokError("expected callee symbol for .amdgpu_call");
7029 ParsedInfoData.Calls.push_back(
7030 {FuncSym, getContext().getOrCreateSymbol(DstName)});
7031 } else if (Dir == "indirect_call") {
7032 std::string TypeId;
7033 if (getParser().parseEscapedString(TypeId))
7034 return TokError("expected type ID string for .amdgpu_indirect_call");
7035 ParsedInfoData.IndirectCalls.push_back({FuncSym, std::move(TypeId)});
7036 } else if (Dir == "typeid") {
7037 std::string TypeId;
7038 if (getParser().parseEscapedString(TypeId))
7039 return TokError("expected type ID string for .amdgpu_typeid");
7040 ParsedInfoData.TypeIds.push_back({FuncSym, std::move(TypeId)});
7041 } else {
7042 return Error(IDLoc, "unknown .amdgpu_info directive '" + ID + "'");
7043 }
7044 }
7045
7046 if (HasScalarAttrs)
7047 ParsedInfoData.Funcs.push_back(std::move(FI));
7048
7049 AMDGPU::InfoSectionData &Data = InfoData ? *InfoData : InfoData.emplace();
7050 for (AMDGPU::FuncInfo &Func : ParsedInfoData.Funcs)
7051 Data.Funcs.push_back(std::move(Func));
7052 for (std::pair<MCSymbol *, MCSymbol *> &Use : ParsedInfoData.Uses)
7053 Data.Uses.push_back(Use);
7054 for (std::pair<MCSymbol *, MCSymbol *> &Call : ParsedInfoData.Calls)
7055 Data.Calls.push_back(Call);
7056 for (std::pair<MCSymbol *, std::string> &IndirectCall :
7057 ParsedInfoData.IndirectCalls)
7058 Data.IndirectCalls.push_back(std::move(IndirectCall));
7059 for (std::pair<MCSymbol *, std::string> &TypeId : ParsedInfoData.TypeIds)
7060 Data.TypeIds.push_back(std::move(TypeId));
7061
7062 return false;
7063}
7064
7065void AMDGPUAsmParser::doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) {
7066 // Record every parsed label in the timeline so that, at end of file, the
7067 // instructions following a kernel's label can be located regardless of
7068 // whether the .amdhsa_kernel directive came before or after the label.
7069 OpcodeStreamSymbols.emplace_back(Symbol, IDLoc, OpcodeStream.size());
7070}
7071
7072void AMDGPUAsmParser::checkKernelPrologues() {
7073 if (getFeatureBits()[AMDGPU::FeatureRequiresInitialUnclausedVmem]) {
7074 static const unsigned Required[] = {S_MOV_B64_gfx12, V_NOP_e32_gfx12,
7075 GLOBAL_PREFETCH_B8_SADDR_gfx1250};
7076 for (auto [Sym, Loc, Offset] : OpcodeStreamSymbols) {
7077 if (!AMDHSAKernelSymbols.contains(Sym))
7078 continue;
7079 ArrayRef<unsigned> Prologue = ArrayRef(OpcodeStream).drop_front(Offset);
7080 if (!Prologue.empty() && Prologue.front() == S_SETREG_IMM32_B32_gfx12)
7081 Prologue = Prologue.drop_front();
7082 if (Prologue.take_front(std::size(Required)) != ArrayRef(Required)) {
7083 Warning(Loc, "kernel '" + Sym->getName() +
7084 "' does not begin with the required prologue "
7085 "sequence: s_mov_b64 followed by v_nop and "
7086 "global_prefetch_b8");
7087 }
7088 }
7089 }
7090 OpcodeStream.clear();
7091 OpcodeStreamSymbols.clear();
7092 AMDHSAKernelSymbols.clear();
7093}
7094
7095void AMDGPUAsmParser::onEndOfFile() {
7096 emitTargetDirective();
7097 checkKernelPrologues();
7098 if (InfoData)
7099 getTargetStreamer().emitAMDGPUInfo(*InfoData);
7100}
7101
7102bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
7103 StringRef IDVal = DirectiveID.getString();
7104
7105 if (isHsaAbi(getSTI())) {
7106 if (IDVal == ".amdhsa_kernel")
7107 return ParseDirectiveAMDHSAKernel();
7108
7109 if (IDVal == ".amdhsa_code_object_version")
7110 return ParseDirectiveAMDHSACodeObjectVersion();
7111
7112 // TODO: Restructure/combine with PAL metadata directive.
7114 return ParseDirectiveHSAMetadata();
7115 } else {
7116 if (IDVal == ".amd_kernel_code_t")
7117 return ParseDirectiveAMDKernelCodeT();
7118
7119 if (IDVal == ".amdgpu_hsa_kernel")
7120 return ParseDirectiveAMDGPUHsaKernel();
7121
7122 if (IDVal == ".amd_amdgpu_isa")
7123 return ParseDirectiveISAVersion();
7124
7126 return Error(getLoc(), (Twine(HSAMD::AssemblerDirectiveBegin) +
7127 Twine(" directive is "
7128 "not available on non-amdhsa OSes"))
7129 .str());
7130 }
7131 }
7132
7133 if (IDVal == ".amdgcn_target")
7134 return ParseDirectiveAMDGCNTarget();
7135
7136 if (IDVal == ".amdgpu_lds")
7137 return ParseDirectiveAMDGPULDS();
7138
7139 if (IDVal == ".amdgpu_info")
7140 return ParseDirectiveAMDGPUInfo();
7141
7142 if (IDVal == PALMD::AssemblerDirectiveBegin)
7143 return ParseDirectivePALMetadataBegin();
7144
7145 if (IDVal == PALMD::AssemblerDirective)
7146 return ParseDirectivePALMetadata();
7147
7148 return true;
7149}
7150
7151bool AMDGPUAsmParser::subtargetHasRegister(const MCRegisterInfo &MRI,
7152 MCRegister Reg) {
7153 if (MRI.regsOverlap(TTMP12_TTMP13_TTMP14_TTMP15, Reg))
7154 return isGFX9Plus();
7155
7156 // GFX10+ has 2 more SGPRs 104 and 105.
7157 if (MRI.regsOverlap(SGPR104_SGPR105, Reg))
7158 return hasSGPR104_SGPR105();
7159
7160 switch (Reg.id()) {
7161 case SRC_SHARED_BASE_LO:
7162 case SRC_SHARED_BASE:
7163 case SRC_SHARED_LIMIT_LO:
7164 case SRC_SHARED_LIMIT:
7165 return isGFX9Plus();
7166 case SRC_PRIVATE_BASE_LO:
7167 case SRC_PRIVATE_BASE:
7168 case SRC_PRIVATE_LIMIT_LO:
7169 case SRC_PRIVATE_LIMIT:
7170 return AMDGPU::hasPrivateApertureRegs(getSTI());
7171 case SRC_FLAT_SCRATCH_BASE_LO:
7172 case SRC_FLAT_SCRATCH_BASE_HI:
7173 return hasGloballyAddressableScratch();
7174 case SRC_POPS_EXITING_WAVE_ID:
7175 return hasPopsExitingWaveID(getSTI());
7176 case TBA:
7177 case TBA_LO:
7178 case TBA_HI:
7179 case TMA:
7180 case TMA_LO:
7181 case TMA_HI:
7182 return !isGFX9Plus();
7183 case XNACK_MASK:
7184 case XNACK_MASK_LO:
7185 case XNACK_MASK_HI:
7186 return (isVI() || isGFX9()) &&
7187 getTargetStreamer().getTargetID()->isXnackSupported();
7188 case SGPR_NULL:
7189 return isGFX10Plus();
7190 case SRC_EXECZ:
7191 case SRC_VCCZ:
7192 return !isGFX11Plus();
7193 default:
7194 break;
7195 }
7196
7197 if (isCI())
7198 return true;
7199
7200 if (isSI() || isGFX10Plus()) {
7201 // No flat_scr on SI.
7202 // On GFX10Plus flat scratch is not a valid register operand and can only be
7203 // accessed with s_setreg/s_getreg.
7204 switch (Reg.id()) {
7205 case FLAT_SCR:
7206 case FLAT_SCR_LO:
7207 case FLAT_SCR_HI:
7208 return false;
7209 default:
7210 return true;
7211 }
7212 }
7213
7214 // VI only has 102 SGPRs, so make sure we aren't trying to use the 2 more that
7215 // SI/CI have.
7216 if (MRI.regsOverlap(SGPR102_SGPR103, Reg))
7217 return hasSGPR102_SGPR103();
7218
7219 return true;
7220}
7221
7222ParseStatus AMDGPUAsmParser::parseOperand(OperandVector &Operands,
7223 StringRef Mnemonic,
7224 OperandMode Mode) {
7225 ParseStatus Res = parseVOPD(Operands);
7226 if (Res.isSuccess() || Res.isFailure() || isToken(AsmToken::EndOfStatement))
7227 return Res;
7228
7229 // Try to parse with a custom parser
7230 Res = MatchOperandParserImpl(Operands, Mnemonic);
7231
7232 // If we successfully parsed the operand or if there as an error parsing,
7233 // we are done.
7234 //
7235 // If we are parsing after we reach EndOfStatement then this means we
7236 // are appending default values to the Operands list. This is only done
7237 // by custom parser, so we shouldn't continue on to the generic parsing.
7238 if (Res.isSuccess() || Res.isFailure() || isToken(AsmToken::EndOfStatement))
7239 return Res;
7240
7241 SMLoc RBraceLoc;
7242 SMLoc LBraceLoc = getLoc();
7243 if (Mode == OperandMode_NSA && trySkipToken(AsmToken::LBrac)) {
7244 unsigned Prefix = Operands.size();
7245
7246 for (;;) {
7247 auto Loc = getLoc();
7248 Res = parseReg(Operands);
7249 if (Res.isNoMatch())
7250 Error(Loc, "expected a register");
7251 if (!Res.isSuccess())
7252 return ParseStatus::Failure;
7253
7254 RBraceLoc = getLoc();
7255 if (trySkipToken(AsmToken::RBrac))
7256 break;
7257
7258 if (!skipToken(AsmToken::Comma,
7259 "expected a comma or a closing square bracket"))
7260 return ParseStatus::Failure;
7261 }
7262
7263 if (Operands.size() - Prefix > 1) {
7264 Operands.insert(Operands.begin() + Prefix,
7265 AMDGPUOperand::CreateToken(this, "[", LBraceLoc));
7266 Operands.push_back(AMDGPUOperand::CreateToken(this, "]", RBraceLoc));
7267 }
7268
7269 return ParseStatus::Success;
7270 }
7271
7272 return parseRegOrImm(Operands);
7273}
7274
7275StringRef AMDGPUAsmParser::parseMnemonicSuffix(StringRef Name) {
7276 // Clear any forced encodings from the previous instruction.
7277 setForcedEncodingSize(0);
7278 setForcedDPP(false);
7279 setForcedSDWA(false);
7280
7281 if (Name.consume_back("_e64_dpp")) {
7282 setForcedDPP(true);
7283 setForcedEncodingSize(64);
7284 return Name;
7285 }
7286 if (Name.consume_back("_e64")) {
7287 setForcedEncodingSize(64);
7288 return Name;
7289 }
7290 if (Name.consume_back("_e32")) {
7291 setForcedEncodingSize(32);
7292 return Name;
7293 }
7294 if (Name.consume_back("_dpp")) {
7295 setForcedDPP(true);
7296 return Name;
7297 }
7298 if (Name.consume_back("_sdwa")) {
7299 setForcedSDWA(true);
7300 return Name;
7301 }
7302 return Name;
7303}
7304
7305static void applyMnemonicAliases(StringRef &Mnemonic,
7306 const FeatureBitset &Features,
7307 unsigned VariantID);
7308
7309bool AMDGPUAsmParser::parseInstruction(ParseInstructionInfo &Info,
7310 StringRef Name, SMLoc NameLoc,
7312 // Add the instruction mnemonic
7313 Name = parseMnemonicSuffix(Name);
7314
7315 // If the target architecture uses MnemonicAlias, call it here to parse
7316 // operands correctly.
7317 applyMnemonicAliases(Name, getAvailableFeatures(), 0);
7318
7319 Operands.push_back(AMDGPUOperand::CreateToken(this, Name, NameLoc));
7320
7321 bool IsMIMG = Name.starts_with("image_");
7322
7323 while (!trySkipToken(AsmToken::EndOfStatement)) {
7324 OperandMode Mode = OperandMode_Default;
7325 if (IsMIMG && isGFX10Plus() && Operands.size() == 2)
7326 Mode = OperandMode_NSA;
7327 ParseStatus Res = parseOperand(Operands, Name, Mode);
7328
7329 if (!Res.isSuccess()) {
7330 checkUnsupportedInstruction(Name, NameLoc);
7331 if (!Parser.hasPendingError()) {
7332 // FIXME: use real operand location rather than the current location.
7333 StringRef Msg = Res.isFailure() ? "failed parsing operand."
7334 : "not a valid operand.";
7335 Error(getLoc(), Msg);
7336 }
7337 while (!trySkipToken(AsmToken::EndOfStatement)) {
7338 lex();
7339 }
7340 return true;
7341 }
7342
7343 // Eat the comma or space if there is one.
7344 trySkipToken(AsmToken::Comma);
7345 }
7346
7347 return false;
7348}
7349
7350//===----------------------------------------------------------------------===//
7351// Utility functions
7352//===----------------------------------------------------------------------===//
7353
7354ParseStatus AMDGPUAsmParser::parseTokenOp(StringRef Name,
7356 SMLoc S = getLoc();
7357 if (!trySkipId(Name))
7358 return ParseStatus::NoMatch;
7359
7360 Operands.push_back(AMDGPUOperand::CreateToken(this, Name, S));
7361 return ParseStatus::Success;
7362}
7363
7364ParseStatus AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix,
7365 int64_t &IntVal) {
7366
7367 if (!trySkipId(Prefix, AsmToken::Colon))
7368 return ParseStatus::NoMatch;
7369
7371}
7372
7373ParseStatus AMDGPUAsmParser::parseIntWithPrefix(
7374 const char *Prefix, OperandVector &Operands, AMDGPUOperand::ImmTy ImmTy,
7375 std::function<bool(int64_t &)> ConvertResult) {
7376 SMLoc S = getLoc();
7377 int64_t Value = 0;
7378
7379 ParseStatus Res = parseIntWithPrefix(Prefix, Value);
7380 if (!Res.isSuccess())
7381 return Res;
7382
7383 if (ConvertResult && !ConvertResult(Value)) {
7384 Error(S, "invalid " + StringRef(Prefix) + " value.");
7385 }
7386
7387 Operands.push_back(AMDGPUOperand::CreateImm(this, Value, S, ImmTy));
7388 return ParseStatus::Success;
7389}
7390
7391ParseStatus AMDGPUAsmParser::parseOperandArrayWithPrefix(
7392 const char *Prefix, OperandVector &Operands, AMDGPUOperand::ImmTy ImmTy,
7393 bool (*ConvertResult)(int64_t &)) {
7394 SMLoc S = getLoc();
7395 if (!trySkipId(Prefix, AsmToken::Colon))
7396 return ParseStatus::NoMatch;
7397
7398 if (!skipToken(AsmToken::LBrac, "expected a left square bracket"))
7399 return ParseStatus::Failure;
7400
7401 unsigned Val = 0;
7402 const unsigned MaxSize = 4;
7403
7404 // FIXME: How to verify the number of elements matches the number of src
7405 // operands?
7406 for (int I = 0;; ++I) {
7407 int64_t Op;
7408 SMLoc Loc = getLoc();
7409 if (!parseExpr(Op))
7410 return ParseStatus::Failure;
7411
7412 if (Op != 0 && Op != 1)
7413 return Error(Loc, "invalid " + StringRef(Prefix) + " value.");
7414
7415 Val |= (Op << I);
7416
7417 if (trySkipToken(AsmToken::RBrac))
7418 break;
7419
7420 if (I + 1 == MaxSize)
7421 return Error(getLoc(), "expected a closing square bracket");
7422
7423 if (!skipToken(AsmToken::Comma, "expected a comma"))
7424 return ParseStatus::Failure;
7425 }
7426
7427 Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S, ImmTy));
7428 return ParseStatus::Success;
7429}
7430
7431ParseStatus AMDGPUAsmParser::parseNamedBit(StringRef Name,
7433 AMDGPUOperand::ImmTy ImmTy,
7434 bool IgnoreNegative) {
7435 int64_t Bit;
7436 SMLoc S = getLoc();
7437
7438 if (trySkipId(Name)) {
7439 Bit = 1;
7440 } else if (trySkipId("no", Name)) {
7441 if (IgnoreNegative)
7442 return ParseStatus::Success;
7443 Bit = 0;
7444 } else {
7445 return ParseStatus::NoMatch;
7446 }
7447
7448 if (Name == "r128" && !hasMIMG_R128())
7449 return Error(S, "r128 modifier is not supported on this GPU");
7450 if (Name == "a16" && !hasA16())
7451 return Error(S, "a16 modifier is not supported on this GPU");
7452
7453 if (Bit == 0 && Name == "gds") {
7454 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
7455 if (Mnemo.starts_with("ds_gws"))
7456 return Error(S, "nogds is not allowed");
7457 }
7458
7459 if (isGFX9() && ImmTy == AMDGPUOperand::ImmTyA16)
7460 ImmTy = AMDGPUOperand::ImmTyR128A16;
7461
7462 Operands.push_back(AMDGPUOperand::CreateImm(this, Bit, S, ImmTy));
7463 return ParseStatus::Success;
7464}
7465
7466unsigned AMDGPUAsmParser::getCPolKind(StringRef Id, StringRef Mnemo,
7467 bool &Disabling) const {
7468 Disabling = Id.consume_front("no");
7469
7470 if (isGFX940() && !Mnemo.starts_with("s_")) {
7471 return StringSwitch<unsigned>(Id)
7472 .Case("nt", AMDGPU::CPol::NT)
7473 .Case("sc0", AMDGPU::CPol::SC0)
7474 .Case("sc1", AMDGPU::CPol::SC1)
7475 .Default(0);
7476 }
7477
7478 return StringSwitch<unsigned>(Id)
7479 .Case("dlc", AMDGPU::CPol::DLC)
7480 .Case("glc", AMDGPU::CPol::GLC)
7481 .Case("scc", AMDGPU::CPol::SCC)
7482 .Case("slc", AMDGPU::CPol::SLC)
7483 .Default(0);
7484}
7485
7486ParseStatus AMDGPUAsmParser::parseCPol(OperandVector &Operands) {
7487 if (isGFX12Plus()) {
7488 SMLoc StringLoc = getLoc();
7489
7490 int64_t CPolVal = 0;
7491 ParseStatus ResTH = ParseStatus::NoMatch;
7492 ParseStatus ResScope = ParseStatus::NoMatch;
7493 ParseStatus ResNV = ParseStatus::NoMatch;
7494 ParseStatus ResScal = ParseStatus::NoMatch;
7495 ParseStatus ResCFS = ParseStatus::NoMatch;
7496
7497 for (;;) {
7498 if (ResTH.isNoMatch()) {
7499 int64_t TH;
7500 ResTH = parseTH(Operands, TH);
7501 if (ResTH.isFailure())
7502 return ResTH;
7503 if (ResTH.isSuccess()) {
7504 CPolVal |= TH;
7505 continue;
7506 }
7507 }
7508
7509 if (ResScope.isNoMatch()) {
7510 int64_t Scope;
7511 ResScope = parseScope(Operands, Scope);
7512 if (ResScope.isFailure())
7513 return ResScope;
7514 if (ResScope.isSuccess()) {
7515 CPolVal |= Scope;
7516 continue;
7517 }
7518 }
7519
7520 // NV bit exists on GFX12+, but does something starting from GFX1250.
7521 // Allow parsing on all GFX12 and fail on validation for better
7522 // diagnostics.
7523 if (ResNV.isNoMatch()) {
7524 if (trySkipId("nv")) {
7525 ResNV = ParseStatus::Success;
7526 CPolVal |= CPol::NV;
7527 continue;
7528 } else if (trySkipId("no", "nv")) {
7529 ResNV = ParseStatus::Success;
7530 continue;
7531 }
7532 }
7533
7534 if (ResScal.isNoMatch()) {
7535 if (trySkipId("scale_offset")) {
7536 ResScal = ParseStatus::Success;
7537 CPolVal |= CPol::SCAL;
7538 continue;
7539 } else if (trySkipId("no", "scale_offset")) {
7540 ResScal = ParseStatus::Success;
7541 continue;
7542 }
7543 }
7544
7545 if (ResCFS.isNoMatch()) {
7546 int64_t CFS;
7547 ResCFS = parseCFS(Operands, CFS);
7548 if (ResCFS.isFailure())
7549 return ResCFS;
7550 if (ResCFS.isSuccess()) {
7551 CPolVal |= CFS;
7552 continue;
7553 }
7554 }
7555
7556 break;
7557 }
7558
7559 if (ResTH.isNoMatch() && ResScope.isNoMatch() && ResNV.isNoMatch() &&
7560 ResScal.isNoMatch() && ResCFS.isNoMatch())
7561 return ParseStatus::NoMatch;
7562
7563 Operands.push_back(AMDGPUOperand::CreateImm(this, CPolVal, StringLoc,
7564 AMDGPUOperand::ImmTyCPol));
7565 return ParseStatus::Success;
7566 }
7567
7568 StringRef Mnemo = ((AMDGPUOperand &)*Operands[0]).getToken();
7569 SMLoc OpLoc = getLoc();
7570 unsigned Enabled = 0, Seen = 0;
7571 for (;;) {
7572 SMLoc S = getLoc();
7573 bool Disabling;
7574 unsigned CPol = getCPolKind(getId(), Mnemo, Disabling);
7575 if (!CPol)
7576 break;
7577
7578 lex();
7579
7580 if (!isGFX10Plus() && CPol == AMDGPU::CPol::DLC)
7581 return Error(S, "dlc modifier is not supported on this GPU");
7582
7583 if (!isGFX90A() && CPol == AMDGPU::CPol::SCC)
7584 return Error(S, "scc modifier is not supported on this GPU");
7585
7586 if (Seen & CPol)
7587 return Error(S, "duplicate cache policy modifier");
7588
7589 if (!Disabling)
7590 Enabled |= CPol;
7591
7592 Seen |= CPol;
7593 }
7594
7595 if (!Seen)
7596 return ParseStatus::NoMatch;
7597
7598 Operands.push_back(
7599 AMDGPUOperand::CreateImm(this, Enabled, OpLoc, AMDGPUOperand::ImmTyCPol));
7600 return ParseStatus::Success;
7601}
7602
7603ParseStatus AMDGPUAsmParser::parseScope(OperandVector &Operands,
7604 int64_t &Scope) {
7605 static const unsigned Scopes[] = {CPol::SCOPE_CU, CPol::SCOPE_SE,
7607
7608 ParseStatus Res = parseStringOrIntWithPrefix(
7609 Operands, "scope", {"SCOPE_CU", "SCOPE_SE", "SCOPE_DEV", "SCOPE_SYS"},
7610 Scope);
7611
7612 if (Res.isSuccess())
7613 Scope = Scopes[Scope];
7614
7615 return Res;
7616}
7617
7618ParseStatus AMDGPUAsmParser::parseTH(OperandVector &Operands, int64_t &TH) {
7619 TH = AMDGPU::CPol::TH_RT; // default
7620
7621 StringRef Value;
7622 SMLoc StringLoc;
7623 ParseStatus Res = parseStringWithPrefix("th", Value, StringLoc);
7624 if (!Res.isSuccess())
7625 return Res;
7626
7627 if (Value == "TH_DEFAULT")
7629 else if (Value == "TH_STORE_LU" || Value == "TH_LOAD_WB" ||
7630 Value == "TH_LOAD_NT_WB") {
7631 return Error(StringLoc, "invalid th value");
7632 } else if (Value.consume_front("TH_ATOMIC_")) {
7634 } else if (Value.consume_front("TH_LOAD_")) {
7636 } else if (Value.consume_front("TH_STORE_")) {
7638 } else {
7639 return Error(StringLoc, "invalid th value");
7640 }
7641
7642 if (Value == "BYPASS")
7644
7645 if (TH != 0) {
7647 TH |= StringSwitch<int64_t>(Value)
7648 .Case("RETURN", AMDGPU::CPol::TH_ATOMIC_RETURN)
7649 .Case("RT", AMDGPU::CPol::TH_RT)
7650 .Case("RT_RETURN", AMDGPU::CPol::TH_ATOMIC_RETURN)
7651 .Case("NT", AMDGPU::CPol::TH_ATOMIC_NT)
7652 .Case("NT_RETURN", AMDGPU::CPol::TH_ATOMIC_NT |
7654 .Case("CASCADE_RT", AMDGPU::CPol::TH_ATOMIC_CASCADE)
7655 .Case("CASCADE_NT", AMDGPU::CPol::TH_ATOMIC_CASCADE |
7657 .Default(0xffffffff);
7658 else
7659 TH |= StringSwitch<int64_t>(Value)
7660 .Case("RT", AMDGPU::CPol::TH_RT)
7661 .Case("NT", AMDGPU::CPol::TH_NT)
7662 .Case("HT", AMDGPU::CPol::TH_HT)
7663 .Case("LU", AMDGPU::CPol::TH_LU)
7664 .Case("WB", AMDGPU::CPol::TH_WB)
7665 .Case("NT_RT", AMDGPU::CPol::TH_NT_RT)
7666 .Case("RT_NT", AMDGPU::CPol::TH_RT_NT)
7667 .Case("NT_HT", AMDGPU::CPol::TH_NT_HT)
7668 .Case("NT_WB", AMDGPU::CPol::TH_NT_WB)
7669 .Case("BYPASS", AMDGPU::CPol::TH_BYPASS)
7670 .Default(0xffffffff);
7671 }
7672
7673 if (TH == 0xffffffff)
7674 return Error(StringLoc, "invalid th value");
7675
7676 return ParseStatus::Success;
7677}
7678
7679ParseStatus AMDGPUAsmParser::parseCFS(OperandVector &Operands, int64_t &CFS) {
7680 static const unsigned CFSVals[] = {CPol::CFS_256B, CPol::CFS_128B,
7682
7683 ParseStatus Res = parseStringOrIntWithPrefix(
7684 Operands, "cfs", {"CFS_256B", "CFS_128B", "CFS_64B", "CFS_32B"}, CFS);
7685
7686 if (Res.isSuccess())
7687 CFS = CFSVals[CFS];
7688
7689 return Res;
7690}
7691
7692static void
7694 AMDGPUAsmParser::OptionalImmIndexMap &OptionalIdx,
7695 AMDGPUOperand::ImmTy ImmT, int64_t Default = 0,
7696 std::optional<unsigned> InsertAt = std::nullopt) {
7697 auto i = OptionalIdx.find(ImmT);
7698 if (i != OptionalIdx.end()) {
7699 unsigned Idx = i->second;
7700 const AMDGPUOperand &Op =
7701 static_cast<const AMDGPUOperand &>(*Operands[Idx]);
7702 if (InsertAt)
7703 Inst.insert(Inst.begin() + *InsertAt, MCOperand::createImm(Op.getImm()));
7704 else
7705 Op.addImmOperands(Inst, 1);
7706 } else {
7707 if (InsertAt.has_value())
7708 Inst.insert(Inst.begin() + *InsertAt, MCOperand::createImm(Default));
7709 else
7711 }
7712}
7713
7714ParseStatus AMDGPUAsmParser::parseStringWithPrefix(StringRef Prefix,
7715 StringRef &Value,
7716 SMLoc &StringLoc) {
7717 if (!trySkipId(Prefix, AsmToken::Colon))
7718 return ParseStatus::NoMatch;
7719
7720 StringLoc = getLoc();
7721 return parseId(Value, "expected an identifier") ? ParseStatus::Success
7723}
7724
7725ParseStatus AMDGPUAsmParser::parseStringOrIntWithPrefix(
7726 OperandVector &Operands, StringRef Name, ArrayRef<const char *> Ids,
7727 int64_t &IntVal) {
7728 if (!trySkipId(Name, AsmToken::Colon))
7729 return ParseStatus::NoMatch;
7730
7731 SMLoc StringLoc = getLoc();
7732
7733 StringRef Value;
7734 if (isToken(AsmToken::Identifier)) {
7735 Value = getTokenStr();
7736 lex();
7737
7738 for (IntVal = 0; IntVal < (int64_t)Ids.size(); ++IntVal)
7739 if (Value == Ids[IntVal])
7740 break;
7741 } else if (!parseExpr(IntVal))
7742 return ParseStatus::Failure;
7743
7744 if (IntVal < 0 || IntVal >= (int64_t)Ids.size())
7745 return Error(StringLoc, "invalid " + Twine(Name) + " value");
7746
7747 return ParseStatus::Success;
7748}
7749
7750ParseStatus AMDGPUAsmParser::parseStringOrIntWithPrefix(
7751 OperandVector &Operands, StringRef Name, ArrayRef<const char *> Ids,
7752 AMDGPUOperand::ImmTy Type) {
7753 SMLoc S = getLoc();
7754 int64_t IntVal;
7755
7756 ParseStatus Res = parseStringOrIntWithPrefix(Operands, Name, Ids, IntVal);
7757 if (Res.isSuccess())
7758 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S, Type));
7759
7760 return Res;
7761}
7762
7763//===----------------------------------------------------------------------===//
7764// MTBUF format
7765//===----------------------------------------------------------------------===//
7766
7767ParseStatus AMDGPUAsmParser::tryParseFmt(const char *Pref, int64_t MaxVal,
7768 int64_t &Fmt) {
7769 int64_t Val;
7770 SMLoc Loc = getLoc();
7771
7772 ParseStatus Res = parseIntWithPrefix(Pref, Val);
7773 if (!Res.isSuccess())
7774 return Res;
7775
7776 if (Val < 0 || Val > MaxVal)
7777 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7778
7779 Fmt = Val;
7780 return ParseStatus::Success;
7781}
7782
7783ParseStatus AMDGPUAsmParser::tryParseIndexKey(OperandVector &Operands,
7784 AMDGPUOperand::ImmTy ImmTy) {
7785 const char *Pref = "index_key";
7786 int64_t ImmVal = 0;
7787 SMLoc Loc = getLoc();
7788 auto Res = parseIntWithPrefix(Pref, ImmVal);
7789 if (!Res.isSuccess())
7790 return Res;
7791
7792 if ((ImmTy == AMDGPUOperand::ImmTyIndexKey16bit ||
7793 ImmTy == AMDGPUOperand::ImmTyIndexKey32bit) &&
7794 (ImmVal < 0 || ImmVal > 1))
7795 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7796
7797 if (ImmTy == AMDGPUOperand::ImmTyIndexKey8bit && (ImmVal < 0 || ImmVal > 3))
7798 return Error(Loc, Twine("out of range ", StringRef(Pref)));
7799
7800 Operands.push_back(AMDGPUOperand::CreateImm(this, ImmVal, Loc, ImmTy));
7801 return ParseStatus::Success;
7802}
7803
7804ParseStatus AMDGPUAsmParser::parseIndexKey8bit(OperandVector &Operands) {
7805 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey8bit);
7806}
7807
7808ParseStatus AMDGPUAsmParser::parseIndexKey16bit(OperandVector &Operands) {
7809 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey16bit);
7810}
7811
7812ParseStatus AMDGPUAsmParser::parseIndexKey32bit(OperandVector &Operands) {
7813 return tryParseIndexKey(Operands, AMDGPUOperand::ImmTyIndexKey32bit);
7814}
7815
7816ParseStatus AMDGPUAsmParser::tryParseMatrixFMT(OperandVector &Operands,
7817 StringRef Name,
7818 AMDGPUOperand::ImmTy Type) {
7819 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixFmt,
7820 Type);
7821}
7822
7823ParseStatus AMDGPUAsmParser::parseMatrixAFMT(OperandVector &Operands) {
7824 return tryParseMatrixFMT(Operands, "matrix_a_fmt",
7825 AMDGPUOperand::ImmTyMatrixAFMT);
7826}
7827
7828ParseStatus AMDGPUAsmParser::parseMatrixBFMT(OperandVector &Operands) {
7829 return tryParseMatrixFMT(Operands, "matrix_b_fmt",
7830 AMDGPUOperand::ImmTyMatrixBFMT);
7831}
7832
7833ParseStatus AMDGPUAsmParser::tryParseMatrixScale(OperandVector &Operands,
7834 StringRef Name,
7835 AMDGPUOperand::ImmTy Type) {
7836 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixScale,
7837 Type);
7838}
7839
7840ParseStatus AMDGPUAsmParser::parseMatrixAScale(OperandVector &Operands) {
7841 return tryParseMatrixScale(Operands, "matrix_a_scale",
7842 AMDGPUOperand::ImmTyMatrixAScale);
7843}
7844
7845ParseStatus AMDGPUAsmParser::parseMatrixBScale(OperandVector &Operands) {
7846 return tryParseMatrixScale(Operands, "matrix_b_scale",
7847 AMDGPUOperand::ImmTyMatrixBScale);
7848}
7849
7850ParseStatus AMDGPUAsmParser::tryParseMatrixScaleFmt(OperandVector &Operands,
7851 StringRef Name,
7852 AMDGPUOperand::ImmTy Type) {
7853 return parseStringOrIntWithPrefix(Operands, Name, WMMAMods::ModMatrixScaleFmt,
7854 Type);
7855}
7856
7857ParseStatus AMDGPUAsmParser::parseMatrixAScaleFmt(OperandVector &Operands) {
7858 return tryParseMatrixScaleFmt(Operands, "matrix_a_scale_fmt",
7859 AMDGPUOperand::ImmTyMatrixAScaleFmt);
7860}
7861
7862ParseStatus AMDGPUAsmParser::parseMatrixBScaleFmt(OperandVector &Operands) {
7863 return tryParseMatrixScaleFmt(Operands, "matrix_b_scale_fmt",
7864 AMDGPUOperand::ImmTyMatrixBScaleFmt);
7865}
7866
7867// dfmt and nfmt (in a tbuffer instruction) are parsed as one to allow their
7868// values to live in a joint format operand in the MCInst encoding.
7869ParseStatus AMDGPUAsmParser::parseDfmtNfmt(int64_t &Format) {
7870 using namespace llvm::AMDGPU::MTBUFFormat;
7871
7872 int64_t Dfmt = DFMT_DEFAULT;
7873 int64_t Nfmt = NFMT_DEFAULT;
7874
7875 auto TryAfterComma = [&](const char *Pref, int64_t MaxVal,
7876 int64_t &Fmt) -> ParseStatus {
7877 if (isId(Pref) && peekToken().is(AsmToken::Colon))
7878 return Error(getLoc(), "expected a comma");
7879 AsmToken NextTokens[2];
7880 peekTokens(NextTokens);
7881 if (!isToken(AsmToken::Comma) || !isId(NextTokens[0], Pref) ||
7882 !NextTokens[1].is(AsmToken::Colon))
7883 return ParseStatus::Success;
7884 lex();
7885 return tryParseFmt(Pref, MaxVal, Fmt);
7886 };
7887
7888 // dfmt and nfmt can appear in either order, and each is optional. If both
7889 // are present, they are separated by a comma.
7890 ParseStatus Res = tryParseFmt("dfmt", DFMT_MAX, Dfmt);
7891 if (Res.isSuccess()) {
7892 Res = TryAfterComma("nfmt", NFMT_MAX, Nfmt);
7893 } else if (Res.isNoMatch()) {
7894 Res = tryParseFmt("nfmt", NFMT_MAX, Nfmt);
7895 if (Res.isSuccess())
7896 Res = TryAfterComma("dfmt", DFMT_MAX, Dfmt);
7897 }
7898 if (!Res.isSuccess())
7899 return Res;
7900
7901 Format = encodeDfmtNfmt(Dfmt, Nfmt);
7902 return ParseStatus::Success;
7903}
7904
7905ParseStatus AMDGPUAsmParser::parseUfmt(int64_t &Format) {
7906 return tryParseFmt("format", MTBUFFormat::UFMT_MAX, Format);
7907}
7908
7909bool AMDGPUAsmParser::matchDfmtNfmt(int64_t &Dfmt, int64_t &Nfmt,
7910 StringRef FormatStr, SMLoc Loc) {
7911 using namespace llvm::AMDGPU::MTBUFFormat;
7912 int64_t Format;
7913
7914 Format = getDfmt(FormatStr);
7915 if (Format != DFMT_UNDEF) {
7916 Dfmt = Format;
7917 return true;
7918 }
7919
7920 Format = getNfmt(FormatStr, getSTI());
7921 if (Format != NFMT_UNDEF) {
7922 Nfmt = Format;
7923 return true;
7924 }
7925
7926 Error(Loc, "unsupported format");
7927 return false;
7928}
7929
7930ParseStatus AMDGPUAsmParser::parseSymbolicSplitFormat(StringRef FormatStr,
7931 SMLoc FormatLoc,
7932 int64_t &Format) {
7933 using namespace llvm::AMDGPU::MTBUFFormat;
7934
7935 int64_t Dfmt = DFMT_UNDEF;
7936 int64_t Nfmt = NFMT_UNDEF;
7937 if (!matchDfmtNfmt(Dfmt, Nfmt, FormatStr, FormatLoc))
7938 return ParseStatus::Failure;
7939
7940 if (trySkipToken(AsmToken::Comma)) {
7941 StringRef Str;
7942 SMLoc Loc = getLoc();
7943 if (!parseId(Str, "expected a format string") ||
7944 !matchDfmtNfmt(Dfmt, Nfmt, Str, Loc))
7945 return ParseStatus::Failure;
7946 if (Dfmt == DFMT_UNDEF)
7947 return Error(Loc, "duplicate numeric format");
7948 if (Nfmt == NFMT_UNDEF)
7949 return Error(Loc, "duplicate data format");
7950 }
7951
7952 Dfmt = (Dfmt == DFMT_UNDEF) ? DFMT_DEFAULT : Dfmt;
7953 Nfmt = (Nfmt == NFMT_UNDEF) ? NFMT_DEFAULT : Nfmt;
7954
7955 if (isGFX10Plus()) {
7956 auto Ufmt = convertDfmtNfmt2Ufmt(Dfmt, Nfmt, getSTI());
7957 if (Ufmt == UFMT_UNDEF)
7958 return Error(FormatLoc, "unsupported format");
7959 Format = Ufmt;
7960 } else {
7961 Format = encodeDfmtNfmt(Dfmt, Nfmt);
7962 }
7963
7964 return ParseStatus::Success;
7965}
7966
7967ParseStatus AMDGPUAsmParser::parseSymbolicUnifiedFormat(StringRef FormatStr,
7968 SMLoc Loc,
7969 int64_t &Format) {
7970 using namespace llvm::AMDGPU::MTBUFFormat;
7971
7972 auto Id = getUnifiedFormat(FormatStr, getSTI());
7973 if (Id == UFMT_UNDEF)
7974 return ParseStatus::NoMatch;
7975
7976 if (!isGFX10Plus())
7977 return Error(Loc, "unified format is not supported on this GPU");
7978
7979 Format = Id;
7980 return ParseStatus::Success;
7981}
7982
7983ParseStatus AMDGPUAsmParser::parseNumericFormat(int64_t &Format) {
7984 using namespace llvm::AMDGPU::MTBUFFormat;
7985 SMLoc Loc = getLoc();
7986
7987 if (!parseExpr(Format))
7988 return ParseStatus::Failure;
7989 if (!isValidFormatEncoding(Format, getSTI()))
7990 return Error(Loc, "out of range format");
7991
7992 return ParseStatus::Success;
7993}
7994
7995ParseStatus AMDGPUAsmParser::parseSymbolicOrNumericFormat(int64_t &Format) {
7996 using namespace llvm::AMDGPU::MTBUFFormat;
7997
7998 if (!trySkipId("format", AsmToken::Colon))
7999 return ParseStatus::NoMatch;
8000
8001 if (trySkipToken(AsmToken::LBrac)) {
8002 StringRef FormatStr;
8003 SMLoc Loc = getLoc();
8004 if (!parseId(FormatStr, "expected a format string"))
8005 return ParseStatus::Failure;
8006
8007 auto Res = parseSymbolicUnifiedFormat(FormatStr, Loc, Format);
8008 if (Res.isNoMatch())
8009 Res = parseSymbolicSplitFormat(FormatStr, Loc, Format);
8010 if (!Res.isSuccess())
8011 return Res;
8012
8013 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
8014 return ParseStatus::Failure;
8015
8016 return ParseStatus::Success;
8017 }
8018
8019 return parseNumericFormat(Format);
8020}
8021
8022ParseStatus AMDGPUAsmParser::parseFormat(OperandVector &Operands) {
8023 SMLoc Loc = getLoc();
8024 int64_t Format;
8025 ParseStatus Res = parseSymbolicOrNumericFormat(Format);
8026 if (!Res.isSuccess())
8027 return Res;
8028
8029 Operands.push_back(
8030 AMDGPUOperand::CreateImm(this, Format, Loc, AMDGPUOperand::ImmTyFormat));
8031 return ParseStatus::Success;
8032}
8033
8034ParseStatus AMDGPUAsmParser::parseFormatOp(OperandVector &Operands) {
8035 SMLoc Loc = getLoc();
8036 int64_t Format;
8037 ParseStatus Res = isGFX10Plus() ? parseUfmt(Format) : parseDfmtNfmt(Format);
8038 if (!Res.isSuccess())
8039 return Res;
8040
8041 Operands.push_back(AMDGPUOperand::CreateImm(this, Format, Loc,
8042 AMDGPUOperand::ImmTyFormatOp));
8043 return ParseStatus::Success;
8044}
8045
8046ParseStatus AMDGPUAsmParser::parseFlatOffset(OperandVector &Operands) {
8047 ParseStatus Res =
8048 parseIntWithPrefix("offset", Operands, AMDGPUOperand::ImmTyOffset);
8049 if (Res.isNoMatch()) {
8050 Res = parseIntWithPrefix("inst_offset", Operands,
8051 AMDGPUOperand::ImmTyInstOffset);
8052 }
8053 return Res;
8054}
8055
8056ParseStatus AMDGPUAsmParser::parseR128A16(OperandVector &Operands) {
8057 ParseStatus Res =
8058 parseNamedBit("r128", Operands, AMDGPUOperand::ImmTyR128A16);
8059 if (Res.isNoMatch())
8060 Res = parseNamedBit("a16", Operands, AMDGPUOperand::ImmTyA16);
8061 return Res;
8062}
8063
8064ParseStatus AMDGPUAsmParser::parseBLGP(OperandVector &Operands) {
8065 ParseStatus Res =
8066 parseIntWithPrefix("blgp", Operands, AMDGPUOperand::ImmTyBLGP);
8067 if (Res.isNoMatch()) {
8068 Res =
8069 parseOperandArrayWithPrefix("neg", Operands, AMDGPUOperand::ImmTyBLGP);
8070 }
8071 return Res;
8072}
8073
8074//===----------------------------------------------------------------------===//
8075// Exp
8076//===----------------------------------------------------------------------===//
8077
8078void AMDGPUAsmParser::cvtExp(MCInst &Inst, const OperandVector &Operands) {
8079 OptionalImmIndexMap OptionalIdx;
8080
8081 unsigned OperandIdx[4];
8082 unsigned EnMask = 0;
8083 int SrcIdx = 0;
8084
8085 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
8086 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
8087
8088 // Add the register arguments
8089 if (Op.isReg()) {
8090 assert(SrcIdx < 4);
8091 OperandIdx[SrcIdx] = Inst.size();
8092 Op.addRegOperands(Inst, 1);
8093 ++SrcIdx;
8094 continue;
8095 }
8096
8097 if (Op.isOff()) {
8098 assert(SrcIdx < 4);
8099 OperandIdx[SrcIdx] = Inst.size();
8100 Inst.addOperand(MCOperand::createReg(MCRegister()));
8101 ++SrcIdx;
8102 continue;
8103 }
8104
8105 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyExpTgt) {
8106 Op.addImmOperands(Inst, 1);
8107 continue;
8108 }
8109
8110 // Handle optional arguments
8111 OptionalIdx[Op.getImmTy()] = i;
8112 }
8113
8114 assert(SrcIdx == 4);
8115
8116 auto ComprIt = OptionalIdx.find(AMDGPUOperand::ImmTyExpCompr);
8117 bool Compr = ComprIt != OptionalIdx.end() &&
8118 ((AMDGPUOperand &)*Operands[ComprIt->second]).getImm();
8119 if (Compr) {
8120 Inst.getOperand(OperandIdx[1]) = Inst.getOperand(OperandIdx[2]);
8121 Inst.getOperand(OperandIdx[2]).setReg(MCRegister());
8122 Inst.getOperand(OperandIdx[3]).setReg(MCRegister());
8123 }
8124
8125 for (auto i = 0; i < SrcIdx; ++i) {
8126 if (Inst.getOperand(OperandIdx[i]).getReg()) {
8127 EnMask |= Compr ? (0x3 << i * 2) : (0x1 << i);
8128 }
8129 }
8130
8131 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpVM);
8132 addOptionalImmOperand(Inst, Operands, OptionalIdx,
8133 AMDGPUOperand::ImmTyExpCompr);
8134
8135 Inst.addOperand(MCOperand::createImm(EnMask));
8136
8137 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDone);
8138 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyRowEn);
8139}
8140
8141//===----------------------------------------------------------------------===//
8142// s_waitcnt
8143//===----------------------------------------------------------------------===//
8144
8145static bool encodeCnt(const AMDGPU::IsaVersion ISA, int64_t &IntVal,
8146 int64_t CntVal, bool Saturate,
8147 unsigned (*encode)(const IsaVersion &Version, unsigned,
8148 unsigned),
8149 unsigned (*decode)(const IsaVersion &Version, unsigned)) {
8150 bool Failed = false;
8151
8152 IntVal = encode(ISA, IntVal, CntVal);
8153 if (CntVal != decode(ISA, IntVal)) {
8154 if (Saturate) {
8155 IntVal = encode(ISA, IntVal, -1);
8156 } else {
8157 Failed = true;
8158 }
8159 }
8160 return Failed;
8161}
8162
8163bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
8164
8165 SMLoc CntLoc = getLoc();
8166 StringRef CntName = getTokenStr();
8167
8168 if (!skipToken(AsmToken::Identifier, "expected a counter name") ||
8169 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8170 return false;
8171
8172 int64_t CntVal;
8173 SMLoc ValLoc = getLoc();
8174 if (!parseExpr(CntVal))
8175 return false;
8176
8177 bool Failed = true;
8178 bool Sat = CntName.ends_with("_sat");
8179
8180 if (CntName == "vmcnt" || CntName == "vmcnt_sat") {
8181 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeVmcnt, decodeVmcnt);
8182 } else if (CntName == "expcnt" || CntName == "expcnt_sat") {
8183 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeExpcnt, decodeExpcnt);
8184 } else if (CntName == "lgkmcnt" || CntName == "lgkmcnt_sat") {
8185 Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeLgkmcnt, decodeLgkmcnt);
8186 } else {
8187 Error(CntLoc, "invalid counter name " + CntName);
8188 return false;
8189 }
8190
8191 if (Failed) {
8192 Error(ValLoc, "too large value for " + CntName);
8193 return false;
8194 }
8195
8196 if (!skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8197 return false;
8198
8199 if (trySkipToken(AsmToken::Amp) || trySkipToken(AsmToken::Comma)) {
8200 if (isToken(AsmToken::EndOfStatement)) {
8201 Error(getLoc(), "expected a counter name");
8202 return false;
8203 }
8204 }
8205
8206 return true;
8207}
8208
8209ParseStatus AMDGPUAsmParser::parseSWaitCnt(OperandVector &Operands) {
8210 int64_t Waitcnt = getWaitcntBitMask(ISA);
8211 SMLoc S = getLoc();
8212
8213 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8214 while (!isToken(AsmToken::EndOfStatement)) {
8215 if (!parseCnt(Waitcnt))
8216 return ParseStatus::Failure;
8217 }
8218 } else {
8219 if (!parseExpr(Waitcnt))
8220 return ParseStatus::Failure;
8221 }
8222
8223 Operands.push_back(AMDGPUOperand::CreateImm(this, Waitcnt, S));
8224 return ParseStatus::Success;
8225}
8226
8227bool AMDGPUAsmParser::parseDelay(int64_t &Delay) {
8228 SMLoc FieldLoc = getLoc();
8229 StringRef FieldName = getTokenStr();
8230 if (!skipToken(AsmToken::Identifier, "expected a field name") ||
8231 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8232 return false;
8233
8234 SMLoc ValueLoc = getLoc();
8235 StringRef ValueName = getTokenStr();
8236 if (!skipToken(AsmToken::Identifier, "expected a value name") ||
8237 !skipToken(AsmToken::RParen, "expected a right parenthesis"))
8238 return false;
8239
8240 unsigned Shift;
8241 if (FieldName == "instid0") {
8242 Shift = 0;
8243 } else if (FieldName == "instskip") {
8244 Shift = 4;
8245 } else if (FieldName == "instid1") {
8246 Shift = 7;
8247 } else {
8248 Error(FieldLoc, "invalid field name " + FieldName);
8249 return false;
8250 }
8251
8252 int Value;
8253 if (Shift == 4) {
8254 // Parse values for instskip.
8255 Value = StringSwitch<int>(ValueName)
8256 .Case("SAME", 0)
8257 .Case("NEXT", 1)
8258 .Case("SKIP_1", 2)
8259 .Case("SKIP_2", 3)
8260 .Case("SKIP_3", 4)
8261 .Case("SKIP_4", 5)
8262 .Default(-1);
8263 } else {
8264 // Parse values for instid0 and instid1.
8265 Value = StringSwitch<int>(ValueName)
8266 .Case("NO_DEP", 0)
8267 .Case("VALU_DEP_1", 1)
8268 .Case("VALU_DEP_2", 2)
8269 .Case("VALU_DEP_3", 3)
8270 .Case("VALU_DEP_4", 4)
8271 .Case("TRANS32_DEP_1", 5)
8272 .Case("TRANS32_DEP_2", 6)
8273 .Case("TRANS32_DEP_3", 7)
8274 .Case("FMA_ACCUM_CYCLE_1", 8)
8275 .Case("SALU_CYCLE_1", 9)
8276 .Case("SALU_CYCLE_2", 10)
8277 .Case("SALU_CYCLE_3", 11)
8278 .Default(-1);
8279 }
8280 if (Value < 0) {
8281 Error(ValueLoc, "invalid value name " + ValueName);
8282 return false;
8283 }
8284
8285 Delay |= Value << Shift;
8286 return true;
8287}
8288
8289ParseStatus AMDGPUAsmParser::parseSDelayALU(OperandVector &Operands) {
8290 int64_t Delay = 0;
8291 SMLoc S = getLoc();
8292
8293 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8294 do {
8295 if (!parseDelay(Delay))
8296 return ParseStatus::Failure;
8297 } while (trySkipToken(AsmToken::Pipe));
8298 } else {
8299 if (!parseExpr(Delay))
8300 return ParseStatus::Failure;
8301 }
8302
8303 Operands.push_back(AMDGPUOperand::CreateImm(this, Delay, S));
8304 return ParseStatus::Success;
8305}
8306
8307bool AMDGPUOperand::isSWaitCnt() const { return isImm(); }
8308
8309bool AMDGPUOperand::isSDelayALU() const { return isImm(); }
8310
8311//===----------------------------------------------------------------------===//
8312// DepCtr
8313//===----------------------------------------------------------------------===//
8314
8315void AMDGPUAsmParser::depCtrError(SMLoc Loc, int ErrorId,
8316 StringRef DepCtrName) {
8317 switch (ErrorId) {
8318 case OPR_ID_UNKNOWN:
8319 Error(Loc, Twine("invalid counter name ", DepCtrName));
8320 return;
8321 case OPR_ID_UNSUPPORTED:
8322 Error(Loc, Twine(DepCtrName, " is not supported on this GPU"));
8323 return;
8324 case OPR_ID_DUPLICATE:
8325 Error(Loc, Twine("duplicate counter name ", DepCtrName));
8326 return;
8327 case OPR_VAL_INVALID:
8328 Error(Loc, Twine("invalid value for ", DepCtrName));
8329 return;
8330 default:
8331 assert(false);
8332 }
8333}
8334
8335bool AMDGPUAsmParser::parseDepCtr(int64_t &DepCtr, unsigned &UsedOprMask) {
8336
8337 using namespace llvm::AMDGPU::DepCtr;
8338
8339 SMLoc DepCtrLoc = getLoc();
8340 StringRef DepCtrName = getTokenStr();
8341
8342 if (!skipToken(AsmToken::Identifier, "expected a counter name") ||
8343 !skipToken(AsmToken::LParen, "expected a left parenthesis"))
8344 return false;
8345
8346 int64_t ExprVal;
8347 if (!parseExpr(ExprVal))
8348 return false;
8349
8350 unsigned PrevOprMask = UsedOprMask;
8351 int CntVal = encodeDepCtr(DepCtrName, ExprVal, UsedOprMask, getSTI());
8352
8353 if (CntVal < 0) {
8354 depCtrError(DepCtrLoc, CntVal, DepCtrName);
8355 return false;
8356 }
8357
8358 if (!skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8359 return false;
8360
8361 if (trySkipToken(AsmToken::Amp) || trySkipToken(AsmToken::Comma)) {
8362 if (isToken(AsmToken::EndOfStatement)) {
8363 Error(getLoc(), "expected a counter name");
8364 return false;
8365 }
8366 }
8367
8368 int64_t CntValMask = PrevOprMask ^ UsedOprMask;
8369 DepCtr = (DepCtr & ~CntValMask) | CntVal;
8370 return true;
8371}
8372
8373ParseStatus AMDGPUAsmParser::parseDepCtr(OperandVector &Operands) {
8374 using namespace llvm::AMDGPU::DepCtr;
8375
8376 int64_t DepCtr = getDefaultDepCtrEncoding(getSTI());
8377 SMLoc Loc = getLoc();
8378
8379 if (isToken(AsmToken::Identifier) && peekToken().is(AsmToken::LParen)) {
8380 unsigned UsedOprMask = 0;
8381 while (!isToken(AsmToken::EndOfStatement)) {
8382 if (!parseDepCtr(DepCtr, UsedOprMask))
8383 return ParseStatus::Failure;
8384 }
8385 } else {
8386 if (!parseExpr(DepCtr))
8387 return ParseStatus::Failure;
8388 }
8389
8390 Operands.push_back(AMDGPUOperand::CreateImm(this, DepCtr, Loc));
8391 return ParseStatus::Success;
8392}
8393
8394bool AMDGPUOperand::isDepCtr() const { return isS16Imm(); }
8395
8396//===----------------------------------------------------------------------===//
8397// hwreg
8398//===----------------------------------------------------------------------===//
8399
8400ParseStatus AMDGPUAsmParser::parseHwregFunc(OperandInfoTy &HwReg,
8401 OperandInfoTy &Offset,
8402 OperandInfoTy &Width) {
8403 using namespace llvm::AMDGPU::Hwreg;
8404
8405 if (!trySkipId("hwreg", AsmToken::LParen))
8406 return ParseStatus::NoMatch;
8407
8408 // The register may be specified by name or using a numeric code
8409 HwReg.Loc = getLoc();
8410 if (isToken(AsmToken::Identifier) &&
8411 (HwReg.Val = getHwregId(getTokenStr(), getSTI())) != OPR_ID_UNKNOWN) {
8412 HwReg.IsSymbolic = true;
8413 lex(); // skip register name
8414 } else if (!parseExpr(HwReg.Val, "a register name")) {
8415 return ParseStatus::Failure;
8416 }
8417
8418 if (trySkipToken(AsmToken::RParen))
8419 return ParseStatus::Success;
8420
8421 // parse optional params
8422 if (!skipToken(AsmToken::Comma, "expected a comma or a closing parenthesis"))
8423 return ParseStatus::Failure;
8424
8425 Offset.Loc = getLoc();
8426 if (!parseExpr(Offset.Val))
8427 return ParseStatus::Failure;
8428
8429 if (!skipToken(AsmToken::Comma, "expected a comma"))
8430 return ParseStatus::Failure;
8431
8432 Width.Loc = getLoc();
8433 if (!parseExpr(Width.Val) ||
8434 !skipToken(AsmToken::RParen, "expected a closing parenthesis"))
8435 return ParseStatus::Failure;
8436
8437 return ParseStatus::Success;
8438}
8439
8440ParseStatus AMDGPUAsmParser::parseHwreg(OperandVector &Operands) {
8441 using namespace llvm::AMDGPU::Hwreg;
8442
8443 int64_t ImmVal = 0;
8444 SMLoc Loc = getLoc();
8445
8446 StructuredOpField HwReg("id", "hardware register", HwregId::Width,
8447 HwregId::Default);
8448 StructuredOpField Offset("offset", "bit offset", HwregOffset::Width,
8449 HwregOffset::Default);
8450 struct : StructuredOpField {
8451 using StructuredOpField::StructuredOpField;
8452 bool validate(AMDGPUAsmParser &Parser) const override {
8453 if (!isUIntN(Width, Val - 1))
8454 return Error(Parser, "only values from 1 to 32 are legal");
8455 return true;
8456 }
8457 } Width("size", "bitfield width", HwregSize::Width, HwregSize::Default);
8458 ParseStatus Res = parseStructuredOpFields({&HwReg, &Offset, &Width});
8459
8460 if (Res.isNoMatch())
8461 Res = parseHwregFunc(HwReg, Offset, Width);
8462
8463 if (Res.isSuccess()) {
8464 if (!validateStructuredOpFields({&HwReg, &Offset, &Width}))
8465 return ParseStatus::Failure;
8466 ImmVal = HwregEncoding::encode(HwReg.Val, Offset.Val, Width.Val);
8467 }
8468
8469 if (Res.isNoMatch() &&
8470 parseExpr(ImmVal, "a hwreg macro, structured immediate"))
8472
8473 if (!Res.isSuccess())
8474 return ParseStatus::Failure;
8475
8476 if (!isUInt<16>(ImmVal))
8477 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8478 Operands.push_back(
8479 AMDGPUOperand::CreateImm(this, ImmVal, Loc, AMDGPUOperand::ImmTyHwreg));
8480 return ParseStatus::Success;
8481}
8482
8483bool AMDGPUOperand::isHwreg() const { return isImmTy(ImmTyHwreg); }
8484
8485//===----------------------------------------------------------------------===//
8486// sendmsg
8487//===----------------------------------------------------------------------===//
8488
8489bool AMDGPUAsmParser::parseSendMsgBody(OperandInfoTy &Msg, OperandInfoTy &Op,
8490 OperandInfoTy &Stream) {
8491 using namespace llvm::AMDGPU::SendMsg;
8492
8493 Msg.Loc = getLoc();
8494 if (isToken(AsmToken::Identifier) &&
8495 (Msg.Val = getMsgId(getTokenStr(), getSTI())) != OPR_ID_UNKNOWN) {
8496 Msg.IsSymbolic = true;
8497 lex(); // skip message name
8498 } else if (!parseExpr(Msg.Val, "a message name")) {
8499 return false;
8500 }
8501
8502 if (trySkipToken(AsmToken::Comma)) {
8503 Op.IsDefined = true;
8504 Op.Loc = getLoc();
8505 if (isToken(AsmToken::Identifier) &&
8506 (Op.Val = getMsgOpId(Msg.Val, getTokenStr(), getSTI())) !=
8508 lex(); // skip operation name
8509 } else if (!parseExpr(Op.Val, "an operation name")) {
8510 return false;
8511 }
8512
8513 if (trySkipToken(AsmToken::Comma)) {
8514 Stream.IsDefined = true;
8515 Stream.Loc = getLoc();
8516 if (!parseExpr(Stream.Val))
8517 return false;
8518 }
8519 }
8520
8521 return skipToken(AsmToken::RParen, "expected a closing parenthesis");
8522}
8523
8524bool AMDGPUAsmParser::validateSendMsg(const OperandInfoTy &Msg,
8525 const OperandInfoTy &Op,
8526 const OperandInfoTy &Stream) {
8527 using namespace llvm::AMDGPU::SendMsg;
8528
8529 // Validation strictness depends on whether message is specified
8530 // in a symbolic or in a numeric form. In the latter case
8531 // only encoding possibility is checked.
8532 bool Strict = Msg.IsSymbolic;
8533
8534 if (Strict) {
8535 if (Msg.Val == OPR_ID_UNSUPPORTED) {
8536 Error(Msg.Loc, "specified message id is not supported on this GPU");
8537 return false;
8538 }
8539 } else {
8540 if (!isValidMsgId(Msg.Val, getSTI())) {
8541 Error(Msg.Loc, "invalid message id");
8542 return false;
8543 }
8544 }
8545 if (Strict && (msgRequiresOp(Msg.Val, getSTI()) != Op.IsDefined)) {
8546 if (Op.IsDefined) {
8547 Error(Op.Loc, "message does not support operations");
8548 } else {
8549 Error(Msg.Loc, "missing message operation");
8550 }
8551 return false;
8552 }
8553 if (!isValidMsgOp(Msg.Val, Op.Val, getSTI(), Strict)) {
8554 if (Op.Val == OPR_ID_UNSUPPORTED)
8555 Error(Op.Loc, "specified operation id is not supported on this GPU");
8556 else
8557 Error(Op.Loc, "invalid operation id");
8558 return false;
8559 }
8560 if (Strict && !msgSupportsStream(Msg.Val, Op.Val, getSTI()) &&
8561 Stream.IsDefined) {
8562 Error(Stream.Loc, "message operation does not support streams");
8563 return false;
8564 }
8565 if (!isValidMsgStream(Msg.Val, Op.Val, Stream.Val, getSTI(), Strict)) {
8566 Error(Stream.Loc, "invalid message stream id");
8567 return false;
8568 }
8569 return true;
8570}
8571
8572ParseStatus AMDGPUAsmParser::parseSendMsg(OperandVector &Operands) {
8573 using namespace llvm::AMDGPU::SendMsg;
8574
8575 int64_t ImmVal = 0;
8576 SMLoc Loc = getLoc();
8577
8578 if (trySkipId("sendmsg", AsmToken::LParen)) {
8579 OperandInfoTy Msg(OPR_ID_UNKNOWN);
8580 OperandInfoTy Op(OP_NONE_);
8581 OperandInfoTy Stream(STREAM_ID_NONE_);
8582 if (parseSendMsgBody(Msg, Op, Stream) && validateSendMsg(Msg, Op, Stream)) {
8583 ImmVal = encodeMsg(Msg.Val, Op.Val, Stream.Val);
8584 } else {
8585 return ParseStatus::Failure;
8586 }
8587 } else if (parseExpr(ImmVal, "a sendmsg macro")) {
8588 if (ImmVal < 0 || !isUInt<16>(ImmVal))
8589 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8590 } else {
8591 return ParseStatus::Failure;
8592 }
8593
8594 Operands.push_back(
8595 AMDGPUOperand::CreateImm(this, ImmVal, Loc, AMDGPUOperand::ImmTySendMsg));
8596 return ParseStatus::Success;
8597}
8598
8599bool AMDGPUOperand::isSendMsg() const { return isImmTy(ImmTySendMsg); }
8600
8601ParseStatus AMDGPUAsmParser::parseWaitEvent(OperandVector &Operands) {
8602 using namespace llvm::AMDGPU::WaitEvent;
8603
8604 SMLoc Loc = getLoc();
8605 int64_t ImmVal = 0;
8606
8607 StructuredOpField DontWaitExportReady("dont_wait_export_ready", "bit value",
8608 1, 0);
8609 StructuredOpField ExportReady("export_ready", "bit value", 1, 0);
8610
8611 StructuredOpField *TargetBitfield =
8612 isGFX11() ? &DontWaitExportReady : &ExportReady;
8613
8614 ParseStatus Res = parseStructuredOpFields({TargetBitfield});
8615 if (Res.isNoMatch() && parseExpr(ImmVal, "structured immediate"))
8617 else if (Res.isSuccess()) {
8618 if (!validateStructuredOpFields({TargetBitfield}))
8619 return ParseStatus::Failure;
8620 ImmVal = TargetBitfield->Val;
8621 }
8622
8623 if (!Res.isSuccess())
8624 return ParseStatus::Failure;
8625
8626 if (!isUInt<16>(ImmVal))
8627 return Error(Loc, "invalid immediate: only 16-bit values are legal");
8628
8629 Operands.push_back(AMDGPUOperand::CreateImm(this, ImmVal, Loc,
8630 AMDGPUOperand::ImmTyWaitEvent));
8631 return ParseStatus::Success;
8632}
8633
8634bool AMDGPUOperand::isWaitEvent() const { return isImmTy(ImmTyWaitEvent); }
8635
8636//===----------------------------------------------------------------------===//
8637// v_interp
8638//===----------------------------------------------------------------------===//
8639
8640ParseStatus AMDGPUAsmParser::parseInterpSlot(OperandVector &Operands) {
8641 StringRef Str;
8642 SMLoc S = getLoc();
8643
8644 if (!parseId(Str))
8645 return ParseStatus::NoMatch;
8646
8647 int Slot = StringSwitch<int>(Str)
8648 .Case("p10", 0)
8649 .Case("p20", 1)
8650 .Case("p0", 2)
8651 .Default(-1);
8652
8653 if (Slot == -1)
8654 return Error(S, "invalid interpolation slot");
8655
8656 Operands.push_back(
8657 AMDGPUOperand::CreateImm(this, Slot, S, AMDGPUOperand::ImmTyInterpSlot));
8658 return ParseStatus::Success;
8659}
8660
8661ParseStatus AMDGPUAsmParser::parseInterpAttr(OperandVector &Operands) {
8662 StringRef Str;
8663 SMLoc S = getLoc();
8664
8665 if (!parseId(Str))
8666 return ParseStatus::NoMatch;
8667
8668 if (!Str.starts_with("attr"))
8669 return Error(S, "invalid interpolation attribute");
8670
8671 StringRef Chan = Str.take_back(2);
8672 int AttrChan = StringSwitch<int>(Chan)
8673 .Case(".x", 0)
8674 .Case(".y", 1)
8675 .Case(".z", 2)
8676 .Case(".w", 3)
8677 .Default(-1);
8678 if (AttrChan == -1)
8679 return Error(S, "invalid or missing interpolation attribute channel");
8680
8681 Str = Str.drop_back(2).drop_front(4);
8682
8683 uint8_t Attr;
8684 if (Str.getAsInteger(10, Attr))
8685 return Error(S, "invalid or missing interpolation attribute number");
8686
8687 if (Attr > 32)
8688 return Error(S, "out of bounds interpolation attribute number");
8689
8690 SMLoc SChan = SMLoc::getFromPointer(Chan.data());
8691
8692 Operands.push_back(
8693 AMDGPUOperand::CreateImm(this, Attr, S, AMDGPUOperand::ImmTyInterpAttr));
8694 Operands.push_back(AMDGPUOperand::CreateImm(
8695 this, AttrChan, SChan, AMDGPUOperand::ImmTyInterpAttrChan));
8696 return ParseStatus::Success;
8697}
8698
8699//===----------------------------------------------------------------------===//
8700// exp
8701//===----------------------------------------------------------------------===//
8702
8703ParseStatus AMDGPUAsmParser::parseExpTgt(OperandVector &Operands) {
8704 using namespace llvm::AMDGPU::Exp;
8705
8706 StringRef Str;
8707 SMLoc S = getLoc();
8708
8709 if (!parseId(Str))
8710 return ParseStatus::NoMatch;
8711
8712 unsigned Id = getTgtId(Str);
8713 if (Id == ET_INVALID || !isSupportedTgtId(Id, getSTI()))
8714 return Error(S, (Id == ET_INVALID)
8715 ? "invalid exp target"
8716 : "exp target is not supported on this GPU");
8717
8718 Operands.push_back(
8719 AMDGPUOperand::CreateImm(this, Id, S, AMDGPUOperand::ImmTyExpTgt));
8720 return ParseStatus::Success;
8721}
8722
8723//===----------------------------------------------------------------------===//
8724// parser helpers
8725//===----------------------------------------------------------------------===//
8726
8727bool AMDGPUAsmParser::isId(const AsmToken &Token, const StringRef Id) const {
8728 return Token.is(AsmToken::Identifier) && Token.getString() == Id;
8729}
8730
8731bool AMDGPUAsmParser::isId(const StringRef Id) const {
8732 return isId(getToken(), Id);
8733}
8734
8735bool AMDGPUAsmParser::isToken(const AsmToken::TokenKind Kind) const {
8736 return getTokenKind() == Kind;
8737}
8738
8739StringRef AMDGPUAsmParser::getId() const {
8740 return isToken(AsmToken::Identifier) ? getTokenStr() : StringRef();
8741}
8742
8743bool AMDGPUAsmParser::trySkipId(const StringRef Id) {
8744 if (isId(Id)) {
8745 lex();
8746 return true;
8747 }
8748 return false;
8749}
8750
8751bool AMDGPUAsmParser::trySkipId(const StringRef Pref, const StringRef Id) {
8752 if (isToken(AsmToken::Identifier)) {
8753 StringRef Tok = getTokenStr();
8754 if (Tok.starts_with(Pref) && Tok.drop_front(Pref.size()) == Id) {
8755 lex();
8756 return true;
8757 }
8758 }
8759 return false;
8760}
8761
8762bool AMDGPUAsmParser::trySkipId(const StringRef Id,
8763 const AsmToken::TokenKind Kind) {
8764 if (isId(Id) && peekToken().is(Kind)) {
8765 lex();
8766 lex();
8767 return true;
8768 }
8769 return false;
8770}
8771
8772bool AMDGPUAsmParser::trySkipToken(const AsmToken::TokenKind Kind) {
8773 if (isToken(Kind)) {
8774 lex();
8775 return true;
8776 }
8777 return false;
8778}
8779
8780bool AMDGPUAsmParser::skipToken(const AsmToken::TokenKind Kind,
8781 const StringRef ErrMsg) {
8782 if (!trySkipToken(Kind)) {
8783 Error(getLoc(), ErrMsg);
8784 return false;
8785 }
8786 return true;
8787}
8788
8789bool AMDGPUAsmParser::parseExpr(int64_t &Imm, StringRef Expected) {
8790 SMLoc S = getLoc();
8791
8792 const MCExpr *Expr;
8793 if (Parser.parseExpression(Expr))
8794 return false;
8795
8796 if (Expr->evaluateAsAbsolute(Imm))
8797 return true;
8798
8799 if (Expected.empty()) {
8800 Error(S, "expected absolute expression");
8801 } else {
8802 Error(S,
8803 Twine("expected ", Expected) + Twine(" or an absolute expression"));
8804 }
8805 return false;
8806}
8807
8808bool AMDGPUAsmParser::parseExpr(OperandVector &Operands) {
8809 SMLoc S = getLoc();
8810
8811 const MCExpr *Expr;
8812 if (Parser.parseExpression(Expr))
8813 return false;
8814
8815 int64_t IntVal;
8816 if (Expr->evaluateAsAbsolute(IntVal)) {
8817 Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
8818 } else {
8819 Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
8820 }
8821 return true;
8822}
8823
8824bool AMDGPUAsmParser::parseString(StringRef &Val, const StringRef ErrMsg) {
8825 if (isToken(AsmToken::String)) {
8826 Val = getToken().getStringContents();
8827 lex();
8828 return true;
8829 }
8830 Error(getLoc(), ErrMsg);
8831 return false;
8832}
8833
8834bool AMDGPUAsmParser::parseId(StringRef &Val, const StringRef ErrMsg) {
8835 if (isToken(AsmToken::Identifier)) {
8836 Val = getTokenStr();
8837 lex();
8838 return true;
8839 }
8840 if (!ErrMsg.empty())
8841 Error(getLoc(), ErrMsg);
8842 return false;
8843}
8844
8845AsmToken AMDGPUAsmParser::getToken() const { return Parser.getTok(); }
8846
8847AsmToken AMDGPUAsmParser::peekToken(bool ShouldSkipSpace) {
8848 return isToken(AsmToken::EndOfStatement)
8849 ? getToken()
8850 : getLexer().peekTok(ShouldSkipSpace);
8851}
8852
8853void AMDGPUAsmParser::peekTokens(MutableArrayRef<AsmToken> Tokens) {
8854 auto TokCount = getLexer().peekTokens(Tokens);
8855
8856 for (auto Idx = TokCount; Idx < Tokens.size(); ++Idx)
8857 Tokens[Idx] = AsmToken(AsmToken::Error, "");
8858}
8859
8860AsmToken::TokenKind AMDGPUAsmParser::getTokenKind() const {
8861 return getLexer().getKind();
8862}
8863
8864SMLoc AMDGPUAsmParser::getLoc() const { return getToken().getLoc(); }
8865
8866StringRef AMDGPUAsmParser::getTokenStr() const {
8867 return getToken().getString();
8868}
8869
8870void AMDGPUAsmParser::lex() { Parser.Lex(); }
8871
8872const AMDGPUOperand &
8873AMDGPUAsmParser::findMCOperand(const OperandVector &Operands,
8874 int MCOpIdx) const {
8875 for (const auto &Op : Operands) {
8876 const AMDGPUOperand &TargetOp = static_cast<AMDGPUOperand &>(*Op);
8877 if (TargetOp.getMCOpIdx() == MCOpIdx)
8878 return TargetOp;
8879 }
8880 llvm_unreachable("no such MC operand!");
8881}
8882
8883SMLoc AMDGPUAsmParser::getInstLoc(const OperandVector &Operands) const {
8884 return ((AMDGPUOperand &)*Operands[0]).getStartLoc();
8885}
8886
8887// Returns one of the given locations that comes later in the source.
8888SMLoc AMDGPUAsmParser::getLaterLoc(SMLoc a, SMLoc b) {
8889 return a.getPointer() < b.getPointer() ? b : a;
8890}
8891
8892SMLoc AMDGPUAsmParser::getOperandLoc(const OperandVector &Operands,
8893 int MCOpIdx) const {
8894 return findMCOperand(Operands, MCOpIdx).getStartLoc();
8895}
8896
8897SMLoc AMDGPUAsmParser::getOperandLoc(
8898 std::function<bool(const AMDGPUOperand &)> Test,
8899 const OperandVector &Operands) const {
8900 for (unsigned i = Operands.size() - 1; i > 0; --i) {
8901 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
8902 if (Test(Op))
8903 return Op.getStartLoc();
8904 }
8905 return getInstLoc(Operands);
8906}
8907
8908SMLoc AMDGPUAsmParser::getImmLoc(AMDGPUOperand::ImmTy Type,
8909 const OperandVector &Operands) const {
8910 auto Test = [=](const AMDGPUOperand &Op) { return Op.isImmTy(Type); };
8911 return getOperandLoc(Test, Operands);
8912}
8913
8914ParseStatus
8915AMDGPUAsmParser::parseStructuredOpFields(ArrayRef<StructuredOpField *> Fields) {
8916 if (!trySkipToken(AsmToken::LCurly))
8917 return ParseStatus::NoMatch;
8918
8919 bool First = true;
8920 while (!trySkipToken(AsmToken::RCurly)) {
8921 if (!First &&
8922 !skipToken(AsmToken::Comma, "comma or closing brace expected"))
8923 return ParseStatus::Failure;
8924
8925 StringRef Id = getTokenStr();
8926 SMLoc IdLoc = getLoc();
8927 if (!skipToken(AsmToken::Identifier, "field name expected") ||
8928 !skipToken(AsmToken::Colon, "colon expected"))
8929 return ParseStatus::Failure;
8930
8931 const auto *I =
8932 find_if(Fields, [Id](StructuredOpField *F) { return F->Id == Id; });
8933 if (I == Fields.end())
8934 return Error(IdLoc, "unknown field");
8935 if ((*I)->IsDefined)
8936 return Error(IdLoc, "duplicate field");
8937
8938 // TODO: Support symbolic values.
8939 (*I)->Loc = getLoc();
8940 if (!parseExpr((*I)->Val))
8941 return ParseStatus::Failure;
8942 (*I)->IsDefined = true;
8943
8944 First = false;
8945 }
8946 return ParseStatus::Success;
8947}
8948
8949bool AMDGPUAsmParser::validateStructuredOpFields(
8951 return all_of(Fields, [this](const StructuredOpField *F) {
8952 return F->validate(*this);
8953 });
8954}
8955
8956//===----------------------------------------------------------------------===//
8957// swizzle
8958//===----------------------------------------------------------------------===//
8959
8961static unsigned encodeBitmaskPerm(const unsigned AndMask, const unsigned OrMask,
8962 const unsigned XorMask) {
8963 using namespace llvm::AMDGPU::Swizzle;
8964
8965 return BITMASK_PERM_ENC | (AndMask << BITMASK_AND_SHIFT) |
8966 (OrMask << BITMASK_OR_SHIFT) | (XorMask << BITMASK_XOR_SHIFT);
8967}
8968
8969bool AMDGPUAsmParser::parseSwizzleOperand(int64_t &Op, const unsigned MinVal,
8970 const unsigned MaxVal,
8971 const Twine &ErrMsg, SMLoc &Loc) {
8972 if (!skipToken(AsmToken::Comma, "expected a comma")) {
8973 return false;
8974 }
8975 Loc = getLoc();
8976 if (!parseExpr(Op)) {
8977 return false;
8978 }
8979 if (Op < MinVal || Op > MaxVal) {
8980 Error(Loc, ErrMsg);
8981 return false;
8982 }
8983
8984 return true;
8985}
8986
8987bool AMDGPUAsmParser::parseSwizzleOperands(const unsigned OpNum, int64_t *Op,
8988 const unsigned MinVal,
8989 const unsigned MaxVal,
8990 const StringRef ErrMsg) {
8991 SMLoc Loc;
8992 for (unsigned i = 0; i < OpNum; ++i) {
8993 if (!parseSwizzleOperand(Op[i], MinVal, MaxVal, ErrMsg, Loc))
8994 return false;
8995 }
8996
8997 return true;
8998}
8999
9000bool AMDGPUAsmParser::parseSwizzleQuadPerm(int64_t &Imm) {
9001 using namespace llvm::AMDGPU::Swizzle;
9002
9003 int64_t Lane[LANE_NUM];
9004 if (parseSwizzleOperands(LANE_NUM, Lane, 0, LANE_MAX,
9005 "expected a 2-bit lane id")) {
9007 for (unsigned I = 0; I < LANE_NUM; ++I) {
9008 Imm |= Lane[I] << (LANE_SHIFT * I);
9009 }
9010 return true;
9011 }
9012 return false;
9013}
9014
9015bool AMDGPUAsmParser::parseSwizzleBroadcast(int64_t &Imm) {
9016 using namespace llvm::AMDGPU::Swizzle;
9017
9018 SMLoc Loc;
9019 int64_t GroupSize;
9020 int64_t LaneIdx;
9021
9022 if (!parseSwizzleOperand(GroupSize, 2, 32,
9023 "group size must be in the interval [2,32]", Loc)) {
9024 return false;
9025 }
9026 if (!isPowerOf2_64(GroupSize)) {
9027 Error(Loc, "group size must be a power of two");
9028 return false;
9029 }
9030 if (parseSwizzleOperand(LaneIdx, 0, GroupSize - 1,
9031 "lane id must be in the interval [0,group size - 1]",
9032 Loc)) {
9033 Imm = encodeBitmaskPerm(BITMASK_MAX - GroupSize + 1, LaneIdx, 0);
9034 return true;
9035 }
9036 return false;
9037}
9038
9039bool AMDGPUAsmParser::parseSwizzleReverse(int64_t &Imm) {
9040 using namespace llvm::AMDGPU::Swizzle;
9041
9042 SMLoc Loc;
9043 int64_t GroupSize;
9044
9045 if (!parseSwizzleOperand(GroupSize, 2, 32,
9046 "group size must be in the interval [2,32]", Loc)) {
9047 return false;
9048 }
9049 if (!isPowerOf2_64(GroupSize)) {
9050 Error(Loc, "group size must be a power of two");
9051 return false;
9052 }
9053
9054 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize - 1);
9055 return true;
9056}
9057
9058bool AMDGPUAsmParser::parseSwizzleSwap(int64_t &Imm) {
9059 using namespace llvm::AMDGPU::Swizzle;
9060
9061 SMLoc Loc;
9062 int64_t GroupSize;
9063
9064 if (!parseSwizzleOperand(GroupSize, 1, 16,
9065 "group size must be in the interval [1,16]", Loc)) {
9066 return false;
9067 }
9068 if (!isPowerOf2_64(GroupSize)) {
9069 Error(Loc, "group size must be a power of two");
9070 return false;
9071 }
9072
9073 Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize);
9074 return true;
9075}
9076
9077bool AMDGPUAsmParser::parseSwizzleBitmaskPerm(int64_t &Imm) {
9078 using namespace llvm::AMDGPU::Swizzle;
9079
9080 if (!skipToken(AsmToken::Comma, "expected a comma")) {
9081 return false;
9082 }
9083
9084 StringRef Ctl;
9085 SMLoc StrLoc = getLoc();
9086 if (!parseString(Ctl)) {
9087 return false;
9088 }
9089 if (Ctl.size() != BITMASK_WIDTH) {
9090 Error(StrLoc, "expected a 5-character mask");
9091 return false;
9092 }
9093
9094 unsigned AndMask = 0;
9095 unsigned OrMask = 0;
9096 unsigned XorMask = 0;
9097
9098 for (size_t i = 0; i < Ctl.size(); ++i) {
9099 unsigned Mask = 1 << (BITMASK_WIDTH - 1 - i);
9100 switch (Ctl[i]) {
9101 default:
9102 Error(StrLoc, "invalid mask");
9103 return false;
9104 case '0':
9105 break;
9106 case '1':
9107 OrMask |= Mask;
9108 break;
9109 case 'p':
9110 AndMask |= Mask;
9111 break;
9112 case 'i':
9113 AndMask |= Mask;
9114 XorMask |= Mask;
9115 break;
9116 }
9117 }
9118
9119 Imm = encodeBitmaskPerm(AndMask, OrMask, XorMask);
9120 return true;
9121}
9122
9123bool AMDGPUAsmParser::parseSwizzleFFT(int64_t &Imm) {
9124 using namespace llvm::AMDGPU::Swizzle;
9125
9126 if (!AMDGPU::isGFX9Plus(getSTI())) {
9127 Error(getLoc(), "FFT mode swizzle not supported on this GPU");
9128 return false;
9129 }
9130
9131 int64_t Swizzle;
9132 SMLoc Loc;
9133 if (!parseSwizzleOperand(Swizzle, 0, FFT_SWIZZLE_MAX,
9134 "FFT swizzle must be in the interval [0," +
9135 Twine(FFT_SWIZZLE_MAX) + Twine(']'),
9136 Loc))
9137 return false;
9138
9139 Imm = FFT_MODE_ENC | Swizzle;
9140 return true;
9141}
9142
9143bool AMDGPUAsmParser::parseSwizzleRotate(int64_t &Imm) {
9144 using namespace llvm::AMDGPU::Swizzle;
9145
9146 if (!AMDGPU::isGFX9Plus(getSTI())) {
9147 Error(getLoc(), "Rotate mode swizzle not supported on this GPU");
9148 return false;
9149 }
9150
9151 SMLoc Loc;
9152 int64_t Direction;
9153
9154 if (!parseSwizzleOperand(Direction, 0, 1,
9155 "direction must be 0 (left) or 1 (right)", Loc))
9156 return false;
9157
9158 int64_t RotateSize;
9159 if (!parseSwizzleOperand(
9160 RotateSize, 0, ROTATE_MAX_SIZE,
9161 "number of threads to rotate must be in the interval [0," +
9162 Twine(ROTATE_MAX_SIZE) + Twine(']'),
9163 Loc))
9164 return false;
9165
9167 (RotateSize << ROTATE_SIZE_SHIFT);
9168 return true;
9169}
9170
9171bool AMDGPUAsmParser::parseSwizzleOffset(int64_t &Imm) {
9172
9173 SMLoc OffsetLoc = getLoc();
9174
9175 if (!parseExpr(Imm, "a swizzle macro")) {
9176 return false;
9177 }
9178 if (!isUInt<16>(Imm)) {
9179 Error(OffsetLoc, "expected a 16-bit offset");
9180 return false;
9181 }
9182 return true;
9183}
9184
9185bool AMDGPUAsmParser::parseSwizzleMacro(int64_t &Imm) {
9186 using namespace llvm::AMDGPU::Swizzle;
9187
9188 if (skipToken(AsmToken::LParen, "expected a left parentheses")) {
9189
9190 SMLoc ModeLoc = getLoc();
9191 bool Ok = false;
9192
9193 if (trySkipId(IdSymbolic[ID_QUAD_PERM])) {
9194 Ok = parseSwizzleQuadPerm(Imm);
9195 } else if (trySkipId(IdSymbolic[ID_BITMASK_PERM])) {
9196 Ok = parseSwizzleBitmaskPerm(Imm);
9197 } else if (trySkipId(IdSymbolic[ID_BROADCAST])) {
9198 Ok = parseSwizzleBroadcast(Imm);
9199 } else if (trySkipId(IdSymbolic[ID_SWAP])) {
9200 Ok = parseSwizzleSwap(Imm);
9201 } else if (trySkipId(IdSymbolic[ID_REVERSE])) {
9202 Ok = parseSwizzleReverse(Imm);
9203 } else if (trySkipId(IdSymbolic[ID_FFT])) {
9204 Ok = parseSwizzleFFT(Imm);
9205 } else if (trySkipId(IdSymbolic[ID_ROTATE])) {
9206 Ok = parseSwizzleRotate(Imm);
9207 } else {
9208 Error(ModeLoc, "expected a swizzle mode");
9209 }
9210
9211 return Ok && skipToken(AsmToken::RParen, "expected a closing parentheses");
9212 }
9213
9214 return false;
9215}
9216
9217ParseStatus AMDGPUAsmParser::parseSwizzle(OperandVector &Operands) {
9218 SMLoc S = getLoc();
9219 int64_t Imm = 0;
9220
9221 if (trySkipId("offset")) {
9222
9223 bool Ok = false;
9224 if (skipToken(AsmToken::Colon, "expected a colon")) {
9225 if (trySkipId("swizzle")) {
9226 Ok = parseSwizzleMacro(Imm);
9227 } else {
9228 Ok = parseSwizzleOffset(Imm);
9229 }
9230 }
9231
9232 Operands.push_back(
9233 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTySwizzle));
9234
9236 }
9237 return ParseStatus::NoMatch;
9238}
9239
9240bool AMDGPUOperand::isSwizzle() const { return isImmTy(ImmTySwizzle); }
9241
9242//===----------------------------------------------------------------------===//
9243// VGPR Index Mode
9244//===----------------------------------------------------------------------===//
9245
9246int64_t AMDGPUAsmParser::parseGPRIdxMacro() {
9247
9248 using namespace llvm::AMDGPU::VGPRIndexMode;
9249
9250 if (trySkipToken(AsmToken::RParen)) {
9251 return OFF;
9252 }
9253
9254 int64_t Imm = 0;
9255
9256 while (true) {
9257 unsigned Mode = 0;
9258 SMLoc S = getLoc();
9259
9260 for (unsigned ModeId = ID_MIN; ModeId <= ID_MAX; ++ModeId) {
9261 if (trySkipId(IdSymbolic[ModeId])) {
9262 Mode = 1 << ModeId;
9263 break;
9264 }
9265 }
9266
9267 if (Mode == 0) {
9268 Error(S, (Imm == 0)
9269 ? "expected a VGPR index mode or a closing parenthesis"
9270 : "expected a VGPR index mode");
9271 return UNDEF;
9272 }
9273
9274 if (Imm & Mode) {
9275 Error(S, "duplicate VGPR index mode");
9276 return UNDEF;
9277 }
9278 Imm |= Mode;
9279
9280 if (trySkipToken(AsmToken::RParen))
9281 break;
9282 if (!skipToken(AsmToken::Comma,
9283 "expected a comma or a closing parenthesis"))
9284 return UNDEF;
9285 }
9286
9287 return Imm;
9288}
9289
9290ParseStatus AMDGPUAsmParser::parseGPRIdxMode(OperandVector &Operands) {
9291
9292 using namespace llvm::AMDGPU::VGPRIndexMode;
9293
9294 int64_t Imm = 0;
9295 SMLoc S = getLoc();
9296
9297 if (trySkipId("gpr_idx", AsmToken::LParen)) {
9298 Imm = parseGPRIdxMacro();
9299 if (Imm == UNDEF)
9300 return ParseStatus::Failure;
9301 } else {
9302 if (getParser().parseAbsoluteExpression(Imm))
9303 return ParseStatus::Failure;
9304 if (Imm < 0 || !isUInt<4>(Imm))
9305 return Error(S, "invalid immediate: only 4-bit values are legal");
9306 }
9307
9308 Operands.push_back(
9309 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTyGprIdxMode));
9310 return ParseStatus::Success;
9311}
9312
9313bool AMDGPUOperand::isGPRIdxMode() const { return isImmTy(ImmTyGprIdxMode); }
9314
9315//===----------------------------------------------------------------------===//
9316// sopp branch targets
9317//===----------------------------------------------------------------------===//
9318
9319ParseStatus AMDGPUAsmParser::parseSOPPBrTarget(OperandVector &Operands) {
9320
9321 // Make sure we are not parsing something
9322 // that looks like a label or an expression but is not.
9323 // This will improve error messages.
9324 if (isRegister() || isModifier())
9325 return ParseStatus::NoMatch;
9326
9327 if (!parseExpr(Operands))
9328 return ParseStatus::Failure;
9329
9330 AMDGPUOperand &Opr = ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
9331 assert(Opr.isImm() || Opr.isExpr());
9332 SMLoc Loc = Opr.getStartLoc();
9333
9334 // Currently we do not support arbitrary expressions as branch targets.
9335 // Only labels and absolute expressions are accepted.
9336 if (Opr.isExpr() && !Opr.isSymbolRefExpr()) {
9337 Error(Loc, "expected an absolute expression or a label");
9338 } else if (Opr.isImm() && !Opr.isS16Imm()) {
9339 Error(Loc, "expected a 16-bit signed jump offset");
9340 }
9341
9342 return ParseStatus::Success;
9343}
9344
9345ParseStatus AMDGPUAsmParser::parseSMEMOffsetPCRel(OperandVector &Operands) {
9346 if (isRegister() || isModifier())
9347 return ParseStatus::NoMatch;
9348 if (!parseExpr(Operands))
9349 return ParseStatus::Failure;
9350 AMDGPUOperand &Opr = ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
9351 assert(Opr.isImm() || Opr.isExpr());
9352 // Numeric operands are the encoded offset and are range-checked later.
9353 // Labels are resolved by fixup_si_smem_pcrel.
9354 if (Opr.isExpr() && (!Opr.isSymbolRefExpr() || Opr.hasSymbolSpecifier()))
9355 Error(Opr.getStartLoc(),
9356 "expected an absolute expression or an unqualified label");
9357 return ParseStatus::Success;
9358}
9359
9360//===----------------------------------------------------------------------===//
9361// Boolean holding registers
9362//===----------------------------------------------------------------------===//
9363
9364ParseStatus AMDGPUAsmParser::parseBoolReg(OperandVector &Operands) {
9365 return parseReg(Operands);
9366}
9367
9368//===----------------------------------------------------------------------===//
9369// mubuf
9370//===----------------------------------------------------------------------===//
9371
9372void AMDGPUAsmParser::cvtMubufImpl(MCInst &Inst, const OperandVector &Operands,
9373 bool IsAtomic) {
9374 OptionalImmIndexMap OptionalIdx;
9375 unsigned FirstOperandIdx = 1;
9376 bool IsAtomicReturn = false;
9377
9378 if (IsAtomic) {
9379 IsAtomicReturn = SIInstrFlags::isAtomicRet(MII, Inst);
9380 }
9381
9382 for (unsigned i = FirstOperandIdx, e = Operands.size(); i != e; ++i) {
9383 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
9384
9385 // Add the register arguments
9386 if (Op.isReg()) {
9387 Op.addRegOperands(Inst, 1);
9388 // Insert a tied src for atomic return dst.
9389 // This cannot be postponed as subsequent calls to
9390 // addImmOperands rely on correct number of MC operands.
9391 if (IsAtomicReturn && i == FirstOperandIdx)
9392 Op.addRegOperands(Inst, 1);
9393 continue;
9394 }
9395
9396 // Handle the case where soffset is an immediate
9397 if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
9398 Op.addImmOperands(Inst, 1);
9399 continue;
9400 }
9401
9402 // Handle tokens like 'offen' which are sometimes hard-coded into the
9403 // asm string. There are no MCInst operands for these.
9404 if (Op.isToken()) {
9405 continue;
9406 }
9407 assert(Op.isImm());
9408
9409 // Handle optional arguments
9410 OptionalIdx[Op.getImmTy()] = i;
9411 }
9412
9413 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9414 AMDGPUOperand::ImmTyOffset);
9415 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyCPol,
9416 0);
9417 // Parse a dummy operand as a placeholder for the SWZ operand. This enforces
9418 // agreement between MCInstrDesc.getNumOperands and MCInst.getNumOperands.
9420 // The LDS variants carry a trailing IsAsync operand. Parse a dummy the same
9421 // way as the SWZ operand.
9422 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::IsAsync))
9424}
9425
9426//===----------------------------------------------------------------------===//
9427// smrd
9428//===----------------------------------------------------------------------===//
9429
9430bool AMDGPUOperand::isSMRDOffset8() const {
9431 return isImmLiteral() && isUInt<8>(getImm());
9432}
9433
9434bool AMDGPUOperand::isSMEMOffset() const {
9435 // Offset range is checked later by validator.
9436 return isImmLiteral();
9437}
9438
9439bool AMDGPUOperand::isSMRDLiteralOffset() const {
9440 // 32-bit literals are only supported on CI and we only want to use them
9441 // when the offset is > 8-bits.
9442 return isImmLiteral() && !isUInt<8>(getImm()) && isUInt<32>(getImm());
9443}
9444
9445//===----------------------------------------------------------------------===//
9446// vop3
9447//===----------------------------------------------------------------------===//
9448
9449static bool ConvertOmodMul(int64_t &Mul) {
9450 if (Mul != 1 && Mul != 2 && Mul != 4)
9451 return false;
9452
9453 Mul >>= 1;
9454 return true;
9455}
9456
9457static bool ConvertOmodDiv(int64_t &Div) {
9458 if (Div == 1) {
9459 Div = 0;
9460 return true;
9461 }
9462
9463 if (Div == 2) {
9464 Div = 3;
9465 return true;
9466 }
9467
9468 return false;
9469}
9470
9471// For pre-gfx11 targets, both bound_ctrl:0 and bound_ctrl:1 are encoded as 1.
9472// This is intentional and ensures compatibility with sp3.
9473// See bug 35397 for details.
9474bool AMDGPUAsmParser::convertDppBoundCtrl(int64_t &BoundCtrl) {
9475 if (BoundCtrl == 0 || BoundCtrl == 1) {
9476 if (!isGFX11Plus())
9477 BoundCtrl = 1;
9478 return true;
9479 }
9480 return false;
9481}
9482
9483void AMDGPUAsmParser::onBeginOfFile() {
9484 if (!getParser().getStreamer().getTargetStreamer())
9485 return;
9486
9487 if (!getTargetStreamer().getTargetID())
9488 getTargetStreamer().initializeTargetID(getSTI(),
9489 /*ApplyFeatureString=*/true);
9490}
9491
9492void AMDGPUAsmParser::emitTargetDirective() {
9493 if (!getParser().getStreamer().getTargetStreamer() ||
9494 getSTI().getTargetTriple().getArch() == Triple::r600)
9495 return;
9496
9497 if (isHsaAbi(getSTI()))
9498 getTargetStreamer().emitDirectiveAMDGCNTargetOnce();
9499}
9500
9501/// Parse AMDGPU specific expressions.
9502///
9503/// expr ::= or(expr, ...) |
9504/// max(expr, ...) |
9505/// min(expr, ...)
9506///
9507bool AMDGPUAsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
9508 using AGVK = AMDGPUMCExpr::VariantKind;
9509
9510 if (isToken(AsmToken::Identifier)) {
9511 StringRef TokenId = getTokenStr();
9512 AGVK VK = StringSwitch<AGVK>(TokenId)
9513 .Case("max", AGVK::AGVK_Max)
9514 .Case("min", AGVK::AGVK_Min)
9515 .Case("or", AGVK::AGVK_Or)
9516 .Case("extrasgprs", AGVK::AGVK_ExtraSGPRs)
9517 .Case("totalnumvgprs", AGVK::AGVK_TotalNumVGPRs)
9518 .Case("alignto", AGVK::AGVK_AlignTo)
9519 .Case("occupancy", AGVK::AGVK_Occupancy)
9520 .Case("instprefsize", AGVK::AGVK_InstPrefSize)
9521 .Default(AGVK::AGVK_None);
9522
9523 if (VK != AGVK::AGVK_None && peekToken().is(AsmToken::LParen)) {
9525 uint64_t CommaCount = 0;
9526 lex(); // Eat Arg ('or', 'max', 'occupancy', etc.)
9527 lex(); // Eat '('
9528 while (true) {
9529 if (trySkipToken(AsmToken::RParen)) {
9530 if (Exprs.empty()) {
9531 Error(getToken().getLoc(),
9532 "empty " + Twine(TokenId) + " expression");
9533 return true;
9534 }
9535 if (CommaCount + 1 != Exprs.size()) {
9536 Error(getToken().getLoc(),
9537 "mismatch of commas in " + Twine(TokenId) + " expression");
9538 return true;
9539 }
9540 if (unsigned Expected = AMDGPUMCExpr::getNumExpectedArgs(VK);
9541 Expected && Exprs.size() != Expected) {
9542 Error(getToken().getLoc(), Twine(TokenId) + " expression expects " +
9543 Twine(Expected) + " operands");
9544 return true;
9545 }
9546 Res = AMDGPUMCExpr::create(VK, Exprs, getContext());
9547 return false;
9548 }
9549 const MCExpr *Expr;
9550 if (getParser().parseExpression(Expr, EndLoc))
9551 return true;
9552 Exprs.push_back(Expr);
9553 bool LastTokenWasComma = trySkipToken(AsmToken::Comma);
9554 if (LastTokenWasComma)
9555 CommaCount++;
9556 if (!LastTokenWasComma && !isToken(AsmToken::RParen)) {
9557 Error(getToken().getLoc(),
9558 "unexpected token in " + Twine(TokenId) + " expression");
9559 return true;
9560 }
9561 }
9562 }
9563 }
9564 return getParser().parsePrimaryExpr(Res, EndLoc, nullptr);
9565}
9566
9567ParseStatus AMDGPUAsmParser::parseOModSI(OperandVector &Operands) {
9568 StringRef Name = getTokenStr();
9569 if (Name == "mul") {
9570 return parseIntWithPrefix("mul", Operands, AMDGPUOperand::ImmTyOModSI,
9572 }
9573
9574 if (Name == "div") {
9575 return parseIntWithPrefix("div", Operands, AMDGPUOperand::ImmTyOModSI,
9577 }
9578
9579 return ParseStatus::NoMatch;
9580}
9581
9582// Determines which bit DST_OP_SEL occupies in the op_sel operand according to
9583// the number of src operands present, then copies that bit into src0_modifiers.
9584static void cvtVOP3DstOpSelOnly(MCInst &Inst, const MCRegisterInfo &MRI) {
9585 int Opc = Inst.getOpcode();
9586 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9587 if (OpSelIdx == -1)
9588 return;
9589
9590 int SrcNum;
9591 const AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
9592 AMDGPU::OpName::src2};
9593 for (SrcNum = 0; SrcNum < 3 && AMDGPU::hasNamedOperand(Opc, Ops[SrcNum]);
9594 ++SrcNum)
9595 ;
9596 assert(SrcNum > 0);
9597
9598 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9599
9600 int DstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
9601 if (DstIdx == -1)
9602 return;
9603
9604 const MCOperand &DstOp = Inst.getOperand(DstIdx);
9605 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
9606 uint32_t ModVal = Inst.getOperand(ModIdx).getImm();
9607 if (DstOp.isReg() &&
9608 MRI.getRegClass(AMDGPU::VGPR_16RegClassID).contains(DstOp.getReg())) {
9610 ModVal |= SISrcMods::DST_OP_SEL;
9611 } else {
9612 if ((OpSel & (1 << SrcNum)) != 0)
9613 ModVal |= SISrcMods::DST_OP_SEL;
9614 }
9615 Inst.getOperand(ModIdx).setImm(ModVal);
9616}
9617
9618void AMDGPUAsmParser::cvtVOP3OpSel(MCInst &Inst,
9619 const OperandVector &Operands) {
9620 cvtVOP3P(Inst, Operands);
9621 cvtVOP3DstOpSelOnly(Inst, *getMRI());
9622}
9623
9624void AMDGPUAsmParser::cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands,
9625 OptionalImmIndexMap &OptionalIdx) {
9626 cvtVOP3P(Inst, Operands, OptionalIdx);
9627 cvtVOP3DstOpSelOnly(Inst, *getMRI());
9628}
9629
9630static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum) {
9631 return
9632 // 1. This operand is input modifiers
9633 Desc.operands()[OpNum].OperandType == AMDGPU::OPERAND_INPUT_MODS
9634 // 2. This is not last operand
9635 && Desc.NumOperands > (OpNum + 1)
9636 // 3. Next operand is register class
9637 && Desc.operands()[OpNum + 1].RegClass != -1
9638 // 4. Next register is not tied to any other operand
9639 && Desc.getOperandConstraint(OpNum + 1,
9641}
9642
9643void AMDGPUAsmParser::cvtOpSelHelper(MCInst &Inst, unsigned OpSel) {
9644 unsigned Opc = Inst.getOpcode();
9645 constexpr AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
9646 AMDGPU::OpName::src2};
9647 constexpr AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
9648 AMDGPU::OpName::src1_modifiers,
9649 AMDGPU::OpName::src2_modifiers};
9650 for (int J = 0; J < 3; ++J) {
9651 int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
9652 if (OpIdx == -1)
9653 // Some instructions, e.g. v_interp_p2_f16 in GFX9, have src0, src2, but
9654 // no src1. So continue instead of break.
9655 continue;
9656
9657 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
9658 uint32_t ModVal = Inst.getOperand(ModIdx).getImm();
9659
9660 if ((OpSel & (1 << J)) != 0)
9661 ModVal |= SISrcMods::OP_SEL_0;
9662 // op_sel[3] is encoded in src0_modifiers.
9663 if (ModOps[J] == AMDGPU::OpName::src0_modifiers && (OpSel & (1 << 3)) != 0)
9664 ModVal |= SISrcMods::DST_OP_SEL;
9665
9666 Inst.getOperand(ModIdx).setImm(ModVal);
9667 }
9668}
9669
9670void AMDGPUAsmParser::cvtVOP3Interp(MCInst &Inst,
9671 const OperandVector &Operands) {
9672 OptionalImmIndexMap OptionalIdx;
9673 unsigned Opc = Inst.getOpcode();
9674
9675 unsigned I = 1;
9676 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9677 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9678 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9679 }
9680
9681 for (unsigned E = Operands.size(); I != E; ++I) {
9682 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9684 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9685 } else if (Op.isInterpSlot() || Op.isInterpAttr() ||
9686 Op.isInterpAttrChan()) {
9687 Inst.addOperand(MCOperand::createImm(Op.getImm()));
9688 } else if (Op.isImmModifier()) {
9689 OptionalIdx[Op.getImmTy()] = I;
9690 } else {
9691 llvm_unreachable("unhandled operand type");
9692 }
9693 }
9694
9695 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::high))
9696 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9697 AMDGPUOperand::ImmTyHigh);
9698
9699 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
9700 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9701 AMDGPUOperand::ImmTyClamp);
9702
9703 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
9704 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9705 AMDGPUOperand::ImmTyOModSI);
9706
9707 // Some v_interp instructions use op_sel[3] for dst.
9708 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
9709 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9710 AMDGPUOperand::ImmTyOpSel);
9711 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9712 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9713
9714 cvtOpSelHelper(Inst, OpSel);
9715 }
9716}
9717
9718void AMDGPUAsmParser::cvtVINTERP(MCInst &Inst, const OperandVector &Operands) {
9719 OptionalImmIndexMap OptionalIdx;
9720 unsigned Opc = Inst.getOpcode();
9721
9722 unsigned I = 1;
9723 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9724 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9725 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9726 }
9727
9728 for (unsigned E = Operands.size(); I != E; ++I) {
9729 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9731 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9732 } else if (Op.isImmModifier()) {
9733 OptionalIdx[Op.getImmTy()] = I;
9734 } else {
9735 llvm_unreachable("unhandled operand type");
9736 }
9737 }
9738
9739 addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClamp);
9740
9741 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9742 if (OpSelIdx != -1)
9743 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9744 AMDGPUOperand::ImmTyOpSel);
9745
9746 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9747 AMDGPUOperand::ImmTyWaitEXP);
9748
9749 if (OpSelIdx == -1)
9750 return;
9751
9752 unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
9753 cvtOpSelHelper(Inst, OpSel);
9754}
9755
9756void AMDGPUAsmParser::cvtScaledMFMA(MCInst &Inst,
9757 const OperandVector &Operands) {
9758 OptionalImmIndexMap OptionalIdx;
9759 unsigned Opc = Inst.getOpcode();
9760 unsigned I = 1;
9761 int CbszOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::cbsz);
9762
9763 const MCInstrDesc &Desc = MII.get(Opc);
9764
9765 for (unsigned J = 0; J < Desc.getNumDefs(); ++J)
9766 static_cast<AMDGPUOperand &>(*Operands[I++]).addRegOperands(Inst, 1);
9767
9768 for (unsigned E = Operands.size(); I != E; ++I) {
9769 AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands[I]);
9770 int NumOperands = Inst.getNumOperands();
9771 // The order of operands in MCInst and parsed operands are different.
9772 // Adding dummy cbsz and blgp operands at corresponding MCInst operand
9773 // indices for parsing scale values correctly.
9774 if (NumOperands == CbszOpIdx) {
9777 }
9778 if (isRegOrImmWithInputMods(Desc, NumOperands)) {
9779 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9780 } else if (Op.isImmModifier()) {
9781 OptionalIdx[Op.getImmTy()] = I;
9782 } else {
9783 Op.addRegOrImmOperands(Inst, 1);
9784 }
9785 }
9786
9787 // Insert CBSZ and BLGP operands for F8F6F4 variants
9788 auto CbszIdx = OptionalIdx.find(AMDGPUOperand::ImmTyCBSZ);
9789 if (CbszIdx != OptionalIdx.end()) {
9790 int CbszVal = ((AMDGPUOperand &)*Operands[CbszIdx->second]).getImm();
9791 Inst.getOperand(CbszOpIdx).setImm(CbszVal);
9792 }
9793
9794 int BlgpOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::blgp);
9795 auto BlgpIdx = OptionalIdx.find(AMDGPUOperand::ImmTyBLGP);
9796 if (BlgpIdx != OptionalIdx.end()) {
9797 int BlgpVal = ((AMDGPUOperand &)*Operands[BlgpIdx->second]).getImm();
9798 Inst.getOperand(BlgpOpIdx).setImm(BlgpVal);
9799 }
9800
9801 // Add dummy src_modifiers
9804
9805 // Handle op_sel fields
9806
9807 unsigned OpSel = 0;
9808 auto OpselIdx = OptionalIdx.find(AMDGPUOperand::ImmTyOpSel);
9809 if (OpselIdx != OptionalIdx.end()) {
9810 OpSel = static_cast<const AMDGPUOperand &>(*Operands[OpselIdx->second])
9811 .getImm();
9812 }
9813
9814 unsigned OpSelHi = 0;
9815 auto OpselHiIdx = OptionalIdx.find(AMDGPUOperand::ImmTyOpSelHi);
9816 if (OpselHiIdx != OptionalIdx.end()) {
9817 OpSelHi = static_cast<const AMDGPUOperand &>(*Operands[OpselHiIdx->second])
9818 .getImm();
9819 }
9820 const AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
9821 AMDGPU::OpName::src1_modifiers};
9822
9823 for (unsigned J = 0; J < 2; ++J) {
9824 unsigned ModVal = 0;
9825 if (OpSel & (1 << J))
9826 ModVal |= SISrcMods::OP_SEL_0;
9827 if (OpSelHi & (1 << J))
9828 ModVal |= SISrcMods::OP_SEL_1;
9829
9830 const int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
9831 Inst.getOperand(ModIdx).setImm(ModVal);
9832 }
9833}
9834
9835void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands,
9836 OptionalImmIndexMap &OptionalIdx) {
9837 unsigned Opc = Inst.getOpcode();
9838
9839 unsigned I = 1;
9840 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
9841 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
9842 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
9843 }
9844
9845 for (unsigned E = Operands.size(); I != E; ++I) {
9846 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
9848 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
9849 } else if (Op.isImmModifier()) {
9850 OptionalIdx[Op.getImmTy()] = I;
9851 } else {
9852 Op.addRegOrImmOperands(Inst, 1);
9853 }
9854 }
9855
9856 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::scale_sel))
9857 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9858 AMDGPUOperand::ImmTyScaleSel);
9859
9860 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
9861 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9862 AMDGPUOperand::ImmTyClamp);
9863
9864 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::byte_sel)) {
9865 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vdst_in))
9866 Inst.addOperand(Inst.getOperand(0));
9867 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9868 AMDGPUOperand::ImmTyByteSel);
9869 }
9870
9871 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
9872 addOptionalImmOperand(Inst, Operands, OptionalIdx,
9873 AMDGPUOperand::ImmTyOModSI);
9874
9875 // Special case v_mac_{f16, f32} and v_fmac_{f16, f32} (gfx906/gfx10+):
9876 // it has src2 register operand that is tied to dst operand
9877 // we don't allow modifiers for this operand in assembler so src2_modifiers
9878 // should be 0.
9879 if (isMAC(Opc)) {
9880 auto *it = Inst.begin();
9881 std::advance(
9882 it, AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers));
9883 it = Inst.insert(it, MCOperand::createImm(0)); // no modifiers for src2
9884 ++it;
9885 // Copy the operand to ensure it's not invalidated when Inst grows.
9886 Inst.insert(it, MCOperand(Inst.getOperand(0))); // src2 = dst
9887 }
9888}
9889
9890void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
9891 OptionalImmIndexMap OptionalIdx;
9892 cvtVOP3(Inst, Operands, OptionalIdx);
9893}
9894
9895void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst, const OperandVector &Operands,
9896 OptionalImmIndexMap &OptIdx) {
9897 const int Opc = Inst.getOpcode();
9898
9899 const bool IsPacked = SIInstrFlags::isPacked(MII, Inst);
9900
9901 if (Opc == AMDGPU::V_CVT_SCALEF32_PK_FP4_F16_vi ||
9902 Opc == AMDGPU::V_CVT_SCALEF32_PK_FP4_BF16_vi ||
9903 Opc == AMDGPU::V_CVT_SR_BF8_F32_vi ||
9904 Opc == AMDGPU::V_CVT_SR_FP8_F32_vi ||
9905 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx11 ||
9906 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx11 ||
9907 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx12 ||
9908 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx12 ||
9909 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_gfx13 ||
9910 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_gfx13) {
9911 Inst.addOperand(MCOperand::createImm(0)); // Placeholder for src2_mods
9912 Inst.addOperand(Inst.getOperand(0));
9913 }
9914
9915 // Append vdst_in only if a previous converter (cvtVOP3DPP for DPP variants,
9916 // cvtVOP3 for byte_sel variants) hasn't already placed it. Use the position
9917 // of the named operand to detect that, the same way cvtVOP3DPP does
9918 // internally.
9919 int VdstInIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
9920 if (VdstInIdx != -1 && VdstInIdx == static_cast<int>(Inst.getNumOperands()))
9921 Inst.addOperand(Inst.getOperand(0));
9922
9923 int BitOp3Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::bitop3);
9924 if (BitOp3Idx != -1) {
9925 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyBitOp3);
9926 }
9927
9928 // FIXME: This is messy. Parse the modifiers as if it was a normal VOP3
9929 // instruction, and then figure out where to actually put the modifiers
9930
9931 int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
9932 if (OpSelIdx != -1) {
9933 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSel);
9934 }
9935
9936 int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
9937 if (OpSelHiIdx != -1) {
9938 int DefaultVal = IsPacked ? -1 : 0;
9939 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSelHi,
9940 DefaultVal);
9941 }
9942
9943 int MatrixAFMTIdx =
9944 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_fmt);
9945 if (MatrixAFMTIdx != -1) {
9946 addOptionalImmOperand(Inst, Operands, OptIdx,
9947 AMDGPUOperand::ImmTyMatrixAFMT, 0);
9948 }
9949
9950 int MatrixBFMTIdx =
9951 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_fmt);
9952 if (MatrixBFMTIdx != -1) {
9953 addOptionalImmOperand(Inst, Operands, OptIdx,
9954 AMDGPUOperand::ImmTyMatrixBFMT, 0);
9955 }
9956
9957 int MatrixAScaleIdx =
9958 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale);
9959 if (MatrixAScaleIdx != -1) {
9960 addOptionalImmOperand(Inst, Operands, OptIdx,
9961 AMDGPUOperand::ImmTyMatrixAScale, 0);
9962 }
9963
9964 int MatrixBScaleIdx =
9965 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale);
9966 if (MatrixBScaleIdx != -1) {
9967 addOptionalImmOperand(Inst, Operands, OptIdx,
9968 AMDGPUOperand::ImmTyMatrixBScale, 0);
9969 }
9970
9971 int MatrixAScaleFmtIdx =
9972 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_a_scale_fmt);
9973 if (MatrixAScaleFmtIdx != -1) {
9974 addOptionalImmOperand(Inst, Operands, OptIdx,
9975 AMDGPUOperand::ImmTyMatrixAScaleFmt, 0);
9976 }
9977
9978 int MatrixBScaleFmtIdx =
9979 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::matrix_b_scale_fmt);
9980 if (MatrixBScaleFmtIdx != -1) {
9981 addOptionalImmOperand(Inst, Operands, OptIdx,
9982 AMDGPUOperand::ImmTyMatrixBScaleFmt, 0);
9983 }
9984
9985 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::matrix_a_reuse))
9986 addOptionalImmOperand(Inst, Operands, OptIdx,
9987 AMDGPUOperand::ImmTyMatrixAReuse, 0);
9988
9989 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::matrix_b_reuse))
9990 addOptionalImmOperand(Inst, Operands, OptIdx,
9991 AMDGPUOperand::ImmTyMatrixBReuse, 0);
9992
9993 int NegLoIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_lo);
9994 if (NegLoIdx != -1)
9995 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegLo);
9996
9997 int NegHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_hi);
9998 if (NegHiIdx != -1)
9999 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegHi);
10000
10001 const AMDGPU::OpName Ops[] = {AMDGPU::OpName::src0, AMDGPU::OpName::src1,
10002 AMDGPU::OpName::src2};
10003 const AMDGPU::OpName ModOps[] = {AMDGPU::OpName::src0_modifiers,
10004 AMDGPU::OpName::src1_modifiers,
10005 AMDGPU::OpName::src2_modifiers};
10006
10007 unsigned OpSel = 0;
10008 unsigned OpSelHi = 0;
10009 unsigned NegLo = 0;
10010 unsigned NegHi = 0;
10011
10012 if (OpSelIdx != -1)
10013 OpSel = Inst.getOperand(OpSelIdx).getImm();
10014
10015 if (OpSelHiIdx != -1)
10016 OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
10017
10018 if (NegLoIdx != -1)
10019 NegLo = Inst.getOperand(NegLoIdx).getImm();
10020
10021 if (NegHiIdx != -1)
10022 NegHi = Inst.getOperand(NegHiIdx).getImm();
10023
10024 for (int J = 0; J < 3; ++J) {
10025 int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
10026 if (OpIdx == -1)
10027 break;
10028
10029 int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
10030
10031 if (ModIdx == -1)
10032 continue;
10033
10034 // For MAC instructions, src2 is tied to vdst and its op_sel bit
10035 // is not encoded.
10036 if (AMDGPU::isMAC(Opc) && ModOps[J] == AMDGPU::OpName::src2_modifiers)
10037 continue;
10038
10039 uint32_t ModVal = 0;
10040
10041 const MCOperand &SrcOp = Inst.getOperand(OpIdx);
10042 if (SrcOp.isReg() && getMRI()
10043 ->getRegClass(AMDGPU::VGPR_16RegClassID)
10044 .contains(SrcOp.getReg())) {
10045 bool VGPRSuffixIsHi = AMDGPU::isHi16Reg(SrcOp.getReg(), *getMRI());
10046 if (VGPRSuffixIsHi)
10047 ModVal |= SISrcMods::OP_SEL_0;
10048 } else {
10049 if ((OpSel & (1 << J)) != 0)
10050 ModVal |= SISrcMods::OP_SEL_0;
10051 }
10052
10053 if ((OpSelHi & (1 << J)) != 0)
10054 ModVal |= SISrcMods::OP_SEL_1;
10055
10056 if ((NegLo & (1 << J)) != 0)
10057 ModVal |= SISrcMods::NEG;
10058
10059 if ((NegHi & (1 << J)) != 0)
10060 ModVal |= SISrcMods::NEG_HI;
10061
10062 Inst.getOperand(ModIdx).setImm(Inst.getOperand(ModIdx).getImm() | ModVal);
10063 }
10064}
10065
10066void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst, const OperandVector &Operands) {
10067 OptionalImmIndexMap OptIdx;
10068 cvtVOP3(Inst, Operands, OptIdx);
10069 cvtVOP3P(Inst, Operands, OptIdx);
10070}
10071
10073 unsigned i, unsigned Opc,
10074 AMDGPU::OpName OpName) {
10075 if (AMDGPU::getNamedOperandIdx(Opc, OpName) != -1)
10076 ((AMDGPUOperand &)*Operands[i]).addRegOrImmWithFPInputModsOperands(Inst, 2);
10077 else
10078 ((AMDGPUOperand &)*Operands[i]).addRegOperands(Inst, 1);
10079}
10080
10081void AMDGPUAsmParser::cvtSWMMAC(MCInst &Inst, const OperandVector &Operands) {
10082 unsigned Opc = Inst.getOpcode();
10083
10084 ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1);
10085 addSrcModifiersAndSrc(Inst, Operands, 2, Opc, AMDGPU::OpName::src0_modifiers);
10086 addSrcModifiersAndSrc(Inst, Operands, 3, Opc, AMDGPU::OpName::src1_modifiers);
10087 ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1); // srcTiedDef
10088 ((AMDGPUOperand &)*Operands[4]).addRegOperands(Inst, 1); // src2
10089
10090 OptionalImmIndexMap OptIdx;
10091 for (unsigned i = 5; i < Operands.size(); ++i) {
10092 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
10093 OptIdx[Op.getImmTy()] = i;
10094 }
10095
10096 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_8bit))
10097 addOptionalImmOperand(Inst, Operands, OptIdx,
10098 AMDGPUOperand::ImmTyIndexKey8bit);
10099
10100 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_16bit))
10101 addOptionalImmOperand(Inst, Operands, OptIdx,
10102 AMDGPUOperand::ImmTyIndexKey16bit);
10103
10104 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::index_key_32bit))
10105 addOptionalImmOperand(Inst, Operands, OptIdx,
10106 AMDGPUOperand::ImmTyIndexKey32bit);
10107
10108 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
10109 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyClamp);
10110
10111 cvtVOP3P(Inst, Operands, OptIdx);
10112}
10113
10114//===----------------------------------------------------------------------===//
10115// VOPD
10116//===----------------------------------------------------------------------===//
10117
10118ParseStatus AMDGPUAsmParser::parseVOPD(OperandVector &Operands) {
10119 if (!hasVOPD(getSTI()))
10120 return ParseStatus::NoMatch;
10121
10122 if (isToken(AsmToken::Colon) && peekToken(false).is(AsmToken::Colon)) {
10123 SMLoc S = getLoc();
10124 lex();
10125 lex();
10126 Operands.push_back(AMDGPUOperand::CreateToken(this, "::", S));
10127 SMLoc OpYLoc = getLoc();
10128 StringRef OpYName;
10129 if (isToken(AsmToken::Identifier) && !Parser.parseIdentifier(OpYName)) {
10130 Operands.push_back(AMDGPUOperand::CreateToken(this, OpYName, OpYLoc));
10131 return ParseStatus::Success;
10132 }
10133 return Error(OpYLoc, "expected a VOPDY instruction after ::");
10134 }
10135 return ParseStatus::NoMatch;
10136}
10137
10138// Create VOPD MCInst operands using parsed assembler operands.
10139void AMDGPUAsmParser::cvtVOPD(MCInst &Inst, const OperandVector &Operands) {
10140 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10141
10142 auto addOp = [&](uint16_t ParsedOprIdx) { // NOLINT:function pointer
10143 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[ParsedOprIdx]);
10145 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
10146 return;
10147 }
10148 if (Op.isReg()) {
10149 Op.addRegOperands(Inst, 1);
10150 return;
10151 }
10152 if (Op.isImm() || Op.isExpr()) {
10153 Op.addImmOperands(Inst, 1);
10154 return;
10155 }
10156 llvm_unreachable("Unhandled operand type in cvtVOPD");
10157 };
10158
10159 const auto &InstInfo = getVOPDInstInfo(Inst.getOpcode(), &MII);
10160
10161 // MCInst operands are ordered as follows:
10162 // dstX, dstY, src0X [, other OpX operands], src0Y [, other OpY operands]
10163
10164 for (auto CompIdx : VOPD::COMPONENTS) {
10165 addOp(InstInfo[CompIdx].getIndexOfDstInParsedOperands());
10166 }
10167
10168 for (auto CompIdx : VOPD::COMPONENTS) {
10169 const auto &CInfo = InstInfo[CompIdx];
10170 auto CompSrcOperandsNum = InstInfo[CompIdx].getCompParsedSrcOperandsNum();
10171 for (unsigned CompSrcIdx = 0; CompSrcIdx < CompSrcOperandsNum; ++CompSrcIdx)
10172 addOp(CInfo.getIndexOfSrcInParsedOperands(CompSrcIdx));
10173 if (CInfo.hasSrc2Acc())
10174 addOp(CInfo.getIndexOfDstInParsedOperands());
10175 }
10176
10177 int BitOp3Idx =
10178 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::bitop3);
10179 if (BitOp3Idx != -1) {
10180 OptionalImmIndexMap OptIdx;
10181 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands.back());
10182 if (Op.isImm())
10183 OptIdx[Op.getImmTy()] = Operands.size() - 1;
10184
10185 addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyBitOp3);
10186 }
10187}
10188
10189//===----------------------------------------------------------------------===//
10190// dpp
10191//===----------------------------------------------------------------------===//
10192
10193bool AMDGPUOperand::isDPP8() const { return isImmTy(ImmTyDPP8); }
10194
10195bool AMDGPUOperand::isDPPCtrl() const {
10196 using namespace AMDGPU::DPP;
10197
10198 bool result = isImm() && getImmTy() == ImmTyDppCtrl && isUInt<9>(getImm());
10199 if (result) {
10200 int64_t Imm = getImm();
10201 return (Imm >= DppCtrl::QUAD_PERM_FIRST &&
10202 Imm <= DppCtrl::QUAD_PERM_LAST) ||
10203 (Imm >= DppCtrl::ROW_SHL_FIRST && Imm <= DppCtrl::ROW_SHL_LAST) ||
10204 (Imm >= DppCtrl::ROW_SHR_FIRST && Imm <= DppCtrl::ROW_SHR_LAST) ||
10205 (Imm >= DppCtrl::ROW_ROR_FIRST && Imm <= DppCtrl::ROW_ROR_LAST) ||
10206 (Imm == DppCtrl::WAVE_SHL1) || (Imm == DppCtrl::WAVE_ROL1) ||
10207 (Imm == DppCtrl::WAVE_SHR1) || (Imm == DppCtrl::WAVE_ROR1) ||
10208 (Imm == DppCtrl::ROW_MIRROR) || (Imm == DppCtrl::ROW_HALF_MIRROR) ||
10209 (Imm == DppCtrl::BCAST15) || (Imm == DppCtrl::BCAST31) ||
10210 (Imm >= DppCtrl::ROW_SHARE_FIRST &&
10211 Imm <= DppCtrl::ROW_SHARE_LAST) ||
10212 (Imm >= DppCtrl::ROW_XMASK_FIRST && Imm <= DppCtrl::ROW_XMASK_LAST);
10213 }
10214 return false;
10215}
10216
10217//===----------------------------------------------------------------------===//
10218// mAI
10219//===----------------------------------------------------------------------===//
10220
10221bool AMDGPUOperand::isBLGP() const {
10222 return isImm() && getImmTy() == ImmTyBLGP && isUInt<3>(getImm());
10223}
10224
10225bool AMDGPUOperand::isS16Imm() const {
10226 return isImmLiteral() && (isInt<16>(getImm()) || isUInt<16>(getImm()));
10227}
10228
10229bool AMDGPUOperand::isU16Imm() const {
10230 return isImmLiteral() && isUInt<16>(getImm());
10231}
10232
10233//===----------------------------------------------------------------------===//
10234// dim
10235//===----------------------------------------------------------------------===//
10236
10237bool AMDGPUAsmParser::parseDimId(unsigned &Encoding) {
10238 // We want to allow "dim:1D" etc.,
10239 // but the initial 1 is tokenized as an integer.
10240 std::string Token;
10241 if (isToken(AsmToken::Integer)) {
10242 SMLoc Loc = getToken().getEndLoc();
10243 Token = std::string(getTokenStr());
10244 lex();
10245 if (getLoc() != Loc)
10246 return false;
10247 }
10248
10249 StringRef Suffix;
10250 if (!parseId(Suffix))
10251 return false;
10252 Token += Suffix;
10253
10254 StringRef DimId = Token;
10255 DimId.consume_front("SQ_RSRC_IMG_");
10256
10257 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfoByAsmSuffix(DimId);
10258 if (!DimInfo)
10259 return false;
10260
10261 Encoding = DimInfo->Encoding;
10262 return true;
10263}
10264
10265ParseStatus AMDGPUAsmParser::parseDim(OperandVector &Operands) {
10266 if (!isGFX10Plus())
10267 return ParseStatus::NoMatch;
10268
10269 SMLoc S = getLoc();
10270
10271 if (!trySkipId("dim", AsmToken::Colon))
10272 return ParseStatus::NoMatch;
10273
10274 unsigned Encoding;
10275 SMLoc Loc = getLoc();
10276 if (!parseDimId(Encoding))
10277 return Error(Loc, "invalid dim value");
10278
10279 Operands.push_back(
10280 AMDGPUOperand::CreateImm(this, Encoding, S, AMDGPUOperand::ImmTyDim));
10281 return ParseStatus::Success;
10282}
10283
10284//===----------------------------------------------------------------------===//
10285// dpp
10286//===----------------------------------------------------------------------===//
10287
10288ParseStatus AMDGPUAsmParser::parseDPP8(OperandVector &Operands) {
10289 SMLoc S = getLoc();
10290
10291 if (!isGFX10Plus() || !trySkipId("dpp8", AsmToken::Colon))
10292 return ParseStatus::NoMatch;
10293
10294 // dpp8:[%d,%d,%d,%d,%d,%d,%d,%d]
10295
10296 int64_t Sels[8];
10297
10298 if (!skipToken(AsmToken::LBrac, "expected an opening square bracket"))
10299 return ParseStatus::Failure;
10300
10301 for (size_t i = 0; i < 8; ++i) {
10302 if (i > 0 && !skipToken(AsmToken::Comma, "expected a comma"))
10303 return ParseStatus::Failure;
10304
10305 SMLoc Loc = getLoc();
10306 if (getParser().parseAbsoluteExpression(Sels[i]))
10307 return ParseStatus::Failure;
10308 if (0 > Sels[i] || 7 < Sels[i])
10309 return Error(Loc, "expected a 3-bit value");
10310 }
10311
10312 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
10313 return ParseStatus::Failure;
10314
10315 unsigned DPP8 = 0;
10316 for (size_t i = 0; i < 8; ++i)
10317 DPP8 |= (Sels[i] << (i * 3));
10318
10319 Operands.push_back(
10320 AMDGPUOperand::CreateImm(this, DPP8, S, AMDGPUOperand::ImmTyDPP8));
10321 return ParseStatus::Success;
10322}
10323
10324bool AMDGPUAsmParser::isSupportedDPPCtrl(StringRef Ctrl,
10325 const OperandVector &Operands) {
10326 if (Ctrl == "row_newbcast")
10327 return isGFX90A();
10328
10329 if (Ctrl == "row_share" || Ctrl == "row_xmask")
10330 return isGFX10Plus();
10331
10332 if (Ctrl == "wave_shl" || Ctrl == "wave_shr" || Ctrl == "wave_rol" ||
10333 Ctrl == "wave_ror" || Ctrl == "row_bcast")
10334 return isVI() || isGFX9();
10335
10336 return Ctrl == "row_mirror" || Ctrl == "row_half_mirror" ||
10337 Ctrl == "quad_perm" || Ctrl == "row_shl" || Ctrl == "row_shr" ||
10338 Ctrl == "row_ror";
10339}
10340
10341int64_t AMDGPUAsmParser::parseDPPCtrlPerm() {
10342 // quad_perm:[%d,%d,%d,%d]
10343
10344 if (!skipToken(AsmToken::LBrac, "expected an opening square bracket"))
10345 return -1;
10346
10347 int64_t Val = 0;
10348 for (int i = 0; i < 4; ++i) {
10349 if (i > 0 && !skipToken(AsmToken::Comma, "expected a comma"))
10350 return -1;
10351
10352 int64_t Temp;
10353 SMLoc Loc = getLoc();
10354 if (getParser().parseAbsoluteExpression(Temp))
10355 return -1;
10356 if (Temp < 0 || Temp > 3) {
10357 Error(Loc, "expected a 2-bit value");
10358 return -1;
10359 }
10360
10361 Val += (Temp << i * 2);
10362 }
10363
10364 if (!skipToken(AsmToken::RBrac, "expected a closing square bracket"))
10365 return -1;
10366
10367 return Val;
10368}
10369
10370int64_t AMDGPUAsmParser::parseDPPCtrlSel(StringRef Ctrl) {
10371 using namespace AMDGPU::DPP;
10372
10373 // sel:%d
10374
10375 int64_t Val;
10376 SMLoc Loc = getLoc();
10377
10378 if (getParser().parseAbsoluteExpression(Val))
10379 return -1;
10380
10381 struct DppCtrlCheck {
10382 int64_t Ctrl;
10383 int Lo;
10384 int Hi;
10385 };
10386
10387 DppCtrlCheck Check =
10388 StringSwitch<DppCtrlCheck>(Ctrl)
10389 .Case("wave_shl", {DppCtrl::WAVE_SHL1, 1, 1})
10390 .Case("wave_rol", {DppCtrl::WAVE_ROL1, 1, 1})
10391 .Case("wave_shr", {DppCtrl::WAVE_SHR1, 1, 1})
10392 .Case("wave_ror", {DppCtrl::WAVE_ROR1, 1, 1})
10393 .Case("row_shl", {DppCtrl::ROW_SHL0, 1, 15})
10394 .Case("row_shr", {DppCtrl::ROW_SHR0, 1, 15})
10395 .Case("row_ror", {DppCtrl::ROW_ROR0, 1, 15})
10396 .Case("row_share", {DppCtrl::ROW_SHARE_FIRST, 0, 15})
10397 .Case("row_xmask", {DppCtrl::ROW_XMASK_FIRST, 0, 15})
10398 .Case("row_newbcast", {DppCtrl::ROW_NEWBCAST_FIRST, 0, 15})
10399 .Default({-1, 0, 0});
10400
10401 bool Valid;
10402 if (Check.Ctrl == -1) {
10403 Valid = (Ctrl == "row_bcast" && (Val == 15 || Val == 31));
10404 Val = (Val == 15) ? DppCtrl::BCAST15 : DppCtrl::BCAST31;
10405 } else {
10406 Valid = Check.Lo <= Val && Val <= Check.Hi;
10407 Val = (Check.Lo == Check.Hi) ? Check.Ctrl : (Check.Ctrl | Val);
10408 }
10409
10410 if (!Valid) {
10411 Error(Loc, Twine("invalid ", Ctrl) + Twine(" value"));
10412 return -1;
10413 }
10414
10415 return Val;
10416}
10417
10418ParseStatus AMDGPUAsmParser::parseDPPCtrl(OperandVector &Operands) {
10419 using namespace AMDGPU::DPP;
10420
10421 if (!isToken(AsmToken::Identifier) ||
10422 !isSupportedDPPCtrl(getTokenStr(), Operands))
10423 return ParseStatus::NoMatch;
10424
10425 SMLoc S = getLoc();
10426 int64_t Val = -1;
10427 StringRef Ctrl;
10428
10429 parseId(Ctrl);
10430
10431 if (Ctrl == "row_mirror") {
10432 Val = DppCtrl::ROW_MIRROR;
10433 } else if (Ctrl == "row_half_mirror") {
10434 Val = DppCtrl::ROW_HALF_MIRROR;
10435 } else {
10436 if (skipToken(AsmToken::Colon, "expected a colon")) {
10437 if (Ctrl == "quad_perm") {
10438 Val = parseDPPCtrlPerm();
10439 } else {
10440 Val = parseDPPCtrlSel(Ctrl);
10441 }
10442 }
10443 }
10444
10445 if (Val == -1)
10446 return ParseStatus::Failure;
10447
10448 Operands.push_back(
10449 AMDGPUOperand::CreateImm(this, Val, S, AMDGPUOperand::ImmTyDppCtrl));
10450 return ParseStatus::Success;
10451}
10452
10453void AMDGPUAsmParser::cvtVOP3DPP(MCInst &Inst, const OperandVector &Operands,
10454 bool IsDPP8) {
10455 OptionalImmIndexMap OptionalIdx;
10456 unsigned Opc = Inst.getOpcode();
10457 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10458
10459 // MAC instructions are special because they have 'old'
10460 // operand which is not tied to dst (but assumed to be).
10461 // They also have dummy unused src2_modifiers.
10462 int OldIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::old);
10463 int Src2ModIdx =
10464 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers);
10465 bool IsMAC = OldIdx != -1 && Src2ModIdx != -1 &&
10466 Desc.getOperandConstraint(OldIdx, MCOI::TIED_TO) == -1;
10467
10468 unsigned I = 1;
10469 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10470 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10471 }
10472
10473 int Fi = 0;
10474 int VdstInIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
10475 bool IsVOP3CvtSrDpp = Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp8_gfx12 ||
10476 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp8_gfx13 ||
10477 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp8_gfx12 ||
10478 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp8_gfx13 ||
10479 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp_gfx12 ||
10480 Opc == AMDGPU::V_CVT_SR_BF8_F32_gfx12_e64_dpp_gfx13 ||
10481 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp_gfx12 ||
10482 Opc == AMDGPU::V_CVT_SR_FP8_F32_gfx12_e64_dpp_gfx13;
10483
10484 for (unsigned E = Operands.size(); I != E; ++I) {
10485
10486 if (IsMAC) {
10487 int NumOperands = Inst.getNumOperands();
10488 if (OldIdx == NumOperands) {
10489 // Handle old operand
10490 constexpr int DST_IDX = 0;
10491 Inst.addOperand(Inst.getOperand(DST_IDX));
10492 } else if (Src2ModIdx == NumOperands) {
10493 // Add unused dummy src2_modifiers
10495 }
10496 }
10497
10498 if (VdstInIdx == static_cast<int>(Inst.getNumOperands())) {
10499 Inst.addOperand(Inst.getOperand(0));
10500 }
10501
10502 if (IsVOP3CvtSrDpp) {
10503 if (Src2ModIdx == static_cast<int>(Inst.getNumOperands())) {
10505 Inst.addOperand(MCOperand::createReg(MCRegister()));
10506 }
10507 }
10508
10509 auto TiedTo =
10510 Desc.getOperandConstraint(Inst.getNumOperands(), MCOI::TIED_TO);
10511 if (TiedTo != -1) {
10512 assert((unsigned)TiedTo < Inst.getNumOperands());
10513 // handle tied old or src2 for MAC instructions
10514 Inst.addOperand(Inst.getOperand(TiedTo));
10515 }
10516 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10517 // Add the register arguments
10518 if (IsDPP8 && Op.isDppFI()) {
10519 Fi = Op.getImm();
10520 } else if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
10521 Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
10522 } else if (Op.isReg()) {
10523 Op.addRegOperands(Inst, 1);
10524 } else if (Op.isImm() &&
10525 Desc.operands()[Inst.getNumOperands()].RegClass != -1) {
10526 Op.addImmOperands(Inst, 1);
10527 } else if (Op.isImm()) {
10528 OptionalIdx[Op.getImmTy()] = I;
10529 } else {
10530 llvm_unreachable("unhandled operand type");
10531 }
10532 }
10533
10534 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp) && !IsVOP3CvtSrDpp)
10535 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10536 AMDGPUOperand::ImmTyClamp);
10537
10538 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::byte_sel)) {
10539 if (VdstInIdx == static_cast<int>(Inst.getNumOperands()))
10540 Inst.addOperand(Inst.getOperand(0));
10541 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10542 AMDGPUOperand::ImmTyByteSel);
10543 }
10544
10545 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
10546 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10547 AMDGPUOperand::ImmTyOModSI);
10548
10550 cvtVOP3P(Inst, Operands, OptionalIdx);
10551 else if (SIInstrFlags::isVOP3(Desc))
10552 cvtVOP3OpSel(Inst, Operands, OptionalIdx);
10553 else if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
10554 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10555 AMDGPUOperand::ImmTyOpSel);
10556 }
10557
10558 if (IsDPP8) {
10559 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10560 AMDGPUOperand::ImmTyDPP8);
10561 using namespace llvm::AMDGPU::DPP;
10562 Inst.addOperand(MCOperand::createImm(Fi ? DPP8_FI_1 : DPP8_FI_0));
10563 } else {
10564 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10565 AMDGPUOperand::ImmTyDppCtrl, 0xe4);
10566 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10567 AMDGPUOperand::ImmTyDppRowMask, 0xf);
10568 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10569 AMDGPUOperand::ImmTyDppBankMask, 0xf);
10570 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10571 AMDGPUOperand::ImmTyDppBoundCtrl);
10572
10573 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::fi))
10574 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10575 AMDGPUOperand::ImmTyDppFI);
10576 }
10577}
10578
10579void AMDGPUAsmParser::cvtDPP(MCInst &Inst, const OperandVector &Operands,
10580 bool IsDPP8) {
10581 OptionalImmIndexMap OptionalIdx;
10582
10583 unsigned I = 1;
10584 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10585 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10586 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10587 }
10588
10589 int Fi = 0;
10590 for (unsigned E = Operands.size(); I != E; ++I) {
10591 auto TiedTo =
10592 Desc.getOperandConstraint(Inst.getNumOperands(), MCOI::TIED_TO);
10593 if (TiedTo != -1) {
10594 assert((unsigned)TiedTo < Inst.getNumOperands());
10595 // handle tied old or src2 for MAC instructions
10596 Inst.addOperand(Inst.getOperand(TiedTo));
10597 }
10598 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10599 // Add the register arguments
10600 if (Op.isReg() && validateVccOperand(Op.getReg())) {
10601 // VOP2b (v_add_u32, v_sub_u32 ...) dpp use "vcc" token.
10602 // Skip it.
10603 continue;
10604 }
10605
10606 if (IsDPP8) {
10607 if (Op.isDPP8()) {
10608 Op.addImmOperands(Inst, 1);
10609 } else if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
10610 Op.addRegWithFPInputModsOperands(Inst, 2);
10611 } else if (Op.isDppFI()) {
10612 Fi = Op.getImm();
10613 } else if (Op.isReg()) {
10614 Op.addRegOperands(Inst, 1);
10615 } else {
10616 llvm_unreachable("Invalid operand type");
10617 }
10618 } else {
10620 Op.addRegWithFPInputModsOperands(Inst, 2);
10621 } else if (Op.isReg()) {
10622 Op.addRegOperands(Inst, 1);
10623 } else if (Op.isDPPCtrl()) {
10624 Op.addImmOperands(Inst, 1);
10625 } else if (Op.isImm()) {
10626 // Handle optional arguments
10627 OptionalIdx[Op.getImmTy()] = I;
10628 } else {
10629 llvm_unreachable("Invalid operand type");
10630 }
10631 }
10632 }
10633
10634 if (IsDPP8) {
10635 using namespace llvm::AMDGPU::DPP;
10636 Inst.addOperand(MCOperand::createImm(Fi ? DPP8_FI_1 : DPP8_FI_0));
10637 } else {
10638 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10639 AMDGPUOperand::ImmTyDppRowMask, 0xf);
10640 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10641 AMDGPUOperand::ImmTyDppBankMask, 0xf);
10642 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10643 AMDGPUOperand::ImmTyDppBoundCtrl);
10644 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::fi)) {
10645 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10646 AMDGPUOperand::ImmTyDppFI);
10647 }
10648 }
10649}
10650
10651//===----------------------------------------------------------------------===//
10652// sdwa
10653//===----------------------------------------------------------------------===//
10654
10655ParseStatus AMDGPUAsmParser::parseSDWASel(OperandVector &Operands,
10656 StringRef Prefix,
10657 AMDGPUOperand::ImmTy Type) {
10658 return parseStringOrIntWithPrefix(
10659 Operands, Prefix,
10660 {"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD"},
10661 Type);
10662}
10663
10664ParseStatus AMDGPUAsmParser::parseSDWADstUnused(OperandVector &Operands) {
10665 return parseStringOrIntWithPrefix(
10666 Operands, "dst_unused", {"UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"},
10667 AMDGPUOperand::ImmTySDWADstUnused);
10668}
10669
10670void AMDGPUAsmParser::cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands) {
10671 cvtSDWA(Inst, Operands, SDWAInstType::VOP1);
10672}
10673
10674void AMDGPUAsmParser::cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands) {
10675 cvtSDWA(Inst, Operands, SDWAInstType::VOP2);
10676}
10677
10678void AMDGPUAsmParser::cvtSdwaVOP2b(MCInst &Inst,
10679 const OperandVector &Operands) {
10680 cvtSDWA(Inst, Operands, SDWAInstType::VOP2, true, true);
10681}
10682
10683void AMDGPUAsmParser::cvtSdwaVOP2e(MCInst &Inst,
10684 const OperandVector &Operands) {
10685 cvtSDWA(Inst, Operands, SDWAInstType::VOP2, false, true);
10686}
10687
10688void AMDGPUAsmParser::cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands) {
10689 cvtSDWA(Inst, Operands, SDWAInstType::VOPC, isVI());
10690}
10691
10692void AMDGPUAsmParser::cvtSDWA(MCInst &Inst, const OperandVector &Operands,
10693 SDWAInstType BasicInstType, bool SkipDstVcc,
10694 bool SkipSrcVcc) {
10695 using namespace llvm::AMDGPU::SDWA;
10696
10697 OptionalImmIndexMap OptionalIdx;
10698 bool SkipVcc = SkipDstVcc || SkipSrcVcc;
10699 bool SkippedVcc = false;
10700
10701 unsigned I = 1;
10702 const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
10703 for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
10704 ((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
10705 }
10706
10707 for (unsigned E = Operands.size(); I != E; ++I) {
10708 AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
10709 if (SkipVcc && !SkippedVcc && Op.isReg() &&
10710 (Op.getReg() == AMDGPU::VCC || Op.getReg() == AMDGPU::VCC_LO)) {
10711 // VOP2b (v_add_u32, v_sub_u32 ...) sdwa use "vcc" token as dst.
10712 // Skip it if it's 2nd (e.g. v_add_i32_sdwa v1, vcc, v2, v3)
10713 // or 4th (v_addc_u32_sdwa v1, vcc, v2, v3, vcc) operand.
10714 // Skip VCC only if we didn't skip it on previous iteration.
10715 // Note that src0 and src1 occupy 2 slots each because of modifiers.
10716 if (BasicInstType == SDWAInstType::VOP2 &&
10717 ((SkipDstVcc && Inst.getNumOperands() == 1) ||
10718 (SkipSrcVcc && Inst.getNumOperands() == 5))) {
10719 SkippedVcc = true;
10720 continue;
10721 }
10722 if (BasicInstType == SDWAInstType::VOPC && Inst.getNumOperands() == 0) {
10723 SkippedVcc = true;
10724 continue;
10725 }
10726 }
10728 Op.addRegOrImmWithInputModsOperands(Inst, 2);
10729 } else if (Op.isImm()) {
10730 // Handle optional arguments
10731 OptionalIdx[Op.getImmTy()] = I;
10732 } else {
10733 llvm_unreachable("Invalid operand type");
10734 }
10735 SkippedVcc = false;
10736 }
10737
10738 const unsigned Opc = Inst.getOpcode();
10739 if (Opc != AMDGPU::V_NOP_sdwa_gfx10 && Opc != AMDGPU::V_NOP_sdwa_gfx9 &&
10740 Opc != AMDGPU::V_NOP_sdwa_vi) {
10741 // v_nop_sdwa_sdwa_vi/gfx9 has no optional sdwa arguments
10742 switch (BasicInstType) {
10743 case SDWAInstType::VOP1:
10744 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::clamp))
10745 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10746 AMDGPUOperand::ImmTyClamp, 0);
10747
10748 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::omod))
10749 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10750 AMDGPUOperand::ImmTyOModSI, 0);
10751
10752 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::dst_sel))
10753 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10754 AMDGPUOperand::ImmTySDWADstSel, SdwaSel::DWORD);
10755
10756 if (AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::dst_unused))
10757 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10758 AMDGPUOperand::ImmTySDWADstUnused,
10759 DstUnused::UNUSED_PRESERVE);
10760
10761 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10762 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10763 break;
10764
10765 case SDWAInstType::VOP2:
10766 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10767 AMDGPUOperand::ImmTyClamp, 0);
10768
10769 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::omod))
10770 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10771 AMDGPUOperand::ImmTyOModSI, 0);
10772
10773 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10774 AMDGPUOperand::ImmTySDWADstSel, SdwaSel::DWORD);
10775 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10776 AMDGPUOperand::ImmTySDWADstUnused,
10777 DstUnused::UNUSED_PRESERVE);
10778 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10779 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10780 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10781 AMDGPUOperand::ImmTySDWASrc1Sel, SdwaSel::DWORD);
10782 break;
10783
10784 case SDWAInstType::VOPC:
10785 if (AMDGPU::hasNamedOperand(Inst.getOpcode(), AMDGPU::OpName::clamp))
10786 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10787 AMDGPUOperand::ImmTyClamp, 0);
10788 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10789 AMDGPUOperand::ImmTySDWASrc0Sel, SdwaSel::DWORD);
10790 addOptionalImmOperand(Inst, Operands, OptionalIdx,
10791 AMDGPUOperand::ImmTySDWASrc1Sel, SdwaSel::DWORD);
10792 break;
10793 }
10794 }
10795
10796 // special case v_mac_{f16, f32}:
10797 // it has src2 register operand that is tied to dst operand
10798 if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
10799 Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
10800 auto *it = Inst.begin();
10801 std::advance(
10802 it, AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::src2));
10803 Inst.insert(it, Inst.getOperand(0)); // src2 = dst
10804 }
10805}
10806
10807/// Force static initialization.
10808extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
10814
10815#define GET_MATCHER_IMPLEMENTATION
10816#define GET_MNEMONIC_SPELL_CHECKER
10817#define GET_MNEMONIC_CHECKER
10818#include "AMDGPUGenAsmMatcher.inc"
10819
10820ParseStatus AMDGPUAsmParser::parseCustomOperand(OperandVector &Operands,
10821 unsigned MCK) {
10822 switch (MCK) {
10823 case MCK_addr64:
10824 return parseTokenOp("addr64", Operands);
10825 case MCK_idxen:
10826 return parseTokenOp("idxen", Operands);
10827 case MCK_lds:
10828 return parseNamedBit("lds", Operands, AMDGPUOperand::ImmTyLDS,
10829 /*IgnoreNegative=*/true);
10830 case MCK_offen:
10831 return parseTokenOp("offen", Operands);
10832 case MCK_off:
10833 return parseTokenOp("off", Operands);
10834 case MCK_gds:
10835 return parseNamedBit("gds", Operands, AMDGPUOperand::ImmTyGDS);
10836 case MCK_tfe:
10837 return parseNamedBit("tfe", Operands, AMDGPUOperand::ImmTyTFE);
10838 }
10839 return tryCustomParseOperand(Operands, MCK);
10840}
10841
10842// This function should be defined after auto-generated include so that we have
10843// MatchClassKind enum defined
10844unsigned
10845AMDGPUAsmParser::validateTargetOperandClass(const MCParsedAsmOperand &Op,
10846 unsigned Kind) {
10847 // Tokens like "glc" would be parsed as immediate operands in ParseOperand().
10848 // But MatchInstructionImpl() expects to meet token and fails to validate
10849 // operand. This method checks if we are given immediate operand but expect to
10850 // get corresponding token.
10851 const AMDGPUOperand &Operand = static_cast<const AMDGPUOperand &>(Op);
10852 switch (Kind) {
10853 case MCK_addr64:
10854 return Operand.isAddr64() ? Match_Success : Match_InvalidOperand;
10855 case MCK_gds:
10856 return Operand.isGDS() ? Match_Success : Match_InvalidOperand;
10857 case MCK_lds:
10858 return Operand.isLDS() ? Match_Success : Match_InvalidOperand;
10859 case MCK_idxen:
10860 return Operand.isIdxen() ? Match_Success : Match_InvalidOperand;
10861 case MCK_offen:
10862 return Operand.isOffen() ? Match_Success : Match_InvalidOperand;
10863 case MCK_tfe:
10864 return Operand.isTFE() ? Match_Success : Match_InvalidOperand;
10865 case MCK_SSrc_b32:
10866 // When operands have expression values, they will return true for isToken,
10867 // because it is not possible to distinguish between a token and an
10868 // expression at parse time. MatchInstructionImpl() will always try to
10869 // match an operand as a token, when isToken returns true, and when the
10870 // name of the expression is not a valid token, the match will fail,
10871 // so we need to handle it here.
10872 return Operand.isSSrc_b32() ? Match_Success : Match_InvalidOperand;
10873 case MCK_SSrc_f32:
10874 return Operand.isSSrc_f32() ? Match_Success : Match_InvalidOperand;
10875 case MCK_SOPPBrTarget:
10876 return Operand.isSOPPBrTarget() ? Match_Success : Match_InvalidOperand;
10877 case MCK_VReg32OrOff:
10878 return Operand.isVReg32OrOff() ? Match_Success : Match_InvalidOperand;
10879 case MCK_InterpSlot:
10880 return Operand.isInterpSlot() ? Match_Success : Match_InvalidOperand;
10881 case MCK_InterpAttr:
10882 return Operand.isInterpAttr() ? Match_Success : Match_InvalidOperand;
10883 case MCK_InterpAttrChan:
10884 return Operand.isInterpAttrChan() ? Match_Success : Match_InvalidOperand;
10885 case MCK_SReg_64:
10886 case MCK_SReg_64_XEXEC:
10887 // Null is defined as a 32-bit register but
10888 // it should also be enabled with 64-bit operands or larger.
10889 // The following code enables it for SReg_64 and larger operands
10890 // used as source and destination. Remaining source
10891 // operands are handled in isInlinableImm.
10892 case MCK_SReg_96:
10893 case MCK_SReg_128:
10894 case MCK_SReg_256:
10895 case MCK_SReg_512:
10896 return Operand.isNull() ? Match_Success : Match_InvalidOperand;
10897 default:
10898 return Match_InvalidOperand;
10899 }
10900}
10901
10902//===----------------------------------------------------------------------===//
10903// endpgm
10904//===----------------------------------------------------------------------===//
10905
10906ParseStatus AMDGPUAsmParser::parseEndpgm(OperandVector &Operands) {
10907 SMLoc S = getLoc();
10908 int64_t Imm = 0;
10909
10910 if (!parseExpr(Imm)) {
10911 // The operand is optional, if not present default to 0
10912 Imm = 0;
10913 }
10914
10915 if (!isUInt<16>(Imm))
10916 return Error(S, "expected a 16-bit value");
10917
10918 Operands.push_back(
10919 AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTyEndpgm));
10920 return ParseStatus::Success;
10921}
10922
10923bool AMDGPUOperand::isEndpgm() const { return isImmTy(ImmTyEndpgm); }
10924
10925//===----------------------------------------------------------------------===//
10926// Split Barrier
10927//===----------------------------------------------------------------------===//
10928
10929bool AMDGPUOperand::isSplitBarrier() const {
10930 if (!isImm())
10931 return false;
10932
10933 int64_t Imm = getImm();
10936}
#define Success
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
SmallVector< int16_t, MAX_SRC_OPERANDS_NUM > OperandIndices
static bool checkWriteLane(const MCInst &Inst)
static bool getRegNum(StringRef Str, unsigned &Num)
static void addSrcModifiersAndSrc(MCInst &Inst, const OperandVector &Operands, unsigned i, unsigned Opc, AMDGPU::OpName OpName)
static constexpr RegInfo RegularRegisters[]
static const RegInfo * getRegularRegInfo(StringRef Str)
static ArrayRef< unsigned > getAllVariants()
static OperandIndices getSrcOperandIndices(unsigned Opcode, bool AddMandatoryLiterals=false)
static int IsAGPROperand(const MCInst &Inst, AMDGPU::OpName Name, const MCRegisterInfo *MRI)
static bool IsMovrelsSDWAOpcode(const unsigned Opcode)
static const fltSemantics * getFltSemantics(unsigned Size)
static bool isRegularReg(RegisterKind Kind)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUAsmParser()
Force static initialization.
static bool ConvertOmodMul(int64_t &Mul)
#define PARSE_BITS_ENTRY(FIELD, ENTRY, VALUE, RANGE)
static bool isInlineableLiteralOp16(int64_t Val, MVT VT, bool HasInv2Pi)
static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT)
static bool AMDGPUCheckMnemonic(StringRef Mnemonic, const FeatureBitset &AvailableFeatures, unsigned VariantID)
static void applyMnemonicAliases(StringRef &Mnemonic, const FeatureBitset &Features, unsigned VariantID)
constexpr unsigned MAX_SRC_OPERANDS_NUM
#define EXPR_RESOLVE_OR_ERROR(RESOLVED)
static bool ConvertOmodDiv(int64_t &Div)
static bool IsRevOpcode(const unsigned Opcode)
static bool encodeCnt(const AMDGPU::IsaVersion ISA, int64_t &IntVal, int64_t CntVal, bool Saturate, unsigned(*encode)(const IsaVersion &Version, unsigned, unsigned), unsigned(*decode)(const IsaVersion &Version, unsigned))
static MCRegister getSpecialRegForName(StringRef RegName)
static void addOptionalImmOperand(MCInst &Inst, const OperandVector &Operands, AMDGPUAsmParser::OptionalImmIndexMap &OptionalIdx, AMDGPUOperand::ImmTy ImmT, int64_t Default=0, std::optional< unsigned > InsertAt=std::nullopt)
static void cvtVOP3DstOpSelOnly(MCInst &Inst, const MCRegisterInfo &MRI)
static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum)
static const fltSemantics * getOpFltSemantics(uint8_t OperandType)
static bool isInvalidVOPDY(const OperandVector &Operands, uint64_t InvalidOprIdx)
static std::string AMDGPUMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS, unsigned VariantID=0)
static LLVM_READNONE unsigned encodeBitmaskPerm(const unsigned AndMask, const unsigned OrMask, const unsigned XorMask)
static bool isSafeTruncation(int64_t Val, unsigned Size)
uint64_t uint64_t
AMDHSA kernel descriptor MCExpr struct for use in MC layer.
Provides AMDGPU specific target descriptions.
AMDGPU metadata definitions and in-memory representations.
Enums shared between the AMDGPU backend (LLVM) and the ELF linker (LLD) for the .amdgpu....
AMDHSA kernel descriptor definitions.
static bool parseExpr(MCAsmParser &MCParser, const MCExpr *&Value, raw_ostream &Err)
MC layer struct for AMDGPUMCKernelCodeT, provides MCExpr functionality where required.
@ AMD_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#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< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_READNONE
Definition Compiler.h:327
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
@ Default
#define Check(C,...)
static llvm::Expected< InlineInfo > decode(GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr)
Decode an InlineInfo in Data at the specified offset.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
unsigned Opc
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:249
static bool hasFeature(StringRef Feature, const FeatureBitset &FeatureBits, ArrayRef< SubtargetFeatureKV > ProcFeatures)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
MachineRegisterInfo & MRI
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
Interface definition for SIInstrInfo.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
const char * Msg
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
static Triple::ObjectFormatType parseFormat(StringRef EnvironmentName)
Definition Triple.cpp:735
BinaryOperator * Mul
static const char * getRegisterName(MCRegister Reg)
static const AMDGPUMCExpr * createMax(ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static unsigned getNumExpectedArgs(VariantKind Kind)
static const AMDGPUMCExpr * createLit(LitModifier Lit, int64_t Value, MCContext &Ctx)
static const AMDGPUMCExpr * create(VariantKind Kind, ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static const AMDGPUMCExpr * createExtraSGPRs(const MCExpr *VCCUsed, const MCExpr *FlatScrUsed, bool XNACKUsed, MCContext &Ctx)
Allow delayed MCExpr resolve of ExtraSGPRs (in case VCCUsed or FlatScrUsed are unresolvable but neede...
static const AMDGPUMCExpr * createAlignTo(const MCExpr *Value, const MCExpr *Align, MCContext &Ctx)
static std::optional< TargetID > parseTargetIDString(StringRef TargetIDDirective)
Parse and validate a TargetID from a full "<triple>-<processor>:<features>" directive string.
TargetIDSetting getXnackSetting() const
StringRef getTargetTripleString() const
std::string toString() const
TargetIDSetting getSramEccSetting() const
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr const fltSemantics & BFloat()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
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
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition MCAsmMacro.h:103
bool is(TokenKind K) const
Definition MCAsmMacro.h:75
Register getReg() const
Container class for subtarget features.
constexpr bool test(unsigned I) const
constexpr FeatureBitset & flip(unsigned I)
void printExpr(raw_ostream &, const MCExpr &) const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:339
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:349
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:424
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:84
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
unsigned getNumOperands() const
Definition MCInst.h:211
SMLoc getLoc() const
Definition MCInst.h:207
void setLoc(SMLoc loc)
Definition MCInst.h:206
unsigned getOpcode() const
Definition MCInst.h:201
iterator insert(iterator I, const MCOperand &Op)
Definition MCInst.h:231
void addOperand(const MCOperand Op)
Definition MCInst.h:214
iterator begin()
Definition MCInst.h:226
size_t size() const
Definition MCInst.h:225
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:209
Describe properties that are true of each instruction in the target description file.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
const int16_t * getRegClassByHwModeTable(unsigned ModeId) const
Definition MCInstrInfo.h:70
int16_t getOpRegClassID(const MCOperandInfo &OpInfo, unsigned HwModeId) const
Return the ID of the register class to use for OpInfo, for the active HwMode HwModeId.
Definition MCInstrInfo.h:79
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:39
void setImm(int64_t Val)
Definition MCInst.h:88
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:165
int64_t getImm() const
Definition MCInst.h:83
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
bool isImm() const
Definition MCInst.h:65
void setReg(MCRegister Reg)
Set the register number.
Definition MCInst.h:78
bool isReg() const
Definition MCInst.h:64
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:72
const MCExpr * getExpr() const
Definition MCInst.h:117
bool isExpr() const
Definition MCInst.h:68
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
MCRegisterClass - Base class of TargetRegisterClass.
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
unsigned getNumRegs() const
getNumRegs - Return the number of registers in this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
Generic base class for all target subtargets.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition MCSymbol.h:267
LLVM_ABI void setVariableValue(const MCExpr *Value)
Definition MCSymbol.cpp:51
void setRedefinable(bool Value)
Mark this symbol as redefinable.
Definition MCSymbol.h:210
const MCExpr * getVariableValue() const
Get the expression of the variable symbol.
Definition MCSymbol.h:270
MCTargetAsmParser - Generic interface to target specific assembly parsers.
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Ternary parse status returned by various parse* methods.
constexpr bool isFailure() const
static constexpr StatusTy Failure
constexpr bool isSuccess() const
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
constexpr bool isNoMatch() const
constexpr unsigned id() const
Definition Register.h:100
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
constexpr const char * getPointer() const
Definition SMLoc.h:33
constexpr bool isValid() const
Definition SMLoc.h:28
SMLoc Start
Definition SMLoc.h:49
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:627
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:62
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:41
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int encodeDepCtr(const StringRef Name, int64_t Val, unsigned &UsedOprMask, const MCSubtargetInfo &STI)
int getDefaultDepCtrEncoding(const MCSubtargetInfo &STI)
bool isSupportedTgtId(unsigned Id, const MCSubtargetInfo &STI)
unsigned getTgtId(const StringRef Name)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char NumSGPRs[]
Key for Kernel::CodeProps::Metadata::mNumSGPRs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr char AssemblerDirectiveBegin[]
HSA metadata beginning assembler directive.
constexpr char AssemblerDirectiveEnd[]
HSA metadata ending assembler directive.
constexpr char AssemblerDirectiveBegin[]
Old HSA metadata beginning assembler directive for V2.
int64_t getHwregId(StringRef Name, const MCSubtargetInfo &STI)
unsigned getVGPREncodingGranule(const MCSubtargetInfo &STI, std::optional< bool > EnableWavefrontSize32)
unsigned getSGPREncodingGranule(const MCSubtargetInfo &STI)
bool targetIDSettingsConflict(TargetIDSetting Lhs, TargetIDSetting Rhs)
Returns true if Lhs and Rhs are incompatible (both specific but different).
unsigned getLocalMemorySize(const MCSubtargetInfo &STI)
int64_t convertDfmtNfmt2Ufmt(unsigned Dfmt, unsigned Nfmt, const MCSubtargetInfo &STI)
int64_t encodeDfmtNfmt(unsigned Dfmt, unsigned Nfmt)
int64_t getUnifiedFormat(const StringRef Name, const MCSubtargetInfo &STI)
bool isValidFormatEncoding(unsigned Val, const MCSubtargetInfo &STI)
int64_t getNfmt(const StringRef Name, const MCSubtargetInfo &STI)
int64_t getDfmt(const StringRef Name)
constexpr char AssemblerDirective[]
PAL metadata (old linear format) assembler directive.
constexpr char AssemblerDirectiveBegin[]
PAL metadata (new MsgPack format) beginning assembler directive.
constexpr char AssemblerDirectiveEnd[]
PAL metadata (new MsgPack format) ending assembler directive.
int64_t getMsgOpId(int64_t MsgId, StringRef Name, const MCSubtargetInfo &STI)
Map from a symbolic name for a sendmsg operation to the operation portion of the immediate encoding.
int64_t getMsgId(StringRef Name, const MCSubtargetInfo &STI)
Map from a symbolic name for a msg_id to the message portion of the immediate encoding.
uint64_t encodeMsg(uint64_t MsgId, uint64_t OpId, uint64_t StreamId)
bool msgSupportsStream(int64_t MsgId, int64_t OpId, const MCSubtargetInfo &STI)
bool isValidMsgId(int64_t MsgId, const MCSubtargetInfo &STI)
bool isValidMsgStream(int64_t MsgId, int64_t OpId, int64_t StreamId, const MCSubtargetInfo &STI, bool Strict)
bool msgRequiresOp(int64_t MsgId, const MCSubtargetInfo &STI)
bool isValidMsgOp(int64_t MsgId, int64_t OpId, const MCSubtargetInfo &STI, bool Strict)
ArrayRef< GFXVersion > getGFXVersions()
constexpr unsigned COMPONENTS[]
constexpr const char *const ModMatrixFmt[]
constexpr const char *const ModMatrixScaleFmt[]
constexpr const char *const ModMatrixScale[]
bool isInlineValue(MCRegister Reg)
bool isPKFMACF16InlineConstant(uint32_t Literal, bool IsGFX11Plus)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
bool isInlinableLiteralFP16(int16_t Literal, bool HasInv2Pi)
bool isSGPR(MCRegister Reg, const MCRegisterInfo *TRI)
Is Reg - scalar register.
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
FuncInfoFlags
Per-function flags packed into INFO_FLAGS entries.
uint8_t wmmaScaleF8F6F4FormatToNumRegs(unsigned Fmt)
const int OPR_ID_UNSUPPORTED
bool isInlinableLiteralV2I16(uint32_t Literal)
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
unsigned getTemporalHintType(const MCInstrDesc TID)
static AMDGPUMCExpr::Specifier getSpecifier(const MCSymbolRefExpr *SRE)
LLVM_READONLY bool isLitExpr(const MCExpr *Expr)
bool isInlinableLiteralV2BF16(uint32_t Literal)
LLVM_ABI bool isCPUValidForSubArch(Triple::SubArchType SubArch, GPUKind AK)
Return true if the GPU AK is usable with the triple subarch SubArch.
unsigned getMaxNumUserSGPRs(const MCSubtargetInfo &STI)
unsigned getNumFlatOffsetBits(const MCSubtargetInfo &ST)
For pre-GFX12 FLAT instructions the offset must be positive; MSB is ignored and forced to zero.
bool hasA16(const MCSubtargetInfo &STI)
bool isLegalSMRDEncodedSignedOffset(const MCSubtargetInfo &ST, int64_t EncodedOffset, bool IsBuffer)
bool isGFX12Plus(const MCSubtargetInfo &STI)
unsigned getNSAMaxSize(const MCSubtargetInfo &STI, bool HasSampler)
bool hasPackedD16(const MCSubtargetInfo &STI)
bool isGFX940(const MCSubtargetInfo &STI)
bool isInlinableLiteralV2F16(uint32_t Literal)
bool isHsaAbi(const MCSubtargetInfo &STI)
bool isGFX11(const MCSubtargetInfo &STI)
const int OPR_VAL_INVALID
bool getSMEMIsBuffer(unsigned Opc)
bool isPackedSingleSGPRFP32Inst(unsigned Opc)
The opcode is a packed fp32 instruction which only reads low 32 bits of a scalar operand and propagat...
LLVM_ABI unsigned getAddressableNumSGPRs(GPUKind AK)
uint8_t mfmaScaleF8F6F4FormatToNumRegs(unsigned EncodingVal)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned getRegBitWidth(unsigned RCID)
Get the size in bits of a register from the register class RC.
bool isValid32BitLiteral(uint64_t Val, bool IsFP64)
LLVM_ABI unsigned getTotalNumVGPRs(GPUKind AK, bool IsWave32)
CanBeVOPD getCanBeVOPD(unsigned Opc, unsigned EncodingFamily, bool VOPD3)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
bool isVOP3DPPSrc1RevOpc(const MCSubtargetInfo &STI, unsigned Opc)
bool isSI(const MCSubtargetInfo &STI)
bool hasPrivateApertureRegs(const MCSubtargetInfo &STI)
unsigned decodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt)
unsigned getWaitcntBitMask(const IsaVersion &Version)
bool isGFX9(const MCSubtargetInfo &STI)
unsigned getVOPDEncodingFamily(const MCSubtargetInfo &ST)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
bool isKImmOperand(const MCInstrDesc &Desc, unsigned OpNo)
Is this a KImm operand?
GPUKind
GPU kinds supported by the AMDGPU target.
bool isGFX90A(const MCSubtargetInfo &STI)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByEncoding(uint8_t DimEnc)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
bool isGFX12(const MCSubtargetInfo &STI)
unsigned encodeExpcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Expcnt)
bool hasMAIInsts(const MCSubtargetInfo &STI)
constexpr bool isSISrcOperand(const MCOperandInfo &OpInfo)
Is this an AMDGPU specific source operand?
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi, bool *IsBF16)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByAsmSuffix(StringRef AsmSuffix)
bool hasMIMG_R128(const MCSubtargetInfo &STI)
LLVM_ABI GPUKind parseArchAMDGCN(StringRef CPU)
bool hasG16(const MCSubtargetInfo &STI)
unsigned getAddrSizeMIMGOp(const MIMGBaseOpcodeInfo *BaseOpcode, const MIMGDimInfo *Dim, bool IsA16, bool IsG16Supported)
bool hasArchitectedFlatScratch(const MCSubtargetInfo &STI)
LLVM_READONLY int64_t getLitValue(const MCExpr *Expr)
bool isGFX11Plus(const MCSubtargetInfo &STI)
bool isSISrcFPOperand(const MCInstrDesc &Desc, unsigned OpNo)
Is this floating-point operand?
bool isGFX10Plus(const MCSubtargetInfo &STI)
AMDGPU::TargetID TargetID
int64_t encode32BitLiteral(int64_t Imm, OperandType Type, bool IsLit)
bool isValidWMMAScaleFmtCombination(unsigned AFmt, unsigned AScale, unsigned BFmt, unsigned BScale)
@ OPERAND_REG_IMM_V2FP64
Definition SIDefines.h:447
@ OPERAND_KIMM32
Operand with 32-bit immediate that uses the constant bus.
Definition SIDefines.h:465
@ OPERAND_REG_IMM_INT64
Definition SIDefines.h:432
@ OPERAND_REG_IMM_V2FP16
Definition SIDefines.h:440
@ OPERAND_REG_INLINE_C_FP64
Definition SIDefines.h:456
@ OPERAND_REG_IMM_NOINLINE_FP16
Definition SIDefines.h:438
@ OPERAND_REG_INLINE_C_BF16
Definition SIDefines.h:453
@ OPERAND_REG_INLINE_C_V2BF16
Definition SIDefines.h:458
@ OPERAND_REG_IMM_V2INT64
Definition SIDefines.h:443
@ OPERAND_REG_IMM_V2INT16
Definition SIDefines.h:442
@ OPERAND_REG_IMM_BF16
Definition SIDefines.h:436
@ OPERAND_REG_IMM_INT32
Operands with register, 32-bit, or 64-bit immediate.
Definition SIDefines.h:431
@ OPERAND_REG_IMM_V2BF16
Definition SIDefines.h:439
@ OPERAND_REG_IMM_FP16
Definition SIDefines.h:437
@ OPERAND_REG_IMM_V2FP16_SPLAT
Definition SIDefines.h:441
@ OPERAND_REG_INLINE_C_INT64
Definition SIDefines.h:452
@ OPERAND_REG_INLINE_C_INT16
Operands with register or inline constant.
Definition SIDefines.h:450
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition SIDefines.h:444
@ OPERAND_REG_IMM_FP64
Definition SIDefines.h:435
@ OPERAND_REG_INLINE_C_V2FP16
Definition SIDefines.h:459
@ OPERAND_REG_INLINE_AC_INT32
Operands with an AccVGPR register or inline constant.
Definition SIDefines.h:470
@ OPERAND_REG_INLINE_AC_FP32
Definition SIDefines.h:471
@ OPERAND_REG_IMM_V2INT32
Definition SIDefines.h:445
@ OPERAND_REG_IMM_FP32
Definition SIDefines.h:434
@ OPERAND_REG_INLINE_C_FP32
Definition SIDefines.h:455
@ OPERAND_REG_INLINE_C_INT32
Definition SIDefines.h:451
@ OPERAND_REG_INLINE_C_V2INT16
Definition SIDefines.h:457
@ OPERAND_REG_IMM_V2FP32
Definition SIDefines.h:446
@ OPERAND_REG_INLINE_AC_FP64
Definition SIDefines.h:472
@ OPERAND_REG_INLINE_C_FP16
Definition SIDefines.h:454
@ OPERAND_REG_IMM_INT16
Definition SIDefines.h:433
@ OPERAND_INLINE_SPLIT_BARRIER_INT32
Definition SIDefines.h:462
constexpr bool isBF16SrcOperand(const MCOperandInfo &OpInfo)
Is this a scalar (i.e. not packed) bf16 source operand?
bool isDPALU_DPP(const MCInstrDesc &OpDesc, const MCInstrInfo &MII, const MCSubtargetInfo &ST)
LLVM_ABI StringRef getArchNameAMDGCN(GPUKind AK)
bool hasGDS(const MCSubtargetInfo &STI)
bool isLegalSMRDEncodedUnsignedOffset(const MCSubtargetInfo &ST, int64_t EncodedOffset)
bool isGFX9Plus(const MCSubtargetInfo &STI)
bool hasDPPSrc1SGPR(const MCSubtargetInfo &STI)
const int OPR_ID_DUPLICATE
bool isVOPD(unsigned Opc)
VOPD::InstInfo getVOPDInstInfo(const MCInstrDesc &OpX, const MCInstrDesc &OpY)
unsigned encodeVmcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Vmcnt)
unsigned decodeExpcnt(const IsaVersion &Version, unsigned Waitcnt)
const MIMGBaseOpcodeInfo * getMIMGBaseOpcode(unsigned Opc)
bool isVI(const MCSubtargetInfo &STI)
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
MCRegister mc2PseudoReg(MCRegister Reg)
Convert hardware register Reg to a pseudo register.
unsigned hasKernargPreload(const MCSubtargetInfo &STI)
bool supportsWGP(const MCSubtargetInfo &STI)
bool isMAC(unsigned Opc)
LLVM_READNONE unsigned getOperandSize(const MCOperandInfo &OpInfo)
bool isCI(const MCSubtargetInfo &STI)
unsigned encodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned Lgkmcnt)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
const int OPR_ID_UNKNOWN
bool isGFX1250Plus(const MCSubtargetInfo &STI)
bool hasPopsExitingWaveID(const MCSubtargetInfo &STI)
unsigned decodeVmcnt(const IsaVersion &Version, unsigned Waitcnt)
bool isInlinableLiteralI16(int32_t Literal, bool HasInv2Pi)
bool hasVOPD(const MCSubtargetInfo &STI)
bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi)
Is this literal inlinable.
bool isPermlane16(unsigned Opc)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ STT_AMDGPU_HSA_KERNEL
Definition ELF.h:1286
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ OPERAND_IMMEDIATE
Definition MCInstrDesc.h:61
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
void validate(const Triple &TT, const FeatureBitset &FeatureBits)
constexpr bool isAtomicRet(const T &...O)
Definition SIDefines.h:367
constexpr bool isVOPC(const T &...O)
Definition SIDefines.h:236
constexpr bool isVOP3(const T &...O)
Definition SIDefines.h:239
constexpr bool isVOP1(const T &...O)
Definition SIDefines.h:230
constexpr bool usesTENSOR_CNT(const T &...O)
Definition SIDefines.h:310
constexpr bool isMAI(const T &...O)
Definition SIDefines.h:355
constexpr bool isVOP2(const T &...O)
Definition SIDefines.h:233
constexpr bool isSWMMAC(const T &...O)
Definition SIDefines.h:382
constexpr bool isSOP2(const T &...O)
Definition SIDefines.h:218
constexpr bool isFLAT(const T &...O)
Definition SIDefines.h:286
constexpr bool isVOP3P(const T &...O)
Definition SIDefines.h:242
constexpr bool isBuffer(const T &...O)
Definition SIDefines.h:267
constexpr bool hasIntClamp(const T &...O)
Definition SIDefines.h:334
constexpr bool isAtomicNoRet(const T &...O)
Definition SIDefines.h:364
constexpr bool isSMRD(const T &...O)
Definition SIDefines.h:271
constexpr bool isVOP3Like(const T &...O)
Definition SIDefines.h:245
constexpr bool isMIMG(const T &...O)
Definition SIDefines.h:274
constexpr bool isVMEM(const T &...O)
Definition SIDefines.h:407
constexpr bool isImage(const T &...O)
Definition SIDefines.h:403
constexpr bool isWMMA(const T &...O)
Definition SIDefines.h:370
constexpr bool isVOPD3(const T &...O)
Definition SIDefines.h:385
constexpr bool isGWS(const T &...O)
Definition SIDefines.h:379
constexpr bool isMUBUF(const T &...O)
Definition SIDefines.h:261
constexpr bool isSDWA(const T &...O)
Definition SIDefines.h:252
constexpr bool isSOPC(const T &...O)
Definition SIDefines.h:221
constexpr bool isDOT(const T &...O)
Definition SIDefines.h:358
constexpr bool isVSAMPLE(const T &...O)
Definition SIDefines.h:280
constexpr bool isDS(const T &...O)
Definition SIDefines.h:289
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:396
constexpr bool isGather4(const T &...O)
Definition SIDefines.h:307
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
constexpr bool isDPP(const T &...O)
Definition SIDefines.h:255
constexpr bool isSegmentSpecificFLAT(const T &...O)
Definition SIDefines.h:399
@ Valid
The data is already valid.
EnumSet< Modifier > Modifiers
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
bool isNull(StringRef S)
Definition YAMLTraits.h:571
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1129
@ Offset
Definition DWP.cpp:577
StringMapEntry< Value * > ValueName
Definition Value.h:56
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
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition Alignment.h:211
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
static bool isMem(const MachineInstr &MI, unsigned Op)
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
LLVM_ABI void PrintError(const Twine &Msg)
Definition Error.cpp:104
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
Op::Description Desc
Target & getTheR600Target()
The target for R600 GPUs.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SmallVectorImpl< std::unique_ptr< MCParsedAsmOperand > > OperandVector
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
Target & getTheGCNTarget()
The target for GCN GPUs.
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
Target & getTheGCNLegacyTarget()
The target for GCN GPUs, registered under the legacy "amdgcn" architecture name for use with -march.
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
#define N
RegisterKind Kind
StringLiteral Name
void initDefault(const MCSubtargetInfo &STI, MCContext &Ctx, bool InitMCExpr=true)
void validate(const MCSubtargetInfo *STI, MCContext &Ctx)
SmallVector< std::pair< MCSymbol *, std::string >, 4 > IndirectCalls
SmallVector< std::pair< MCSymbol *, MCSymbol * >, 8 > Calls
SmallVector< FuncInfo, 8 > Funcs
SmallVector< std::pair< MCSymbol *, std::string >, 4 > TypeIds
SmallVector< std::pair< MCSymbol *, MCSymbol * >, 4 > Uses
Instruction set architecture version.
static void bits_set(const MCExpr *&Dst, const MCExpr *Value, uint32_t Shift, uint32_t Mask, MCContext &Ctx)
static MCKernelDescriptor getDefaultAmdhsaKernelDescriptor(const MCSubtargetInfo *STI, MCContext &Ctx)
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...