blob: c6a0b93f91d8d0fcf3a861a4ddad82acfa2288f1 [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
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010027#include "binary.h"
David Netofcc7d582015-10-27 15:31:10 -040028
29#include <cassert>
30#include <cstring>
David Neto0ca6b592015-10-30 16:06:15 -040031#include <limits>
David Netofcc7d582015-10-27 15:31:10 -040032#include <unordered_map>
33
34#include <libspirv/libspirv.h>
35#include "assembly_grammar.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010036#include "diagnostic.h"
David Netodb901b62015-10-27 16:14:40 -040037#include "endian.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010038#include "ext_inst.h"
39#include "opcode.h"
40#include "operand.h"
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040041
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010042spv_result_t spvBinaryHeaderGet(const spv_binary binary,
43 const spv_endianness_t endian,
Lei Zhang1a0334e2015-11-02 09:41:20 -050044 spv_header_t* pHeader) {
David Neto0ca6b592015-10-30 16:06:15 -040045 if (!binary->code) return SPV_ERROR_INVALID_BINARY;
46 if (binary->wordCount < SPV_INDEX_INSTRUCTION)
47 return SPV_ERROR_INVALID_BINARY;
Lei Zhang40056702015-09-11 14:31:27 -040048 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010049
50 // TODO: Validation checking?
51 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
52 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
53 pHeader->generator =
54 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
55 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
56 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
57 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
58
59 return SPV_SUCCESS;
60}
61
David Neto78c3b432015-08-27 13:03:52 -040062// TODO(dneto): This API is not powerful enough in the case that the
63// number and type of operands are not known until partway through parsing
64// the operation. This happens when enum operands might have different number
65// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010066spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
67 const uint16_t operandIndex,
68 const spv_opcode_desc opcodeEntry,
69 const spv_operand_table operandTable,
Lei Zhang1a0334e2015-11-02 09:41:20 -050070 spv_operand_desc* pOperandEntry) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010071 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -040072 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010073 // NOTE: Do operand table lookup to set operandEntry if successful
74 uint16_t index = operandIndex - 1;
75 type = opcodeEntry->operandTypes[index];
76 spv_operand_desc entry = nullptr;
77 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
78 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
79 *pOperandEntry = entry;
80 }
81 }
82 } else if (*pOperandEntry) {
83 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -040084 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010085 type = (*pOperandEntry)->operandTypes[index];
Lei Zhangb36e7042015-10-28 13:40:52 -040086 } else if (SpvOpSwitch == opcodeEntry->opcode) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010087 // NOTE: OpSwitch is a special case which expects a list of paired extra
88 // operands
89 assert(0 &&
90 "This case is previously untested, remove this assert and ensure it "
91 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -040092 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010093 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
94 type = opcodeEntry->operandTypes[index];
95 } else {
96 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -040097 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010098 type = opcodeEntry->operandTypes[index];
99 }
100 return type;
101}
102
David Neto0ca6b592015-10-30 16:06:15 -0400103namespace {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100104
David Neto0ca6b592015-10-30 16:06:15 -0400105// A SPIR-V binary parser. A parser instance communicates detailed parse
106// results via callbacks.
107class Parser {
108 public:
109 // The user_data value is provided to the callbacks as context.
110 Parser(void* user_data, spv_parsed_header_fn_t parsed_header_fn,
111 spv_parsed_instruction_fn_t parsed_instruction_fn)
112 : user_data_(user_data),
113 parsed_header_fn_(parsed_header_fn),
114 parsed_instruction_fn_(parsed_instruction_fn) {}
115
116 // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
117 // header and for each parsed instruction. Returns SPV_SUCCESS on success.
118 // Otherwise returns an error code and issues a diagnostic.
119 spv_result_t parse(const uint32_t* words, size_t num_words,
120 spv_diagnostic* diagnostic);
121
122 private:
123 // All remaining methods work on the current module parse state.
124
125 // Like the parse method, but works on the current module parse state.
126 spv_result_t parseModule();
127
128 // Parses an instruction at the current position of the binary. Assumes
129 // the header has been parsed, the endian has been set, and the word index is
130 // still in range. Advances the parsing position past the instruction, and
131 // updates other parsing state for the current module.
132 // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
133 // On failure, returns an error code and issues a diagnostic.
134 spv_result_t parseInstruction();
135
136 // Parses an instruction operand with the given type.
137 // May update the expected_operands parameter, and the scalar members of the
138 // inst parameter. On success, returns SPV_SUCCESS, advances past the
139 // operand, and pushes a new entry on to the operands vector. Otherwise
140 // returns an error code and issues a diagnostic.
141 spv_result_t parseOperand(spv_parsed_instruction_t* inst,
142 const spv_operand_type_t type,
143 std::vector<spv_parsed_operand_t>* operands,
144 spv_operand_pattern_t* expected_operands);
145
146 // Records the numeric type for an operand according to the type information
147 // associated with the given non-zero type Id. This can fail if the type Id
148 // is not a type Id, or if the type Id does not reference a scalar numeric
149 // type. On success, return SPV_SUCCESS and populates the num_words,
150 // number_kind, and number_bit_width fields of parsed_operand.
151 spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
152 uint32_t type_id);
153
154 // Records the number type for an instruction if that instruction generates
155 // a type. For types that aren't scalar numbers, record something with
156 // number kind SPV_NUMBER_NONE.
157 void recordNumberType(const spv_parsed_instruction_t* inst);
158
159 // Returns a diagnostic stream object initialized with current position in
160 // the input stream, and for the given error code. Any data written to the
161 // returned object will be propagated to the current parse's diagnostic
162 // object.
163 DiagnosticStream diagnostic(spv_result_t error) {
164 return DiagnosticStream({0, 0, _.word_index}, _.diagnostic, error);
165 }
166
167 // Returns a diagnostic stream object with the default parse error code.
168 DiagnosticStream diagnostic() {
169 // The default failure for parsing is invalid binary.
170 return diagnostic(SPV_ERROR_INVALID_BINARY);
171 }
172
173 // Returns the endian-corrected word at the current position.
174 uint32_t peek() const { return peekAt(_.word_index); }
175
176 // Returns the endian-corrected word at the given position.
177 uint32_t peekAt(size_t index) const {
178 assert(index < _.num_words);
179 return spvFixWord(_.words[index], _.endian);
180 }
181
182 // Data members
183
184 const libspirv::AssemblyGrammar grammar_; // SPIR-V syntax utility.
185 void* const user_data_; // Context for the callbacks
186 const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
187 const spv_parsed_instruction_fn_t
188 parsed_instruction_fn_; // Parsed instruction callback
189
190 // Describes the format of a typed literal number.
191 struct NumberType {
192 spv_number_kind_t type;
193 uint32_t bit_width;
194 };
195
196 // The state used to parse a single SPIR-V binary module.
197 struct State {
198 State(const uint32_t* words_arg, size_t num_words_arg,
199 spv_diagnostic* diagnostic_arg)
200 : words(words_arg),
201 num_words(num_words_arg),
202 diagnostic(diagnostic_arg),
203 word_index(0),
204 endian() {}
205 State() : State(0, 0, nullptr) {}
206 const uint32_t* words; // Words in the binary SPIR-V module.
207 size_t num_words; // Number of words in the module.
208 spv_diagnostic* diagnostic; // Where diagnostics go.
209 size_t word_index; // The current position in words.
210 spv_endianness_t endian; // The endianness of the binary.
211
212 // Maps a result ID to its type ID. By convention:
213 // - a result ID that is a type definition maps to itself.
214 // - a result ID without a type maps to 0. (E.g. for OpLabel)
215 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
216 // Maps a type ID to its number type description.
217 std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
218 // Maps an ExtInstImport id to the extended instruction type.
219 std::unordered_map<uint32_t, spv_ext_inst_type_t>
220 import_id_to_ext_inst_type;
221 } _;
222};
223
224spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
225 spv_diagnostic* diagnostic_arg) {
226 _ = State(words, num_words, diagnostic_arg);
227
228 const spv_result_t result = parseModule();
229
230 // Clear the module state. The tables might be big.
231 _ = State();
232
233 return result;
234}
235
236spv_result_t Parser::parseModule() {
237 if (!_.words) return diagnostic() << "Missing module.";
238
239 if (_.num_words < SPV_INDEX_INSTRUCTION)
240 return diagnostic() << "Module has incomplete header: only " << _.num_words
241 << " words instead of " << SPV_INDEX_INSTRUCTION;
242
243 // Check the magic number and detect the module's endianness.
244 spv_binary_t binary = {_.words, _.num_words}; // Can't make this const. :-(
245 if (spvBinaryEndianness(&binary, &_.endian)) {
246 return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
247 << _.words[0] << "'.";
248 }
249
250 // Process the header.
251 spv_header_t header;
252 if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
253 // It turns out there is no way to trigger this error since the only
254 // failure cases are already handled above, with better messages.
255 return diagnostic(SPV_ERROR_INTERNAL)
256 << "Internal error: unhandled header parse failure";
257 }
258 if (parsed_header_fn_) {
259 if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
260 header.version, header.generator,
261 header.bound, header.schema)) {
262 return error;
263 }
264 }
265
266 // Process the instructions.
267 _.word_index = SPV_INDEX_INSTRUCTION;
268 while (_.word_index < _.num_words)
269 if (auto error = parseInstruction()) return error;
270
271 // Running off the end should already have been reported earlier.
272 assert(_.word_index == _.num_words);
273
274 return SPV_SUCCESS;
275}
276
277spv_result_t Parser::parseInstruction() {
278 // The zero values for all members except for opcode are the
279 // correct initial values.
280 spv_parsed_instruction_t inst = {};
281 inst.offset = _.word_index;
282
283 // After a successful parse of the instruction, the inst.operands member
284 // will point to this vector's storage.
285 // TODO(dneto): If it's too expensive to construct the operands vector for
286 // each instruction, then make this a class data member instead, and clear it
287 // here.
288 std::vector<spv_parsed_operand_t> operands;
289 // Most instructions have fewer than 25 logical operands.
290 operands.reserve(25);
291
292 assert(_.word_index < _.num_words);
293 // Decompose and check the first word.
294 uint16_t inst_word_count = 0;
295 spvOpcodeSplit(peek(), &inst_word_count, &inst.opcode);
296 if (inst_word_count < 1) {
297 return diagnostic() << "Invalid instruction word count: "
298 << inst_word_count;
299 }
300 spv_opcode_desc opcode_desc;
301 if (grammar_.lookupOpcode(inst.opcode, &opcode_desc))
302 return diagnostic() << "Invalid opcode: " << int(inst.opcode);
303
304 _.word_index++;
305
306 // Maintains the ordered list of expected operand types.
307 // For many instructions we only need the {numTypes, operandTypes}
308 // entries in opcode_desc. However, sometimes we need to modify
309 // the list as we parse the operands. This occurs when an operand
310 // has its own logical operands (such as the LocalSize operand for
311 // ExecutionMode), or for extended instructions that may have their
312 // own operands depending on the selected extended instruction.
313 spv_operand_pattern_t expected_operands(
314 opcode_desc->operandTypes,
315 opcode_desc->operandTypes + opcode_desc->numTypes);
316
317 while (_.word_index < inst.offset + inst_word_count) {
318 const uint16_t inst_word_index = _.word_index - inst.offset;
319 if (expected_operands.empty()) {
320 return diagnostic() << "Invalid instruction Op" << opcode_desc->name
321 << " starting at word " << inst.offset
322 << ": expected no more operands after "
323 << inst_word_index
324 << " words, but stated word count is "
325 << inst_word_count << ".";
326 }
327
328 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expected_operands);
329
330 if (auto error = parseOperand(&inst, type, &operands, &expected_operands))
331 return error;
332 }
333
334 if (!expected_operands.empty() &&
335 !spvOperandIsOptional(expected_operands.front())) {
336 return diagnostic() << "End of input reached while decoding Op"
337 << opcode_desc->name << " starting at word "
338 << inst.offset << ": expected more operands after "
339 << inst_word_count << " words.";
340 }
341
342 if ((inst.offset + inst_word_count) != _.word_index) {
343 return diagnostic() << "Invalid word count: Instruction starting at word "
344 << inst.offset << " says it has " << inst_word_count
345 << " words, but found " << _.word_index - inst.offset
346 << " words instead.";
347 }
348
349 recordNumberType(&inst);
350
351 // Must wait until here to set the inst.operands pointer because the vector
352 // might be resized while we accumulate itse elements.
353 inst.operands = operands.data();
354 inst.num_operands = operands.size();
355
356 // Issue the callback. The callee should know that all the storage in inst
357 // is transient, and will disappear immediately afterward.
358 if (parsed_instruction_fn_) {
359 if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
360 }
361
362 return SPV_SUCCESS;
363}
364
365spv_result_t Parser::parseOperand(spv_parsed_instruction_t* inst,
366 const spv_operand_type_t type,
367 std::vector<spv_parsed_operand_t>* operands,
368 spv_operand_pattern_t* expected_operands) {
369 // We'll fill in this result as we go along.
370 spv_parsed_operand_t parsed_operand;
371 parsed_operand.offset = _.word_index - inst->offset;
372 // Most operands occupy one word. This might be be adjusted later.
373 parsed_operand.num_words = 1;
374 // The type argument is the one used by the grammar to parse the instruction.
375 // But it can exposes internal parser details such as whether an operand is
376 // optional or actually represents a variable-length sequence of operands.
377 // The resulting type should be adjusted to avoid those internal details.
378 // In most cases, the resulting operand type is the same as the grammar type.
379 parsed_operand.type = type;
380
381 // Assume non-numeric values. This will be updated for literal numbers.
382 parsed_operand.number_kind = SPV_NUMBER_NONE;
383 parsed_operand.number_bit_width = 0;
384
385 const uint32_t word = peek();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100386
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100387 switch (type) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400388 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto0ca6b592015-10-30 16:06:15 -0400389 if (!word) return diagnostic() << "Error: Type Id is 0";
390 inst->type_id = word;
391 break;
392
393 case SPV_OPERAND_TYPE_RESULT_ID:
394 if (!word) return diagnostic() << "Error: Result Id is 0";
395 inst->result_id = word;
396 // Save the result ID to type ID mapping.
397 // In the grammar, type ID always appears before result ID.
398 if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
399 return diagnostic() << "Id " << inst->result_id
400 << " is defined more than once";
401 // Record it.
402 // A regular value maps to its type. Some instructions (e.g. OpLabel)
403 // have no type Id, and will map to 0. The result Id for a
404 // type-generating instruction (e.g. OpTypeInt) maps to itself.
405 _.id_to_type_id[inst->result_id] = spvOpcodeGeneratesType(inst->opcode)
406 ? inst->result_id
407 : inst->type_id;
408 break;
409
410 case SPV_OPERAND_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400411 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400412 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Neto0ca6b592015-10-30 16:06:15 -0400413 if (!word) return diagnostic() << "Id is 0";
414 parsed_operand.type = SPV_OPERAND_TYPE_ID;
415
416 if (inst->opcode == SpvOpExtInst && parsed_operand.offset == 3) {
417 // The current word is the extended instruction set Id.
418 // Set the extended instruction set type for the current instruction.
419 auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
420 if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
421 return diagnostic()
422 << "OpExtInst set Id " << word
423 << " does not reference an OpExtInstImport result Id";
424 }
425 inst->ext_inst_type = ext_inst_type_iter->second;
426 }
427 break;
428
429 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Netob14a7272015-09-25 13:56:09 -0400430 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
David Neto0ca6b592015-10-30 16:06:15 -0400431 if (!word) return diagnostic() << spvOperandTypeStr(type) << " Id is 0";
432 break;
433
David Neto445ce442015-10-15 15:22:06 -0400434 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
David Neto0ca6b592015-10-30 16:06:15 -0400435 assert(SpvOpExtInst == inst->opcode);
436 assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
437 spv_ext_inst_desc ext_inst;
438 if (grammar_.lookupExtInst(inst->ext_inst_type, word, &ext_inst))
439 return diagnostic() << "Invalid extended instruction number: " << word;
440 spvPrependOperandTypes(ext_inst->operandTypes, expected_operands);
David Neto445ce442015-10-15 15:22:06 -0400441 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400442
David Neto445ce442015-10-15 15:22:06 -0400443 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400444 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
David Neto0ca6b592015-10-30 16:06:15 -0400445 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE:
446 // TODO(dneto): Type checking and validation?
447 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
448 if (inst->opcode == SpvOpSwitch) {
449 // The literal operands have the same type as the value
450 // referenced by the selector Id.
451 const uint32_t selector_id = peekAt(inst->offset + 1);
452 auto type_id_iter = _.id_to_type_id.find(selector_id);
453 if (type_id_iter == _.id_to_type_id.end()) {
454 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
455 << " has no type";
456 }
457 uint32_t type_id = type_id_iter->second;
458
459 if (selector_id == type_id) {
460 // Recall that by convention, a result ID that is a type definition
461 // maps to itself.
462 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
463 << " is a type, not a value";
464 }
465 if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
466 return error;
467 if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
468 parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
469 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
470 << " is not a scalar integer";
471 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400472 } else {
David Neto0ca6b592015-10-30 16:06:15 -0400473 // These are regular single-word literal integer operands.
474 // Post-parsing validation should check the range.
475 parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
476 parsed_operand.number_bit_width = 32;
Lei Zhangb41d1502015-09-14 15:22:23 -0400477 }
David Neto0ca6b592015-10-30 16:06:15 -0400478 break;
479
480 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
481 // TODO(dneto): Consider creating a SPV_OPERAND_TYPE_LITERAL_FLOATING
482 // for the floating point OpConstant/OpSpecConstant case.
483 assert(inst->opcode == SpvOpConstant ||
484 inst->opcode == SpvOpSpecConstant);
485 if (auto error =
486 setNumericTypeInfoForType(&parsed_operand, inst->type_id))
487 return error;
488 break;
489
David Neto78c3b432015-08-27 13:03:52 -0400490 case SPV_OPERAND_TYPE_LITERAL_STRING:
491 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
David Neto0ca6b592015-10-30 16:06:15 -0400492 // TODO(dneto): Make and use spvFixupString();
493 const char* string =
494 reinterpret_cast<const char*>(_.words + _.word_index);
495 size_t string_num_words = (strlen(string) / 4) + 1; // Account for null.
496 // Make sure we can record the word count without overflow.
497 // We still might have a string that's 64K words, but would still
498 // make the instruction too long because of earlier operands.
499 // That will be caught later at the end of the instruciton.
500 if (string_num_words > std::numeric_limits<uint16_t>::max()) {
501 return diagnostic() << "Literal string is longer than "
502 << std::numeric_limits<uint16_t>::max()
503 << " words: " << string_num_words << " words long";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100504 }
David Neto0ca6b592015-10-30 16:06:15 -0400505 parsed_operand.num_words = string_num_words;
506 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100507
David Neto0ca6b592015-10-30 16:06:15 -0400508 if (SpvOpExtInstImport == inst->opcode) {
509 // Record the extended instruction type for the ID for this import.
510 // There is only one string literal argument to OpExtInstImport,
511 // so it's sufficient to guard this just on the opcode.
512 const spv_ext_inst_type_t ext_inst_type =
513 spvExtInstImportTypeGet(string);
514 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
515 return diagnostic() << "Invalid extended instruction import '"
516 << string << "'";
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400517 }
David Neto0ca6b592015-10-30 16:06:15 -0400518 // We must have parsed a valid result ID. It's a condition
519 // of the grammar, and we only accept non-zero result Ids.
520 assert(inst->result_id);
521 _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400522 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100523 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400524
525 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
526 parsed_operand.type = SPV_OPERAND_TYPE_EXECUTION_MODE;
527 // Fall through
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100528 case SPV_OPERAND_TYPE_CAPABILITY:
529 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
530 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
531 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
532 case SPV_OPERAND_TYPE_MEMORY_MODEL:
533 case SPV_OPERAND_TYPE_EXECUTION_MODE:
534 case SPV_OPERAND_TYPE_STORAGE_CLASS:
535 case SPV_OPERAND_TYPE_DIMENSIONALITY:
536 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
537 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100538 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
539 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
540 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
541 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
542 case SPV_OPERAND_TYPE_DECORATION:
543 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100544 case SPV_OPERAND_TYPE_GROUP_OPERATION:
545 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400546 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
David Neto0ca6b592015-10-30 16:06:15 -0400547 // A single word that is a plain enum value.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100548 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400549 if (grammar_.lookupOperand(type, word, &entry)) {
550 return diagnostic() << "Invalid " << spvOperandTypeStr(type)
551 << " operand: " << word;
Lei Zhang40056702015-09-11 14:31:27 -0400552 }
David Neto78c3b432015-08-27 13:03:52 -0400553 // Prepare to accept operands to this operand, if needed.
David Neto0ca6b592015-10-30 16:06:15 -0400554 spvPrependOperandTypes(entry->operandTypes, expected_operands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100555 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400556
David Neto619db262015-09-25 12:43:37 -0400557 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
558 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
559 case SPV_OPERAND_TYPE_LOOP_CONTROL:
560 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
561 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
562 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
563 // This operand is a mask.
David Neto0ca6b592015-10-30 16:06:15 -0400564 // Check validity of set mask bits. Also prepare for operands for those
565 // masks if they have any. To get operand order correct, scan from
566 // MSB to LSB since we can only prepend operands to a pattern.
567 // The only case in the grammar where you have more than one mask bit
568 // having an operand is for image operands. See SPIR-V 3.14 Image
569 // Operands.
570 uint32_t remaining_word = word;
571 for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
David Neto619db262015-09-25 12:43:37 -0400572 if (remaining_word & mask) {
David Neto619db262015-09-25 12:43:37 -0400573 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400574 if (grammar_.lookupOperand(type, mask, &entry)) {
575 return diagnostic() << "Invalid " << spvOperandTypeStr(type)
576 << " operand: " << word
577 << " has invalid mask component " << mask;
David Neto619db262015-09-25 12:43:37 -0400578 }
David Neto0ca6b592015-10-30 16:06:15 -0400579 remaining_word ^= mask;
580 spvPrependOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400581 }
582 }
David Neto0ca6b592015-10-30 16:06:15 -0400583 if (word == 0) {
584 // An all-zeroes mask *might* also be valid.
David Neto619db262015-09-25 12:43:37 -0400585 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400586 if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400587 // Prepare for its operands, if any.
David Neto0ca6b592015-10-30 16:06:15 -0400588 spvPrependOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400589 }
590 }
David Neto619db262015-09-25 12:43:37 -0400591 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400592 default:
593 return diagnostic() << "Internal error: Unhandled operand type: " << type;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100594 }
595
David Neto0ca6b592015-10-30 16:06:15 -0400596 assert(int(SPV_OPERAND_TYPE_FIRST_CONCRETE_TYPE) <= int(parsed_operand.type));
597 assert(int(SPV_OPERAND_TYPE_LAST_CONCRETE_TYPE) >= int(parsed_operand.type));
598
599 operands->push_back(parsed_operand);
600
601 _.word_index += parsed_operand.num_words;
602
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100603 return SPV_SUCCESS;
604}
605
David Neto0ca6b592015-10-30 16:06:15 -0400606spv_result_t Parser::setNumericTypeInfoForType(
607 spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
608 assert(type_id);
609 auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
610 if (type_info_iter == _.type_id_to_number_type_info.end()) {
611 return diagnostic() << "Type Id " << type_id << " is not a type";
612 }
613 const NumberType& info = type_info_iter->second;
614 if (info.type == SPV_NUMBER_NONE) {
615 // This is a valid type, but for something other than a scalar number.
616 return diagnostic() << "Type Id " << type_id
617 << " is not a scalar numeric type";
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400618 }
619
David Neto0ca6b592015-10-30 16:06:15 -0400620 parsed_operand->number_kind = info.type;
621 parsed_operand->number_bit_width = info.bit_width;
622 parsed_operand->num_words = info.bit_width / 32;
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400623 return SPV_SUCCESS;
624}
625
David Neto0ca6b592015-10-30 16:06:15 -0400626void Parser::recordNumberType(const spv_parsed_instruction_t* inst) {
627 if (spvOpcodeGeneratesType(inst->opcode)) {
628 NumberType info = {SPV_NUMBER_NONE, 0};
629 if (SpvOpTypeInt == inst->opcode) {
630 const bool is_signed = peekAt(inst->offset + 3) != 0;
631 info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
632 info.bit_width = peekAt(inst->offset + 2);
633 } else if (SpvOpTypeFloat == inst->opcode) {
634 info.type = SPV_NUMBER_FLOATING;
635 info.bit_width = peekAt(inst->offset + 2);
Lei Zhang40056702015-09-11 14:31:27 -0400636 }
David Neto0ca6b592015-10-30 16:06:15 -0400637 // The *result* Id of a type generating instruction is the type Id.
638 _.type_id_to_number_type_info[inst->result_id] = info;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100639 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100640}
641
David Neto0ca6b592015-10-30 16:06:15 -0400642} // anonymous namespace
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400643
David Neto0ca6b592015-10-30 16:06:15 -0400644spv_result_t spvBinaryParse(void* user_data, const uint32_t* const code,
645 const size_t num_words,
646 spv_parsed_header_fn_t parsed_header,
647 spv_parsed_instruction_fn_t parsed_instruction,
648 spv_diagnostic* diagnostic) {
649 Parser parser(user_data, parsed_header, parsed_instruction);
650 return parser.parse(code, num_words, diagnostic);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100651}
652
David Neto0ca6b592015-10-30 16:06:15 -0400653// TODO(dneto): This probably belongs in text.cpp since that's the only place
654// that a spv_binary_t value is created.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100655void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400656 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100657 if (binary->code) {
658 delete[] binary->code;
659 }
660 delete binary;
661}