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