blob: ba575f90d9892e0899c681ec85b14690dfa39106 [file] [log] [blame]
Dejan Mircevskib6fe02f2016-01-07 13:44:22 -05001// Copyright (c) 2015-2016 The Khronos Group Inc.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01002//
David Neto9fc86582016-09-01 15:33:59 -04003// 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
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01006//
David Neto9fc86582016-09-01 15:33:59 -04007// http://www.apache.org/licenses/LICENSE-2.0
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01008//
David Neto9fc86582016-09-01 15:33:59 -04009// 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.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010014
dan sinclaireda2cfb2018-08-03 15:06:09 -040015#include "source/text.h"
David Neto36b0c0f2015-09-16 18:32:54 -040016
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040017#include <algorithm>
18#include <cassert>
Andrew Woloszyn13804e52015-09-22 15:50:33 -040019#include <cctype>
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040020#include <cstdio>
21#include <cstdlib>
David Neto36b0c0f2015-09-16 18:32:54 -040022#include <cstring>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040023#include <memory>
dan sinclaireda2cfb2018-08-03 15:06:09 -040024#include <set>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040025#include <sstream>
David Neto201caf72015-11-04 17:38:17 -050026#include <string>
David Neto36b0c0f2015-09-16 18:32:54 -040027#include <unordered_map>
dan sinclaireda2cfb2018-08-03 15:06:09 -040028#include <utility>
David Neto36b0c0f2015-09-16 18:32:54 -040029#include <vector>
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040030
dan sinclaireda2cfb2018-08-03 15:06:09 -040031#include "source/assembly_grammar.h"
32#include "source/binary.h"
33#include "source/diagnostic.h"
34#include "source/ext_inst.h"
35#include "source/instruction.h"
36#include "source/message.h"
37#include "source/opcode.h"
38#include "source/operand.h"
39#include "source/spirv_constant.h"
40#include "source/spirv_target_env.h"
41#include "source/table.h"
42#include "source/text_handler.h"
43#include "source/util/bitutils.h"
44#include "source/util/parse_number.h"
David Neto5a703352016-02-17 14:44:00 -050045#include "spirv-tools/libspirv.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010046
Andrew Woloszyn13804e52015-09-22 15:50:33 -040047bool spvIsValidIDCharacter(const char value) {
48 return value == '_' || 0 != ::isalnum(value);
49}
50
51// Returns true if the given string represents a valid ID name.
Dejan Mircevski14c4b102015-09-29 17:07:21 -040052bool spvIsValidID(const char* textValue) {
53 const char* c = textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -040054 for (; *c != '\0'; ++c) {
55 if (!spvIsValidIDCharacter(*c)) {
56 return false;
57 }
58 }
59 // If the string was empty, then the ID also is not valid.
60 return c != textValue;
61}
62
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040063// Text API
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010064
Dejan Mircevski903f9d62015-09-28 17:04:39 -040065spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010066 bool isSigned = false;
David Netoaffa6962015-08-24 15:33:14 -040067 int numPeriods = 0;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010068 bool isString = false;
69
David Netoaffa6962015-08-24 15:33:14 -040070 const size_t len = strlen(textValue);
David Neto98290a22015-08-24 16:27:02 -040071 if (len == 0) return SPV_FAILED_MATCH;
72
David Netoaffa6962015-08-24 15:33:14 -040073 for (uint64_t index = 0; index < len; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010074 switch (textValue[index]) {
75 case '0':
76 case '1':
77 case '2':
78 case '3':
79 case '4':
80 case '5':
81 case '6':
82 case '7':
83 case '8':
84 case '9':
85 break;
86 case '.':
David Netoaffa6962015-08-24 15:33:14 -040087 numPeriods++;
88 break;
89 case '-':
90 if (index == 0) {
91 isSigned = true;
92 } else {
93 isString = true;
94 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010095 break;
96 default:
97 isString = true;
Lei Zhange78a7c12015-09-10 17:07:21 -040098 index = len; // break out of the loop too.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010099 break;
100 }
101 }
102
David Netoaffa6962015-08-24 15:33:14 -0400103 pLiteral->type = spv_literal_type_t(99);
104
Lei Zhange78a7c12015-09-10 17:07:21 -0400105 if (isString || numPeriods > 1 || (isSigned && len == 1)) {
David Neto98290a22015-08-24 16:27:02 -0400106 if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
107 return SPV_FAILED_MATCH;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400108 bool escaping = false;
Lei Zhang6483bd72015-10-14 17:02:39 -0400109 for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400110 if ((*val == '\\') && (!escaping)) {
111 escaping = true;
112 } else {
113 // Have to save space for the null-terminator
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500114 if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400115 return SPV_ERROR_OUT_OF_MEMORY;
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500116 pLiteral->str.push_back(*val);
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400117 escaping = false;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400118 }
119 }
120
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100121 pLiteral->type = SPV_LITERAL_TYPE_STRING;
David Netoaffa6962015-08-24 15:33:14 -0400122 } else if (numPeriods == 1) {
123 double d = std::strtod(textValue, nullptr);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100124 float f = (float)d;
125 if (d == (double)f) {
126 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
127 pLiteral->value.f = f;
128 } else {
129 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
130 pLiteral->value.d = d;
131 }
132 } else if (isSigned) {
133 int64_t i64 = strtoll(textValue, nullptr, 10);
134 int32_t i32 = (int32_t)i64;
135 if (i64 == (int64_t)i32) {
136 pLiteral->type = SPV_LITERAL_TYPE_INT_32;
137 pLiteral->value.i32 = i32;
138 } else {
139 pLiteral->type = SPV_LITERAL_TYPE_INT_64;
140 pLiteral->value.i64 = i64;
141 }
142 } else {
143 uint64_t u64 = strtoull(textValue, nullptr, 10);
144 uint32_t u32 = (uint32_t)u64;
145 if (u64 == (uint64_t)u32) {
146 pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
147 pLiteral->value.u32 = u32;
148 } else {
149 pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
150 pLiteral->value.u64 = u64;
151 }
152 }
153
154 return SPV_SUCCESS;
155}
156
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400157namespace {
158
159/// Parses an immediate integer from text, guarding against overflow. If
160/// successful, adds the parsed value to pInst, advances the context past it,
161/// and returns SPV_SUCCESS. Otherwise, leaves pInst alone, emits diagnostics,
162/// and returns SPV_ERROR_INVALID_TEXT.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400163spv_result_t encodeImmediate(spvtools::AssemblyContext* context,
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400164 const char* text, spv_instruction_t* pInst) {
165 assert(*text == '!');
David Neto78e677b2015-10-05 13:28:46 -0400166 uint32_t parse_result;
dan sinclair76e0bde2018-07-06 13:25:17 -0400167 if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) {
qining1773b952016-09-01 14:27:04 -0400168 return context->diagnostic(SPV_ERROR_INVALID_TEXT)
169 << "Invalid immediate integer: !" << text + 1;
170 }
David Neto78e677b2015-10-05 13:28:46 -0400171 context->binaryEncodeU32(parse_result, pInst);
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800172 context->seekForward(static_cast<uint32_t>(strlen(text)));
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400173 return SPV_SUCCESS;
174}
175
176} // anonymous namespace
177
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400178/// @brief Translate an Opcode operand to binary form
179///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400180/// @param[in] grammar the grammar to use for compilation
181/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400182/// @param[in] type of the operand
183/// @param[in] textValue word of text to be parsed
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400184/// @param[out] pInst return binary Opcode
185/// @param[in,out] pExpectedOperands the operand types expected
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400186///
187/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400188spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,
189 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400190 const spv_operand_type_t type,
191 const char* textValue,
192 spv_instruction_t* pInst,
193 spv_operand_pattern_t* pExpectedOperands) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100194 // NOTE: Handle immediate int in the stream
195 if ('!' == textValue[0]) {
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400196 if (auto error = encodeImmediate(context, textValue, pInst)) {
197 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400198 }
Dejan Mircevski897bff92015-09-29 10:38:18 -0400199 *pExpectedOperands =
200 spvAlternatePatternFollowingImmediate(*pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100201 return SPV_SUCCESS;
202 }
203
David Neto51013d12015-10-14 11:31:51 -0400204 // Optional literal operands can fail to parse. In that case use
205 // SPV_FAILED_MATCH to avoid emitting a diagostic. Use the following
206 // for those situations.
207 spv_result_t error_code_for_literals =
208 spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
209
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100210 switch (type) {
David Netoe3f70b92015-08-27 13:50:05 -0400211 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400212 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto201caf72015-11-04 17:38:17 -0500213 case SPV_OPERAND_TYPE_RESULT_ID:
214 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
215 case SPV_OPERAND_TYPE_SCOPE_ID:
216 case SPV_OPERAND_TYPE_OPTIONAL_ID: {
Lei Zhangabafd5e2015-08-21 11:52:29 -0400217 if ('%' == textValue[0]) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100218 textValue++;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100219 } else {
David Netoac508b02015-10-09 15:48:09 -0400220 return context->diagnostic() << "Expected id to start with %.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100221 }
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400222 if (!spvIsValidID(textValue)) {
David Netoac508b02015-10-09 15:48:09 -0400223 return context->diagnostic() << "Invalid ID " << textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400224 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400225 const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400226 if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
David Netob5dc8fc2015-10-06 16:22:00 -0400227 spvInstructionAddWord(pInst, id);
David Neto2ae4a682015-11-09 18:55:42 -0500228
229 // Set the extended instruction type.
230 // The import set id is the 3rd operand of OpExtInst.
231 if (pInst->opcode == SpvOpExtInst && pInst->words.size() == 4) {
232 auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
233 if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
234 return context->diagnostic()
235 << "Invalid extended instruction import Id "
236 << pInst->words[2];
237 }
238 pInst->extInstType = ext_inst_type;
239 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100240 } break;
David Neto201caf72015-11-04 17:38:17 -0500241
David Neto445ce442015-10-15 15:22:06 -0400242 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
243 // The assembler accepts the symbolic name for an extended instruction,
244 // and emits its corresponding number.
245 spv_ext_inst_desc extInst;
246 if (grammar.lookupExtInst(pInst->extInstType, textValue, &extInst)) {
Diego Novillod2938e42017-11-08 12:40:02 -0500247 return context->diagnostic()
248 << "Invalid extended instruction name '" << textValue << "'.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100249 }
David Neto445ce442015-10-15 15:22:06 -0400250 spvInstructionAddWord(pInst, extInst->ext_inst);
251
252 // Prepare to parse the operands for the extended instructions.
Chris Forbes78338d52017-06-27 16:28:22 -0700253 spvPushOperandTypes(extInst->operandTypes, pExpectedOperands);
David Neto0f166be2015-11-11 01:56:49 -0500254 } break;
David Neto445ce442015-10-15 15:22:06 -0400255
David Neto0f166be2015-11-11 01:56:49 -0500256 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
257 // The assembler accepts the symbolic name for the opcode, but without
258 // the "Op" prefix. For example, "IAdd" is accepted. The number
259 // of the opcode is emitted.
260 SpvOp opcode;
261 if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
262 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
263 << " '" << textValue << "'.";
264 }
265 spv_opcode_desc opcodeEntry = nullptr;
266 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
267 return context->diagnostic(SPV_ERROR_INTERNAL)
268 << "OpSpecConstant opcode table out of sync";
269 }
270 spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
271
272 // Prepare to parse the operands for the opcode. Except skip the
273 // type Id and result Id, since they've already been processed.
274 assert(opcodeEntry->hasType);
275 assert(opcodeEntry->hasResult);
276 assert(opcodeEntry->numTypes >= 2);
Chris Forbes78338d52017-06-27 16:28:22 -0700277 spvPushOperandTypes(opcodeEntry->operandTypes + 2, pExpectedOperands);
David Neto445ce442015-10-15 15:22:06 -0400278 } break;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400279
David Neto201caf72015-11-04 17:38:17 -0500280 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
281 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
282 // The current operand is an *unsigned* 32-bit integer.
283 // That's just how the grammar works.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400284 spvtools::IdType expected_type = {
285 32, false, spvtools::IdTypeClass::kScalarIntegerType};
David Neto78e677b2015-10-05 13:28:46 -0400286 if (auto error = context->binaryEncodeNumericLiteral(
David Neto51013d12015-10-14 11:31:51 -0400287 textValue, error_code_for_literals, expected_type, pInst)) {
David Neto78e677b2015-10-05 13:28:46 -0400288 return error;
David Neto51013d12015-10-14 11:31:51 -0400289 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100290 } break;
David Neto201caf72015-11-04 17:38:17 -0500291
292 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
293 // This is a context-independent literal number which can be a 32-bit
294 // number of floating point value.
295 if (auto error = context->binaryEncodeNumericLiteral(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400296 textValue, error_code_for_literals, spvtools::kUnknownType,
David Neto201caf72015-11-04 17:38:17 -0500297 pInst)) {
298 return error;
299 }
300 break;
301
302 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
303 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400304 spvtools::IdType expected_type = spvtools::kUnknownType;
David Neto201caf72015-11-04 17:38:17 -0500305 // The encoding for OpConstant, OpSpecConstant and OpSwitch all
306 // depend on either their own result-id or the result-id of
307 // one of their parameters.
308 if (SpvOpConstant == pInst->opcode ||
309 SpvOpSpecConstant == pInst->opcode) {
310 // The type of the literal is determined by the type Id of the
311 // instruction.
312 expected_type =
313 context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400314 if (!spvtools::isScalarFloating(expected_type) &&
315 !spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500316 spv_opcode_desc d;
317 const char* opcode_name = "opcode";
318 if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
319 opcode_name = d->name;
320 }
321 return context->diagnostic()
322 << "Type for " << opcode_name
323 << " must be a scalar floating point or integer type";
324 }
325 } else if (pInst->opcode == SpvOpSwitch) {
326 // The type of the literal is the same as the type of the selector.
327 expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400328 if (!spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500329 return context->diagnostic()
330 << "The selector operand for OpSwitch must be the result"
331 " of an instruction that generates an integer scalar";
332 }
333 }
334 if (auto error = context->binaryEncodeNumericLiteral(
335 textValue, error_code_for_literals, expected_type, pInst)) {
336 return error;
337 }
338 } break;
339
David Neto78c3b432015-08-27 13:03:52 -0400340 case SPV_OPERAND_TYPE_LITERAL_STRING:
341 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang6d415812015-09-15 13:36:21 -0400342 spv_literal_t literal = {};
343 spv_result_t error = spvTextToLiteral(textValue, &literal);
344 if (error != SPV_SUCCESS) {
345 if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
David Neto51013d12015-10-14 11:31:51 -0400346 return context->diagnostic(error_code_for_literals)
347 << "Invalid literal string '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400348 }
Lei Zhang6d415812015-09-15 13:36:21 -0400349 if (literal.type != SPV_LITERAL_TYPE_STRING) {
David Neto51013d12015-10-14 11:31:51 -0400350 return context->diagnostic()
David Netoac508b02015-10-09 15:48:09 -0400351 << "Expected literal string, found literal number '" << textValue
352 << "'.";
Lei Zhang6d415812015-09-15 13:36:21 -0400353 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100354
355 // NOTE: Special case for extended instruction library import
Lei Zhangb36e7042015-10-28 13:40:52 -0400356 if (SpvOpExtInstImport == pInst->opcode) {
David Neto2ae4a682015-11-09 18:55:42 -0500357 const spv_ext_inst_type_t ext_inst_type =
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500358 spvExtInstImportTypeGet(literal.str.c_str());
David Neto2ae4a682015-11-09 18:55:42 -0500359 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
360 return context->diagnostic()
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500361 << "Invalid extended instruction import '" << literal.str
David Neto2ae4a682015-11-09 18:55:42 -0500362 << "'";
363 }
David Neto677e0c72016-01-05 14:56:02 -0500364 if ((error = context->recordIdAsExtInstImport(pInst->words[1],
365 ext_inst_type)))
David Neto2ae4a682015-11-09 18:55:42 -0500366 return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100367 }
368
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500369 if (context->binaryEncodeString(literal.str.c_str(), pInst))
Lei Zhang40056702015-09-11 14:31:27 -0400370 return SPV_ERROR_INVALID_TEXT;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100371 } break;
David Neto59de6102017-12-03 12:30:08 -0500372
373 // Masks.
David Neto36b0c0f2015-09-16 18:32:54 -0400374 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
375 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
376 case SPV_OPERAND_TYPE_LOOP_CONTROL:
David Neto2889a0c2016-02-15 13:50:00 -0500377 case SPV_OPERAND_TYPE_IMAGE:
David Netoee1b3bb2015-09-18 11:19:18 -0400378 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
David Neto5bf88fc2015-09-17 17:06:10 -0400379 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
David Neto59de6102017-12-03 12:30:08 -0500380 case SPV_OPERAND_TYPE_SELECTION_CONTROL:
381 case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
David Neto36b0c0f2015-09-16 18:32:54 -0400382 uint32_t value;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400383 if (grammar.parseMaskOperand(type, textValue, &value)) {
David Netoac508b02015-10-09 15:48:09 -0400384 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
David Netod9ad0502015-11-24 18:37:24 -0500385 << " operand '" << textValue << "'.";
David Neto36b0c0f2015-09-16 18:32:54 -0400386 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400387 if (auto error = context->binaryEncodeU32(value, pInst)) return error;
David Neto5bf88fc2015-09-17 17:06:10 -0400388 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700389 grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400390 } break;
391 case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
392 auto error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400393 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
394 pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400395 if (error == SPV_FAILED_MATCH) {
396 // It's not a literal number -- is it a literal string?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400397 error = spvTextEncodeOperand(grammar, context,
398 SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
399 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400400 }
401 if (error == SPV_FAILED_MATCH) {
402 // It's not a literal -- is it an ID?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400403 error =
404 spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
405 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400406 }
407 if (error) {
David Netoac508b02015-10-09 15:48:09 -0400408 return context->diagnostic(error)
409 << "Invalid word following !<integer>: " << textValue;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400410 }
411 if (pExpectedOperands->empty()) {
412 pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
413 }
David Neto36b0c0f2015-09-16 18:32:54 -0400414 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100415 default: {
416 // NOTE: All non literal operands are handled here using the operand
417 // table.
418 spv_operand_desc entry;
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400419 if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
David Netoac508b02015-10-09 15:48:09 -0400420 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
421 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400422 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400423 if (context->binaryEncodeU32(entry->value, pInst)) {
David Netoac508b02015-10-09 15:48:09 -0400424 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
425 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400426 }
David Neto78c3b432015-08-27 13:03:52 -0400427
428 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700429 spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100430 } break;
431 }
432 return SPV_SUCCESS;
433}
434
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400435namespace {
436
437/// Encodes an instruction started by !<integer> at the given position in text.
438///
439/// Puts the encoded words into *pInst. If successful, moves position past the
440/// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
441/// leaves position pointing to the error in text.
442spv_result_t encodeInstructionStartingWithImmediate(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400443 const spvtools::AssemblyGrammar& grammar,
444 spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400445 std::string firstWord;
446 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400447 auto error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400448 if (error) return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400449
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400450 if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
451 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400452 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400453 while (context->advance() != SPV_END_OF_STREAM) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400454 // A beginning of a new instruction means we're done.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400455 if (context->isStartOfNewInst()) return SPV_SUCCESS;
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400456
457 // Otherwise, there must be an operand that's either a literal, an ID, or
458 // an immediate.
459 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400460 if ((error = context->getWord(&operandValue, &nextPosition)))
David Netoac508b02015-10-09 15:48:09 -0400461 return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400462
David Netoac508b02015-10-09 15:48:09 -0400463 if (operandValue == "=")
464 return context->diagnostic() << firstWord << " not allowed before =.";
Dejan Mircevskie3a19c02015-09-11 15:03:54 -0400465
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400466 // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
467 // expanded.
468 spv_operand_pattern_t dummyExpectedOperands;
469 error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400470 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
471 pInst, &dummyExpectedOperands);
Lei Zhang40056702015-09-11 14:31:27 -0400472 if (error) return error;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400473 context->setPosition(nextPosition);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400474 }
475 return SPV_SUCCESS;
476}
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400477
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400478/// @brief Translate single Opcode and operands to binary form
479///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400480/// @param[in] grammar the grammar to use for compilation
481/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400482/// @param[in] text stream to translate
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400483/// @param[out] pInst returned binary Opcode
484/// @param[in,out] pPosition in the text stream
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400485///
486/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400487spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
488 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400489 spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400490 // Check for !<integer> first.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400491 if ('!' == context->peek()) {
492 return encodeInstructionStartingWithImmediate(grammar, context, pInst);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400493 }
494
Lei Zhang06efdc52015-09-10 14:00:00 -0400495 std::string firstWord;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100496 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400497 spv_result_t error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400498 if (error) return context->diagnostic() << "Internal Error";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100499
Lei Zhang06efdc52015-09-10 14:00:00 -0400500 std::string opcodeName;
Lei Zhangdfc50082015-08-21 11:50:55 -0400501 std::string result_id;
502 spv_position_t result_id_position = {};
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400503 if (context->startsWithOp()) {
Lei Zhang06efdc52015-09-10 14:00:00 -0400504 opcodeName = firstWord;
505 } else {
Lei Zhang06efdc52015-09-10 14:00:00 -0400506 result_id = firstWord;
Lei Zhang40056702015-09-11 14:31:27 -0400507 if ('%' != result_id.front()) {
David Netoac508b02015-10-09 15:48:09 -0400508 return context->diagnostic()
509 << "Expected <opcode> or <result-id> at the beginning "
510 "of an instruction, found '"
511 << result_id << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400512 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400513 result_id_position = context->position();
Lei Zhang06efdc52015-09-10 14:00:00 -0400514
515 // The '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400516 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400517 if (context->advance())
518 return context->diagnostic() << "Expected '=', found end of stream.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400519 std::string equal_sign;
Lei Zhang6032b982016-03-15 16:52:40 -0400520 error = context->getWord(&equal_sign, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400521 if ("=" != equal_sign)
522 return context->diagnostic() << "'=' expected after result id.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400523
524 // The <opcode> after the '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400525 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400526 if (context->advance())
527 return context->diagnostic() << "Expected opcode, found end of stream.";
Lei Zhang6032b982016-03-15 16:52:40 -0400528 error = context->getWord(&opcodeName, &nextPosition);
Lei Zhang6483bd72015-10-14 17:02:39 -0400529 if (error) return context->diagnostic(error) << "Internal Error";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400530 if (!context->startsWithOp()) {
Diego Novillod2938e42017-11-08 12:40:02 -0500531 return context->diagnostic()
532 << "Invalid Opcode prefix '" << opcodeName << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400533 }
Lei Zhangdfc50082015-08-21 11:50:55 -0400534 }
535
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100536 // NOTE: The table contains Opcode names without the "Op" prefix.
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400537 const char* pInstName = opcodeName.data() + 2;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100538
539 spv_opcode_desc opcodeEntry;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400540 error = grammar.lookupOpcode(pInstName, &opcodeEntry);
Lei Zhang40056702015-09-11 14:31:27 -0400541 if (error) {
Diego Novillod2938e42017-11-08 12:40:02 -0500542 return context->diagnostic(error)
543 << "Invalid Opcode name '" << opcodeName << "'";
Lei Zhang40056702015-09-11 14:31:27 -0400544 }
Lei Zhang9042f402015-11-05 17:45:09 -0500545 if (opcodeEntry->hasResult && result_id.empty()) {
546 return context->diagnostic()
547 << "Expected <result-id> at the beginning of an instruction, found '"
548 << firstWord << "'.";
Lei Zhang06efdc52015-09-10 14:00:00 -0400549 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100550 pInst->opcode = opcodeEntry->opcode;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400551 context->setPosition(nextPosition);
David Netob5dc8fc2015-10-06 16:22:00 -0400552 // Reserve the first word for the instruction.
553 spvInstructionAddWord(pInst, 0);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100554
David Neto78c3b432015-08-27 13:03:52 -0400555 // Maintains the ordered list of expected operand types.
556 // For many instructions we only need the {numTypes, operandTypes}
557 // entries in opcodeEntry. However, sometimes we need to modify
558 // the list as we parse the operands. This occurs when an operand
559 // has its own logical operands (such as the LocalSize operand for
560 // ExecutionMode), or for extended instructions that may have their
561 // own operands depending on the selected extended instruction.
Chris Forbes78338d52017-06-27 16:28:22 -0700562 spv_operand_pattern_t expectedOperands;
563 expectedOperands.reserve(opcodeEntry->numTypes);
564 for (auto i = 0; i < opcodeEntry->numTypes; i++)
Diego Novillod2938e42017-11-08 12:40:02 -0500565 expectedOperands.push_back(
566 opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
Lei Zhangdfc50082015-08-21 11:50:55 -0400567
David Neto78c3b432015-08-27 13:03:52 -0400568 while (!expectedOperands.empty()) {
Chris Forbes78338d52017-06-27 16:28:22 -0700569 const spv_operand_type_t type = expectedOperands.back();
570 expectedOperands.pop_back();
David Neto78c3b432015-08-27 13:03:52 -0400571
572 // Expand optional tuples lazily.
Lei Zhange78a7c12015-09-10 17:07:21 -0400573 if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
David Neto78c3b432015-08-27 13:03:52 -0400574
575 if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
576 // Handle the <result-id> for value generating instructions.
577 // We've already consumed it from the text stream. Here
578 // we inject its words into the instruction.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400579 spv_position_t temp_pos = context->position();
580 error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
581 result_id.c_str(), pInst, nullptr);
582 result_id_position = context->position();
583 // Because we are injecting we have to reset the position afterwards.
584 context->setPosition(temp_pos);
Lei Zhang40056702015-09-11 14:31:27 -0400585 if (error) return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100586 } else {
David Neto78c3b432015-08-27 13:03:52 -0400587 // Find the next word.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400588 error = context->advance();
David Neto78c3b432015-08-27 13:03:52 -0400589 if (error == SPV_END_OF_STREAM) {
590 if (spvOperandIsOptional(type)) {
Lei Zhange78a7c12015-09-10 17:07:21 -0400591 // This would have been the last potential operand for the
592 // instruction,
David Neto78c3b432015-08-27 13:03:52 -0400593 // and we didn't find one. We're finished parsing this instruction.
594 break;
595 } else {
David Netoac508b02015-10-09 15:48:09 -0400596 return context->diagnostic()
597 << "Expected operand, found end of stream.";
David Neto78c3b432015-08-27 13:03:52 -0400598 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100599 }
David Neto78c3b432015-08-27 13:03:52 -0400600 assert(error == SPV_SUCCESS && "Somebody added another way to fail");
601
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400602 if (context->isStartOfNewInst()) {
David Neto78c3b432015-08-27 13:03:52 -0400603 if (spvOperandIsOptional(type)) {
604 break;
605 } else {
David Netoac508b02015-10-09 15:48:09 -0400606 return context->diagnostic()
607 << "Expected operand, found next instruction instead.";
David Neto78c3b432015-08-27 13:03:52 -0400608 }
609 }
610
611 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400612 error = context->getWord(&operandValue, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400613 if (error) return context->diagnostic(error) << "Internal Error";
David Neto78c3b432015-08-27 13:03:52 -0400614
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400615 error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
616 pInst, &expectedOperands);
David Neto78c3b432015-08-27 13:03:52 -0400617
618 if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
619 return SPV_SUCCESS;
620
Lei Zhang40056702015-09-11 14:31:27 -0400621 if (error) return error;
David Neto78c3b432015-08-27 13:03:52 -0400622
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400623 context->setPosition(nextPosition);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100624 }
625 }
626
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400627 if (spvOpcodeGeneratesType(pInst->opcode)) {
628 if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
629 return SPV_ERROR_INVALID_TEXT;
630 }
631 } else if (opcodeEntry->hasType) {
632 // SPIR-V dictates that if an instruction has both a return value and a
633 // type ID then the type id is first, and the return value is second.
634 assert(opcodeEntry->hasResult &&
635 "Unknown opcode: has a type but no result.");
636 context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
637 }
638
David Netob5dc8fc2015-10-06 16:22:00 -0400639 if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Netoac508b02015-10-09 15:48:09 -0400640 return context->diagnostic()
641 << "Instruction too long: " << pInst->words.size()
642 << " words, but the limit is "
643 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
David Netob5dc8fc2015-10-06 16:22:00 -0400644 }
645
David Netod9ad0502015-11-24 18:37:24 -0500646 pInst->words[0] =
647 spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100648
649 return SPV_SUCCESS;
650}
651
David Netod9ad0502015-11-24 18:37:24 -0500652enum { kAssemblerVersion = 0 };
David Neto14b93e42015-11-12 18:33:47 -0500653
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400654// Populates a binary stream's |header|. The target environment is specified via
655// |env| and Id bound is via |bound|.
656spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
657 uint32_t* header) {
658 if (!header) return SPV_ERROR_INVALID_BINARY;
David Neto0b981682015-10-27 15:51:34 -0400659
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400660 header[SPV_INDEX_MAGIC_NUMBER] = SpvMagicNumber;
661 header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
662 header[SPV_INDEX_GENERATOR_NUMBER] =
David Neto14b93e42015-11-12 18:33:47 -0500663 SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400664 header[SPV_INDEX_BOUND] = bound;
665 header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
David Neto0b981682015-10-27 15:51:34 -0400666
667 return SPV_SUCCESS;
668}
669
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400670// Collects all numeric ids in the module source into |numeric_ids|.
671// This function is essentially a dry-run of spvTextToBinary.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400672spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400673 const spvtools::MessageConsumer& consumer,
674 const spv_text text,
675 std::set<uint32_t>* numeric_ids) {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400676 spvtools::AssemblyContext context(text, consumer);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400677
678 if (!text->str) return context.diagnostic() << "Missing assembly text.";
679
680 if (!grammar.isValid()) {
681 return SPV_ERROR_INVALID_TABLE;
682 }
683
684 // Skip past whitespace and comments.
685 context.advance();
686
687 while (context.hasText()) {
688 spv_instruction_t inst;
689
690 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
691 return SPV_ERROR_INVALID_TEXT;
692 }
693
694 if (context.advance()) break;
695 }
696
697 *numeric_ids = context.GetNumericIds();
698 return SPV_SUCCESS;
699}
700
David Netoc9786432015-09-01 18:05:14 -0400701// Translates a given assembly language module into binary form.
702// If a diagnostic is generated, it is not yet marked as being
703// for a text-based input.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400704spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
Diego Novillod2938e42017-11-08 12:40:02 -0500705 const spvtools::MessageConsumer& consumer,
706 const spv_text text,
707 const uint32_t options,
708 spv_binary* pBinary) {
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400709 // The ids in this set will have the same values both in source and binary.
710 // All other ids will be generated by filling in the gaps.
711 std::set<uint32_t> ids_to_preserve;
712
713 if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
714 // Collect all numeric ids from the source into ids_to_preserve.
715 const spv_result_t result =
716 GetNumericIds(grammar, consumer, text, &ids_to_preserve);
717 if (result != SPV_SUCCESS) return result;
718 }
719
dan sinclair3dad1cd2018-07-07 09:38:00 -0400720 spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400721
David Neto201caf72015-11-04 17:38:17 -0500722 if (!text->str) return context.diagnostic() << "Missing assembly text.";
David Netoac508b02015-10-09 15:48:09 -0400723
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400724 if (!grammar.isValid()) {
Lei Zhang40056702015-09-11 14:31:27 -0400725 return SPV_ERROR_INVALID_TABLE;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400726 }
Lei Zhang40056702015-09-11 14:31:27 -0400727 if (!pBinary) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100728
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100729 std::vector<spv_instruction_t> instructions;
730
David Netoea633a62015-11-02 11:40:59 -0500731 // Skip past whitespace and comments.
732 context.advance();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100733
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400734 while (context.hasText()) {
David Netob5dc8fc2015-10-06 16:22:00 -0400735 instructions.push_back({});
736 spv_instruction_t& inst = instructions.back();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100737
Lei Zhang9042f402015-11-05 17:45:09 -0500738 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400739 return SPV_ERROR_INVALID_TEXT;
Lei Zhang40056702015-09-11 14:31:27 -0400740 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400741
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400742 if (context.advance()) break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100743 }
744
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100745 size_t totalSize = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400746 for (auto& inst : instructions) {
David Netob5dc8fc2015-10-06 16:22:00 -0400747 totalSize += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100748 }
749
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400750 uint32_t* data = new uint32_t[totalSize];
Lei Zhang40056702015-09-11 14:31:27 -0400751 if (!data) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100752 uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400753 for (auto& inst : instructions) {
Lei Zhang6483bd72015-10-14 17:02:39 -0400754 memcpy(data + currentIndex, inst.words.data(),
755 sizeof(uint32_t) * inst.words.size());
David Netob5dc8fc2015-10-06 16:22:00 -0400756 currentIndex += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100757 }
758
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400759 if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
760 return error;
David Netoe4945de2015-10-28 13:50:32 -0400761
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100762 spv_binary binary = new spv_binary_t();
Lei Zhang40056702015-09-11 14:31:27 -0400763 if (!binary) {
764 delete[] data;
765 return SPV_ERROR_OUT_OF_MEMORY;
766 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100767 binary->code = data;
768 binary->wordCount = totalSize;
769
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100770 *pBinary = binary;
771
772 return SPV_SUCCESS;
773}
774
Lei Zhange78a7c12015-09-10 17:07:21 -0400775} // anonymous namespace
David Netoc9786432015-09-01 18:05:14 -0400776
Lei Zhang972788b2015-11-12 13:48:30 -0500777spv_result_t spvTextToBinary(const spv_const_context context,
778 const char* input_text,
Lei Zhangdf920ec2015-11-11 11:33:26 -0500779 const size_t input_text_size, spv_binary* pBinary,
780 spv_diagnostic* pDiagnostic) {
Diego Novillod2938e42017-11-08 12:40:02 -0500781 return spvTextToBinaryWithOptions(context, input_text, input_text_size,
782 SPV_BINARY_TO_TEXT_OPTION_NONE, pBinary,
783 pDiagnostic);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400784}
785
Diego Novillod2938e42017-11-08 12:40:02 -0500786spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
787 const char* input_text,
788 const size_t input_text_size,
789 const uint32_t options,
790 spv_binary* pBinary,
791 spv_diagnostic* pDiagnostic) {
Lei Zhang755f97f2016-09-02 18:06:18 -0400792 spv_context_t hijack_context = *context;
793 if (pDiagnostic) {
794 *pDiagnostic = nullptr;
dan sinclair3dad1cd2018-07-07 09:38:00 -0400795 spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
Lei Zhang755f97f2016-09-02 18:06:18 -0400796 }
797
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400798 spv_text_t text = {input_text, input_text_size};
dan sinclair3dad1cd2018-07-07 09:38:00 -0400799 spvtools::AssemblyGrammar grammar(&hijack_context);
Lei Zhang9042f402015-11-05 17:45:09 -0500800
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400801 spv_result_t result = spvTextToBinaryInternal(
802 grammar, hijack_context.consumer, &text, options, pBinary);
David Netoc9786432015-09-01 18:05:14 -0400803 if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
804
805 return result;
806}
807
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100808void spvTextDestroy(spv_text text) {
Lei Zhang40056702015-09-11 14:31:27 -0400809 if (!text) return;
Eric Engestromeb6ae972016-02-18 23:41:16 +0000810 delete[] text->str;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100811 delete text;
812}