Coverage Report

Created: 2026-08-13 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/shaderc/third_party/spirv-tools/source/text.cpp
Line
Count
Source
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
15
#include "source/text.h"
16
17
#include <algorithm>
18
#include <cassert>
19
#include <cctype>
20
#include <cstdio>
21
#include <cstdlib>
22
#include <cstring>
23
#include <memory>
24
#include <set>
25
#include <sstream>
26
#include <string>
27
#include <unordered_map>
28
#include <utility>
29
#include <vector>
30
31
#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/opcode.h"
37
#include "source/operand.h"
38
#include "source/spirv_constant.h"
39
#include "source/spirv_target_env.h"
40
#include "source/table.h"
41
#include "source/table2.h"
42
#include "source/text_handler.h"
43
#include "source/util/bitutils.h"
44
#include "source/util/parse_number.h"
45
#include "spirv-tools/libspirv.h"
46
47
0
bool spvIsValidIDCharacter(const char value) {
48
0
  return value == '_' || 0 != ::isalnum(static_cast<unsigned char>(value));
49
0
}
50
51
// Returns true if the given string represents a valid ID name.
52
0
bool spvIsValidID(const char* textValue) {
53
0
  const char* c = textValue;
54
0
  for (; *c != '\0'; ++c) {
55
0
    if (!spvIsValidIDCharacter(*c)) {
56
0
      return false;
57
0
    }
58
0
  }
59
  // If the string was empty, then the ID also is not valid.
60
0
  return c != textValue;
61
0
}
62
63
// Text API
64
65
0
spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
66
0
  bool isSigned = false;
67
0
  int numPeriods = 0;
68
0
  bool isString = false;
69
70
0
  const size_t len = strlen(textValue);
71
0
  if (len == 0) return SPV_FAILED_MATCH;
72
73
0
  for (uint64_t index = 0; index < len; ++index) {
74
0
    switch (textValue[index]) {
75
0
      case '0':
76
0
      case '1':
77
0
      case '2':
78
0
      case '3':
79
0
      case '4':
80
0
      case '5':
81
0
      case '6':
82
0
      case '7':
83
0
      case '8':
84
0
      case '9':
85
0
        break;
86
0
      case '.':
87
0
        numPeriods++;
88
0
        break;
89
0
      case '-':
90
0
        if (index == 0) {
91
0
          isSigned = true;
92
0
        } else {
93
0
          isString = true;
94
0
        }
95
0
        break;
96
0
      default:
97
0
        isString = true;
98
0
        index = len;  // break out of the loop too.
99
0
        break;
100
0
    }
101
0
  }
102
103
0
  pLiteral->type = spv_literal_type_t(99);
104
105
0
  if (isString || numPeriods > 1 || (isSigned && len == 1)) {
106
0
    if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
107
0
      return SPV_FAILED_MATCH;
108
0
    bool escaping = false;
109
0
    for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
110
0
      if ((*val == '\\') && (!escaping)) {
111
0
        escaping = true;
112
0
      } else {
113
        // Have to save space for the null-terminator
114
0
        if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
115
0
          return SPV_ERROR_OUT_OF_MEMORY;
116
0
        pLiteral->str.push_back(*val);
117
0
        escaping = false;
118
0
      }
119
0
    }
120
121
0
    pLiteral->type = SPV_LITERAL_TYPE_STRING;
122
0
  } else if (numPeriods == 1) {
123
0
    double d = std::strtod(textValue, nullptr);
124
0
    float f = (float)d;
125
0
    if (d == (double)f) {
126
0
      pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
127
0
      pLiteral->value.f = f;
128
0
    } else {
129
0
      pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
130
0
      pLiteral->value.d = d;
131
0
    }
132
0
  } else if (isSigned) {
133
0
    int64_t i64 = strtoll(textValue, nullptr, 10);
134
0
    int32_t i32 = (int32_t)i64;
135
0
    if (i64 == (int64_t)i32) {
136
0
      pLiteral->type = SPV_LITERAL_TYPE_INT_32;
137
0
      pLiteral->value.i32 = i32;
138
0
    } else {
139
0
      pLiteral->type = SPV_LITERAL_TYPE_INT_64;
140
0
      pLiteral->value.i64 = i64;
141
0
    }
142
0
  } else {
143
0
    uint64_t u64 = strtoull(textValue, nullptr, 10);
144
0
    uint32_t u32 = (uint32_t)u64;
145
0
    if (u64 == (uint64_t)u32) {
146
0
      pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
147
0
      pLiteral->value.u32 = u32;
148
0
    } else {
149
0
      pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
150
0
      pLiteral->value.u64 = u64;
151
0
    }
152
0
  }
153
154
0
  return SPV_SUCCESS;
155
0
}
156
157
namespace {
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.
163
spv_result_t encodeImmediate(spvtools::AssemblyContext* context,
164
0
                             const char* text, spv_instruction_t* pInst) {
165
0
  assert(*text == '!');
166
0
  uint32_t parse_result;
167
0
  if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) {
168
0
    return context->diagnostic(SPV_ERROR_INVALID_TEXT)
169
0
           << "Invalid immediate integer: !" << text + 1;
170
0
  }
171
0
  context->binaryEncodeU32(parse_result, pInst);
172
0
  context->seekForward(static_cast<uint32_t>(strlen(text)));
173
0
  return SPV_SUCCESS;
174
0
}
175
176
}  // anonymous namespace
177
178
/// @brief Translate an Opcode operand to binary form
179
///
180
/// @param[in] grammar the grammar to use for compilation
181
/// @param[in, out] context the dynamic compilation info
182
/// @param[in] type of the operand
183
/// @param[in] textValue word of text to be parsed
184
/// @param[out] pInst return binary Opcode
185
/// @param[in,out] pExpectedOperands the operand types expected
186
///
187
/// @return result code
188
spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,
189
                                  spvtools::AssemblyContext* context,
190
                                  const spv_operand_type_t type,
191
                                  const char* textValue,
192
                                  spv_instruction_t* pInst,
193
0
                                  spv_operand_pattern_t* pExpectedOperands) {
194
  // NOTE: Handle immediate int in the stream
195
0
  if ('!' == textValue[0]) {
196
0
    if (auto error = encodeImmediate(context, textValue, pInst)) {
197
0
      return error;
198
0
    }
199
0
    *pExpectedOperands =
200
0
        spvAlternatePatternFollowingImmediate(*pExpectedOperands);
201
0
    return SPV_SUCCESS;
202
0
  }
203
204
  // Optional literal operands can fail to parse. In that case use
205
  // SPV_FAILED_MATCH to avoid emitting a diagnostic.  Use the following
206
  // for those situations.
207
0
  spv_result_t error_code_for_literals =
208
0
      spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
209
210
0
  switch (type) {
211
0
    case SPV_OPERAND_TYPE_ID:
212
0
    case SPV_OPERAND_TYPE_TYPE_ID:
213
0
    case SPV_OPERAND_TYPE_RESULT_ID:
214
0
    case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
215
0
    case SPV_OPERAND_TYPE_SCOPE_ID:
216
0
    case SPV_OPERAND_TYPE_OPTIONAL_ID: {
217
0
      if ('%' == textValue[0]) {
218
0
        textValue++;
219
0
      } else {
220
0
        return context->diagnostic() << "Expected id to start with %.";
221
0
      }
222
0
      if (!spvIsValidID(textValue)) {
223
0
        return context->diagnostic() << "Invalid ID " << textValue;
224
0
      }
225
0
      const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
226
0
      if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
227
0
      spvInstructionAddWord(pInst, id);
228
229
      // Set the extended instruction type.
230
      // The import set id is the 3rd operand of OpExtInst.
231
0
      if (spvIsExtendedInstruction(pInst->opcode) && pInst->words.size() == 4) {
232
0
        auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
233
0
        if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
234
0
          return context->diagnostic()
235
0
                 << "Invalid extended instruction import Id "
236
0
                 << pInst->words[2];
237
0
        }
238
0
        pInst->extInstType = ext_inst_type;
239
0
      }
240
0
    } break;
241
242
0
    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
0
      const spvtools::ExtInstDesc* desc = nullptr;
246
0
      if (spvtools::LookupExtInst(pInst->extInstType, textValue, &desc) ==
247
0
          SPV_SUCCESS) {
248
        // if we know about this extended instruction, push the numeric value
249
0
        spvInstructionAddWord(pInst, desc->value);
250
251
        // Push VARIABLE_ID so extra trailing operands from future NSDI
252
        // versions are silently absorbed after the instruction-specific ones.
253
0
        if (spvExtInstIsNonSemantic(pInst->extInstType)) {
254
0
          pExpectedOperands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
255
0
        }
256
257
        // Prepare to parse the operands for the extended instructions.
258
0
        spvPushOperandTypes(desc->operands(), pExpectedOperands);
259
0
      } else {
260
        // if we don't know this extended instruction and the set isn't
261
        // non-semantic, we cannot process further
262
0
        if (!spvExtInstIsNonSemantic(pInst->extInstType)) {
263
0
          return context->diagnostic()
264
0
                 << "Invalid extended instruction name '" << textValue << "'.";
265
0
        } else {
266
          // for non-semantic instruction sets, as long as the text name is an
267
          // integer value we can encode it since we know the form of all such
268
          // extended instructions
269
0
          spv_literal_t extInstValue;
270
0
          if (spvTextToLiteral(textValue, &extInstValue) ||
271
0
              extInstValue.type != SPV_LITERAL_TYPE_UINT_32) {
272
0
            return context->diagnostic()
273
0
                   << "Couldn't translate unknown extended instruction name '"
274
0
                   << textValue << "' to unsigned integer.";
275
0
          }
276
277
0
          spvInstructionAddWord(pInst, extInstValue.value.u32);
278
279
          // opcode contains an unknown number of IDs.
280
0
          pExpectedOperands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
281
0
        }
282
0
      }
283
0
    } break;
284
285
0
    case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
286
      // The assembler accepts the symbolic name for the opcode, but without
287
      // the "Op" prefix.  For example, "IAdd" is accepted.  The number
288
      // of the opcode is emitted.
289
0
      spv::Op opcode;
290
0
      if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
291
0
        return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
292
0
                                     << " '" << textValue << "'.";
293
0
      }
294
0
      const spvtools::InstructionDesc* opcodeEntry = nullptr;
295
0
      if (LookupOpcodeForEnv(grammar.target_env(), opcode, &opcodeEntry)) {
296
0
        return context->diagnostic(SPV_ERROR_INTERNAL)
297
0
               << "OpSpecConstant opcode table out of sync";
298
0
      }
299
0
      spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
300
301
      // Prepare to parse the operands for the opcode.  Except skip the
302
      // type Id and result Id, since they've already been processed.
303
0
      assert(opcodeEntry->hasType);
304
0
      assert(opcodeEntry->hasResult);
305
0
      assert(opcodeEntry->operands().size() >= 2);
306
0
      spvPushOperandTypes(opcodeEntry->operands().subspan(2),
307
0
                          pExpectedOperands);
308
0
    } break;
309
310
0
    case SPV_OPERAND_TYPE_LITERAL_INTEGER:
311
0
    case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
312
      // The current operand is an *unsigned* 32-bit integer.
313
      // That's just how the grammar works.
314
0
      spvtools::IdType expected_type = {
315
0
          32, false, spvtools::IdTypeClass::kScalarIntegerType};
316
0
      if (auto error = context->binaryEncodeNumericLiteral(
317
0
              textValue, error_code_for_literals, expected_type, pInst)) {
318
0
        return error;
319
0
      }
320
0
    } break;
321
322
0
    case SPV_OPERAND_TYPE_LITERAL_FLOAT: {
323
      // The current operand is a 32-bit float.
324
      // That's just how the grammar works.
325
0
      spvtools::IdType expected_type = {
326
0
          32, false, spvtools::IdTypeClass::kScalarFloatType};
327
0
      if (auto error = context->binaryEncodeNumericLiteral(
328
0
              textValue, error_code_for_literals, expected_type, pInst)) {
329
0
        return error;
330
0
      }
331
0
    } break;
332
333
0
    case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
334
      // This is a context-independent literal number which can be a 32-bit
335
      // number of floating point value.
336
0
      if (auto error = context->binaryEncodeNumericLiteral(
337
0
              textValue, error_code_for_literals, spvtools::kUnknownType,
338
0
              pInst)) {
339
0
        return error;
340
0
      }
341
0
      break;
342
343
0
    case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
344
0
    case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
345
0
      spvtools::IdType expected_type = spvtools::kUnknownType;
346
      // The encoding for OpConstant, OpSpecConstant and OpSwitch all
347
      // depend on either their own result-id or the result-id of
348
      // one of their parameters.
349
0
      if (spv::Op::OpConstant == pInst->opcode ||
350
0
          spv::Op::OpSpecConstant == pInst->opcode) {
351
        // The type of the literal is determined by the type Id of the
352
        // instruction.
353
0
        expected_type =
354
0
            context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
355
0
        if (!spvtools::isScalarFloating(expected_type) &&
356
0
            !spvtools::isScalarIntegral(expected_type)) {
357
0
          const spvtools::InstructionDesc* opcodeEntry = nullptr;
358
0
          const char* opcode_name = "opcode";
359
0
          if (SPV_SUCCESS == LookupOpcode(pInst->opcode, &opcodeEntry)) {
360
0
            opcode_name =
361
0
                opcodeEntry->name().data();  // assumes it's null-terminated
362
0
          }
363
0
          return context->diagnostic()
364
0
                 << "Type for " << opcode_name
365
0
                 << " must be a scalar floating point or integer type";
366
0
        }
367
0
      } else if (pInst->opcode == spv::Op::OpSwitch) {
368
        // The type of the literal is the same as the type of the selector.
369
0
        expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
370
0
        if (!spvtools::isScalarIntegral(expected_type)) {
371
0
          return context->diagnostic()
372
0
                 << "The selector operand for OpSwitch must be the result"
373
0
                    " of an instruction that generates an integer scalar";
374
0
        }
375
0
      }
376
0
      if (auto error = context->binaryEncodeNumericLiteral(
377
0
              textValue, error_code_for_literals, expected_type, pInst)) {
378
0
        return error;
379
0
      }
380
0
    } break;
381
382
0
    case SPV_OPERAND_TYPE_LITERAL_STRING:
383
0
    case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
384
0
      spv_literal_t literal = {};
385
0
      spv_result_t error = spvTextToLiteral(textValue, &literal);
386
0
      if (error != SPV_SUCCESS) {
387
0
        if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
388
0
        return context->diagnostic(error_code_for_literals)
389
0
               << "Invalid literal string '" << textValue << "'.";
390
0
      }
391
0
      if (literal.type != SPV_LITERAL_TYPE_STRING) {
392
0
        return context->diagnostic()
393
0
               << "Expected literal string, found literal number '" << textValue
394
0
               << "'.";
395
0
      }
396
397
      // NOTE: Special case for extended instruction library import
398
0
      if (spv::Op::OpExtInstImport == pInst->opcode) {
399
0
        const spv_ext_inst_type_t ext_inst_type =
400
0
            spvExtInstImportTypeGet(literal.str.c_str());
401
0
        if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
402
0
          return context->diagnostic()
403
0
                 << "Invalid extended instruction import '" << literal.str
404
0
                 << "'";
405
0
        }
406
0
        if ((error = context->recordIdAsExtInstImport(pInst->words[1],
407
0
                                                      ext_inst_type)))
408
0
          return error;
409
0
      }
410
411
0
      if (context->binaryEncodeString(literal.str.c_str(), pInst))
412
0
        return SPV_ERROR_INVALID_TEXT;
413
0
    } break;
414
415
    // Masks.
416
0
    case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
417
0
    case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
418
0
    case SPV_OPERAND_TYPE_LOOP_CONTROL:
419
0
    case SPV_OPERAND_TYPE_IMAGE:
420
0
    case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
421
0
    case SPV_OPERAND_TYPE_TENSOR_OPERANDS:
422
0
    case SPV_OPERAND_TYPE_OPTIONAL_TENSOR_OPERANDS:
423
0
    case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
424
0
    case SPV_OPERAND_TYPE_OPTIONAL_RAW_ACCESS_CHAIN_OPERANDS:
425
0
    case SPV_OPERAND_TYPE_SELECTION_CONTROL:
426
0
    case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
427
0
    case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
428
0
    case SPV_OPERAND_TYPE_OPTIONAL_COOPERATIVE_MATRIX_OPERANDS:
429
0
    case SPV_OPERAND_TYPE_TENSOR_ADDRESSING_OPERANDS:
430
0
    case SPV_OPERAND_TYPE_COOPERATIVE_MATRIX_REDUCE:
431
0
    case SPV_OPERAND_TYPE_OPTIONAL_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS: {
432
0
      uint32_t value;
433
0
      if (auto error = grammar.parseMaskOperand(type, textValue, &value)) {
434
0
        return context->diagnostic(error)
435
0
               << "Invalid " << spvOperandTypeStr(type) << " operand '"
436
0
               << textValue << "'.";
437
0
      }
438
0
      if (auto error = context->binaryEncodeU32(value, pInst)) return error;
439
      // Prepare to parse the operands for this logical operand.
440
0
      grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
441
0
    } break;
442
0
    case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
443
0
      auto error = spvTextEncodeOperand(
444
0
          grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
445
0
          pInst, pExpectedOperands);
446
0
      if (error == SPV_FAILED_MATCH) {
447
        // It's not a literal number -- is it a literal string?
448
0
        error = spvTextEncodeOperand(grammar, context,
449
0
                                     SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
450
0
                                     textValue, pInst, pExpectedOperands);
451
0
      }
452
0
      if (error == SPV_FAILED_MATCH) {
453
        // It's not a literal -- is it an ID?
454
0
        error =
455
0
            spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
456
0
                                 textValue, pInst, pExpectedOperands);
457
0
      }
458
0
      if (error) {
459
0
        return context->diagnostic(error)
460
0
               << "Invalid word following !<integer>: " << textValue;
461
0
      }
462
0
      if (pExpectedOperands->empty()) {
463
0
        pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
464
0
      }
465
0
    } break;
466
0
    default: {
467
      // NOTE: All non literal operands are handled here using the operand
468
      // table.
469
0
      const spvtools::OperandDesc* entry = nullptr;
470
0
      if (spvtools::LookupOperand(type, textValue, strlen(textValue), &entry)) {
471
0
        return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
472
0
                                     << " '" << textValue << "'.";
473
0
      }
474
0
      if (context->binaryEncodeU32(entry->value, pInst)) {
475
0
        return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
476
0
                                     << " '" << textValue << "'.";
477
0
      }
478
479
      // Prepare to parse the operands for this logical operand.
480
0
      spvPushOperandTypes(entry->operands(), pExpectedOperands);
481
0
    } break;
482
0
  }
483
0
  return SPV_SUCCESS;
484
0
}
485
486
namespace {
487
488
/// Encodes an instruction started by !<integer> at the given position in text.
489
///
490
/// Puts the encoded words into *pInst.  If successful, moves position past the
491
/// instruction and returns SPV_SUCCESS.  Otherwise, returns an error code and
492
/// leaves position pointing to the error in text.
493
spv_result_t encodeInstructionStartingWithImmediate(
494
    const spvtools::AssemblyGrammar& grammar,
495
0
    spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
496
0
  std::string firstWord;
497
0
  spv_position_t nextPosition = {};
498
0
  auto error = context->getWord(&firstWord, &nextPosition);
499
0
  if (error) return context->diagnostic(error) << "Internal Error";
500
501
0
  if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
502
0
    return error;
503
0
  }
504
0
  while (context->advance() != SPV_END_OF_STREAM) {
505
    // A beginning of a new instruction means we're done.
506
0
    if (context->isStartOfNewInst()) return SPV_SUCCESS;
507
508
    // Otherwise, there must be an operand that's either a literal, an ID, or
509
    // an immediate.
510
0
    std::string operandValue;
511
0
    if ((error = context->getWord(&operandValue, &nextPosition)))
512
0
      return context->diagnostic(error) << "Internal Error";
513
514
0
    if (operandValue == "=")
515
0
      return context->diagnostic() << firstWord << " not allowed before =.";
516
517
    // Needed to pass to spvTextEncodeOperand(), but it shouldn't ever be
518
    // expanded.
519
0
    spv_operand_pattern_t dummyExpectedOperands;
520
0
    error = spvTextEncodeOperand(
521
0
        grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
522
0
        pInst, &dummyExpectedOperands);
523
0
    if (error) return error;
524
0
    context->setPosition(nextPosition);
525
0
  }
526
0
  return SPV_SUCCESS;
527
0
}
528
529
/// @brief Translate an instruction started by OpUnknown and the following
530
/// operands to binary form
531
///
532
/// @param[in] grammar the grammar to use for compilation
533
/// @param[in, out] context the dynamic compilation info
534
/// @param[out] pInst returned binary Opcode
535
///
536
/// @return result code
537
spv_result_t encodeInstructionStartingWithOpUnknown(
538
    const spvtools::AssemblyGrammar& grammar,
539
0
    spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
540
0
  spv_position_t nextPosition = {};
541
542
0
  uint16_t opcode;
543
0
  uint16_t wordCount;
544
545
  // The '(' character.
546
0
  if (context->advance())
547
0
    return context->diagnostic() << "Expected '(', found end of stream.";
548
0
  if ('(' != context->peek()) {
549
0
    return context->diagnostic() << "'(' expected after OpUnknown but found '"
550
0
                                 << context->peek() << "'.";
551
0
  }
552
0
  context->seekForward(1);
553
554
  // The opcode enumerant.
555
0
  if (context->advance())
556
0
    return context->diagnostic()
557
0
           << "Expected opcode enumerant, found end of stream.";
558
0
  std::string opcodeString;
559
0
  spv_result_t error = context->getWord(&opcodeString, &nextPosition);
560
0
  if (error) return context->diagnostic(error) << "Internal Error";
561
562
0
  if (!spvtools::utils::ParseNumber(opcodeString.c_str(), &opcode)) {
563
0
    return context->diagnostic()
564
0
           << "Invalid opcode enumerant: \"" << opcodeString << "\".";
565
0
  }
566
567
0
  context->setPosition(nextPosition);
568
569
  // The ',' character.
570
0
  if (context->advance())
571
0
    return context->diagnostic() << "Expected ',', found end of stream.";
572
0
  if (',' != context->peek()) {
573
0
    return context->diagnostic()
574
0
           << "',' expected after opcode enumerant but found '"
575
0
           << context->peek() << "'.";
576
0
  }
577
0
  context->seekForward(1);
578
579
  // The number of words.
580
0
  if (context->advance())
581
0
    return context->diagnostic()
582
0
           << "Expected number of words, found end of stream.";
583
0
  std::string wordCountString;
584
0
  error = context->getWord(&wordCountString, &nextPosition);
585
0
  if (error) return context->diagnostic(error) << "Internal Error";
586
587
0
  if (!spvtools::utils::ParseNumber(wordCountString.c_str(), &wordCount)) {
588
0
    return context->diagnostic()
589
0
           << "Invalid number of words: \"" << wordCountString << "\".";
590
0
  }
591
592
0
  if (wordCount == 0) {
593
0
    return context->diagnostic() << "Number of words (which includes the "
594
0
                                    "opcode) must be greater than zero.";
595
0
  }
596
597
0
  context->setPosition(nextPosition);
598
599
  // The ')' character.
600
0
  if (context->advance())
601
0
    return context->diagnostic() << "Expected ')', found end of stream.";
602
0
  if (')' != context->peek()) {
603
0
    return context->diagnostic()
604
0
           << "')' expected after number of words but found '"
605
0
           << context->peek() << "'.";
606
0
  }
607
0
  context->seekForward(1);
608
609
0
  pInst->opcode = static_cast<spv::Op>(opcode);
610
0
  context->binaryEncodeU32(spvOpcodeMake(wordCount, pInst->opcode), pInst);
611
612
0
  wordCount--;  // Subtract the opcode from the number of words left to read.
613
614
0
  while (wordCount-- > 0) {
615
0
    if (context->advance() == SPV_END_OF_STREAM) {
616
0
      return context->diagnostic() << "Expected " << wordCount + 1
617
0
                                   << " more operands, found end of stream.";
618
0
    }
619
0
    if (context->isStartOfNewInst()) {
620
0
      std::string invalid;
621
0
      context->getWord(&invalid, &nextPosition);
622
0
      return context->diagnostic()
623
0
             << "Unexpected start of new instruction: \"" << invalid
624
0
             << "\". Expected " << wordCount + 1 << " more operands";
625
0
    }
626
627
0
    std::string operandValue;
628
0
    if ((error = context->getWord(&operandValue, &nextPosition)))
629
0
      return context->diagnostic(error) << "Internal Error";
630
631
0
    if (operandValue == "=")
632
0
      return context->diagnostic() << "OpUnknown not allowed before =.";
633
634
    // Needed to pass to spvTextEncodeOperand(), but it shouldn't ever be
635
    // expanded.
636
0
    spv_operand_pattern_t dummyExpectedOperands;
637
0
    error = spvTextEncodeOperand(
638
0
        grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
639
0
        pInst, &dummyExpectedOperands);
640
0
    if (error) return error;
641
0
    context->setPosition(nextPosition);
642
0
  }
643
644
0
  return SPV_SUCCESS;
645
0
}
646
647
/// @brief Translate single Opcode and operands to binary form
648
///
649
/// @param[in] grammar the grammar to use for compilation
650
/// @param[in, out] context the dynamic compilation info
651
/// @param[in] text stream to translate
652
/// @param[out] pInst returned binary Opcode
653
/// @param[in,out] pPosition in the text stream
654
///
655
/// @return result code
656
spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
657
                                 spvtools::AssemblyContext* context,
658
0
                                 spv_instruction_t* pInst) {
659
  // Check for !<integer> first.
660
0
  if ('!' == context->peek()) {
661
0
    return encodeInstructionStartingWithImmediate(grammar, context, pInst);
662
0
  }
663
664
0
  std::string firstWord;
665
0
  spv_position_t nextPosition = {};
666
0
  spv_result_t error = context->getWord(&firstWord, &nextPosition);
667
0
  if (error) return context->diagnostic() << "Internal Error";
668
669
0
  std::string opcodeName;
670
0
  std::string result_id;
671
0
  spv_position_t result_id_position = {};
672
0
  if (context->startsWithOp()) {
673
0
    opcodeName = firstWord;
674
0
  } else {
675
0
    result_id = firstWord;
676
0
    if ('%' != result_id.front()) {
677
0
      return context->diagnostic()
678
0
             << "Expected <opcode> or <result-id> at the beginning "
679
0
                "of an instruction, found '"
680
0
             << result_id << "'.";
681
0
    }
682
0
    result_id_position = context->position();
683
684
    // The '=' sign.
685
0
    context->setPosition(nextPosition);
686
0
    if (context->advance())
687
0
      return context->diagnostic() << "Expected '=', found end of stream.";
688
0
    std::string equal_sign;
689
0
    error = context->getWord(&equal_sign, &nextPosition);
690
0
    if ("=" != equal_sign)
691
0
      return context->diagnostic() << "'=' expected after result id but found '"
692
0
                                   << equal_sign << "'.";
693
694
    // The <opcode> after the '=' sign.
695
0
    context->setPosition(nextPosition);
696
0
    if (context->advance())
697
0
      return context->diagnostic() << "Expected opcode, found end of stream.";
698
0
    error = context->getWord(&opcodeName, &nextPosition);
699
0
    if (error) return context->diagnostic(error) << "Internal Error";
700
0
    if (!context->startsWithOp()) {
701
0
      return context->diagnostic()
702
0
             << "Invalid Opcode prefix '" << opcodeName << "'.";
703
0
    }
704
0
  }
705
706
0
  if (opcodeName == "OpUnknown") {
707
0
    if (!result_id.empty()) {
708
0
      return context->diagnostic()
709
0
             << "OpUnknown not allowed in assignment. Use an explicit result "
710
0
                "id operand instead.";
711
0
    }
712
0
    context->setPosition(nextPosition);
713
0
    return encodeInstructionStartingWithOpUnknown(grammar, context, pInst);
714
0
  }
715
716
  // NOTE: The table contains Opcode names without the "Op" prefix.
717
0
  const char* pInstName = opcodeName.data() + 2;
718
719
0
  const spvtools::InstructionDesc* opcodeEntry = nullptr;
720
0
  error = LookupOpcodeForEnv(grammar.target_env(), pInstName, &opcodeEntry);
721
0
  if (error) {
722
0
    return context->diagnostic(error)
723
0
           << "Invalid Opcode name '" << opcodeName << "'";
724
0
  }
725
0
  if (opcodeEntry->hasResult && result_id.empty()) {
726
0
    return context->diagnostic()
727
0
           << "Expected <result-id> at the beginning of an instruction, found '"
728
0
           << firstWord << "'.";
729
0
  }
730
0
  if (!opcodeEntry->hasResult && !result_id.empty()) {
731
0
    return context->diagnostic()
732
0
           << "Cannot set ID " << result_id << " because " << opcodeName
733
0
           << " does not produce a result ID.";
734
0
  }
735
0
  pInst->opcode = opcodeEntry->opcode;
736
0
  context->setPosition(nextPosition);
737
  // Reserve the first word for the instruction.
738
0
  spvInstructionAddWord(pInst, 0);
739
740
  // Maintains the ordered list of expected operand types.
741
  // For many instructions we only need the {numTypes, operandTypes}
742
  // entries in opcodeEntry.  However, sometimes we need to modify
743
  // the list as we parse the operands. This occurs when an operand
744
  // has its own logical operands (such as the LocalSize operand for
745
  // ExecutionMode), or for extended instructions that may have their
746
  // own operands depending on the selected extended instruction.
747
0
  spv_operand_pattern_t expectedOperands;
748
0
  {
749
0
    const auto operands = opcodeEntry->operands();
750
0
    const auto n = operands.size();
751
0
    expectedOperands.reserve(n);
752
0
    for (auto i = 0u; i < n; i++) {
753
0
      auto ty = operands[n - i - 1];
754
0
      expectedOperands.push_back(ty);
755
0
    }
756
0
  }
757
758
0
  while (!expectedOperands.empty()) {
759
0
    const spv_operand_type_t type = expectedOperands.back();
760
0
    expectedOperands.pop_back();
761
762
    // Expand optional tuples lazily.
763
0
    if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
764
765
0
    if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
766
      // Handle the <result-id> for value generating instructions.
767
      // We've already consumed it from the text stream.  Here
768
      // we inject its words into the instruction.
769
0
      spv_position_t temp_pos = context->position();
770
0
      error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
771
0
                                   result_id.c_str(), pInst, nullptr);
772
0
      result_id_position = context->position();
773
      // Because we are injecting we have to reset the position afterwards.
774
0
      context->setPosition(temp_pos);
775
0
      if (error) return error;
776
0
    } else {
777
      // Find the next word.
778
0
      error = context->advance();
779
0
      if (error == SPV_END_OF_STREAM) {
780
0
        if (spvOperandIsOptional(type)) {
781
          // This would have been the last potential operand for the
782
          // instruction,
783
          // and we didn't find one.  We're finished parsing this instruction.
784
0
          break;
785
0
        } else {
786
0
          return context->diagnostic()
787
0
                 << "Expected operand for " << opcodeName
788
0
                 << " instruction, but found the end of the stream.";
789
0
        }
790
0
      }
791
0
      assert(error == SPV_SUCCESS && "Somebody added another way to fail");
792
793
0
      if (context->isStartOfNewInst()) {
794
0
        if (spvOperandIsOptional(type)) {
795
0
          break;
796
0
        } else {
797
0
          if (opcodeName == "OpSpecConstantOp" &&
798
0
              type == SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER) {
799
0
            std::string operandValue;
800
0
            error = context->getWord(&operandValue, &nextPosition);
801
0
            spv::Op opcode;
802
0
            if (!grammar.lookupSpecConstantOpcode(operandValue.c_str() + 2,
803
0
                                                  &opcode)) {
804
0
              return context->diagnostic()
805
0
                     << "Invalid " << opcodeName << " opcode '" << operandValue
806
0
                     << "'. Did you mean '" << operandValue.substr(2) << "'?";
807
0
            }
808
0
          }
809
0
          return context->diagnostic()
810
0
                 << "Expected operand for " << opcodeName
811
0
                 << " instruction, but found the next instruction instead.";
812
0
        }
813
0
      }
814
815
0
      std::string operandValue;
816
0
      error = context->getWord(&operandValue, &nextPosition);
817
0
      if (error) return context->diagnostic(error) << "Internal Error";
818
819
0
      error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
820
0
                                   pInst, &expectedOperands);
821
822
0
      if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
823
0
        return SPV_SUCCESS;
824
825
0
      if (error) return error;
826
827
0
      context->setPosition(nextPosition);
828
0
    }
829
0
  }
830
831
0
  if (spvOpcodeGeneratesType(pInst->opcode)) {
832
0
    if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
833
0
      return SPV_ERROR_INVALID_TEXT;
834
0
    }
835
0
  } else if (opcodeEntry->hasType) {
836
    // SPIR-V dictates that if an instruction has both a return value and a
837
    // type ID then the type id is first, and the return value is second.
838
0
    assert(opcodeEntry->hasResult &&
839
0
           "Unknown opcode: has a type but no result.");
840
0
    context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
841
0
  }
842
843
0
  if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
844
0
    return context->diagnostic()
845
0
           << opcodeName << " Instruction too long: " << pInst->words.size()
846
0
           << " words, but the limit is "
847
0
           << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
848
0
  }
849
850
0
  pInst->words[0] =
851
0
      spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
852
853
0
  return SPV_SUCCESS;
854
0
}
855
856
enum { kAssemblerVersion = 0 };
857
858
// Populates a binary stream's |header|. The target environment is specified via
859
// |env| and Id bound is via |bound|.
860
spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
861
0
                       uint32_t* header) {
862
0
  if (!header) return SPV_ERROR_INVALID_BINARY;
863
864
0
  header[SPV_INDEX_MAGIC_NUMBER] = spv::MagicNumber;
865
0
  header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
866
0
  header[SPV_INDEX_GENERATOR_NUMBER] =
867
0
      SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
868
0
  header[SPV_INDEX_BOUND] = bound;
869
0
  header[SPV_INDEX_SCHEMA] = 0;  // NOTE: Reserved
870
871
0
  return SPV_SUCCESS;
872
0
}
873
874
// Collects all numeric ids in the module source into |numeric_ids|.
875
// This function is essentially a dry-run of spvTextToBinary.
876
spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
877
                           const spvtools::MessageConsumer& consumer,
878
                           const spv_text text,
879
0
                           std::set<uint32_t>* numeric_ids) {
880
0
  spvtools::AssemblyContext context(text, consumer);
881
882
0
  if (!text->str) return context.diagnostic() << "Missing assembly text.";
883
884
  // Skip past whitespace and comments.
885
0
  context.advance();
886
887
0
  while (context.hasText()) {
888
0
    spv_instruction_t inst;
889
890
    // Operand parsing sometimes involves knowing the opcode of the instruction
891
    // being parsed. A malformed input might feature such an operand *before*
892
    // the opcode is known. To guard against accessing an uninitialized opcode,
893
    // the instruction's opcode is initialized to a default value.
894
0
    inst.opcode = spv::Op::Max;
895
896
0
    if (spvTextEncodeOpcode(grammar, &context, &inst)) {
897
0
      return SPV_ERROR_INVALID_TEXT;
898
0
    }
899
900
0
    if (context.advance()) break;
901
0
  }
902
903
0
  *numeric_ids = context.GetNumericIds();
904
0
  return SPV_SUCCESS;
905
0
}
906
907
// Translates a given assembly language module into binary form.
908
// If a diagnostic is generated, it is not yet marked as being
909
// for a text-based input.
910
spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
911
                                     const spvtools::MessageConsumer& consumer,
912
                                     const spv_text text,
913
                                     const uint32_t options,
914
0
                                     spv_binary* pBinary) {
915
  // The ids in this set will have the same values both in source and binary.
916
  // All other ids will be generated by filling in the gaps.
917
0
  std::set<uint32_t> ids_to_preserve;
918
919
0
  if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
920
    // Collect all numeric ids from the source into ids_to_preserve.
921
0
    const spv_result_t result =
922
0
        GetNumericIds(grammar, consumer, text, &ids_to_preserve);
923
0
    if (result != SPV_SUCCESS) return result;
924
0
  }
925
926
0
  spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
927
928
0
  if (!text->str) return context.diagnostic() << "Missing assembly text.";
929
0
  if (!pBinary) return SPV_ERROR_INVALID_POINTER;
930
931
0
  std::vector<spv_instruction_t> instructions;
932
933
  // Skip past whitespace and comments.
934
0
  context.advance();
935
936
0
  while (context.hasText()) {
937
0
    instructions.push_back({});
938
0
    spv_instruction_t& inst = instructions.back();
939
940
0
    if (auto error = spvTextEncodeOpcode(grammar, &context, &inst)) {
941
0
      return error;
942
0
    }
943
944
0
    if (context.advance()) break;
945
0
  }
946
947
0
  size_t totalSize = SPV_INDEX_INSTRUCTION;
948
0
  for (auto& inst : instructions) {
949
0
    totalSize += inst.words.size();
950
0
  }
951
952
0
  uint32_t* data = new uint32_t[totalSize];
953
0
  if (!data) return SPV_ERROR_OUT_OF_MEMORY;
954
0
  uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
955
0
  for (auto& inst : instructions) {
956
0
    memcpy(data + currentIndex, inst.words.data(),
957
0
           sizeof(uint32_t) * inst.words.size());
958
0
    currentIndex += inst.words.size();
959
0
  }
960
961
0
  if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
962
0
    return error;
963
964
0
  spv_binary binary = new spv_binary_t();
965
0
  if (!binary) {
966
0
    delete[] data;
967
0
    return SPV_ERROR_OUT_OF_MEMORY;
968
0
  }
969
0
  binary->code = data;
970
0
  binary->wordCount = totalSize;
971
972
0
  *pBinary = binary;
973
974
0
  return SPV_SUCCESS;
975
0
}
976
977
}  // anonymous namespace
978
979
spv_result_t spvTextToBinary(const spv_const_context context,
980
                             const char* input_text,
981
                             const size_t input_text_size, spv_binary* pBinary,
982
0
                             spv_diagnostic* pDiagnostic) {
983
0
  return spvTextToBinaryWithOptions(context, input_text, input_text_size,
984
0
                                    SPV_TEXT_TO_BINARY_OPTION_NONE, pBinary,
985
0
                                    pDiagnostic);
986
0
}
987
988
spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
989
                                        const char* input_text,
990
                                        const size_t input_text_size,
991
                                        const uint32_t options,
992
                                        spv_binary* pBinary,
993
0
                                        spv_diagnostic* pDiagnostic) {
994
0
  spv_context_t hijack_context = *context;
995
0
  if (pDiagnostic) {
996
0
    *pDiagnostic = nullptr;
997
0
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
998
0
  }
999
1000
0
  spv_text_t text = {input_text, input_text_size};
1001
0
  spvtools::AssemblyGrammar grammar(&hijack_context);
1002
1003
0
  spv_result_t result = spvTextToBinaryInternal(
1004
0
      grammar, hijack_context.consumer, &text, options, pBinary);
1005
0
  if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
1006
1007
0
  return result;
1008
0
}
1009
1010
166
void spvTextDestroy(spv_text text) {
1011
166
  if (text) {
1012
165
    if (text->str) delete[] text->str;
1013
165
    delete text;
1014
165
  }
1015
166
}