blob: 83cf45283e2e0aea25562c84425cf83e470f426b [file] [log] [blame]
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01001// Copyright (c) 2015 The Khronos Group Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and/or associated documentation files (the
5// "Materials"), to deal in the Materials without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Materials, and to
8// permit persons to whom the Materials are furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Materials.
13//
14// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
15// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
16// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
17// https://www.khronos.org/registry/
18//
19// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
26
27#include <libspirv/libspirv.h>
28#include "binary.h"
29#include "diagnostic.h"
30#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040031#include "instruction.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010032#include "opcode.h"
33#include "operand.h"
Andrew Woloszynccc210b2015-10-16 10:23:42 -040034#include "text_handler.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010035
36#include <assert.h>
37#include <string.h>
38
39#include <sstream>
40
41// Binary API
42
43enum {
44 I32_ENDIAN_LITTLE = 0x03020100ul,
45 I32_ENDIAN_BIG = 0x00010203ul,
46};
47
48static const union {
49 unsigned char bytes[4];
50 uint32_t value;
51} o32_host_order = {{0, 1, 2, 3}};
52
53#define I32_ENDIAN_HOST (o32_host_order.value)
54
55spv_result_t spvBinaryEndianness(const spv_binary binary,
56 spv_endianness_t *pEndian) {
Lei Zhang40056702015-09-11 14:31:27 -040057 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
58 if (!pEndian) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010059
60 uint8_t bytes[4];
61 memcpy(bytes, binary->code, sizeof(uint32_t));
62
63 if (0x03 == bytes[0] && 0x02 == bytes[1] && 0x23 == bytes[2] &&
64 0x07 == bytes[3]) {
65 *pEndian = SPV_ENDIANNESS_LITTLE;
66 return SPV_SUCCESS;
67 }
68
69 if (0x07 == bytes[0] && 0x23 == bytes[1] && 0x02 == bytes[2] &&
70 0x03 == bytes[3]) {
71 *pEndian = SPV_ENDIANNESS_BIG;
72 return SPV_SUCCESS;
73 }
74
75 return SPV_ERROR_INVALID_BINARY;
76}
77
78uint32_t spvFixWord(const uint32_t word, const spv_endianness_t endian) {
79 if ((SPV_ENDIANNESS_LITTLE == endian && I32_ENDIAN_HOST == I32_ENDIAN_BIG) ||
80 (SPV_ENDIANNESS_BIG == endian && I32_ENDIAN_HOST == I32_ENDIAN_LITTLE)) {
81 return (word & 0x000000ff) << 24 | (word & 0x0000ff00) << 8 |
82 (word & 0x00ff0000) >> 8 | (word & 0xff000000) >> 24;
83 }
84
85 return word;
86}
87
Lei Zhangb41d1502015-09-14 15:22:23 -040088uint64_t spvFixDoubleWord(const uint32_t low, const uint32_t high,
89 const spv_endianness_t endian) {
90 return (uint64_t(spvFixWord(high, endian)) << 32) | spvFixWord(low, endian);
91}
92
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010093spv_result_t spvBinaryHeaderGet(const spv_binary binary,
94 const spv_endianness_t endian,
95 spv_header_t *pHeader) {
Lei Zhang40056702015-09-11 14:31:27 -040096 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
97 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010098
99 // TODO: Validation checking?
100 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
101 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
102 pHeader->generator =
103 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
104 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
105 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
106 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
107
108 return SPV_SUCCESS;
109}
110
111spv_result_t spvBinaryHeaderSet(spv_binary_t *binary, const uint32_t bound) {
Lei Zhang40056702015-09-11 14:31:27 -0400112 if (!binary) return SPV_ERROR_INVALID_BINARY;
113 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100114
115 binary->code[SPV_INDEX_MAGIC_NUMBER] = SPV_MAGIC_NUMBER;
116 binary->code[SPV_INDEX_VERSION_NUMBER] = SPV_VERSION_NUMBER;
Kenneth Benzie (Benie)81d7d492015-06-01 09:50:46 -0700117 binary->code[SPV_INDEX_GENERATOR_NUMBER] = SPV_GENERATOR_KHRONOS;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100118 binary->code[SPV_INDEX_BOUND] = bound;
119 binary->code[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
120
121 return SPV_SUCCESS;
122}
123
David Neto78c3b432015-08-27 13:03:52 -0400124// TODO(dneto): This API is not powerful enough in the case that the
125// number and type of operands are not known until partway through parsing
126// the operation. This happens when enum operands might have different number
127// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100128spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
129 const uint16_t operandIndex,
130 const spv_opcode_desc opcodeEntry,
131 const spv_operand_table operandTable,
132 spv_operand_desc *pOperandEntry) {
133 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400134 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100135 // NOTE: Do operand table lookup to set operandEntry if successful
136 uint16_t index = operandIndex - 1;
137 type = opcodeEntry->operandTypes[index];
138 spv_operand_desc entry = nullptr;
139 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
140 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
141 *pOperandEntry = entry;
142 }
143 }
144 } else if (*pOperandEntry) {
145 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400146 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100147 type = (*pOperandEntry)->operandTypes[index];
148 } else if (OpSwitch == opcodeEntry->opcode) {
149 // NOTE: OpSwitch is a special case which expects a list of paired extra
150 // operands
151 assert(0 &&
152 "This case is previously untested, remove this assert and ensure it "
153 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400154 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100155 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
156 type = opcodeEntry->operandTypes[index];
157 } else {
158 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400159 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100160 type = opcodeEntry->operandTypes[index];
161 }
162 return type;
163}
164
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400165
166/// @brief Translate a binary operand to the textual form
167///
168/// @param[in] opcode of the current instruction
169/// @param[in] type type of the operand to decode
170/// @param[in] words the binary stream of words
171/// @param[in] endian the endianness of the stream
172/// @param[in] options bitfield of spv_binary_to_text_options_t values
173/// @param[in] grammar the AssemblyGrammar to when decoding this operand
174/// @param[in,out] stream the text output stream
175/// @param[in,out] position position in the binary stream
176/// @param[out] pDiag return diagnostic on error
177///
178/// @return result code
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100179spv_result_t spvBinaryDecodeOperand(
180 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400181 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400182 const libspirv::AssemblyGrammar& grammar,
David Neto78c3b432015-08-27 13:03:52 -0400183 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
184 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400185 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
186 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100187
188 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
189 bool color =
190 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
191
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100192 switch (type) {
David Netob14a7272015-09-25 13:56:09 -0400193 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Neto78c3b432015-08-27 13:03:52 -0400194 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400195 case SPV_OPERAND_TYPE_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400196 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400197 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netob14a7272015-09-25 13:56:09 -0400198 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
199 case SPV_OPERAND_TYPE_RESULT_ID: {
David Neto78c3b432015-08-27 13:03:52 -0400200 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700201 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
202 stream.get() << clr::blue();
203 } else {
204 stream.get() << clr::yellow();
205 }
David Neto78c3b432015-08-27 13:03:52 -0400206 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400207 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100208 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100209 position->index++;
210 } break;
Lei Zhang6483bd72015-10-14 17:02:39 -0400211 case SPV_OPERAND_TYPE_LITERAL_INTEGER: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100212 // NOTE: Special case for extended instruction use
213 if (OpExtInst == opcode) {
214 spv_ext_inst_desc extInst;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400215 if (grammar.lookupExtInst(*pExtInstType, words[0], &extInst)) {
Lei Zhang40056702015-09-11 14:31:27 -0400216 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
217 return SPV_ERROR_INVALID_BINARY;
218 }
David Neto78c3b432015-08-27 13:03:52 -0400219 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400220 stream.get() << (color ? clr::red() : "");
221 stream.get() << extInst->name;
222 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400223 position->index++;
224 break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100225 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400226 } // Fall through for the general case.
Lei Zhangb41d1502015-09-14 15:22:23 -0400227 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400228 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
229 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE: {
Lei Zhang41bf0732015-09-14 12:26:15 -0400230 // TODO: Need to support multiple word literals
231 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400232 if (numWords > 2) {
233 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
234 return SPV_UNSUPPORTED;
235 } else if (numWords == 2) {
236 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
237 position->index += 2;
238 } else {
239 stream.get() << spvFixWord(words[0], endian);
240 position->index++;
241 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400242 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100243 } break;
David Neto78c3b432015-08-27 13:03:52 -0400244 case SPV_OPERAND_TYPE_LITERAL_STRING:
245 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400246 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100247 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
248
249 // NOTE: Special case for extended instruction import
250 if (OpExtInstImport == opcode) {
251 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400252 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
253 DIAGNOSTIC << "Invalid extended instruction import'" << string
254 << "'.";
255 return SPV_ERROR_INVALID_BINARY;
256 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100257 }
258
259 stream.get() << "\"";
260 stream.get() << (color ? clr::green() : "");
David Neto980b7cb2015-10-15 16:40:04 -0400261 for (const char* p = string; *p; ++p) {
262 if(*p == '"' || *p == '\\') {
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400263 stream.get() << '\\';
264 }
David Neto980b7cb2015-10-15 16:40:04 -0400265 stream.get() << *p;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400266 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100267 stream.get() << (color ? clr::reset() : "");
268 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100269 position->index += stringOperandCount;
270 } break;
271 case SPV_OPERAND_TYPE_CAPABILITY:
272 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
273 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
274 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
275 case SPV_OPERAND_TYPE_MEMORY_MODEL:
276 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400277 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100278 case SPV_OPERAND_TYPE_STORAGE_CLASS:
279 case SPV_OPERAND_TYPE_DIMENSIONALITY:
280 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
281 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100282 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
283 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
284 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
285 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
286 case SPV_OPERAND_TYPE_DECORATION:
287 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100288 case SPV_OPERAND_TYPE_GROUP_OPERATION:
289 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400290 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100291 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400292 if (grammar.lookupOperand(type, spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400293 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400294 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400295 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400296 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100297 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400298 // Prepare to accept operands to this operand, if needed.
299 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100300 position->index++;
301 } break;
David Neto619db262015-09-25 12:43:37 -0400302 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
303 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
304 case SPV_OPERAND_TYPE_LOOP_CONTROL:
305 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
306 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
307 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
308 // This operand is a mask.
309 // Scan it from least significant bit to most significant bit. For each
310 // set bit, emit the name of that bit and prepare to parse its operands,
311 // if any.
312 uint32_t remaining_word = spvFixWord(words[0], endian);
313 uint32_t mask;
314 int num_emitted = 0;
315 for (mask = 1; remaining_word; mask <<= 1) {
316 if (remaining_word & mask) {
317 remaining_word ^= mask;
318 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400319 if (grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400320 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
321 << words[0] << "'.";
322 return SPV_ERROR_INVALID_BINARY;
323 }
324 if (num_emitted) stream.get() << "|";
325 stream.get() << entry->name;
326 num_emitted++;
327 }
328 }
329 if (!num_emitted) {
330 // An operand value of 0 was provided, so represent it by the name
331 // of the 0 value. In many cases, that's "None".
332 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400333 if (SPV_SUCCESS == grammar.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400334 stream.get() << entry->name;
335 // Prepare for its operands, if any.
336 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
337 }
338 }
339 // Prepare for subsequent operands, if any.
340 // Scan from MSB to LSB since we can only prepend operands to a pattern.
341 remaining_word = spvFixWord(words[0], endian);
342 for (mask = (1u << 31); remaining_word; mask >>= 1) {
343 if (remaining_word & mask) {
344 remaining_word ^= mask;
345 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400346 if (SPV_SUCCESS == grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400347 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
348 }
349 }
350 }
351 position->index++;
352 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100353 default: {
354 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
355 return SPV_ERROR_INVALID_BINARY;
356 }
357 }
358
359 return SPV_SUCCESS;
360}
361
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400362/// @brief Translate binary Opcode stream to textual form
363///
364/// @param[in] pInst the Opcode instruction stream
365/// @param[in] endian the endianness of the stream
366/// @param[in] options bitfield of spv_binary_to_text_options_t values
367/// @param[in] grammar the AssemblyGrammar to when decoding this operand
368/// @param[in] format the assembly syntax format to decode into
369/// @param[out] stream output text stream
370/// @param[in,out] position position in the stream
371/// @param[out] pDiag return diagnostic on error
372///
373/// @return result code
374spv_result_t spvBinaryDecodeOpcode(spv_instruction_t* pInst,
375 const spv_endianness_t endian,
376 const uint32_t options,
377 const libspirv::AssemblyGrammar& grammar,
378 spv_assembly_syntax_format_t format,
379 out_stream &stream, spv_position position,
380 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400381 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
Lei Zhang40056702015-09-11 14:31:27 -0400382 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100383
David Neto78c3b432015-08-27 13:03:52 -0400384 spv_position_t instructionStart = *position;
385
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100386 uint16_t wordCount;
387 Op opcode;
388 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
389
390 spv_opcode_desc opcodeEntry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400391 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400392 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
393 return SPV_ERROR_INVALID_BINARY;
394 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100395
David Neto78c3b432015-08-27 13:03:52 -0400396 // See if there are enough required words.
397 // Some operands in the operand types are optional or could be zero length.
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400398 // The optional and zero length operands must be at the end of the list.
David Neto78c3b432015-08-27 13:03:52 -0400399 if (opcodeEntry->numTypes > wordCount &&
400 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
401 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400402 for (numRequired = 0;
403 numRequired < opcodeEntry->numTypes &&
404 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
405 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400406 ;
407 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400408 << " word count '" << wordCount << "', expected at least '"
409 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400410 return SPV_ERROR_INVALID_BINARY;
411 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100412
Lei Zhang29e667e2015-09-11 11:01:59 -0400413 const bool isAssigmentFormat =
414 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
415
416 // For Canonical Assembly Format, all words are written to stream in order.
417 // For Assignment Assembly Format, <result-id> and the equal sign are written
418 // to stream first, while the rest are written to no_result_id_stream. After
419 // processing all words, all words in no_result_id_stream are transcribed to
420 // stream.
421
Lei Zhang8a375202015-08-24 15:52:26 -0400422 std::stringstream no_result_id_strstream;
423 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400424 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
425 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100426
Lei Zhang29e667e2015-09-11 11:01:59 -0400427 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100428 position->index++;
429
David Neto78c3b432015-08-27 13:03:52 -0400430 // Maintains the ordered list of expected operand types.
431 // For many instructions we only need the {numTypes, operandTypes}
432 // entries in opcodeEntry. However, sometimes we need to modify
433 // the list as we parse the operands. This occurs when an operand
434 // has its own logical operands (such as the LocalSize operand for
435 // ExecutionMode), or for extended instructions that may have their
436 // own operands depending on the selected extended instruction.
437 spv_operand_pattern_t expectedOperands(
438 opcodeEntry->operandTypes,
439 opcodeEntry->operandTypes + opcodeEntry->numTypes);
440
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100441 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100442 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400443 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100444
Lei Zhang40056702015-09-11 14:31:27 -0400445 if (expectedOperands.empty()) {
446 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
447 << " starting at word " << instructionStart.index
448 << ": expected no more operands after " << index
449 << " words, but word count is " << wordCount << ".";
450 return SPV_ERROR_INVALID_BINARY;
451 }
David Neto78c3b432015-08-27 13:03:52 -0400452
453 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
454
Lei Zhang29e667e2015-09-11 11:01:59 -0400455 if (isAssigmentFormat) {
456 if (!currentIsResultId) no_result_id_stream.get() << " ";
457 } else {
458 stream.get() << " ";
459 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400460
461 uint16_t numWords = 1;
462 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
463 // Make sure this is the last operand for this instruction.
464 if (expectedOperands.empty()) {
465 numWords = wordCount - index;
466 } else {
467 // TODO(antiagainst): This may not be an error. The exact design has not
468 // been settled yet.
469 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
470 "last operand of an instruction.";
471 return SPV_ERROR_INVALID_BINARY;
472 }
473 }
474
Lei Zhang40056702015-09-11 14:31:27 -0400475 if (spvBinaryDecodeOperand(
David Netob5dc8fc2015-10-06 16:22:00 -0400476 opcodeEntry->opcode, type, &pInst->words[index], numWords, endian,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400477 options, grammar, &expectedOperands,
Lei Zhangb41d1502015-09-14 15:22:23 -0400478 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400479 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
480 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400481 position, pDiagnostic)) {
482 DIAGNOSTIC << "UNEXPLAINED ERROR";
483 return SPV_ERROR_INVALID_BINARY;
484 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400485 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100486 index += (uint16_t)(position->index - currentPosIndex - 1);
487 }
David Neto78c3b432015-08-27 13:03:52 -0400488 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400489 if (!expectedOperands.empty() &&
490 !spvOperandIsOptional(expectedOperands.front())) {
491 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
492 << " starting at word " << instructionStart.index
493 << ": expected more operands after " << wordCount << " words.";
494 return SPV_ERROR_INVALID_BINARY;
495 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100496
Lei Zhang8a375202015-08-24 15:52:26 -0400497 stream.get() << no_result_id_strstream.str();
498
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100499 return SPV_SUCCESS;
500}
501
Lei Zhange78a7c12015-09-10 17:07:21 -0400502spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400503 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100504 const spv_opcode_table opcodeTable,
505 const spv_operand_table operandTable,
506 const spv_ext_inst_table extInstTable,
507 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400508 return spvBinaryToTextWithFormat(
509 code, wordCount, options, opcodeTable, operandTable, extInstTable,
510 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
511}
512
513spv_result_t spvBinaryToTextWithFormat(
514 uint32_t *code, const uint64_t wordCount, const uint32_t options,
515 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
516 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
517 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400518 spv_binary_t binary = {code, wordCount};
519
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400520 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400521 if (!binary.code || !binary.wordCount) {
522 DIAGNOSTIC << "Binary stream is empty.";
523 return SPV_ERROR_INVALID_BINARY;
524 }
525 if (!opcodeTable || !operandTable || !extInstTable)
526 return SPV_ERROR_INVALID_TABLE;
527 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
528 return SPV_ERROR_INVALID_POINTER;
529 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
530 return SPV_ERROR_INVALID_POINTER;
531 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100532
533 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400534 if (spvBinaryEndianness(&binary, &endian)) {
535 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
536 << "'.";
537 return SPV_ERROR_INVALID_BINARY;
538 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100539
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400540 libspirv::AssemblyGrammar grammar(operandTable, opcodeTable, extInstTable);
541
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100542 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400543 if (spvBinaryHeaderGet(&binary, endian, &header)) {
544 DIAGNOSTIC << "Invalid SPIR-V header.";
545 return SPV_ERROR_INVALID_BINARY;
546 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100547
548 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
549 bool color =
550 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
551
552 std::stringstream sstream;
553 out_stream stream(sstream);
554 if (print) {
555 stream = out_stream();
556 }
557
558 if (color) {
559 stream.get() << clr::grey();
560 }
561 stream.get() << "; SPIR-V\n"
562 << "; Version: " << header.version << "\n"
563 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
564 << "; Bound: " << header.bound << "\n"
565 << "; Schema: " << header.schema << "\n";
566 if (color) {
567 stream.get() << clr::reset();
568 }
569
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400570 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100571 position.index = SPV_INDEX_INSTRUCTION;
572 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400573 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100574 uint64_t index = position.index;
575 uint16_t wordCount;
576 Op opcode;
577 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
578 &opcode);
579
580 spv_instruction_t inst = {};
581 inst.extInstType = extInstType;
582 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
583 &inst);
584
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400585 if (spvBinaryDecodeOpcode(&inst, endian, options, grammar, format, stream,
586 &position, pDiagnostic))
Lei Zhang40056702015-09-11 14:31:27 -0400587 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100588 extInstType = inst.extInstType;
589
Lei Zhang40056702015-09-11 14:31:27 -0400590 if ((index + wordCount) != position.index) {
591 DIAGNOSTIC << "Invalid word count.";
592 return SPV_ERROR_INVALID_BINARY;
593 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100594
595 stream.get() << "\n";
596 }
597
598 if (!print) {
599 size_t length = sstream.str().size();
600 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400601 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100602 strncpy(str, sstream.str().c_str(), length + 1);
603 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400604 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100605 text->str = str;
606 text->length = length;
607 *pText = text;
608 }
609
610 return SPV_SUCCESS;
611}
612
613void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400614 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100615 if (binary->code) {
616 delete[] binary->code;
617 }
618 delete binary;
619}