1 // Copyright (c) 2014-2020 The Khronos Group Inc.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and/or associated documentation files (the "Materials"),
5 // to deal in the Materials without restriction, including without limitation
6 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 // and/or sell copies of the Materials, and to permit persons to whom the
8 // Materials are furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Materials.
12 //
13 // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
14 // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
15 // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
16 //
17 // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
23 // IN THE MATERIALS.
24
25 #include <assert.h>
26 #include <string.h>
27 #include <algorithm>
28 #include <iostream>
29 #include <unordered_map>
30 #include <unordered_set>
31 #include <utility>
32 #include <fstream>
33
34 #include "jsoncpp/dist/json/json.h"
35
36 #include "jsonToSpirv.h"
37
38 namespace spv {
39
40 // The set of objects that hold all the instruction/operand
41 // parameterization information.
42 InstructionValues InstructionDesc;
43
44 // The ordered list (in printing order) of printing classes
45 // (specification subsections).
46 PrintingClasses InstructionPrintingClasses;
47
48 // Note: There is no entry for OperandOpcode. Use InstructionDesc instead.
49 EnumDefinition OperandClassParams[OperandOpcode];
50 EnumValues SourceLanguageParams;
51 EnumValues ExecutionModelParams;
52 EnumValues AddressingParams;
53 EnumValues MemoryParams;
54 EnumValues ExecutionModeParams;
55 EnumValues StorageParams;
56 EnumValues SamplerAddressingModeParams;
57 EnumValues SamplerFilterModeParams;
58 EnumValues ImageFormatParams;
59 EnumValues ImageChannelOrderParams;
60 EnumValues ImageChannelDataTypeParams;
61 EnumValues ImageOperandsParams;
62 EnumValues FPFastMathParams;
63 EnumValues FPRoundingModeParams;
64 EnumValues LinkageTypeParams;
65 EnumValues DecorationParams;
66 EnumValues BuiltInParams;
67 EnumValues DimensionalityParams;
68 EnumValues FuncParamAttrParams;
69 EnumValues AccessQualifierParams;
70 EnumValues GroupOperationParams;
71 EnumValues LoopControlParams;
72 EnumValues SelectionControlParams;
73 EnumValues FunctionControlParams;
74 EnumValues MemorySemanticsParams;
75 EnumValues MemoryAccessParams;
76 EnumValues ScopeParams;
77 EnumValues KernelEnqueueFlagsParams;
78 EnumValues KernelProfilingInfoParams;
79 EnumValues CapabilityParams;
80 EnumValues RayFlagsParams;
81 EnumValues RayQueryIntersectionParams;
82 EnumValues RayQueryCommittedIntersectionTypeParams;
83 EnumValues RayQueryCandidateIntersectionTypeParams;
84 EnumValues FragmentShadingRateParams;
85
ReadFile(const std::string & path)86 std::pair<bool, std::string> ReadFile(const std::string& path)
87 {
88 std::ifstream fstream(path, std::ios::in);
89 if (fstream) {
90 std::string contents;
91 fstream.seekg(0, std::ios::end);
92 contents.reserve((unsigned int)fstream.tellg());
93 fstream.seekg(0, std::ios::beg);
94 contents.assign((std::istreambuf_iterator<char>(fstream)),
95 std::istreambuf_iterator<char>());
96 return std::make_pair(true, contents);
97 }
98 return std::make_pair(false, "");
99 }
100
101 struct ClassOptionality {
102 OperandClass type;
103 bool optional;
104 };
105
106 // Converts the |operandKind| and |quantifier| pair used to describe operands
107 // in the JSON grammar to OperandClass and optionality used in this repo.
ToOperandClassAndOptionality(const std::string & operandKind,const std::string & quantifier)108 ClassOptionality ToOperandClassAndOptionality(const std::string& operandKind, const std::string& quantifier)
109 {
110 assert(quantifier.empty() || quantifier == "?" || quantifier == "*");
111
112 if (operandKind == "IdRef") {
113 if (quantifier.empty())
114 return {OperandId, false};
115 else if (quantifier == "?")
116 return {OperandId, true};
117 else
118 return {OperandVariableIds, false};
119 } else if (operandKind == "LiteralInteger") {
120 if (quantifier.empty())
121 return {OperandLiteralNumber, false};
122 if (quantifier == "?")
123 return {OperandOptionalLiteral, true};
124 else
125 return {OperandVariableLiterals, false};
126 } else if (operandKind == "LiteralString") {
127 if (quantifier.empty())
128 return {OperandLiteralString, false};
129 else if (quantifier == "?")
130 return {OperandLiteralString, true};
131 else {
132 return {OperandOptionalLiteralStrings, false};
133 }
134 } else if (operandKind == "PairLiteralIntegerIdRef") {
135 // Used by OpSwitch in the grammar
136 return {OperandVariableLiteralId, false};
137 } else if (operandKind == "PairIdRefLiteralInteger") {
138 // Used by OpGroupMemberDecorate in the grammar
139 return {OperandVariableIdLiteral, false};
140 } else if (operandKind == "PairIdRefIdRef") {
141 // Used by OpPhi in the grammar
142 return {OperandVariableIds, false};
143 } else {
144 OperandClass type = OperandNone;
145 if (operandKind == "IdMemorySemantics" || operandKind == "MemorySemantics") {
146 type = OperandMemorySemantics;
147 } else if (operandKind == "IdScope" || operandKind == "Scope") {
148 type = OperandScope;
149 } else if (operandKind == "LiteralExtInstInteger") {
150 type = OperandLiteralNumber;
151 } else if (operandKind == "LiteralSpecConstantOpInteger") {
152 type = OperandLiteralNumber;
153 } else if (operandKind == "LiteralContextDependentNumber") {
154 type = OperandAnySizeLiteralNumber;
155 } else if (operandKind == "SourceLanguage") {
156 type = OperandSource;
157 } else if (operandKind == "ExecutionModel") {
158 type = OperandExecutionModel;
159 } else if (operandKind == "AddressingModel") {
160 type = OperandAddressing;
161 } else if (operandKind == "MemoryModel") {
162 type = OperandMemory;
163 } else if (operandKind == "ExecutionMode") {
164 type = OperandExecutionMode;
165 } else if (operandKind == "StorageClass") {
166 type = OperandStorage;
167 } else if (operandKind == "Dim") {
168 type = OperandDimensionality;
169 } else if (operandKind == "SamplerAddressingMode") {
170 type = OperandSamplerAddressingMode;
171 } else if (operandKind == "SamplerFilterMode") {
172 type = OperandSamplerFilterMode;
173 } else if (operandKind == "ImageFormat") {
174 type = OperandSamplerImageFormat;
175 } else if (operandKind == "ImageChannelOrder") {
176 type = OperandImageChannelOrder;
177 } else if (operandKind == "ImageChannelDataType") {
178 type = OperandImageChannelDataType;
179 } else if (operandKind == "FPRoundingMode") {
180 type = OperandFPRoundingMode;
181 } else if (operandKind == "LinkageType") {
182 type = OperandLinkageType;
183 } else if (operandKind == "AccessQualifier") {
184 type = OperandAccessQualifier;
185 } else if (operandKind == "FunctionParameterAttribute") {
186 type = OperandFuncParamAttr;
187 } else if (operandKind == "Decoration") {
188 type = OperandDecoration;
189 } else if (operandKind == "BuiltIn") {
190 type = OperandBuiltIn;
191 } else if (operandKind == "GroupOperation") {
192 type = OperandGroupOperation;
193 } else if (operandKind == "KernelEnqueueFlags") {
194 type = OperandKernelEnqueueFlags;
195 } else if (operandKind == "KernelProfilingInfo") {
196 type = OperandKernelProfilingInfo;
197 } else if (operandKind == "Capability") {
198 type = OperandCapability;
199 } else if (operandKind == "ImageOperands") {
200 type = OperandImageOperands;
201 } else if (operandKind == "FPFastMathMode") {
202 type = OperandFPFastMath;
203 } else if (operandKind == "SelectionControl") {
204 type = OperandSelect;
205 } else if (operandKind == "LoopControl") {
206 type = OperandLoop;
207 } else if (operandKind == "FunctionControl") {
208 type = OperandFunction;
209 } else if (operandKind == "MemoryAccess") {
210 type = OperandMemoryOperands;
211 } else if (operandKind == "RayFlags") {
212 type = OperandRayFlags;
213 } else if (operandKind == "RayQueryIntersection") {
214 type = OperandRayQueryIntersection;
215 } else if (operandKind == "RayQueryCommittedIntersectionType") {
216 type = OperandRayQueryCommittedIntersectionType;
217 } else if (operandKind == "RayQueryCandidateIntersectionType") {
218 type = OperandRayQueryCandidateIntersectionType;
219 } else if (operandKind == "FragmentShadingRate") {
220 type = OperandFragmentShadingRate;
221 }
222
223 if (type == OperandNone) {
224 std::cerr << "Unhandled operand kind found: " << operandKind << std::endl;
225 exit(1);
226 }
227 return {type, !quantifier.empty()};
228 }
229 }
230
IsTypeOrResultId(const std::string & str,bool * isType,bool * isResult)231 bool IsTypeOrResultId(const std::string& str, bool* isType, bool* isResult)
232 {
233 if (str == "IdResultType")
234 return *isType = true;
235 if (str == "IdResult")
236 return *isResult = true;
237 return false;
238 }
239
240 // Given a number string, returns the position of the only bits set in the number.
241 // So it requires the number is a power of two.
NumberStringToBit(const std::string & str)242 unsigned int NumberStringToBit(const std::string& str)
243 {
244 char* parseEnd;
245 unsigned int value = (unsigned int)std::strtol(str.c_str(), &parseEnd, 16);
246 assert(!(value & (value - 1)) && "input number is not a power of 2");
247 unsigned int bit = 0;
248 for (; value; value >>= 1) ++bit;
249 return bit;
250 }
251
jsonToSpirv(const std::string & jsonPath,bool buildingHeaders)252 void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders)
253 {
254 // only do this once.
255 static bool initialized = false;
256 if (initialized)
257 return;
258 initialized = true;
259
260 // Read the JSON grammar file.
261 bool fileReadOk = false;
262 std::string content;
263 std::tie(fileReadOk, content) = ReadFile(jsonPath);
264 if (!fileReadOk) {
265 std::cerr << "Failed to read JSON grammar file: "
266 << jsonPath << std::endl;
267 exit(1);
268 }
269
270 // Decode the JSON grammar file.
271 Json::Reader reader;
272 Json::Value root;
273 if (!reader.parse(content, root)) {
274 std::cerr << "Failed to parse JSON grammar:\n"
275 << reader.getFormattedErrorMessages();
276 exit(1);
277 }
278
279 // Layouts for all instructions.
280
281 // A lambda for returning capabilities from a JSON object as strings.
282 const auto getCaps = [](const Json::Value& object) {
283 EnumCaps result;
284 const auto& caps = object["capabilities"];
285 if (!caps.empty()) {
286 assert(caps.isArray());
287 for (const auto& cap : caps) {
288 result.emplace_back(cap.asString());
289 }
290 }
291 return result;
292 };
293
294 // A lambda for returning extensions from a JSON object as strings.
295 const auto getExts = [](const Json::Value& object) {
296 Extensions result;
297 const auto& exts = object["extensions"];
298 if (!exts.empty()) {
299 assert(exts.isArray());
300 for (const auto& ext : exts) {
301 result.emplace_back(ext.asString());
302 }
303 }
304 return result;
305 };
306
307 // set up the printing classes
308 std::unordered_set<std::string> tags; // short-lived local for error checking below
309 const Json::Value printingClasses = root["instruction_printing_class"];
310 for (const auto& printingClass : printingClasses) {
311 if (printingClass["tag"].asString().size() > 0)
312 tags.insert(printingClass["tag"].asString()); // just for error checking
313 else
314 std::cerr << "Error: each instruction_printing_class requires a non-empty \"tag\"" << std::endl;
315 if (buildingHeaders || printingClass["tag"].asString() != "@exclude") {
316 InstructionPrintingClasses.push_back({printingClass["tag"].asString(),
317 printingClass["heading"].asString()});
318 }
319 }
320
321 // process the instructions
322 const Json::Value insts = root["instructions"];
323 for (const auto& inst : insts) {
324 const auto printingClass = inst["class"].asString();
325 if (printingClass.size() == 0) {
326 std::cerr << "Error: " << inst["opname"].asString()
327 << " requires a non-empty printing \"class\" tag" << std::endl;
328 }
329 if (!buildingHeaders && printingClass == "@exclude")
330 continue;
331 if (tags.find(printingClass) == tags.end()) {
332 std::cerr << "Error: " << inst["opname"].asString()
333 << " requires a \"class\" declared as a \"tag\" in \"instruction printing_class\""
334 << std::endl;
335 }
336 const auto opcode = inst["opcode"].asUInt();
337 const std::string name = inst["opname"].asString();
338 EnumCaps caps = getCaps(inst);
339 std::string version = inst["version"].asString();
340 std::string lastVersion = inst["lastVersion"].asString();
341 Extensions exts = getExts(inst);
342 OperandParameters operands;
343 bool defResultId = false;
344 bool defTypeId = false;
345 for (const auto& operand : inst["operands"]) {
346 const std::string kind = operand["kind"].asString();
347 const std::string quantifier = operand.get("quantifier", "").asString();
348 const std::string doc = operand.get("name", "").asString();
349 if (!IsTypeOrResultId(kind, &defTypeId, &defResultId)) {
350 const auto p = ToOperandClassAndOptionality(kind, quantifier);
351 operands.push(p.type, doc, p.optional);
352 }
353 }
354 InstructionDesc.emplace_back(
355 std::move(EnumValue(opcode, name,
356 std::move(caps), std::move(version), std::move(lastVersion), std::move(exts),
357 std::move(operands))),
358 printingClass, defTypeId, defResultId);
359 }
360
361 // Specific additional context-dependent operands
362
363 // Populate dest with EnumValue objects constructed from source.
364 const auto populateEnumValues = [&getCaps,&getExts](EnumValues* dest, const Json::Value& source, bool bitEnum) {
365 // A lambda for determining the numeric value to be used for a given
366 // enumerant in JSON form, and whether that value is a 0 in a bitfield.
367 auto getValue = [&bitEnum](const Json::Value& enumerant) {
368 std::pair<unsigned, bool> result{0u,false};
369 if (!bitEnum) {
370 result.first = enumerant["value"].asUInt();
371 } else {
372 const unsigned int bit = NumberStringToBit(enumerant["value"].asString());
373 if (bit == 0)
374 result.second = true;
375 else
376 result.first = bit - 1; // This is the *shift* amount.
377 }
378 return result;
379 };
380
381 for (const auto& enumerant : source["enumerants"]) {
382 unsigned value;
383 bool skip_zero_in_bitfield;
384 std::tie(value, skip_zero_in_bitfield) = getValue(enumerant);
385 if (skip_zero_in_bitfield)
386 continue;
387 EnumCaps caps(getCaps(enumerant));
388 std::string version = enumerant["version"].asString();
389 std::string lastVersion = enumerant["lastVersion"].asString();
390 Extensions exts(getExts(enumerant));
391 OperandParameters params;
392 const Json::Value& paramsJson = enumerant["parameters"];
393 if (!paramsJson.empty()) { // This enumerant has parameters.
394 assert(paramsJson.isArray());
395 for (const auto& param : paramsJson) {
396 const std::string kind = param["kind"].asString();
397 const std::string doc = param.get("name", "").asString();
398 const auto p = ToOperandClassAndOptionality(kind, ""); // All parameters are required!
399 params.push(p.type, doc);
400 }
401 }
402 dest->emplace_back(
403 value, enumerant["enumerant"].asString(),
404 std::move(caps), std::move(version), std::move(lastVersion), std::move(exts), std::move(params));
405 }
406 };
407
408 const auto establishOperandClass = [&populateEnumValues](
409 const std::string& enumName, spv::OperandClass operandClass,
410 spv::EnumValues* enumValues, const Json::Value& operandEnum, const std::string& category) {
411 assert(category == "BitEnum" || category == "ValueEnum");
412 bool bitEnum = (category == "BitEnum");
413 populateEnumValues(enumValues, operandEnum, bitEnum);
414 OperandClassParams[operandClass].set(enumName, enumValues, bitEnum);
415 };
416
417 const Json::Value operandEnums = root["operand_kinds"];
418 for (const auto& operandEnum : operandEnums) {
419 const std::string enumName = operandEnum["kind"].asString();
420 const std::string category = operandEnum["category"].asString();
421 if (enumName == "SourceLanguage") {
422 establishOperandClass(enumName, OperandSource, &SourceLanguageParams, operandEnum, category);
423 } else if (enumName == "Decoration") {
424 establishOperandClass(enumName, OperandDecoration, &DecorationParams, operandEnum, category);
425 } else if (enumName == "ExecutionMode") {
426 establishOperandClass(enumName, OperandExecutionMode, &ExecutionModeParams, operandEnum, category);
427 } else if (enumName == "Capability") {
428 establishOperandClass(enumName, OperandCapability, &CapabilityParams, operandEnum, category);
429 } else if (enumName == "AddressingModel") {
430 establishOperandClass(enumName, OperandAddressing, &AddressingParams, operandEnum, category);
431 } else if (enumName == "MemoryModel") {
432 establishOperandClass(enumName, OperandMemory, &MemoryParams, operandEnum, category);
433 } else if (enumName == "MemorySemantics") {
434 establishOperandClass(enumName, OperandMemorySemantics, &MemorySemanticsParams, operandEnum, category);
435 } else if (enumName == "ExecutionModel") {
436 establishOperandClass(enumName, OperandExecutionModel, &ExecutionModelParams, operandEnum, category);
437 } else if (enumName == "StorageClass") {
438 establishOperandClass(enumName, OperandStorage, &StorageParams, operandEnum, category);
439 } else if (enumName == "SamplerAddressingMode") {
440 establishOperandClass(enumName, OperandSamplerAddressingMode, &SamplerAddressingModeParams, operandEnum, category);
441 } else if (enumName == "SamplerFilterMode") {
442 establishOperandClass(enumName, OperandSamplerFilterMode, &SamplerFilterModeParams, operandEnum, category);
443 } else if (enumName == "ImageFormat") {
444 establishOperandClass(enumName, OperandSamplerImageFormat, &ImageFormatParams, operandEnum, category);
445 } else if (enumName == "ImageChannelOrder") {
446 establishOperandClass(enumName, OperandImageChannelOrder, &ImageChannelOrderParams, operandEnum, category);
447 } else if (enumName == "ImageChannelDataType") {
448 establishOperandClass(enumName, OperandImageChannelDataType, &ImageChannelDataTypeParams, operandEnum, category);
449 } else if (enumName == "ImageOperands") {
450 establishOperandClass(enumName, OperandImageOperands, &ImageOperandsParams, operandEnum, category);
451 } else if (enumName == "FPFastMathMode") {
452 establishOperandClass(enumName, OperandFPFastMath, &FPFastMathParams, operandEnum, category);
453 } else if (enumName == "FPRoundingMode") {
454 establishOperandClass(enumName, OperandFPRoundingMode, &FPRoundingModeParams, operandEnum, category);
455 } else if (enumName == "LinkageType") {
456 establishOperandClass(enumName, OperandLinkageType, &LinkageTypeParams, operandEnum, category);
457 } else if (enumName == "FunctionParameterAttribute") {
458 establishOperandClass(enumName, OperandFuncParamAttr, &FuncParamAttrParams, operandEnum, category);
459 } else if (enumName == "AccessQualifier") {
460 establishOperandClass(enumName, OperandAccessQualifier, &AccessQualifierParams, operandEnum, category);
461 } else if (enumName == "BuiltIn") {
462 establishOperandClass(enumName, OperandBuiltIn, &BuiltInParams, operandEnum, category);
463 } else if (enumName == "SelectionControl") {
464 establishOperandClass(enumName, OperandSelect, &SelectionControlParams, operandEnum, category);
465 } else if (enumName == "LoopControl") {
466 establishOperandClass(enumName, OperandLoop, &LoopControlParams, operandEnum, category);
467 } else if (enumName == "FunctionControl") {
468 establishOperandClass(enumName, OperandFunction, &FunctionControlParams, operandEnum, category);
469 } else if (enumName == "Dim") {
470 establishOperandClass(enumName, OperandDimensionality, &DimensionalityParams, operandEnum, category);
471 } else if (enumName == "MemoryAccess") {
472 establishOperandClass(enumName, OperandMemoryOperands, &MemoryAccessParams, operandEnum, category);
473 } else if (enumName == "Scope") {
474 establishOperandClass(enumName, OperandScope, &ScopeParams, operandEnum, category);
475 } else if (enumName == "GroupOperation") {
476 establishOperandClass(enumName, OperandGroupOperation, &GroupOperationParams, operandEnum, category);
477 } else if (enumName == "KernelEnqueueFlags") {
478 establishOperandClass(enumName, OperandKernelEnqueueFlags, &KernelEnqueueFlagsParams, operandEnum, category);
479 } else if (enumName == "KernelProfilingInfo") {
480 establishOperandClass(enumName, OperandKernelProfilingInfo, &KernelProfilingInfoParams, operandEnum, category);
481 } else if (enumName == "RayFlags") {
482 establishOperandClass(enumName, OperandRayFlags, &RayFlagsParams, operandEnum, category);
483 } else if (enumName == "RayQueryIntersection") {
484 establishOperandClass(enumName, OperandRayQueryIntersection, &RayQueryIntersectionParams, operandEnum, category);
485 } else if (enumName == "RayQueryCommittedIntersectionType") {
486 establishOperandClass(enumName, OperandRayQueryCommittedIntersectionType, &RayQueryCommittedIntersectionTypeParams, operandEnum, category);
487 } else if (enumName == "RayQueryCandidateIntersectionType") {
488 establishOperandClass(enumName, OperandRayQueryCandidateIntersectionType, &RayQueryCandidateIntersectionTypeParams, operandEnum, category);
489 } else if (enumName == "FragmentShadingRate") {
490 establishOperandClass(enumName, OperandFragmentShadingRate, &FragmentShadingRateParams, operandEnum, category);
491 }
492 }
493 }
494
495 }; // end namespace spv
496