blob: 8724b1cd018c0f204135cde2d84d096ac6943d46 [file] [log] [blame]
Dejan Mircevskib6fe02f2016-01-07 13:44:22 -05001// Copyright (c) 2015-2016 The Khronos Group Inc.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -04002//
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
Andrew Woloszyn71fc0552015-09-24 10:26:51 -04006//
David Neto9fc86582016-09-01 15:33:59 -04007// http://www.apache.org/licenses/LICENSE-2.0
Andrew Woloszyn71fc0552015-09-24 10:26:51 -04008//
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.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040014
15#include "text_handler.h"
16
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040017#include <cassert>
David Neto78e677b2015-10-05 13:28:46 -040018#include <cstdlib>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040019#include <cstring>
Andrew Woloszyn537e7762015-09-29 11:28:34 -040020#include <tuple>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040021
David Netofcc7d582015-10-27 15:31:10 -040022#include "assembly_grammar.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040023#include "binary.h"
24#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040025#include "instruction.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040026#include "opcode.h"
27#include "text.h"
Andrew Woloszynf731cbf2015-10-23 09:53:58 -040028#include "util/bitutils.h"
David Neto9e545d72015-11-06 18:08:49 -050029#include "util/hex_float.h"
qining1773b952016-09-01 14:27:04 -040030#include "util/parse_number.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040031
32namespace {
Lei Zhangf2cf7192016-04-21 15:50:23 -040033// Advances |text| to the start of the next line and writes the new position to
34// |position|.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040035spv_result_t advanceLine(spv_text text, spv_position position) {
36 while (true) {
Lei Zhangf2cf7192016-04-21 15:50:23 -040037 if (position->index >= text->length) return SPV_END_OF_STREAM;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040038 switch (text->str[position->index]) {
39 case '\0':
40 return SPV_END_OF_STREAM;
41 case '\n':
42 position->column = 0;
43 position->line++;
44 position->index++;
45 return SPV_SUCCESS;
46 default:
47 position->column++;
48 position->index++;
49 break;
50 }
51 }
52}
53
Lei Zhangf2cf7192016-04-21 15:50:23 -040054// Advances |text| to first non white space character and writes the new
55// position to |position|.
56// If a null terminator is found during the text advance, SPV_END_OF_STREAM is
57// returned, SPV_SUCCESS otherwise. No error checking is performed on the
58// parameters, its the users responsibility to ensure these are non null.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040059spv_result_t advance(spv_text text, spv_position position) {
60 // NOTE: Consume white space, otherwise don't advance.
Lei Zhang8f6ba142015-11-06 15:09:04 -050061 if (position->index >= text->length) return SPV_END_OF_STREAM;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040062 switch (text->str[position->index]) {
63 case '\0':
64 return SPV_END_OF_STREAM;
65 case ';':
66 if (spv_result_t error = advanceLine(text, position)) return error;
67 return advance(text, position);
68 case ' ':
69 case '\t':
Dejan Mircevskia1de2b32016-04-01 00:47:02 -040070 case '\r':
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040071 position->column++;
72 position->index++;
73 return advance(text, position);
74 case '\n':
75 position->column = 0;
76 position->line++;
77 position->index++;
78 return advance(text, position);
79 default:
80 break;
81 }
82 return SPV_SUCCESS;
83}
84
Lei Zhang6032b982016-03-15 16:52:40 -040085// Fetches the next word from the given text stream starting from the given
86// *position. On success, writes the decoded word into *word and updates
87// *position to the location past the returned word.
88//
89// A word ends at the next comment or whitespace. However, double-quoted
90// strings remain intact, and a backslash always escapes the next character.
91spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040092 if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
Lei Zhang6032b982016-03-15 16:52:40 -040093 if (!position) return SPV_ERROR_INVALID_POINTER;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040094
Lei Zhang6032b982016-03-15 16:52:40 -040095 const size_t start_index = position->index;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040096
97 bool quoting = false;
98 bool escaping = false;
99
100 // NOTE: Assumes first character is not white space!
101 while (true) {
Lei Zhang6032b982016-03-15 16:52:40 -0400102 if (position->index >= text->length) {
103 word->assign(text->str + start_index, text->str + position->index);
Lei Zhang9413fbb2016-02-22 17:17:25 -0500104 return SPV_SUCCESS;
105 }
Lei Zhang6032b982016-03-15 16:52:40 -0400106 const char ch = text->str[position->index];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400107 if (ch == '\\')
108 escaping = !escaping;
109 else {
110 switch (ch) {
111 case '"':
112 if (!escaping) quoting = !quoting;
113 break;
114 case ' ':
115 case ';':
116 case '\t':
117 case '\n':
Dejan Mircevskia1de2b32016-04-01 00:47:02 -0400118 case '\r':
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400119 if (escaping || quoting) break;
120 // Fall through.
121 case '\0': { // NOTE: End of word found!
Lei Zhang6032b982016-03-15 16:52:40 -0400122 word->assign(text->str + start_index, text->str + position->index);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400123 return SPV_SUCCESS;
124 }
125 default:
126 break;
127 }
128 escaping = false;
129 }
130
Lei Zhang6032b982016-03-15 16:52:40 -0400131 position->column++;
132 position->index++;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400133 }
134}
135
136// Returns true if the characters in the text as position represent
137// the start of an Opcode.
138bool startsWithOp(spv_text text, spv_position position) {
139 if (text->length < position->index + 3) return false;
140 char ch0 = text->str[position->index];
141 char ch1 = text->str[position->index + 1];
142 char ch2 = text->str[position->index + 2];
143 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
144}
145
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400146} // anonymous namespace
147
148namespace libspirv {
149
David Neto78e677b2015-10-05 13:28:46 -0400150const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
151
David Neto78e677b2015-10-05 13:28:46 -0400152// TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
153
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400154// This represents all of the data that is only valid for the duration of
155// a single compilation.
Lei Zhang1a0334e2015-11-02 09:41:20 -0500156uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400157 if (named_ids_.end() == named_ids_.find(textValue)) {
158 named_ids_[std::string(textValue)] = bound_++;
159 }
160 return named_ids_[textValue];
161}
162uint32_t AssemblyContext::getBound() const { return bound_; }
163
164spv_result_t AssemblyContext::advance() {
165 return ::advance(text_, &current_position_);
166}
167
Lei Zhang6032b982016-03-15 16:52:40 -0400168spv_result_t AssemblyContext::getWord(std::string* word,
169 spv_position next_position) {
170 *next_position = current_position_;
171 return ::getWord(text_, next_position, word);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400172}
173
174bool AssemblyContext::startsWithOp() {
175 return ::startsWithOp(text_, &current_position_);
176}
177
178bool AssemblyContext::isStartOfNewInst() {
Lei Zhang6032b982016-03-15 16:52:40 -0400179 spv_position_t pos = current_position_;
180 if (::advance(text_, &pos)) return false;
181 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400182
183 std::string word;
Lei Zhang6032b982016-03-15 16:52:40 -0400184 pos = current_position_;
185 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400186 if ('%' != word.front()) return false;
187
Lei Zhang6032b982016-03-15 16:52:40 -0400188 if (::advance(text_, &pos)) return false;
189 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400190 if ("=" != word) return false;
191
Lei Zhang6032b982016-03-15 16:52:40 -0400192 if (::advance(text_, &pos)) return false;
193 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400194 return false;
195}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400196
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400197char AssemblyContext::peek() const {
198 return text_->str[current_position_.index];
199}
200
201bool AssemblyContext::hasText() const {
202 return text_->length > current_position_.index;
203}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400204
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400205void AssemblyContext::seekForward(uint32_t size) {
206 current_position_.index += size;
207 current_position_.column += size;
208}
209
210spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
Lei Zhang1a0334e2015-11-02 09:41:20 -0500211 spv_instruction_t* pInst) {
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500212 pInst->words.insert(pInst->words.end(), value);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400213 return SPV_SUCCESS;
214}
215
David Neto78e677b2015-10-05 13:28:46 -0400216spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500217 const char* val, spv_result_t error_code, const IdType& type,
218 spv_instruction_t* pInst) {
qining1773b952016-09-01 14:27:04 -0400219 using spvutils::EncodeNumberStatus;
220 // Populate the NumberType from the IdType for parsing.
221 spvutils::NumberType number_type;
222 switch (type.type_class) {
223 case IdTypeClass::kOtherType:
224 return diagnostic(SPV_ERROR_INTERNAL)
225 << "Unexpected numeric literal type";
226 case IdTypeClass::kScalarIntegerType:
227 if (type.isSigned) {
228 number_type = {type.bitwidth, SPV_NUMBER_SIGNED_INT};
229 } else {
230 number_type = {type.bitwidth, SPV_NUMBER_UNSIGNED_INT};
231 }
232 break;
233 case IdTypeClass::kScalarFloatType:
234 number_type = {type.bitwidth, SPV_NUMBER_FLOATING};
235 break;
236 case IdTypeClass::kBottom:
237 // kBottom means the type is unknown and we need to infer the type before
238 // parsing the number. The rule is: If there is a decimal point, treat
239 // the value as a floating point value, otherwise a integer value, then
240 // if the first char of the integer text is '-', treat the integer as a
241 // signed integer, otherwise an unsigned integer.
242 uint32_t bitwidth = static_cast<uint32_t>(assumedBitWidth(type));
243 if (strchr(val, '.')) {
244 number_type = {bitwidth, SPV_NUMBER_FLOATING};
245 } else if (type.isSigned || val[0] == '-') {
246 number_type = {bitwidth, SPV_NUMBER_SIGNED_INT};
247 } else {
248 number_type = {bitwidth, SPV_NUMBER_UNSIGNED_INT};
249 }
250 break;
David Neto78e677b2015-10-05 13:28:46 -0400251 }
252
qining1773b952016-09-01 14:27:04 -0400253 std::string error_msg;
254 EncodeNumberStatus parse_status = ParseAndEncodeNumber(
255 val, number_type,
256 [this, pInst](uint32_t d) { this->binaryEncodeU32(d, pInst); },
257 &error_msg);
258 switch (parse_status) {
259 case EncodeNumberStatus::kSuccess:
260 return SPV_SUCCESS;
261 case EncodeNumberStatus::kInvalidText:
262 return diagnostic(error_code) << error_msg;
263 case EncodeNumberStatus::kUnsupported:
264 return diagnostic(SPV_ERROR_INTERNAL) << error_msg;
265 case EncodeNumberStatus::kInvalidUsage:
266 return diagnostic(SPV_ERROR_INVALID_TEXT) << error_msg;
267 }
268 // This line is not reachable, only added to satisfy the compiler.
269 return diagnostic(SPV_ERROR_INTERNAL)
270 << "Unexpected result code from ParseAndEncodeNumber()";
David Neto78e677b2015-10-05 13:28:46 -0400271}
272
Lei Zhang1a0334e2015-11-02 09:41:20 -0500273spv_result_t AssemblyContext::binaryEncodeString(const char* value,
274 spv_instruction_t* pInst) {
David Netob5dc8fc2015-10-06 16:22:00 -0400275 const size_t length = strlen(value);
276 const size_t wordCount = (length / 4) + 1;
277 const size_t oldWordCount = pInst->words.size();
278 const size_t newWordCount = oldWordCount + wordCount;
279
280 // TODO(dneto): We can just defer this check until later.
281 if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Neto78e677b2015-10-05 13:28:46 -0400282 return diagnostic() << "Instruction too long: more than "
283 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400284 }
285
David Netob5dc8fc2015-10-06 16:22:00 -0400286 pInst->words.resize(newWordCount);
287
288 // Make sure all the bytes in the last word are 0, in case we only
289 // write a partial word at the end.
290 pInst->words.back() = 0;
291
Lei Zhang1a0334e2015-11-02 09:41:20 -0500292 char* dest = (char*)&pInst->words[oldWordCount];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400293 strncpy(dest, value, length);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400294
295 return SPV_SUCCESS;
296}
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400297
298spv_result_t AssemblyContext::recordTypeDefinition(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500299 const spv_instruction_t* pInst) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400300 uint32_t value = pInst->words[1];
301 if (types_.find(value) != types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500302 return diagnostic() << "Value " << value
303 << " has already been used to generate a type";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400304 }
305
Lei Zhangb36e7042015-10-28 13:40:52 -0400306 if (pInst->opcode == SpvOpTypeInt) {
David Neto78e677b2015-10-05 13:28:46 -0400307 if (pInst->words.size() != 4)
308 return diagnostic() << "Invalid OpTypeInt instruction";
309 types_[value] = {pInst->words[2], pInst->words[3] != 0,
310 IdTypeClass::kScalarIntegerType};
Lei Zhangb36e7042015-10-28 13:40:52 -0400311 } else if (pInst->opcode == SpvOpTypeFloat) {
David Neto78e677b2015-10-05 13:28:46 -0400312 if (pInst->words.size() != 3)
313 return diagnostic() << "Invalid OpTypeFloat instruction";
314 types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400315 } else {
David Neto78e677b2015-10-05 13:28:46 -0400316 types_[value] = {0, false, IdTypeClass::kOtherType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400317 }
318 return SPV_SUCCESS;
319}
320
321IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
322 auto type = types_.find(value);
323 if (type == types_.end()) {
David Neto78e677b2015-10-05 13:28:46 -0400324 return kUnknownType;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400325 }
326 return std::get<1>(*type);
327}
328
329IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
330 auto type_value = value_types_.find(value);
331 if (type_value == value_types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500332 return {0, false, IdTypeClass::kBottom};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400333 }
334 return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
335}
336
337spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
338 uint32_t type) {
339 bool successfully_inserted = false;
340 std::tie(std::ignore, successfully_inserted) =
341 value_types_.insert(std::make_pair(value, type));
David Neto78e677b2015-10-05 13:28:46 -0400342 if (!successfully_inserted)
343 return diagnostic() << "Value is being defined a second time";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400344 return SPV_SUCCESS;
345}
346
David Neto2ae4a682015-11-09 18:55:42 -0500347spv_result_t AssemblyContext::recordIdAsExtInstImport(
348 uint32_t id, spv_ext_inst_type_t type) {
349 bool successfully_inserted = false;
350 std::tie(std::ignore, successfully_inserted) =
351 import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
352 if (!successfully_inserted)
353 return diagnostic() << "Import Id is being defined a second time";
354 return SPV_SUCCESS;
355}
356
357spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
358 auto type = import_id_to_ext_inst_type_.find(id);
359 if (type == import_id_to_ext_inst_type_.end()) {
360 return SPV_EXT_INST_TYPE_NONE;
361 }
362 return std::get<1>(*type);
363}
364
Lei Zhang1a0334e2015-11-02 09:41:20 -0500365} // namespace libspirv