blob: cc4a42be4d2a75db8870282f8b7880879b385c5e [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//
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 "text_handler.h"
28
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040029#include <cassert>
David Neto78e677b2015-10-05 13:28:46 -040030#include <cstdlib>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040031#include <cstring>
Andrew Woloszyn537e7762015-09-29 11:28:34 -040032#include <tuple>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040033
David Netofcc7d582015-10-27 15:31:10 -040034#include "assembly_grammar.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040035#include "binary.h"
36#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040037#include "instruction.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040038#include "opcode.h"
39#include "text.h"
Andrew Woloszynf731cbf2015-10-23 09:53:58 -040040#include "util/bitutils.h"
David Neto9e545d72015-11-06 18:08:49 -050041#include "util/hex_float.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040042
43namespace {
44
David Neto78e677b2015-10-05 13:28:46 -040045using spvutils::BitwiseCast;
David Neto9e545d72015-11-06 18:08:49 -050046using spvutils::FloatProxy;
47using spvutils::HexFloat;
David Neto78e677b2015-10-05 13:28:46 -040048
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040049/// @brief Advance text to the start of the next line
50///
51/// @param[in] text to be parsed
52/// @param[in,out] position position text has been advanced to
53///
54/// @return result code
55spv_result_t advanceLine(spv_text text, spv_position position) {
56 while (true) {
57 switch (text->str[position->index]) {
58 case '\0':
59 return SPV_END_OF_STREAM;
60 case '\n':
61 position->column = 0;
62 position->line++;
63 position->index++;
64 return SPV_SUCCESS;
65 default:
66 position->column++;
67 position->index++;
68 break;
69 }
70 }
71}
72
73/// @brief Advance text to first non white space character
74/// If a null terminator is found during the text advance SPV_END_OF_STREAM is
75/// returned, SPV_SUCCESS otherwise. No error checking is performed on the
76/// parameters, its the users responsibility to ensure these are non null.
77///
78/// @param[in] text to be parsed
79/// @param[in,out] position text has been advanced to
80///
81/// @return result code
82spv_result_t advance(spv_text text, spv_position position) {
83 // NOTE: Consume white space, otherwise don't advance.
Lei Zhang8f6ba142015-11-06 15:09:04 -050084 if (position->index >= text->length) return SPV_END_OF_STREAM;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040085 switch (text->str[position->index]) {
86 case '\0':
87 return SPV_END_OF_STREAM;
88 case ';':
89 if (spv_result_t error = advanceLine(text, position)) return error;
90 return advance(text, position);
91 case ' ':
92 case '\t':
93 position->column++;
94 position->index++;
95 return advance(text, position);
96 case '\n':
97 position->column = 0;
98 position->line++;
99 position->index++;
100 return advance(text, position);
101 default:
102 break;
103 }
104 return SPV_SUCCESS;
105}
106
Lei Zhang6032b982016-03-15 16:52:40 -0400107// Fetches the next word from the given text stream starting from the given
108// *position. On success, writes the decoded word into *word and updates
109// *position to the location past the returned word.
110//
111// A word ends at the next comment or whitespace. However, double-quoted
112// strings remain intact, and a backslash always escapes the next character.
113spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400114 if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
Lei Zhang6032b982016-03-15 16:52:40 -0400115 if (!position) return SPV_ERROR_INVALID_POINTER;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400116
Lei Zhang6032b982016-03-15 16:52:40 -0400117 const size_t start_index = position->index;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400118
119 bool quoting = false;
120 bool escaping = false;
121
122 // NOTE: Assumes first character is not white space!
123 while (true) {
Lei Zhang6032b982016-03-15 16:52:40 -0400124 if (position->index >= text->length) {
125 word->assign(text->str + start_index, text->str + position->index);
Lei Zhang9413fbb2016-02-22 17:17:25 -0500126 return SPV_SUCCESS;
127 }
Lei Zhang6032b982016-03-15 16:52:40 -0400128 const char ch = text->str[position->index];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400129 if (ch == '\\')
130 escaping = !escaping;
131 else {
132 switch (ch) {
133 case '"':
134 if (!escaping) quoting = !quoting;
135 break;
136 case ' ':
137 case ';':
138 case '\t':
139 case '\n':
140 if (escaping || quoting) break;
141 // Fall through.
142 case '\0': { // NOTE: End of word found!
Lei Zhang6032b982016-03-15 16:52:40 -0400143 word->assign(text->str + start_index, text->str + position->index);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400144 return SPV_SUCCESS;
145 }
146 default:
147 break;
148 }
149 escaping = false;
150 }
151
Lei Zhang6032b982016-03-15 16:52:40 -0400152 position->column++;
153 position->index++;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400154 }
155}
156
157// Returns true if the characters in the text as position represent
158// the start of an Opcode.
159bool startsWithOp(spv_text text, spv_position position) {
160 if (text->length < position->index + 3) return false;
161 char ch0 = text->str[position->index];
162 char ch1 = text->str[position->index + 1];
163 char ch2 = text->str[position->index + 2];
164 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
165}
166
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400167} // anonymous namespace
168
169namespace libspirv {
170
David Neto78e677b2015-10-05 13:28:46 -0400171const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
172
David Neto78e677b2015-10-05 13:28:46 -0400173// TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
174
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400175// This represents all of the data that is only valid for the duration of
176// a single compilation.
Lei Zhang1a0334e2015-11-02 09:41:20 -0500177uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400178 if (named_ids_.end() == named_ids_.find(textValue)) {
179 named_ids_[std::string(textValue)] = bound_++;
180 }
181 return named_ids_[textValue];
182}
183uint32_t AssemblyContext::getBound() const { return bound_; }
184
185spv_result_t AssemblyContext::advance() {
186 return ::advance(text_, &current_position_);
187}
188
Lei Zhang6032b982016-03-15 16:52:40 -0400189spv_result_t AssemblyContext::getWord(std::string* word,
190 spv_position next_position) {
191 *next_position = current_position_;
192 return ::getWord(text_, next_position, word);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400193}
194
195bool AssemblyContext::startsWithOp() {
196 return ::startsWithOp(text_, &current_position_);
197}
198
199bool AssemblyContext::isStartOfNewInst() {
Lei Zhang6032b982016-03-15 16:52:40 -0400200 spv_position_t pos = current_position_;
201 if (::advance(text_, &pos)) return false;
202 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400203
204 std::string word;
Lei Zhang6032b982016-03-15 16:52:40 -0400205 pos = current_position_;
206 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400207 if ('%' != word.front()) return false;
208
Lei Zhang6032b982016-03-15 16:52:40 -0400209 if (::advance(text_, &pos)) return false;
210 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400211 if ("=" != word) return false;
212
Lei Zhang6032b982016-03-15 16:52:40 -0400213 if (::advance(text_, &pos)) return false;
214 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400215 return false;
216}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400217
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400218char AssemblyContext::peek() const {
219 return text_->str[current_position_.index];
220}
221
222bool AssemblyContext::hasText() const {
223 return text_->length > current_position_.index;
224}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400225
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400226void AssemblyContext::seekForward(uint32_t size) {
227 current_position_.index += size;
228 current_position_.column += size;
229}
230
231spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
Lei Zhang1a0334e2015-11-02 09:41:20 -0500232 spv_instruction_t* pInst) {
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500233 pInst->words.insert(pInst->words.end(), value);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400234 return SPV_SUCCESS;
235}
236
237spv_result_t AssemblyContext::binaryEncodeU64(const uint64_t value,
Lei Zhang1a0334e2015-11-02 09:41:20 -0500238 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400239 uint32_t low = uint32_t(0x00000000ffffffff & value);
240 uint32_t high = uint32_t((0xffffffff00000000 & value) >> 32);
David Netoac508b02015-10-09 15:48:09 -0400241 binaryEncodeU32(low, pInst);
242 binaryEncodeU32(high, pInst);
243 return SPV_SUCCESS;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400244}
245
David Neto78e677b2015-10-05 13:28:46 -0400246spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500247 const char* val, spv_result_t error_code, const IdType& type,
248 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400249 const bool is_bottom = type.type_class == libspirv::IdTypeClass::kBottom;
250 const bool is_floating = libspirv::isScalarFloating(type);
251 const bool is_integer = libspirv::isScalarIntegral(type);
252
253 if (!is_bottom && !is_floating && !is_integer) {
254 return diagnostic(SPV_ERROR_INTERNAL)
255 << "The expected type is not a scalar integer or float type";
256 }
257
258 // If this is bottom, but looks like a float, we should treat it like a
259 // float.
260 const bool looks_like_float = is_bottom && strchr(val, '.');
261
262 // If we explicitly expect a floating-point number, we should handle that
263 // first.
264 if (is_floating || looks_like_float)
David Neto51013d12015-10-14 11:31:51 -0400265 return binaryEncodeFloatingPointLiteral(val, error_code, type, pInst);
David Neto78e677b2015-10-05 13:28:46 -0400266
David Neto51013d12015-10-14 11:31:51 -0400267 return binaryEncodeIntegerLiteral(val, error_code, type, pInst);
David Neto78e677b2015-10-05 13:28:46 -0400268}
269
Lei Zhang1a0334e2015-11-02 09:41:20 -0500270spv_result_t AssemblyContext::binaryEncodeString(const char* value,
271 spv_instruction_t* pInst) {
David Netob5dc8fc2015-10-06 16:22:00 -0400272 const size_t length = strlen(value);
273 const size_t wordCount = (length / 4) + 1;
274 const size_t oldWordCount = pInst->words.size();
275 const size_t newWordCount = oldWordCount + wordCount;
276
277 // TODO(dneto): We can just defer this check until later.
278 if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Neto78e677b2015-10-05 13:28:46 -0400279 return diagnostic() << "Instruction too long: more than "
280 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400281 }
282
David Netob5dc8fc2015-10-06 16:22:00 -0400283 pInst->words.resize(newWordCount);
284
285 // Make sure all the bytes in the last word are 0, in case we only
286 // write a partial word at the end.
287 pInst->words.back() = 0;
288
Lei Zhang1a0334e2015-11-02 09:41:20 -0500289 char* dest = (char*)&pInst->words[oldWordCount];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400290 strncpy(dest, value, length);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400291
292 return SPV_SUCCESS;
293}
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400294
295spv_result_t AssemblyContext::recordTypeDefinition(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500296 const spv_instruction_t* pInst) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400297 uint32_t value = pInst->words[1];
298 if (types_.find(value) != types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500299 return diagnostic() << "Value " << value
300 << " has already been used to generate a type";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400301 }
302
Lei Zhangb36e7042015-10-28 13:40:52 -0400303 if (pInst->opcode == SpvOpTypeInt) {
David Neto78e677b2015-10-05 13:28:46 -0400304 if (pInst->words.size() != 4)
305 return diagnostic() << "Invalid OpTypeInt instruction";
306 types_[value] = {pInst->words[2], pInst->words[3] != 0,
307 IdTypeClass::kScalarIntegerType};
Lei Zhangb36e7042015-10-28 13:40:52 -0400308 } else if (pInst->opcode == SpvOpTypeFloat) {
David Neto78e677b2015-10-05 13:28:46 -0400309 if (pInst->words.size() != 3)
310 return diagnostic() << "Invalid OpTypeFloat instruction";
311 types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400312 } else {
David Neto78e677b2015-10-05 13:28:46 -0400313 types_[value] = {0, false, IdTypeClass::kOtherType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400314 }
315 return SPV_SUCCESS;
316}
317
318IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
319 auto type = types_.find(value);
320 if (type == types_.end()) {
David Neto78e677b2015-10-05 13:28:46 -0400321 return kUnknownType;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400322 }
323 return std::get<1>(*type);
324}
325
326IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
327 auto type_value = value_types_.find(value);
328 if (type_value == value_types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500329 return {0, false, IdTypeClass::kBottom};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400330 }
331 return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
332}
333
334spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
335 uint32_t type) {
336 bool successfully_inserted = false;
337 std::tie(std::ignore, successfully_inserted) =
338 value_types_.insert(std::make_pair(value, type));
David Neto78e677b2015-10-05 13:28:46 -0400339 if (!successfully_inserted)
340 return diagnostic() << "Value is being defined a second time";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400341 return SPV_SUCCESS;
342}
343
David Neto2ae4a682015-11-09 18:55:42 -0500344spv_result_t AssemblyContext::recordIdAsExtInstImport(
345 uint32_t id, spv_ext_inst_type_t type) {
346 bool successfully_inserted = false;
347 std::tie(std::ignore, successfully_inserted) =
348 import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
349 if (!successfully_inserted)
350 return diagnostic() << "Import Id is being defined a second time";
351 return SPV_SUCCESS;
352}
353
354spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
355 auto type = import_id_to_ext_inst_type_.find(id);
356 if (type == import_id_to_ext_inst_type_.end()) {
357 return SPV_EXT_INST_TYPE_NONE;
358 }
359 return std::get<1>(*type);
360}
361
David Neto78e677b2015-10-05 13:28:46 -0400362spv_result_t AssemblyContext::binaryEncodeFloatingPointLiteral(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500363 const char* val, spv_result_t error_code, const IdType& type,
364 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400365 const auto bit_width = assumedBitWidth(type);
366 switch (bit_width) {
Andrew Woloszyn43401d22016-01-08 09:54:42 -0500367 case 16: {
368 spvutils::HexFloat<FloatProxy<spvutils::Float16>> hVal(0);
369 if (auto error = parseNumber(val, error_code, &hVal,
370 "Invalid 16-bit float literal: "))
371 return error;
372 // getAsFloat will return the spvutils::Float16 value, and get_value
373 // will return a uint16_t representing the bits of the float.
374 // The encoding is therefore correct from the perspective of the SPIR-V
375 // spec since the top 16 bits will be 0.
376 return binaryEncodeU32(
377 static_cast<uint32_t>(hVal.value().getAsFloat().get_value()), pInst);
378 } break;
David Neto78e677b2015-10-05 13:28:46 -0400379 case 32: {
David Neto9e545d72015-11-06 18:08:49 -0500380 spvutils::HexFloat<FloatProxy<float>> fVal(0.0f);
David Neto51013d12015-10-14 11:31:51 -0400381 if (auto error = parseNumber(val, error_code, &fVal,
David Neto78e677b2015-10-05 13:28:46 -0400382 "Invalid 32-bit float literal: "))
383 return error;
384 return binaryEncodeU32(BitwiseCast<uint32_t>(fVal), pInst);
385 } break;
386 case 64: {
David Neto9e545d72015-11-06 18:08:49 -0500387 spvutils::HexFloat<FloatProxy<double>> dVal(0.0);
David Neto51013d12015-10-14 11:31:51 -0400388 if (auto error = parseNumber(val, error_code, &dVal,
David Neto78e677b2015-10-05 13:28:46 -0400389 "Invalid 64-bit float literal: "))
390 return error;
391 return binaryEncodeU64(BitwiseCast<uint64_t>(dVal), pInst);
392 } break;
393 default:
394 break;
395 }
396 return diagnostic() << "Unsupported " << bit_width << "-bit float literals";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400397}
398
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500399// Returns SPV_SUCCESS if the given value fits within the target scalar
400// integral type. The target type may have an unusual bit width.
401// If the value was originally specified as a hexadecimal number, then
402// the overflow bits should be zero. If it was hex and the target type is
403// signed, then return the sign-extended value through the
404// updated_value_for_hex pointer argument.
405// On failure, return the given error code and emit a diagnostic if that error
406// code is not SPV_FAILED_MATCH.
David Neto78e677b2015-10-05 13:28:46 -0400407template <typename T>
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500408spv_result_t checkRangeAndIfHexThenSignExtend(T value, spv_result_t error_code,
409 const IdType& type, bool is_hex,
410 T* updated_value_for_hex) {
David Neto78e677b2015-10-05 13:28:46 -0400411 // The encoded result has three regions of bits that are of interest, from
412 // least to most significant:
413 // - magnitude bits, where the magnitude of the number would be stored if
414 // we were using a signed-magnitude representation.
415 // - an optional sign bit
416 // - overflow bits, up to bit 63 of a 64-bit number
417 // For example:
418 // Type Overflow Sign Magnitude
419 // --------------- -------- ---- ---------
420 // unsigned 8 bit 8-63 n/a 0-7
421 // signed 8 bit 8-63 7 0-6
422 // unsigned 16 bit 16-63 n/a 0-15
423 // signed 16 bit 16-63 15 0-14
424
425 // We'll use masks to define the three regions.
426 // At first we'll assume the number is unsigned.
427 const uint32_t bit_width = assumedBitWidth(type);
428 uint64_t magnitude_mask =
429 (bit_width == 64) ? -1 : ((uint64_t(1) << bit_width) - 1);
430 uint64_t sign_mask = 0;
431 uint64_t overflow_mask = ~magnitude_mask;
432
433 if (value < 0 || type.isSigned) {
434 // Accommodate the sign bit.
435 magnitude_mask >>= 1;
436 sign_mask = magnitude_mask + 1;
437 }
438
439 bool failed = false;
440 if (value < 0) {
441 // The top bits must all be 1 for a negative signed value.
442 failed = ((value & overflow_mask) != overflow_mask) ||
443 ((value & sign_mask) != sign_mask);
444 } else {
445 if (is_hex) {
446 // Hex values are a bit special. They decode as unsigned values, but
447 // may represent a negative number. In this case, the overflow bits
448 // should be zero.
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800449 failed = (value & overflow_mask) != 0;
David Neto78e677b2015-10-05 13:28:46 -0400450 } else {
Lei Zhang8bd75d62015-11-18 09:22:10 -0500451 const uint64_t value_as_u64 = static_cast<uint64_t>(value);
David Neto78e677b2015-10-05 13:28:46 -0400452 // Check overflow in the ordinary case.
Lei Zhang8bd75d62015-11-18 09:22:10 -0500453 failed = (value_as_u64 & magnitude_mask) != value_as_u64;
David Neto78e677b2015-10-05 13:28:46 -0400454 }
455 }
456
457 if (failed) {
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500458 return error_code;
David Neto78e677b2015-10-05 13:28:46 -0400459 }
460
461 // Sign extend hex the number.
462 if (is_hex && (value & sign_mask))
463 *updated_value_for_hex = (value | overflow_mask);
464
465 return SPV_SUCCESS;
466}
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500467
468spv_result_t AssemblyContext::binaryEncodeIntegerLiteral(
469 const char* val, spv_result_t error_code, const IdType& type,
470 spv_instruction_t* pInst) {
471 const bool is_bottom = type.type_class == libspirv::IdTypeClass::kBottom;
472 const uint32_t bit_width = assumedBitWidth(type);
473
474 if (bit_width > 64)
475 return diagnostic(SPV_ERROR_INTERNAL) << "Unsupported " << bit_width
476 << "-bit integer literals";
477
478 // Either we are expecting anything or integer.
479 bool is_negative = val[0] == '-';
480 bool can_be_signed = is_bottom || type.isSigned;
481
482 if (is_negative && !can_be_signed) {
483 return diagnostic()
484 << "Cannot put a negative number in an unsigned literal";
485 }
486
487 const bool is_hex = val[0] == '0' && (val[1] == 'x' || val[1] == 'X');
488
489 uint64_t decoded_bits;
490 if (is_negative) {
491 int64_t decoded_signed = 0;
492
493 if (auto error = parseNumber(val, error_code, &decoded_signed,
494 "Invalid signed integer literal: "))
495 return error;
496 if (auto error = checkRangeAndIfHexThenSignExtend(
497 decoded_signed, error_code, type, is_hex, &decoded_signed)) {
498 diagnostic(error_code)
499 << "Integer " << (is_hex ? std::hex : std::dec) << std::showbase
500 << decoded_signed << " does not fit in a " << std::dec << bit_width
501 << "-bit " << (type.isSigned ? "signed" : "unsigned") << " integer";
502 return error;
503 }
504 decoded_bits = decoded_signed;
505 } else {
506 // There's no leading minus sign, so parse it as an unsigned integer.
507 if (auto error = parseNumber(val, error_code, &decoded_bits,
508 "Invalid unsigned integer literal: "))
509 return error;
510 if (auto error = checkRangeAndIfHexThenSignExtend(
511 decoded_bits, error_code, type, is_hex, &decoded_bits)) {
512 diagnostic(error_code)
513 << "Integer " << (is_hex ? std::hex : std::dec) << std::showbase
514 << decoded_bits << " does not fit in a " << std::dec << bit_width
515 << "-bit " << (type.isSigned ? "signed" : "unsigned") << " integer";
516 return error;
517 }
518 }
519 if (bit_width > 32) {
520 return binaryEncodeU64(decoded_bits, pInst);
521 } else {
522 return binaryEncodeU32(uint32_t(decoded_bits), pInst);
523 }
524}
Lei Zhang1a0334e2015-11-02 09:41:20 -0500525} // namespace libspirv