binary.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. // Copyright (c) 2015-2020 The Khronos Group Inc.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #include "source/binary.h"
  17. #include <algorithm>
  18. #include <cassert>
  19. #include <cstring>
  20. #include <iterator>
  21. #include <limits>
  22. #include <string>
  23. #include <unordered_map>
  24. #include <vector>
  25. #include "source/assembly_grammar.h"
  26. #include "source/diagnostic.h"
  27. #include "source/ext_inst.h"
  28. #include "source/latest_version_spirv_header.h"
  29. #include "source/opcode.h"
  30. #include "source/operand.h"
  31. #include "source/spirv_constant.h"
  32. #include "source/spirv_endian.h"
  33. spv_result_t spvBinaryHeaderGet(const spv_const_binary binary,
  34. const spv_endianness_t endian,
  35. spv_header_t* pHeader) {
  36. if (!binary->code) return SPV_ERROR_INVALID_BINARY;
  37. if (binary->wordCount < SPV_INDEX_INSTRUCTION)
  38. return SPV_ERROR_INVALID_BINARY;
  39. if (!pHeader) return SPV_ERROR_INVALID_POINTER;
  40. // TODO: Validation checking?
  41. pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
  42. pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
  43. pHeader->generator =
  44. spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
  45. pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
  46. pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
  47. pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
  48. return SPV_SUCCESS;
  49. }
  50. namespace {
  51. // A SPIR-V binary parser. A parser instance communicates detailed parse
  52. // results via callbacks.
  53. class Parser {
  54. public:
  55. // The user_data value is provided to the callbacks as context.
  56. Parser(const spv_const_context context, void* user_data,
  57. spv_parsed_header_fn_t parsed_header_fn,
  58. spv_parsed_instruction_fn_t parsed_instruction_fn)
  59. : grammar_(context),
  60. consumer_(context->consumer),
  61. user_data_(user_data),
  62. parsed_header_fn_(parsed_header_fn),
  63. parsed_instruction_fn_(parsed_instruction_fn) {}
  64. // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
  65. // header and for each parsed instruction. Returns SPV_SUCCESS on success.
  66. // Otherwise returns an error code and issues a diagnostic.
  67. spv_result_t parse(const uint32_t* words, size_t num_words,
  68. spv_diagnostic* diagnostic);
  69. private:
  70. // All remaining methods work on the current module parse state.
  71. // Like the parse method, but works on the current module parse state.
  72. spv_result_t parseModule();
  73. // Parses an instruction at the current position of the binary. Assumes
  74. // the header has been parsed, the endian has been set, and the word index is
  75. // still in range. Advances the parsing position past the instruction, and
  76. // updates other parsing state for the current module.
  77. // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
  78. // On failure, returns an error code and issues a diagnostic.
  79. spv_result_t parseInstruction();
  80. // Parses an instruction operand with the given type, for an instruction
  81. // starting at inst_offset words into the SPIR-V binary.
  82. // If the SPIR-V binary is the same endianness as the host, then the
  83. // endian_converted_inst_words parameter is ignored. Otherwise, this method
  84. // appends the words for this operand, converted to host native endianness,
  85. // to the end of endian_converted_inst_words. This method also updates the
  86. // expected_operands parameter, and the scalar members of the inst parameter.
  87. // On success, returns SPV_SUCCESS, advances past the operand, and pushes a
  88. // new entry on to the operands vector. Otherwise returns an error code and
  89. // issues a diagnostic.
  90. spv_result_t parseOperand(size_t inst_offset, spv_parsed_instruction_t* inst,
  91. const spv_operand_type_t type,
  92. std::vector<uint32_t>* endian_converted_inst_words,
  93. std::vector<spv_parsed_operand_t>* operands,
  94. spv_operand_pattern_t* expected_operands);
  95. // Records the numeric type for an operand according to the type information
  96. // associated with the given non-zero type Id. This can fail if the type Id
  97. // is not a type Id, or if the type Id does not reference a scalar numeric
  98. // type. On success, return SPV_SUCCESS and populates the num_words,
  99. // number_kind, and number_bit_width fields of parsed_operand.
  100. spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
  101. uint32_t type_id);
  102. // Records the number type for an instruction at the given offset, if that
  103. // instruction generates a type. For types that aren't scalar numbers,
  104. // record something with number kind SPV_NUMBER_NONE.
  105. void recordNumberType(size_t inst_offset,
  106. const spv_parsed_instruction_t* inst);
  107. // Returns a diagnostic stream object initialized with current position in
  108. // the input stream, and for the given error code. Any data written to the
  109. // returned object will be propagated to the current parse's diagnostic
  110. // object.
  111. spvtools::DiagnosticStream diagnostic(spv_result_t error) {
  112. return spvtools::DiagnosticStream({0, 0, _.instruction_count}, consumer_,
  113. "", error);
  114. }
  115. // Returns a diagnostic stream object with the default parse error code.
  116. spvtools::DiagnosticStream diagnostic() {
  117. // The default failure for parsing is invalid binary.
  118. return diagnostic(SPV_ERROR_INVALID_BINARY);
  119. }
  120. // Issues a diagnostic describing an exhaustion of input condition when
  121. // trying to decode an instruction operand, and returns
  122. // SPV_ERROR_INVALID_BINARY.
  123. spv_result_t exhaustedInputDiagnostic(size_t inst_offset, SpvOp opcode,
  124. spv_operand_type_t type) {
  125. return diagnostic() << "End of input reached while decoding Op"
  126. << spvOpcodeString(opcode) << " starting at word "
  127. << inst_offset
  128. << ((_.word_index < _.num_words) ? ": truncated "
  129. : ": missing ")
  130. << spvOperandTypeStr(type) << " operand at word offset "
  131. << _.word_index - inst_offset << ".";
  132. }
  133. // Returns the endian-corrected word at the current position.
  134. uint32_t peek() const { return peekAt(_.word_index); }
  135. // Returns the endian-corrected word at the given position.
  136. uint32_t peekAt(size_t index) const {
  137. assert(index < _.num_words);
  138. return spvFixWord(_.words[index], _.endian);
  139. }
  140. // Data members
  141. const spvtools::AssemblyGrammar grammar_; // SPIR-V syntax utility.
  142. const spvtools::MessageConsumer& consumer_; // Message consumer callback.
  143. void* const user_data_; // Context for the callbacks
  144. const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
  145. const spv_parsed_instruction_fn_t
  146. parsed_instruction_fn_; // Parsed instruction callback
  147. // Describes the format of a typed literal number.
  148. struct NumberType {
  149. spv_number_kind_t type;
  150. uint32_t bit_width;
  151. };
  152. // The state used to parse a single SPIR-V binary module.
  153. struct State {
  154. State(const uint32_t* words_arg, size_t num_words_arg,
  155. spv_diagnostic* diagnostic_arg)
  156. : words(words_arg),
  157. num_words(num_words_arg),
  158. diagnostic(diagnostic_arg),
  159. word_index(0),
  160. instruction_count(0),
  161. endian(),
  162. requires_endian_conversion(false) {
  163. // Temporary storage for parser state within a single instruction.
  164. // Most instructions require fewer than 25 words or operands.
  165. operands.reserve(25);
  166. endian_converted_words.reserve(25);
  167. expected_operands.reserve(25);
  168. }
  169. State() : State(0, 0, nullptr) {}
  170. const uint32_t* words; // Words in the binary SPIR-V module.
  171. size_t num_words; // Number of words in the module.
  172. spv_diagnostic* diagnostic; // Where diagnostics go.
  173. size_t word_index; // The current position in words.
  174. size_t instruction_count; // The count of processed instructions
  175. spv_endianness_t endian; // The endianness of the binary.
  176. // Is the SPIR-V binary in a different endiannes from the host native
  177. // endianness?
  178. bool requires_endian_conversion;
  179. // Maps a result ID to its type ID. By convention:
  180. // - a result ID that is a type definition maps to itself.
  181. // - a result ID without a type maps to 0. (E.g. for OpLabel)
  182. std::unordered_map<uint32_t, uint32_t> id_to_type_id;
  183. // Maps a type ID to its number type description.
  184. std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
  185. // Maps an ExtInstImport id to the extended instruction type.
  186. std::unordered_map<uint32_t, spv_ext_inst_type_t>
  187. import_id_to_ext_inst_type;
  188. // Used by parseOperand
  189. std::vector<spv_parsed_operand_t> operands;
  190. std::vector<uint32_t> endian_converted_words;
  191. spv_operand_pattern_t expected_operands;
  192. } _;
  193. };
  194. spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
  195. spv_diagnostic* diagnostic_arg) {
  196. _ = State(words, num_words, diagnostic_arg);
  197. const spv_result_t result = parseModule();
  198. // Clear the module state. The tables might be big.
  199. _ = State();
  200. return result;
  201. }
  202. spv_result_t Parser::parseModule() {
  203. if (!_.words) return diagnostic() << "Missing module.";
  204. if (_.num_words < SPV_INDEX_INSTRUCTION)
  205. return diagnostic() << "Module has incomplete header: only " << _.num_words
  206. << " words instead of " << SPV_INDEX_INSTRUCTION;
  207. // Check the magic number and detect the module's endianness.
  208. spv_const_binary_t binary{_.words, _.num_words};
  209. if (spvBinaryEndianness(&binary, &_.endian)) {
  210. return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
  211. << _.words[0] << "'.";
  212. }
  213. _.requires_endian_conversion = !spvIsHostEndian(_.endian);
  214. // Process the header.
  215. spv_header_t header;
  216. if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
  217. // It turns out there is no way to trigger this error since the only
  218. // failure cases are already handled above, with better messages.
  219. return diagnostic(SPV_ERROR_INTERNAL)
  220. << "Internal error: unhandled header parse failure";
  221. }
  222. if (parsed_header_fn_) {
  223. if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
  224. header.version, header.generator,
  225. header.bound, header.schema)) {
  226. return error;
  227. }
  228. }
  229. // Process the instructions.
  230. _.word_index = SPV_INDEX_INSTRUCTION;
  231. while (_.word_index < _.num_words)
  232. if (auto error = parseInstruction()) return error;
  233. // Running off the end should already have been reported earlier.
  234. assert(_.word_index == _.num_words);
  235. return SPV_SUCCESS;
  236. }
  237. spv_result_t Parser::parseInstruction() {
  238. _.instruction_count++;
  239. // The zero values for all members except for opcode are the
  240. // correct initial values.
  241. spv_parsed_instruction_t inst = {};
  242. const uint32_t first_word = peek();
  243. // If the module's endianness is different from the host native endianness,
  244. // then converted_words contains the the endian-translated words in the
  245. // instruction.
  246. _.endian_converted_words.clear();
  247. _.endian_converted_words.push_back(first_word);
  248. // After a successful parse of the instruction, the inst.operands member
  249. // will point to this vector's storage.
  250. _.operands.clear();
  251. assert(_.word_index < _.num_words);
  252. // Decompose and check the first word.
  253. uint16_t inst_word_count = 0;
  254. spvOpcodeSplit(first_word, &inst_word_count, &inst.opcode);
  255. if (inst_word_count < 1) {
  256. return diagnostic() << "Invalid instruction word count: "
  257. << inst_word_count;
  258. }
  259. spv_opcode_desc opcode_desc;
  260. if (grammar_.lookupOpcode(static_cast<SpvOp>(inst.opcode), &opcode_desc))
  261. return diagnostic() << "Invalid opcode: " << inst.opcode;
  262. // Advance past the opcode word. But remember the of the start
  263. // of the instruction.
  264. const size_t inst_offset = _.word_index;
  265. _.word_index++;
  266. // Maintains the ordered list of expected operand types.
  267. // For many instructions we only need the {numTypes, operandTypes}
  268. // entries in opcode_desc. However, sometimes we need to modify
  269. // the list as we parse the operands. This occurs when an operand
  270. // has its own logical operands (such as the LocalSize operand for
  271. // ExecutionMode), or for extended instructions that may have their
  272. // own operands depending on the selected extended instruction.
  273. _.expected_operands.clear();
  274. for (auto i = 0; i < opcode_desc->numTypes; i++)
  275. _.expected_operands.push_back(
  276. opcode_desc->operandTypes[opcode_desc->numTypes - i - 1]);
  277. while (_.word_index < inst_offset + inst_word_count) {
  278. const uint16_t inst_word_index = uint16_t(_.word_index - inst_offset);
  279. if (_.expected_operands.empty()) {
  280. return diagnostic() << "Invalid instruction Op" << opcode_desc->name
  281. << " starting at word " << inst_offset
  282. << ": expected no more operands after "
  283. << inst_word_index
  284. << " words, but stated word count is "
  285. << inst_word_count << ".";
  286. }
  287. spv_operand_type_t type =
  288. spvTakeFirstMatchableOperand(&_.expected_operands);
  289. if (auto error =
  290. parseOperand(inst_offset, &inst, type, &_.endian_converted_words,
  291. &_.operands, &_.expected_operands)) {
  292. return error;
  293. }
  294. }
  295. if (!_.expected_operands.empty() &&
  296. !spvOperandIsOptional(_.expected_operands.back())) {
  297. return diagnostic() << "End of input reached while decoding Op"
  298. << opcode_desc->name << " starting at word "
  299. << inst_offset << ": expected more operands after "
  300. << inst_word_count << " words.";
  301. }
  302. if ((inst_offset + inst_word_count) != _.word_index) {
  303. return diagnostic() << "Invalid word count: Op" << opcode_desc->name
  304. << " starting at word " << inst_offset
  305. << " says it has " << inst_word_count
  306. << " words, but found " << _.word_index - inst_offset
  307. << " words instead.";
  308. }
  309. // Check the computed length of the endian-converted words vector against
  310. // the declared number of words in the instruction. If endian conversion
  311. // is required, then they should match. If no endian conversion was
  312. // performed, then the vector only contains the initial opcode/word-count
  313. // word.
  314. assert(!_.requires_endian_conversion ||
  315. (inst_word_count == _.endian_converted_words.size()));
  316. assert(_.requires_endian_conversion ||
  317. (_.endian_converted_words.size() == 1));
  318. recordNumberType(inst_offset, &inst);
  319. if (_.requires_endian_conversion) {
  320. // We must wait until here to set this pointer, because the vector might
  321. // have been be resized while we accumulated its elements.
  322. inst.words = _.endian_converted_words.data();
  323. } else {
  324. // If no conversion is required, then just point to the underlying binary.
  325. // This saves time and space.
  326. inst.words = _.words + inst_offset;
  327. }
  328. inst.num_words = inst_word_count;
  329. // We must wait until here to set this pointer, because the vector might
  330. // have been be resized while we accumulated its elements.
  331. inst.operands = _.operands.data();
  332. inst.num_operands = uint16_t(_.operands.size());
  333. // Issue the callback. The callee should know that all the storage in inst
  334. // is transient, and will disappear immediately afterward.
  335. if (parsed_instruction_fn_) {
  336. if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
  337. }
  338. return SPV_SUCCESS;
  339. }
  340. spv_result_t Parser::parseOperand(size_t inst_offset,
  341. spv_parsed_instruction_t* inst,
  342. const spv_operand_type_t type,
  343. std::vector<uint32_t>* words,
  344. std::vector<spv_parsed_operand_t>* operands,
  345. spv_operand_pattern_t* expected_operands) {
  346. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  347. // We'll fill in this result as we go along.
  348. spv_parsed_operand_t parsed_operand;
  349. parsed_operand.offset = uint16_t(_.word_index - inst_offset);
  350. // Most operands occupy one word. This might be be adjusted later.
  351. parsed_operand.num_words = 1;
  352. // The type argument is the one used by the grammar to parse the instruction.
  353. // But it can exposes internal parser details such as whether an operand is
  354. // optional or actually represents a variable-length sequence of operands.
  355. // The resulting type should be adjusted to avoid those internal details.
  356. // In most cases, the resulting operand type is the same as the grammar type.
  357. parsed_operand.type = type;
  358. // Assume non-numeric values. This will be updated for literal numbers.
  359. parsed_operand.number_kind = SPV_NUMBER_NONE;
  360. parsed_operand.number_bit_width = 0;
  361. if (_.word_index >= _.num_words)
  362. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  363. const uint32_t word = peek();
  364. // Do the words in this operand have to be converted to native endianness?
  365. // True for all but literal strings.
  366. bool convert_operand_endianness = true;
  367. switch (type) {
  368. case SPV_OPERAND_TYPE_TYPE_ID:
  369. if (!word)
  370. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Type Id is 0";
  371. inst->type_id = word;
  372. break;
  373. case SPV_OPERAND_TYPE_RESULT_ID:
  374. if (!word)
  375. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Result Id is 0";
  376. inst->result_id = word;
  377. // Save the result ID to type ID mapping.
  378. // In the grammar, type ID always appears before result ID.
  379. if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
  380. return diagnostic(SPV_ERROR_INVALID_ID)
  381. << "Id " << inst->result_id << " is defined more than once";
  382. // Record it.
  383. // A regular value maps to its type. Some instructions (e.g. OpLabel)
  384. // have no type Id, and will map to 0. The result Id for a
  385. // type-generating instruction (e.g. OpTypeInt) maps to itself.
  386. _.id_to_type_id[inst->result_id] =
  387. spvOpcodeGeneratesType(opcode) ? inst->result_id : inst->type_id;
  388. break;
  389. case SPV_OPERAND_TYPE_ID:
  390. case SPV_OPERAND_TYPE_OPTIONAL_ID:
  391. if (!word) return diagnostic(SPV_ERROR_INVALID_ID) << "Id is 0";
  392. parsed_operand.type = SPV_OPERAND_TYPE_ID;
  393. if (opcode == SpvOpExtInst && parsed_operand.offset == 3) {
  394. // The current word is the extended instruction set Id.
  395. // Set the extended instruction set type for the current instruction.
  396. auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
  397. if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
  398. return diagnostic(SPV_ERROR_INVALID_ID)
  399. << "OpExtInst set Id " << word
  400. << " does not reference an OpExtInstImport result Id";
  401. }
  402. inst->ext_inst_type = ext_inst_type_iter->second;
  403. }
  404. break;
  405. case SPV_OPERAND_TYPE_SCOPE_ID:
  406. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  407. // Check for trivially invalid values. The operand descriptions already
  408. // have the word "ID" in them.
  409. if (!word) return diagnostic() << spvOperandTypeStr(type) << " is 0";
  410. break;
  411. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  412. assert(SpvOpExtInst == opcode);
  413. assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
  414. spv_ext_inst_desc ext_inst;
  415. if (grammar_.lookupExtInst(inst->ext_inst_type, word, &ext_inst) ==
  416. SPV_SUCCESS) {
  417. // if we know about this ext inst, push the expected operands
  418. spvPushOperandTypes(ext_inst->operandTypes, expected_operands);
  419. } else {
  420. // if we don't know this extended instruction and the set isn't
  421. // non-semantic, we cannot process further
  422. if (!spvExtInstIsNonSemantic(inst->ext_inst_type)) {
  423. return diagnostic()
  424. << "Invalid extended instruction number: " << word;
  425. } else {
  426. // for non-semantic instruction sets, we know the form of all such
  427. // extended instructions contains a series of IDs as parameters
  428. expected_operands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
  429. }
  430. }
  431. } break;
  432. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  433. assert(SpvOpSpecConstantOp == opcode);
  434. if (grammar_.lookupSpecConstantOpcode(SpvOp(word))) {
  435. return diagnostic()
  436. << "Invalid " << spvOperandTypeStr(type) << ": " << word;
  437. }
  438. spv_opcode_desc opcode_entry = nullptr;
  439. if (grammar_.lookupOpcode(SpvOp(word), &opcode_entry)) {
  440. return diagnostic(SPV_ERROR_INTERNAL)
  441. << "OpSpecConstant opcode table out of sync";
  442. }
  443. // OpSpecConstant opcodes must have a type and result. We've already
  444. // processed them, so skip them when preparing to parse the other
  445. // operants for the opcode.
  446. assert(opcode_entry->hasType);
  447. assert(opcode_entry->hasResult);
  448. assert(opcode_entry->numTypes >= 2);
  449. spvPushOperandTypes(opcode_entry->operandTypes + 2, expected_operands);
  450. } break;
  451. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  452. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
  453. // These are regular single-word literal integer operands.
  454. // Post-parsing validation should check the range of the parsed value.
  455. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
  456. // It turns out they are always unsigned integers!
  457. parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
  458. parsed_operand.number_bit_width = 32;
  459. break;
  460. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  461. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  462. parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
  463. if (opcode == SpvOpSwitch) {
  464. // The literal operands have the same type as the value
  465. // referenced by the selector Id.
  466. const uint32_t selector_id = peekAt(inst_offset + 1);
  467. const auto type_id_iter = _.id_to_type_id.find(selector_id);
  468. if (type_id_iter == _.id_to_type_id.end() ||
  469. type_id_iter->second == 0) {
  470. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  471. << " has no type";
  472. }
  473. uint32_t type_id = type_id_iter->second;
  474. if (selector_id == type_id) {
  475. // Recall that by convention, a result ID that is a type definition
  476. // maps to itself.
  477. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  478. << " is a type, not a value";
  479. }
  480. if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
  481. return error;
  482. if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
  483. parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
  484. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  485. << " is not a scalar integer";
  486. }
  487. } else {
  488. assert(opcode == SpvOpConstant || opcode == SpvOpSpecConstant);
  489. // The literal number type is determined by the type Id for the
  490. // constant.
  491. assert(inst->type_id);
  492. if (auto error =
  493. setNumericTypeInfoForType(&parsed_operand, inst->type_id))
  494. return error;
  495. }
  496. break;
  497. case SPV_OPERAND_TYPE_LITERAL_STRING:
  498. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  499. convert_operand_endianness = false;
  500. const char* string =
  501. reinterpret_cast<const char*>(_.words + _.word_index);
  502. // Compute the length of the string, but make sure we don't run off the
  503. // end of the input.
  504. const size_t remaining_input_bytes =
  505. sizeof(uint32_t) * (_.num_words - _.word_index);
  506. const size_t string_num_content_bytes =
  507. spv_strnlen_s(string, remaining_input_bytes);
  508. // If there was no terminating null byte, then that's an end-of-input
  509. // error.
  510. if (string_num_content_bytes == remaining_input_bytes)
  511. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  512. // Account for null in the word length, so add 1 for null, then add 3 to
  513. // make sure we round up. The following is equivalent to:
  514. // (string_num_content_bytes + 1 + 3) / 4
  515. const size_t string_num_words = string_num_content_bytes / 4 + 1;
  516. // Make sure we can record the word count without overflow.
  517. //
  518. // This error can't currently be triggered because of validity
  519. // checks elsewhere.
  520. if (string_num_words > std::numeric_limits<uint16_t>::max()) {
  521. return diagnostic() << "Literal string is longer than "
  522. << std::numeric_limits<uint16_t>::max()
  523. << " words: " << string_num_words << " words long";
  524. }
  525. parsed_operand.num_words = uint16_t(string_num_words);
  526. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
  527. if (SpvOpExtInstImport == opcode) {
  528. // Record the extended instruction type for the ID for this import.
  529. // There is only one string literal argument to OpExtInstImport,
  530. // so it's sufficient to guard this just on the opcode.
  531. const spv_ext_inst_type_t ext_inst_type =
  532. spvExtInstImportTypeGet(string);
  533. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  534. return diagnostic()
  535. << "Invalid extended instruction import '" << string << "'";
  536. }
  537. // We must have parsed a valid result ID. It's a condition
  538. // of the grammar, and we only accept non-zero result Ids.
  539. assert(inst->result_id);
  540. _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
  541. }
  542. } break;
  543. case SPV_OPERAND_TYPE_CAPABILITY:
  544. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  545. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  546. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  547. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  548. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  549. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  550. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  551. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  552. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  553. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  554. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  555. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  556. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  557. case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER:
  558. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  559. case SPV_OPERAND_TYPE_DECORATION:
  560. case SPV_OPERAND_TYPE_BUILT_IN:
  561. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  562. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  563. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  564. case SPV_OPERAND_TYPE_RAY_FLAGS:
  565. case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
  566. case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
  567. case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
  568. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  569. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  570. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  571. case SPV_OPERAND_TYPE_DEBUG_OPERATION:
  572. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  573. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
  574. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
  575. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
  576. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: {
  577. // A single word that is a plain enum value.
  578. // Map an optional operand type to its corresponding concrete type.
  579. if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER)
  580. parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER;
  581. spv_operand_desc entry;
  582. if (grammar_.lookupOperand(type, word, &entry)) {
  583. return diagnostic()
  584. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  585. << " operand: " << word;
  586. }
  587. // Prepare to accept operands to this operand, if needed.
  588. spvPushOperandTypes(entry->operandTypes, expected_operands);
  589. } break;
  590. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  591. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  592. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  593. case SPV_OPERAND_TYPE_IMAGE:
  594. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  595. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  596. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  597. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
  598. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
  599. // This operand is a mask.
  600. // Map an optional operand type to its corresponding concrete type.
  601. if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
  602. parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
  603. else if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
  604. parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
  605. // Check validity of set mask bits. Also prepare for operands for those
  606. // masks if they have any. To get operand order correct, scan from
  607. // MSB to LSB since we can only prepend operands to a pattern.
  608. // The only case in the grammar where you have more than one mask bit
  609. // having an operand is for image operands. See SPIR-V 3.14 Image
  610. // Operands.
  611. uint32_t remaining_word = word;
  612. for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
  613. if (remaining_word & mask) {
  614. spv_operand_desc entry;
  615. if (grammar_.lookupOperand(type, mask, &entry)) {
  616. return diagnostic()
  617. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  618. << " operand: " << word << " has invalid mask component "
  619. << mask;
  620. }
  621. remaining_word ^= mask;
  622. spvPushOperandTypes(entry->operandTypes, expected_operands);
  623. }
  624. }
  625. if (word == 0) {
  626. // An all-zeroes mask *might* also be valid.
  627. spv_operand_desc entry;
  628. if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
  629. // Prepare for its operands, if any.
  630. spvPushOperandTypes(entry->operandTypes, expected_operands);
  631. }
  632. }
  633. } break;
  634. default:
  635. return diagnostic() << "Internal error: Unhandled operand type: " << type;
  636. }
  637. assert(spvOperandIsConcrete(parsed_operand.type));
  638. operands->push_back(parsed_operand);
  639. const size_t index_after_operand = _.word_index + parsed_operand.num_words;
  640. // Avoid buffer overrun for the cases where the operand has more than one
  641. // word, and where it isn't a string. (Those other cases have already been
  642. // handled earlier.) For example, this error can occur for a multi-word
  643. // argument to OpConstant, or a multi-word case literal operand for OpSwitch.
  644. if (_.num_words < index_after_operand)
  645. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  646. if (_.requires_endian_conversion) {
  647. // Copy instruction words. Translate to native endianness as needed.
  648. if (convert_operand_endianness) {
  649. const spv_endianness_t endianness = _.endian;
  650. std::transform(_.words + _.word_index, _.words + index_after_operand,
  651. std::back_inserter(*words),
  652. [endianness](const uint32_t raw_word) {
  653. return spvFixWord(raw_word, endianness);
  654. });
  655. } else {
  656. words->insert(words->end(), _.words + _.word_index,
  657. _.words + index_after_operand);
  658. }
  659. }
  660. // Advance past the operand.
  661. _.word_index = index_after_operand;
  662. return SPV_SUCCESS;
  663. }
  664. spv_result_t Parser::setNumericTypeInfoForType(
  665. spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
  666. assert(type_id != 0);
  667. auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
  668. if (type_info_iter == _.type_id_to_number_type_info.end()) {
  669. return diagnostic() << "Type Id " << type_id << " is not a type";
  670. }
  671. const NumberType& info = type_info_iter->second;
  672. if (info.type == SPV_NUMBER_NONE) {
  673. // This is a valid type, but for something other than a scalar number.
  674. return diagnostic() << "Type Id " << type_id
  675. << " is not a scalar numeric type";
  676. }
  677. parsed_operand->number_kind = info.type;
  678. parsed_operand->number_bit_width = info.bit_width;
  679. // Round up the word count.
  680. parsed_operand->num_words = static_cast<uint16_t>((info.bit_width + 31) / 32);
  681. return SPV_SUCCESS;
  682. }
  683. void Parser::recordNumberType(size_t inst_offset,
  684. const spv_parsed_instruction_t* inst) {
  685. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  686. if (spvOpcodeGeneratesType(opcode)) {
  687. NumberType info = {SPV_NUMBER_NONE, 0};
  688. if (SpvOpTypeInt == opcode) {
  689. const bool is_signed = peekAt(inst_offset + 3) != 0;
  690. info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
  691. info.bit_width = peekAt(inst_offset + 2);
  692. } else if (SpvOpTypeFloat == opcode) {
  693. info.type = SPV_NUMBER_FLOATING;
  694. info.bit_width = peekAt(inst_offset + 2);
  695. }
  696. // The *result* Id of a type generating instruction is the type Id.
  697. _.type_id_to_number_type_info[inst->result_id] = info;
  698. }
  699. }
  700. } // anonymous namespace
  701. spv_result_t spvBinaryParse(const spv_const_context context, void* user_data,
  702. const uint32_t* code, const size_t num_words,
  703. spv_parsed_header_fn_t parsed_header,
  704. spv_parsed_instruction_fn_t parsed_instruction,
  705. spv_diagnostic* diagnostic) {
  706. spv_context_t hijack_context = *context;
  707. if (diagnostic) {
  708. *diagnostic = nullptr;
  709. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, diagnostic);
  710. }
  711. Parser parser(&hijack_context, user_data, parsed_header, parsed_instruction);
  712. return parser.parse(code, num_words, diagnostic);
  713. }
  714. // TODO(dneto): This probably belongs in text.cpp since that's the only place
  715. // that a spv_binary_t value is created.
  716. void spvBinaryDestroy(spv_binary binary) {
  717. if (binary) {
  718. if (binary->code) delete[] binary->code;
  719. delete binary;
  720. }
  721. }
  722. size_t spv_strnlen_s(const char* str, size_t strsz) {
  723. if (!str) return 0;
  724. for (size_t i = 0; i < strsz; i++) {
  725. if (!str[i]) return i;
  726. }
  727. return strsz;
  728. }