LLVM 22.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 assert((NumVarOps == 1 || NumVarOps == 2) &&
54 "Unsupported number of bits for literal variable");
55
56 O << ' ';
57
58 uint64_t Imm = MI->getOperand(StartIndex).getImm();
59
60 // Handle 64 bit literals.
61 if (NumVarOps == 2) {
62 Imm |= (MI->getOperand(StartIndex + 1).getImm() << 32);
63 }
64
65 // Format and print float values.
66 if (MI->getOpcode() == SPIRV::OpConstantF && IsBitwidth16 == 0) {
67 APFloat FP = NumVarOps == 1 ? APFloat(APInt(32, Imm).bitsToFloat())
68 : APFloat(APInt(64, Imm).bitsToDouble());
69
70 // Print infinity and NaN as hex floats.
71 // TODO: Make sure subnormal numbers are handled correctly as they may also
72 // require hex float notation.
73 if (FP.isInfinity()) {
74 if (FP.isNegative())
75 O << '-';
76 O << "0x1p+128";
77 return;
78 }
79 if (FP.isNaN()) {
80 O << "0x1.8p+128";
81 return;
82 }
83
84 // Format val as a decimal floating point or scientific notation (whichever
85 // is shorter), with enough digits of precision to produce the exact value.
86 O << format("%.*g", std::numeric_limits<double>::max_digits10,
87 FP.convertToDouble());
88
89 return;
90 }
91
92 // Print integer values directly.
93 O << Imm;
94}
95
96void SPIRVInstPrinter::recordOpExtInstImport(const MCInst *MI) {
97 MCRegister Reg = MI->getOperand(0).getReg();
98 auto Name = getSPIRVStringOperand(*MI, 1);
99 auto Set = getExtInstSetFromString(std::move(Name));
100 ExtInstSetIDs.insert({Reg, Set});
101}
102
104 StringRef Annot, const MCSubtargetInfo &STI,
105 raw_ostream &OS) {
106 const unsigned OpCode = MI->getOpcode();
108
109 if (OpCode == SPIRV::OpDecorate) {
111 } else if (OpCode == SPIRV::OpExtInstImport) {
112 recordOpExtInstImport(MI);
113 } else if (OpCode == SPIRV::OpExtInst) {
115 } else if (OpCode == SPIRV::UNKNOWN_type) {
117 } else {
118 // Print any extra operands for variadic instructions.
119 const MCInstrDesc &MCDesc = MII.get(OpCode);
120 if (MCDesc.isVariadic()) {
121 const unsigned NumFixedOps = MCDesc.getNumOperands();
122 const unsigned LastFixedIndex = NumFixedOps - 1;
123 const int FirstVariableIndex = NumFixedOps;
124 if (NumFixedOps > 0 && MCDesc.operands()[LastFixedIndex].OperandType ==
126 // For instructions where a custom type (not reg or immediate) comes as
127 // the last operand before the variable_ops. This is usually a StringImm
128 // operand, but there are a few other cases.
129 switch (OpCode) {
130 case SPIRV::OpTypeImage:
131 OS << ' ';
132 printSymbolicOperand<OperandCategory::AccessQualifierOperand>(
133 MI, FirstVariableIndex, OS);
134 break;
135 case SPIRV::OpVariable:
136 OS << ' ';
137 printOperand(MI, FirstVariableIndex, OS);
138 break;
139 case SPIRV::OpEntryPoint: {
140 // Print the interface ID operands, skipping the name's string
141 // literal.
142 printRemainingVariableOps(MI, NumFixedOps, OS, false, true);
143 break;
144 }
145 case SPIRV::OpMemberDecorate:
146 printRemainingVariableOps(MI, NumFixedOps, OS);
147 break;
148 case SPIRV::OpExecutionMode:
149 case SPIRV::OpExecutionModeId:
150 case SPIRV::OpLoopMerge: {
151 // Print any literals after the OPERAND_UNKNOWN argument normally.
152 printRemainingVariableOps(MI, NumFixedOps, OS);
153 break;
154 }
155 default:
156 break; // printStringImm has already been handled.
157 }
158 } else {
159 // For instructions with no fixed ops or a reg/immediate as the final
160 // fixed operand, we can usually print the rest with "printOperand", but
161 // check for a few cases with custom types first.
162 switch (OpCode) {
163 case SPIRV::OpLoad:
164 case SPIRV::OpStore:
165 OS << ' ';
166 printSymbolicOperand<OperandCategory::MemoryOperandOperand>(
167 MI, FirstVariableIndex, OS);
168 printRemainingVariableOps(MI, FirstVariableIndex + 1, OS);
169 break;
170 case SPIRV::OpImageSampleImplicitLod:
171 case SPIRV::OpImageSampleDrefImplicitLod:
172 case SPIRV::OpImageSampleProjImplicitLod:
173 case SPIRV::OpImageSampleProjDrefImplicitLod:
174 case SPIRV::OpImageFetch:
175 case SPIRV::OpImageGather:
176 case SPIRV::OpImageDrefGather:
177 case SPIRV::OpImageRead:
178 case SPIRV::OpImageWrite:
179 case SPIRV::OpImageSparseSampleImplicitLod:
180 case SPIRV::OpImageSparseSampleDrefImplicitLod:
181 case SPIRV::OpImageSparseSampleProjImplicitLod:
182 case SPIRV::OpImageSparseSampleProjDrefImplicitLod:
183 case SPIRV::OpImageSparseFetch:
184 case SPIRV::OpImageSparseGather:
185 case SPIRV::OpImageSparseDrefGather:
186 case SPIRV::OpImageSparseRead:
187 case SPIRV::OpImageSampleFootprintNV:
188 OS << ' ';
189 printSymbolicOperand<OperandCategory::ImageOperandOperand>(
190 MI, FirstVariableIndex, OS);
191 printRemainingVariableOps(MI, NumFixedOps + 1, OS);
192 break;
193 case SPIRV::OpCopyMemory:
194 case SPIRV::OpCopyMemorySized: {
195 const unsigned NumOps = MI->getNumOperands();
196 for (unsigned i = NumFixedOps; i < NumOps; ++i) {
197 OS << ' ';
198 printSymbolicOperand<OperandCategory::MemoryOperandOperand>(MI, i,
199 OS);
200 if (MI->getOperand(i).getImm() & MemoryOperand::Aligned) {
201 assert(i + 1 < NumOps && "Missing alignment operand");
202 OS << ' ';
203 printOperand(MI, i + 1, OS);
204 i += 1;
205 }
206 }
207 break;
208 }
209 case SPIRV::OpConstantI:
210 case SPIRV::OpConstantF:
211 // The last fixed operand along with any variadic operands that follow
212 // are part of the variable value.
213 assert(NumFixedOps > 0 && "Expected at least one fixed operand");
214 printOpConstantVarOps(MI, NumFixedOps - 1, OS);
215 break;
216 case SPIRV::OpCooperativeMatrixMulAddKHR: {
217 const unsigned NumOps = MI->getNumOperands();
218 if (NumFixedOps == NumOps)
219 break;
220
221 OS << ' ';
222 const unsigned MulAddOp = MI->getOperand(FirstVariableIndex).getImm();
223 if (MulAddOp == 0) {
225 OperandCategory::CooperativeMatrixOperandsOperand>(
226 MI, FirstVariableIndex, OS);
227 } else {
228 std::string Buffer;
229 for (unsigned Mask = 0x1;
230 Mask != SPIRV::CooperativeMatrixOperands::
231 MatrixResultBFloat16ComponentsINTEL;
232 Mask <<= 1) {
233 if (MulAddOp & Mask) {
234 if (!Buffer.empty())
235 Buffer += '|';
237 OperandCategory::CooperativeMatrixOperandsOperand, Mask);
238 }
239 }
240 OS << Buffer;
241 }
242 break;
243 }
244 case SPIRV::OpSubgroupMatrixMultiplyAccumulateINTEL: {
245 const unsigned NumOps = MI->getNumOperands();
246 if (NumFixedOps >= NumOps)
247 break;
248 OS << ' ';
249 const unsigned Flags = MI->getOperand(NumOps - 1).getImm();
250 if (Flags == 0) {
252 OperandCategory::MatrixMultiplyAccumulateOperandsOperand>(
253 MI, NumOps - 1, OS);
254 } else {
255 std::string Buffer;
256 for (unsigned Mask = 0x1;
257 Mask <= SPIRV::MatrixMultiplyAccumulateOperands::
258 MatrixBPackedBFloat16INTEL;
259 Mask <<= 1) {
260 if (Flags & Mask) {
261 if (!Buffer.empty())
262 Buffer += '|';
264 OperandCategory::MatrixMultiplyAccumulateOperandsOperand,
265 Mask);
266 }
267 }
268 OS << Buffer;
269 }
270 break;
271 }
272 default:
273 printRemainingVariableOps(MI, NumFixedOps, OS);
274 break;
275 }
276 }
277 }
278 }
279
280 printAnnotation(OS, Annot);
281}
282
284 // The fixed operands have already been printed, so just need to decide what
285 // type of ExtInst operands to print based on the instruction set and number.
286 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
287 unsigned NumFixedOps = MCDesc.getNumOperands();
288 const auto NumOps = MI->getNumOperands();
289 if (NumOps == NumFixedOps)
290 return;
291
292 O << ' ';
293
294 // TODO: implement special printing for OpenCLExtInst::vstor*.
295 printRemainingVariableOps(MI, NumFixedOps, O, true);
296}
297
299 // The fixed operands have already been printed, so just need to decide what
300 // type of decoration operands to print based on the Decoration type.
301 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
302 unsigned NumFixedOps = MCDesc.getNumOperands();
303
304 if (NumFixedOps != MI->getNumOperands()) {
305 auto DecOp = MI->getOperand(NumFixedOps - 1);
306 auto Dec = static_cast<Decoration::Decoration>(DecOp.getImm());
307
308 O << ' ';
309
310 switch (Dec) {
311 case Decoration::BuiltIn:
312 printSymbolicOperand<OperandCategory::BuiltInOperand>(MI, NumFixedOps, O);
313 break;
314 case Decoration::UniformId:
315 printSymbolicOperand<OperandCategory::ScopeOperand>(MI, NumFixedOps, O);
316 break;
317 case Decoration::FuncParamAttr:
318 printSymbolicOperand<OperandCategory::FunctionParameterAttributeOperand>(
319 MI, NumFixedOps, O);
320 break;
321 case Decoration::FPRoundingMode:
322 printSymbolicOperand<OperandCategory::FPRoundingModeOperand>(
323 MI, NumFixedOps, O);
324 break;
325 case Decoration::FPFastMathMode:
326 printSymbolicOperand<OperandCategory::FPFastMathModeOperand>(
327 MI, NumFixedOps, O);
328 break;
329 case Decoration::LinkageAttributes:
330 case Decoration::UserSemantic:
331 printStringImm(MI, NumFixedOps, O);
332 break;
333 case Decoration::HostAccessINTEL:
334 printOperand(MI, NumFixedOps, O);
335 if (NumFixedOps + 1 < MI->getNumOperands()) {
336 O << ' ';
337 printStringImm(MI, NumFixedOps + 1, O);
338 }
339 break;
340 default:
341 printRemainingVariableOps(MI, NumFixedOps, O, true);
342 break;
343 }
344 }
345}
346
348 const auto EnumOperand = MI->getOperand(1);
349 assert(EnumOperand.isImm() &&
350 "second operand of UNKNOWN_type must be opcode!");
351
352 const auto Enumerant = EnumOperand.getImm();
353 const auto NumOps = MI->getNumOperands();
354
355 // Print the opcode using the spirv-as unknown opcode syntax
356 O << "OpUnknown(" << Enumerant << ", " << NumOps << ") ";
357
358 // The result ID must be printed after the opcode when using this syntax
359 printOperand(MI, 0, O);
360
361 O << " ";
362
363 const MCInstrDesc &MCDesc = MII.get(MI->getOpcode());
364 unsigned NumFixedOps = MCDesc.getNumOperands();
365 if (NumOps == NumFixedOps)
366 return;
367
368 // Print the rest of the operands
369 printRemainingVariableOps(MI, NumFixedOps, O, true);
370}
371
372void SPIRVInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
373 raw_ostream &O) {
374 if (OpNo < MI->getNumOperands()) {
375 const MCOperand &Op = MI->getOperand(OpNo);
376 if (Op.isReg())
377 O << '%' << (getIDFromRegister(Op.getReg().id()) + 1);
378 else if (Op.isImm()) {
379 int64_t Imm = Op.getImm();
380 // For OpVectorShuffle:
381 // A Component literal may also be FFFFFFFF, which means the corresponding
382 // result component has no source and is undefined.
383 // LLVM representation of poison/undef becomes -1 when lowered to MI.
384 if (MI->getOpcode() == SPIRV::OpVectorShuffle && Imm == -1)
385 O << "0xFFFFFFFF";
386 else
387 O << formatImm(Imm);
388 } else if (Op.isDFPImm())
389 O << formatImm((double)Op.getDFPImm());
390 else if (Op.isExpr())
391 MAI.printExpr(O, *Op.getExpr());
392 else
393 llvm_unreachable("Unexpected operand type");
394 }
395}
396
397void SPIRVInstPrinter::printStringImm(const MCInst *MI, unsigned OpNo,
398 raw_ostream &O) {
399 const unsigned NumOps = MI->getNumOperands();
400 unsigned StrStartIndex = OpNo;
401 while (StrStartIndex < NumOps) {
402 if (MI->getOperand(StrStartIndex).isReg())
403 break;
404
405 std::string Str = getSPIRVStringOperand(*MI, StrStartIndex);
406 if (StrStartIndex != OpNo)
407 O << ' '; // Add a space if we're starting a new string/argument.
408 O << '"';
409 for (char c : Str) {
410 // Escape ", \n characters (might break for complex UTF-8).
411 if (c == '\n') {
412 O.write("\\n", 2);
413 } else {
414 if (c == '"')
415 O.write('\\');
416 O.write(c);
417 }
418 }
419 O << '"';
420
421 unsigned numOpsInString = (Str.size() / 4) + 1;
422 StrStartIndex += numOpsInString;
423
424 // Check for final Op of "OpDecorate %x %stringImm %linkageAttribute".
425 if (MI->getOpcode() == SPIRV::OpDecorate &&
426 MI->getOperand(1).getImm() ==
427 static_cast<unsigned>(Decoration::LinkageAttributes)) {
428 O << ' ';
429 printSymbolicOperand<OperandCategory::LinkageTypeOperand>(
430 MI, StrStartIndex, O);
431 break;
432 }
433 }
434}
435
436void SPIRVInstPrinter::printExtension(const MCInst *MI, unsigned OpNo,
437 raw_ostream &O) {
438 auto SetReg = MI->getOperand(2).getReg();
439 auto Set = ExtInstSetIDs[SetReg];
440 auto Op = MI->getOperand(OpNo).getImm();
441 O << getExtInstName(Set, Op);
442}
443
444template <OperandCategory::OperandCategory category>
446 raw_ostream &O) {
447 if (OpNo < MI->getNumOperands()) {
448 O << getSymbolicOperandMnemonic(category, MI->getOperand(OpNo).getImm());
449 }
450}
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...
std::string Name
IRTranslator LLVM IR MI
raw_pwrite_stream & OS
Class for arbitrary precision integers.
Definition: APInt.h:78
This class represents an Operation in the Expression.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
void printExpr(raw_ostream &, const MCExpr &) const
Definition: MCAsmInfo.cpp:153
const MCInstrInfo & MII
Definition: MCInstPrinter.h:53
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
const MCAsmInfo & MAI
Definition: MCInstPrinter.h:52
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.
Definition: MCInstrDesc.h:199
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:238
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:240
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:262
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:64
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:33
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.
@ OPERAND_UNKNOWN
Definition: MCInstrDesc.h:60
unsigned getIDFromRegister(unsigned Reg)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::string getExtInstName(SPIRV::InstructionSet::InstructionSet Set, uint32_t InstructionNumber)
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:126
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)