1 //
2 // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2016-2020 Google, Inc.
5 // Modifications Copyright(C) 2021 Advanced Micro Devices, Inc.All rights reserved.
6 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 // Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
15 //
16 // Redistributions in binary form must reproduce the above
17 // copyright notice, this list of conditions and the following
18 // disclaimer in the documentation and/or other materials provided
19 // with the distribution.
20 //
21 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 // contributors may be used to endorse or promote products derived
23 // from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
37 //
38
39 // this only applies to the standalone wrapper, not the front end in general
40 #ifndef _CRT_SECURE_NO_WARNINGS
41 #define _CRT_SECURE_NO_WARNINGS
42 #endif
43
44 #include "glslang/Public/ResourceLimits.h"
45 #include "Worklist.h"
46 #include "DirStackFileIncluder.h"
47 #include "./../glslang/Include/ShHandle.h"
48 #include "./../glslang/Public/ShaderLang.h"
49 #include "../glslang/MachineIndependent/localintermediate.h"
50 #include "../SPIRV/GlslangToSpv.h"
51 #include "../SPIRV/GLSL.std.450.h"
52 #include "../SPIRV/doc.h"
53 #include "../SPIRV/disassemble.h"
54
55 #include <array>
56 #include <atomic>
57 #include <cctype>
58 #include <cmath>
59 #include <cstdlib>
60 #include <cstring>
61 #include <map>
62 #include <memory>
63 #include <set>
64 #include <thread>
65
66 #include "../glslang/OSDependent/osinclude.h"
67
68 // Build-time generated includes
69 #include "glslang/build_info.h"
70
71 #include "glslang/glsl_intrinsic_header.h"
72
73 extern "C" {
74 GLSLANG_EXPORT void ShOutputHtml();
75 }
76
77 // Command-line options
78 enum TOptions : uint64_t {
79 EOptionNone = 0,
80 EOptionIntermediate = (1ull << 0),
81 EOptionSuppressInfolog = (1ull << 1),
82 EOptionMemoryLeakMode = (1ull << 2),
83 EOptionRelaxedErrors = (1ull << 3),
84 EOptionGiveWarnings = (1ull << 4),
85 EOptionLinkProgram = (1ull << 5),
86 EOptionMultiThreaded = (1ull << 6),
87 EOptionDumpConfig = (1ull << 7),
88 EOptionDumpReflection = (1ull << 8),
89 EOptionSuppressWarnings = (1ull << 9),
90 EOptionDumpVersions = (1ull << 10),
91 EOptionSpv = (1ull << 11),
92 EOptionHumanReadableSpv = (1ull << 12),
93 EOptionVulkanRules = (1ull << 13),
94 EOptionDefaultDesktop = (1ull << 14),
95 EOptionOutputPreprocessed = (1ull << 15),
96 EOptionOutputHexadecimal = (1ull << 16),
97 EOptionReadHlsl = (1ull << 17),
98 EOptionCascadingErrors = (1ull << 18),
99 EOptionAutoMapBindings = (1ull << 19),
100 EOptionFlattenUniformArrays = (1ull << 20),
101 EOptionNoStorageFormat = (1ull << 21),
102 EOptionKeepUncalled = (1ull << 22),
103 EOptionHlslOffsets = (1ull << 23),
104 EOptionHlslIoMapping = (1ull << 24),
105 EOptionAutoMapLocations = (1ull << 25),
106 EOptionDebug = (1ull << 26),
107 EOptionStdin = (1ull << 27),
108 EOptionOptimizeDisable = (1ull << 28),
109 EOptionOptimizeSize = (1ull << 29),
110 EOptionInvertY = (1ull << 30),
111 EOptionDumpBareVersion = (1ull << 31),
112 EOptionCompileOnly = (1ull << 32),
113 };
114 bool targetHlslFunctionality1 = false;
115 bool SpvToolsDisassembler = false;
116 bool SpvToolsValidate = false;
117 bool NaNClamp = false;
118 bool stripDebugInfo = false;
119 bool emitNonSemanticShaderDebugInfo = false;
120 bool emitNonSemanticShaderDebugSource = false;
121 bool beQuiet = false;
122 bool VulkanRulesRelaxed = false;
123 bool autoSampledTextures = false;
124
125 //
126 // Return codes from main/exit().
127 //
128 enum TFailCode {
129 ESuccess = 0,
130 EFailUsage,
131 EFailCompile,
132 EFailLink,
133 EFailCompilerCreate,
134 EFailThreadCreate,
135 EFailLinkerCreate
136 };
137
138 //
139 // Forward declarations.
140 //
141 EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
142 void CompileFile(const char* fileName, ShHandle);
143 void usage();
144 char* ReadFileData(const char* fileName);
145 void FreeFileData(char* data);
146 void InfoLogMsg(const char* msg, const char* name, const int num);
147
148 // Globally track if any compile or link failure.
149 std::atomic<int8_t> CompileFailed{0};
150 std::atomic<int8_t> LinkFailed{0};
151 std::atomic<int8_t> CompileOrLinkFailed{0};
152
153 // array of unique places to leave the shader names and infologs for the asynchronous compiles
154 std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
155
156 std::string ConfigFile;
157
158 //
159 // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
160 //
ProcessConfigFile()161 void ProcessConfigFile()
162 {
163 if (ConfigFile.size() == 0)
164 *GetResources() = *GetDefaultResources();
165 else {
166 char* configString = ReadFileData(ConfigFile.c_str());
167 DecodeResourceLimits(GetResources(), configString);
168 FreeFileData(configString);
169 }
170 }
171
172 int ReflectOptions = EShReflectionDefault;
173 std::underlying_type_t<TOptions> Options = EOptionNone;
174 const char* ExecutableName = nullptr;
175 const char* binaryFileName = nullptr;
176 const char* depencyFileName = nullptr;
177 const char* entryPointName = nullptr;
178 const char* sourceEntryPointName = nullptr;
179 const char* shaderStageName = nullptr;
180 const char* variableName = nullptr;
181 bool HlslEnable16BitTypes = false;
182 bool HlslDX9compatible = false;
183 bool HlslDxPositionW = false;
184 bool EnhancedMsgs = false;
185 bool DumpBuiltinSymbols = false;
186 std::vector<std::string> IncludeDirectoryList;
187
188 // Source environment
189 // (source 'Client' is currently the same as target 'Client')
190 int ClientInputSemanticsVersion = 100;
191
192 // Target environment
193 glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
194 glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
195 glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
196 glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
197
198 // GLSL version
199 int GlslVersion = 0; // GLSL version specified on CLI, overrides #version in shader source
200
201 std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
202
203 // Per descriptor-set binding base data
204 typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
205
206 std::vector<std::pair<std::string, int>> uniformLocationOverrides;
207 int uniformBase = 0;
208
209 std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
210 std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
211 std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
212
213 std::vector<std::pair<std::string, glslang::TBlockStorageClass>> blockStorageOverrides;
214
215 bool setGlobalUniformBlock = false;
216 std::string globalUniformName;
217 unsigned int globalUniformBinding;
218 unsigned int globalUniformSet;
219
220 bool setGlobalBufferBlock = false;
221 std::string atomicCounterBlockName;
222 unsigned int atomicCounterBlockSet;
223
224 // Add things like "#define ..." to a preamble to use in the beginning of the shader.
225 class TPreamble {
226 public:
TPreamble()227 TPreamble() { }
228
isSet() const229 bool isSet() const { return text.size() > 0; }
get() const230 const char* get() const { return text.c_str(); }
231
232 // #define...
addDef(std::string def)233 void addDef(std::string def)
234 {
235 text.append("#define ");
236 fixLine(def);
237
238 Processes.push_back("define-macro ");
239 Processes.back().append(def);
240
241 // The first "=" needs to turn into a space
242 const size_t equal = def.find_first_of("=");
243 if (equal != def.npos)
244 def[equal] = ' ';
245
246 text.append(def);
247 text.append("\n");
248 }
249
250 // #undef...
addUndef(std::string undef)251 void addUndef(std::string undef)
252 {
253 text.append("#undef ");
254 fixLine(undef);
255
256 Processes.push_back("undef-macro ");
257 Processes.back().append(undef);
258
259 text.append(undef);
260 text.append("\n");
261 }
262
addText(std::string preambleText)263 void addText(std::string preambleText)
264 {
265 fixLine(preambleText);
266
267 Processes.push_back("preamble-text");
268 Processes.back().append(preambleText);
269
270 text.append(preambleText);
271 text.append("\n");
272 }
273
274 protected:
fixLine(std::string & line)275 void fixLine(std::string& line)
276 {
277 // Can't go past a newline in the line
278 const size_t end = line.find_first_of("\n");
279 if (end != line.npos)
280 line = line.substr(0, end);
281 }
282
283 std::string text; // contents of preamble
284 };
285
286 // Track the user's #define and #undef from the command line.
287 TPreamble UserPreamble;
288 std::string PreambleString;
289
290 //
291 // Create the default name for saving a binary if -o is not provided.
292 //
GetBinaryName(EShLanguage stage)293 const char* GetBinaryName(EShLanguage stage)
294 {
295 const char* name;
296 if (binaryFileName == nullptr) {
297 switch (stage) {
298 case EShLangVertex: name = "vert.spv"; break;
299 case EShLangTessControl: name = "tesc.spv"; break;
300 case EShLangTessEvaluation: name = "tese.spv"; break;
301 case EShLangGeometry: name = "geom.spv"; break;
302 case EShLangFragment: name = "frag.spv"; break;
303 case EShLangCompute: name = "comp.spv"; break;
304 case EShLangRayGen: name = "rgen.spv"; break;
305 case EShLangIntersect: name = "rint.spv"; break;
306 case EShLangAnyHit: name = "rahit.spv"; break;
307 case EShLangClosestHit: name = "rchit.spv"; break;
308 case EShLangMiss: name = "rmiss.spv"; break;
309 case EShLangCallable: name = "rcall.spv"; break;
310 case EShLangMesh : name = "mesh.spv"; break;
311 case EShLangTask : name = "task.spv"; break;
312 default: name = "unknown"; break;
313 }
314 } else
315 name = binaryFileName;
316
317 return name;
318 }
319
320 //
321 // *.conf => this is a config file that can set limits/resources
322 //
SetConfigFile(const std::string & name)323 bool SetConfigFile(const std::string& name)
324 {
325 if (name.size() < 5)
326 return false;
327
328 if (name.compare(name.size() - 5, 5, ".conf") == 0) {
329 ConfigFile = name;
330 return true;
331 }
332
333 return false;
334 }
335
336 //
337 // Give error and exit with failure code.
338 //
Error(const char * message,const char * detail=nullptr)339 void Error(const char* message, const char* detail = nullptr)
340 {
341 fprintf(stderr, "%s: Error: ", ExecutableName);
342 if (detail != nullptr)
343 fprintf(stderr, "%s: ", detail);
344 fprintf(stderr, "%s (use -h for usage)\n", message);
345 exit(EFailUsage);
346 }
347
348 //
349 // Process an optional binding base of one the forms:
350 // --argname [stage] base // base for stage (if given) or all stages (if not)
351 // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
352
353 // Where stage is one of the forms accepted by FindLanguage, and base is an integer
354 //
ProcessBindingBase(int & argc,char ** & argv,glslang::TResourceType res)355 void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
356 {
357 if (argc < 2)
358 usage();
359
360 EShLanguage lang = EShLangCount;
361 int singleBase = 0;
362 TPerSetBaseBinding perSetBase;
363 int arg = 1;
364
365 // Parse stage, if given
366 if (!isdigit(argv[arg][0])) {
367 if (argc < 3) // this form needs one more argument
368 usage();
369
370 lang = FindLanguage(argv[arg++], false);
371 }
372
373 if ((argc - arg) >= 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
374 // Parse a per-set binding base
375 do {
376 const int baseNum = atoi(argv[arg++]);
377 const int setNum = atoi(argv[arg++]);
378 perSetBase[setNum] = baseNum;
379 } while ((argc - arg) >= 2 && isdigit(argv[arg + 0][0]) && isdigit(argv[arg + 1][0]));
380 } else {
381 // Parse single binding base
382 singleBase = atoi(argv[arg++]);
383 }
384
385 argc -= (arg-1);
386 argv += (arg-1);
387
388 // Set one or all languages
389 const int langMin = (lang < EShLangCount) ? lang+0 : 0;
390 const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
391
392 for (int lang = langMin; lang < langMax; ++lang) {
393 if (!perSetBase.empty())
394 baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
395 else
396 baseBinding[res][lang] = singleBase;
397 }
398 }
399
ProcessResourceSetBindingBase(int & argc,char ** & argv,std::array<std::vector<std::string>,EShLangCount> & base)400 void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
401 {
402 if (argc < 2)
403 usage();
404
405 if (!isdigit(argv[1][0])) {
406 if (argc < 3) // this form needs one more argument
407 usage();
408
409 // Parse form: --argname stage [regname set base...], or:
410 // --argname stage set
411 const EShLanguage lang = FindLanguage(argv[1], false);
412
413 argc--;
414 argv++;
415
416 while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
417 base[lang].push_back(argv[1]);
418
419 argc--;
420 argv++;
421 }
422
423 // Must have one arg, or a multiple of three (for [regname set binding] triples)
424 if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
425 usage();
426
427 } else {
428 // Parse form: --argname set
429 for (int lang=0; lang<EShLangCount; ++lang)
430 base[lang].push_back(argv[1]);
431
432 argc--;
433 argv++;
434 }
435 }
436
437 //
438 // Process an optional binding base of one the forms:
439 // --argname name {uniform|buffer|push_constant}
ProcessBlockStorage(int & argc,char ** & argv,std::vector<std::pair<std::string,glslang::TBlockStorageClass>> & storage)440 void ProcessBlockStorage(int& argc, char**& argv, std::vector<std::pair<std::string, glslang::TBlockStorageClass>>& storage)
441 {
442 if (argc < 3)
443 usage();
444
445 glslang::TBlockStorageClass blockStorage = glslang::EbsNone;
446
447 std::string strBacking(argv[2]);
448 if (strBacking == "uniform")
449 blockStorage = glslang::EbsUniform;
450 else if (strBacking == "buffer")
451 blockStorage = glslang::EbsStorageBuffer;
452 else if (strBacking == "push_constant")
453 blockStorage = glslang::EbsPushConstant;
454 else {
455 printf("%s: invalid block storage\n", strBacking.c_str());
456 usage();
457 }
458
459 storage.push_back(std::make_pair(std::string(argv[1]), blockStorage));
460
461 argc -= 2;
462 argv += 2;
463 }
464
isNonDigit(char c)465 inline bool isNonDigit(char c) {
466 // a non-digit character valid in a glsl identifier
467 return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
468 }
469
470 // whether string isa valid identifier to be used in glsl
isValidIdentifier(const char * str)471 bool isValidIdentifier(const char* str) {
472 std::string idn(str);
473
474 if (idn.length() == 0) {
475 return false;
476 }
477
478 if (idn.length() >= 3 && idn.substr(0, 3) == "gl_") {
479 // identifiers startin with "gl_" are reserved
480 return false;
481 }
482
483 if (!isNonDigit(idn[0])) {
484 return false;
485 }
486
487 for (unsigned int i = 1; i < idn.length(); ++i) {
488 if (!(isdigit(idn[i]) || isNonDigit(idn[i]))) {
489 return false;
490 }
491 }
492
493 return true;
494 }
495
496 // Process settings for either the global buffer block or global unfirom block
497 // of the form:
498 // --argname name set binding
ProcessGlobalBlockSettings(int & argc,char ** & argv,std::string * name,unsigned int * set,unsigned int * binding)499 void ProcessGlobalBlockSettings(int& argc, char**& argv, std::string* name, unsigned int* set, unsigned int* binding)
500 {
501 if (argc < 4)
502 usage();
503
504 unsigned int curArg = 1;
505
506 assert(name || set || binding);
507
508 if (name) {
509 if (!isValidIdentifier(argv[curArg])) {
510 printf("%s: invalid identifier\n", argv[curArg]);
511 usage();
512 }
513 *name = argv[curArg];
514
515 curArg++;
516 }
517
518 if (set) {
519 errno = 0;
520 int setVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
521 if (errno || setVal < 0) {
522 printf("%s: invalid set\n", argv[curArg]);
523 usage();
524 }
525 *set = setVal;
526
527 curArg++;
528 }
529
530 if (binding) {
531 errno = 0;
532 int bindingVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
533 if (errno || bindingVal < 0) {
534 printf("%s: invalid binding\n", argv[curArg]);
535 usage();
536 }
537 *binding = bindingVal;
538
539 curArg++;
540 }
541
542 argc -= (curArg - 1);
543 argv += (curArg - 1);
544 }
545
546 //
547 // Do all command-line argument parsing. This includes building up the work-items
548 // to be processed later, and saving all the command-line options.
549 //
550 // Does not return (it exits) if command-line is fatally flawed.
551 //
ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>> & workItems,int argc,char * argv[])552 void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
553 {
554 for (int res = 0; res < glslang::EResCount; ++res)
555 baseBinding[res].fill(0);
556
557 ExecutableName = argv[0];
558 workItems.reserve(argc);
559
560 const auto bumpArg = [&]() {
561 if (argc > 0) {
562 argc--;
563 argv++;
564 }
565 };
566
567 // read a string directly attached to a single-letter option
568 const auto getStringOperand = [&](const char* desc) {
569 if (argv[0][2] == 0) {
570 printf("%s must immediately follow option (no spaces)\n", desc);
571 exit(EFailUsage);
572 }
573 return argv[0] + 2;
574 };
575
576 // read a number attached to a single-letter option
577 const auto getAttachedNumber = [&](const char* desc) {
578 int num = atoi(argv[0] + 2);
579 if (num == 0) {
580 printf("%s: expected attached non-0 number\n", desc);
581 exit(EFailUsage);
582 }
583 return num;
584 };
585
586 // minimum needed (without overriding something else) to target Vulkan SPIR-V
587 const auto setVulkanSpv = []() {
588 if (Client == glslang::EShClientNone)
589 ClientVersion = glslang::EShTargetVulkan_1_0;
590 Client = glslang::EShClientVulkan;
591 Options |= EOptionSpv;
592 Options |= EOptionVulkanRules;
593 Options |= EOptionLinkProgram;
594 };
595
596 // minimum needed (without overriding something else) to target OpenGL SPIR-V
597 const auto setOpenGlSpv = []() {
598 if (Client == glslang::EShClientNone)
599 ClientVersion = glslang::EShTargetOpenGL_450;
600 Client = glslang::EShClientOpenGL;
601 Options |= EOptionSpv;
602 Options |= EOptionLinkProgram;
603 // undo a -H default to Vulkan
604 Options &= ~EOptionVulkanRules;
605 };
606
607 const auto getUniformOverride = [getStringOperand]() {
608 const char *arg = getStringOperand("-u<name>:<location>");
609 const char *split = strchr(arg, ':');
610 if (split == nullptr) {
611 printf("%s: missing location\n", arg);
612 exit(EFailUsage);
613 }
614 errno = 0;
615 int location = static_cast<int>(::strtol(split + 1, nullptr, 10));
616 if (errno) {
617 printf("%s: invalid location\n", arg);
618 exit(EFailUsage);
619 }
620 return std::make_pair(std::string(arg, split - arg), location);
621 };
622
623 for (bumpArg(); argc >= 1; bumpArg()) {
624 if (argv[0][0] == '-') {
625 switch (argv[0][1]) {
626 case '-':
627 {
628 std::string lowerword(argv[0]+2);
629 std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
630
631 // handle --word style options
632 if (lowerword == "auto-map-bindings" || // synonyms
633 lowerword == "auto-map-binding" ||
634 lowerword == "amb") {
635 Options |= EOptionAutoMapBindings;
636 } else if (lowerword == "auto-map-locations" || // synonyms
637 lowerword == "aml") {
638 Options |= EOptionAutoMapLocations;
639 } else if (lowerword == "uniform-base") {
640 if (argc <= 1)
641 Error("no <base> provided", lowerword.c_str());
642 uniformBase = static_cast<int>(::strtol(argv[1], nullptr, 10));
643 bumpArg();
644 break;
645 } else if (lowerword == "client") {
646 if (argc > 1) {
647 if (strcmp(argv[1], "vulkan100") == 0)
648 setVulkanSpv();
649 else if (strcmp(argv[1], "opengl100") == 0)
650 setOpenGlSpv();
651 else
652 Error("expects vulkan100 or opengl100", lowerword.c_str());
653 } else
654 Error("expects vulkan100 or opengl100", lowerword.c_str());
655 bumpArg();
656 } else if (lowerword == "define-macro" ||
657 lowerword == "d") {
658 if (argc > 1)
659 UserPreamble.addDef(argv[1]);
660 else
661 Error("expects <name[=def]>", argv[0]);
662 bumpArg();
663 } else if (lowerword == "dump-builtin-symbols") {
664 DumpBuiltinSymbols = true;
665 } else if (lowerword == "entry-point") {
666 entryPointName = argv[1];
667 if (argc <= 1)
668 Error("no <name> provided", lowerword.c_str());
669 bumpArg();
670 } else if (lowerword == "flatten-uniform-arrays" || // synonyms
671 lowerword == "flatten-uniform-array" ||
672 lowerword == "fua") {
673 Options |= EOptionFlattenUniformArrays;
674 } else if (lowerword == "glsl-version") {
675 if (argc > 1) {
676 if (strcmp(argv[1], "100") == 0) {
677 GlslVersion = 100;
678 } else if (strcmp(argv[1], "110") == 0) {
679 GlslVersion = 110;
680 } else if (strcmp(argv[1], "120") == 0) {
681 GlslVersion = 120;
682 } else if (strcmp(argv[1], "130") == 0) {
683 GlslVersion = 130;
684 } else if (strcmp(argv[1], "140") == 0) {
685 GlslVersion = 140;
686 } else if (strcmp(argv[1], "150") == 0) {
687 GlslVersion = 150;
688 } else if (strcmp(argv[1], "300es") == 0) {
689 GlslVersion = 300;
690 } else if (strcmp(argv[1], "310es") == 0) {
691 GlslVersion = 310;
692 } else if (strcmp(argv[1], "320es") == 0) {
693 GlslVersion = 320;
694 } else if (strcmp(argv[1], "330") == 0) {
695 GlslVersion = 330;
696 } else if (strcmp(argv[1], "400") == 0) {
697 GlslVersion = 400;
698 } else if (strcmp(argv[1], "410") == 0) {
699 GlslVersion = 410;
700 } else if (strcmp(argv[1], "420") == 0) {
701 GlslVersion = 420;
702 } else if (strcmp(argv[1], "430") == 0) {
703 GlslVersion = 430;
704 } else if (strcmp(argv[1], "440") == 0) {
705 GlslVersion = 440;
706 } else if (strcmp(argv[1], "450") == 0) {
707 GlslVersion = 450;
708 } else if (strcmp(argv[1], "460") == 0) {
709 GlslVersion = 460;
710 } else
711 Error("--glsl-version expected one of: 100, 110, 120, 130, 140, 150,\n"
712 "300es, 310es, 320es, 330\n"
713 "400, 410, 420, 430, 440, 450, 460");
714 }
715 bumpArg();
716 } else if (lowerword == "hlsl-offsets") {
717 Options |= EOptionHlslOffsets;
718 } else if (lowerword == "hlsl-iomap" ||
719 lowerword == "hlsl-iomapper" ||
720 lowerword == "hlsl-iomapping") {
721 Options |= EOptionHlslIoMapping;
722 } else if (lowerword == "hlsl-enable-16bit-types") {
723 HlslEnable16BitTypes = true;
724 } else if (lowerword == "hlsl-dx9-compatible") {
725 HlslDX9compatible = true;
726 } else if (lowerword == "hlsl-dx-position-w") {
727 HlslDxPositionW = true;
728 } else if (lowerword == "enhanced-msgs") {
729 EnhancedMsgs = true;
730 } else if (lowerword == "auto-sampled-textures") {
731 autoSampledTextures = true;
732 } else if (lowerword == "invert-y" || // synonyms
733 lowerword == "iy") {
734 Options |= EOptionInvertY;
735 } else if (lowerword == "keep-uncalled" || // synonyms
736 lowerword == "ku") {
737 Options |= EOptionKeepUncalled;
738 } else if (lowerword == "nan-clamp") {
739 NaNClamp = true;
740 } else if (lowerword == "no-storage-format" || // synonyms
741 lowerword == "nsf") {
742 Options |= EOptionNoStorageFormat;
743 } else if (lowerword == "preamble-text" ||
744 lowerword == "p") {
745 if (argc > 1)
746 UserPreamble.addText(argv[1]);
747 else
748 Error("expects <text>", argv[0]);
749 bumpArg();
750 } else if (lowerword == "relaxed-errors") {
751 Options |= EOptionRelaxedErrors;
752 } else if (lowerword == "reflect-strict-array-suffix") {
753 ReflectOptions |= EShReflectionStrictArraySuffix;
754 } else if (lowerword == "reflect-basic-array-suffix") {
755 ReflectOptions |= EShReflectionBasicArraySuffix;
756 } else if (lowerword == "reflect-intermediate-io") {
757 ReflectOptions |= EShReflectionIntermediateIO;
758 } else if (lowerword == "reflect-separate-buffers") {
759 ReflectOptions |= EShReflectionSeparateBuffers;
760 } else if (lowerword == "reflect-all-block-variables") {
761 ReflectOptions |= EShReflectionAllBlockVariables;
762 } else if (lowerword == "reflect-unwrap-io-blocks") {
763 ReflectOptions |= EShReflectionUnwrapIOBlocks;
764 } else if (lowerword == "reflect-all-io-variables") {
765 ReflectOptions |= EShReflectionAllIOVariables;
766 } else if (lowerword == "reflect-shared-std140-ubo") {
767 ReflectOptions |= EShReflectionSharedStd140UBO;
768 } else if (lowerword == "reflect-shared-std140-ssbo") {
769 ReflectOptions |= EShReflectionSharedStd140SSBO;
770 } else if (lowerword == "resource-set-bindings" || // synonyms
771 lowerword == "resource-set-binding" ||
772 lowerword == "rsb") {
773 ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
774 } else if (lowerword == "set-block-storage" ||
775 lowerword == "sbs") {
776 ProcessBlockStorage(argc, argv, blockStorageOverrides);
777 } else if (lowerword == "set-atomic-counter-block" ||
778 lowerword == "sacb") {
779 ProcessGlobalBlockSettings(argc, argv, &atomicCounterBlockName, &atomicCounterBlockSet, nullptr);
780 setGlobalBufferBlock = true;
781 } else if (lowerword == "set-default-uniform-block" ||
782 lowerword == "sdub") {
783 ProcessGlobalBlockSettings(argc, argv, &globalUniformName, &globalUniformSet, &globalUniformBinding);
784 setGlobalUniformBlock = true;
785 } else if (lowerword == "shift-image-bindings" || // synonyms
786 lowerword == "shift-image-binding" ||
787 lowerword == "sib") {
788 ProcessBindingBase(argc, argv, glslang::EResImage);
789 } else if (lowerword == "shift-sampler-bindings" || // synonyms
790 lowerword == "shift-sampler-binding" ||
791 lowerword == "ssb") {
792 ProcessBindingBase(argc, argv, glslang::EResSampler);
793 } else if (lowerword == "shift-uav-bindings" || // synonyms
794 lowerword == "shift-uav-binding" ||
795 lowerword == "suavb") {
796 ProcessBindingBase(argc, argv, glslang::EResUav);
797 } else if (lowerword == "shift-texture-bindings" || // synonyms
798 lowerword == "shift-texture-binding" ||
799 lowerword == "stb") {
800 ProcessBindingBase(argc, argv, glslang::EResTexture);
801 } else if (lowerword == "shift-ubo-bindings" || // synonyms
802 lowerword == "shift-ubo-binding" ||
803 lowerword == "shift-cbuffer-bindings" ||
804 lowerword == "shift-cbuffer-binding" ||
805 lowerword == "sub" ||
806 lowerword == "scb") {
807 ProcessBindingBase(argc, argv, glslang::EResUbo);
808 } else if (lowerword == "shift-ssbo-bindings" || // synonyms
809 lowerword == "shift-ssbo-binding" ||
810 lowerword == "sbb") {
811 ProcessBindingBase(argc, argv, glslang::EResSsbo);
812 } else if (lowerword == "source-entrypoint" || // synonyms
813 lowerword == "sep") {
814 if (argc <= 1)
815 Error("no <entry-point> provided", lowerword.c_str());
816 sourceEntryPointName = argv[1];
817 bumpArg();
818 break;
819 } else if (lowerword == "spirv-dis") {
820 SpvToolsDisassembler = true;
821 } else if (lowerword == "spirv-val") {
822 SpvToolsValidate = true;
823 } else if (lowerword == "stdin") {
824 Options |= EOptionStdin;
825 shaderStageName = argv[1];
826 } else if (lowerword == "suppress-warnings") {
827 Options |= EOptionSuppressWarnings;
828 } else if (lowerword == "target-env") {
829 if (argc > 1) {
830 if (strcmp(argv[1], "vulkan1.0") == 0) {
831 setVulkanSpv();
832 ClientVersion = glslang::EShTargetVulkan_1_0;
833 } else if (strcmp(argv[1], "vulkan1.1") == 0) {
834 setVulkanSpv();
835 ClientVersion = glslang::EShTargetVulkan_1_1;
836 } else if (strcmp(argv[1], "vulkan1.2") == 0) {
837 setVulkanSpv();
838 ClientVersion = glslang::EShTargetVulkan_1_2;
839 } else if (strcmp(argv[1], "vulkan1.3") == 0) {
840 setVulkanSpv();
841 ClientVersion = glslang::EShTargetVulkan_1_3;
842 } else if (strcmp(argv[1], "opengl") == 0) {
843 setOpenGlSpv();
844 ClientVersion = glslang::EShTargetOpenGL_450;
845 } else if (strcmp(argv[1], "spirv1.0") == 0) {
846 TargetLanguage = glslang::EShTargetSpv;
847 TargetVersion = glslang::EShTargetSpv_1_0;
848 } else if (strcmp(argv[1], "spirv1.1") == 0) {
849 TargetLanguage = glslang::EShTargetSpv;
850 TargetVersion = glslang::EShTargetSpv_1_1;
851 } else if (strcmp(argv[1], "spirv1.2") == 0) {
852 TargetLanguage = glslang::EShTargetSpv;
853 TargetVersion = glslang::EShTargetSpv_1_2;
854 } else if (strcmp(argv[1], "spirv1.3") == 0) {
855 TargetLanguage = glslang::EShTargetSpv;
856 TargetVersion = glslang::EShTargetSpv_1_3;
857 } else if (strcmp(argv[1], "spirv1.4") == 0) {
858 TargetLanguage = glslang::EShTargetSpv;
859 TargetVersion = glslang::EShTargetSpv_1_4;
860 } else if (strcmp(argv[1], "spirv1.5") == 0) {
861 TargetLanguage = glslang::EShTargetSpv;
862 TargetVersion = glslang::EShTargetSpv_1_5;
863 } else if (strcmp(argv[1], "spirv1.6") == 0) {
864 TargetLanguage = glslang::EShTargetSpv;
865 TargetVersion = glslang::EShTargetSpv_1_6;
866 } else
867 Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2,\n"
868 "vulkan1.3, opengl, spirv1.0, spirv1.1, spirv1.2, spirv1.3,\n"
869 "spirv1.4, spirv1.5 or spirv1.6");
870 }
871 bumpArg();
872 } else if (lowerword == "undef-macro" ||
873 lowerword == "u") {
874 if (argc > 1)
875 UserPreamble.addUndef(argv[1]);
876 else
877 Error("expects <name>", argv[0]);
878 bumpArg();
879 } else if (lowerword == "variable-name" || // synonyms
880 lowerword == "vn") {
881 Options |= EOptionOutputHexadecimal;
882 if (argc <= 1)
883 Error("no <C-variable-name> provided", lowerword.c_str());
884 variableName = argv[1];
885 bumpArg();
886 break;
887 } else if (lowerword == "quiet") {
888 beQuiet = true;
889 } else if (lowerword == "depfile") {
890 if (argc <= 1)
891 Error("no <depfile-name> provided", lowerword.c_str());
892 depencyFileName = argv[1];
893 bumpArg();
894 } else if (lowerword == "version") {
895 Options |= EOptionDumpVersions;
896 } else if (lowerword == "no-link") {
897 Options |= EOptionCompileOnly;
898 } else if (lowerword == "help") {
899 usage();
900 break;
901 } else {
902 Error("unrecognized command-line option", argv[0]);
903 }
904 }
905 break;
906 case 'C':
907 Options |= EOptionCascadingErrors;
908 break;
909 case 'D':
910 if (argv[0][2] == 0)
911 Options |= EOptionReadHlsl;
912 else
913 UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
914 break;
915 case 'u':
916 uniformLocationOverrides.push_back(getUniformOverride());
917 break;
918 case 'E':
919 Options |= EOptionOutputPreprocessed;
920 break;
921 case 'G':
922 // OpenGL client
923 setOpenGlSpv();
924 if (argv[0][2] != 0)
925 ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
926 if (ClientInputSemanticsVersion != 100)
927 Error("unknown client version for -G, should be 100");
928 break;
929 case 'H':
930 Options |= EOptionHumanReadableSpv;
931 if ((Options & EOptionSpv) == 0) {
932 // default to Vulkan
933 setVulkanSpv();
934 }
935 break;
936 case 'I':
937 IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
938 break;
939 case 'O':
940 if (argv[0][2] == 'd')
941 Options |= EOptionOptimizeDisable;
942 else if (argv[0][2] == 's')
943 #if ENABLE_OPT
944 Options |= EOptionOptimizeSize;
945 #else
946 Error("-Os not available; optimizer not linked");
947 #endif
948 else
949 Error("unknown -O option");
950 break;
951 case 'P':
952 UserPreamble.addText(getStringOperand("-P<text>"));
953 break;
954 case 'R':
955 VulkanRulesRelaxed = true;
956 break;
957 case 'S':
958 if (argc <= 1)
959 Error("no <stage> specified for -S");
960 shaderStageName = argv[1];
961 bumpArg();
962 break;
963 case 'U':
964 UserPreamble.addUndef(getStringOperand("-U<name>"));
965 break;
966 case 'V':
967 setVulkanSpv();
968 if (argv[0][2] != 0)
969 ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
970 if (ClientInputSemanticsVersion != 100)
971 Error("unknown client version for -V, should be 100");
972 break;
973 case 'c':
974 Options |= EOptionDumpConfig;
975 break;
976 case 'd':
977 if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
978 strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
979 Options |= EOptionDumpBareVersion;
980 else
981 Options |= EOptionDefaultDesktop;
982 break;
983 case 'e':
984 entryPointName = argv[1];
985 if (argc <= 1)
986 Error("no <name> provided for -e");
987 bumpArg();
988 break;
989 case 'f':
990 if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
991 targetHlslFunctionality1 = true;
992 else
993 Error("-f: expected hlsl_functionality1");
994 break;
995 case 'g':
996 // Override previous -g or -g0 argument
997 stripDebugInfo = false;
998 emitNonSemanticShaderDebugInfo = false;
999 Options &= ~EOptionDebug;
1000 if (argv[0][2] == '0')
1001 stripDebugInfo = true;
1002 else {
1003 Options |= EOptionDebug;
1004 if (argv[0][2] == 'V') {
1005 emitNonSemanticShaderDebugInfo = true;
1006 if (argv[0][3] == 'S') {
1007 emitNonSemanticShaderDebugSource = true;
1008 } else {
1009 emitNonSemanticShaderDebugSource = false;
1010 }
1011 }
1012 }
1013 break;
1014 case 'h':
1015 usage();
1016 break;
1017 case 'i':
1018 Options |= EOptionIntermediate;
1019 break;
1020 case 'l':
1021 Options |= EOptionLinkProgram;
1022 break;
1023 case 'm':
1024 Options |= EOptionMemoryLeakMode;
1025 break;
1026 case 'o':
1027 if (argc <= 1)
1028 Error("no <file> provided for -o");
1029 binaryFileName = argv[1];
1030 bumpArg();
1031 break;
1032 case 'q':
1033 Options |= EOptionDumpReflection;
1034 break;
1035 case 'r':
1036 Options |= EOptionRelaxedErrors;
1037 break;
1038 case 's':
1039 Options |= EOptionSuppressInfolog;
1040 break;
1041 case 't':
1042 Options |= EOptionMultiThreaded;
1043 break;
1044 case 'v':
1045 Options |= EOptionDumpVersions;
1046 break;
1047 case 'w':
1048 Options |= EOptionSuppressWarnings;
1049 break;
1050 case 'x':
1051 Options |= EOptionOutputHexadecimal;
1052 break;
1053 default:
1054 Error("unrecognized command-line option", argv[0]);
1055 break;
1056 }
1057 } else {
1058 std::string name(argv[0]);
1059 if (! SetConfigFile(name)) {
1060 workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
1061 }
1062 }
1063 }
1064
1065 // Make sure that -S is always specified if --stdin is specified
1066 if ((Options & EOptionStdin) && shaderStageName == nullptr)
1067 Error("must provide -S when --stdin is given");
1068
1069 // Make sure that -E is not specified alongside linking (which includes SPV generation)
1070 // Or things that require linking
1071 if (Options & EOptionOutputPreprocessed) {
1072 if (Options & EOptionLinkProgram)
1073 Error("can't use -E when linking is selected");
1074 if (Options & EOptionDumpReflection)
1075 Error("reflection requires linking, which can't be used when -E when is selected");
1076 }
1077
1078 // reflection requires linking
1079 if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
1080 Error("reflection requires -l for linking");
1081
1082 // -o or -x makes no sense if there is no target binary
1083 if (binaryFileName && (Options & EOptionSpv) == 0)
1084 Error("no binary generation requested (e.g., -V)");
1085
1086 if ((Options & EOptionFlattenUniformArrays) != 0 &&
1087 (Options & EOptionReadHlsl) == 0)
1088 Error("uniform array flattening only valid when compiling HLSL source.");
1089
1090 if ((Options & EOptionReadHlsl) && (Client == glslang::EShClientOpenGL)) {
1091 Error("Using HLSL input under OpenGL semantics is not currently supported.");
1092 }
1093
1094 // rationalize client and target language
1095 if (TargetLanguage == glslang::EShTargetNone) {
1096 switch (ClientVersion) {
1097 case glslang::EShTargetVulkan_1_0:
1098 TargetLanguage = glslang::EShTargetSpv;
1099 TargetVersion = glslang::EShTargetSpv_1_0;
1100 break;
1101 case glslang::EShTargetVulkan_1_1:
1102 TargetLanguage = glslang::EShTargetSpv;
1103 TargetVersion = glslang::EShTargetSpv_1_3;
1104 break;
1105 case glslang::EShTargetVulkan_1_2:
1106 TargetLanguage = glslang::EShTargetSpv;
1107 TargetVersion = glslang::EShTargetSpv_1_5;
1108 break;
1109 case glslang::EShTargetVulkan_1_3:
1110 TargetLanguage = glslang::EShTargetSpv;
1111 TargetVersion = glslang::EShTargetSpv_1_6;
1112 break;
1113 case glslang::EShTargetOpenGL_450:
1114 TargetLanguage = glslang::EShTargetSpv;
1115 TargetVersion = glslang::EShTargetSpv_1_0;
1116 break;
1117 default:
1118 break;
1119 }
1120 }
1121 if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
1122 Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
1123 }
1124
1125 //
1126 // Translate the meaningful subset of command-line options to parser-behavior options.
1127 //
SetMessageOptions(EShMessages & messages)1128 void SetMessageOptions(EShMessages& messages)
1129 {
1130 if (Options & EOptionRelaxedErrors)
1131 messages = (EShMessages)(messages | EShMsgRelaxedErrors);
1132 if (Options & EOptionIntermediate)
1133 messages = (EShMessages)(messages | EShMsgAST);
1134 if (Options & EOptionSuppressWarnings)
1135 messages = (EShMessages)(messages | EShMsgSuppressWarnings);
1136 if (Options & EOptionSpv)
1137 messages = (EShMessages)(messages | EShMsgSpvRules);
1138 if (Options & EOptionVulkanRules)
1139 messages = (EShMessages)(messages | EShMsgVulkanRules);
1140 if (Options & EOptionOutputPreprocessed)
1141 messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
1142 if (Options & EOptionReadHlsl)
1143 messages = (EShMessages)(messages | EShMsgReadHlsl);
1144 if (Options & EOptionCascadingErrors)
1145 messages = (EShMessages)(messages | EShMsgCascadingErrors);
1146 if (Options & EOptionKeepUncalled)
1147 messages = (EShMessages)(messages | EShMsgKeepUncalled);
1148 if (Options & EOptionHlslOffsets)
1149 messages = (EShMessages)(messages | EShMsgHlslOffsets);
1150 if (Options & EOptionDebug)
1151 messages = (EShMessages)(messages | EShMsgDebugInfo);
1152 if (HlslEnable16BitTypes)
1153 messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
1154 if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
1155 messages = (EShMessages)(messages | EShMsgHlslLegalization);
1156 if (HlslDX9compatible)
1157 messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
1158 if (DumpBuiltinSymbols)
1159 messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
1160 if (EnhancedMsgs)
1161 messages = (EShMessages)(messages | EShMsgEnhanced);
1162 }
1163
1164 //
1165 // Thread entry point, for non-linking asynchronous mode.
1166 //
CompileShaders(glslang::TWorklist & worklist)1167 void CompileShaders(glslang::TWorklist& worklist)
1168 {
1169 if (Options & EOptionDebug)
1170 Error("cannot generate debug information unless linking to generate code");
1171
1172 // NOTE: TWorkList::remove is thread-safe
1173 glslang::TWorkItem* workItem;
1174 if (Options & EOptionStdin) {
1175 if (worklist.remove(workItem)) {
1176 ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), 0);
1177 if (compiler == nullptr)
1178 return;
1179
1180 CompileFile("stdin", compiler);
1181
1182 if (! (Options & EOptionSuppressInfolog))
1183 workItem->results = ShGetInfoLog(compiler);
1184
1185 ShDestruct(compiler);
1186 }
1187 } else {
1188 while (worklist.remove(workItem)) {
1189 ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), 0);
1190 if (compiler == nullptr)
1191 return;
1192
1193 CompileFile(workItem->name.c_str(), compiler);
1194
1195 if (! (Options & EOptionSuppressInfolog))
1196 workItem->results = ShGetInfoLog(compiler);
1197
1198 ShDestruct(compiler);
1199 }
1200 }
1201 }
1202
1203 // Outputs the given string, but only if it is non-null and non-empty.
1204 // This prevents erroneous newlines from appearing.
PutsIfNonEmpty(const char * str)1205 void PutsIfNonEmpty(const char* str)
1206 {
1207 if (str && str[0]) {
1208 puts(str);
1209 }
1210 }
1211
1212 // Outputs the given string to stderr, but only if it is non-null and non-empty.
1213 // This prevents erroneous newlines from appearing.
StderrIfNonEmpty(const char * str)1214 void StderrIfNonEmpty(const char* str)
1215 {
1216 if (str && str[0])
1217 fprintf(stderr, "%s\n", str);
1218 }
1219
1220 // Simple bundling of what makes a compilation unit for ease in passing around,
1221 // and separation of handling file IO versus API (programmatic) compilation.
1222 struct ShaderCompUnit {
1223 EShLanguage stage;
1224 static const int maxCount = 1;
1225 int count; // live number of strings/names
1226 const char* text[maxCount]; // memory owned/managed externally
1227 std::string fileName[maxCount]; // hold's the memory, but...
1228 const char* fileNameList[maxCount]; // downstream interface wants pointers
1229
ShaderCompUnitShaderCompUnit1230 ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
1231
ShaderCompUnitShaderCompUnit1232 ShaderCompUnit(const ShaderCompUnit& rhs)
1233 {
1234 stage = rhs.stage;
1235 count = rhs.count;
1236 for (int i = 0; i < count; ++i) {
1237 fileName[i] = rhs.fileName[i];
1238 text[i] = rhs.text[i];
1239 fileNameList[i] = rhs.fileName[i].c_str();
1240 }
1241 }
1242
addStringShaderCompUnit1243 void addString(std::string& ifileName, const char* itext)
1244 {
1245 assert(count < maxCount);
1246 fileName[count] = ifileName;
1247 text[count] = itext;
1248 fileNameList[count] = fileName[count].c_str();
1249 ++count;
1250 }
1251 };
1252
1253 // Writes a string into a depfile, escaping some special characters following the Makefile rules.
writeEscapedDepString(std::ofstream & file,const std::string & str)1254 static void writeEscapedDepString(std::ofstream& file, const std::string& str)
1255 {
1256 for (char c : str) {
1257 switch (c) {
1258 case ' ':
1259 case ':':
1260 case '#':
1261 case '[':
1262 case ']':
1263 case '\\':
1264 file << '\\';
1265 break;
1266 case '$':
1267 file << '$';
1268 break;
1269 }
1270 file << c;
1271 }
1272 }
1273
1274 // Writes a depfile similar to gcc -MMD foo.c
writeDepFile(std::string depfile,std::vector<std::string> & binaryFiles,const std::vector<std::string> & sources)1275 bool writeDepFile(std::string depfile, std::vector<std::string>& binaryFiles, const std::vector<std::string>& sources)
1276 {
1277 std::ofstream file(depfile);
1278 if (file.fail())
1279 return false;
1280
1281 for (auto binaryFile = binaryFiles.begin(); binaryFile != binaryFiles.end(); binaryFile++) {
1282 writeEscapedDepString(file, *binaryFile);
1283 file << ":";
1284 for (auto sourceFile = sources.begin(); sourceFile != sources.end(); sourceFile++) {
1285 file << " ";
1286 writeEscapedDepString(file, *sourceFile);
1287 }
1288 file << std::endl;
1289 }
1290 return true;
1291 }
1292
1293 //
1294 // For linking mode: Will independently parse each compilation unit, but then put them
1295 // in the same program and link them together, making at most one linked module per
1296 // pipeline stage.
1297 //
1298 // Uses the new C++ interface instead of the old handle-based interface.
1299 //
1300
CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)1301 void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
1302 {
1303 // keep track of what to free
1304 std::list<glslang::TShader*> shaders;
1305
1306 EShMessages messages = EShMsgDefault;
1307 SetMessageOptions(messages);
1308
1309 DirStackFileIncluder includer;
1310 std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
1311 includer.pushExternalLocalDirectory(dir); });
1312
1313 std::vector<std::string> sources;
1314
1315 //
1316 // Per-shader processing...
1317 //
1318
1319 glslang::TProgram& program = *new glslang::TProgram;
1320 const bool compileOnly = (Options & EOptionCompileOnly) != 0;
1321 for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
1322 const auto &compUnit = *it;
1323 for (int i = 0; i < compUnit.count; i++) {
1324 sources.push_back(compUnit.fileNameList[i]);
1325 }
1326 glslang::TShader* shader = new glslang::TShader(compUnit.stage);
1327 shader->setStringsWithLengthsAndNames(compUnit.text, nullptr, compUnit.fileNameList, compUnit.count);
1328 if (entryPointName)
1329 shader->setEntryPoint(entryPointName);
1330 if (sourceEntryPointName) {
1331 if (entryPointName == nullptr)
1332 printf("Warning: Changing source entry point name without setting an entry-point name.\n"
1333 "Use '-e <name>'.\n");
1334 shader->setSourceEntryPoint(sourceEntryPointName);
1335 }
1336
1337 if (compileOnly)
1338 shader->setCompileOnly();
1339
1340 shader->setOverrideVersion(GlslVersion);
1341
1342 std::string intrinsicString = getIntrinsic(compUnit.text, compUnit.count);
1343
1344 PreambleString = "";
1345 if (UserPreamble.isSet())
1346 PreambleString.append(UserPreamble.get());
1347
1348 if (!intrinsicString.empty())
1349 PreambleString.append(intrinsicString);
1350
1351 shader->setPreamble(PreambleString.c_str());
1352 shader->addProcesses(Processes);
1353
1354 // Set IO mapper binding shift values
1355 for (int r = 0; r < glslang::EResCount; ++r) {
1356 const glslang::TResourceType res = glslang::TResourceType(r);
1357
1358 // Set base bindings
1359 shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
1360
1361 // Set bindings for particular resource sets
1362 // TODO: use a range based for loop here, when available in all environments.
1363 for (auto i = baseBindingForSet[res][compUnit.stage].begin();
1364 i != baseBindingForSet[res][compUnit.stage].end(); ++i)
1365 shader->setShiftBindingForSet(res, i->second, i->first);
1366 }
1367 shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
1368 shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
1369
1370 if (autoSampledTextures)
1371 shader->setTextureSamplerTransformMode(EShTexSampTransUpgradeTextureRemoveSampler);
1372
1373 if (Options & EOptionAutoMapBindings)
1374 shader->setAutoMapBindings(true);
1375
1376 if (Options & EOptionAutoMapLocations)
1377 shader->setAutoMapLocations(true);
1378
1379 for (auto& uniOverride : uniformLocationOverrides) {
1380 shader->addUniformLocationOverride(uniOverride.first.c_str(),
1381 uniOverride.second);
1382 }
1383
1384 shader->setUniformLocationBase(uniformBase);
1385
1386 if (VulkanRulesRelaxed) {
1387 for (auto& storageOverride : blockStorageOverrides) {
1388 shader->addBlockStorageOverride(storageOverride.first.c_str(),
1389 storageOverride.second);
1390 }
1391
1392 if (setGlobalBufferBlock) {
1393 shader->setAtomicCounterBlockName(atomicCounterBlockName.c_str());
1394 shader->setAtomicCounterBlockSet(atomicCounterBlockSet);
1395 }
1396
1397 if (setGlobalUniformBlock) {
1398 shader->setGlobalUniformBlockName(globalUniformName.c_str());
1399 shader->setGlobalUniformSet(globalUniformSet);
1400 shader->setGlobalUniformBinding(globalUniformBinding);
1401 }
1402 }
1403
1404 shader->setNanMinMaxClamp(NaNClamp);
1405
1406 #ifdef ENABLE_HLSL
1407 shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
1408 if (Options & EOptionHlslIoMapping)
1409 shader->setHlslIoMapping(true);
1410 #endif
1411
1412 if (Options & EOptionInvertY)
1413 shader->setInvertY(true);
1414
1415 if (HlslDxPositionW)
1416 shader->setDxPositionW(true);
1417
1418 if (EnhancedMsgs)
1419 shader->setEnhancedMsgs();
1420
1421 if (emitNonSemanticShaderDebugInfo)
1422 shader->setDebugInfo(true);
1423
1424 // Set up the environment, some subsettings take precedence over earlier
1425 // ways of setting things.
1426 if (Options & EOptionSpv) {
1427 shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
1428 : glslang::EShSourceGlsl,
1429 compUnit.stage, Client, ClientInputSemanticsVersion);
1430 shader->setEnvClient(Client, ClientVersion);
1431 shader->setEnvTarget(TargetLanguage, TargetVersion);
1432 #ifdef ENABLE_HLSL
1433 if (targetHlslFunctionality1)
1434 shader->setEnvTargetHlslFunctionality1();
1435 #endif
1436 if (VulkanRulesRelaxed)
1437 shader->setEnvInputVulkanRulesRelaxed();
1438 }
1439
1440 shaders.push_back(shader);
1441
1442 const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
1443
1444 if (Options & EOptionOutputPreprocessed) {
1445 std::string str;
1446 if (shader->preprocess(GetResources(), defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
1447 PutsIfNonEmpty(str.c_str());
1448 } else {
1449 CompileFailed = 1;
1450 }
1451 StderrIfNonEmpty(shader->getInfoLog());
1452 StderrIfNonEmpty(shader->getInfoDebugLog());
1453 continue;
1454 }
1455
1456 if (! shader->parse(GetResources(), defaultVersion, false, messages, includer))
1457 CompileFailed = 1;
1458
1459 if (!compileOnly)
1460 program.addShader(shader);
1461
1462 if (! (Options & EOptionSuppressInfolog) &&
1463 ! (Options & EOptionMemoryLeakMode)) {
1464 if (!beQuiet)
1465 PutsIfNonEmpty(compUnit.fileName[0].c_str());
1466 PutsIfNonEmpty(shader->getInfoLog());
1467 PutsIfNonEmpty(shader->getInfoDebugLog());
1468 }
1469 }
1470
1471 //
1472 // Program-level processing...
1473 //
1474
1475 if (!compileOnly) {
1476 // Link
1477 if (!(Options & EOptionOutputPreprocessed) && !program.link(messages))
1478 LinkFailed = true;
1479
1480 // Map IO
1481 if (Options & EOptionSpv) {
1482 if (!program.mapIO())
1483 LinkFailed = true;
1484 }
1485
1486 // Report
1487 if (!(Options & EOptionSuppressInfolog) && !(Options & EOptionMemoryLeakMode)) {
1488 PutsIfNonEmpty(program.getInfoLog());
1489 PutsIfNonEmpty(program.getInfoDebugLog());
1490 }
1491
1492 // Reflect
1493 if (Options & EOptionDumpReflection) {
1494 program.buildReflection(ReflectOptions);
1495 program.dumpReflection();
1496 }
1497 }
1498
1499 std::vector<std::string> outputFiles;
1500
1501 // Dump SPIR-V
1502 if (Options & EOptionSpv) {
1503 CompileOrLinkFailed.fetch_or(CompileFailed);
1504 CompileOrLinkFailed.fetch_or(LinkFailed);
1505 if (static_cast<bool>(CompileOrLinkFailed.load()))
1506 printf("SPIR-V is not generated for failed compile or link\n");
1507 else {
1508 std::vector<glslang::TIntermediate*> intermediates;
1509 if (!compileOnly) {
1510 for (int stage = 0; stage < EShLangCount; ++stage) {
1511 if (auto* i = program.getIntermediate((EShLanguage)stage)) {
1512 intermediates.emplace_back(i);
1513 }
1514 }
1515 } else {
1516 for (const auto* shader : shaders) {
1517 if (auto* i = shader->getIntermediate()) {
1518 intermediates.emplace_back(i);
1519 }
1520 }
1521 }
1522 for (auto* intermediate : intermediates) {
1523 std::vector<unsigned int> spirv;
1524 spv::SpvBuildLogger logger;
1525 glslang::SpvOptions spvOptions;
1526 if (Options & EOptionDebug) {
1527 spvOptions.generateDebugInfo = true;
1528 if (emitNonSemanticShaderDebugInfo) {
1529 spvOptions.emitNonSemanticShaderDebugInfo = true;
1530 if (emitNonSemanticShaderDebugSource) {
1531 spvOptions.emitNonSemanticShaderDebugSource = true;
1532 }
1533 }
1534 } else if (stripDebugInfo)
1535 spvOptions.stripDebugInfo = true;
1536 spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
1537 spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
1538 spvOptions.disassemble = SpvToolsDisassembler;
1539 spvOptions.validate = SpvToolsValidate;
1540 spvOptions.compileOnly = compileOnly;
1541 glslang::GlslangToSpv(*intermediate, spirv, &logger, &spvOptions);
1542
1543 // Dump the spv to a file or stdout, etc., but only if not doing
1544 // memory/perf testing, as it's not internal to programmatic use.
1545 if (!(Options & EOptionMemoryLeakMode)) {
1546 printf("%s", logger.getAllMessages().c_str());
1547 const auto filename = GetBinaryName(intermediate->getStage());
1548 if (Options & EOptionOutputHexadecimal) {
1549 if (!glslang::OutputSpvHex(spirv, filename, variableName))
1550 exit(EFailUsage);
1551 } else {
1552 if (!glslang::OutputSpvBin(spirv, filename))
1553 exit(EFailUsage);
1554 }
1555
1556 outputFiles.push_back(filename);
1557 if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
1558 spv::Disassemble(std::cout, spirv);
1559 }
1560 }
1561 }
1562 }
1563
1564 CompileOrLinkFailed.fetch_or(CompileFailed);
1565 CompileOrLinkFailed.fetch_or(LinkFailed);
1566 if (depencyFileName && !static_cast<bool>(CompileOrLinkFailed.load())) {
1567 std::set<std::string> includedFiles = includer.getIncludedFiles();
1568 sources.insert(sources.end(), includedFiles.begin(), includedFiles.end());
1569
1570 writeDepFile(depencyFileName, outputFiles, sources);
1571 }
1572
1573 // Free everything up, program has to go before the shaders
1574 // because it might have merged stuff from the shaders, and
1575 // the stuff from the shaders has to have its destructors called
1576 // before the pools holding the memory in the shaders is freed.
1577 delete &program;
1578 while (shaders.size() > 0) {
1579 delete shaders.back();
1580 shaders.pop_back();
1581 }
1582 }
1583
1584 //
1585 // Do file IO part of compile and link, handing off the pure
1586 // API/programmatic mode to CompileAndLinkShaderUnits(), which can
1587 // be put in a loop for testing memory footprint and performance.
1588 //
1589 // This is just for linking mode: meaning all the shaders will be put into the
1590 // the same program linked together.
1591 //
1592 // This means there are a limited number of work items (not multi-threading mode)
1593 // and that the point is testing at the linking level. Hence, to enable
1594 // performance and memory testing, the actual compile/link can be put in
1595 // a loop, independent of processing the work items and file IO.
1596 //
CompileAndLinkShaderFiles(glslang::TWorklist & Worklist)1597 void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
1598 {
1599 std::vector<ShaderCompUnit> compUnits;
1600
1601 // If this is using stdin, we can't really detect multiple different file
1602 // units by input type. We need to assume that we're just being given one
1603 // file of a certain type.
1604 if ((Options & EOptionStdin) != 0) {
1605 ShaderCompUnit compUnit(FindLanguage("stdin"));
1606 std::istreambuf_iterator<char> begin(std::cin), end;
1607 std::string tempString(begin, end);
1608 char* fileText = strdup(tempString.c_str());
1609 std::string fileName = "stdin";
1610 compUnit.addString(fileName, fileText);
1611 compUnits.push_back(compUnit);
1612 } else {
1613 // Transfer all the work items from to a simple list of
1614 // of compilation units. (We don't care about the thread
1615 // work-item distribution properties in this path, which
1616 // is okay due to the limited number of shaders, know since
1617 // they are all getting linked together.)
1618 glslang::TWorkItem* workItem;
1619 while (Worklist.remove(workItem)) {
1620 ShaderCompUnit compUnit(FindLanguage(workItem->name));
1621 char* fileText = ReadFileData(workItem->name.c_str());
1622 if (fileText == nullptr)
1623 usage();
1624 compUnit.addString(workItem->name, fileText);
1625 compUnits.push_back(compUnit);
1626 }
1627 }
1628
1629 // Actual call to programmatic processing of compile and link,
1630 // in a loop for testing memory and performance. This part contains
1631 // all the perf/memory that a programmatic consumer will care about.
1632 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1633 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
1634 CompileAndLinkShaderUnits(compUnits);
1635
1636 if (Options & EOptionMemoryLeakMode)
1637 glslang::OS_DumpMemoryCounters();
1638 }
1639
1640 // free memory from ReadFileData, which got stored in a const char*
1641 // as the first string above
1642 for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
1643 FreeFileData(const_cast<char*>(it->text[0]));
1644 }
1645
singleMain()1646 int singleMain()
1647 {
1648 glslang::TWorklist workList;
1649 std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
1650 assert(item);
1651 workList.add(item.get());
1652 });
1653
1654 if (Options & EOptionDumpConfig) {
1655 printf("%s", GetDefaultTBuiltInResourceString().c_str());
1656 if (workList.empty())
1657 return ESuccess;
1658 }
1659
1660 if (Options & EOptionDumpBareVersion) {
1661 printf("%d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
1662 GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1663 if (workList.empty())
1664 return ESuccess;
1665 } else if (Options & EOptionDumpVersions) {
1666 printf("Glslang Version: %d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR,
1667 GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1668 printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
1669 printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
1670 std::string spirvVersion;
1671 glslang::GetSpirvVersion(spirvVersion);
1672 printf("SPIR-V Version %s\n", spirvVersion.c_str());
1673 printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
1674 printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
1675 printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
1676 printf("GL_KHR_vulkan_glsl version %d\n", 100);
1677 printf("ARB_GL_gl_spirv version %d\n", 100);
1678 if (workList.empty())
1679 return ESuccess;
1680 }
1681
1682 if (workList.empty() && ((Options & EOptionStdin) == 0)) {
1683 usage();
1684 }
1685
1686 if (Options & EOptionStdin) {
1687 WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
1688 workList.add(WorkItems.back().get());
1689 }
1690
1691 ProcessConfigFile();
1692
1693 if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
1694 Error("HLSL requires SPIR-V code generation (or preprocessing only)");
1695
1696 //
1697 // Two modes:
1698 // 1) linking all arguments together, single-threaded, new C++ interface
1699 // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
1700 //
1701 if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
1702 glslang::InitializeProcess();
1703 glslang::InitializeProcess(); // also test reference counting of users
1704 glslang::InitializeProcess(); // also test reference counting of users
1705 glslang::FinalizeProcess(); // also test reference counting of users
1706 glslang::FinalizeProcess(); // also test reference counting of users
1707 CompileAndLinkShaderFiles(workList);
1708 glslang::FinalizeProcess();
1709 } else {
1710 ShInitialize();
1711 ShInitialize(); // also test reference counting of users
1712 ShFinalize(); // also test reference counting of users
1713
1714 bool printShaderNames = workList.size() > 1;
1715
1716 if (Options & EOptionMultiThreaded) {
1717 std::array<std::thread, 16> threads;
1718 for (unsigned int t = 0; t < threads.size(); ++t) {
1719 threads[t] = std::thread(CompileShaders, std::ref(workList));
1720 if (threads[t].get_id() == std::thread::id()) {
1721 fprintf(stderr, "Failed to create thread\n");
1722 return EFailThreadCreate;
1723 }
1724 }
1725
1726 std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
1727 } else
1728 CompileShaders(workList);
1729
1730 // Print out all the resulting infologs
1731 for (size_t w = 0; w < WorkItems.size(); ++w) {
1732 if (WorkItems[w]) {
1733 if (printShaderNames || WorkItems[w]->results.size() > 0)
1734 PutsIfNonEmpty(WorkItems[w]->name.c_str());
1735 PutsIfNonEmpty(WorkItems[w]->results.c_str());
1736 }
1737 }
1738
1739 ShFinalize();
1740 }
1741
1742 if (CompileFailed.load())
1743 return EFailCompile;
1744 if (LinkFailed.load())
1745 return EFailLink;
1746
1747 return 0;
1748 }
1749
main(int argc,char * argv[])1750 int C_DECL main(int argc, char* argv[])
1751 {
1752 ProcessArguments(WorkItems, argc, argv);
1753
1754 int ret = 0;
1755
1756 // Loop over the entire init/finalize cycle to watch memory changes
1757 const int iterations = 1;
1758 if (iterations > 1)
1759 glslang::OS_DumpMemoryCounters();
1760 for (int i = 0; i < iterations; ++i) {
1761 ret = singleMain();
1762 if (iterations > 1)
1763 glslang::OS_DumpMemoryCounters();
1764 }
1765
1766 return ret;
1767 }
1768
1769 //
1770 // Deduce the language from the filename. Files must end in one of the
1771 // following extensions:
1772 //
1773 // .vert = vertex
1774 // .tesc = tessellation control
1775 // .tese = tessellation evaluation
1776 // .geom = geometry
1777 // .frag = fragment
1778 // .comp = compute
1779 // .rgen = ray generation
1780 // .rint = ray intersection
1781 // .rahit = ray any hit
1782 // .rchit = ray closest hit
1783 // .rmiss = ray miss
1784 // .rcall = ray callable
1785 // .mesh = mesh
1786 // .task = task
1787 // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
1788 // where <stage> is one of the stages listed above.
1789 //
FindLanguage(const std::string & name,bool parseStageName)1790 EShLanguage FindLanguage(const std::string& name, bool parseStageName)
1791 {
1792 std::string stageName;
1793 if (shaderStageName)
1794 stageName = shaderStageName;
1795 else if (parseStageName) {
1796 // Note: "first" extension means "first from the end", i.e.
1797 // if the file is named foo.vert.glsl, then "glsl" is first,
1798 // "vert" is second.
1799 size_t firstExtStart = name.find_last_of(".");
1800 bool hasFirstExt = firstExtStart != std::string::npos;
1801 size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
1802 bool hasSecondExt = secondExtStart != std::string::npos;
1803 std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
1804 bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
1805 if (usesUnifiedExt && firstExt == "hlsl")
1806 Options |= EOptionReadHlsl;
1807 if (hasFirstExt && !usesUnifiedExt)
1808 stageName = firstExt;
1809 else if (usesUnifiedExt && hasSecondExt)
1810 stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
1811 else {
1812 usage();
1813 return EShLangVertex;
1814 }
1815 } else
1816 stageName = name;
1817
1818 if (stageName == "vert")
1819 return EShLangVertex;
1820 else if (stageName == "tesc")
1821 return EShLangTessControl;
1822 else if (stageName == "tese")
1823 return EShLangTessEvaluation;
1824 else if (stageName == "geom")
1825 return EShLangGeometry;
1826 else if (stageName == "frag")
1827 return EShLangFragment;
1828 else if (stageName == "comp")
1829 return EShLangCompute;
1830 else if (stageName == "rgen")
1831 return EShLangRayGen;
1832 else if (stageName == "rint")
1833 return EShLangIntersect;
1834 else if (stageName == "rahit")
1835 return EShLangAnyHit;
1836 else if (stageName == "rchit")
1837 return EShLangClosestHit;
1838 else if (stageName == "rmiss")
1839 return EShLangMiss;
1840 else if (stageName == "rcall")
1841 return EShLangCallable;
1842 else if (stageName == "mesh")
1843 return EShLangMesh;
1844 else if (stageName == "task")
1845 return EShLangTask;
1846
1847 usage();
1848 return EShLangVertex;
1849 }
1850
1851 //
1852 // Read a file's data into a string, and compile it using the old interface ShCompile,
1853 // for non-linkable results.
1854 //
CompileFile(const char * fileName,ShHandle compiler)1855 void CompileFile(const char* fileName, ShHandle compiler)
1856 {
1857 int ret = 0;
1858 char* shaderString;
1859 if ((Options & EOptionStdin) != 0) {
1860 std::istreambuf_iterator<char> begin(std::cin), end;
1861 std::string tempString(begin, end);
1862 shaderString = strdup(tempString.c_str());
1863 } else {
1864 shaderString = ReadFileData(fileName);
1865 }
1866
1867 // move to length-based strings, rather than null-terminated strings
1868 int* lengths = new int[1];
1869 lengths[0] = (int)strlen(shaderString);
1870
1871 EShMessages messages = EShMsgDefault;
1872 SetMessageOptions(messages);
1873
1874 if (UserPreamble.isSet())
1875 Error("-D, -U and -P options require -l (linking)\n");
1876
1877 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1878 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
1879 // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1880 ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, GetResources(), 0,
1881 (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1882 // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
1883 // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
1884 // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
1885 // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
1886 // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1887 }
1888
1889 if (Options & EOptionMemoryLeakMode)
1890 glslang::OS_DumpMemoryCounters();
1891 }
1892
1893 delete [] lengths;
1894 FreeFileData(shaderString);
1895
1896 if (ret == 0)
1897 CompileFailed = true;
1898 }
1899
1900 //
1901 // print usage to stdout
1902 //
usage()1903 void usage()
1904 {
1905 printf("Usage: glslang [option]... [file]...\n"
1906 "\n"
1907 "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
1908 " .conf to provide a config file that replaces the default configuration\n"
1909 " (see -c option below for generating a template)\n"
1910 " .vert for a vertex shader\n"
1911 " .tesc for a tessellation control shader\n"
1912 " .tese for a tessellation evaluation shader\n"
1913 " .geom for a geometry shader\n"
1914 " .frag for a fragment shader\n"
1915 " .comp for a compute shader\n"
1916 " .mesh for a mesh shader\n"
1917 " .task for a task shader\n"
1918 " .rgen for a ray generation shader\n"
1919 " .rint for a ray intersection shader\n"
1920 " .rahit for a ray any hit shader\n"
1921 " .rchit for a ray closest hit shader\n"
1922 " .rmiss for a ray miss shader\n"
1923 " .rcall for a ray callable shader\n"
1924 " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
1925 " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
1926 "\n"
1927 "Options:\n"
1928 " -C cascading errors; risk crash from accumulation of error recoveries\n"
1929 " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
1930 " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
1931 " define a pre-processor macro\n"
1932 " -E print pre-processed GLSL; cannot be used with -l;\n"
1933 " errors will appear on stderr\n"
1934 " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
1935 " default file name is <stage>.spv (-o overrides this);\n"
1936 " 'ver', when present, is the version of the input semantics,\n"
1937 " which will appear in #define GL_SPIRV ver;\n"
1938 " '--client opengl100' is the same as -G100;\n"
1939 " a '--target-env' for OpenGL will also imply '-G';\n"
1940 " currently only supports GLSL\n"
1941 " -H print human readable form of SPIR-V; turns on -V\n"
1942 " -I<dir> add dir to the include search path; includer's directory\n"
1943 " is searched first, followed by left-to-right order of -I\n"
1944 " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
1945 " -Os optimizes SPIR-V to minimize size\n"
1946 " -P<text> | --preamble-text <text> | --P <text>\n"
1947 " inject custom preamble text, which is treated as if it\n"
1948 " appeared immediately after the version declaration (if any).\n"
1949 " -R use relaxed verification rules for generating Vulkan SPIR-V,\n"
1950 " allowing the use of default uniforms, atomic_uints, and\n"
1951 " gl_VertexID and gl_InstanceID keywords.\n"
1952 " -S <stage> uses specified stage rather than parsing the file extension\n"
1953 " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
1954 " -U<name> | --undef-macro <name> | --U <name>\n"
1955 " undefine a pre-processor macro\n"
1956 " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
1957 " default file name is <stage>.spv (-o overrides this)\n"
1958 " 'ver', when present, is the version of the input semantics,\n"
1959 " which will appear in #define VULKAN ver\n"
1960 " '--client vulkan100' is the same as -V100\n"
1961 " a '--target-env' for Vulkan will also imply '-V'\n"
1962 " -c configuration dump;\n"
1963 " creates the default configuration file (redirect to a .conf file)\n"
1964 " -d default to desktop (#version 110) when there is no shader #version\n"
1965 " (default is ES version 100)\n"
1966 " -e <name> | --entry-point <name>\n"
1967 " specify <name> as the entry-point function name\n"
1968 " -f{hlsl_functionality1}\n"
1969 " 'hlsl_functionality1' enables use of the\n"
1970 " SPV_GOOGLE_hlsl_functionality1 extension\n"
1971 " -g generate debug information\n"
1972 " -g0 strip debug information\n"
1973 " -gV generate nonsemantic shader debug information\n"
1974 " -gVS generate nonsemantic shader debug information with source\n"
1975 " -h print this usage message\n"
1976 " -i intermediate tree (glslang AST) is printed out\n"
1977 " -l link all input files together to form a single module\n"
1978 " -m memory leak mode\n"
1979 " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
1980 " -q dump reflection query database; requires -l for linking\n"
1981 " -r | --relaxed-errors"
1982 " relaxed GLSL semantic error-checking mode\n"
1983 " -s silence syntax and semantic error reporting\n"
1984 " -t multi-threaded mode\n"
1985 " -v | --version\n"
1986 " print version strings\n"
1987 " -w | --suppress-warnings\n"
1988 " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
1989 " -x save binary output as text-based 32-bit hexadecimal numbers\n"
1990 " -u<name>:<loc> specify a uniform location override for --aml\n"
1991 " --uniform-base <base> set a base to use for generated uniform locations\n"
1992 " --auto-map-bindings | --amb automatically bind uniform variables\n"
1993 " without explicit bindings\n"
1994 " --auto-map-locations | --aml automatically locate input/output lacking\n"
1995 " 'location' (fragile, not cross stage)\n"
1996 " --auto-sampled-textures Removes sampler variables and converts\n"
1997 " existing textures to sampled textures\n"
1998 " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
1999 " --depfile <file> writes depfile for build systems\n"
2000 " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
2001 " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
2002 " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
2003 " scalars\n"
2004 " --glsl-version {100 | 110 | 120 | 130 | 140 | 150 |\n"
2005 " 300es | 310es | 320es | 330\n"
2006 " 400 | 410 | 420 | 430 | 440 | 450 | 460}\n"
2007 " set GLSL version, overrides #version\n"
2008 " in shader sourcen\n"
2009 " --hlsl-offsets allow block offsets to follow HLSL rules\n"
2010 " works independently of source language\n"
2011 " --hlsl-iomap perform IO mapping in HLSL register space\n"
2012 " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
2013 " --hlsl-dx9-compatible interprets sampler declarations as a\n"
2014 " texture/sampler combo like DirectX9 would,\n"
2015 " and recognizes DirectX9-specific semantics\n"
2016 " --hlsl-dx-position-w W component of SV_Position in HLSL fragment\n"
2017 " shaders compatible with DirectX\n"
2018 " --invert-y | --iy invert position.Y output in vertex shader\n"
2019 " --enhanced-msgs print more readable error messages (GLSL only)\n"
2020 " --keep-uncalled | --ku don't eliminate uncalled functions\n"
2021 " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
2022 " --no-storage-format | --nsf use Unknown image format\n"
2023 " --quiet do not print anything to stdout, unless\n"
2024 " requested by another option\n"
2025 " --reflect-strict-array-suffix use strict array suffix rules when\n"
2026 " reflecting\n"
2027 " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
2028 " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
2029 " shaders rather than just vertex/fragment\n"
2030 " --reflect-separate-buffers reflect buffer variables and blocks\n"
2031 " separately to uniforms\n"
2032 " --reflect-all-block-variables reflect all variables in blocks, whether\n"
2033 " inactive or active\n"
2034 " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
2035 " uniform blocks\n"
2036 " --resource-set-binding [stage] name set binding\n"
2037 " set descriptor set and binding for\n"
2038 " individual resources\n"
2039 " --resource-set-binding [stage] set\n"
2040 " set descriptor set for all resources\n"
2041 " --rsb synonym for --resource-set-binding\n"
2042 " --set-block-backing name {uniform|buffer|push_constant}\n"
2043 " changes the backing type of a uniform, buffer,\n"
2044 " or push_constant block declared in\n"
2045 " in the program, when using -R option.\n"
2046 " This can be used to change the backing\n"
2047 " for existing blocks as well as implicit ones\n"
2048 " such as 'gl_DefaultUniformBlock'.\n"
2049 " --sbs synonym for set-block-storage\n"
2050 " --set-atomic-counter-block name set\n"
2051 " set name, and descriptor set for\n"
2052 " atomic counter blocks, with -R opt\n"
2053 " --sacb synonym for set-atomic-counter-block\n"
2054 " --set-default-uniform-block name set binding\n"
2055 " set name, descriptor set, and binding for\n"
2056 " global default-uniform-block, with -R opt\n"
2057 " --sdub synonym for set-default-uniform-block\n"
2058 " --shift-image-binding [stage] num\n"
2059 " base binding number for images (uav)\n"
2060 " --shift-image-binding [stage] [num set]...\n"
2061 " per-descriptor-set shift values\n"
2062 " --sib synonym for --shift-image-binding\n"
2063 " --shift-sampler-binding [stage] num\n"
2064 " base binding number for samplers\n"
2065 " --shift-sampler-binding [stage] [num set]...\n"
2066 " per-descriptor-set shift values\n"
2067 " --ssb synonym for --shift-sampler-binding\n"
2068 " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
2069 " --shift-ssbo-binding [stage] [num set]...\n"
2070 " per-descriptor-set shift values\n"
2071 " --sbb synonym for --shift-ssbo-binding\n"
2072 " --shift-texture-binding [stage] num\n"
2073 " base binding number for textures\n"
2074 " --shift-texture-binding [stage] [num set]...\n"
2075 " per-descriptor-set shift values\n"
2076 " --stb synonym for --shift-texture-binding\n"
2077 " --shift-uav-binding [stage] num base binding number for UAVs\n"
2078 " --shift-uav-binding [stage] [num set]...\n"
2079 " per-descriptor-set shift values\n"
2080 " --suavb synonym for --shift-uav-binding\n"
2081 " --shift-UBO-binding [stage] num base binding number for UBOs\n"
2082 " --shift-UBO-binding [stage] [num set]...\n"
2083 " per-descriptor-set shift values\n"
2084 " --sub synonym for --shift-UBO-binding\n"
2085 " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
2086 " --spirv-dis output standard-form disassembly; works only\n"
2087 " when a SPIR-V generation option is also used\n"
2088 " --spirv-val execute the SPIRV-Tools validator\n"
2089 " --source-entrypoint <name> the given shader source function is\n"
2090 " renamed to be the <name> given in -e\n"
2091 " --sep synonym for --source-entrypoint\n"
2092 " --stdin read from stdin instead of from a file;\n"
2093 " requires providing the shader stage using -S\n"
2094 " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | opengl |\n"
2095 " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 |\n"
2096 " spirv1.5 | spirv1.6}\n"
2097 " Set the execution environment that the\n"
2098 " generated code will be executed in.\n"
2099 " Defaults to:\n"
2100 " * vulkan1.0 under --client vulkan<ver>\n"
2101 " * opengl under --client opengl<ver>\n"
2102 " * spirv1.0 under --target-env vulkan1.0\n"
2103 " * spirv1.3 under --target-env vulkan1.1\n"
2104 " * spirv1.5 under --target-env vulkan1.2\n"
2105 " * spirv1.6 under --target-env vulkan1.3\n"
2106 " Multiple --target-env can be specified.\n"
2107 " --variable-name <name>\n"
2108 " --vn <name> creates a C header file that contains a\n"
2109 " uint32_t array named <name>\n"
2110 " initialized with the shader binary code\n"
2111 " --no-link Only compile shader; do not link (GLSL-only)\n"
2112 " NOTE: this option will set the export linkage\n"
2113 " attribute on all functions\n");
2114
2115 exit(EFailUsage);
2116 }
2117
2118 #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
2119
2120 #include <errno.h>
2121
fopen_s(FILE ** pFile,const char * filename,const char * mode)2122 int fopen_s(
2123 FILE** pFile,
2124 const char* filename,
2125 const char* mode
2126 )
2127 {
2128 if (!pFile || !filename || !mode) {
2129 return EINVAL;
2130 }
2131
2132 FILE* f = fopen(filename, mode);
2133 if (! f) {
2134 if (errno != 0) {
2135 return errno;
2136 } else {
2137 return ENOENT;
2138 }
2139 }
2140 *pFile = f;
2141
2142 return 0;
2143 }
2144
2145 #endif
2146
2147 //
2148 // Malloc a string of sufficient size and read a string into it.
2149 //
ReadFileData(const char * fileName)2150 char* ReadFileData(const char* fileName)
2151 {
2152 FILE *in = nullptr;
2153 int errorCode = fopen_s(&in, fileName, "r");
2154 if (errorCode || in == nullptr)
2155 Error("unable to open input file");
2156
2157 int count = 0;
2158 while (fgetc(in) != EOF)
2159 count++;
2160
2161 fseek(in, 0, SEEK_SET);
2162
2163 char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
2164 if ((int)fread(return_data, 1, count, in) != count) {
2165 free(return_data);
2166 Error("can't read input file");
2167 }
2168
2169 return_data[count] = '\0';
2170 fclose(in);
2171
2172 return return_data;
2173 }
2174
FreeFileData(char * data)2175 void FreeFileData(char* data)
2176 {
2177 free(data);
2178 }
2179
InfoLogMsg(const char * msg,const char * name,const int num)2180 void InfoLogMsg(const char* msg, const char* name, const int num)
2181 {
2182 if (num >= 0 )
2183 printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
2184 else
2185 printf("#### %s %s INFO LOG ####\n", msg, name);
2186 }
2187