yum-mirror/glslang

git clone https://git.yummers.dev/yum-mirror/glslang

Qingyuan ZhengImplement DebugEntryPoint instruction in NSDI 1024ede04ac

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