xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 //===- AMDGPUDisassembler.cpp - Disassembler for AMDGPU ISA ---------------===//
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 //===----------------------------------------------------------------------===//
10 //
11 /// \file
12 ///
13 /// This file contains definition for AMDGPU ISA disassembler
14 //
15 //===----------------------------------------------------------------------===//
16 
17 // ToDo: What to do with instruction suffixes (v_mov_b32 vs v_mov_b32_e32)?
18 
19 #include "Disassembler/AMDGPUDisassembler.h"
20 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
21 #include "SIDefines.h"
22 #include "SIRegisterInfo.h"
23 #include "TargetInfo/AMDGPUTargetInfo.h"
24 #include "Utils/AMDGPUBaseInfo.h"
25 #include "llvm-c/DisassemblerTypes.h"
26 #include "llvm/BinaryFormat/ELF.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDecoderOps.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/TargetRegistry.h"
35 #include "llvm/Support/AMDHSAKernelDescriptor.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "amdgpu-disassembler"
40 
41 #define SGPR_MAX                                                               \
42   (isGFX10Plus() ? AMDGPU::EncValues::SGPR_MAX_GFX10                           \
43                  : AMDGPU::EncValues::SGPR_MAX_SI)
44 
45 using DecodeStatus = llvm::MCDisassembler::DecodeStatus;
46 
47 AMDGPUDisassembler::AMDGPUDisassembler(const MCSubtargetInfo &STI,
48                                        MCContext &Ctx, MCInstrInfo const *MCII)
49     : MCDisassembler(STI, Ctx), MCII(MCII), MRI(*Ctx.getRegisterInfo()),
50       MAI(*Ctx.getAsmInfo()), TargetMaxInstBytes(MAI.getMaxInstLength(&STI)) {
51   // ToDo: AMDGPUDisassembler supports only VI ISA.
52   if (!STI.hasFeature(AMDGPU::FeatureGCN3Encoding) && !isGFX10Plus())
53     report_fatal_error("Disassembly not yet supported for subtarget");
54 }
55 
56 inline static MCDisassembler::DecodeStatus
57 addOperand(MCInst &Inst, const MCOperand& Opnd) {
58   Inst.addOperand(Opnd);
59   return Opnd.isValid() ?
60     MCDisassembler::Success :
61     MCDisassembler::Fail;
62 }
63 
64 static int insertNamedMCOperand(MCInst &MI, const MCOperand &Op,
65                                 uint16_t NameIdx) {
66   int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), NameIdx);
67   if (OpIdx != -1) {
68     auto I = MI.begin();
69     std::advance(I, OpIdx);
70     MI.insert(I, Op);
71   }
72   return OpIdx;
73 }
74 
75 static DecodeStatus decodeSOPPBrTarget(MCInst &Inst, unsigned Imm,
76                                        uint64_t Addr,
77                                        const MCDisassembler *Decoder) {
78   auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder);
79 
80   // Our branches take a simm16, but we need two extra bits to account for the
81   // factor of 4.
82   APInt SignedOffset(18, Imm * 4, true);
83   int64_t Offset = (SignedOffset.sext(64) + 4 + Addr).getSExtValue();
84 
85   if (DAsm->tryAddingSymbolicOperand(Inst, Offset, Addr, true, 2, 2, 0))
86     return MCDisassembler::Success;
87   return addOperand(Inst, MCOperand::createImm(Imm));
88 }
89 
90 static DecodeStatus decodeSMEMOffset(MCInst &Inst, unsigned Imm, uint64_t Addr,
91                                      const MCDisassembler *Decoder) {
92   auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder);
93   int64_t Offset;
94   if (DAsm->isVI()) {         // VI supports 20-bit unsigned offsets.
95     Offset = Imm & 0xFFFFF;
96   } else {                    // GFX9+ supports 21-bit signed offsets.
97     Offset = SignExtend64<21>(Imm);
98   }
99   return addOperand(Inst, MCOperand::createImm(Offset));
100 }
101 
102 static DecodeStatus decodeBoolReg(MCInst &Inst, unsigned Val, uint64_t Addr,
103                                   const MCDisassembler *Decoder) {
104   auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder);
105   return addOperand(Inst, DAsm->decodeBoolReg(Val));
106 }
107 
108 #define DECODE_OPERAND(StaticDecoderName, DecoderName)                         \
109   static DecodeStatus StaticDecoderName(MCInst &Inst, unsigned Imm,            \
110                                         uint64_t /*Addr*/,                     \
111                                         const MCDisassembler *Decoder) {       \
112     auto DAsm = static_cast<const AMDGPUDisassembler *>(Decoder);              \
113     return addOperand(Inst, DAsm->DecoderName(Imm));                           \
114   }
115 
116 // Decoder for registers, decode directly using RegClassID. Imm(8-bit) is
117 // number of register. Used by VGPR only and AGPR only operands.
118 #define DECODE_OPERAND_REG_8(RegClass)                                         \
119   static DecodeStatus Decode##RegClass##RegisterClass(                         \
120       MCInst &Inst, unsigned Imm, uint64_t /*Addr*/,                           \
121       const MCDisassembler *Decoder) {                                         \
122     assert(Imm < (1 << 8) && "8-bit encoding");                                \
123     auto DAsm = static_cast<const AMDGPUDisassembler *>(Decoder);              \
124     return addOperand(                                                         \
125         Inst, DAsm->createRegOperand(AMDGPU::RegClass##RegClassID, Imm));      \
126   }
127 
128 #define DECODE_SrcOp(Name, EncSize, OpWidth, EncImm, MandatoryLiteral,         \
129                      ImmWidth)                                                 \
130   static DecodeStatus Name(MCInst &Inst, unsigned Imm, uint64_t /*Addr*/,      \
131                            const MCDisassembler *Decoder) {                    \
132     assert(Imm < (1 << EncSize) && #EncSize "-bit encoding");                  \
133     auto DAsm = static_cast<const AMDGPUDisassembler *>(Decoder);              \
134     return addOperand(Inst,                                                    \
135                       DAsm->decodeSrcOp(AMDGPUDisassembler::OpWidth, EncImm,   \
136                                         MandatoryLiteral, ImmWidth));          \
137   }
138 
139 // Decoder for registers. Imm(7-bit) is number of register, uses decodeSrcOp to
140 // get register class. Used by SGPR only operands.
141 #define DECODE_OPERAND_REG_7(RegClass, OpWidth)                                \
142   DECODE_SrcOp(Decode##RegClass##RegisterClass, 7, OpWidth, Imm, false, 0)
143 
144 // Decoder for registers. Imm(10-bit): Imm{7-0} is number of register,
145 // Imm{9} is acc(agpr or vgpr) Imm{8} should be 0 (see VOP3Pe_SMFMAC).
146 // Set Imm{8} to 1 (IS_VGPR) to decode using 'enum10' from decodeSrcOp.
147 // Used by AV_ register classes (AGPR or VGPR only register operands).
148 #define DECODE_OPERAND_REG_AV10(RegClass, OpWidth)                             \
149   DECODE_SrcOp(Decode##RegClass##RegisterClass, 10, OpWidth,                   \
150                Imm | AMDGPU::EncValues::IS_VGPR, false, 0)
151 
152 // Decoder for Src(9-bit encoding) registers only.
153 #define DECODE_OPERAND_SRC_REG_9(RegClass, OpWidth)                            \
154   DECODE_SrcOp(decodeOperand_##RegClass, 9, OpWidth, Imm, false, 0)
155 
156 // Decoder for Src(9-bit encoding) AGPR, register number encoded in 9bits, set
157 // Imm{9} to 1 (set acc) and decode using 'enum10' from decodeSrcOp, registers
158 // only.
159 #define DECODE_OPERAND_SRC_REG_A9(RegClass, OpWidth)                           \
160   DECODE_SrcOp(decodeOperand_##RegClass, 9, OpWidth, Imm | 512, false, 0)
161 
162 // Decoder for 'enum10' from decodeSrcOp, Imm{0-8} is 9-bit Src encoding
163 // Imm{9} is acc, registers only.
164 #define DECODE_SRC_OPERAND_REG_AV10(RegClass, OpWidth)                         \
165   DECODE_SrcOp(decodeOperand_##RegClass, 10, OpWidth, Imm, false, 0)
166 
167 // Decoder for RegisterOperands using 9-bit Src encoding. Operand can be
168 // register from RegClass or immediate. Registers that don't belong to RegClass
169 // will be decoded and InstPrinter will report warning. Immediate will be
170 // decoded into constant of size ImmWidth, should match width of immediate used
171 // by OperandType (important for floating point types).
172 #define DECODE_OPERAND_SRC_REG_OR_IMM_9(RegClass, OpWidth, ImmWidth)           \
173   DECODE_SrcOp(decodeOperand_##RegClass##_Imm##ImmWidth, 9, OpWidth, Imm,      \
174                false, ImmWidth)
175 
176 // Decoder for Src(9-bit encoding) AGPR or immediate. Set Imm{9} to 1 (set acc)
177 // and decode using 'enum10' from decodeSrcOp.
178 #define DECODE_OPERAND_SRC_REG_OR_IMM_A9(RegClass, OpWidth, ImmWidth)          \
179   DECODE_SrcOp(decodeOperand_##RegClass##_Imm##ImmWidth, 9, OpWidth,           \
180                Imm | 512, false, ImmWidth)
181 
182 #define DECODE_OPERAND_SRC_REG_OR_IMM_DEFERRED_9(RegClass, OpWidth, ImmWidth)  \
183   DECODE_SrcOp(decodeOperand_##RegClass##_Deferred##_Imm##ImmWidth, 9,         \
184                OpWidth, Imm, true, ImmWidth)
185 
186 // Default decoders generated by tablegen: 'Decode<RegClass>RegisterClass'
187 // when RegisterClass is used as an operand. Most often used for destination
188 // operands.
189 
190 DECODE_OPERAND_REG_8(VGPR_32)
191 DECODE_OPERAND_REG_8(VGPR_32_Lo128)
192 DECODE_OPERAND_REG_8(VReg_64)
193 DECODE_OPERAND_REG_8(VReg_96)
194 DECODE_OPERAND_REG_8(VReg_128)
195 DECODE_OPERAND_REG_8(VReg_256)
196 DECODE_OPERAND_REG_8(VReg_288)
197 DECODE_OPERAND_REG_8(VReg_352)
198 DECODE_OPERAND_REG_8(VReg_384)
199 DECODE_OPERAND_REG_8(VReg_512)
200 DECODE_OPERAND_REG_8(VReg_1024)
201 
202 DECODE_OPERAND_REG_7(SReg_32, OPW32)
203 DECODE_OPERAND_REG_7(SReg_32_XM0_XEXEC, OPW32)
204 DECODE_OPERAND_REG_7(SReg_32_XEXEC_HI, OPW32)
205 DECODE_OPERAND_REG_7(SReg_64, OPW64)
206 DECODE_OPERAND_REG_7(SReg_64_XEXEC, OPW64)
207 DECODE_OPERAND_REG_7(SReg_128, OPW128)
208 DECODE_OPERAND_REG_7(SReg_256, OPW256)
209 DECODE_OPERAND_REG_7(SReg_512, OPW512)
210 
211 DECODE_OPERAND_REG_8(AGPR_32)
212 DECODE_OPERAND_REG_8(AReg_64)
213 DECODE_OPERAND_REG_8(AReg_128)
214 DECODE_OPERAND_REG_8(AReg_256)
215 DECODE_OPERAND_REG_8(AReg_512)
216 DECODE_OPERAND_REG_8(AReg_1024)
217 
218 DECODE_OPERAND_REG_AV10(AVDst_128, OPW128)
219 DECODE_OPERAND_REG_AV10(AVDst_512, OPW512)
220 
221 // Decoders for register only source RegisterOperands that use use 9-bit Src
222 // encoding: 'decodeOperand_<RegClass>'.
223 
224 DECODE_OPERAND_SRC_REG_9(VGPR_32, OPW32)
225 DECODE_OPERAND_SRC_REG_9(VReg_64, OPW64)
226 DECODE_OPERAND_SRC_REG_9(VReg_128, OPW128)
227 DECODE_OPERAND_SRC_REG_9(VReg_256, OPW256)
228 DECODE_OPERAND_SRC_REG_9(VRegOrLds_32, OPW32)
229 
230 DECODE_OPERAND_SRC_REG_A9(AGPR_32, OPW32)
231 
232 DECODE_SRC_OPERAND_REG_AV10(AV_32, OPW32)
233 DECODE_SRC_OPERAND_REG_AV10(AV_64, OPW64)
234 DECODE_SRC_OPERAND_REG_AV10(AV_128, OPW128)
235 
236 // Decoders for register or immediate RegisterOperands that use 9-bit Src
237 // encoding: 'decodeOperand_<RegClass>_Imm<ImmWidth>'.
238 
239 DECODE_OPERAND_SRC_REG_OR_IMM_9(SReg_64, OPW64, 64)
240 DECODE_OPERAND_SRC_REG_OR_IMM_9(SReg_32, OPW32, 32)
241 DECODE_OPERAND_SRC_REG_OR_IMM_9(SRegOrLds_32, OPW32, 32)
242 DECODE_OPERAND_SRC_REG_OR_IMM_9(VS_32_Lo128, OPW16, 16)
243 DECODE_OPERAND_SRC_REG_OR_IMM_9(VS_32, OPW32, 16)
244 DECODE_OPERAND_SRC_REG_OR_IMM_9(VS_32, OPW32, 32)
245 DECODE_OPERAND_SRC_REG_OR_IMM_9(VS_64, OPW64, 64)
246 DECODE_OPERAND_SRC_REG_OR_IMM_9(VS_64, OPW64, 32)
247 DECODE_OPERAND_SRC_REG_OR_IMM_9(VReg_64, OPW64, 64)
248 DECODE_OPERAND_SRC_REG_OR_IMM_9(VReg_128, OPW128, 32)
249 DECODE_OPERAND_SRC_REG_OR_IMM_9(VReg_256, OPW256, 64)
250 DECODE_OPERAND_SRC_REG_OR_IMM_9(VReg_512, OPW512, 32)
251 DECODE_OPERAND_SRC_REG_OR_IMM_9(VReg_1024, OPW1024, 32)
252 
253 DECODE_OPERAND_SRC_REG_OR_IMM_A9(AReg_64, OPW64, 64)
254 DECODE_OPERAND_SRC_REG_OR_IMM_A9(AReg_128, OPW128, 32)
255 DECODE_OPERAND_SRC_REG_OR_IMM_A9(AReg_256, OPW256, 64)
256 DECODE_OPERAND_SRC_REG_OR_IMM_A9(AReg_512, OPW512, 32)
257 DECODE_OPERAND_SRC_REG_OR_IMM_A9(AReg_1024, OPW1024, 32)
258 
259 DECODE_OPERAND_SRC_REG_OR_IMM_DEFERRED_9(VS_32_Lo128, OPW16, 16)
260 DECODE_OPERAND_SRC_REG_OR_IMM_DEFERRED_9(VS_32, OPW16, 16)
261 DECODE_OPERAND_SRC_REG_OR_IMM_DEFERRED_9(VS_32, OPW32, 32)
262 
263 static DecodeStatus decodeOperand_KImmFP(MCInst &Inst, unsigned Imm,
264                                          uint64_t Addr,
265                                          const MCDisassembler *Decoder) {
266   const auto *DAsm = static_cast<const AMDGPUDisassembler *>(Decoder);
267   return addOperand(Inst, DAsm->decodeMandatoryLiteralConstant(Imm));
268 }
269 
270 static DecodeStatus decodeOperandVOPDDstY(MCInst &Inst, unsigned Val,
271                                           uint64_t Addr, const void *Decoder) {
272   const auto *DAsm = static_cast<const AMDGPUDisassembler *>(Decoder);
273   return addOperand(Inst, DAsm->decodeVOPDDstYOp(Inst, Val));
274 }
275 
276 static bool IsAGPROperand(const MCInst &Inst, int OpIdx,
277                           const MCRegisterInfo *MRI) {
278   if (OpIdx < 0)
279     return false;
280 
281   const MCOperand &Op = Inst.getOperand(OpIdx);
282   if (!Op.isReg())
283     return false;
284 
285   unsigned Sub = MRI->getSubReg(Op.getReg(), AMDGPU::sub0);
286   auto Reg = Sub ? Sub : Op.getReg();
287   return Reg >= AMDGPU::AGPR0 && Reg <= AMDGPU::AGPR255;
288 }
289 
290 static DecodeStatus decodeOperand_AVLdSt_Any(MCInst &Inst, unsigned Imm,
291                                              AMDGPUDisassembler::OpWidthTy Opw,
292                                              const MCDisassembler *Decoder) {
293   auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder);
294   if (!DAsm->isGFX90A()) {
295     Imm &= 511;
296   } else {
297     // If atomic has both vdata and vdst their register classes are tied.
298     // The bit is decoded along with the vdst, first operand. We need to
299     // change register class to AGPR if vdst was AGPR.
300     // If a DS instruction has both data0 and data1 their register classes
301     // are also tied.
302     unsigned Opc = Inst.getOpcode();
303     uint64_t TSFlags = DAsm->getMCII()->get(Opc).TSFlags;
304     uint16_t DataNameIdx = (TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
305                                                         : AMDGPU::OpName::vdata;
306     const MCRegisterInfo *MRI = DAsm->getContext().getRegisterInfo();
307     int DataIdx = AMDGPU::getNamedOperandIdx(Opc, DataNameIdx);
308     if ((int)Inst.getNumOperands() == DataIdx) {
309       int DstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
310       if (IsAGPROperand(Inst, DstIdx, MRI))
311         Imm |= 512;
312     }
313 
314     if (TSFlags & SIInstrFlags::DS) {
315       int Data2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
316       if ((int)Inst.getNumOperands() == Data2Idx &&
317           IsAGPROperand(Inst, DataIdx, MRI))
318         Imm |= 512;
319     }
320   }
321   return addOperand(Inst, DAsm->decodeSrcOp(Opw, Imm | 256));
322 }
323 
324 static DecodeStatus
325 DecodeAVLdSt_32RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
326                              const MCDisassembler *Decoder) {
327   return decodeOperand_AVLdSt_Any(Inst, Imm,
328                                   AMDGPUDisassembler::OPW32, Decoder);
329 }
330 
331 static DecodeStatus
332 DecodeAVLdSt_64RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
333                              const MCDisassembler *Decoder) {
334   return decodeOperand_AVLdSt_Any(Inst, Imm,
335                                   AMDGPUDisassembler::OPW64, Decoder);
336 }
337 
338 static DecodeStatus
339 DecodeAVLdSt_96RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
340                              const MCDisassembler *Decoder) {
341   return decodeOperand_AVLdSt_Any(Inst, Imm,
342                                   AMDGPUDisassembler::OPW96, Decoder);
343 }
344 
345 static DecodeStatus
346 DecodeAVLdSt_128RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
347                               const MCDisassembler *Decoder) {
348   return decodeOperand_AVLdSt_Any(Inst, Imm,
349                                   AMDGPUDisassembler::OPW128, Decoder);
350 }
351 
352 static DecodeStatus
353 DecodeAVLdSt_160RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
354                               const MCDisassembler *Decoder) {
355   return decodeOperand_AVLdSt_Any(Inst, Imm, AMDGPUDisassembler::OPW160,
356                                   Decoder);
357 }
358 
359 #define DECODE_SDWA(DecName) \
360 DECODE_OPERAND(decodeSDWA##DecName, decodeSDWA##DecName)
361 
362 DECODE_SDWA(Src32)
363 DECODE_SDWA(Src16)
364 DECODE_SDWA(VopcDst)
365 
366 #include "AMDGPUGenDisassemblerTables.inc"
367 
368 //===----------------------------------------------------------------------===//
369 //
370 //===----------------------------------------------------------------------===//
371 
372 template <typename T> static inline T eatBytes(ArrayRef<uint8_t>& Bytes) {
373   assert(Bytes.size() >= sizeof(T));
374   const auto Res = support::endian::read<T, support::endianness::little>(Bytes.data());
375   Bytes = Bytes.slice(sizeof(T));
376   return Res;
377 }
378 
379 static inline DecoderUInt128 eat12Bytes(ArrayRef<uint8_t> &Bytes) {
380   assert(Bytes.size() >= 12);
381   uint64_t Lo = support::endian::read<uint64_t, support::endianness::little>(
382       Bytes.data());
383   Bytes = Bytes.slice(8);
384   uint64_t Hi = support::endian::read<uint32_t, support::endianness::little>(
385       Bytes.data());
386   Bytes = Bytes.slice(4);
387   return DecoderUInt128(Lo, Hi);
388 }
389 
390 // The disassembler is greedy, so we need to check FI operand value to
391 // not parse a dpp if the correct literal is not set. For dpp16 the
392 // autogenerated decoder checks the dpp literal
393 static bool isValidDPP8(const MCInst &MI) {
394   using namespace llvm::AMDGPU::DPP;
395   int FiIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::fi);
396   assert(FiIdx != -1);
397   if ((unsigned)FiIdx >= MI.getNumOperands())
398     return false;
399   unsigned Fi = MI.getOperand(FiIdx).getImm();
400   return Fi == DPP8_FI_0 || Fi == DPP8_FI_1;
401 }
402 
403 DecodeStatus AMDGPUDisassembler::getInstruction(MCInst &MI, uint64_t &Size,
404                                                 ArrayRef<uint8_t> Bytes_,
405                                                 uint64_t Address,
406                                                 raw_ostream &CS) const {
407   bool IsSDWA = false;
408 
409   unsigned MaxInstBytesNum = std::min((size_t)TargetMaxInstBytes, Bytes_.size());
410   Bytes = Bytes_.slice(0, MaxInstBytesNum);
411 
412   DecodeStatus Res = MCDisassembler::Fail;
413   do {
414     // ToDo: better to switch encoding length using some bit predicate
415     // but it is unknown yet, so try all we can
416 
417     // Try to decode DPP and SDWA first to solve conflict with VOP1 and VOP2
418     // encodings
419     if (isGFX11Plus() && Bytes.size() >= 12 ) {
420       DecoderUInt128 DecW = eat12Bytes(Bytes);
421       Res = tryDecodeInst(DecoderTableDPP8GFX1196, MI, DecW, Address, CS);
422       if (Res && convertDPP8Inst(MI) == MCDisassembler::Success)
423         break;
424       MI = MCInst(); // clear
425       Res = tryDecodeInst(DecoderTableDPPGFX1196, MI, DecW, Address, CS);
426       if (Res) {
427         if (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::VOP3P)
428           convertVOP3PDPPInst(MI);
429         else if (AMDGPU::isVOPC64DPP(MI.getOpcode()))
430           convertVOPCDPPInst(MI); // Special VOP3 case
431         else {
432           assert(MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::VOP3);
433           convertVOP3DPPInst(MI); // Regular VOP3 case
434         }
435         break;
436       }
437       Res = tryDecodeInst(DecoderTableGFX1196, MI, DecW, Address, CS);
438       if (Res)
439         break;
440     }
441     // Reinitialize Bytes
442     Bytes = Bytes_.slice(0, MaxInstBytesNum);
443 
444     if (Bytes.size() >= 8) {
445       const uint64_t QW = eatBytes<uint64_t>(Bytes);
446 
447       if (STI.hasFeature(AMDGPU::FeatureGFX10_BEncoding)) {
448         Res = tryDecodeInst(DecoderTableGFX10_B64, MI, QW, Address, CS);
449         if (Res) {
450           if (AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dpp8)
451               == -1)
452             break;
453           if (convertDPP8Inst(MI) == MCDisassembler::Success)
454             break;
455           MI = MCInst(); // clear
456         }
457       }
458 
459       Res = tryDecodeInst(DecoderTableDPP864, MI, QW, Address, CS);
460       if (Res && convertDPP8Inst(MI) == MCDisassembler::Success)
461         break;
462       MI = MCInst(); // clear
463 
464       Res = tryDecodeInst(DecoderTableDPP8GFX1164, MI, QW, Address, CS);
465       if (Res && convertDPP8Inst(MI) == MCDisassembler::Success)
466         break;
467       MI = MCInst(); // clear
468 
469       Res = tryDecodeInst(DecoderTableDPP64, MI, QW, Address, CS);
470       if (Res) break;
471 
472       Res = tryDecodeInst(DecoderTableDPPGFX1164, MI, QW, Address, CS);
473       if (Res) {
474         if (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::VOPC)
475           convertVOPCDPPInst(MI);
476         break;
477       }
478 
479       Res = tryDecodeInst(DecoderTableSDWA64, MI, QW, Address, CS);
480       if (Res) { IsSDWA = true;  break; }
481 
482       Res = tryDecodeInst(DecoderTableSDWA964, MI, QW, Address, CS);
483       if (Res) { IsSDWA = true;  break; }
484 
485       Res = tryDecodeInst(DecoderTableSDWA1064, MI, QW, Address, CS);
486       if (Res) { IsSDWA = true;  break; }
487 
488       if (STI.hasFeature(AMDGPU::FeatureUnpackedD16VMem)) {
489         Res = tryDecodeInst(DecoderTableGFX80_UNPACKED64, MI, QW, Address, CS);
490         if (Res)
491           break;
492       }
493 
494       // Some GFX9 subtargets repurposed the v_mad_mix_f32, v_mad_mixlo_f16 and
495       // v_mad_mixhi_f16 for FMA variants. Try to decode using this special
496       // table first so we print the correct name.
497       if (STI.hasFeature(AMDGPU::FeatureFmaMixInsts)) {
498         Res = tryDecodeInst(DecoderTableGFX9_DL64, MI, QW, Address, CS);
499         if (Res)
500           break;
501       }
502     }
503 
504     // Reinitialize Bytes as DPP64 could have eaten too much
505     Bytes = Bytes_.slice(0, MaxInstBytesNum);
506 
507     // Try decode 32-bit instruction
508     if (Bytes.size() < 4) break;
509     const uint32_t DW = eatBytes<uint32_t>(Bytes);
510     Res = tryDecodeInst(DecoderTableGFX832, MI, DW, Address, CS);
511     if (Res) break;
512 
513     Res = tryDecodeInst(DecoderTableAMDGPU32, MI, DW, Address, CS);
514     if (Res) break;
515 
516     Res = tryDecodeInst(DecoderTableGFX932, MI, DW, Address, CS);
517     if (Res) break;
518 
519     if (STI.hasFeature(AMDGPU::FeatureGFX90AInsts)) {
520       Res = tryDecodeInst(DecoderTableGFX90A32, MI, DW, Address, CS);
521       if (Res)
522         break;
523     }
524 
525     if (STI.hasFeature(AMDGPU::FeatureGFX10_BEncoding)) {
526       Res = tryDecodeInst(DecoderTableGFX10_B32, MI, DW, Address, CS);
527       if (Res) break;
528     }
529 
530     Res = tryDecodeInst(DecoderTableGFX1032, MI, DW, Address, CS);
531     if (Res) break;
532 
533     Res = tryDecodeInst(DecoderTableGFX1132, MI, DW, Address, CS);
534     if (Res) break;
535 
536     if (Bytes.size() < 4) break;
537     const uint64_t QW = ((uint64_t)eatBytes<uint32_t>(Bytes) << 32) | DW;
538 
539     if (STI.hasFeature(AMDGPU::FeatureGFX940Insts)) {
540       Res = tryDecodeInst(DecoderTableGFX94064, MI, QW, Address, CS);
541       if (Res)
542         break;
543     }
544 
545     if (STI.hasFeature(AMDGPU::FeatureGFX90AInsts)) {
546       Res = tryDecodeInst(DecoderTableGFX90A64, MI, QW, Address, CS);
547       if (Res)
548         break;
549     }
550 
551     Res = tryDecodeInst(DecoderTableGFX864, MI, QW, Address, CS);
552     if (Res) break;
553 
554     Res = tryDecodeInst(DecoderTableAMDGPU64, MI, QW, Address, CS);
555     if (Res) break;
556 
557     Res = tryDecodeInst(DecoderTableGFX964, MI, QW, Address, CS);
558     if (Res) break;
559 
560     Res = tryDecodeInst(DecoderTableGFX1064, MI, QW, Address, CS);
561     if (Res) break;
562 
563     Res = tryDecodeInst(DecoderTableGFX1164, MI, QW, Address, CS);
564     if (Res)
565       break;
566 
567     Res = tryDecodeInst(DecoderTableWMMAGFX1164, MI, QW, Address, CS);
568   } while (false);
569 
570   if (Res && AMDGPU::isMAC(MI.getOpcode())) {
571     // Insert dummy unused src2_modifiers.
572     insertNamedMCOperand(MI, MCOperand::createImm(0),
573                          AMDGPU::OpName::src2_modifiers);
574   }
575 
576   if (Res && (MCII->get(MI.getOpcode()).TSFlags &
577           (SIInstrFlags::MUBUF | SIInstrFlags::FLAT | SIInstrFlags::SMRD))) {
578     int CPolPos = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
579                                              AMDGPU::OpName::cpol);
580     if (CPolPos != -1) {
581       unsigned CPol =
582           (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::IsAtomicRet) ?
583               AMDGPU::CPol::GLC : 0;
584       if (MI.getNumOperands() <= (unsigned)CPolPos) {
585         insertNamedMCOperand(MI, MCOperand::createImm(CPol),
586                              AMDGPU::OpName::cpol);
587       } else if (CPol) {
588         MI.getOperand(CPolPos).setImm(MI.getOperand(CPolPos).getImm() | CPol);
589       }
590     }
591   }
592 
593   if (Res && (MCII->get(MI.getOpcode()).TSFlags &
594               (SIInstrFlags::MTBUF | SIInstrFlags::MUBUF)) &&
595              (STI.hasFeature(AMDGPU::FeatureGFX90AInsts))) {
596     // GFX90A lost TFE, its place is occupied by ACC.
597     int TFEOpIdx =
598         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::tfe);
599     if (TFEOpIdx != -1) {
600       auto TFEIter = MI.begin();
601       std::advance(TFEIter, TFEOpIdx);
602       MI.insert(TFEIter, MCOperand::createImm(0));
603     }
604   }
605 
606   if (Res && (MCII->get(MI.getOpcode()).TSFlags &
607               (SIInstrFlags::MTBUF | SIInstrFlags::MUBUF))) {
608     int SWZOpIdx =
609         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::swz);
610     if (SWZOpIdx != -1) {
611       auto SWZIter = MI.begin();
612       std::advance(SWZIter, SWZOpIdx);
613       MI.insert(SWZIter, MCOperand::createImm(0));
614     }
615   }
616 
617   if (Res && (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::MIMG)) {
618     int VAddr0Idx =
619         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vaddr0);
620     int RsrcIdx =
621         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
622     unsigned NSAArgs = RsrcIdx - VAddr0Idx - 1;
623     if (VAddr0Idx >= 0 && NSAArgs > 0) {
624       unsigned NSAWords = (NSAArgs + 3) / 4;
625       if (Bytes.size() < 4 * NSAWords) {
626         Res = MCDisassembler::Fail;
627       } else {
628         for (unsigned i = 0; i < NSAArgs; ++i) {
629           const unsigned VAddrIdx = VAddr0Idx + 1 + i;
630           auto VAddrRCID =
631               MCII->get(MI.getOpcode()).operands()[VAddrIdx].RegClass;
632           MI.insert(MI.begin() + VAddrIdx,
633                     createRegOperand(VAddrRCID, Bytes[i]));
634         }
635         Bytes = Bytes.slice(4 * NSAWords);
636       }
637     }
638 
639     if (Res)
640       Res = convertMIMGInst(MI);
641   }
642 
643   if (Res && (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::EXP))
644     Res = convertEXPInst(MI);
645 
646   if (Res && (MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::VINTERP))
647     Res = convertVINTERPInst(MI);
648 
649   if (Res && IsSDWA)
650     Res = convertSDWAInst(MI);
651 
652   int VDstIn_Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
653                                               AMDGPU::OpName::vdst_in);
654   if (VDstIn_Idx != -1) {
655     int Tied = MCII->get(MI.getOpcode()).getOperandConstraint(VDstIn_Idx,
656                            MCOI::OperandConstraint::TIED_TO);
657     if (Tied != -1 && (MI.getNumOperands() <= (unsigned)VDstIn_Idx ||
658          !MI.getOperand(VDstIn_Idx).isReg() ||
659          MI.getOperand(VDstIn_Idx).getReg() != MI.getOperand(Tied).getReg())) {
660       if (MI.getNumOperands() > (unsigned)VDstIn_Idx)
661         MI.erase(&MI.getOperand(VDstIn_Idx));
662       insertNamedMCOperand(MI,
663         MCOperand::createReg(MI.getOperand(Tied).getReg()),
664         AMDGPU::OpName::vdst_in);
665     }
666   }
667 
668   int ImmLitIdx =
669       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::imm);
670   bool IsSOPK = MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::SOPK;
671   if (Res && ImmLitIdx != -1 && !IsSOPK)
672     Res = convertFMAanyK(MI, ImmLitIdx);
673 
674   // if the opcode was not recognized we'll assume a Size of 4 bytes
675   // (unless there are fewer bytes left)
676   Size = Res ? (MaxInstBytesNum - Bytes.size())
677              : std::min((size_t)4, Bytes_.size());
678   return Res;
679 }
680 
681 DecodeStatus AMDGPUDisassembler::convertEXPInst(MCInst &MI) const {
682   if (STI.hasFeature(AMDGPU::FeatureGFX11)) {
683     // The MCInst still has these fields even though they are no longer encoded
684     // in the GFX11 instruction.
685     insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::vm);
686     insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::compr);
687   }
688   return MCDisassembler::Success;
689 }
690 
691 DecodeStatus AMDGPUDisassembler::convertVINTERPInst(MCInst &MI) const {
692   if (MI.getOpcode() == AMDGPU::V_INTERP_P10_F16_F32_inreg_gfx11 ||
693       MI.getOpcode() == AMDGPU::V_INTERP_P10_RTZ_F16_F32_inreg_gfx11 ||
694       MI.getOpcode() == AMDGPU::V_INTERP_P2_F16_F32_inreg_gfx11 ||
695       MI.getOpcode() == AMDGPU::V_INTERP_P2_RTZ_F16_F32_inreg_gfx11) {
696     // The MCInst has this field that is not directly encoded in the
697     // instruction.
698     insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::op_sel);
699   }
700   return MCDisassembler::Success;
701 }
702 
703 DecodeStatus AMDGPUDisassembler::convertSDWAInst(MCInst &MI) const {
704   if (STI.hasFeature(AMDGPU::FeatureGFX9) ||
705       STI.hasFeature(AMDGPU::FeatureGFX10)) {
706     if (AMDGPU::hasNamedOperand(MI.getOpcode(), AMDGPU::OpName::sdst))
707       // VOPC - insert clamp
708       insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::clamp);
709   } else if (STI.hasFeature(AMDGPU::FeatureVolcanicIslands)) {
710     int SDst = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sdst);
711     if (SDst != -1) {
712       // VOPC - insert VCC register as sdst
713       insertNamedMCOperand(MI, createRegOperand(AMDGPU::VCC),
714                            AMDGPU::OpName::sdst);
715     } else {
716       // VOP1/2 - insert omod if present in instruction
717       insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::omod);
718     }
719   }
720   return MCDisassembler::Success;
721 }
722 
723 struct VOPModifiers {
724   unsigned OpSel = 0;
725   unsigned OpSelHi = 0;
726   unsigned NegLo = 0;
727   unsigned NegHi = 0;
728 };
729 
730 // Reconstruct values of VOP3/VOP3P operands such as op_sel.
731 // Note that these values do not affect disassembler output,
732 // so this is only necessary for consistency with src_modifiers.
733 static VOPModifiers collectVOPModifiers(const MCInst &MI,
734                                         bool IsVOP3P = false) {
735   VOPModifiers Modifiers;
736   unsigned Opc = MI.getOpcode();
737   const int ModOps[] = {AMDGPU::OpName::src0_modifiers,
738                         AMDGPU::OpName::src1_modifiers,
739                         AMDGPU::OpName::src2_modifiers};
740   for (int J = 0; J < 3; ++J) {
741     int OpIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
742     if (OpIdx == -1)
743       continue;
744 
745     unsigned Val = MI.getOperand(OpIdx).getImm();
746 
747     Modifiers.OpSel |= !!(Val & SISrcMods::OP_SEL_0) << J;
748     if (IsVOP3P) {
749       Modifiers.OpSelHi |= !!(Val & SISrcMods::OP_SEL_1) << J;
750       Modifiers.NegLo |= !!(Val & SISrcMods::NEG) << J;
751       Modifiers.NegHi |= !!(Val & SISrcMods::NEG_HI) << J;
752     } else if (J == 0) {
753       Modifiers.OpSel |= !!(Val & SISrcMods::DST_OP_SEL) << 3;
754     }
755   }
756 
757   return Modifiers;
758 }
759 
760 // MAC opcodes have special old and src2 operands.
761 // src2 is tied to dst, while old is not tied (but assumed to be).
762 bool AMDGPUDisassembler::isMacDPP(MCInst &MI) const {
763   constexpr int DST_IDX = 0;
764   auto Opcode = MI.getOpcode();
765   const auto &Desc = MCII->get(Opcode);
766   auto OldIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::old);
767 
768   if (OldIdx != -1 && Desc.getOperandConstraint(
769                           OldIdx, MCOI::OperandConstraint::TIED_TO) == -1) {
770     assert(AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::src2));
771     assert(Desc.getOperandConstraint(
772                AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2),
773                MCOI::OperandConstraint::TIED_TO) == DST_IDX);
774     (void)DST_IDX;
775     return true;
776   }
777 
778   return false;
779 }
780 
781 // Create dummy old operand and insert dummy unused src2_modifiers
782 void AMDGPUDisassembler::convertMacDPPInst(MCInst &MI) const {
783   assert(MI.getNumOperands() + 1 < MCII->get(MI.getOpcode()).getNumOperands());
784   insertNamedMCOperand(MI, MCOperand::createReg(0), AMDGPU::OpName::old);
785   insertNamedMCOperand(MI, MCOperand::createImm(0),
786                        AMDGPU::OpName::src2_modifiers);
787 }
788 
789 // We must check FI == literal to reject not genuine dpp8 insts, and we must
790 // first add optional MI operands to check FI
791 DecodeStatus AMDGPUDisassembler::convertDPP8Inst(MCInst &MI) const {
792   unsigned Opc = MI.getOpcode();
793   if (MCII->get(Opc).TSFlags & SIInstrFlags::VOP3P) {
794     convertVOP3PDPPInst(MI);
795   } else if ((MCII->get(Opc).TSFlags & SIInstrFlags::VOPC) ||
796              AMDGPU::isVOPC64DPP(Opc)) {
797     convertVOPCDPPInst(MI);
798   } else {
799     if (isMacDPP(MI))
800       convertMacDPPInst(MI);
801 
802     unsigned DescNumOps = MCII->get(Opc).getNumOperands();
803     if (MI.getNumOperands() < DescNumOps &&
804         AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
805       auto Mods = collectVOPModifiers(MI);
806       insertNamedMCOperand(MI, MCOperand::createImm(Mods.OpSel),
807                            AMDGPU::OpName::op_sel);
808     } else {
809       // Insert dummy unused src modifiers.
810       if (MI.getNumOperands() < DescNumOps &&
811           AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src0_modifiers))
812         insertNamedMCOperand(MI, MCOperand::createImm(0),
813                              AMDGPU::OpName::src0_modifiers);
814 
815       if (MI.getNumOperands() < DescNumOps &&
816           AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src1_modifiers))
817         insertNamedMCOperand(MI, MCOperand::createImm(0),
818                              AMDGPU::OpName::src1_modifiers);
819     }
820   }
821   return isValidDPP8(MI) ? MCDisassembler::Success : MCDisassembler::SoftFail;
822 }
823 
824 DecodeStatus AMDGPUDisassembler::convertVOP3DPPInst(MCInst &MI) const {
825   if (isMacDPP(MI))
826     convertMacDPPInst(MI);
827 
828   unsigned Opc = MI.getOpcode();
829   unsigned DescNumOps = MCII->get(Opc).getNumOperands();
830   if (MI.getNumOperands() < DescNumOps &&
831       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel)) {
832     auto Mods = collectVOPModifiers(MI);
833     insertNamedMCOperand(MI, MCOperand::createImm(Mods.OpSel),
834                          AMDGPU::OpName::op_sel);
835   }
836   return MCDisassembler::Success;
837 }
838 
839 // Note that before gfx10, the MIMG encoding provided no information about
840 // VADDR size. Consequently, decoded instructions always show address as if it
841 // has 1 dword, which could be not really so.
842 DecodeStatus AMDGPUDisassembler::convertMIMGInst(MCInst &MI) const {
843 
844   int VDstIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
845                                            AMDGPU::OpName::vdst);
846 
847   int VDataIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
848                                             AMDGPU::OpName::vdata);
849   int VAddr0Idx =
850       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vaddr0);
851   int RsrcIdx =
852       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
853   int DMaskIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
854                                             AMDGPU::OpName::dmask);
855 
856   int TFEIdx   = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
857                                             AMDGPU::OpName::tfe);
858   int D16Idx   = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
859                                             AMDGPU::OpName::d16);
860 
861   const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
862   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
863       AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
864 
865   assert(VDataIdx != -1);
866   if (BaseOpcode->BVH) {
867     // Add A16 operand for intersect_ray instructions
868     addOperand(MI, MCOperand::createImm(BaseOpcode->A16));
869     return MCDisassembler::Success;
870   }
871 
872   bool IsAtomic = (VDstIdx != -1);
873   bool IsGather4 = MCII->get(MI.getOpcode()).TSFlags & SIInstrFlags::Gather4;
874   bool IsNSA = false;
875   bool IsPartialNSA = false;
876   unsigned AddrSize = Info->VAddrDwords;
877 
878   if (isGFX10Plus()) {
879     unsigned DimIdx =
880         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dim);
881     int A16Idx =
882         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::a16);
883     const AMDGPU::MIMGDimInfo *Dim =
884         AMDGPU::getMIMGDimInfoByEncoding(MI.getOperand(DimIdx).getImm());
885     const bool IsA16 = (A16Idx != -1 && MI.getOperand(A16Idx).getImm());
886 
887     AddrSize =
888         AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, AMDGPU::hasG16(STI));
889 
890     IsNSA = Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA ||
891             Info->MIMGEncoding == AMDGPU::MIMGEncGfx11NSA;
892     if (!IsNSA) {
893       if (AddrSize > 12)
894         AddrSize = 16;
895     } else {
896       if (AddrSize > Info->VAddrDwords) {
897         if (!STI.hasFeature(AMDGPU::FeaturePartialNSAEncoding)) {
898           // The NSA encoding does not contain enough operands for the
899           // combination of base opcode / dimension. Should this be an error?
900           return MCDisassembler::Success;
901         }
902         IsPartialNSA = true;
903       }
904     }
905   }
906 
907   unsigned DMask = MI.getOperand(DMaskIdx).getImm() & 0xf;
908   unsigned DstSize = IsGather4 ? 4 : std::max(llvm::popcount(DMask), 1);
909 
910   bool D16 = D16Idx >= 0 && MI.getOperand(D16Idx).getImm();
911   if (D16 && AMDGPU::hasPackedD16(STI)) {
912     DstSize = (DstSize + 1) / 2;
913   }
914 
915   if (TFEIdx != -1 && MI.getOperand(TFEIdx).getImm())
916     DstSize += 1;
917 
918   if (DstSize == Info->VDataDwords && AddrSize == Info->VAddrDwords)
919     return MCDisassembler::Success;
920 
921   int NewOpcode =
922       AMDGPU::getMIMGOpcode(Info->BaseOpcode, Info->MIMGEncoding, DstSize, AddrSize);
923   if (NewOpcode == -1)
924     return MCDisassembler::Success;
925 
926   // Widen the register to the correct number of enabled channels.
927   unsigned NewVdata = AMDGPU::NoRegister;
928   if (DstSize != Info->VDataDwords) {
929     auto DataRCID = MCII->get(NewOpcode).operands()[VDataIdx].RegClass;
930 
931     // Get first subregister of VData
932     unsigned Vdata0 = MI.getOperand(VDataIdx).getReg();
933     unsigned VdataSub0 = MRI.getSubReg(Vdata0, AMDGPU::sub0);
934     Vdata0 = (VdataSub0 != 0)? VdataSub0 : Vdata0;
935 
936     NewVdata = MRI.getMatchingSuperReg(Vdata0, AMDGPU::sub0,
937                                        &MRI.getRegClass(DataRCID));
938     if (NewVdata == AMDGPU::NoRegister) {
939       // It's possible to encode this such that the low register + enabled
940       // components exceeds the register count.
941       return MCDisassembler::Success;
942     }
943   }
944 
945   // If not using NSA on GFX10+, widen vaddr0 address register to correct size.
946   // If using partial NSA on GFX11+ widen last address register.
947   int VAddrSAIdx = IsPartialNSA ? (RsrcIdx - 1) : VAddr0Idx;
948   unsigned NewVAddrSA = AMDGPU::NoRegister;
949   if (STI.hasFeature(AMDGPU::FeatureNSAEncoding) && (!IsNSA || IsPartialNSA) &&
950       AddrSize != Info->VAddrDwords) {
951     unsigned VAddrSA = MI.getOperand(VAddrSAIdx).getReg();
952     unsigned VAddrSubSA = MRI.getSubReg(VAddrSA, AMDGPU::sub0);
953     VAddrSA = VAddrSubSA ? VAddrSubSA : VAddrSA;
954 
955     auto AddrRCID = MCII->get(NewOpcode).operands()[VAddrSAIdx].RegClass;
956     NewVAddrSA = MRI.getMatchingSuperReg(VAddrSA, AMDGPU::sub0,
957                                         &MRI.getRegClass(AddrRCID));
958     if (!NewVAddrSA)
959       return MCDisassembler::Success;
960   }
961 
962   MI.setOpcode(NewOpcode);
963 
964   if (NewVdata != AMDGPU::NoRegister) {
965     MI.getOperand(VDataIdx) = MCOperand::createReg(NewVdata);
966 
967     if (IsAtomic) {
968       // Atomic operations have an additional operand (a copy of data)
969       MI.getOperand(VDstIdx) = MCOperand::createReg(NewVdata);
970     }
971   }
972 
973   if (NewVAddrSA) {
974     MI.getOperand(VAddrSAIdx) = MCOperand::createReg(NewVAddrSA);
975   } else if (IsNSA) {
976     assert(AddrSize <= Info->VAddrDwords);
977     MI.erase(MI.begin() + VAddr0Idx + AddrSize,
978              MI.begin() + VAddr0Idx + Info->VAddrDwords);
979   }
980 
981   return MCDisassembler::Success;
982 }
983 
984 // Opsel and neg bits are used in src_modifiers and standalone operands. Autogen
985 // decoder only adds to src_modifiers, so manually add the bits to the other
986 // operands.
987 DecodeStatus AMDGPUDisassembler::convertVOP3PDPPInst(MCInst &MI) const {
988   unsigned Opc = MI.getOpcode();
989   unsigned DescNumOps = MCII->get(Opc).getNumOperands();
990   auto Mods = collectVOPModifiers(MI, true);
991 
992   if (MI.getNumOperands() < DescNumOps &&
993       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vdst_in))
994     insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::vdst_in);
995 
996   if (MI.getNumOperands() < DescNumOps &&
997       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel))
998     insertNamedMCOperand(MI, MCOperand::createImm(Mods.OpSel),
999                          AMDGPU::OpName::op_sel);
1000   if (MI.getNumOperands() < DescNumOps &&
1001       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel_hi))
1002     insertNamedMCOperand(MI, MCOperand::createImm(Mods.OpSelHi),
1003                          AMDGPU::OpName::op_sel_hi);
1004   if (MI.getNumOperands() < DescNumOps &&
1005       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::neg_lo))
1006     insertNamedMCOperand(MI, MCOperand::createImm(Mods.NegLo),
1007                          AMDGPU::OpName::neg_lo);
1008   if (MI.getNumOperands() < DescNumOps &&
1009       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::neg_hi))
1010     insertNamedMCOperand(MI, MCOperand::createImm(Mods.NegHi),
1011                          AMDGPU::OpName::neg_hi);
1012 
1013   return MCDisassembler::Success;
1014 }
1015 
1016 // Create dummy old operand and insert optional operands
1017 DecodeStatus AMDGPUDisassembler::convertVOPCDPPInst(MCInst &MI) const {
1018   unsigned Opc = MI.getOpcode();
1019   unsigned DescNumOps = MCII->get(Opc).getNumOperands();
1020 
1021   if (MI.getNumOperands() < DescNumOps &&
1022       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::old))
1023     insertNamedMCOperand(MI, MCOperand::createReg(0), AMDGPU::OpName::old);
1024 
1025   if (MI.getNumOperands() < DescNumOps &&
1026       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src0_modifiers))
1027     insertNamedMCOperand(MI, MCOperand::createImm(0),
1028                          AMDGPU::OpName::src0_modifiers);
1029 
1030   if (MI.getNumOperands() < DescNumOps &&
1031       AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::src1_modifiers))
1032     insertNamedMCOperand(MI, MCOperand::createImm(0),
1033                          AMDGPU::OpName::src1_modifiers);
1034   return MCDisassembler::Success;
1035 }
1036 
1037 DecodeStatus AMDGPUDisassembler::convertFMAanyK(MCInst &MI,
1038                                                 int ImmLitIdx) const {
1039   assert(HasLiteral && "Should have decoded a literal");
1040   const MCInstrDesc &Desc = MCII->get(MI.getOpcode());
1041   unsigned DescNumOps = Desc.getNumOperands();
1042   insertNamedMCOperand(MI, MCOperand::createImm(Literal),
1043                        AMDGPU::OpName::immDeferred);
1044   assert(DescNumOps == MI.getNumOperands());
1045   for (unsigned I = 0; I < DescNumOps; ++I) {
1046     auto &Op = MI.getOperand(I);
1047     auto OpType = Desc.operands()[I].OperandType;
1048     bool IsDeferredOp = (OpType == AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED ||
1049                          OpType == AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED);
1050     if (Op.isImm() && Op.getImm() == AMDGPU::EncValues::LITERAL_CONST &&
1051         IsDeferredOp)
1052       Op.setImm(Literal);
1053   }
1054   return MCDisassembler::Success;
1055 }
1056 
1057 const char* AMDGPUDisassembler::getRegClassName(unsigned RegClassID) const {
1058   return getContext().getRegisterInfo()->
1059     getRegClassName(&AMDGPUMCRegisterClasses[RegClassID]);
1060 }
1061 
1062 inline
1063 MCOperand AMDGPUDisassembler::errOperand(unsigned V,
1064                                          const Twine& ErrMsg) const {
1065   *CommentStream << "Error: " + ErrMsg;
1066 
1067   // ToDo: add support for error operands to MCInst.h
1068   // return MCOperand::createError(V);
1069   return MCOperand();
1070 }
1071 
1072 inline
1073 MCOperand AMDGPUDisassembler::createRegOperand(unsigned int RegId) const {
1074   return MCOperand::createReg(AMDGPU::getMCReg(RegId, STI));
1075 }
1076 
1077 inline
1078 MCOperand AMDGPUDisassembler::createRegOperand(unsigned RegClassID,
1079                                                unsigned Val) const {
1080   const auto& RegCl = AMDGPUMCRegisterClasses[RegClassID];
1081   if (Val >= RegCl.getNumRegs())
1082     return errOperand(Val, Twine(getRegClassName(RegClassID)) +
1083                            ": unknown register " + Twine(Val));
1084   return createRegOperand(RegCl.getRegister(Val));
1085 }
1086 
1087 inline
1088 MCOperand AMDGPUDisassembler::createSRegOperand(unsigned SRegClassID,
1089                                                 unsigned Val) const {
1090   // ToDo: SI/CI have 104 SGPRs, VI - 102
1091   // Valery: here we accepting as much as we can, let assembler sort it out
1092   int shift = 0;
1093   switch (SRegClassID) {
1094   case AMDGPU::SGPR_32RegClassID:
1095   case AMDGPU::TTMP_32RegClassID:
1096     break;
1097   case AMDGPU::SGPR_64RegClassID:
1098   case AMDGPU::TTMP_64RegClassID:
1099     shift = 1;
1100     break;
1101   case AMDGPU::SGPR_128RegClassID:
1102   case AMDGPU::TTMP_128RegClassID:
1103   // ToDo: unclear if s[100:104] is available on VI. Can we use VCC as SGPR in
1104   // this bundle?
1105   case AMDGPU::SGPR_256RegClassID:
1106   case AMDGPU::TTMP_256RegClassID:
1107     // ToDo: unclear if s[96:104] is available on VI. Can we use VCC as SGPR in
1108   // this bundle?
1109   case AMDGPU::SGPR_288RegClassID:
1110   case AMDGPU::TTMP_288RegClassID:
1111   case AMDGPU::SGPR_320RegClassID:
1112   case AMDGPU::TTMP_320RegClassID:
1113   case AMDGPU::SGPR_352RegClassID:
1114   case AMDGPU::TTMP_352RegClassID:
1115   case AMDGPU::SGPR_384RegClassID:
1116   case AMDGPU::TTMP_384RegClassID:
1117   case AMDGPU::SGPR_512RegClassID:
1118   case AMDGPU::TTMP_512RegClassID:
1119     shift = 2;
1120     break;
1121   // ToDo: unclear if s[88:104] is available on VI. Can we use VCC as SGPR in
1122   // this bundle?
1123   default:
1124     llvm_unreachable("unhandled register class");
1125   }
1126 
1127   if (Val % (1 << shift)) {
1128     *CommentStream << "Warning: " << getRegClassName(SRegClassID)
1129                    << ": scalar reg isn't aligned " << Val;
1130   }
1131 
1132   return createRegOperand(SRegClassID, Val >> shift);
1133 }
1134 
1135 // Decode Literals for insts which always have a literal in the encoding
1136 MCOperand
1137 AMDGPUDisassembler::decodeMandatoryLiteralConstant(unsigned Val) const {
1138   if (HasLiteral) {
1139     assert(
1140         AMDGPU::hasVOPD(STI) &&
1141         "Should only decode multiple kimm with VOPD, check VSrc operand types");
1142     if (Literal != Val)
1143       return errOperand(Val, "More than one unique literal is illegal");
1144   }
1145   HasLiteral = true;
1146   Literal = Val;
1147   return MCOperand::createImm(Literal);
1148 }
1149 
1150 MCOperand AMDGPUDisassembler::decodeLiteralConstant() const {
1151   // For now all literal constants are supposed to be unsigned integer
1152   // ToDo: deal with signed/unsigned 64-bit integer constants
1153   // ToDo: deal with float/double constants
1154   if (!HasLiteral) {
1155     if (Bytes.size() < 4) {
1156       return errOperand(0, "cannot read literal, inst bytes left " +
1157                         Twine(Bytes.size()));
1158     }
1159     HasLiteral = true;
1160     Literal = eatBytes<uint32_t>(Bytes);
1161   }
1162   return MCOperand::createImm(Literal);
1163 }
1164 
1165 MCOperand AMDGPUDisassembler::decodeIntImmed(unsigned Imm) {
1166   using namespace AMDGPU::EncValues;
1167 
1168   assert(Imm >= INLINE_INTEGER_C_MIN && Imm <= INLINE_INTEGER_C_MAX);
1169   return MCOperand::createImm((Imm <= INLINE_INTEGER_C_POSITIVE_MAX) ?
1170     (static_cast<int64_t>(Imm) - INLINE_INTEGER_C_MIN) :
1171     (INLINE_INTEGER_C_POSITIVE_MAX - static_cast<int64_t>(Imm)));
1172       // Cast prevents negative overflow.
1173 }
1174 
1175 static int64_t getInlineImmVal32(unsigned Imm) {
1176   switch (Imm) {
1177   case 240:
1178     return llvm::bit_cast<uint32_t>(0.5f);
1179   case 241:
1180     return llvm::bit_cast<uint32_t>(-0.5f);
1181   case 242:
1182     return llvm::bit_cast<uint32_t>(1.0f);
1183   case 243:
1184     return llvm::bit_cast<uint32_t>(-1.0f);
1185   case 244:
1186     return llvm::bit_cast<uint32_t>(2.0f);
1187   case 245:
1188     return llvm::bit_cast<uint32_t>(-2.0f);
1189   case 246:
1190     return llvm::bit_cast<uint32_t>(4.0f);
1191   case 247:
1192     return llvm::bit_cast<uint32_t>(-4.0f);
1193   case 248: // 1 / (2 * PI)
1194     return 0x3e22f983;
1195   default:
1196     llvm_unreachable("invalid fp inline imm");
1197   }
1198 }
1199 
1200 static int64_t getInlineImmVal64(unsigned Imm) {
1201   switch (Imm) {
1202   case 240:
1203     return llvm::bit_cast<uint64_t>(0.5);
1204   case 241:
1205     return llvm::bit_cast<uint64_t>(-0.5);
1206   case 242:
1207     return llvm::bit_cast<uint64_t>(1.0);
1208   case 243:
1209     return llvm::bit_cast<uint64_t>(-1.0);
1210   case 244:
1211     return llvm::bit_cast<uint64_t>(2.0);
1212   case 245:
1213     return llvm::bit_cast<uint64_t>(-2.0);
1214   case 246:
1215     return llvm::bit_cast<uint64_t>(4.0);
1216   case 247:
1217     return llvm::bit_cast<uint64_t>(-4.0);
1218   case 248: // 1 / (2 * PI)
1219     return 0x3fc45f306dc9c882;
1220   default:
1221     llvm_unreachable("invalid fp inline imm");
1222   }
1223 }
1224 
1225 static int64_t getInlineImmVal16(unsigned Imm) {
1226   switch (Imm) {
1227   case 240:
1228     return 0x3800;
1229   case 241:
1230     return 0xB800;
1231   case 242:
1232     return 0x3C00;
1233   case 243:
1234     return 0xBC00;
1235   case 244:
1236     return 0x4000;
1237   case 245:
1238     return 0xC000;
1239   case 246:
1240     return 0x4400;
1241   case 247:
1242     return 0xC400;
1243   case 248: // 1 / (2 * PI)
1244     return 0x3118;
1245   default:
1246     llvm_unreachable("invalid fp inline imm");
1247   }
1248 }
1249 
1250 MCOperand AMDGPUDisassembler::decodeFPImmed(unsigned ImmWidth, unsigned Imm) {
1251   assert(Imm >= AMDGPU::EncValues::INLINE_FLOATING_C_MIN
1252       && Imm <= AMDGPU::EncValues::INLINE_FLOATING_C_MAX);
1253 
1254   // ToDo: case 248: 1/(2*PI) - is allowed only on VI
1255   // ImmWidth 0 is a default case where operand should not allow immediates.
1256   // Imm value is still decoded into 32 bit immediate operand, inst printer will
1257   // use it to print verbose error message.
1258   switch (ImmWidth) {
1259   case 0:
1260   case 32:
1261     return MCOperand::createImm(getInlineImmVal32(Imm));
1262   case 64:
1263     return MCOperand::createImm(getInlineImmVal64(Imm));
1264   case 16:
1265     return MCOperand::createImm(getInlineImmVal16(Imm));
1266   default:
1267     llvm_unreachable("implement me");
1268   }
1269 }
1270 
1271 unsigned AMDGPUDisassembler::getVgprClassId(const OpWidthTy Width) const {
1272   using namespace AMDGPU;
1273 
1274   assert(OPW_FIRST_ <= Width && Width < OPW_LAST_);
1275   switch (Width) {
1276   default: // fall
1277   case OPW32:
1278   case OPW16:
1279   case OPWV216:
1280     return VGPR_32RegClassID;
1281   case OPW64:
1282   case OPWV232: return VReg_64RegClassID;
1283   case OPW96: return VReg_96RegClassID;
1284   case OPW128: return VReg_128RegClassID;
1285   case OPW160: return VReg_160RegClassID;
1286   case OPW256: return VReg_256RegClassID;
1287   case OPW288: return VReg_288RegClassID;
1288   case OPW320: return VReg_320RegClassID;
1289   case OPW352: return VReg_352RegClassID;
1290   case OPW384: return VReg_384RegClassID;
1291   case OPW512: return VReg_512RegClassID;
1292   case OPW1024: return VReg_1024RegClassID;
1293   }
1294 }
1295 
1296 unsigned AMDGPUDisassembler::getAgprClassId(const OpWidthTy Width) const {
1297   using namespace AMDGPU;
1298 
1299   assert(OPW_FIRST_ <= Width && Width < OPW_LAST_);
1300   switch (Width) {
1301   default: // fall
1302   case OPW32:
1303   case OPW16:
1304   case OPWV216:
1305     return AGPR_32RegClassID;
1306   case OPW64:
1307   case OPWV232: return AReg_64RegClassID;
1308   case OPW96: return AReg_96RegClassID;
1309   case OPW128: return AReg_128RegClassID;
1310   case OPW160: return AReg_160RegClassID;
1311   case OPW256: return AReg_256RegClassID;
1312   case OPW288: return AReg_288RegClassID;
1313   case OPW320: return AReg_320RegClassID;
1314   case OPW352: return AReg_352RegClassID;
1315   case OPW384: return AReg_384RegClassID;
1316   case OPW512: return AReg_512RegClassID;
1317   case OPW1024: return AReg_1024RegClassID;
1318   }
1319 }
1320 
1321 
1322 unsigned AMDGPUDisassembler::getSgprClassId(const OpWidthTy Width) const {
1323   using namespace AMDGPU;
1324 
1325   assert(OPW_FIRST_ <= Width && Width < OPW_LAST_);
1326   switch (Width) {
1327   default: // fall
1328   case OPW32:
1329   case OPW16:
1330   case OPWV216:
1331     return SGPR_32RegClassID;
1332   case OPW64:
1333   case OPWV232: return SGPR_64RegClassID;
1334   case OPW96: return SGPR_96RegClassID;
1335   case OPW128: return SGPR_128RegClassID;
1336   case OPW160: return SGPR_160RegClassID;
1337   case OPW256: return SGPR_256RegClassID;
1338   case OPW288: return SGPR_288RegClassID;
1339   case OPW320: return SGPR_320RegClassID;
1340   case OPW352: return SGPR_352RegClassID;
1341   case OPW384: return SGPR_384RegClassID;
1342   case OPW512: return SGPR_512RegClassID;
1343   }
1344 }
1345 
1346 unsigned AMDGPUDisassembler::getTtmpClassId(const OpWidthTy Width) const {
1347   using namespace AMDGPU;
1348 
1349   assert(OPW_FIRST_ <= Width && Width < OPW_LAST_);
1350   switch (Width) {
1351   default: // fall
1352   case OPW32:
1353   case OPW16:
1354   case OPWV216:
1355     return TTMP_32RegClassID;
1356   case OPW64:
1357   case OPWV232: return TTMP_64RegClassID;
1358   case OPW128: return TTMP_128RegClassID;
1359   case OPW256: return TTMP_256RegClassID;
1360   case OPW288: return TTMP_288RegClassID;
1361   case OPW320: return TTMP_320RegClassID;
1362   case OPW352: return TTMP_352RegClassID;
1363   case OPW384: return TTMP_384RegClassID;
1364   case OPW512: return TTMP_512RegClassID;
1365   }
1366 }
1367 
1368 int AMDGPUDisassembler::getTTmpIdx(unsigned Val) const {
1369   using namespace AMDGPU::EncValues;
1370 
1371   unsigned TTmpMin = isGFX9Plus() ? TTMP_GFX9PLUS_MIN : TTMP_VI_MIN;
1372   unsigned TTmpMax = isGFX9Plus() ? TTMP_GFX9PLUS_MAX : TTMP_VI_MAX;
1373 
1374   return (TTmpMin <= Val && Val <= TTmpMax)? Val - TTmpMin : -1;
1375 }
1376 
1377 MCOperand AMDGPUDisassembler::decodeSrcOp(const OpWidthTy Width, unsigned Val,
1378                                           bool MandatoryLiteral,
1379                                           unsigned ImmWidth) const {
1380   using namespace AMDGPU::EncValues;
1381 
1382   assert(Val < 1024); // enum10
1383 
1384   bool IsAGPR = Val & 512;
1385   Val &= 511;
1386 
1387   if (VGPR_MIN <= Val && Val <= VGPR_MAX) {
1388     return createRegOperand(IsAGPR ? getAgprClassId(Width)
1389                                    : getVgprClassId(Width), Val - VGPR_MIN);
1390   }
1391   if (Val <= SGPR_MAX) {
1392     // "SGPR_MIN <= Val" is always true and causes compilation warning.
1393     static_assert(SGPR_MIN == 0);
1394     return createSRegOperand(getSgprClassId(Width), Val - SGPR_MIN);
1395   }
1396 
1397   int TTmpIdx = getTTmpIdx(Val);
1398   if (TTmpIdx >= 0) {
1399     return createSRegOperand(getTtmpClassId(Width), TTmpIdx);
1400   }
1401 
1402   if (INLINE_INTEGER_C_MIN <= Val && Val <= INLINE_INTEGER_C_MAX)
1403     return decodeIntImmed(Val);
1404 
1405   if (INLINE_FLOATING_C_MIN <= Val && Val <= INLINE_FLOATING_C_MAX)
1406     return decodeFPImmed(ImmWidth, Val);
1407 
1408   if (Val == LITERAL_CONST) {
1409     if (MandatoryLiteral)
1410       // Keep a sentinel value for deferred setting
1411       return MCOperand::createImm(LITERAL_CONST);
1412     else
1413       return decodeLiteralConstant();
1414   }
1415 
1416   switch (Width) {
1417   case OPW32:
1418   case OPW16:
1419   case OPWV216:
1420     return decodeSpecialReg32(Val);
1421   case OPW64:
1422   case OPWV232:
1423     return decodeSpecialReg64(Val);
1424   default:
1425     llvm_unreachable("unexpected immediate type");
1426   }
1427 }
1428 
1429 // Bit 0 of DstY isn't stored in the instruction, because it's always the
1430 // opposite of bit 0 of DstX.
1431 MCOperand AMDGPUDisassembler::decodeVOPDDstYOp(MCInst &Inst,
1432                                                unsigned Val) const {
1433   int VDstXInd =
1434       AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::vdstX);
1435   assert(VDstXInd != -1);
1436   assert(Inst.getOperand(VDstXInd).isReg());
1437   unsigned XDstReg = MRI.getEncodingValue(Inst.getOperand(VDstXInd).getReg());
1438   Val |= ~XDstReg & 1;
1439   auto Width = llvm::AMDGPUDisassembler::OPW32;
1440   return createRegOperand(getVgprClassId(Width), Val);
1441 }
1442 
1443 MCOperand AMDGPUDisassembler::decodeSpecialReg32(unsigned Val) const {
1444   using namespace AMDGPU;
1445 
1446   switch (Val) {
1447   // clang-format off
1448   case 102: return createRegOperand(FLAT_SCR_LO);
1449   case 103: return createRegOperand(FLAT_SCR_HI);
1450   case 104: return createRegOperand(XNACK_MASK_LO);
1451   case 105: return createRegOperand(XNACK_MASK_HI);
1452   case 106: return createRegOperand(VCC_LO);
1453   case 107: return createRegOperand(VCC_HI);
1454   case 108: return createRegOperand(TBA_LO);
1455   case 109: return createRegOperand(TBA_HI);
1456   case 110: return createRegOperand(TMA_LO);
1457   case 111: return createRegOperand(TMA_HI);
1458   case 124:
1459     return isGFX11Plus() ? createRegOperand(SGPR_NULL) : createRegOperand(M0);
1460   case 125:
1461     return isGFX11Plus() ? createRegOperand(M0) : createRegOperand(SGPR_NULL);
1462   case 126: return createRegOperand(EXEC_LO);
1463   case 127: return createRegOperand(EXEC_HI);
1464   case 235: return createRegOperand(SRC_SHARED_BASE_LO);
1465   case 236: return createRegOperand(SRC_SHARED_LIMIT_LO);
1466   case 237: return createRegOperand(SRC_PRIVATE_BASE_LO);
1467   case 238: return createRegOperand(SRC_PRIVATE_LIMIT_LO);
1468   case 239: return createRegOperand(SRC_POPS_EXITING_WAVE_ID);
1469   case 251: return createRegOperand(SRC_VCCZ);
1470   case 252: return createRegOperand(SRC_EXECZ);
1471   case 253: return createRegOperand(SRC_SCC);
1472   case 254: return createRegOperand(LDS_DIRECT);
1473   default: break;
1474     // clang-format on
1475   }
1476   return errOperand(Val, "unknown operand encoding " + Twine(Val));
1477 }
1478 
1479 MCOperand AMDGPUDisassembler::decodeSpecialReg64(unsigned Val) const {
1480   using namespace AMDGPU;
1481 
1482   switch (Val) {
1483   case 102: return createRegOperand(FLAT_SCR);
1484   case 104: return createRegOperand(XNACK_MASK);
1485   case 106: return createRegOperand(VCC);
1486   case 108: return createRegOperand(TBA);
1487   case 110: return createRegOperand(TMA);
1488   case 124:
1489     if (isGFX11Plus())
1490       return createRegOperand(SGPR_NULL);
1491     break;
1492   case 125:
1493     if (!isGFX11Plus())
1494       return createRegOperand(SGPR_NULL);
1495     break;
1496   case 126: return createRegOperand(EXEC);
1497   case 235: return createRegOperand(SRC_SHARED_BASE);
1498   case 236: return createRegOperand(SRC_SHARED_LIMIT);
1499   case 237: return createRegOperand(SRC_PRIVATE_BASE);
1500   case 238: return createRegOperand(SRC_PRIVATE_LIMIT);
1501   case 239: return createRegOperand(SRC_POPS_EXITING_WAVE_ID);
1502   case 251: return createRegOperand(SRC_VCCZ);
1503   case 252: return createRegOperand(SRC_EXECZ);
1504   case 253: return createRegOperand(SRC_SCC);
1505   default: break;
1506   }
1507   return errOperand(Val, "unknown operand encoding " + Twine(Val));
1508 }
1509 
1510 MCOperand AMDGPUDisassembler::decodeSDWASrc(const OpWidthTy Width,
1511                                             const unsigned Val,
1512                                             unsigned ImmWidth) const {
1513   using namespace AMDGPU::SDWA;
1514   using namespace AMDGPU::EncValues;
1515 
1516   if (STI.hasFeature(AMDGPU::FeatureGFX9) ||
1517       STI.hasFeature(AMDGPU::FeatureGFX10)) {
1518     // XXX: cast to int is needed to avoid stupid warning:
1519     // compare with unsigned is always true
1520     if (int(SDWA9EncValues::SRC_VGPR_MIN) <= int(Val) &&
1521         Val <= SDWA9EncValues::SRC_VGPR_MAX) {
1522       return createRegOperand(getVgprClassId(Width),
1523                               Val - SDWA9EncValues::SRC_VGPR_MIN);
1524     }
1525     if (SDWA9EncValues::SRC_SGPR_MIN <= Val &&
1526         Val <= (isGFX10Plus() ? SDWA9EncValues::SRC_SGPR_MAX_GFX10
1527                               : SDWA9EncValues::SRC_SGPR_MAX_SI)) {
1528       return createSRegOperand(getSgprClassId(Width),
1529                                Val - SDWA9EncValues::SRC_SGPR_MIN);
1530     }
1531     if (SDWA9EncValues::SRC_TTMP_MIN <= Val &&
1532         Val <= SDWA9EncValues::SRC_TTMP_MAX) {
1533       return createSRegOperand(getTtmpClassId(Width),
1534                                Val - SDWA9EncValues::SRC_TTMP_MIN);
1535     }
1536 
1537     const unsigned SVal = Val - SDWA9EncValues::SRC_SGPR_MIN;
1538 
1539     if (INLINE_INTEGER_C_MIN <= SVal && SVal <= INLINE_INTEGER_C_MAX)
1540       return decodeIntImmed(SVal);
1541 
1542     if (INLINE_FLOATING_C_MIN <= SVal && SVal <= INLINE_FLOATING_C_MAX)
1543       return decodeFPImmed(ImmWidth, SVal);
1544 
1545     return decodeSpecialReg32(SVal);
1546   } else if (STI.hasFeature(AMDGPU::FeatureVolcanicIslands)) {
1547     return createRegOperand(getVgprClassId(Width), Val);
1548   }
1549   llvm_unreachable("unsupported target");
1550 }
1551 
1552 MCOperand AMDGPUDisassembler::decodeSDWASrc16(unsigned Val) const {
1553   return decodeSDWASrc(OPW16, Val, 16);
1554 }
1555 
1556 MCOperand AMDGPUDisassembler::decodeSDWASrc32(unsigned Val) const {
1557   return decodeSDWASrc(OPW32, Val, 32);
1558 }
1559 
1560 MCOperand AMDGPUDisassembler::decodeSDWAVopcDst(unsigned Val) const {
1561   using namespace AMDGPU::SDWA;
1562 
1563   assert((STI.hasFeature(AMDGPU::FeatureGFX9) ||
1564           STI.hasFeature(AMDGPU::FeatureGFX10)) &&
1565          "SDWAVopcDst should be present only on GFX9+");
1566 
1567   bool IsWave64 = STI.hasFeature(AMDGPU::FeatureWavefrontSize64);
1568 
1569   if (Val & SDWA9EncValues::VOPC_DST_VCC_MASK) {
1570     Val &= SDWA9EncValues::VOPC_DST_SGPR_MASK;
1571 
1572     int TTmpIdx = getTTmpIdx(Val);
1573     if (TTmpIdx >= 0) {
1574       auto TTmpClsId = getTtmpClassId(IsWave64 ? OPW64 : OPW32);
1575       return createSRegOperand(TTmpClsId, TTmpIdx);
1576     } else if (Val > SGPR_MAX) {
1577       return IsWave64 ? decodeSpecialReg64(Val)
1578                       : decodeSpecialReg32(Val);
1579     } else {
1580       return createSRegOperand(getSgprClassId(IsWave64 ? OPW64 : OPW32), Val);
1581     }
1582   } else {
1583     return createRegOperand(IsWave64 ? AMDGPU::VCC : AMDGPU::VCC_LO);
1584   }
1585 }
1586 
1587 MCOperand AMDGPUDisassembler::decodeBoolReg(unsigned Val) const {
1588   return STI.hasFeature(AMDGPU::FeatureWavefrontSize64)
1589              ? decodeSrcOp(OPW64, Val)
1590              : decodeSrcOp(OPW32, Val);
1591 }
1592 
1593 bool AMDGPUDisassembler::isVI() const {
1594   return STI.hasFeature(AMDGPU::FeatureVolcanicIslands);
1595 }
1596 
1597 bool AMDGPUDisassembler::isGFX9() const { return AMDGPU::isGFX9(STI); }
1598 
1599 bool AMDGPUDisassembler::isGFX90A() const {
1600   return STI.hasFeature(AMDGPU::FeatureGFX90AInsts);
1601 }
1602 
1603 bool AMDGPUDisassembler::isGFX9Plus() const { return AMDGPU::isGFX9Plus(STI); }
1604 
1605 bool AMDGPUDisassembler::isGFX10() const { return AMDGPU::isGFX10(STI); }
1606 
1607 bool AMDGPUDisassembler::isGFX10Plus() const {
1608   return AMDGPU::isGFX10Plus(STI);
1609 }
1610 
1611 bool AMDGPUDisassembler::isGFX11() const {
1612   return STI.hasFeature(AMDGPU::FeatureGFX11);
1613 }
1614 
1615 bool AMDGPUDisassembler::isGFX11Plus() const {
1616   return AMDGPU::isGFX11Plus(STI);
1617 }
1618 
1619 
1620 bool AMDGPUDisassembler::hasArchitectedFlatScratch() const {
1621   return STI.hasFeature(AMDGPU::FeatureArchitectedFlatScratch);
1622 }
1623 
1624 //===----------------------------------------------------------------------===//
1625 // AMDGPU specific symbol handling
1626 //===----------------------------------------------------------------------===//
1627 #define GET_FIELD(MASK) (AMDHSA_BITS_GET(FourByteBuffer, MASK))
1628 #define PRINT_DIRECTIVE(DIRECTIVE, MASK)                                       \
1629   do {                                                                         \
1630     KdStream << Indent << DIRECTIVE " " << GET_FIELD(MASK) << '\n';            \
1631   } while (0)
1632 #define PRINT_PSEUDO_DIRECTIVE_COMMENT(DIRECTIVE, MASK)                        \
1633   do {                                                                         \
1634     KdStream << Indent << MAI.getCommentString() << ' ' << DIRECTIVE " "       \
1635              << GET_FIELD(MASK) << '\n';                                       \
1636   } while (0)
1637 
1638 // NOLINTNEXTLINE(readability-identifier-naming)
1639 MCDisassembler::DecodeStatus AMDGPUDisassembler::decodeCOMPUTE_PGM_RSRC1(
1640     uint32_t FourByteBuffer, raw_string_ostream &KdStream) const {
1641   using namespace amdhsa;
1642   StringRef Indent = "\t";
1643 
1644   // We cannot accurately backward compute #VGPRs used from
1645   // GRANULATED_WORKITEM_VGPR_COUNT. But we are concerned with getting the same
1646   // value of GRANULATED_WORKITEM_VGPR_COUNT in the reassembled binary. So we
1647   // simply calculate the inverse of what the assembler does.
1648 
1649   uint32_t GranulatedWorkitemVGPRCount =
1650       GET_FIELD(COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT);
1651 
1652   uint32_t NextFreeVGPR =
1653       (GranulatedWorkitemVGPRCount + 1) *
1654       AMDGPU::IsaInfo::getVGPREncodingGranule(&STI, EnableWavefrontSize32);
1655 
1656   KdStream << Indent << ".amdhsa_next_free_vgpr " << NextFreeVGPR << '\n';
1657 
1658   // We cannot backward compute values used to calculate
1659   // GRANULATED_WAVEFRONT_SGPR_COUNT. Hence the original values for following
1660   // directives can't be computed:
1661   // .amdhsa_reserve_vcc
1662   // .amdhsa_reserve_flat_scratch
1663   // .amdhsa_reserve_xnack_mask
1664   // They take their respective default values if not specified in the assembly.
1665   //
1666   // GRANULATED_WAVEFRONT_SGPR_COUNT
1667   //    = f(NEXT_FREE_SGPR + VCC + FLAT_SCRATCH + XNACK_MASK)
1668   //
1669   // We compute the inverse as though all directives apart from NEXT_FREE_SGPR
1670   // are set to 0. So while disassembling we consider that:
1671   //
1672   // GRANULATED_WAVEFRONT_SGPR_COUNT
1673   //    = f(NEXT_FREE_SGPR + 0 + 0 + 0)
1674   //
1675   // The disassembler cannot recover the original values of those 3 directives.
1676 
1677   uint32_t GranulatedWavefrontSGPRCount =
1678       GET_FIELD(COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT);
1679 
1680   if (isGFX10Plus() && GranulatedWavefrontSGPRCount)
1681     return MCDisassembler::Fail;
1682 
1683   uint32_t NextFreeSGPR = (GranulatedWavefrontSGPRCount + 1) *
1684                           AMDGPU::IsaInfo::getSGPREncodingGranule(&STI);
1685 
1686   KdStream << Indent << ".amdhsa_reserve_vcc " << 0 << '\n';
1687   if (!hasArchitectedFlatScratch())
1688     KdStream << Indent << ".amdhsa_reserve_flat_scratch " << 0 << '\n';
1689   KdStream << Indent << ".amdhsa_reserve_xnack_mask " << 0 << '\n';
1690   KdStream << Indent << ".amdhsa_next_free_sgpr " << NextFreeSGPR << "\n";
1691 
1692   if (FourByteBuffer & COMPUTE_PGM_RSRC1_PRIORITY)
1693     return MCDisassembler::Fail;
1694 
1695   PRINT_DIRECTIVE(".amdhsa_float_round_mode_32",
1696                   COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_32);
1697   PRINT_DIRECTIVE(".amdhsa_float_round_mode_16_64",
1698                   COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_16_64);
1699   PRINT_DIRECTIVE(".amdhsa_float_denorm_mode_32",
1700                   COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_32);
1701   PRINT_DIRECTIVE(".amdhsa_float_denorm_mode_16_64",
1702                   COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_16_64);
1703 
1704   if (FourByteBuffer & COMPUTE_PGM_RSRC1_PRIV)
1705     return MCDisassembler::Fail;
1706 
1707   PRINT_DIRECTIVE(".amdhsa_dx10_clamp", COMPUTE_PGM_RSRC1_ENABLE_DX10_CLAMP);
1708 
1709   if (FourByteBuffer & COMPUTE_PGM_RSRC1_DEBUG_MODE)
1710     return MCDisassembler::Fail;
1711 
1712   PRINT_DIRECTIVE(".amdhsa_ieee_mode", COMPUTE_PGM_RSRC1_ENABLE_IEEE_MODE);
1713 
1714   if (FourByteBuffer & COMPUTE_PGM_RSRC1_BULKY)
1715     return MCDisassembler::Fail;
1716 
1717   if (FourByteBuffer & COMPUTE_PGM_RSRC1_CDBG_USER)
1718     return MCDisassembler::Fail;
1719 
1720   PRINT_DIRECTIVE(".amdhsa_fp16_overflow", COMPUTE_PGM_RSRC1_FP16_OVFL);
1721 
1722   if (FourByteBuffer & COMPUTE_PGM_RSRC1_RESERVED0)
1723     return MCDisassembler::Fail;
1724 
1725   if (isGFX10Plus()) {
1726     PRINT_DIRECTIVE(".amdhsa_workgroup_processor_mode",
1727                     COMPUTE_PGM_RSRC1_WGP_MODE);
1728     PRINT_DIRECTIVE(".amdhsa_memory_ordered", COMPUTE_PGM_RSRC1_MEM_ORDERED);
1729     PRINT_DIRECTIVE(".amdhsa_forward_progress", COMPUTE_PGM_RSRC1_FWD_PROGRESS);
1730   }
1731   return MCDisassembler::Success;
1732 }
1733 
1734 // NOLINTNEXTLINE(readability-identifier-naming)
1735 MCDisassembler::DecodeStatus AMDGPUDisassembler::decodeCOMPUTE_PGM_RSRC2(
1736     uint32_t FourByteBuffer, raw_string_ostream &KdStream) const {
1737   using namespace amdhsa;
1738   StringRef Indent = "\t";
1739   if (hasArchitectedFlatScratch())
1740     PRINT_DIRECTIVE(".amdhsa_enable_private_segment",
1741                     COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT);
1742   else
1743     PRINT_DIRECTIVE(".amdhsa_system_sgpr_private_segment_wavefront_offset",
1744                     COMPUTE_PGM_RSRC2_ENABLE_PRIVATE_SEGMENT);
1745   PRINT_DIRECTIVE(".amdhsa_system_sgpr_workgroup_id_x",
1746                   COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_X);
1747   PRINT_DIRECTIVE(".amdhsa_system_sgpr_workgroup_id_y",
1748                   COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Y);
1749   PRINT_DIRECTIVE(".amdhsa_system_sgpr_workgroup_id_z",
1750                   COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Z);
1751   PRINT_DIRECTIVE(".amdhsa_system_sgpr_workgroup_info",
1752                   COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_INFO);
1753   PRINT_DIRECTIVE(".amdhsa_system_vgpr_workitem_id",
1754                   COMPUTE_PGM_RSRC2_ENABLE_VGPR_WORKITEM_ID);
1755 
1756   if (FourByteBuffer & COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_ADDRESS_WATCH)
1757     return MCDisassembler::Fail;
1758 
1759   if (FourByteBuffer & COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_MEMORY)
1760     return MCDisassembler::Fail;
1761 
1762   if (FourByteBuffer & COMPUTE_PGM_RSRC2_GRANULATED_LDS_SIZE)
1763     return MCDisassembler::Fail;
1764 
1765   PRINT_DIRECTIVE(
1766       ".amdhsa_exception_fp_ieee_invalid_op",
1767       COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION);
1768   PRINT_DIRECTIVE(".amdhsa_exception_fp_denorm_src",
1769                   COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE);
1770   PRINT_DIRECTIVE(
1771       ".amdhsa_exception_fp_ieee_div_zero",
1772       COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO);
1773   PRINT_DIRECTIVE(".amdhsa_exception_fp_ieee_overflow",
1774                   COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW);
1775   PRINT_DIRECTIVE(".amdhsa_exception_fp_ieee_underflow",
1776                   COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW);
1777   PRINT_DIRECTIVE(".amdhsa_exception_fp_ieee_inexact",
1778                   COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT);
1779   PRINT_DIRECTIVE(".amdhsa_exception_int_div_zero",
1780                   COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_INT_DIVIDE_BY_ZERO);
1781 
1782   if (FourByteBuffer & COMPUTE_PGM_RSRC2_RESERVED0)
1783     return MCDisassembler::Fail;
1784 
1785   return MCDisassembler::Success;
1786 }
1787 
1788 // NOLINTNEXTLINE(readability-identifier-naming)
1789 MCDisassembler::DecodeStatus AMDGPUDisassembler::decodeCOMPUTE_PGM_RSRC3(
1790     uint32_t FourByteBuffer, raw_string_ostream &KdStream) const {
1791   using namespace amdhsa;
1792   StringRef Indent = "\t";
1793   if (isGFX90A()) {
1794     KdStream << Indent << ".amdhsa_accum_offset "
1795              << (GET_FIELD(COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET) + 1) * 4
1796              << '\n';
1797     if (FourByteBuffer & COMPUTE_PGM_RSRC3_GFX90A_RESERVED0)
1798       return MCDisassembler::Fail;
1799     PRINT_DIRECTIVE(".amdhsa_tg_split", COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT);
1800     if (FourByteBuffer & COMPUTE_PGM_RSRC3_GFX90A_RESERVED1)
1801       return MCDisassembler::Fail;
1802   } else if (isGFX10Plus()) {
1803     if (!EnableWavefrontSize32 || !*EnableWavefrontSize32) {
1804       PRINT_DIRECTIVE(".amdhsa_shared_vgpr_count",
1805                       COMPUTE_PGM_RSRC3_GFX10_PLUS_SHARED_VGPR_COUNT);
1806     } else {
1807       PRINT_PSEUDO_DIRECTIVE_COMMENT(
1808           "SHARED_VGPR_COUNT", COMPUTE_PGM_RSRC3_GFX10_PLUS_SHARED_VGPR_COUNT);
1809     }
1810     PRINT_PSEUDO_DIRECTIVE_COMMENT("INST_PREF_SIZE",
1811                                    COMPUTE_PGM_RSRC3_GFX10_PLUS_INST_PREF_SIZE);
1812     PRINT_PSEUDO_DIRECTIVE_COMMENT("TRAP_ON_START",
1813                                    COMPUTE_PGM_RSRC3_GFX10_PLUS_TRAP_ON_START);
1814     PRINT_PSEUDO_DIRECTIVE_COMMENT("TRAP_ON_END",
1815                                    COMPUTE_PGM_RSRC3_GFX10_PLUS_TRAP_ON_END);
1816     if (FourByteBuffer & COMPUTE_PGM_RSRC3_GFX10_PLUS_RESERVED0)
1817       return MCDisassembler::Fail;
1818     PRINT_PSEUDO_DIRECTIVE_COMMENT("IMAGE_OP",
1819                                    COMPUTE_PGM_RSRC3_GFX10_PLUS_TRAP_ON_START);
1820   } else if (FourByteBuffer) {
1821     return MCDisassembler::Fail;
1822   }
1823   return MCDisassembler::Success;
1824 }
1825 #undef PRINT_PSEUDO_DIRECTIVE_COMMENT
1826 #undef PRINT_DIRECTIVE
1827 #undef GET_FIELD
1828 
1829 MCDisassembler::DecodeStatus
1830 AMDGPUDisassembler::decodeKernelDescriptorDirective(
1831     DataExtractor::Cursor &Cursor, ArrayRef<uint8_t> Bytes,
1832     raw_string_ostream &KdStream) const {
1833 #define PRINT_DIRECTIVE(DIRECTIVE, MASK)                                       \
1834   do {                                                                         \
1835     KdStream << Indent << DIRECTIVE " "                                        \
1836              << ((TwoByteBuffer & MASK) >> (MASK##_SHIFT)) << '\n';            \
1837   } while (0)
1838 
1839   uint16_t TwoByteBuffer = 0;
1840   uint32_t FourByteBuffer = 0;
1841 
1842   StringRef ReservedBytes;
1843   StringRef Indent = "\t";
1844 
1845   assert(Bytes.size() == 64);
1846   DataExtractor DE(Bytes, /*IsLittleEndian=*/true, /*AddressSize=*/8);
1847 
1848   switch (Cursor.tell()) {
1849   case amdhsa::GROUP_SEGMENT_FIXED_SIZE_OFFSET:
1850     FourByteBuffer = DE.getU32(Cursor);
1851     KdStream << Indent << ".amdhsa_group_segment_fixed_size " << FourByteBuffer
1852              << '\n';
1853     return MCDisassembler::Success;
1854 
1855   case amdhsa::PRIVATE_SEGMENT_FIXED_SIZE_OFFSET:
1856     FourByteBuffer = DE.getU32(Cursor);
1857     KdStream << Indent << ".amdhsa_private_segment_fixed_size "
1858              << FourByteBuffer << '\n';
1859     return MCDisassembler::Success;
1860 
1861   case amdhsa::KERNARG_SIZE_OFFSET:
1862     FourByteBuffer = DE.getU32(Cursor);
1863     KdStream << Indent << ".amdhsa_kernarg_size "
1864              << FourByteBuffer << '\n';
1865     return MCDisassembler::Success;
1866 
1867   case amdhsa::RESERVED0_OFFSET:
1868     // 4 reserved bytes, must be 0.
1869     ReservedBytes = DE.getBytes(Cursor, 4);
1870     for (int I = 0; I < 4; ++I) {
1871       if (ReservedBytes[I] != 0) {
1872         return MCDisassembler::Fail;
1873       }
1874     }
1875     return MCDisassembler::Success;
1876 
1877   case amdhsa::KERNEL_CODE_ENTRY_BYTE_OFFSET_OFFSET:
1878     // KERNEL_CODE_ENTRY_BYTE_OFFSET
1879     // So far no directive controls this for Code Object V3, so simply skip for
1880     // disassembly.
1881     DE.skip(Cursor, 8);
1882     return MCDisassembler::Success;
1883 
1884   case amdhsa::RESERVED1_OFFSET:
1885     // 20 reserved bytes, must be 0.
1886     ReservedBytes = DE.getBytes(Cursor, 20);
1887     for (int I = 0; I < 20; ++I) {
1888       if (ReservedBytes[I] != 0) {
1889         return MCDisassembler::Fail;
1890       }
1891     }
1892     return MCDisassembler::Success;
1893 
1894   case amdhsa::COMPUTE_PGM_RSRC3_OFFSET:
1895     FourByteBuffer = DE.getU32(Cursor);
1896     return decodeCOMPUTE_PGM_RSRC3(FourByteBuffer, KdStream);
1897 
1898   case amdhsa::COMPUTE_PGM_RSRC1_OFFSET:
1899     FourByteBuffer = DE.getU32(Cursor);
1900     return decodeCOMPUTE_PGM_RSRC1(FourByteBuffer, KdStream);
1901 
1902   case amdhsa::COMPUTE_PGM_RSRC2_OFFSET:
1903     FourByteBuffer = DE.getU32(Cursor);
1904     return decodeCOMPUTE_PGM_RSRC2(FourByteBuffer, KdStream);
1905 
1906   case amdhsa::KERNEL_CODE_PROPERTIES_OFFSET:
1907     using namespace amdhsa;
1908     TwoByteBuffer = DE.getU16(Cursor);
1909 
1910     if (!hasArchitectedFlatScratch())
1911       PRINT_DIRECTIVE(".amdhsa_user_sgpr_private_segment_buffer",
1912                       KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER);
1913     PRINT_DIRECTIVE(".amdhsa_user_sgpr_dispatch_ptr",
1914                     KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR);
1915     PRINT_DIRECTIVE(".amdhsa_user_sgpr_queue_ptr",
1916                     KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR);
1917     PRINT_DIRECTIVE(".amdhsa_user_sgpr_kernarg_segment_ptr",
1918                     KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR);
1919     PRINT_DIRECTIVE(".amdhsa_user_sgpr_dispatch_id",
1920                     KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID);
1921     if (!hasArchitectedFlatScratch())
1922       PRINT_DIRECTIVE(".amdhsa_user_sgpr_flat_scratch_init",
1923                       KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT);
1924     PRINT_DIRECTIVE(".amdhsa_user_sgpr_private_segment_size",
1925                     KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE);
1926 
1927     if (TwoByteBuffer & KERNEL_CODE_PROPERTY_RESERVED0)
1928       return MCDisassembler::Fail;
1929 
1930     // Reserved for GFX9
1931     if (isGFX9() &&
1932         (TwoByteBuffer & KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32)) {
1933       return MCDisassembler::Fail;
1934     } else if (isGFX10Plus()) {
1935       PRINT_DIRECTIVE(".amdhsa_wavefront_size32",
1936                       KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32);
1937     }
1938 
1939     if (AMDGPU::getAmdhsaCodeObjectVersion() >= AMDGPU::AMDHSA_COV5)
1940       PRINT_DIRECTIVE(".amdhsa_uses_dynamic_stack",
1941                       KERNEL_CODE_PROPERTY_USES_DYNAMIC_STACK);
1942 
1943     if (TwoByteBuffer & KERNEL_CODE_PROPERTY_RESERVED1)
1944       return MCDisassembler::Fail;
1945 
1946     return MCDisassembler::Success;
1947 
1948   case amdhsa::RESERVED2_OFFSET:
1949     // 6 bytes from here are reserved, must be 0.
1950     ReservedBytes = DE.getBytes(Cursor, 6);
1951     for (int I = 0; I < 6; ++I) {
1952       if (ReservedBytes[I] != 0)
1953         return MCDisassembler::Fail;
1954     }
1955     return MCDisassembler::Success;
1956 
1957   default:
1958     llvm_unreachable("Unhandled index. Case statements cover everything.");
1959     return MCDisassembler::Fail;
1960   }
1961 #undef PRINT_DIRECTIVE
1962 }
1963 
1964 MCDisassembler::DecodeStatus AMDGPUDisassembler::decodeKernelDescriptor(
1965     StringRef KdName, ArrayRef<uint8_t> Bytes, uint64_t KdAddress) const {
1966   // CP microcode requires the kernel descriptor to be 64 aligned.
1967   if (Bytes.size() != 64 || KdAddress % 64 != 0)
1968     return MCDisassembler::Fail;
1969 
1970   // FIXME: We can't actually decode "in order" as is done below, as e.g. GFX10
1971   // requires us to know the setting of .amdhsa_wavefront_size32 in order to
1972   // accurately produce .amdhsa_next_free_vgpr, and they appear in the wrong
1973   // order. Workaround this by first looking up .amdhsa_wavefront_size32 here
1974   // when required.
1975   if (isGFX10Plus()) {
1976     uint16_t KernelCodeProperties =
1977         support::endian::read16(&Bytes[amdhsa::KERNEL_CODE_PROPERTIES_OFFSET],
1978                                 support::endianness::little);
1979     EnableWavefrontSize32 =
1980         AMDHSA_BITS_GET(KernelCodeProperties,
1981                         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32);
1982   }
1983 
1984   std::string Kd;
1985   raw_string_ostream KdStream(Kd);
1986   KdStream << ".amdhsa_kernel " << KdName << '\n';
1987 
1988   DataExtractor::Cursor C(0);
1989   while (C && C.tell() < Bytes.size()) {
1990     MCDisassembler::DecodeStatus Status =
1991         decodeKernelDescriptorDirective(C, Bytes, KdStream);
1992 
1993     cantFail(C.takeError());
1994 
1995     if (Status == MCDisassembler::Fail)
1996       return MCDisassembler::Fail;
1997   }
1998   KdStream << ".end_amdhsa_kernel\n";
1999   outs() << KdStream.str();
2000   return MCDisassembler::Success;
2001 }
2002 
2003 std::optional<MCDisassembler::DecodeStatus>
2004 AMDGPUDisassembler::onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size,
2005                                   ArrayRef<uint8_t> Bytes, uint64_t Address,
2006                                   raw_ostream &CStream) const {
2007   // Right now only kernel descriptor needs to be handled.
2008   // We ignore all other symbols for target specific handling.
2009   // TODO:
2010   // Fix the spurious symbol issue for AMDGPU kernels. Exists for both Code
2011   // Object V2 and V3 when symbols are marked protected.
2012 
2013   // amd_kernel_code_t for Code Object V2.
2014   if (Symbol.Type == ELF::STT_AMDGPU_HSA_KERNEL) {
2015     Size = 256;
2016     return MCDisassembler::Fail;
2017   }
2018 
2019   // Code Object V3 kernel descriptors.
2020   StringRef Name = Symbol.Name;
2021   if (Symbol.Type == ELF::STT_OBJECT && Name.endswith(StringRef(".kd"))) {
2022     Size = 64; // Size = 64 regardless of success or failure.
2023     return decodeKernelDescriptor(Name.drop_back(3), Bytes, Address);
2024   }
2025   return std::nullopt;
2026 }
2027 
2028 //===----------------------------------------------------------------------===//
2029 // AMDGPUSymbolizer
2030 //===----------------------------------------------------------------------===//
2031 
2032 // Try to find symbol name for specified label
2033 bool AMDGPUSymbolizer::tryAddingSymbolicOperand(
2034     MCInst &Inst, raw_ostream & /*cStream*/, int64_t Value,
2035     uint64_t /*Address*/, bool IsBranch, uint64_t /*Offset*/,
2036     uint64_t /*OpSize*/, uint64_t /*InstSize*/) {
2037 
2038   if (!IsBranch) {
2039     return false;
2040   }
2041 
2042   auto *Symbols = static_cast<SectionSymbolsTy *>(DisInfo);
2043   if (!Symbols)
2044     return false;
2045 
2046   auto Result = llvm::find_if(*Symbols, [Value](const SymbolInfoTy &Val) {
2047     return Val.Addr == static_cast<uint64_t>(Value) &&
2048            Val.Type == ELF::STT_NOTYPE;
2049   });
2050   if (Result != Symbols->end()) {
2051     auto *Sym = Ctx.getOrCreateSymbol(Result->Name);
2052     const auto *Add = MCSymbolRefExpr::create(Sym, Ctx);
2053     Inst.addOperand(MCOperand::createExpr(Add));
2054     return true;
2055   }
2056   // Add to list of referenced addresses, so caller can synthesize a label.
2057   ReferencedAddresses.push_back(static_cast<uint64_t>(Value));
2058   return false;
2059 }
2060 
2061 void AMDGPUSymbolizer::tryAddingPcLoadReferenceComment(raw_ostream &cStream,
2062                                                        int64_t Value,
2063                                                        uint64_t Address) {
2064   llvm_unreachable("unimplemented");
2065 }
2066 
2067 //===----------------------------------------------------------------------===//
2068 // Initialization
2069 //===----------------------------------------------------------------------===//
2070 
2071 static MCSymbolizer *createAMDGPUSymbolizer(const Triple &/*TT*/,
2072                               LLVMOpInfoCallback /*GetOpInfo*/,
2073                               LLVMSymbolLookupCallback /*SymbolLookUp*/,
2074                               void *DisInfo,
2075                               MCContext *Ctx,
2076                               std::unique_ptr<MCRelocationInfo> &&RelInfo) {
2077   return new AMDGPUSymbolizer(*Ctx, std::move(RelInfo), DisInfo);
2078 }
2079 
2080 static MCDisassembler *createAMDGPUDisassembler(const Target &T,
2081                                                 const MCSubtargetInfo &STI,
2082                                                 MCContext &Ctx) {
2083   return new AMDGPUDisassembler(STI, Ctx, T.createMCInstrInfo());
2084 }
2085 
2086 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUDisassembler() {
2087   TargetRegistry::RegisterMCDisassembler(getTheGCNTarget(),
2088                                          createAMDGPUDisassembler);
2089   TargetRegistry::RegisterMCSymbolizer(getTheGCNTarget(),
2090                                        createAMDGPUSymbolizer);
2091 }
2092