text.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/text.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cctype>
  18. #include <cstdio>
  19. #include <cstdlib>
  20. #include <cstring>
  21. #include <memory>
  22. #include <set>
  23. #include <sstream>
  24. #include <string>
  25. #include <unordered_map>
  26. #include <utility>
  27. #include <vector>
  28. #include "source/assembly_grammar.h"
  29. #include "source/binary.h"
  30. #include "source/diagnostic.h"
  31. #include "source/ext_inst.h"
  32. #include "source/instruction.h"
  33. #include "source/opcode.h"
  34. #include "source/operand.h"
  35. #include "source/spirv_constant.h"
  36. #include "source/spirv_target_env.h"
  37. #include "source/table.h"
  38. #include "source/text_handler.h"
  39. #include "source/util/bitutils.h"
  40. #include "source/util/parse_number.h"
  41. #include "spirv-tools/libspirv.h"
  42. bool spvIsValidIDCharacter(const char value) {
  43. return value == '_' || 0 != ::isalnum(value);
  44. }
  45. // Returns true if the given string represents a valid ID name.
  46. bool spvIsValidID(const char* textValue) {
  47. const char* c = textValue;
  48. for (; *c != '\0'; ++c) {
  49. if (!spvIsValidIDCharacter(*c)) {
  50. return false;
  51. }
  52. }
  53. // If the string was empty, then the ID also is not valid.
  54. return c != textValue;
  55. }
  56. // Text API
  57. spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
  58. bool isSigned = false;
  59. int numPeriods = 0;
  60. bool isString = false;
  61. const size_t len = strlen(textValue);
  62. if (len == 0) return SPV_FAILED_MATCH;
  63. for (uint64_t index = 0; index < len; ++index) {
  64. switch (textValue[index]) {
  65. case '0':
  66. case '1':
  67. case '2':
  68. case '3':
  69. case '4':
  70. case '5':
  71. case '6':
  72. case '7':
  73. case '8':
  74. case '9':
  75. break;
  76. case '.':
  77. numPeriods++;
  78. break;
  79. case '-':
  80. if (index == 0) {
  81. isSigned = true;
  82. } else {
  83. isString = true;
  84. }
  85. break;
  86. default:
  87. isString = true;
  88. index = len; // break out of the loop too.
  89. break;
  90. }
  91. }
  92. pLiteral->type = spv_literal_type_t(99);
  93. if (isString || numPeriods > 1 || (isSigned && len == 1)) {
  94. if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
  95. return SPV_FAILED_MATCH;
  96. bool escaping = false;
  97. for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
  98. if ((*val == '\\') && (!escaping)) {
  99. escaping = true;
  100. } else {
  101. // Have to save space for the null-terminator
  102. if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
  103. return SPV_ERROR_OUT_OF_MEMORY;
  104. pLiteral->str.push_back(*val);
  105. escaping = false;
  106. }
  107. }
  108. pLiteral->type = SPV_LITERAL_TYPE_STRING;
  109. } else if (numPeriods == 1) {
  110. double d = std::strtod(textValue, nullptr);
  111. float f = (float)d;
  112. if (d == (double)f) {
  113. pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
  114. pLiteral->value.f = f;
  115. } else {
  116. pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
  117. pLiteral->value.d = d;
  118. }
  119. } else if (isSigned) {
  120. int64_t i64 = strtoll(textValue, nullptr, 10);
  121. int32_t i32 = (int32_t)i64;
  122. if (i64 == (int64_t)i32) {
  123. pLiteral->type = SPV_LITERAL_TYPE_INT_32;
  124. pLiteral->value.i32 = i32;
  125. } else {
  126. pLiteral->type = SPV_LITERAL_TYPE_INT_64;
  127. pLiteral->value.i64 = i64;
  128. }
  129. } else {
  130. uint64_t u64 = strtoull(textValue, nullptr, 10);
  131. uint32_t u32 = (uint32_t)u64;
  132. if (u64 == (uint64_t)u32) {
  133. pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
  134. pLiteral->value.u32 = u32;
  135. } else {
  136. pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
  137. pLiteral->value.u64 = u64;
  138. }
  139. }
  140. return SPV_SUCCESS;
  141. }
  142. namespace {
  143. /// Parses an immediate integer from text, guarding against overflow. If
  144. /// successful, adds the parsed value to pInst, advances the context past it,
  145. /// and returns SPV_SUCCESS. Otherwise, leaves pInst alone, emits diagnostics,
  146. /// and returns SPV_ERROR_INVALID_TEXT.
  147. spv_result_t encodeImmediate(spvtools::AssemblyContext* context,
  148. const char* text, spv_instruction_t* pInst) {
  149. assert(*text == '!');
  150. uint32_t parse_result;
  151. if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) {
  152. return context->diagnostic(SPV_ERROR_INVALID_TEXT)
  153. << "Invalid immediate integer: !" << text + 1;
  154. }
  155. context->binaryEncodeU32(parse_result, pInst);
  156. context->seekForward(static_cast<uint32_t>(strlen(text)));
  157. return SPV_SUCCESS;
  158. }
  159. } // anonymous namespace
  160. /// @brief Translate an Opcode operand to binary form
  161. ///
  162. /// @param[in] grammar the grammar to use for compilation
  163. /// @param[in, out] context the dynamic compilation info
  164. /// @param[in] type of the operand
  165. /// @param[in] textValue word of text to be parsed
  166. /// @param[out] pInst return binary Opcode
  167. /// @param[in,out] pExpectedOperands the operand types expected
  168. ///
  169. /// @return result code
  170. spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,
  171. spvtools::AssemblyContext* context,
  172. const spv_operand_type_t type,
  173. const char* textValue,
  174. spv_instruction_t* pInst,
  175. spv_operand_pattern_t* pExpectedOperands) {
  176. // NOTE: Handle immediate int in the stream
  177. if ('!' == textValue[0]) {
  178. if (auto error = encodeImmediate(context, textValue, pInst)) {
  179. return error;
  180. }
  181. *pExpectedOperands =
  182. spvAlternatePatternFollowingImmediate(*pExpectedOperands);
  183. return SPV_SUCCESS;
  184. }
  185. // Optional literal operands can fail to parse. In that case use
  186. // SPV_FAILED_MATCH to avoid emitting a diagostic. Use the following
  187. // for those situations.
  188. spv_result_t error_code_for_literals =
  189. spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
  190. switch (type) {
  191. case SPV_OPERAND_TYPE_ID:
  192. case SPV_OPERAND_TYPE_TYPE_ID:
  193. case SPV_OPERAND_TYPE_RESULT_ID:
  194. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  195. case SPV_OPERAND_TYPE_SCOPE_ID:
  196. case SPV_OPERAND_TYPE_OPTIONAL_ID: {
  197. if ('%' == textValue[0]) {
  198. textValue++;
  199. } else {
  200. return context->diagnostic() << "Expected id to start with %.";
  201. }
  202. if (!spvIsValidID(textValue)) {
  203. return context->diagnostic() << "Invalid ID " << textValue;
  204. }
  205. const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
  206. if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
  207. spvInstructionAddWord(pInst, id);
  208. // Set the extended instruction type.
  209. // The import set id is the 3rd operand of OpExtInst.
  210. if (spv::Op(pInst->opcode) == spv::Op::OpExtInst &&
  211. pInst->words.size() == 4) {
  212. auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
  213. if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
  214. return context->diagnostic()
  215. << "Invalid extended instruction import Id "
  216. << pInst->words[2];
  217. }
  218. pInst->extInstType = ext_inst_type;
  219. }
  220. } break;
  221. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  222. // The assembler accepts the symbolic name for an extended instruction,
  223. // and emits its corresponding number.
  224. spv_ext_inst_desc extInst;
  225. if (grammar.lookupExtInst(pInst->extInstType, textValue, &extInst) ==
  226. SPV_SUCCESS) {
  227. // if we know about this extended instruction, push the numeric value
  228. spvInstructionAddWord(pInst, extInst->ext_inst);
  229. // Prepare to parse the operands for the extended instructions.
  230. spvPushOperandTypes(extInst->operandTypes, pExpectedOperands);
  231. } else {
  232. // if we don't know this extended instruction and the set isn't
  233. // non-semantic, we cannot process further
  234. if (!spvExtInstIsNonSemantic(pInst->extInstType)) {
  235. return context->diagnostic()
  236. << "Invalid extended instruction name '" << textValue << "'.";
  237. } else {
  238. // for non-semantic instruction sets, as long as the text name is an
  239. // integer value we can encode it since we know the form of all such
  240. // extended instructions
  241. spv_literal_t extInstValue;
  242. if (spvTextToLiteral(textValue, &extInstValue) ||
  243. extInstValue.type != SPV_LITERAL_TYPE_UINT_32) {
  244. return context->diagnostic()
  245. << "Couldn't translate unknown extended instruction name '"
  246. << textValue << "' to unsigned integer.";
  247. }
  248. spvInstructionAddWord(pInst, extInstValue.value.u32);
  249. // opcode contains an unknown number of IDs.
  250. pExpectedOperands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
  251. }
  252. }
  253. } break;
  254. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  255. // The assembler accepts the symbolic name for the opcode, but without
  256. // the "Op" prefix. For example, "IAdd" is accepted. The number
  257. // of the opcode is emitted.
  258. spv::Op opcode;
  259. if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
  260. return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
  261. << " '" << textValue << "'.";
  262. }
  263. spv_opcode_desc opcodeEntry = nullptr;
  264. if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
  265. return context->diagnostic(SPV_ERROR_INTERNAL)
  266. << "OpSpecConstant opcode table out of sync";
  267. }
  268. spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
  269. // Prepare to parse the operands for the opcode. Except skip the
  270. // type Id and result Id, since they've already been processed.
  271. assert(opcodeEntry->hasType);
  272. assert(opcodeEntry->hasResult);
  273. assert(opcodeEntry->numTypes >= 2);
  274. spvPushOperandTypes(opcodeEntry->operandTypes + 2, pExpectedOperands);
  275. } break;
  276. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  277. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
  278. // The current operand is an *unsigned* 32-bit integer.
  279. // That's just how the grammar works.
  280. spvtools::IdType expected_type = {
  281. 32, false, spvtools::IdTypeClass::kScalarIntegerType};
  282. if (auto error = context->binaryEncodeNumericLiteral(
  283. textValue, error_code_for_literals, expected_type, pInst)) {
  284. return error;
  285. }
  286. } break;
  287. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
  288. // This is a context-independent literal number which can be a 32-bit
  289. // number of floating point value.
  290. if (auto error = context->binaryEncodeNumericLiteral(
  291. textValue, error_code_for_literals, spvtools::kUnknownType,
  292. pInst)) {
  293. return error;
  294. }
  295. break;
  296. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  297. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
  298. spvtools::IdType expected_type = spvtools::kUnknownType;
  299. // The encoding for OpConstant, OpSpecConstant and OpSwitch all
  300. // depend on either their own result-id or the result-id of
  301. // one of their parameters.
  302. if (spv::Op::OpConstant == pInst->opcode ||
  303. spv::Op::OpSpecConstant == pInst->opcode) {
  304. // The type of the literal is determined by the type Id of the
  305. // instruction.
  306. expected_type =
  307. context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
  308. if (!spvtools::isScalarFloating(expected_type) &&
  309. !spvtools::isScalarIntegral(expected_type)) {
  310. spv_opcode_desc d;
  311. const char* opcode_name = "opcode";
  312. if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
  313. opcode_name = d->name;
  314. }
  315. return context->diagnostic()
  316. << "Type for " << opcode_name
  317. << " must be a scalar floating point or integer type";
  318. }
  319. } else if (pInst->opcode == spv::Op::OpSwitch) {
  320. // The type of the literal is the same as the type of the selector.
  321. expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
  322. if (!spvtools::isScalarIntegral(expected_type)) {
  323. return context->diagnostic()
  324. << "The selector operand for OpSwitch must be the result"
  325. " of an instruction that generates an integer scalar";
  326. }
  327. }
  328. if (auto error = context->binaryEncodeNumericLiteral(
  329. textValue, error_code_for_literals, expected_type, pInst)) {
  330. return error;
  331. }
  332. } break;
  333. case SPV_OPERAND_TYPE_LITERAL_STRING:
  334. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  335. spv_literal_t literal = {};
  336. spv_result_t error = spvTextToLiteral(textValue, &literal);
  337. if (error != SPV_SUCCESS) {
  338. if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
  339. return context->diagnostic(error_code_for_literals)
  340. << "Invalid literal string '" << textValue << "'.";
  341. }
  342. if (literal.type != SPV_LITERAL_TYPE_STRING) {
  343. return context->diagnostic()
  344. << "Expected literal string, found literal number '" << textValue
  345. << "'.";
  346. }
  347. // NOTE: Special case for extended instruction library import
  348. if (spv::Op::OpExtInstImport == pInst->opcode) {
  349. const spv_ext_inst_type_t ext_inst_type =
  350. spvExtInstImportTypeGet(literal.str.c_str());
  351. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  352. return context->diagnostic()
  353. << "Invalid extended instruction import '" << literal.str
  354. << "'";
  355. }
  356. if ((error = context->recordIdAsExtInstImport(pInst->words[1],
  357. ext_inst_type)))
  358. return error;
  359. }
  360. if (context->binaryEncodeString(literal.str.c_str(), pInst))
  361. return SPV_ERROR_INVALID_TEXT;
  362. } break;
  363. // Masks.
  364. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  365. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  366. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  367. case SPV_OPERAND_TYPE_IMAGE:
  368. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  369. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  370. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  371. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
  372. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS: {
  373. uint32_t value;
  374. if (auto error = grammar.parseMaskOperand(type, textValue, &value)) {
  375. return context->diagnostic(error)
  376. << "Invalid " << spvOperandTypeStr(type) << " operand '"
  377. << textValue << "'.";
  378. }
  379. if (auto error = context->binaryEncodeU32(value, pInst)) return error;
  380. // Prepare to parse the operands for this logical operand.
  381. grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
  382. } break;
  383. case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
  384. auto error = spvTextEncodeOperand(
  385. grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
  386. pInst, pExpectedOperands);
  387. if (error == SPV_FAILED_MATCH) {
  388. // It's not a literal number -- is it a literal string?
  389. error = spvTextEncodeOperand(grammar, context,
  390. SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
  391. textValue, pInst, pExpectedOperands);
  392. }
  393. if (error == SPV_FAILED_MATCH) {
  394. // It's not a literal -- is it an ID?
  395. error =
  396. spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
  397. textValue, pInst, pExpectedOperands);
  398. }
  399. if (error) {
  400. return context->diagnostic(error)
  401. << "Invalid word following !<integer>: " << textValue;
  402. }
  403. if (pExpectedOperands->empty()) {
  404. pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
  405. }
  406. } break;
  407. default: {
  408. // NOTE: All non literal operands are handled here using the operand
  409. // table.
  410. spv_operand_desc entry;
  411. if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
  412. return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
  413. << " '" << textValue << "'.";
  414. }
  415. if (context->binaryEncodeU32(entry->value, pInst)) {
  416. return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
  417. << " '" << textValue << "'.";
  418. }
  419. // Prepare to parse the operands for this logical operand.
  420. spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
  421. } break;
  422. }
  423. return SPV_SUCCESS;
  424. }
  425. namespace {
  426. /// Encodes an instruction started by !<integer> at the given position in text.
  427. ///
  428. /// Puts the encoded words into *pInst. If successful, moves position past the
  429. /// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
  430. /// leaves position pointing to the error in text.
  431. spv_result_t encodeInstructionStartingWithImmediate(
  432. const spvtools::AssemblyGrammar& grammar,
  433. spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
  434. std::string firstWord;
  435. spv_position_t nextPosition = {};
  436. auto error = context->getWord(&firstWord, &nextPosition);
  437. if (error) return context->diagnostic(error) << "Internal Error";
  438. if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
  439. return error;
  440. }
  441. while (context->advance() != SPV_END_OF_STREAM) {
  442. // A beginning of a new instruction means we're done.
  443. if (context->isStartOfNewInst()) return SPV_SUCCESS;
  444. // Otherwise, there must be an operand that's either a literal, an ID, or
  445. // an immediate.
  446. std::string operandValue;
  447. if ((error = context->getWord(&operandValue, &nextPosition)))
  448. return context->diagnostic(error) << "Internal Error";
  449. if (operandValue == "=")
  450. return context->diagnostic() << firstWord << " not allowed before =.";
  451. // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
  452. // expanded.
  453. spv_operand_pattern_t dummyExpectedOperands;
  454. error = spvTextEncodeOperand(
  455. grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
  456. pInst, &dummyExpectedOperands);
  457. if (error) return error;
  458. context->setPosition(nextPosition);
  459. }
  460. return SPV_SUCCESS;
  461. }
  462. /// @brief Translate single Opcode and operands to binary form
  463. ///
  464. /// @param[in] grammar the grammar to use for compilation
  465. /// @param[in, out] context the dynamic compilation info
  466. /// @param[in] text stream to translate
  467. /// @param[out] pInst returned binary Opcode
  468. /// @param[in,out] pPosition in the text stream
  469. ///
  470. /// @return result code
  471. spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
  472. spvtools::AssemblyContext* context,
  473. spv_instruction_t* pInst) {
  474. // Check for !<integer> first.
  475. if ('!' == context->peek()) {
  476. return encodeInstructionStartingWithImmediate(grammar, context, pInst);
  477. }
  478. std::string firstWord;
  479. spv_position_t nextPosition = {};
  480. spv_result_t error = context->getWord(&firstWord, &nextPosition);
  481. if (error) return context->diagnostic() << "Internal Error";
  482. std::string opcodeName;
  483. std::string result_id;
  484. spv_position_t result_id_position = {};
  485. if (context->startsWithOp()) {
  486. opcodeName = firstWord;
  487. } else {
  488. result_id = firstWord;
  489. if ('%' != result_id.front()) {
  490. return context->diagnostic()
  491. << "Expected <opcode> or <result-id> at the beginning "
  492. "of an instruction, found '"
  493. << result_id << "'.";
  494. }
  495. result_id_position = context->position();
  496. // The '=' sign.
  497. context->setPosition(nextPosition);
  498. if (context->advance())
  499. return context->diagnostic() << "Expected '=', found end of stream.";
  500. std::string equal_sign;
  501. error = context->getWord(&equal_sign, &nextPosition);
  502. if ("=" != equal_sign)
  503. return context->diagnostic() << "'=' expected after result id but found '"
  504. << equal_sign << "'.";
  505. // The <opcode> after the '=' sign.
  506. context->setPosition(nextPosition);
  507. if (context->advance())
  508. return context->diagnostic() << "Expected opcode, found end of stream.";
  509. error = context->getWord(&opcodeName, &nextPosition);
  510. if (error) return context->diagnostic(error) << "Internal Error";
  511. if (!context->startsWithOp()) {
  512. return context->diagnostic()
  513. << "Invalid Opcode prefix '" << opcodeName << "'.";
  514. }
  515. }
  516. // NOTE: The table contains Opcode names without the "Op" prefix.
  517. const char* pInstName = opcodeName.data() + 2;
  518. spv_opcode_desc opcodeEntry;
  519. error = grammar.lookupOpcode(pInstName, &opcodeEntry);
  520. if (error) {
  521. return context->diagnostic(error)
  522. << "Invalid Opcode name '" << opcodeName << "'";
  523. }
  524. if (opcodeEntry->hasResult && result_id.empty()) {
  525. return context->diagnostic()
  526. << "Expected <result-id> at the beginning of an instruction, found '"
  527. << firstWord << "'.";
  528. }
  529. if (!opcodeEntry->hasResult && !result_id.empty()) {
  530. return context->diagnostic()
  531. << "Cannot set ID " << result_id << " because " << opcodeName
  532. << " does not produce a result ID.";
  533. }
  534. pInst->opcode = opcodeEntry->opcode;
  535. context->setPosition(nextPosition);
  536. // Reserve the first word for the instruction.
  537. spvInstructionAddWord(pInst, 0);
  538. // Maintains the ordered list of expected operand types.
  539. // For many instructions we only need the {numTypes, operandTypes}
  540. // entries in opcodeEntry. However, sometimes we need to modify
  541. // the list as we parse the operands. This occurs when an operand
  542. // has its own logical operands (such as the LocalSize operand for
  543. // ExecutionMode), or for extended instructions that may have their
  544. // own operands depending on the selected extended instruction.
  545. spv_operand_pattern_t expectedOperands;
  546. expectedOperands.reserve(opcodeEntry->numTypes);
  547. for (auto i = 0; i < opcodeEntry->numTypes; i++)
  548. expectedOperands.push_back(
  549. opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
  550. while (!expectedOperands.empty()) {
  551. const spv_operand_type_t type = expectedOperands.back();
  552. expectedOperands.pop_back();
  553. // Expand optional tuples lazily.
  554. if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
  555. if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
  556. // Handle the <result-id> for value generating instructions.
  557. // We've already consumed it from the text stream. Here
  558. // we inject its words into the instruction.
  559. spv_position_t temp_pos = context->position();
  560. error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
  561. result_id.c_str(), pInst, nullptr);
  562. result_id_position = context->position();
  563. // Because we are injecting we have to reset the position afterwards.
  564. context->setPosition(temp_pos);
  565. if (error) return error;
  566. } else {
  567. // Find the next word.
  568. error = context->advance();
  569. if (error == SPV_END_OF_STREAM) {
  570. if (spvOperandIsOptional(type)) {
  571. // This would have been the last potential operand for the
  572. // instruction,
  573. // and we didn't find one. We're finished parsing this instruction.
  574. break;
  575. } else {
  576. return context->diagnostic()
  577. << "Expected operand for " << opcodeName
  578. << " instruction, but found the end of the stream.";
  579. }
  580. }
  581. assert(error == SPV_SUCCESS && "Somebody added another way to fail");
  582. if (context->isStartOfNewInst()) {
  583. if (spvOperandIsOptional(type)) {
  584. break;
  585. } else {
  586. return context->diagnostic()
  587. << "Expected operand for " << opcodeName
  588. << " instruction, but found the next instruction instead.";
  589. }
  590. }
  591. std::string operandValue;
  592. error = context->getWord(&operandValue, &nextPosition);
  593. if (error) return context->diagnostic(error) << "Internal Error";
  594. error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
  595. pInst, &expectedOperands);
  596. if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
  597. return SPV_SUCCESS;
  598. if (error) return error;
  599. context->setPosition(nextPosition);
  600. }
  601. }
  602. if (spvOpcodeGeneratesType(pInst->opcode)) {
  603. if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
  604. return SPV_ERROR_INVALID_TEXT;
  605. }
  606. } else if (opcodeEntry->hasType) {
  607. // SPIR-V dictates that if an instruction has both a return value and a
  608. // type ID then the type id is first, and the return value is second.
  609. assert(opcodeEntry->hasResult &&
  610. "Unknown opcode: has a type but no result.");
  611. context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
  612. }
  613. if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
  614. return context->diagnostic()
  615. << opcodeName << " Instruction too long: " << pInst->words.size()
  616. << " words, but the limit is "
  617. << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
  618. }
  619. pInst->words[0] =
  620. spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
  621. return SPV_SUCCESS;
  622. }
  623. enum { kAssemblerVersion = 0 };
  624. // Populates a binary stream's |header|. The target environment is specified via
  625. // |env| and Id bound is via |bound|.
  626. spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
  627. uint32_t* header) {
  628. if (!header) return SPV_ERROR_INVALID_BINARY;
  629. header[SPV_INDEX_MAGIC_NUMBER] = spv::MagicNumber;
  630. header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
  631. header[SPV_INDEX_GENERATOR_NUMBER] =
  632. SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
  633. header[SPV_INDEX_BOUND] = bound;
  634. header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
  635. return SPV_SUCCESS;
  636. }
  637. // Collects all numeric ids in the module source into |numeric_ids|.
  638. // This function is essentially a dry-run of spvTextToBinary.
  639. spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
  640. const spvtools::MessageConsumer& consumer,
  641. const spv_text text,
  642. std::set<uint32_t>* numeric_ids) {
  643. spvtools::AssemblyContext context(text, consumer);
  644. if (!text->str) return context.diagnostic() << "Missing assembly text.";
  645. if (!grammar.isValid()) {
  646. return SPV_ERROR_INVALID_TABLE;
  647. }
  648. // Skip past whitespace and comments.
  649. context.advance();
  650. while (context.hasText()) {
  651. spv_instruction_t inst;
  652. // Operand parsing sometimes involves knowing the opcode of the instruction
  653. // being parsed. A malformed input might feature such an operand *before*
  654. // the opcode is known. To guard against accessing an uninitialized opcode,
  655. // the instruction's opcode is initialized to a default value.
  656. inst.opcode = spv::Op::Max;
  657. if (spvTextEncodeOpcode(grammar, &context, &inst)) {
  658. return SPV_ERROR_INVALID_TEXT;
  659. }
  660. if (context.advance()) break;
  661. }
  662. *numeric_ids = context.GetNumericIds();
  663. return SPV_SUCCESS;
  664. }
  665. // Translates a given assembly language module into binary form.
  666. // If a diagnostic is generated, it is not yet marked as being
  667. // for a text-based input.
  668. spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
  669. const spvtools::MessageConsumer& consumer,
  670. const spv_text text,
  671. const uint32_t options,
  672. spv_binary* pBinary) {
  673. // The ids in this set will have the same values both in source and binary.
  674. // All other ids will be generated by filling in the gaps.
  675. std::set<uint32_t> ids_to_preserve;
  676. if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
  677. // Collect all numeric ids from the source into ids_to_preserve.
  678. const spv_result_t result =
  679. GetNumericIds(grammar, consumer, text, &ids_to_preserve);
  680. if (result != SPV_SUCCESS) return result;
  681. }
  682. spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
  683. if (!text->str) return context.diagnostic() << "Missing assembly text.";
  684. if (!grammar.isValid()) {
  685. return SPV_ERROR_INVALID_TABLE;
  686. }
  687. if (!pBinary) return SPV_ERROR_INVALID_POINTER;
  688. std::vector<spv_instruction_t> instructions;
  689. // Skip past whitespace and comments.
  690. context.advance();
  691. while (context.hasText()) {
  692. instructions.push_back({});
  693. spv_instruction_t& inst = instructions.back();
  694. if (auto error = spvTextEncodeOpcode(grammar, &context, &inst)) {
  695. return error;
  696. }
  697. if (context.advance()) break;
  698. }
  699. size_t totalSize = SPV_INDEX_INSTRUCTION;
  700. for (auto& inst : instructions) {
  701. totalSize += inst.words.size();
  702. }
  703. uint32_t* data = new uint32_t[totalSize];
  704. if (!data) return SPV_ERROR_OUT_OF_MEMORY;
  705. uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
  706. for (auto& inst : instructions) {
  707. memcpy(data + currentIndex, inst.words.data(),
  708. sizeof(uint32_t) * inst.words.size());
  709. currentIndex += inst.words.size();
  710. }
  711. if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
  712. return error;
  713. spv_binary binary = new spv_binary_t();
  714. if (!binary) {
  715. delete[] data;
  716. return SPV_ERROR_OUT_OF_MEMORY;
  717. }
  718. binary->code = data;
  719. binary->wordCount = totalSize;
  720. *pBinary = binary;
  721. return SPV_SUCCESS;
  722. }
  723. } // anonymous namespace
  724. spv_result_t spvTextToBinary(const spv_const_context context,
  725. const char* input_text,
  726. const size_t input_text_size, spv_binary* pBinary,
  727. spv_diagnostic* pDiagnostic) {
  728. return spvTextToBinaryWithOptions(context, input_text, input_text_size,
  729. SPV_TEXT_TO_BINARY_OPTION_NONE, pBinary,
  730. pDiagnostic);
  731. }
  732. spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
  733. const char* input_text,
  734. const size_t input_text_size,
  735. const uint32_t options,
  736. spv_binary* pBinary,
  737. spv_diagnostic* pDiagnostic) {
  738. spv_context_t hijack_context = *context;
  739. if (pDiagnostic) {
  740. *pDiagnostic = nullptr;
  741. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  742. }
  743. spv_text_t text = {input_text, input_text_size};
  744. spvtools::AssemblyGrammar grammar(&hijack_context);
  745. spv_result_t result = spvTextToBinaryInternal(
  746. grammar, hijack_context.consumer, &text, options, pBinary);
  747. if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
  748. return result;
  749. }
  750. void spvTextDestroy(spv_text text) {
  751. if (text) {
  752. if (text->str) delete[] text->str;
  753. delete text;
  754. }
  755. }