yum-mirror/glslang

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

ifrforspirv: use the lists of optimization passes from spirv-tools6a0d48e4

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