Debian Codegraph @

tools/matinfo/src/main.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <getopt/getopt.h>
18
19 #include <utils/Path.h>
20
21 #include <filaflat/BlobDictionary.h>
22 #include <filaflat/ChunkContainer.h>
23
24 #include <matdbg/DebugServer.h>
25 #include <matdbg/ShaderExtractor.h>
26 #include <matdbg/ShaderInfo.h>
27 #include <matdbg/TextWriter.h>
28
29 #include <spirv_glsl.hpp>
30 #include <spirv-tools/libspirv.h>
31
32 #include <chrono>
33 #include <fstream>
34 #include <iomanip>
35 #include <iostream>
36 #include <map>
37 #include <regex>
38 #include <set>
39 #include <sstream>
40 #include <thread>
41
42 using namespace filament::matdbg;
43
44 using filaflat::BlobDictionary;
45 using filaflat::ChunkContainer;
46 using filament::backend::Backend;
47 using utils::Path;
48
49 struct Config {
50 bool printGLSL = false;
51 bool printSPIRV = false;
52 bool printMetal = false;
53 bool printDictionaryGLSL = false;
54 bool printDictionarySPIRV = false;
55 bool printDictionaryMetal = false;
56 bool transpile = false;
57 bool binary = false;
58 bool analyze = false;
59 uint64_t shaderIndex;
60 int serverPort = 0;
61 };
62
63 static void printUsage(const char* name) {
64 std::string execName(utils::Path(name).getName());
65 std::string usage(
66 "MATINFO prints information about material files compiled with matc\n"
67 "Usage:\n"
68 " MATINFO [options] <material file>\n"
69 "\n"
70 "Options:\n"
71 " --help, -h\n"
72 " Print this message\n\n"
73 " --print-glsl=[index], -g\n"
74 " Print GLSL for the nth shader (0 is the first OpenGL shader)\n\n"
75 " --print-spirv=[index], -s\n"
76 " Validate and print disasm for the nth shader (0 is the first Vulkan shader)\n\n"
77 " --print-metal=[index], -m\n"
78 " Print Metal Shading Language for the nth shader (0 is the first Metal shader)\n\n"
79 " --print-vkglsl=[index], -v\n"
80 " Print the nth Vulkan shader transpiled into GLSL\n\n"
81 " --print-dic-glsl\n"
82 " Print the GLSL dictionary\n\n"
83 " --print-dic-metal\n"
84 " Print the Metal dictionary\n\n"
85 " --print-dic-vk\n"
86 " Print the Vulkan dictionary\n\n"
87 " --web-server=[port], -w\n"
88 " Serve a web page at the given port (e.g. 8080)\n\n"
89 " --dump-binary=[index], -b\n"
90 " Dump binary SPIRV for the nth Vulkan shader to 'out.spv'\n\n"
91 " --license\n"
92 " Print copyright and license information\n\n"
93 " --analyze-spirv=[index], -a\n"
94 " Print annotated GLSL for the nth shader (0 is the first Vulkan shader)\n\n"
95 );
96
97 const std::string from("MATINFO");
98 for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
99 usage.replace(pos, from.length(), execName);
100 }
101 printf("%s", usage.c_str());
102 }
103
104 static void license() {
105 static const char *license[] = {
106 #include "licenses/licenses.inc"
107 nullptr
108 };
109
110 const char **p = &license[0];
111 while (*p)
112 std::cout << *p++ << std::endl;
113 }
114
115 static int handleArguments(int argc, char* argv[], Config* config) {
116 static constexpr const char* OPTSTR = "hla:g:s:v:b:m:b:w:xyz";
117 static const struct option OPTIONS[] = {
118 { "help", no_argument, 0, 'h' },
119 { "license", no_argument, 0, 'l' },
120 { "analyze-spirv", required_argument, 0, 'a' },
121 { "print-glsl", required_argument, 0, 'g' },
122 { "print-spirv", required_argument, 0, 's' },
123 { "print-vkglsl", required_argument, 0, 'v' },
124 { "print-metal", required_argument, 0, 'm' },
125 { "print-dic-glsl", no_argument, 0, 'x' },
126 { "print-dic-metal", no_argument, 0, 'y' },
127 { "print-dic-vk", no_argument, 0, 'z' },
128 { "dump-binary", required_argument, 0, 'b' },
129 { "web-server", required_argument, 0, 'w' },
130 { 0, 0, 0, 0 } // termination of the option list
131 };
132
133 int opt;
134 int optionIndex = 0;
135
136 while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &optionIndex)) >= 0) {
137 std::string arg(optarg ? optarg : "");
138 switch (opt) {
139 default:
140 case 'h':
141 printUsage(argv[0]);
142 exit(0);
143 case 'l':
144 license();
145 exit(0);
146 case 'g':
147 config->printGLSL = true;
148 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
149 break;
150 case 's':
151 config->printSPIRV = true;
152 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
153 break;
154 case 'v':
155 config->printSPIRV = true;
156 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
157 config->transpile = true;
158 break;
159 case 'a':
160 config->printSPIRV = true;
161 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
162 config->analyze = true;
163 break;
164 case 'b':
165 config->printSPIRV = true;
166 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
167 config->binary = true;
168 break;
169 case 'm':
170 config->printMetal = true;
171 config->shaderIndex = static_cast<uint64_t>(std::stoi(arg));
172 break;
173 case 'w':
174 config->serverPort = std::stoi(arg);
175 break;
176 case 'x':
177 config->printDictionaryGLSL = true;
178 break;
179 case 'y':
180 config->printDictionaryMetal = true;
181 break;
182 case 'z':
183 config->printDictionarySPIRV = true;
184 break;
185 }
186 }
187
188 return optind;
189 }
190
191 template<typename T>
192 static bool read(const filaflat::ChunkContainer& container, filamat::ChunkType type,
193 T* value) noexcept {
194 if (!container.hasChunk(type)) {
195 return false;
196 }
197
198 filaflat::Unflattener unflattener(container.getChunkStart(type), container.getChunkEnd(type));
199 return unflattener.read(value);
200 }
201
202 static std::ifstream::pos_type getFileSize(const char* filename) {
203 std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
204 return in.tellg();
205 }
206
207 // Consumes SPIRV binary and produces a GLSL-ES string.
208 static void transpileSpirv(const std::vector<uint32_t>& spirv) {
209 std::cout << ShaderExtractor::spirvToGLSL(spirv.data(), spirv.size()).c_str();
210 }
211
212 // Consumes SPIRV binary and produces an ordered map from "line number" to "GLSL string" where
213 // the line number is determined by line directives, and the GLSL string is one or more lines of
214 // transpiled GLSL-ES.
215 static std::map<int, std::string> transpileSpirvToLines(const std::vector<uint32_t>& spirv) {
216 using namespace spirv_cross;
217
218 CompilerGLSL::Options emitOptions;
219 emitOptions.es = true;
220 emitOptions.vulkan_semantics = true;
221 emitOptions.emit_line_directives = true;
222
223 CompilerGLSL glslCompiler(move(spirv));
224 glslCompiler.set_common_options(emitOptions);
225 std::string transpiled = glslCompiler.compile();
226
227 std::map<int, std::string> result;
228 const std::regex lineDirectivePattern("\\#line ([0-9]+)");
229
230 std::istringstream ss(glslCompiler.compile());
231 std::string glslCodeline;
232 int currentLineNumber = -1;
233 while (std::getline(ss, glslCodeline, '\n')) {
234 std::smatch matchResult;
235 if (std::regex_search(glslCodeline, matchResult, lineDirectivePattern)) {
236 currentLineNumber = stoi(matchResult[1].str());
237 } else {
238 result[currentLineNumber] += glslCodeline + "\n";
239 }
240 }
241
242 return result;
243 }
244
245 static void analyzeSpirv(const std::vector<uint32_t>& spirv, const char* disassembly) {
246 using namespace std;
247
248 const map<int, string> glsl = transpileSpirvToLines(spirv);
249 const regex globalDecoratorPattern("OpDecorate (\\%[A-Za-z_0-9]+) RelaxedPrecision");
250 const regex typeDefinitionPattern("(\\%[A-Za-z_0-9]+) = OpType[A-Z][a-z]+");
251 const regex memberDecoratorPattern("OpMemberDecorate (\\%[A-Za-z_0-9]+) ([0-9]+) RelaxedPrecision");
252 const regex lineDirectivePattern("OpLine (\\%[A-Za-z_0-9]+) ([0-9]+)");
253 const regex binaryFunctionPattern("(\\%[A-Za-z_0-9]+).*(\\%[A-Za-z_0-9]+)");
254 const regex operandPattern("(\\%[A-Za-z_0-9]+)");
255 const regex sensitivePattern("OpComposite[A-Za-z]+");
256
257 string spirvInstruction;
258 smatch matchResult;
259
260 // In the first pass, collect types and variables that are decorated as "relaxed".
261 //
262 // NOTE: We also collect struct members but do not use them in any analysis (yet).
263 // In SPIR-V, struct fields are accessed through pointers, so we would need to:
264 //
265 // 1) Create a map of all OpConstant values (integers only, %int and %uint)
266 // 2) Parse all "OpAccessChain" instructions and dereference their OpConstant arguments
267 // 3) Follow through to the downstream OpStore / OpLoad
268 //
269 // Regarding struct field precision, the SPIR-V specification says:
270 //
271 // When applied to a variable or structure member, all loads and stores from the decorated
272 // object may be treated as though they were decorated with RelaxedPrecision. Loads may also
273 // be decorated with RelaxedPrecision, in which case they are treated as operating at
274 // relaxed precision.
275
276 set<string> relaxedPrecisionVariables;
277 set<string> typeIds;
278 {
279 istringstream ss(disassembly);
280 while (getline(ss, spirvInstruction, '\n')) {
281 if (regex_search(spirvInstruction, matchResult, typeDefinitionPattern)) {
282 typeIds.insert(matchResult[1].str());
283 } else if (regex_search(spirvInstruction, matchResult, globalDecoratorPattern)) {
284 relaxedPrecisionVariables.insert(matchResult[1].str());
285 } else if (regex_search(spirvInstruction, matchResult, memberDecoratorPattern)) {
286 string member = matchResult[1].str() + "." + matchResult[2].str();
287 relaxedPrecisionVariables.insert(member);
288 }
289 }
290 }
291
292 // In the second pass, track line numbers and detect potential mixed precision.
293 // The line directive are not necessarily in order (!) so we also track their ordering.
294
295 map<int, string> mixedPrecisionInfo;
296 vector<int> lineNumbers = {-1};
297 {
298 istringstream ss(disassembly);
299 int currentLineNumber = -1;
300 while (getline(ss, spirvInstruction, '\n')) {
301 if (regex_search(spirvInstruction, matchResult, lineDirectivePattern)) {
302 currentLineNumber = stoi(matchResult[2].str());
303 lineNumbers.push_back(currentLineNumber);
304 } else {
305
306 // Trim out the leftmost whitespace.
307 const string trimmed = regex_replace(spirvInstruction, regex("^\\s+"), string(""));
308
309 // Check for mixed precision.
310 bool mixed = false;
311 int relaxed = -1;
312 string remaining = trimmed;
313 string info;
314 while (regex_search(remaining, matchResult, operandPattern)) {
315 const string arg = matchResult[1].str();
316 if (typeIds.count(arg) == 0) {
317 if (relaxedPrecisionVariables.count(arg) > 0) {
318 mixed = relaxed == 0 ? true : mixed;
319 relaxed = 1;
320 info += arg + " ";
321 } else {
322 mixed = relaxed == 1 ? true : mixed;
323 relaxed = 0;
324 }
325 }
326 remaining = matchResult.suffix();
327 }
328 if (mixed && currentLineNumber > -1) {
329 if (regex_search(trimmed, matchResult, sensitivePattern)) {
330 info = "// " + trimmed + " ; relaxed = " + info + "\n";
331 mixedPrecisionInfo[currentLineNumber] += info;
332 }
333 }
334 }
335 }
336 if (currentLineNumber == -1) {
337 cerr << "No #line directives found, did you use a debug version of matc?" << endl;
338 return;
339 }
340 }
341
342 // Finally, dump out the annotated GLSL.
343
344 for (int lineNumber : lineNumbers) {
345 if (!glsl.count(lineNumber)) {
346 continue;
347 }
348 istringstream ss(glsl.at(lineNumber));
349 string glslCodeline;
350 bool firstLine = true;
351 while (getline(ss, glslCodeline, '\n')) {
352 cout << glslCodeline << endl;
353 if (firstLine) {
354 if (mixedPrecisionInfo.count(lineNumber)) {
355 string info = mixedPrecisionInfo.at(lineNumber);
356 cout << "// POTENTIAL MIXED PRECISION\n" << info;
357 }
358 firstLine = false;
359 }
360 }
361 }
362 }
363
364 static void disassembleSpirv(const std::vector<uint32_t>& spirv, bool analyze) {
365 utils::CString text = ShaderExtractor::spirvToText(spirv.data(), spirv.size());
366 if (analyze) {
367 analyzeSpirv(spirv, text.c_str());
368 } else {
369 std::cout << text.c_str() << std::endl;
370 }
371 }
372
373 static void dumpSpirvBinary(const std::vector<uint32_t>& spirv, std::string filename) {
374 std::ofstream out(filename, std::ofstream::binary);
375 out.write((const char*) spirv.data(), spirv.size() * 4);
376 std::cout << "Binary SPIR-V dumped to " << filename << std::endl;
377 }
378
379 static bool parseChunks(Config config, void* data, size_t size) {
380 using namespace filament::matdbg;
381 ChunkContainer container(data, size);
382 if (!container.parse()) {
383 return false;
384 }
385
386 if (config.serverPort) {
387 // Spin up a web server on a secondary thread.
388 DebugServer server(Backend::DEFAULT, config.serverPort);
389 if (!server.isReady()) {
390 return false;
391 }
392
393 // Notify the server that we have a filamat file.
394 utils::CString name;
395 read(container, filamat::MaterialName, &name);
396 server.addMaterial(name, data, size);
397
398 // Keep listening until the user does Ctrl+C.
399 while (true) {
400 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
401 }
402
403 return true;
404 }
405
406 if (config.printGLSL || config.printSPIRV || config.printMetal) {
407 filaflat::ShaderBuilder builder;
408 std::vector<ShaderInfo> info;
409
410 if (config.printGLSL) {
411 ShaderExtractor parser(Backend::OPENGL, data, size);
412 if (!parser.parse()) {
413 return false;
414 }
415
416 info.resize(getShaderCount(container, filamat::ChunkType::MaterialGlsl));
417 if (!getGlShaderInfo(container, info.data())) {
418 std::cerr << "Failed to parse GLSL chunk." << std::endl;
419 return false;
420 }
421
422 if (config.shaderIndex >= info.size()) {
423 std::cerr << "Shader index out of range." << std::endl;
424 return false;
425 }
426
427 const auto& item = info[config.shaderIndex];
428 parser.getShader(item.shaderModel, item.variant, item.pipelineStage, builder);
429
430 // Casted to char* to print as a string rather than hex value.
431 std::cout << (const char*) builder.data();
432
433 return true;
434 }
435
436 if (config.printSPIRV) {
437 ShaderExtractor parser(Backend::VULKAN, data, size);
438 if (!parser.parse()) {
439 return false;
440 }
441
442 info.resize(getShaderCount(container, filamat::ChunkType::MaterialSpirv));
443 if (!getVkShaderInfo(container, info.data())) {
444 std::cerr << "Failed to parse SPIRV chunk." << std::endl;
445 return false;
446 }
447
448 if (config.shaderIndex >= info.size()) {
449 std::cerr << "Shader index out of range." << std::endl;
450 return false;
451 }
452
453 const auto& item = info[config.shaderIndex];
454 parser.getShader(item.shaderModel, item.variant, item.pipelineStage, builder);
455
456 // Build std::vector<uint32_t> since that's what the Khronos libraries consume.
457 uint32_t const* words = reinterpret_cast<uint32_t const*>(builder.data());
458 assert(0 == (builder.size() % 4));
459 const std::vector<uint32_t> spirv(words, words + builder.size() / 4);
460
461 if (config.transpile) {
462 transpileSpirv(spirv);
463 } else if (config.binary) {
464 dumpSpirvBinary(spirv, "out.spv");
465 } else {
466 disassembleSpirv(spirv, config.analyze);
467 }
468
469 return true;
470 }
471
472 if (config.printMetal) {
473 ShaderExtractor parser(Backend::METAL, data, size);
474 if (!parser.parse()) {
475 return false;
476 }
477
478 info.resize(getShaderCount(container, filamat::ChunkType::MaterialMetal));
479 if (!getMetalShaderInfo(container, info.data())) {
480 std::cerr << "Failed to parse Metal chunk." << std::endl;
481 return false;
482 }
483
484 if (config.shaderIndex >= info.size()) {
485 std::cerr << "Shader index out of range." << std::endl;
486 return false;
487 }
488
489 const auto& item = info[config.shaderIndex];
490 parser.getShader(item.shaderModel, item.variant, item.pipelineStage, builder);
491 std::cout << (const char*) builder.data();
492
493 return true;
494 }
495 }
496
497 TextWriter writer;
498
499 if (config.printDictionaryGLSL || config.printDictionarySPIRV || config.printDictionaryMetal) {
500 ShaderExtractor parser(
501 (config.printDictionaryGLSL ? Backend::OPENGL :
502 (config.printDictionarySPIRV ? Backend::VULKAN :
503 (config.printDictionaryMetal ? Backend::METAL : Backend::DEFAULT))), data, size);
504
505 if (!parser.parse()) {
506 return false;
507 }
508
509 BlobDictionary dictionary;
510 if (!parser.getDictionary(dictionary)) {
511 return false;
512 }
513
514 for (size_t i = 0; i < dictionary.size(); i++) {
515 std::cout << dictionary.getString(i) << std::endl;
516 }
517
518 return true;
519 }
520
521 if (!writer.writeMaterialInfo(container)) {
522 return false;
523 }
524
525 std::cout << writer.getString();
526
527 return true;
528 }
529
530 // Parse the contents of .inc files, which look like: "0xba, 0xdf, 0xf0" etc. Happily, istream
531 // skips over whitespace and commas, and stoul takes care of leading "0x" when parsing hex.
532 static bool parseTextBlob(Config config, std::istream& in) {
533 std::vector<char> buffer;
534 std::string hexcode;
535 while (in >> hexcode) {
536 buffer.push_back(static_cast<char>(std::stoul(hexcode, nullptr, 16)));
537 }
538 return parseChunks(config, buffer.data(), buffer.size());
539 }
540
541 static bool parseBinary(Config config, std::istream& in, long fileSize) {
542 std::vector<char> buffer(static_cast<unsigned long>(fileSize));
543 if (in.read(buffer.data(), fileSize)) {
544 return parseChunks(config, buffer.data(), buffer.size());
545 }
546 std::cerr << "Could not read the source material." << std::endl;
547 return false;
548 }
549
550 int main(int argc, char* argv[]) {
551 Config config;
552 int optionIndex = handleArguments(argc, argv, &config);
553
554 int numArgs = argc - optionIndex;
555 if (numArgs < 1) {
556 printUsage(argv[0]);
557 return 1;
558 }
559
560 Path src(argv[optionIndex]);
561 if (!src.exists()) {
562 std::cerr << "The source material " << src << " does not exist." << std::endl;
563 return 1;
564 }
565
566 long fileSize = static_cast<long>(getFileSize(src.c_str()));
567 if (fileSize <= 0) {
568 std::cerr << "The source material " << src << " is invalid." << std::endl;
569 return 1;
570 }
571
572 std::ifstream in(src.c_str(), std::ifstream::in | std::ios::binary);
573 if (in.is_open()) {
574 if (src.getExtension() == "inc") {
575 return parseTextBlob(config, in) ? 0 : 1;
576 } else {
577 return parseBinary(config, in, fileSize) ? 0 : 1;
578 }
579 } else {
580 std::cerr << "Could not open the source material " << src << std::endl;
581 return 1;
582 };
583
584 return 0;
585 }