binary.cpp 37 KB

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