LLVM 23.0.0git
SPIRVInstPrinter.cpp
Go to the documentation of this file.
1//===-- SPIRVInstPrinter.cpp - Output SPIR-V MCInsts as ASM -----*- C++ -*-===//
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// This class prints a SPIR-V MCInst to a .s file.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SPIRVInstPrinter.h"
14#include "SPIRV.h"
15#include "SPIRVBaseInfo.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCSymbol.h"
23
24using namespace llvm;
25using namespace llvm::SPIRV;
26
27#define DEBUG_TYPE "asm-printer"
28
29// Include the auto-generated portion of the assembly writer.
30#include "SPIRVGenAsmWriter.inc"
31
33 unsigned StartIndex,
34 raw_ostream &O,
35 bool SkipFirstSpace,
36 bool SkipImmediates) {
37 const unsigned NumOps = MI->getNumOperands();
38 for (unsigned i = StartIndex; i < NumOps; ++i) {
39 if (!SkipImmediates || !MI->getOperand(i).isImm()) {
40 if (!SkipFirstSpace || i != StartIndex)
41 O << ' ';
42 printOperand(MI, i, O);
43 }
44 }
45}
46
48 unsigned StartIndex,
49 raw_ostream &O) {
50 unsigned IsBitwidth16 = MI->getFlags() & SPIRV::INST_PRINTER_WIDTH16;
51 const unsigned NumVarOps = MI->getNumOperands() - StartIndex;
52
53 if (MI->getOpcode() == SPIRV::OpConstantI && NumVarOps > 2) {
54 // SPV_ALTERA_arbitrary_precision_integers allows for integer widths greater
55 // than 64, which will be encoded via multiple operands.
56 for (unsigned I = StartIndex; I != MI->getNumOperands(); ++I)
57 O << ' ' << MI->getOperand(I).getImm();
58 return;
59 }
60
61 assert((NumVarOps == 1 || NumVarOps == 2) &&
62 "Unsupported number of bits for literal variable");
63
64 O << ' ';
65
66 uint64_t Imm = MI->getOperand(StartIndex).getImm();
67
68 // Handle 64 bit literals.
69 if (NumVarOps == 2) {
70 Imm |= (MI->getOperand(StartIndex + 1).getImm() << 32);
71 }
72
73 // Format and print float values.
74 if (MI->getOpcode() == SPIRV::OpConstantF && IsBitwidth16 == 0) {
75 APFloat FP = NumVarOps == 1 ? APFloat(APInt(32, Imm).bitsToFloat())
76 : APFloat(APInt(64, Imm).bitsToDouble());
77
78 // Print infinity and NaN as hex floats.
79 // TODO: Make sure subnormal numbers are handled correctly as they may also
80 // require hex float notation.
81 if (FP.isInfinity()) {
82 if (FP.isNegative())
83 O << '-';
84 O << "0x1p+128";
85 return;
86 }
87 if (FP.isNaN()) {
88 O << "0x1.8p+128";
89 return;
90 }
91
92 // Format val as a decimal floating point or scientific notation (whichever
93 // is shorter), with enough digits of precision to produce the exact value.
94 O << format("%.*g", std::numeric_limits<double>::max_digits10,
95 FP.convertToDouble());
96
97 return;
98 }
99
100 // Print integer values directly.
101 O << Imm;
102}
103
104void SPIRVInstPrinter::recordOpExtInstImport(const MCInst *MI) {
105 MCRegister Reg = MI->getOperand(0).getReg();
106 auto Name = getSPIRVStringOperand(*MI, 1);
107 auto Set = getExtInstSetFromString(std::move(Name));
108 ExtInstSetIDs.insert({Reg, Set});
109}
110
112 StringRef Annot, const MCSubtargetInfo &STI,
113 raw_ostream &OS) {
114 const unsigned OpCode = MI->getOpcode();
116
117 if (OpCode == SPIRV::OpDecorate) {
118 printOpDecorate(MI, OS);
119 } else if (OpCode == SPIRV::OpExtInstImport) {
120 recordOpExtInstImport(MI);
121 } else if (OpCode == SPIRV::OpExtInst) {
122 printOpExtInst(MI, OS);
123 } else if (OpCode == SPIRV::UNKNOWN_type) {
124 printUnknownType(MI, OS);
125 } else {
126 // Print any extra operands for variadic instructions.
127 const MCInstrDesc &MCDesc = MII.get(OpCode);
128 if (MCDesc.isVariadic()) {
129 const unsigned NumFixedOps = MCDesc.getNumOperands();
130 const unsigned LastFixedIndex = NumFixedOps - 1;
131 const int FirstVariableIndex = NumFixedOps;
132 if (NumFixedOps > 0 && MCDesc.operands()[LastFixedIndex].OperandType ==
134 // For instructions where a custom type (not reg or immediate) comes as
135 // the last operand before the variable_ops. This is usually a StringImm
136 // operand, but there are a few other cases.
137 switch (OpCode) {
138 case SPIRV::OpTypeImage:
139 OS << ' ';
141 MI, FirstVariableIndex, OS);
142 break;
143 case SPIRV::OpVariable:
144 OS << ' ';
145 printOperand(MI, FirstVariableIndex, OS);
146 break;
147 case SPIRV::OpEntryPoint: {
148 // Print the interface ID operands, skipping the name's string
149 // literal.
150 printRemainingVariableOps(MI, NumFixedOps, OS, false, true);
151 break;
152 }
153 case SPIRV::OpMemberDecorate:
154 printRemainingVariableOps(MI, NumFixedOps, OS);
155 break;
156 case SPIRV::OpExecutionMode:
157 case SPIRV::OpExecutionModeId:
158 case SPIRV::OpLoopMerge:
159 case SPIRV::OpLoopControlINTEL: {
160 // Print any literals after the OPERAND_UNKNOWN argument normally.
161 printRemainingVariableOps(MI, NumFixedOps, OS);
162 break;
163 }
164 default:
165 break; // printStringImm has already been handled.
166 }
167 } else {
168 // For instructions with no fixed ops or a reg/immediate as the final
169 // fixed operand, we can usually print the rest with "printOperand", but
170 // check for a few cases with custom types first.
171 switch (OpCode) {
172 case SPIRV::OpLoad:
173 case SPIRV::OpStore:
174 OS << ' ';
176 MI, FirstVariableIndex, OS);
177 printRemainingVariableOps(MI, FirstVariableIndex + 1, OS);
178 break;
179 case SPIRV::OpSwitch:
180 if (MI->getFlags() & SPIRV::INST_PRINTER_WIDTH64) {
181 // In binary format 64-bit types are split into two 32-bit operands,
182 // but in text format combine these into a single 64-bit value as
183 // this is what tools such as spirv-as require.
184 const unsigned NumOps = MI->getNumOperands();
185 for (unsigned OpIdx = NumFixedOps; OpIdx < NumOps;) {
186 if (OpIdx + 1 >= NumOps || !MI->getOperand(OpIdx).isImm() ||
187 !MI->getOperand(OpIdx + 1).isImm()) {
188 llvm_unreachable("Unexpected OpSwitch operands");
189 continue;
190 }
191 OS << ' ';
192 uint64_t LowBits = MI->getOperand(OpIdx).getImm();
193 uint64_t HighBits = MI->getOperand(OpIdx + 1).getImm();
194 uint64_t CombinedValue = (HighBits << 32) | LowBits;
195 OS << formatImm(CombinedValue);
196 OpIdx += 2;
197
198 // Next should be the label
199 if (OpIdx < NumOps) {
200 OS << ' ';
201 printOperand(MI, OpIdx, OS);
202 OpIdx++;
203 }
204 }
205 } else {
206 printRemainingVariableOps(MI, NumFixedOps, OS);
207 }
208 break;
209 case SPIRV::OpImageSampleImplicitLod:
210 case SPIRV::OpImageSampleDrefImplicitLod:
211 case SPIRV::OpImageSampleProjImplicitLod:
212 case SPIRV::OpImageSampleProjDrefImplicitLod:
213 case SPIRV::OpImageFetch:
214 case SPIRV::OpImageGather:
215 case SPIRV::OpImageDrefGather:
216 case SPIRV::OpImageRead:
217 case SPIRV::OpImageWrite:
218 case SPIRV::OpImageSparseSampleImplicitLod:
219 case SPIRV::OpImageSparseSampleDrefImplicitLod:
220 case SPIRV::OpImageSparseSampleProjImplicitLod:
221 case SPIRV::OpImageSparseSampleProjDrefImplicitLod:
222 case SPIRV::OpImageSparseFetch:
223 case SPIRV::OpImageSparseGather:
224 case SPIRV::OpImageSparseDrefGather:
225 case SPIRV::OpImageSparseRead:
226 case SPIRV::OpImageSampleFootprintNV:
227 OS << ' ';
229 MI, FirstVariableIndex, OS);
230 printRemainingVariableOps(MI, NumFixedOps + 1, OS);
231 break;
232 case SPIRV::OpCopyMemory:
233 case SPIRV::OpCopyMemorySized: {
234 const unsigned NumOps = MI->getNumOperands();
235 for (unsigned i = NumFixedOps; i < NumOps; ++i) {
236 OS << ' ';
238 OS);
239 if (MI->getOperand(i).getImm() & MemoryOperand::Aligned) {
240 assert(i + 1 < NumOps && "Missing alignment operand");
241 OS << ' ';
242 printOperand(MI, i + 1, OS);
243 i += 1;
244 }
245 }
246 break;
247 }
248 case SPIRV::OpConstantI:
249 case SPIRV::OpConstantF:
250 // The last fixed operand along with any variadic operands that follow
251 // are part of the variable value.
252 assert(NumFixedOps > 0 && "Expected at least one fixed operand");
253 printOpConstantVarOps(MI, NumFixedOps - 1, OS);
254 break;
255 case SPIRV::OpCooperativeMatrixMulAddKHR: {
256 const unsigned NumOps = MI->getNumOperands();
257 if (NumFixedOps == NumOps)
258 break;
259
260 OS << ' ';
261 const unsigned MulAddOp = MI->getOperand(FirstVariableIndex).getImm();
262 if (MulAddOp == 0) {
264 OperandCategory::CooperativeMatrixOperandsOperand>(
265 MI, FirstVariableIndex, OS);
266 } else {
267 std::string Buffer;
268 for (unsigned Mask = 0x1;
269 Mask != SPIRV::CooperativeMatrixOperands::
270 MatrixResultBFloat16ComponentsINTEL;
271 Mask <<= 1) {
272 if (MulAddOp & Mask) {
273 if (!Buffer.empty())
274 Buffer += '|';
276 OperandCategory::CooperativeMatrixOperandsOperand, Mask);
277 }
278 }
279 OS << Buffer;
280 }
281 break;
282 }
283 case SPIRV::OpSubgroupMatrixMultiplyAccumulateINTEL: {
284 const unsigned NumOps = MI->getNumOperands();
285 if (NumFixedOps >= NumOps)
286 break;
287 OS << ' ';
288 const unsigned Flags = MI->getOperand(NumOps - 1).getImm();
289 if (Flags == 0) {
291 OperandCategory::MatrixMultiplyAccumulateOperandsOperand>(
292 MI, NumOps - 1, OS);
293 } else {
294 std::string Buffer;
295 for (unsigned Mask = 0x1;
296 Mask <= SPIRV::MatrixMultiplyAccumulateOperands::
297 MatrixBPackedBFloat16INTEL;
298 Mask <<= 1) {
299 if (Flags & Mask) {
300 if (!Buffer.empty())
301 Buffer += '|';
303 OperandCategory::MatrixMultiplyAccumulateOperandsOperand,
304 Mask);
305 }
306 }
307 OS << Buffer;
308 }
309 break;
310 }
311 case SPIRV::OpSDot:
312 case SPIRV::OpUDot:
313 case SPIRV::OpSUDot:
314 case SPIRV::OpSDotAccSat:
315 case SPIRV::OpUDotAccSat:
316 case SPIRV::OpSUDotAccSat: {
317 const unsigned NumOps = MI->getNumOperands();
318 if (NumOps > NumFixedOps) {
319 OS << ' ';
321 MI, NumOps - 1, OS);
322 break;
323 }
324 break;
325 }
326 case SPIRV::OpPredicatedLoadINTEL:
327 case SPIRV::OpPredicatedStoreINTEL: {
328 const unsigned NumOps = MI->getNumOperands();
329 if (NumOps > NumFixedOps) {
330 OS << ' ';
332 MI, NumOps - 1, OS);
333 break;
334 }
335 break;
336 }
337 default:
338 printRemainingVariableOps(MI, NumFixedOps, OS);
339 break;
340 }
341 }
342 }
343 }
344
345 printAnnotation(OS, Annot);
346}
347
349 // The fixed operands have already been printed, so just need to decide what
350 // type of ExtInst operands to print based on the instruction set and number.
351 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
352 unsigned NumFixedOps = MCDesc.getNumOperands();
353 const auto NumOps = MI->getNumOperands();
354 if (NumOps == NumFixedOps)
355 return;
356
357 O << ' ';
358
359 // TODO: implement special printing for OpenCLExtInst::vstor*.
360 printRemainingVariableOps(MI, NumFixedOps, O, true);
361}
362
364 // The fixed operands have already been printed, so just need to decide what
365 // type of decoration operands to print based on the Decoration type.
366 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
367 unsigned NumFixedOps = MCDesc.getNumOperands();
368
369 if (NumFixedOps != MI->getNumOperands()) {
370 auto DecOp = MI->getOperand(NumFixedOps - 1);
371 auto Dec = static_cast<Decoration::Decoration>(DecOp.getImm());
372
373 O << ' ';
374
375 switch (Dec) {
376 case Decoration::BuiltIn:
378 break;
379 case Decoration::UniformId:
381 break;
382 case Decoration::FuncParamAttr:
384 MI, NumFixedOps, O);
385 break;
386 case Decoration::FPRoundingMode:
388 MI, NumFixedOps, O);
389 break;
390 case Decoration::FPFastMathMode:
392 MI, NumFixedOps, O);
393 break;
394 case Decoration::LinkageAttributes:
395 case Decoration::UserSemantic:
396 printStringImm(MI, NumFixedOps, O);
397 break;
398 case Decoration::HostAccessINTEL:
399 printOperand(MI, NumFixedOps, O);
400 if (NumFixedOps + 1 < MI->getNumOperands()) {
401 O << ' ';
402 printStringImm(MI, NumFixedOps + 1, O);
403 }
404 break;
405 default:
406 printRemainingVariableOps(MI, NumFixedOps, O, true);
407 break;
408 }
409 }
410}
411
413 const auto EnumOperand = MI->getOperand(1);
414 assert(EnumOperand.isImm() &&
415 "second operand of UNKNOWN_type must be opcode!");
416
417 const auto Enumerant = EnumOperand.getImm();
418 const auto NumOps = MI->getNumOperands();
419
420 // Print the opcode using the spirv-as unknown opcode syntax
421 O << "OpUnknown(" << Enumerant << ", " << NumOps << ") ";
422
423 // The result ID must be printed after the opcode when using this syntax
424 printOperand(MI, 0, O);
425
426 O << " ";
427
428 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
429 unsigned NumFixedOps = MCDesc.getNumOperands();
430 if (NumOps == NumFixedOps)
431 return;
432
433 // Print the rest of the operands
434 printRemainingVariableOps(MI, NumFixedOps, O, true);
435}
436
437void SPIRVInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
438 raw_ostream &O) {
439 if (OpNo < MI->getNumOperands()) {
440 const MCOperand &Op = MI->getOperand(OpNo);
441 if (Op.isReg())
442 O << '%' << (getIDFromRegister(Op.getReg().id()) + 1);
443 else if (Op.isImm()) {
444 int64_t Imm = Op.getImm();
445 // For OpVectorShuffle:
446 // A Component literal may also be FFFFFFFF, which means the corresponding
447 // result component has no source and is undefined.
448 // LLVM representation of poison/undef becomes -1 when lowered to MI.
449 if (MI->getOpcode() == SPIRV::OpVectorShuffle && Imm == -1)
450 O << "0xFFFFFFFF";
451 else
452 O << formatImm(Imm);
453 } else if (Op.isDFPImm())
454 O << formatImm((double)Op.getDFPImm());
455 else if (Op.isExpr())
456 MAI.printExpr(O, *Op.getExpr());
457 else
458 llvm_unreachable("Unexpected operand type");
459 }
460}
461
462void SPIRVInstPrinter::printStringImm(const MCInst *MI, unsigned OpNo,
463 raw_ostream &O) {
464 const unsigned NumOps = MI->getNumOperands();
465 unsigned StrStartIndex = OpNo;
466 while (StrStartIndex < NumOps) {
467 if (MI->getOperand(StrStartIndex).isReg())
468 break;
469
470 std::string Str = getSPIRVStringOperand(*MI, StrStartIndex);
471 if (StrStartIndex != OpNo)
472 O << ' '; // Add a space if we're starting a new string/argument.
473 O << '"';
474 for (char c : Str) {
475 // Escape ", \n characters (might break for complex UTF-8).
476 if (c == '\n') {
477 O.write("\\n", 2);
478 } else {
479 if (c == '"')
480 O.write('\\');
481 O.write(c);
482 }
483 }
484 O << '"';
485
486 unsigned numOpsInString = (Str.size() / 4) + 1;
487 StrStartIndex += numOpsInString;
488
489 // Check for final Op of "OpDecorate %x %stringImm %linkageAttribute".
490 if (MI->getOpcode() == SPIRV::OpDecorate &&
491 MI->getOperand(1).getImm() ==
492 static_cast<unsigned>(Decoration::LinkageAttributes)) {
493 O << ' ';
495 MI, StrStartIndex, O);
496 break;
497 }
498 }
499}
500
501void SPIRVInstPrinter::printExtension(const MCInst *MI, unsigned OpNo,
502 raw_ostream &O) {
503 auto SetReg = MI->getOperand(2).getReg();
504 auto Set = ExtInstSetIDs[SetReg];
505 auto Op = MI->getOperand(OpNo).getImm();
506 O << getExtInstName(Set, Op);
507}
508
509template <OperandCategory::OperandCategory category>
511 raw_ostream &O) {
512 if (OpNo < MI->getNumOperands()) {
513 O << getSymbolicOperandMnemonic(category, MI->getOperand(OpNo).getImm());
514 }
515}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
MachineInstr unsigned OpIdx
Class for arbitrary precision integers.
Definition APInt.h:78
const MCInstrInfo & MII
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
const MCAsmInfo & MAI
format_object< int64_t > formatImm(int64_t Value) const
Utility function to print immediates in decimal or hex.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Generic base class for all target subtargets.
void printExtension(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printStringImm(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printInstruction(const MCInst *MI, uint64_t Address, raw_ostream &O)
void printInst(const MCInst *MI, uint64_t Address, StringRef Annot, const MCSubtargetInfo &STI, raw_ostream &OS) override
Print the specified MCInst to the specified raw_ostream.
void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printOpExtInst(const MCInst *MI, raw_ostream &O)
void printOpConstantVarOps(const MCInst *MI, unsigned StartIndex, raw_ostream &O)
void printSymbolicOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O)
void printRemainingVariableOps(const MCInst *MI, unsigned StartIndex, raw_ostream &O, bool SkipFirstSpace=false, bool SkipImmediates=false)
void printOpDecorate(const MCInst *MI, raw_ostream &O)
void printUnknownType(const MCInst *MI, raw_ostream &O)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getIDFromRegister(unsigned Reg)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
std::string getExtInstName(SPIRV::InstructionSet::InstructionSet Set, uint32_t InstructionNumber)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
std::string getSPIRVStringOperand(const InstType &MI, unsigned StartIndex)
SPIRV::InstructionSet::InstructionSet getExtInstSetFromString(std::string SetName)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
DWARFExpression::Operation Op