blob: d06c55c331138bc1f9eb26d4c8eed56a6bfd119b [file] [log] [blame]
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01001// Copyright (c) 2015 The Khronos Group Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and/or associated documentation files (the
5// "Materials"), to deal in the Materials without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Materials, and to
8// permit persons to whom the Materials are furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Materials.
13//
14// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
15// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
16// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
17// https://www.khronos.org/registry/
18//
19// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
26
27#include <libspirv/libspirv.h>
28#include "binary.h"
29#include "diagnostic.h"
30#include "ext_inst.h"
31#include "opcode.h"
32#include "operand.h"
33#include "text.h"
34
35#include <assert.h>
36#include <stdio.h>
David Netoaffa6962015-08-24 15:33:14 -040037#include <cstdlib>
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010038#include <string.h>
39
40#include <string>
41#include <vector>
42#include <unordered_map>
43
44// Structures
45
46struct spv_named_id_table_t {
47 std::unordered_map<std::string, uint32_t> namedIds;
48};
49
50// Text API
51
52std::string getWord(const char *str) {
53 size_t index = 0;
54 while (true) {
55 switch (str[index]) {
56 case '\0':
57 case '\t':
58 case '\n':
59 case ' ':
60 break;
61 default:
62 index++;
63 }
64 }
65 return std::string(str, str + index);
66}
67
68spv_named_id_table spvNamedIdTableCreate() {
69 return new spv_named_id_table_t();
70}
71
72void spvNamedIdTableDestory(spv_named_id_table table) { delete table; }
73
74uint32_t spvNamedIdAssignOrGet(spv_named_id_table table, const char *textValue,
75 uint32_t *pBound) {
76 if (table->namedIds.end() == table->namedIds.find(textValue)) {
77 table->namedIds[textValue] = *pBound;
78 }
79 return table->namedIds[textValue];
80}
81
82int32_t spvTextIsNamedId(const char *textValue) {
83 // TODO: Strengthen the parsing of textValue to only include allow names that
84 // match: ([a-z]|[A-Z])(_|[a-z]|[A-Z]|[0-9])*
85 switch (textValue[0]) {
86 case '0':
87 case '1':
88 case '2':
89 case '3':
90 case '4':
91 case '5':
92 case '6':
93 case '7':
94 case '8':
95 case '9':
96 return false;
97 default:
98 break;
99 }
100 return true;
101}
102
103spv_result_t spvTextAdvanceLine(const spv_text text, spv_position position) {
104 while (true) {
105 switch (text->str[position->index]) {
106 case '\0':
107 return SPV_END_OF_STREAM;
108 case '\n':
109 position->column = 0;
110 position->line++;
111 position->index++;
112 return SPV_SUCCESS;
113 default:
Lei Zhangee87cc22015-08-21 11:51:28 -0400114 position->column++;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100115 position->index++;
116 break;
117 }
118 }
119}
120
121spv_result_t spvTextAdvance(const spv_text text, spv_position position) {
122 // NOTE: Consume white space, otherwise don't advance.
123 switch (text->str[position->index]) {
124 case '\0':
125 return SPV_END_OF_STREAM;
126 case ';':
Lei Zhangee87cc22015-08-21 11:51:28 -0400127 if (spv_result_t error = spvTextAdvanceLine(text, position)) return error;
128 return spvTextAdvance(text, position);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100129 case ' ':
130 case '\t':
131 position->column++;
132 position->index++;
133 return spvTextAdvance(text, position);
134 case '\n':
135 position->column = 0;
136 position->line++;
137 position->index++;
138 return spvTextAdvance(text, position);
139 default:
140 break;
141 }
142
143 return SPV_SUCCESS;
144}
145
146spv_result_t spvTextWordGet(const spv_text text,
147 const spv_position startPosition, std::string &word,
148 spv_position endPosition) {
149 spvCheck(!text->str || !text->length, return SPV_ERROR_INVALID_TEXT);
150 spvCheck(!startPosition || !endPosition, return SPV_ERROR_INVALID_POINTER);
151
152 *endPosition = *startPosition;
153
David Netoe7ee4c42015-08-25 14:21:13 -0400154 bool quoting = false;
155 bool escaping = false;
156
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100157 // NOTE: Assumes first character is not white space!
158 while (true) {
David Netoe7ee4c42015-08-25 14:21:13 -0400159 const char ch = text->str[endPosition->index];
160 if (ch == '\\')
161 escaping = !escaping;
162 else {
163 switch (ch) {
164 case '"':
165 if (!escaping) quoting = !quoting;
166 break;
167 case ' ':
168 case ';':
169 case '\t':
170 case '\n':
171 if (escaping || quoting) break;
172 // Fall through.
173 case '\0': { // NOTE: End of word found!
174 word.assign(text->str + startPosition->index,
175 (size_t)(endPosition->index - startPosition->index));
176 return SPV_SUCCESS;
177 }
178 default:
179 break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100180 }
David Netoe7ee4c42015-08-25 14:21:13 -0400181 escaping = false;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100182 }
183
184 endPosition->column++;
185 endPosition->index++;
186 }
187}
188
David Netoc9786432015-09-01 18:05:14 -0400189namespace {
190
Lei Zhangdfc50082015-08-21 11:50:55 -0400191// Returns true if the string at the given position in text starts with "Op".
David Netoc9786432015-09-01 18:05:14 -0400192bool spvStartsWithOp(const spv_text text, const spv_position position) {
David Neto78c3b432015-08-27 13:03:52 -0400193 if (text->length < position->index + 3) return false;
194 char ch0 = text->str[position->index];
195 char ch1 = text->str[position->index + 1];
196 char ch2 = text->str[position->index + 2];
197 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
Lei Zhangdfc50082015-08-21 11:50:55 -0400198}
199
David Netoc9786432015-09-01 18:05:14 -0400200} // anonymous namespace
201
Lei Zhangdfc50082015-08-21 11:50:55 -0400202// Returns true if a new instruction begins at the given position in text.
David Neto78c3b432015-08-27 13:03:52 -0400203bool spvTextIsStartOfNewInst(const spv_text text,
204 const spv_position position) {
Lei Zhangdfc50082015-08-21 11:50:55 -0400205 spv_position_t nextPosition = *position;
206 if (spvTextAdvance(text, &nextPosition)) return false;
David Neto78c3b432015-08-27 13:03:52 -0400207 if (spvStartsWithOp(text, &nextPosition)) return true;
Lei Zhangdfc50082015-08-21 11:50:55 -0400208
209 std::string word;
David Neto78c3b432015-08-27 13:03:52 -0400210 spv_position_t startPosition = *position;
Lei Zhangdfc50082015-08-21 11:50:55 -0400211 if (spvTextWordGet(text, &startPosition, word, &nextPosition)) return false;
212 if ('%' != word.front()) return false;
213
214 if (spvTextAdvance(text, &nextPosition)) return false;
215 startPosition = nextPosition;
216 if (spvTextWordGet(text, &startPosition, word, &nextPosition)) return false;
217 if ("=" != word) return false;
218
219 if (spvTextAdvance(text, &nextPosition)) return false;
220 startPosition = nextPosition;
221 if (spvStartsWithOp(text, &startPosition)) return true;
222 return false;
223}
224
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100225spv_result_t spvTextStringGet(const spv_text text,
226 const spv_position startPosition,
227 std::string &string, spv_position endPosition) {
228 spvCheck(!text->str || !text->length, return SPV_ERROR_INVALID_TEXT);
229 spvCheck(!startPosition || !endPosition, return SPV_ERROR_INVALID_POINTER);
230
231 spvCheck('"' != text->str[startPosition->index],
232 return SPV_ERROR_INVALID_TEXT);
233
234 *endPosition = *startPosition;
235
236 // NOTE: Assumes first character is not white space
237 while (true) {
238 endPosition->column++;
239 endPosition->index++;
240
241 switch (text->str[endPosition->index]) {
242 case '"': {
243 endPosition->column++;
244 endPosition->index++;
245
246 string.assign(text->str + startPosition->index,
247 (size_t)(endPosition->index - startPosition->index));
248
249 return SPV_SUCCESS;
250 }
251 case '\n':
252 case '\0':
253 return SPV_ERROR_INVALID_TEXT;
254 default:
255 break;
256 }
257 }
258}
259
260spv_result_t spvTextToUInt32(const char *textValue, uint32_t *pValue) {
261 char *endPtr = nullptr;
262 *pValue = strtoul(textValue, &endPtr, 0);
263 if (0 == *pValue && textValue == endPtr) {
264 return SPV_ERROR_INVALID_TEXT;
265 }
266 return SPV_SUCCESS;
267}
268
269spv_result_t spvTextToLiteral(const char *textValue, spv_literal_t *pLiteral) {
270 bool isSigned = false;
David Netoaffa6962015-08-24 15:33:14 -0400271 int numPeriods = 0;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100272 bool isString = false;
273
David Netoaffa6962015-08-24 15:33:14 -0400274 const size_t len = strlen(textValue);
David Neto98290a22015-08-24 16:27:02 -0400275 if (len == 0) return SPV_FAILED_MATCH;
276
David Netoaffa6962015-08-24 15:33:14 -0400277 for (uint64_t index = 0; index < len; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100278 switch (textValue[index]) {
279 case '0':
280 case '1':
281 case '2':
282 case '3':
283 case '4':
284 case '5':
285 case '6':
286 case '7':
287 case '8':
288 case '9':
289 break;
290 case '.':
David Netoaffa6962015-08-24 15:33:14 -0400291 numPeriods++;
292 break;
293 case '-':
294 if (index == 0) {
295 isSigned = true;
296 } else {
297 isString = true;
298 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100299 break;
300 default:
301 isString = true;
David Netoaffa6962015-08-24 15:33:14 -0400302 index = len; // break out of the loop too.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100303 break;
304 }
305 }
306
David Netoaffa6962015-08-24 15:33:14 -0400307 pLiteral->type = spv_literal_type_t(99);
308
309 if (isString || numPeriods > 1 || (isSigned && len==1)) {
David Netoaffa6962015-08-24 15:33:14 -0400310 // TODO(dneto): Allow escaping.
David Neto98290a22015-08-24 16:27:02 -0400311 if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
312 return SPV_FAILED_MATCH;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100313 pLiteral->type = SPV_LITERAL_TYPE_STRING;
David Netoaffa6962015-08-24 15:33:14 -0400314 // Need room for the null-terminator.
David Neto98290a22015-08-24 16:27:02 -0400315 if (len >= sizeof(pLiteral->value.str)) return SPV_ERROR_OUT_OF_MEMORY;
316 strncpy(pLiteral->value.str, textValue+1, len-2);
317 pLiteral->value.str[len-2] = 0;
David Netoaffa6962015-08-24 15:33:14 -0400318 } else if (numPeriods == 1) {
319 double d = std::strtod(textValue, nullptr);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100320 float f = (float)d;
321 if (d == (double)f) {
322 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
323 pLiteral->value.f = f;
324 } else {
325 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
326 pLiteral->value.d = d;
327 }
328 } else if (isSigned) {
329 int64_t i64 = strtoll(textValue, nullptr, 10);
330 int32_t i32 = (int32_t)i64;
331 if (i64 == (int64_t)i32) {
332 pLiteral->type = SPV_LITERAL_TYPE_INT_32;
333 pLiteral->value.i32 = i32;
334 } else {
335 pLiteral->type = SPV_LITERAL_TYPE_INT_64;
336 pLiteral->value.i64 = i64;
337 }
338 } else {
339 uint64_t u64 = strtoull(textValue, nullptr, 10);
340 uint32_t u32 = (uint32_t)u64;
341 if (u64 == (uint64_t)u32) {
342 pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
343 pLiteral->value.u32 = u32;
344 } else {
345 pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
346 pLiteral->value.u64 = u64;
347 }
348 }
349
350 return SPV_SUCCESS;
351}
352
353spv_result_t spvTextEncodeOperand(
354 const spv_operand_type_t type, const char *textValue,
355 const spv_operand_table operandTable, const spv_ext_inst_table extInstTable,
356 spv_named_id_table namedIdTable, spv_instruction_t *pInst,
David Neto78c3b432015-08-27 13:03:52 -0400357 spv_operand_pattern_t* pExpectedOperands, uint32_t *pBound,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100358 const spv_position position, spv_diagnostic *pDiagnostic) {
359 // NOTE: Handle immediate int in the stream
360 if ('!' == textValue[0]) {
361 const char *begin = textValue + 1;
362 char *end = nullptr;
363 uint32_t immediateInt = strtoul(begin, &end, 0);
364 size_t size = strlen(textValue);
365 size_t length = (end - begin);
366 spvCheck(size - 1 != length, DIAGNOSTIC << "Invalid immediate integer '"
367 << textValue << "'.";
368 return SPV_ERROR_INVALID_TEXT);
369 position->column += size;
370 position->index += size;
371 pInst->words[pInst->wordCount] = immediateInt;
372 pInst->wordCount += 1;
373 return SPV_SUCCESS;
374 }
375
376 switch (type) {
David Netoe3f70b92015-08-27 13:50:05 -0400377 case SPV_OPERAND_TYPE_ID:
David Neto78c3b432015-08-27 13:03:52 -0400378 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
379 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netoe3f70b92015-08-27 13:50:05 -0400380 case SPV_OPERAND_TYPE_RESULT_ID: {
Lei Zhangabafd5e2015-08-21 11:52:29 -0400381 if ('%' == textValue[0]) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100382 textValue++;
383 }
Lei Zhangabafd5e2015-08-21 11:52:29 -0400384 // TODO: Force all ID's to be prefixed with '%'.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100385 uint32_t id = 0;
386 if (spvTextIsNamedId(textValue)) {
387 id = spvNamedIdAssignOrGet(namedIdTable, textValue, pBound);
388 } else {
389 spvCheck(spvTextToUInt32(textValue, &id),
David Neto78c3b432015-08-27 13:03:52 -0400390 DIAGNOSTIC
391 << "Invalid "
392 << ((type == SPV_OPERAND_TYPE_RESULT_ID) ? "result " : "")
393 << "ID '" << textValue << "'.";
394 return (spvOperandIsOptional(type) ? SPV_FAILED_MATCH
395 : SPV_ERROR_INVALID_TEXT));
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100396 }
397 pInst->words[pInst->wordCount++] = id;
398 if (*pBound <= id) {
399 *pBound = id + 1;
400 }
401 } break;
402 case SPV_OPERAND_TYPE_LITERAL_NUMBER: {
403 // NOTE: Special case for extension instruction lookup
404 if (OpExtInst == pInst->opcode) {
405 spv_ext_inst_desc extInst;
406 spvCheck(spvExtInstTableNameLookup(extInstTable, pInst->extInstType,
407 textValue, &extInst),
408 DIAGNOSTIC << "Invalid extended instruction name '"
409 << textValue << "'.";
410 return SPV_ERROR_INVALID_TEXT);
411 pInst->words[pInst->wordCount++] = extInst->ext_inst;
David Neto78c3b432015-08-27 13:03:52 -0400412
413 // Prepare to parse the operands for the extended instructions.
414 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
415
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100416 return SPV_SUCCESS;
417 }
418
419 // TODO: Literal numbers can be any number up to 64 bits wide. This
420 // includes integers and floating point numbers.
David Neto78c3b432015-08-27 13:03:52 -0400421 // TODO(dneto): Suggest using spvTextToLiteral and looking for an
422 // appropriate result type.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100423 spvCheck(spvTextToUInt32(textValue, &pInst->words[pInst->wordCount++]),
424 DIAGNOSTIC << "Invalid literal number '" << textValue << "'.";
425 return SPV_ERROR_INVALID_TEXT);
426 } break;
David Neto78c3b432015-08-27 13:03:52 -0400427 case SPV_OPERAND_TYPE_LITERAL:
428 case SPV_OPERAND_TYPE_LITERAL_IN_OPTIONAL_TUPLE:
429 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100430 spv_literal_t literal = {};
David Neto78c3b432015-08-27 13:03:52 -0400431 // TODO(dneto): Is return code different for optional operands?
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100432 spvCheck(spvTextToLiteral(textValue, &literal),
433 DIAGNOSTIC << "Invalid literal '" << textValue << "'.";
434 return SPV_ERROR_INVALID_TEXT);
435 switch (literal.type) {
436 case SPV_LITERAL_TYPE_INT_32:
437 spvCheck(spvBinaryEncodeU32((uint32_t)literal.value.i32, pInst,
438 position, pDiagnostic),
439 return SPV_ERROR_INVALID_TEXT);
440 break;
441 case SPV_LITERAL_TYPE_INT_64: {
442 spvCheck(spvBinaryEncodeU64((uint64_t)literal.value.i64, pInst,
443 position, pDiagnostic),
444 return SPV_ERROR_INVALID_TEXT);
445 } break;
446 case SPV_LITERAL_TYPE_UINT_32: {
447 spvCheck(spvBinaryEncodeU32(literal.value.u32, pInst, position,
448 pDiagnostic),
449 return SPV_ERROR_INVALID_TEXT);
450 } break;
451 case SPV_LITERAL_TYPE_UINT_64: {
452 spvCheck(spvBinaryEncodeU64((uint64_t)literal.value.u64, pInst,
453 position, pDiagnostic),
454 return SPV_ERROR_INVALID_TEXT);
455 } break;
456 case SPV_LITERAL_TYPE_FLOAT_32: {
457 spvCheck(spvBinaryEncodeU32((uint32_t)literal.value.f, pInst,
458 position, pDiagnostic),
459 return SPV_ERROR_INVALID_TEXT);
460 } break;
461 case SPV_LITERAL_TYPE_FLOAT_64: {
462 spvCheck(spvBinaryEncodeU64((uint64_t)literal.value.d, pInst,
463 position, pDiagnostic),
464 return SPV_ERROR_INVALID_TEXT);
465 } break;
466 case SPV_LITERAL_TYPE_STRING: {
467 spvCheck(spvBinaryEncodeString(literal.value.str, pInst, position,
468 pDiagnostic),
469 return SPV_ERROR_INVALID_TEXT);
470 } break;
471 default:
472 DIAGNOSTIC << "Invalid literal '" << textValue << "'";
473 return SPV_ERROR_INVALID_TEXT;
474 }
475 } break;
David Neto78c3b432015-08-27 13:03:52 -0400476 case SPV_OPERAND_TYPE_LITERAL_STRING:
477 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100478 size_t len = strlen(textValue);
479 spvCheck('"' != textValue[0] && '"' != textValue[len - 1],
David Neto78c3b432015-08-27 13:03:52 -0400480 if (spvOperandIsOptional(type))
481 return SPV_FAILED_MATCH;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100482 DIAGNOSTIC << "Invalid literal string '" << textValue
483 << "', expected quotes.";
David Neto78c3b432015-08-27 13:03:52 -0400484 return SPV_ERROR_INVALID_TEXT;);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100485 // NOTE: Strip quotes
486 std::string text(textValue + 1, len - 2);
487
488 // NOTE: Special case for extended instruction library import
489 if (OpExtInstImport == pInst->opcode) {
490 pInst->extInstType = spvExtInstImportTypeGet(text.c_str());
491 }
492
493 spvCheck(
494 spvBinaryEncodeString(text.c_str(), pInst, position, pDiagnostic),
495 return SPV_ERROR_INVALID_TEXT);
496 } break;
David Neto78c3b432015-08-27 13:03:52 -0400497 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
498 assert(0 && " Handle optional optional image operands");
499 break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100500 default: {
501 // NOTE: All non literal operands are handled here using the operand
502 // table.
503 spv_operand_desc entry;
504 spvCheck(spvOperandTableNameLookup(operandTable, type, textValue, &entry),
505 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " '"
506 << textValue << "'.";
507 return SPV_ERROR_INVALID_TEXT;);
508 spvCheck(spvBinaryEncodeU32(entry->value, pInst, position, pDiagnostic),
509 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " '"
510 << textValue << "'.";
511 return SPV_ERROR_INVALID_TEXT;);
David Neto78c3b432015-08-27 13:03:52 -0400512
513 // Prepare to parse the operands for this logical operand.
514 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100515 } break;
516 }
517 return SPV_SUCCESS;
518}
519
520spv_result_t spvTextEncodeOpcode(
521 const spv_text text, const spv_opcode_table opcodeTable,
522 const spv_operand_table operandTable, const spv_ext_inst_table extInstTable,
523 spv_named_id_table namedIdTable, uint32_t *pBound, spv_instruction_t *pInst,
524 spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhangdfc50082015-08-21 11:50:55 -0400525 // An assembly instruction has two possible formats:
526 // 1. <opcode> <operand>.., e.g., "OpMemoryModel Physical64 OpenCL".
527 // 2. <result-id> = <opcode> <operand>.., e.g., "%void = OpTypeVoid".
528
529 // Assume it's the first format at the beginning.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100530 std::string opcodeName;
531 spv_position_t nextPosition = {};
Lei Zhangdfc50082015-08-21 11:50:55 -0400532 spv_result_t error =
533 spvTextWordGet(text, position, opcodeName, &nextPosition);
534 spvCheck(error, return error);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100535
536 // NOTE: Handle insertion of an immediate integer into the binary stream
Lei Zhangdfc50082015-08-21 11:50:55 -0400537 bool immediate = false;
538 spvCheck('!' == text->str[position->index], immediate = true);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100539 if (immediate) {
540 const char *begin = opcodeName.data() + 1;
541 char *end = nullptr;
542 uint32_t immediateInt = strtoul(begin, &end, 0);
543 size_t size = opcodeName.size() - 1;
544 spvCheck(size != (size_t)(end - begin),
545 DIAGNOSTIC << "Invalid immediate integer '" << opcodeName << "'.";
546 return SPV_ERROR_INVALID_TEXT);
547 position->column += opcodeName.size();
548 position->index += opcodeName.size();
549 pInst->words[0] = immediateInt;
550 pInst->wordCount = 1;
551 return SPV_SUCCESS;
552 }
553
Lei Zhangdfc50082015-08-21 11:50:55 -0400554 // Handle value generating instructions (the second format above) here.
555 std::string result_id;
556 spv_position_t result_id_position = {};
557 // If the word we get doesn't start with "Op", assume it's an <result-id>
558 // from now.
559 spvCheck(!spvStartsWithOp(text, position), result_id = opcodeName);
560 if (!result_id.empty()) {
561 spvCheck('%' != result_id.front(),
562 DIAGNOSTIC << "Expected <opcode> or <result-id> at the beginning "
563 "of an instruction, found '"
564 << result_id << "'.";
565 return SPV_ERROR_INVALID_TEXT);
566 result_id_position = *position;
567 *position = nextPosition;
568 spvCheck(spvTextAdvance(text, position),
569 DIAGNOSTIC << "Expected '=', found end of stream.";
570 return SPV_ERROR_INVALID_TEXT);
571 // The '=' sign.
572 std::string equal_sign;
573 error = spvTextWordGet(text, position, equal_sign, &nextPosition);
574 spvCheck("=" != equal_sign, DIAGNOSTIC << "'=' expected after result id.";
575 return SPV_ERROR_INVALID_TEXT);
576
577 // The <opcode> after the '=' sign.
578 *position = nextPosition;
579 spvCheck(spvTextAdvance(text, position),
580 DIAGNOSTIC << "Expected opcode, found end of stream.";
581 return SPV_ERROR_INVALID_TEXT);
Lei Zhang977e9bc2015-08-21 11:52:03 -0400582 error = spvTextWordGet(text, position, opcodeName, &nextPosition);
583 spvCheck(error, return error);
Lei Zhangdfc50082015-08-21 11:50:55 -0400584 spvCheck(!spvStartsWithOp(text, position),
585 DIAGNOSTIC << "Invalid Opcode prefix '" << opcodeName << "'.";
586 return SPV_ERROR_INVALID_TEXT);
Lei Zhangdfc50082015-08-21 11:50:55 -0400587 }
588
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100589 // NOTE: The table contains Opcode names without the "Op" prefix.
590 const char *pInstName = opcodeName.data() + 2;
591
592 spv_opcode_desc opcodeEntry;
Lei Zhangdfc50082015-08-21 11:50:55 -0400593 error = spvOpcodeTableNameLookup(opcodeTable, pInstName, &opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100594 spvCheck(error, DIAGNOSTIC << "Invalid Opcode name '"
595 << getWord(text->str + position->index) << "'";
596 return error);
597 pInst->opcode = opcodeEntry->opcode;
598 *position = nextPosition;
599 pInst->wordCount++;
600
David Neto78c3b432015-08-27 13:03:52 -0400601 // Maintains the ordered list of expected operand types.
602 // For many instructions we only need the {numTypes, operandTypes}
603 // entries in opcodeEntry. However, sometimes we need to modify
604 // the list as we parse the operands. This occurs when an operand
605 // has its own logical operands (such as the LocalSize operand for
606 // ExecutionMode), or for extended instructions that may have their
607 // own operands depending on the selected extended instruction.
608 spv_operand_pattern_t expectedOperands(
609 opcodeEntry->operandTypes,
610 opcodeEntry->operandTypes + opcodeEntry->numTypes);
Lei Zhangdfc50082015-08-21 11:50:55 -0400611
David Neto78c3b432015-08-27 13:03:52 -0400612 while (!expectedOperands.empty()) {
613 const spv_operand_type_t type = expectedOperands.front();
614 expectedOperands.pop_front();
615
616 // Expand optional tuples lazily.
617 if (spvExpandOperandSequenceOnce(type, &expectedOperands))
618 continue;
619
620 if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
621 // Handle the <result-id> for value generating instructions.
622 // We've already consumed it from the text stream. Here
623 // we inject its words into the instruction.
Lei Zhangdfc50082015-08-21 11:50:55 -0400624 error = spvTextEncodeOperand(
625 SPV_OPERAND_TYPE_RESULT_ID, result_id.c_str(), operandTable,
David Neto78c3b432015-08-27 13:03:52 -0400626 extInstTable, namedIdTable, pInst, nullptr, pBound,
Lei Zhangdfc50082015-08-21 11:50:55 -0400627 &result_id_position, pDiagnostic);
628 spvCheck(error, return error);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100629 } else {
David Neto78c3b432015-08-27 13:03:52 -0400630 // Find the next word.
631 error = spvTextAdvance(text, position);
632 if (error == SPV_END_OF_STREAM) {
633 if (spvOperandIsOptional(type)) {
634 // This would have been the last potential operand for the instruction,
635 // and we didn't find one. We're finished parsing this instruction.
636 break;
637 } else {
638 DIAGNOSTIC << "Expected operand, found end of stream.";
639 return SPV_ERROR_INVALID_TEXT;
640 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100641 }
David Neto78c3b432015-08-27 13:03:52 -0400642 assert(error == SPV_SUCCESS && "Somebody added another way to fail");
643
644 if (spvTextIsStartOfNewInst(text, position)) {
645 if (spvOperandIsOptional(type)) {
646 break;
647 } else {
648 DIAGNOSTIC << "Expected operand, found next instruction instead.";
649 return SPV_ERROR_INVALID_TEXT;
650 }
651 }
652
653 std::string operandValue;
654 error = spvTextWordGet(text, position, operandValue, &nextPosition);
655 spvCheck(error, return error);
656
657 error = spvTextEncodeOperand(
658 type, operandValue.c_str(),
659 operandTable, extInstTable, namedIdTable, pInst, &expectedOperands,
660 pBound, position, pDiagnostic);
661
662 if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
663 return SPV_SUCCESS;
664
665 spvCheck(error, return error);
666
667 *position = nextPosition;
668
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100669 }
670 }
671
672 pInst->words[0] = spvOpcodeMake(pInst->wordCount, opcodeEntry->opcode);
673
674 return SPV_SUCCESS;
675}
676
David Netoc9786432015-09-01 18:05:14 -0400677namespace {
678
679// Translates a given assembly language module into binary form.
680// If a diagnostic is generated, it is not yet marked as being
681// for a text-based input.
682spv_result_t spvTextToBinaryInternal(const spv_text text,
683 const spv_opcode_table opcodeTable,
684 const spv_operand_table operandTable,
685 const spv_ext_inst_table extInstTable,
686 spv_binary *pBinary,
687 spv_diagnostic *pDiagnostic) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100688 spv_position_t position = {};
689 spvCheck(!text->str || !text->length, DIAGNOSTIC << "Text stream is empty.";
690 return SPV_ERROR_INVALID_TEXT);
691 spvCheck(!opcodeTable || !operandTable || !extInstTable,
692 return SPV_ERROR_INVALID_TABLE);
693 spvCheck(!pBinary, return SPV_ERROR_INVALID_POINTER);
694 spvCheck(!pDiagnostic, return SPV_ERROR_INVALID_DIAGNOSTIC);
695
696 // NOTE: Ensure diagnostic is zero initialised
697 *pDiagnostic = {};
698
699 uint32_t bound = 1;
700
701 std::vector<spv_instruction_t> instructions;
702
703 spvCheck(spvTextAdvance(text, &position), DIAGNOSTIC
704 << "Text stream is empty.";
705 return SPV_ERROR_INVALID_TEXT);
706
707 spv_named_id_table namedIdTable = spvNamedIdTableCreate();
708 spvCheck(!namedIdTable, return SPV_ERROR_OUT_OF_MEMORY);
709
710 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
711 while (text->length > position.index) {
712 spv_instruction_t inst = {};
713 inst.extInstType = extInstType;
714
715 spvCheck(spvTextEncodeOpcode(text, opcodeTable, operandTable, extInstTable,
716 namedIdTable, &bound, &inst, &position,
717 pDiagnostic),
718 spvNamedIdTableDestory(namedIdTable);
719 return SPV_ERROR_INVALID_TEXT);
720 extInstType = inst.extInstType;
721
722 instructions.push_back(inst);
723
724 spvCheck(spvTextAdvance(text, &position), break);
725 }
726
727 spvNamedIdTableDestory(namedIdTable);
728
729 size_t totalSize = SPV_INDEX_INSTRUCTION;
730 for (auto &inst : instructions) {
731 totalSize += inst.wordCount;
732 }
733
734 uint32_t *data = new uint32_t[totalSize];
735 spvCheck(!data, return SPV_ERROR_OUT_OF_MEMORY);
736 uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
737 for (auto &inst : instructions) {
738 memcpy(data + currentIndex, inst.words, sizeof(uint32_t) * inst.wordCount);
739 currentIndex += inst.wordCount;
740 }
741
742 spv_binary binary = new spv_binary_t();
743 spvCheck(!binary, delete[] data; return SPV_ERROR_OUT_OF_MEMORY);
744 binary->code = data;
745 binary->wordCount = totalSize;
746
747 spv_result_t error = spvBinaryHeaderSet(binary, bound);
748 spvCheck(error, spvBinaryDestroy(binary); return error);
749
750 *pBinary = binary;
751
752 return SPV_SUCCESS;
753}
754
David Netoc9786432015-09-01 18:05:14 -0400755} // anonymous namespace
756
757spv_result_t spvTextToBinary(const spv_text text,
758 const spv_opcode_table opcodeTable,
759 const spv_operand_table operandTable,
760 const spv_ext_inst_table extInstTable,
761 spv_binary *pBinary, spv_diagnostic *pDiagnostic) {
762 spv_result_t result = spvTextToBinaryInternal(
763 text, opcodeTable, operandTable, extInstTable, pBinary, pDiagnostic);
764 if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
765
766 return result;
767}
768
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100769void spvTextDestroy(spv_text text) {
770 spvCheck(!text, return );
771 if (text->str) {
772 delete[] text->str;
773 }
774 delete text;
775}