blob: 062eaddeb11fa6d1f41abb574a464f0fbeacbcb2 [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
David Netofcc7d582015-10-27 15:31:10 -040034#include "assembly_grammar.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010035#include "diagnostic.h"
David Netodb901b62015-10-27 16:14:40 -040036#include "endian.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010037#include "ext_inst.h"
Lei Zhang923f6c12015-11-11 12:45:23 -050038#include "libspirv/libspirv.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010039#include "opcode.h"
40#include "operand.h"
Lei Zhangaa056cd2015-11-11 14:24:04 -050041#include "spirv_constant.h"
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040042
Andrew Woloszyn55ecc2e2015-11-11 11:05:07 -050043spv_result_t spvBinaryHeaderGet(const spv_const_binary binary,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010044 const spv_endianness_t endian,
Lei Zhang1a0334e2015-11-02 09:41:20 -050045 spv_header_t* pHeader) {
David Neto0ca6b592015-10-30 16:06:15 -040046 if (!binary->code) return SPV_ERROR_INVALID_BINARY;
47 if (binary->wordCount < SPV_INDEX_INSTRUCTION)
48 return SPV_ERROR_INVALID_BINARY;
Lei Zhang40056702015-09-11 14:31:27 -040049 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010050
51 // TODO: Validation checking?
52 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
53 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
54 pHeader->generator =
55 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
56 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
57 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
58 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
59
60 return SPV_SUCCESS;
61}
62
David Neto78c3b432015-08-27 13:03:52 -040063// TODO(dneto): This API is not powerful enough in the case that the
64// number and type of operands are not known until partway through parsing
65// the operation. This happens when enum operands might have different number
66// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010067spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
68 const uint16_t operandIndex,
69 const spv_opcode_desc opcodeEntry,
70 const spv_operand_table operandTable,
Lei Zhang1a0334e2015-11-02 09:41:20 -050071 spv_operand_desc* pOperandEntry) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010072 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -040073 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010074 // NOTE: Do operand table lookup to set operandEntry if successful
75 uint16_t index = operandIndex - 1;
76 type = opcodeEntry->operandTypes[index];
77 spv_operand_desc entry = nullptr;
78 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
79 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
80 *pOperandEntry = entry;
81 }
82 }
83 } else if (*pOperandEntry) {
84 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -040085 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010086 type = (*pOperandEntry)->operandTypes[index];
Lei Zhangb36e7042015-10-28 13:40:52 -040087 } else if (SpvOpSwitch == opcodeEntry->opcode) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010088 // NOTE: OpSwitch is a special case which expects a list of paired extra
89 // operands
90 assert(0 &&
91 "This case is previously untested, remove this assert and ensure it "
92 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -040093 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010094 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
95 type = opcodeEntry->operandTypes[index];
96 } else {
97 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -040098 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010099 type = opcodeEntry->operandTypes[index];
100 }
101 return type;
102}
103
David Neto0ca6b592015-10-30 16:06:15 -0400104namespace {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100105
David Neto0ca6b592015-10-30 16:06:15 -0400106// A SPIR-V binary parser. A parser instance communicates detailed parse
107// results via callbacks.
108class Parser {
109 public:
110 // The user_data value is provided to the callbacks as context.
111 Parser(void* user_data, spv_parsed_header_fn_t parsed_header_fn,
112 spv_parsed_instruction_fn_t parsed_instruction_fn)
113 : user_data_(user_data),
114 parsed_header_fn_(parsed_header_fn),
115 parsed_instruction_fn_(parsed_instruction_fn) {}
116
117 // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
118 // header and for each parsed instruction. Returns SPV_SUCCESS on success.
119 // Otherwise returns an error code and issues a diagnostic.
120 spv_result_t parse(const uint32_t* words, size_t num_words,
121 spv_diagnostic* diagnostic);
122
123 private:
124 // All remaining methods work on the current module parse state.
125
126 // Like the parse method, but works on the current module parse state.
127 spv_result_t parseModule();
128
129 // Parses an instruction at the current position of the binary. Assumes
130 // the header has been parsed, the endian has been set, and the word index is
131 // still in range. Advances the parsing position past the instruction, and
132 // updates other parsing state for the current module.
133 // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
134 // On failure, returns an error code and issues a diagnostic.
135 spv_result_t parseInstruction();
136
137 // Parses an instruction operand with the given type.
138 // May update the expected_operands parameter, and the scalar members of the
139 // inst parameter. On success, returns SPV_SUCCESS, advances past the
140 // operand, and pushes a new entry on to the operands vector. Otherwise
141 // returns an error code and issues a diagnostic.
142 spv_result_t parseOperand(spv_parsed_instruction_t* inst,
143 const spv_operand_type_t type,
144 std::vector<spv_parsed_operand_t>* operands,
145 spv_operand_pattern_t* expected_operands);
146
147 // Records the numeric type for an operand according to the type information
148 // associated with the given non-zero type Id. This can fail if the type Id
149 // is not a type Id, or if the type Id does not reference a scalar numeric
150 // type. On success, return SPV_SUCCESS and populates the num_words,
151 // number_kind, and number_bit_width fields of parsed_operand.
152 spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
153 uint32_t type_id);
154
155 // Records the number type for an instruction if that instruction generates
156 // a type. For types that aren't scalar numbers, record something with
157 // number kind SPV_NUMBER_NONE.
158 void recordNumberType(const spv_parsed_instruction_t* inst);
159
160 // Returns a diagnostic stream object initialized with current position in
161 // the input stream, and for the given error code. Any data written to the
162 // returned object will be propagated to the current parse's diagnostic
163 // object.
164 DiagnosticStream diagnostic(spv_result_t error) {
165 return DiagnosticStream({0, 0, _.word_index}, _.diagnostic, error);
166 }
167
168 // Returns a diagnostic stream object with the default parse error code.
169 DiagnosticStream diagnostic() {
170 // The default failure for parsing is invalid binary.
171 return diagnostic(SPV_ERROR_INVALID_BINARY);
172 }
173
174 // Returns the endian-corrected word at the current position.
175 uint32_t peek() const { return peekAt(_.word_index); }
176
177 // Returns the endian-corrected word at the given position.
178 uint32_t peekAt(size_t index) const {
179 assert(index < _.num_words);
180 return spvFixWord(_.words[index], _.endian);
181 }
182
183 // Data members
184
185 const libspirv::AssemblyGrammar grammar_; // SPIR-V syntax utility.
186 void* const user_data_; // Context for the callbacks
187 const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
188 const spv_parsed_instruction_fn_t
189 parsed_instruction_fn_; // Parsed instruction callback
190
191 // Describes the format of a typed literal number.
192 struct NumberType {
193 spv_number_kind_t type;
194 uint32_t bit_width;
195 };
196
197 // The state used to parse a single SPIR-V binary module.
198 struct State {
199 State(const uint32_t* words_arg, size_t num_words_arg,
200 spv_diagnostic* diagnostic_arg)
201 : words(words_arg),
202 num_words(num_words_arg),
203 diagnostic(diagnostic_arg),
204 word_index(0),
205 endian() {}
206 State() : State(0, 0, nullptr) {}
207 const uint32_t* words; // Words in the binary SPIR-V module.
208 size_t num_words; // Number of words in the module.
209 spv_diagnostic* diagnostic; // Where diagnostics go.
210 size_t word_index; // The current position in words.
211 spv_endianness_t endian; // The endianness of the binary.
212
213 // Maps a result ID to its type ID. By convention:
214 // - a result ID that is a type definition maps to itself.
215 // - a result ID without a type maps to 0. (E.g. for OpLabel)
216 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
217 // Maps a type ID to its number type description.
218 std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
219 // Maps an ExtInstImport id to the extended instruction type.
220 std::unordered_map<uint32_t, spv_ext_inst_type_t>
221 import_id_to_ext_inst_type;
222 } _;
223};
224
225spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
226 spv_diagnostic* diagnostic_arg) {
227 _ = State(words, num_words, diagnostic_arg);
228
229 const spv_result_t result = parseModule();
230
231 // Clear the module state. The tables might be big.
232 _ = State();
233
234 return result;
235}
236
237spv_result_t Parser::parseModule() {
238 if (!_.words) return diagnostic() << "Missing module.";
239
240 if (_.num_words < SPV_INDEX_INSTRUCTION)
241 return diagnostic() << "Module has incomplete header: only " << _.num_words
242 << " words instead of " << SPV_INDEX_INSTRUCTION;
243
244 // Check the magic number and detect the module's endianness.
Andrew Woloszyn55ecc2e2015-11-11 11:05:07 -0500245 spv_const_binary_t binary{_.words, _.num_words};
David Neto0ca6b592015-10-30 16:06:15 -0400246 if (spvBinaryEndianness(&binary, &_.endian)) {
247 return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
248 << _.words[0] << "'.";
249 }
250
251 // Process the header.
252 spv_header_t header;
253 if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
254 // It turns out there is no way to trigger this error since the only
255 // failure cases are already handled above, with better messages.
256 return diagnostic(SPV_ERROR_INTERNAL)
257 << "Internal error: unhandled header parse failure";
258 }
259 if (parsed_header_fn_) {
260 if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
261 header.version, header.generator,
262 header.bound, header.schema)) {
263 return error;
264 }
265 }
266
267 // Process the instructions.
268 _.word_index = SPV_INDEX_INSTRUCTION;
269 while (_.word_index < _.num_words)
270 if (auto error = parseInstruction()) return error;
271
272 // Running off the end should already have been reported earlier.
273 assert(_.word_index == _.num_words);
274
275 return SPV_SUCCESS;
276}
277
278spv_result_t Parser::parseInstruction() {
279 // The zero values for all members except for opcode are the
280 // correct initial values.
281 spv_parsed_instruction_t inst = {};
282 inst.offset = _.word_index;
283
284 // After a successful parse of the instruction, the inst.operands member
285 // will point to this vector's storage.
286 // TODO(dneto): If it's too expensive to construct the operands vector for
287 // each instruction, then make this a class data member instead, and clear it
288 // here.
289 std::vector<spv_parsed_operand_t> operands;
290 // Most instructions have fewer than 25 logical operands.
291 operands.reserve(25);
292
293 assert(_.word_index < _.num_words);
294 // Decompose and check the first word.
295 uint16_t inst_word_count = 0;
296 spvOpcodeSplit(peek(), &inst_word_count, &inst.opcode);
297 if (inst_word_count < 1) {
298 return diagnostic() << "Invalid instruction word count: "
299 << inst_word_count;
300 }
301 spv_opcode_desc opcode_desc;
302 if (grammar_.lookupOpcode(inst.opcode, &opcode_desc))
303 return diagnostic() << "Invalid opcode: " << int(inst.opcode);
304
305 _.word_index++;
306
307 // Maintains the ordered list of expected operand types.
308 // For many instructions we only need the {numTypes, operandTypes}
309 // entries in opcode_desc. However, sometimes we need to modify
310 // the list as we parse the operands. This occurs when an operand
311 // has its own logical operands (such as the LocalSize operand for
312 // ExecutionMode), or for extended instructions that may have their
313 // own operands depending on the selected extended instruction.
314 spv_operand_pattern_t expected_operands(
315 opcode_desc->operandTypes,
316 opcode_desc->operandTypes + opcode_desc->numTypes);
317
318 while (_.word_index < inst.offset + inst_word_count) {
319 const uint16_t inst_word_index = _.word_index - inst.offset;
320 if (expected_operands.empty()) {
321 return diagnostic() << "Invalid instruction Op" << opcode_desc->name
322 << " starting at word " << inst.offset
323 << ": expected no more operands after "
324 << inst_word_index
325 << " words, but stated word count is "
326 << inst_word_count << ".";
327 }
328
329 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expected_operands);
330
331 if (auto error = parseOperand(&inst, type, &operands, &expected_operands))
332 return error;
333 }
334
335 if (!expected_operands.empty() &&
336 !spvOperandIsOptional(expected_operands.front())) {
337 return diagnostic() << "End of input reached while decoding Op"
338 << opcode_desc->name << " starting at word "
339 << inst.offset << ": expected more operands after "
340 << inst_word_count << " words.";
341 }
342
343 if ((inst.offset + inst_word_count) != _.word_index) {
344 return diagnostic() << "Invalid word count: Instruction starting at word "
345 << inst.offset << " says it has " << inst_word_count
346 << " words, but found " << _.word_index - inst.offset
347 << " words instead.";
348 }
349
350 recordNumberType(&inst);
351
352 // Must wait until here to set the inst.operands pointer because the vector
353 // might be resized while we accumulate itse elements.
354 inst.operands = operands.data();
355 inst.num_operands = operands.size();
356
357 // Issue the callback. The callee should know that all the storage in inst
358 // is transient, and will disappear immediately afterward.
359 if (parsed_instruction_fn_) {
360 if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
361 }
362
363 return SPV_SUCCESS;
364}
365
366spv_result_t Parser::parseOperand(spv_parsed_instruction_t* inst,
367 const spv_operand_type_t type,
368 std::vector<spv_parsed_operand_t>* operands,
369 spv_operand_pattern_t* expected_operands) {
370 // We'll fill in this result as we go along.
371 spv_parsed_operand_t parsed_operand;
372 parsed_operand.offset = _.word_index - inst->offset;
373 // Most operands occupy one word. This might be be adjusted later.
374 parsed_operand.num_words = 1;
375 // The type argument is the one used by the grammar to parse the instruction.
376 // But it can exposes internal parser details such as whether an operand is
377 // optional or actually represents a variable-length sequence of operands.
378 // The resulting type should be adjusted to avoid those internal details.
379 // In most cases, the resulting operand type is the same as the grammar type.
380 parsed_operand.type = type;
381
382 // Assume non-numeric values. This will be updated for literal numbers.
383 parsed_operand.number_kind = SPV_NUMBER_NONE;
384 parsed_operand.number_bit_width = 0;
385
386 const uint32_t word = peek();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100387
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100388 switch (type) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400389 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto0ca6b592015-10-30 16:06:15 -0400390 if (!word) return diagnostic() << "Error: Type Id is 0";
391 inst->type_id = word;
392 break;
393
394 case SPV_OPERAND_TYPE_RESULT_ID:
395 if (!word) return diagnostic() << "Error: Result Id is 0";
396 inst->result_id = word;
397 // Save the result ID to type ID mapping.
398 // In the grammar, type ID always appears before result ID.
399 if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
400 return diagnostic() << "Id " << inst->result_id
401 << " is defined more than once";
402 // Record it.
403 // A regular value maps to its type. Some instructions (e.g. OpLabel)
404 // have no type Id, and will map to 0. The result Id for a
405 // type-generating instruction (e.g. OpTypeInt) maps to itself.
406 _.id_to_type_id[inst->result_id] = spvOpcodeGeneratesType(inst->opcode)
407 ? inst->result_id
408 : inst->type_id;
409 break;
410
411 case SPV_OPERAND_TYPE_ID:
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 Neto21196942015-11-11 02:45:45 -0500443 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
444 assert(SpvOpSpecConstantOp == inst->opcode);
445 if (grammar_.lookupSpecConstantOpcode(SpvOp(word))) {
446 return diagnostic() << "Invalid " << spvOperandTypeStr(type) << ": "
447 << word;
448 }
449 spv_opcode_desc opcode_entry = nullptr;
450 if (grammar_.lookupOpcode(SpvOp(word), &opcode_entry)) {
451 return diagnostic(SPV_ERROR_INTERNAL)
452 << "OpSpecConstant opcode table out of sync";
453 }
454 // OpSpecConstant opcodes must have a type and result. We've already
455 // processed them, so skip them when preparing to parse the other
456 // operants for the opcode.
457 assert(opcode_entry->hasType);
458 assert(opcode_entry->hasResult);
459 assert(opcode_entry->numTypes >= 2);
460 spvPrependOperandTypes(opcode_entry->operandTypes + 2, expected_operands);
461 } break;
462
David Neto445ce442015-10-15 15:22:06 -0400463 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400464 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
David Neto201caf72015-11-04 17:38:17 -0500465 // These are regular single-word literal integer operands.
466 // Post-parsing validation should check the range of the parsed value.
David Neto0ca6b592015-10-30 16:06:15 -0400467 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
David Neto201caf72015-11-04 17:38:17 -0500468 // It turns out they are always unsigned integers!
469 parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
470 parsed_operand.number_bit_width = 32;
471 break;
472
473 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
474 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
Lei Zhangaa3cd5a2015-11-10 14:29:35 -0500475 parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
David Neto0ca6b592015-10-30 16:06:15 -0400476 if (inst->opcode == SpvOpSwitch) {
477 // The literal operands have the same type as the value
478 // referenced by the selector Id.
479 const uint32_t selector_id = peekAt(inst->offset + 1);
480 auto type_id_iter = _.id_to_type_id.find(selector_id);
481 if (type_id_iter == _.id_to_type_id.end()) {
482 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
483 << " has no type";
484 }
485 uint32_t type_id = type_id_iter->second;
486
487 if (selector_id == type_id) {
488 // Recall that by convention, a result ID that is a type definition
489 // maps to itself.
490 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
491 << " is a type, not a value";
492 }
493 if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
494 return error;
495 if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
496 parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
497 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
498 << " is not a scalar integer";
499 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400500 } else {
David Neto201caf72015-11-04 17:38:17 -0500501 assert(inst->opcode == SpvOpConstant ||
502 inst->opcode == SpvOpSpecConstant);
503 // The literal number type is determined by the type Id for the
504 // constant.
505 assert(inst->type_id);
506 if (auto error =
507 setNumericTypeInfoForType(&parsed_operand, inst->type_id))
508 return error;
Lei Zhangb41d1502015-09-14 15:22:23 -0400509 }
David Neto0ca6b592015-10-30 16:06:15 -0400510 break;
511
David Neto78c3b432015-08-27 13:03:52 -0400512 case SPV_OPERAND_TYPE_LITERAL_STRING:
513 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
David Neto0ca6b592015-10-30 16:06:15 -0400514 // TODO(dneto): Make and use spvFixupString();
515 const char* string =
516 reinterpret_cast<const char*>(_.words + _.word_index);
517 size_t string_num_words = (strlen(string) / 4) + 1; // Account for null.
518 // Make sure we can record the word count without overflow.
519 // We still might have a string that's 64K words, but would still
520 // make the instruction too long because of earlier operands.
521 // That will be caught later at the end of the instruciton.
522 if (string_num_words > std::numeric_limits<uint16_t>::max()) {
523 return diagnostic() << "Literal string is longer than "
524 << std::numeric_limits<uint16_t>::max()
525 << " words: " << string_num_words << " words long";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100526 }
David Neto0ca6b592015-10-30 16:06:15 -0400527 parsed_operand.num_words = string_num_words;
528 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100529
David Neto0ca6b592015-10-30 16:06:15 -0400530 if (SpvOpExtInstImport == inst->opcode) {
531 // Record the extended instruction type for the ID for this import.
532 // There is only one string literal argument to OpExtInstImport,
533 // so it's sufficient to guard this just on the opcode.
534 const spv_ext_inst_type_t ext_inst_type =
535 spvExtInstImportTypeGet(string);
536 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
537 return diagnostic() << "Invalid extended instruction import '"
538 << string << "'";
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400539 }
David Neto0ca6b592015-10-30 16:06:15 -0400540 // We must have parsed a valid result ID. It's a condition
541 // of the grammar, and we only accept non-zero result Ids.
542 assert(inst->result_id);
543 _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400544 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100545 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400546
547 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
548 parsed_operand.type = SPV_OPERAND_TYPE_EXECUTION_MODE;
549 // Fall through
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100550 case SPV_OPERAND_TYPE_CAPABILITY:
551 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
552 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
553 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
554 case SPV_OPERAND_TYPE_MEMORY_MODEL:
555 case SPV_OPERAND_TYPE_EXECUTION_MODE:
556 case SPV_OPERAND_TYPE_STORAGE_CLASS:
557 case SPV_OPERAND_TYPE_DIMENSIONALITY:
558 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
559 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100560 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
561 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
562 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
563 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
564 case SPV_OPERAND_TYPE_DECORATION:
565 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100566 case SPV_OPERAND_TYPE_GROUP_OPERATION:
567 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400568 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
David Neto0ca6b592015-10-30 16:06:15 -0400569 // A single word that is a plain enum value.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100570 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400571 if (grammar_.lookupOperand(type, word, &entry)) {
David Neto201caf72015-11-04 17:38:17 -0500572 return diagnostic() << "Invalid "
573 << spvOperandTypeStr(parsed_operand.type)
David Neto0ca6b592015-10-30 16:06:15 -0400574 << " operand: " << word;
Lei Zhang40056702015-09-11 14:31:27 -0400575 }
David Neto78c3b432015-08-27 13:03:52 -0400576 // Prepare to accept operands to this operand, if needed.
David Neto0ca6b592015-10-30 16:06:15 -0400577 spvPrependOperandTypes(entry->operandTypes, expected_operands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100578 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400579
David Neto619db262015-09-25 12:43:37 -0400580 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
581 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
582 case SPV_OPERAND_TYPE_LOOP_CONTROL:
583 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
584 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
585 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
586 // This operand is a mask.
David Neto201caf72015-11-04 17:38:17 -0500587
588 // Map an optional operand type to its corresponding concrete type.
589 if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
590 parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
591 else if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
592 parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
593
David Neto0ca6b592015-10-30 16:06:15 -0400594 // Check validity of set mask bits. Also prepare for operands for those
595 // masks if they have any. To get operand order correct, scan from
596 // MSB to LSB since we can only prepend operands to a pattern.
597 // The only case in the grammar where you have more than one mask bit
598 // having an operand is for image operands. See SPIR-V 3.14 Image
599 // Operands.
600 uint32_t remaining_word = word;
601 for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
David Neto619db262015-09-25 12:43:37 -0400602 if (remaining_word & mask) {
David Neto619db262015-09-25 12:43:37 -0400603 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400604 if (grammar_.lookupOperand(type, mask, &entry)) {
David Neto201caf72015-11-04 17:38:17 -0500605 return diagnostic()
606 << "Invalid " << spvOperandTypeStr(parsed_operand.type)
607 << " operand: " << word << " has invalid mask component "
608 << mask;
David Neto619db262015-09-25 12:43:37 -0400609 }
David Neto0ca6b592015-10-30 16:06:15 -0400610 remaining_word ^= mask;
611 spvPrependOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400612 }
613 }
David Neto0ca6b592015-10-30 16:06:15 -0400614 if (word == 0) {
615 // An all-zeroes mask *might* also be valid.
David Neto619db262015-09-25 12:43:37 -0400616 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400617 if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400618 // Prepare for its operands, if any.
David Neto0ca6b592015-10-30 16:06:15 -0400619 spvPrependOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400620 }
621 }
David Neto619db262015-09-25 12:43:37 -0400622 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400623 default:
624 return diagnostic() << "Internal error: Unhandled operand type: " << type;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100625 }
626
David Neto0ca6b592015-10-30 16:06:15 -0400627 assert(int(SPV_OPERAND_TYPE_FIRST_CONCRETE_TYPE) <= int(parsed_operand.type));
628 assert(int(SPV_OPERAND_TYPE_LAST_CONCRETE_TYPE) >= int(parsed_operand.type));
629
630 operands->push_back(parsed_operand);
631
632 _.word_index += parsed_operand.num_words;
633
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100634 return SPV_SUCCESS;
635}
636
David Neto0ca6b592015-10-30 16:06:15 -0400637spv_result_t Parser::setNumericTypeInfoForType(
638 spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
David Neto201caf72015-11-04 17:38:17 -0500639 assert(type_id != 0);
David Neto0ca6b592015-10-30 16:06:15 -0400640 auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
641 if (type_info_iter == _.type_id_to_number_type_info.end()) {
642 return diagnostic() << "Type Id " << type_id << " is not a type";
643 }
644 const NumberType& info = type_info_iter->second;
645 if (info.type == SPV_NUMBER_NONE) {
646 // This is a valid type, but for something other than a scalar number.
647 return diagnostic() << "Type Id " << type_id
648 << " is not a scalar numeric type";
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400649 }
650
David Neto0ca6b592015-10-30 16:06:15 -0400651 parsed_operand->number_kind = info.type;
652 parsed_operand->number_bit_width = info.bit_width;
David Neto229b90f2015-11-06 11:23:57 -0500653 parsed_operand->num_words = (info.bit_width + 31) / 32; // Round up
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400654 return SPV_SUCCESS;
655}
656
David Neto0ca6b592015-10-30 16:06:15 -0400657void Parser::recordNumberType(const spv_parsed_instruction_t* inst) {
658 if (spvOpcodeGeneratesType(inst->opcode)) {
659 NumberType info = {SPV_NUMBER_NONE, 0};
660 if (SpvOpTypeInt == inst->opcode) {
661 const bool is_signed = peekAt(inst->offset + 3) != 0;
662 info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
663 info.bit_width = peekAt(inst->offset + 2);
664 } else if (SpvOpTypeFloat == inst->opcode) {
665 info.type = SPV_NUMBER_FLOATING;
666 info.bit_width = peekAt(inst->offset + 2);
Lei Zhang40056702015-09-11 14:31:27 -0400667 }
David Neto0ca6b592015-10-30 16:06:15 -0400668 // The *result* Id of a type generating instruction is the type Id.
669 _.type_id_to_number_type_info[inst->result_id] = info;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100670 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100671}
672
David Neto0ca6b592015-10-30 16:06:15 -0400673} // anonymous namespace
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400674
Andrew Woloszyn55ecc2e2015-11-11 11:05:07 -0500675spv_result_t spvBinaryParse(void* user_data, const uint32_t* code,
David Neto0ca6b592015-10-30 16:06:15 -0400676 const size_t num_words,
677 spv_parsed_header_fn_t parsed_header,
678 spv_parsed_instruction_fn_t parsed_instruction,
679 spv_diagnostic* diagnostic) {
680 Parser parser(user_data, parsed_header, parsed_instruction);
681 return parser.parse(code, num_words, diagnostic);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100682}
683
David Neto0ca6b592015-10-30 16:06:15 -0400684// TODO(dneto): This probably belongs in text.cpp since that's the only place
685// that a spv_binary_t value is created.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100686void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400687 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100688 if (binary->code) {
689 delete[] binary->code;
690 }
691 delete binary;
692}