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_handler.h"
16
17 #include <algorithm>
18 #include <cassert>
19 #include <cstdlib>
20 #include <cstring>
21 #include <tuple>
22
23 #include "source/assembly_grammar.h"
24 #include "source/binary.h"
25 #include "source/ext_inst.h"
26 #include "source/instruction.h"
27 #include "source/opcode.h"
28 #include "source/text.h"
29 #include "source/util/bitutils.h"
30 #include "source/util/hex_float.h"
31 #include "source/util/parse_number.h"
32 #include "source/util/string_utils.h"
33
34 namespace spvtools {
35 namespace {
36
37 // Advances |text| to the start of the next line and writes the new position to
38 // |position|.
advanceLine(spv_text text,spv_position position)39 spv_result_t advanceLine(spv_text text, spv_position position) {
40 while (true) {
41 if (position->index >= text->length) return SPV_END_OF_STREAM;
42 switch (text->str[position->index]) {
43 case '\0':
44 return SPV_END_OF_STREAM;
45 case '\n':
46 position->column = 0;
47 position->line++;
48 position->index++;
49 return SPV_SUCCESS;
50 default:
51 position->column++;
52 position->index++;
53 break;
54 }
55 }
56 }
57
58 // Advances |text| to first non white space character and writes the new
59 // position to |position|.
60 // If a null terminator is found during the text advance, SPV_END_OF_STREAM is
61 // returned, SPV_SUCCESS otherwise. No error checking is performed on the
62 // parameters, its the users responsibility to ensure these are non null.
advance(spv_text text,spv_position position)63 spv_result_t advance(spv_text text, spv_position position) {
64 // NOTE: Consume white space, otherwise don't advance.
65 while (true) {
66 if (position->index >= text->length) return SPV_END_OF_STREAM;
67 switch (text->str[position->index]) {
68 case '\0':
69 return SPV_END_OF_STREAM;
70 case ';':
71 if (spv_result_t error = advanceLine(text, position)) return error;
72 continue;
73 case ' ':
74 case '\t':
75 case '\r':
76 position->column++;
77 position->index++;
78 continue;
79 case '\n':
80 position->column = 0;
81 position->line++;
82 position->index++;
83 continue;
84 default:
85 return SPV_SUCCESS;
86 }
87 }
88 }
89
90 // Fetches the next word from the given text stream starting from the given
91 // *position. On success, writes the decoded word into *word and updates
92 // *position to the location past the returned word.
93 //
94 // A word ends at the next comment or whitespace. However, double-quoted
95 // strings remain intact, and a backslash always escapes the next character.
getWord(spv_text text,spv_position position,std::string * word)96 spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
97 if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
98 if (!position) return SPV_ERROR_INVALID_POINTER;
99
100 const size_t start_index = position->index;
101
102 bool quoting = false;
103 bool escaping = false;
104
105 // NOTE: Assumes first character is not white space!
106 while (true) {
107 if (position->index >= text->length) {
108 word->assign(text->str + start_index, text->str + position->index);
109 return SPV_SUCCESS;
110 }
111 const char ch = text->str[position->index];
112 if (ch == '\\') {
113 escaping = !escaping;
114 } else {
115 switch (ch) {
116 case '"':
117 if (!escaping) quoting = !quoting;
118 break;
119 case ' ':
120 case ';':
121 case ',':
122 case '(':
123 case ')':
124 case '\t':
125 case '\n':
126 case '\r':
127 if (escaping || quoting) break;
128 word->assign(text->str + start_index, text->str + position->index);
129 return SPV_SUCCESS;
130 case '\0': { // NOTE: End of word found!
131 word->assign(text->str + start_index, text->str + position->index);
132 return SPV_SUCCESS;
133 }
134 default:
135 break;
136 }
137 escaping = false;
138 }
139
140 position->column++;
141 position->index++;
142 }
143 }
144
145 // Returns true if the characters in the text as position represent
146 // the start of an Opcode.
startsWithOp(spv_text text,spv_position position)147 bool startsWithOp(spv_text text, spv_position position) {
148 if (text->length < position->index + 3) return false;
149 char ch0 = text->str[position->index];
150 char ch1 = text->str[position->index + 1];
151 char ch2 = text->str[position->index + 2];
152 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
153 }
154
155 } // namespace
156
157 const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
158
159 // TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
160
161 // This represents all of the data that is only valid for the duration of
162 // a single compilation.
spvNamedIdAssignOrGet(const char * textValue)163 uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
164 if (!ids_to_preserve_.empty()) {
165 uint32_t id = 0;
166 if (spvtools::utils::ParseNumber(textValue, &id)) {
167 if (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
168 bound_ = std::max(bound_, id + 1);
169 return id;
170 }
171 }
172 }
173
174 const auto it = named_ids_.find(textValue);
175 if (it == named_ids_.end()) {
176 uint32_t id = next_id_++;
177 if (!ids_to_preserve_.empty()) {
178 while (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
179 id = next_id_++;
180 }
181 }
182
183 named_ids_.emplace(textValue, id);
184 bound_ = std::max(bound_, id + 1);
185 return id;
186 }
187
188 return it->second;
189 }
190
getBound() const191 uint32_t AssemblyContext::getBound() const { return bound_; }
192
advance()193 spv_result_t AssemblyContext::advance() {
194 return spvtools::advance(text_, ¤t_position_);
195 }
196
getWord(std::string * word,spv_position next_position)197 spv_result_t AssemblyContext::getWord(std::string* word,
198 spv_position next_position) {
199 *next_position = current_position_;
200 return spvtools::getWord(text_, next_position, word);
201 }
202
startsWithOp()203 bool AssemblyContext::startsWithOp() {
204 return spvtools::startsWithOp(text_, ¤t_position_);
205 }
206
isStartOfNewInst()207 bool AssemblyContext::isStartOfNewInst() {
208 spv_position_t pos = current_position_;
209 if (spvtools::advance(text_, &pos)) return false;
210 if (spvtools::startsWithOp(text_, &pos)) return true;
211
212 std::string word;
213 pos = current_position_;
214 if (spvtools::getWord(text_, &pos, &word)) return false;
215 if ('%' != word.front()) return false;
216
217 if (spvtools::advance(text_, &pos)) return false;
218 if (spvtools::getWord(text_, &pos, &word)) return false;
219 if ("=" != word) return false;
220
221 if (spvtools::advance(text_, &pos)) return false;
222 if (spvtools::startsWithOp(text_, &pos)) return true;
223 return false;
224 }
225
peek() const226 char AssemblyContext::peek() const {
227 return text_->str[current_position_.index];
228 }
229
hasText() const230 bool AssemblyContext::hasText() const {
231 return text_->length > current_position_.index;
232 }
233
seekForward(uint32_t size)234 void AssemblyContext::seekForward(uint32_t size) {
235 current_position_.index += size;
236 current_position_.column += size;
237 }
238
binaryEncodeU32(const uint32_t value,spv_instruction_t * pInst)239 spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
240 spv_instruction_t* pInst) {
241 pInst->words.insert(pInst->words.end(), value);
242 return SPV_SUCCESS;
243 }
244
binaryEncodeNumericLiteral(const char * val,spv_result_t error_code,const IdType & type,spv_instruction_t * pInst)245 spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
246 const char* val, spv_result_t error_code, const IdType& type,
247 spv_instruction_t* pInst) {
248 using spvtools::utils::EncodeNumberStatus;
249 // Populate the NumberType from the IdType for parsing.
250 spvtools::utils::NumberType number_type;
251 switch (type.type_class) {
252 case IdTypeClass::kOtherType:
253 return diagnostic(SPV_ERROR_INTERNAL)
254 << "Unexpected numeric literal type";
255 case IdTypeClass::kScalarIntegerType:
256 if (type.isSigned) {
257 number_type = {type.bitwidth, SPV_NUMBER_SIGNED_INT};
258 } else {
259 number_type = {type.bitwidth, SPV_NUMBER_UNSIGNED_INT};
260 }
261 break;
262 case IdTypeClass::kScalarFloatType:
263 number_type = {type.bitwidth, SPV_NUMBER_FLOATING};
264 break;
265 case IdTypeClass::kBottom:
266 // kBottom means the type is unknown and we need to infer the type before
267 // parsing the number. The rule is: If there is a decimal point, treat
268 // the value as a floating point value, otherwise a integer value, then
269 // if the first char of the integer text is '-', treat the integer as a
270 // signed integer, otherwise an unsigned integer.
271 uint32_t bitwidth = static_cast<uint32_t>(assumedBitWidth(type));
272 if (strchr(val, '.')) {
273 number_type = {bitwidth, SPV_NUMBER_FLOATING};
274 } else if (type.isSigned || val[0] == '-') {
275 number_type = {bitwidth, SPV_NUMBER_SIGNED_INT};
276 } else {
277 number_type = {bitwidth, SPV_NUMBER_UNSIGNED_INT};
278 }
279 break;
280 }
281
282 std::string error_msg;
283 EncodeNumberStatus parse_status = ParseAndEncodeNumber(
284 val, number_type,
285 [this, pInst](uint32_t d) { this->binaryEncodeU32(d, pInst); },
286 &error_msg);
287 switch (parse_status) {
288 case EncodeNumberStatus::kSuccess:
289 return SPV_SUCCESS;
290 case EncodeNumberStatus::kInvalidText:
291 return diagnostic(error_code) << error_msg;
292 case EncodeNumberStatus::kUnsupported:
293 return diagnostic(SPV_ERROR_INTERNAL) << error_msg;
294 case EncodeNumberStatus::kInvalidUsage:
295 return diagnostic(SPV_ERROR_INVALID_TEXT) << error_msg;
296 }
297 // This line is not reachable, only added to satisfy the compiler.
298 return diagnostic(SPV_ERROR_INTERNAL)
299 << "Unexpected result code from ParseAndEncodeNumber()";
300 }
301
binaryEncodeString(const char * value,spv_instruction_t * pInst)302 spv_result_t AssemblyContext::binaryEncodeString(const char* value,
303 spv_instruction_t* pInst) {
304 const size_t length = strlen(value);
305 const size_t wordCount = (length / 4) + 1;
306 const size_t oldWordCount = pInst->words.size();
307 const size_t newWordCount = oldWordCount + wordCount;
308
309 // TODO(dneto): We can just defer this check until later.
310 if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
311 return diagnostic() << "Instruction too long: more than "
312 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
313 }
314
315 pInst->words.reserve(newWordCount);
316 spvtools::utils::AppendToVector(value, &pInst->words);
317
318 return SPV_SUCCESS;
319 }
320
recordTypeDefinition(const spv_instruction_t * pInst)321 spv_result_t AssemblyContext::recordTypeDefinition(
322 const spv_instruction_t* pInst) {
323 uint32_t value = pInst->words[1];
324 if (types_.find(value) != types_.end()) {
325 return diagnostic() << "Value " << value
326 << " has already been used to generate a type";
327 }
328
329 if (pInst->opcode == spv::Op::OpTypeInt) {
330 if (pInst->words.size() != 4)
331 return diagnostic() << "Invalid OpTypeInt instruction";
332 types_[value] = {pInst->words[2], pInst->words[3] != 0,
333 IdTypeClass::kScalarIntegerType};
334 } else if (pInst->opcode == spv::Op::OpTypeFloat) {
335 if ((pInst->words.size() != 3) && (pInst->words.size() != 4))
336 return diagnostic() << "Invalid OpTypeFloat instruction";
337 // TODO(kpet) Do we need to record the FP Encoding here?
338 types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
339 } else {
340 types_[value] = {0, false, IdTypeClass::kOtherType};
341 }
342 return SPV_SUCCESS;
343 }
344
getTypeOfTypeGeneratingValue(uint32_t value) const345 IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
346 auto type = types_.find(value);
347 if (type == types_.end()) {
348 return kUnknownType;
349 }
350 return std::get<1>(*type);
351 }
352
getTypeOfValueInstruction(uint32_t value) const353 IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
354 auto type_value = value_types_.find(value);
355 if (type_value == value_types_.end()) {
356 return {0, false, IdTypeClass::kBottom};
357 }
358 return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
359 }
360
recordTypeIdForValue(uint32_t value,uint32_t type)361 spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
362 uint32_t type) {
363 bool successfully_inserted = false;
364 std::tie(std::ignore, successfully_inserted) =
365 value_types_.insert(std::make_pair(value, type));
366 if (!successfully_inserted)
367 return diagnostic() << "Value is being defined a second time";
368 return SPV_SUCCESS;
369 }
370
recordIdAsExtInstImport(uint32_t id,spv_ext_inst_type_t type)371 spv_result_t AssemblyContext::recordIdAsExtInstImport(
372 uint32_t id, spv_ext_inst_type_t type) {
373 bool successfully_inserted = false;
374 std::tie(std::ignore, successfully_inserted) =
375 import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
376 if (!successfully_inserted)
377 return diagnostic() << "Import Id is being defined a second time";
378 return SPV_SUCCESS;
379 }
380
getExtInstTypeForId(uint32_t id) const381 spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
382 auto type = import_id_to_ext_inst_type_.find(id);
383 if (type == import_id_to_ext_inst_type_.end()) {
384 return SPV_EXT_INST_TYPE_NONE;
385 }
386 return std::get<1>(*type);
387 }
388
GetNumericIds() const389 std::set<uint32_t> AssemblyContext::GetNumericIds() const {
390 std::set<uint32_t> ids;
391 for (const auto& kv : named_ids_) {
392 uint32_t id;
393 if (spvtools::utils::ParseNumber(kv.first.c_str(), &id)) ids.insert(id);
394 }
395 return ids;
396 }
397
398 } // namespace spvtools
399