Fix comment for setEnvInput()
[platform/upstream/glslang.git] / glslang / Public / ShaderLang.h
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2015-2018 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37 #ifndef _COMPILER_INTERFACE_INCLUDED_
38 #define _COMPILER_INTERFACE_INCLUDED_
39
40 #include "../Include/ResourceLimits.h"
41 #include "../MachineIndependent/Versions.h"
42
43 #include <cstring>
44 #include <vector>
45
46 #ifdef _WIN32
47     #define C_DECL __cdecl
48 #else
49     #define C_DECL
50 #endif
51
52 #ifdef GLSLANG_IS_SHARED_LIBRARY
53     #ifdef _WIN32
54         #ifdef GLSLANG_EXPORTING
55             #define GLSLANG_EXPORT __declspec(dllexport)
56         #else
57             #define GLSLANG_EXPORT __declspec(dllimport)
58         #endif
59     #elif __GNUC__ >= 4
60         #define GLSLANG_EXPORT __attribute__((visibility("default")))
61     #endif
62 #endif // GLSLANG_IS_SHARED_LIBRARY
63
64 #ifndef GLSLANG_EXPORT
65 #define GLSLANG_EXPORT
66 #endif
67
68 //
69 // This is the platform independent interface between an OGL driver
70 // and the shading language compiler/linker.
71 //
72
73 #ifdef __cplusplus
74     extern "C" {
75 #endif
76
77 //
78 // Call before doing any other compiler/linker operations.
79 //
80 // (Call once per process, not once per thread.)
81 //
82 GLSLANG_EXPORT int ShInitialize();
83
84 //
85 // Call this at process shutdown to clean up memory.
86 //
87 GLSLANG_EXPORT int ShFinalize();
88
89 //
90 // Types of languages the compiler can consume.
91 //
92 typedef enum {
93     EShLangVertex,
94     EShLangTessControl,
95     EShLangTessEvaluation,
96     EShLangGeometry,
97     EShLangFragment,
98     EShLangCompute,
99     EShLangRayGen,
100     EShLangRayGenNV = EShLangRayGen,
101     EShLangIntersect,
102     EShLangIntersectNV = EShLangIntersect,
103     EShLangAnyHit,
104     EShLangAnyHitNV = EShLangAnyHit,
105     EShLangClosestHit,
106     EShLangClosestHitNV = EShLangClosestHit,
107     EShLangMiss,
108     EShLangMissNV = EShLangMiss,
109     EShLangCallable,
110     EShLangCallableNV = EShLangCallable,
111     EShLangTaskNV,
112     EShLangMeshNV,
113     LAST_ELEMENT_MARKER(EShLangCount),
114 } EShLanguage;         // would be better as stage, but this is ancient now
115
116 typedef enum : unsigned {
117     EShLangVertexMask         = (1 << EShLangVertex),
118     EShLangTessControlMask    = (1 << EShLangTessControl),
119     EShLangTessEvaluationMask = (1 << EShLangTessEvaluation),
120     EShLangGeometryMask       = (1 << EShLangGeometry),
121     EShLangFragmentMask       = (1 << EShLangFragment),
122     EShLangComputeMask        = (1 << EShLangCompute),
123     EShLangRayGenMask         = (1 << EShLangRayGen),
124     EShLangRayGenNVMask       = EShLangRayGenMask,
125     EShLangIntersectMask      = (1 << EShLangIntersect),
126     EShLangIntersectNVMask    = EShLangIntersectMask,
127     EShLangAnyHitMask         = (1 << EShLangAnyHit),
128     EShLangAnyHitNVMask       = EShLangAnyHitMask,
129     EShLangClosestHitMask     = (1 << EShLangClosestHit),
130     EShLangClosestHitNVMask   = EShLangClosestHitMask,
131     EShLangMissMask           = (1 << EShLangMiss),
132     EShLangMissNVMask         = EShLangMissMask,
133     EShLangCallableMask       = (1 << EShLangCallable),
134     EShLangCallableNVMask     = EShLangCallableMask,
135     EShLangTaskNVMask         = (1 << EShLangTaskNV),
136     EShLangMeshNVMask         = (1 << EShLangMeshNV),
137     LAST_ELEMENT_MARKER(EShLanguageMaskCount),
138 } EShLanguageMask;
139
140 namespace glslang {
141
142 class TType;
143
144 typedef enum {
145     EShSourceNone,
146     EShSourceGlsl,               // GLSL, includes ESSL (OpenGL ES GLSL)
147     EShSourceHlsl,               // HLSL
148     LAST_ELEMENT_MARKER(EShSourceCount),
149 } EShSource;                     // if EShLanguage were EShStage, this could be EShLanguage instead
150
151 typedef enum {
152     EShClientNone,               // use when there is no client, e.g. for validation
153     EShClientVulkan,             // as GLSL dialect, specifies KHR_vulkan_glsl extension
154     EShClientOpenGL,             // as GLSL dialect, specifies ARB_gl_spirv extension
155     LAST_ELEMENT_MARKER(EShClientCount),
156 } EShClient;
157
158 typedef enum {
159     EShTargetNone,
160     EShTargetSpv,                 // SPIR-V (preferred spelling)
161     EshTargetSpv = EShTargetSpv,  // legacy spelling
162     LAST_ELEMENT_MARKER(EShTargetCount),
163 } EShTargetLanguage;
164
165 // TODO(greg-lunarg): Fix non-determinism problem with Universal
166 // https://github.com/KhronosGroup/glslang/issues/2858
167
168 typedef enum {
169     EShTargetUniversal = 0,                           // Universal - Do not use, see comment above
170     EShTargetVulkan_1_0 = (1 << 22),                  // Vulkan 1.0
171     EShTargetVulkan_1_1 = (1 << 22) | (1 << 12),      // Vulkan 1.1
172     EShTargetVulkan_1_2 = (1 << 22) | (2 << 12),      // Vulkan 1.2
173     EShTargetOpenGL_450 = 450,                        // OpenGL
174     LAST_ELEMENT_MARKER(EShTargetClientVersionCount = 4),
175 } EShTargetClientVersion;
176
177 typedef EShTargetClientVersion EshTargetClientVersion;
178
179 typedef enum {
180     EShTargetSpv_1_0 = (1 << 16),                     // SPIR-V 1.0
181     EShTargetSpv_1_1 = (1 << 16) | (1 << 8),          // SPIR-V 1.1
182     EShTargetSpv_1_2 = (1 << 16) | (2 << 8),          // SPIR-V 1.2
183     EShTargetSpv_1_3 = (1 << 16) | (3 << 8),          // SPIR-V 1.3
184     EShTargetSpv_1_4 = (1 << 16) | (4 << 8),          // SPIR-V 1.4
185     EShTargetSpv_1_5 = (1 << 16) | (5 << 8),          // SPIR-V 1.5
186     EShTargetSpv_1_6 = (1 << 16) | (6 << 8),          // SPIR-V 1.6
187     LAST_ELEMENT_MARKER(EShTargetLanguageVersionCount = 7),
188 } EShTargetLanguageVersion;
189
190 struct TInputLanguage {
191     EShSource languageFamily; // redundant information with other input, this one overrides when not EShSourceNone
192     EShLanguage stage;        // redundant information with other input, this one overrides when not EShSourceNone
193     EShClient dialect;
194     int dialectVersion;       // version of client's language definition, not the client (when not EShClientNone)
195     bool vulkanRulesRelaxed;
196 };
197
198 struct TClient {
199     EShClient client;
200     EShTargetClientVersion version;   // version of client itself (not the client's input dialect)
201 };
202
203 struct TTarget {
204     EShTargetLanguage language;
205     EShTargetLanguageVersion version; // version to target, if SPIR-V, defined by "word 1" of the SPIR-V header
206     bool hlslFunctionality1;          // can target hlsl_functionality1 extension(s)
207 };
208
209 // All source/client/target versions and settings.
210 // Can override previous methods of setting, when items are set here.
211 // Expected to grow, as more are added, rather than growing parameter lists.
212 struct TEnvironment {
213     TInputLanguage input;     // definition of the input language
214     TClient client;           // what client is the overall compilation being done for?
215     TTarget target;           // what to generate
216 };
217
218 GLSLANG_EXPORT const char* StageName(EShLanguage);
219
220 } // end namespace glslang
221
222 //
223 // Types of output the linker will create.
224 //
225 typedef enum {
226     EShExVertexFragment,
227     EShExFragment
228 } EShExecutable;
229
230 //
231 // Optimization level for the compiler.
232 //
233 typedef enum {
234     EShOptNoGeneration,
235     EShOptNone,
236     EShOptSimple,       // Optimizations that can be done quickly
237     EShOptFull,         // Optimizations that will take more time
238     LAST_ELEMENT_MARKER(EshOptLevelCount),
239 } EShOptimizationLevel;
240
241 //
242 // Texture and Sampler transformation mode.
243 //
244 typedef enum {
245     EShTexSampTransKeep,   // keep textures and samplers as is (default)
246     EShTexSampTransUpgradeTextureRemoveSampler,  // change texture w/o embeded sampler into sampled texture and throw away all samplers
247     LAST_ELEMENT_MARKER(EShTexSampTransCount),
248 } EShTextureSamplerTransformMode;
249
250 //
251 // Message choices for what errors and warnings are given.
252 //
253 enum EShMessages : unsigned {
254     EShMsgDefault          = 0,         // default is to give all required errors and extra warnings
255     EShMsgRelaxedErrors    = (1 << 0),  // be liberal in accepting input
256     EShMsgSuppressWarnings = (1 << 1),  // suppress all warnings, except those required by the specification
257     EShMsgAST              = (1 << 2),  // print the AST intermediate representation
258     EShMsgSpvRules         = (1 << 3),  // issue messages for SPIR-V generation
259     EShMsgVulkanRules      = (1 << 4),  // issue messages for Vulkan-requirements of GLSL for SPIR-V
260     EShMsgOnlyPreprocessor = (1 << 5),  // only print out errors produced by the preprocessor
261     EShMsgReadHlsl         = (1 << 6),  // use HLSL parsing rules and semantics
262     EShMsgCascadingErrors  = (1 << 7),  // get cascading errors; risks error-recovery issues, instead of an early exit
263     EShMsgKeepUncalled     = (1 << 8),  // for testing, don't eliminate uncalled functions
264     EShMsgHlslOffsets      = (1 << 9),  // allow block offsets to follow HLSL rules instead of GLSL rules
265     EShMsgDebugInfo        = (1 << 10), // save debug information
266     EShMsgHlslEnable16BitTypes  = (1 << 11), // enable use of 16-bit types in SPIR-V for HLSL
267     EShMsgHlslLegalization  = (1 << 12), // enable HLSL Legalization messages
268     EShMsgHlslDX9Compatible = (1 << 13), // enable HLSL DX9 compatible mode (for samplers and semantics)
269     EShMsgBuiltinSymbolTable = (1 << 14), // print the builtin symbol table
270     LAST_ELEMENT_MARKER(EShMsgCount),
271 };
272
273 //
274 // Options for building reflection
275 //
276 typedef enum {
277     EShReflectionDefault            = 0,        // default is original behaviour before options were added
278     EShReflectionStrictArraySuffix  = (1 << 0), // reflection will follow stricter rules for array-of-structs suffixes
279     EShReflectionBasicArraySuffix   = (1 << 1), // arrays of basic types will be appended with [0] as in GL reflection
280     EShReflectionIntermediateIO     = (1 << 2), // reflect inputs and outputs to program, even with no vertex shader
281     EShReflectionSeparateBuffers    = (1 << 3), // buffer variables and buffer blocks are reflected separately
282     EShReflectionAllBlockVariables  = (1 << 4), // reflect all variables in blocks, even if they are inactive
283     EShReflectionUnwrapIOBlocks     = (1 << 5), // unwrap input/output blocks the same as with uniform blocks
284     EShReflectionAllIOVariables     = (1 << 6), // reflect all input/output variables, even if they are inactive
285     EShReflectionSharedStd140SSBO   = (1 << 7), // Apply std140/shared rules for ubo to ssbo
286     EShReflectionSharedStd140UBO    = (1 << 8), // Apply std140/shared rules for ubo to ssbo
287     LAST_ELEMENT_MARKER(EShReflectionCount),
288 } EShReflectionOptions;
289
290 //
291 // Build a table for bindings.  This can be used for locating
292 // attributes, uniforms, globals, etc., as needed.
293 //
294 typedef struct {
295     const char* name;
296     int binding;
297 } ShBinding;
298
299 typedef struct {
300     int numBindings;
301     ShBinding* bindings;  // array of bindings
302 } ShBindingTable;
303
304 //
305 // ShHandle held by but opaque to the driver.  It is allocated,
306 // managed, and de-allocated by the compiler/linker. It's contents
307 // are defined by and used by the compiler and linker.  For example,
308 // symbol table information and object code passed from the compiler
309 // to the linker can be stored where ShHandle points.
310 //
311 // If handle creation fails, 0 will be returned.
312 //
313 typedef void* ShHandle;
314
315 //
316 // Driver calls these to create and destroy compiler/linker
317 // objects.
318 //
319 GLSLANG_EXPORT ShHandle ShConstructCompiler(const EShLanguage, int debugOptions);  // one per shader
320 GLSLANG_EXPORT ShHandle ShConstructLinker(const EShExecutable, int debugOptions);  // one per shader pair
321 GLSLANG_EXPORT ShHandle ShConstructUniformMap();                 // one per uniform namespace (currently entire program object)
322 GLSLANG_EXPORT void ShDestruct(ShHandle);
323
324 //
325 // The return value of ShCompile is boolean, non-zero indicating
326 // success.
327 //
328 // The info-log should be written by ShCompile into
329 // ShHandle, so it can answer future queries.
330 //
331 GLSLANG_EXPORT int ShCompile(
332     const ShHandle,
333     const char* const shaderStrings[],
334     const int numStrings,
335     const int* lengths,
336     const EShOptimizationLevel,
337     const TBuiltInResource *resources,
338     int debugOptions,
339     int defaultVersion = 110,            // use 100 for ES environment, overridden by #version in shader
340     bool forwardCompatible = false,      // give errors for use of deprecated features
341     EShMessages messages = EShMsgDefault // warnings and errors
342     );
343
344 GLSLANG_EXPORT int ShLinkExt(
345     const ShHandle,               // linker object
346     const ShHandle h[],           // compiler objects to link together
347     const int numHandles);
348
349 //
350 // ShSetEncrpytionMethod is a place-holder for specifying
351 // how source code is encrypted.
352 //
353 GLSLANG_EXPORT void ShSetEncryptionMethod(ShHandle);
354
355 //
356 // All the following return 0 if the information is not
357 // available in the object passed down, or the object is bad.
358 //
359 GLSLANG_EXPORT const char* ShGetInfoLog(const ShHandle);
360 GLSLANG_EXPORT const void* ShGetExecutable(const ShHandle);
361 GLSLANG_EXPORT int ShSetVirtualAttributeBindings(const ShHandle, const ShBindingTable*);   // to detect user aliasing
362 GLSLANG_EXPORT int ShSetFixedAttributeBindings(const ShHandle, const ShBindingTable*);     // to force any physical mappings
363 //
364 // Tell the linker to never assign a vertex attribute to this list of physical attributes
365 //
366 GLSLANG_EXPORT int ShExcludeAttributes(const ShHandle, int *attributes, int count);
367
368 //
369 // Returns the location ID of the named uniform.
370 // Returns -1 if error.
371 //
372 GLSLANG_EXPORT int ShGetUniformLocation(const ShHandle uniformMap, const char* name);
373
374 #ifdef __cplusplus
375     }  // end extern "C"
376 #endif
377
378 ////////////////////////////////////////////////////////////////////////////////////////////
379 //
380 // Deferred-Lowering C++ Interface
381 // -----------------------------------
382 //
383 // Below is a new alternate C++ interface, which deprecates the above
384 // opaque handle-based interface.
385 //
386 // The below is further designed to handle multiple compilation units per stage, where
387 // the intermediate results, including the parse tree, are preserved until link time,
388 // rather than the above interface which is designed to have each compilation unit
389 // lowered at compile time.  In the above model, linking occurs on the lowered results,
390 // whereas in this model intra-stage linking can occur at the parse tree
391 // (treeRoot in TIntermediate) level, and then a full stage can be lowered.
392 //
393
394 #include <list>
395 #include <string>
396 #include <utility>
397
398 class TCompiler;
399 class TInfoSink;
400
401 namespace glslang {
402
403 struct Version {
404     int major;
405     int minor;
406     int patch;
407     const char* flavor;
408 };
409
410 GLSLANG_EXPORT Version GetVersion();
411 GLSLANG_EXPORT const char* GetEsslVersionString();
412 GLSLANG_EXPORT const char* GetGlslVersionString();
413 GLSLANG_EXPORT int GetKhronosToolId();
414
415 class TIntermediate;
416 class TProgram;
417 class TPoolAllocator;
418
419 // Call this exactly once per process before using anything else
420 GLSLANG_EXPORT bool InitializeProcess();
421
422 // Call once per process to tear down everything
423 GLSLANG_EXPORT void FinalizeProcess();
424
425 // Resource type for IO resolver
426 enum TResourceType {
427     EResSampler,
428     EResTexture,
429     EResImage,
430     EResUbo,
431     EResSsbo,
432     EResUav,
433     EResCount
434 };
435
436 enum TBlockStorageClass
437 {
438     EbsUniform = 0,
439     EbsStorageBuffer,
440     EbsPushConstant,
441     EbsNone,    // not a uniform or buffer variable
442     EbsCount,
443 };
444
445 // Make one TShader per shader that you will link into a program. Then
446 //  - provide the shader through setStrings() or setStringsWithLengths()
447 //  - optionally call setEnv*(), see below for more detail
448 //  - optionally use setPreamble() to set a special shader string that will be
449 //    processed before all others but won't affect the validity of #version
450 //  - optionally call addProcesses() for each setting/transform,
451 //    see comment for class TProcesses
452 //  - call parse(): source language and target environment must be selected
453 //    either by correct setting of EShMessages sent to parse(), or by
454 //    explicitly calling setEnv*()
455 //  - query the info logs
456 //
457 // N.B.: Does not yet support having the same TShader instance being linked into
458 // multiple programs.
459 //
460 // N.B.: Destruct a linked program *before* destructing the shaders linked into it.
461 //
462 class TShader {
463 public:
464     GLSLANG_EXPORT explicit TShader(EShLanguage);
465     GLSLANG_EXPORT virtual ~TShader();
466     GLSLANG_EXPORT void setStrings(const char* const* s, int n);
467     GLSLANG_EXPORT void setStringsWithLengths(
468         const char* const* s, const int* l, int n);
469     GLSLANG_EXPORT void setStringsWithLengthsAndNames(
470         const char* const* s, const int* l, const char* const* names, int n);
471     void setPreamble(const char* s) { preamble = s; }
472     GLSLANG_EXPORT void setEntryPoint(const char* entryPoint);
473     GLSLANG_EXPORT void setSourceEntryPoint(const char* sourceEntryPointName);
474     GLSLANG_EXPORT void addProcesses(const std::vector<std::string>&);
475     GLSLANG_EXPORT void setUniqueId(unsigned long long id);
476
477     // IO resolver binding data: see comments in ShaderLang.cpp
478     GLSLANG_EXPORT void setShiftBinding(TResourceType res, unsigned int base);
479     GLSLANG_EXPORT void setShiftSamplerBinding(unsigned int base);  // DEPRECATED: use setShiftBinding
480     GLSLANG_EXPORT void setShiftTextureBinding(unsigned int base);  // DEPRECATED: use setShiftBinding
481     GLSLANG_EXPORT void setShiftImageBinding(unsigned int base);    // DEPRECATED: use setShiftBinding
482     GLSLANG_EXPORT void setShiftUboBinding(unsigned int base);      // DEPRECATED: use setShiftBinding
483     GLSLANG_EXPORT void setShiftUavBinding(unsigned int base);      // DEPRECATED: use setShiftBinding
484     GLSLANG_EXPORT void setShiftCbufferBinding(unsigned int base);  // synonym for setShiftUboBinding
485     GLSLANG_EXPORT void setShiftSsboBinding(unsigned int base);     // DEPRECATED: use setShiftBinding
486     GLSLANG_EXPORT void setShiftBindingForSet(TResourceType res, unsigned int base, unsigned int set);
487     GLSLANG_EXPORT void setResourceSetBinding(const std::vector<std::string>& base);
488     GLSLANG_EXPORT void setAutoMapBindings(bool map);
489     GLSLANG_EXPORT void setAutoMapLocations(bool map);
490     GLSLANG_EXPORT void addUniformLocationOverride(const char* name, int loc);
491     GLSLANG_EXPORT void setUniformLocationBase(int base);
492     GLSLANG_EXPORT void setInvertY(bool invert);
493     GLSLANG_EXPORT void setDxPositionW(bool dxPosW);
494 #ifdef ENABLE_HLSL
495     GLSLANG_EXPORT void setHlslIoMapping(bool hlslIoMap);
496     GLSLANG_EXPORT void setFlattenUniformArrays(bool flatten);
497 #endif
498     GLSLANG_EXPORT void setNoStorageFormat(bool useUnknownFormat);
499     GLSLANG_EXPORT void setNanMinMaxClamp(bool nanMinMaxClamp);
500     GLSLANG_EXPORT void setTextureSamplerTransformMode(EShTextureSamplerTransformMode mode);
501     GLSLANG_EXPORT void addBlockStorageOverride(const char* nameStr, glslang::TBlockStorageClass backing);
502
503     GLSLANG_EXPORT void setGlobalUniformBlockName(const char* name);
504     GLSLANG_EXPORT void setAtomicCounterBlockName(const char* name);
505     GLSLANG_EXPORT void setGlobalUniformSet(unsigned int set);
506     GLSLANG_EXPORT void setGlobalUniformBinding(unsigned int binding);
507     GLSLANG_EXPORT void setAtomicCounterBlockSet(unsigned int set);
508     GLSLANG_EXPORT void setAtomicCounterBlockBinding(unsigned int binding);
509
510     // For setting up the environment (cleared to nothingness in the constructor).
511     // These must be called so that parsing is done for the right source language and
512     // target environment, either indirectly through TranslateEnvironment() based on
513     // EShMessages et. al., or directly by the user.
514     //
515     // setEnvInput:    The input source language and stage. If generating code for a
516     //                 specific client, the input client semantics to use and the
517     //                 version of that client's input semantics to use, otherwise
518     //                 use EShClientNone and version of 0, e.g. for validation mode.
519     //                 Note 'version' does not describe the target environment,
520     //                 just the version of the source dialect to compile under.
521     //                 For example, to choose the Vulkan dialect of GLSL defined by
522     //                 version 100 of the KHR_vulkan_glsl extension: lang = EShSourceGlsl,
523     //                 dialect = EShClientVulkan, and version = 100.
524     //
525     //                 See the definitions of TEnvironment, EShSource, EShLanguage,
526     //                 and EShClient for choices and more detail.
527     //
528     // setEnvClient:   The client that will be hosting the execution, and it's version.
529     //                 Note 'version' is not the version of the languages involved, but
530     //                 the version of the client environment.
531     //                 Use EShClientNone and version of 0 if there is no client, e.g.
532     //                 for validation mode.
533     //
534     //                 See EShTargetClientVersion for choices.
535     //
536     // setEnvTarget:   The language to translate to when generating code, and that
537     //                 language's version.
538     //                 Use EShTargetNone and version of 0 if there is no client, e.g.
539     //                 for validation mode.
540     //
541     void setEnvInput(EShSource lang, EShLanguage envStage, EShClient client, int version)
542     {
543         environment.input.languageFamily = lang;
544         environment.input.stage = envStage;
545         environment.input.dialect = client;
546         environment.input.dialectVersion = version;
547     }
548     void setEnvClient(EShClient client, EShTargetClientVersion version)
549     {
550         environment.client.client = client;
551         environment.client.version = version;
552     }
553     void setEnvTarget(EShTargetLanguage lang, EShTargetLanguageVersion version)
554     {
555         environment.target.language = lang;
556         environment.target.version = version;
557     }
558
559     void getStrings(const char* const* &s, int& n) { s = strings; n = numStrings; }
560
561 #ifdef ENABLE_HLSL
562     void setEnvTargetHlslFunctionality1() { environment.target.hlslFunctionality1 = true; }
563     bool getEnvTargetHlslFunctionality1() const { return environment.target.hlslFunctionality1; }
564 #else
565     bool getEnvTargetHlslFunctionality1() const { return false; }
566 #endif
567
568     void setEnvInputVulkanRulesRelaxed() { environment.input.vulkanRulesRelaxed = true; }
569     bool getEnvInputVulkanRulesRelaxed() const { return environment.input.vulkanRulesRelaxed; }
570
571     // Interface to #include handlers.
572     //
573     // To support #include, a client of Glslang does the following:
574     // 1. Call setStringsWithNames to set the source strings and associated
575     //    names.  For example, the names could be the names of the files
576     //    containing the shader sources.
577     // 2. Call parse with an Includer.
578     //
579     // When the Glslang parser encounters an #include directive, it calls
580     // the Includer's include method with the requested include name
581     // together with the current string name.  The returned IncludeResult
582     // contains the fully resolved name of the included source, together
583     // with the source text that should replace the #include directive
584     // in the source stream.  After parsing that source, Glslang will
585     // release the IncludeResult object.
586     class Includer {
587     public:
588         // An IncludeResult contains the resolved name and content of a source
589         // inclusion.
590         struct IncludeResult {
591             IncludeResult(const std::string& headerName, const char* const headerData, const size_t headerLength, void* userData) :
592                 headerName(headerName), headerData(headerData), headerLength(headerLength), userData(userData) { }
593             // For a successful inclusion, the fully resolved name of the requested
594             // include.  For example, in a file system-based includer, full resolution
595             // should convert a relative path name into an absolute path name.
596             // For a failed inclusion, this is an empty string.
597             const std::string headerName;
598             // The content and byte length of the requested inclusion.  The
599             // Includer producing this IncludeResult retains ownership of the
600             // storage.
601             // For a failed inclusion, the header
602             // field points to a string containing error details.
603             const char* const headerData;
604             const size_t headerLength;
605             // Include resolver's context.
606             void* userData;
607         protected:
608             IncludeResult& operator=(const IncludeResult&);
609             IncludeResult();
610         };
611
612         // For both include methods below:
613         //
614         // Resolves an inclusion request by name, current source name,
615         // and include depth.
616         // On success, returns an IncludeResult containing the resolved name
617         // and content of the include.
618         // On failure, returns a nullptr, or an IncludeResult
619         // with an empty string for the headerName and error details in the
620         // header field.
621         // The Includer retains ownership of the contents
622         // of the returned IncludeResult value, and those contents must
623         // remain valid until the releaseInclude method is called on that
624         // IncludeResult object.
625         //
626         // Note "local" vs. "system" is not an "either/or": "local" is an
627         // extra thing to do over "system". Both might get called, as per
628         // the C++ specification.
629
630         // For the "system" or <>-style includes; search the "system" paths.
631         virtual IncludeResult* includeSystem(const char* /*headerName*/,
632                                              const char* /*includerName*/,
633                                              size_t /*inclusionDepth*/) { return nullptr; }
634
635         // For the "local"-only aspect of a "" include. Should not search in the
636         // "system" paths, because on returning a failure, the parser will
637         // call includeSystem() to look in the "system" locations.
638         virtual IncludeResult* includeLocal(const char* /*headerName*/,
639                                             const char* /*includerName*/,
640                                             size_t /*inclusionDepth*/) { return nullptr; }
641
642         // Signals that the parser will no longer use the contents of the
643         // specified IncludeResult.
644         virtual void releaseInclude(IncludeResult*) = 0;
645         virtual ~Includer() {}
646     };
647
648     // Fail all Includer searches
649     class ForbidIncluder : public Includer {
650     public:
651         virtual void releaseInclude(IncludeResult*) override { }
652     };
653
654     GLSLANG_EXPORT bool parse(
655         const TBuiltInResource*, int defaultVersion, EProfile defaultProfile,
656         bool forceDefaultVersionAndProfile, bool forwardCompatible,
657         EShMessages, Includer&);
658
659     bool parse(const TBuiltInResource* res, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
660                bool forwardCompatible, EShMessages messages)
661     {
662         TShader::ForbidIncluder includer;
663         return parse(res, defaultVersion, defaultProfile, forceDefaultVersionAndProfile, forwardCompatible, messages, includer);
664     }
665
666     // Equivalent to parse() without a default profile and without forcing defaults.
667     bool parse(const TBuiltInResource* builtInResources, int defaultVersion, bool forwardCompatible, EShMessages messages)
668     {
669         return parse(builtInResources, defaultVersion, ENoProfile, false, forwardCompatible, messages);
670     }
671
672     bool parse(const TBuiltInResource* builtInResources, int defaultVersion, bool forwardCompatible, EShMessages messages,
673                Includer& includer)
674     {
675         return parse(builtInResources, defaultVersion, ENoProfile, false, forwardCompatible, messages, includer);
676     }
677
678     // NOTE: Doing just preprocessing to obtain a correct preprocessed shader string
679     // is not an officially supported or fully working path.
680     GLSLANG_EXPORT bool preprocess(
681         const TBuiltInResource* builtInResources, int defaultVersion,
682         EProfile defaultProfile, bool forceDefaultVersionAndProfile,
683         bool forwardCompatible, EShMessages message, std::string* outputString,
684         Includer& includer);
685
686     GLSLANG_EXPORT const char* getInfoLog();
687     GLSLANG_EXPORT const char* getInfoDebugLog();
688     EShLanguage getStage() const { return stage; }
689     TIntermediate* getIntermediate() const { return intermediate; }
690
691 protected:
692     TPoolAllocator* pool;
693     EShLanguage stage;
694     TCompiler* compiler;
695     TIntermediate* intermediate;
696     TInfoSink* infoSink;
697     // strings and lengths follow the standard for glShaderSource:
698     //     strings is an array of numStrings pointers to string data.
699     //     lengths can be null, but if not it is an array of numStrings
700     //         integers containing the length of the associated strings.
701     //         if lengths is null or lengths[n] < 0  the associated strings[n] is
702     //         assumed to be null-terminated.
703     // stringNames is the optional names for all the strings. If stringNames
704     // is null, then none of the strings has name. If a certain element in
705     // stringNames is null, then the corresponding string does not have name.
706     const char* const* strings;      // explicit code to compile, see previous comment
707     const int* lengths;
708     const char* const* stringNames;
709     int numStrings;                  // size of the above arrays
710     const char* preamble;            // string of implicit code to compile before the explicitly provided code
711
712     // a function in the source string can be renamed FROM this TO the name given in setEntryPoint.
713     std::string sourceEntryPointName;
714
715     TEnvironment environment;
716
717     friend class TProgram;
718
719 private:
720     TShader& operator=(TShader&);
721 };
722
723 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
724
725 //
726 // A reflection database and its interface, consistent with the OpenGL API reflection queries.
727 //
728
729 // Data needed for just a single object at the granularity exchanged by the reflection API
730 class TObjectReflection {
731 public:
732     GLSLANG_EXPORT TObjectReflection(const std::string& pName, const TType& pType, int pOffset, int pGLDefineType, int pSize, int pIndex);
733
734     const TType* getType() const { return type; }
735     GLSLANG_EXPORT int getBinding() const;
736     GLSLANG_EXPORT void dump() const;
737     static TObjectReflection badReflection() { return TObjectReflection(); }
738
739     std::string name;
740     int offset;
741     int glDefineType;
742     int size;                   // data size in bytes for a block, array size for a (non-block) object that's an array
743     int index;
744     int counterIndex;
745     int numMembers;
746     int arrayStride;            // stride of an array variable
747     int topLevelArraySize;      // size of the top-level variable in a storage buffer member
748     int topLevelArrayStride;    // stride of the top-level variable in a storage buffer member
749     EShLanguageMask stages;
750
751 protected:
752     TObjectReflection()
753         : offset(-1), glDefineType(-1), size(-1), index(-1), counterIndex(-1), numMembers(-1), arrayStride(0),
754           topLevelArrayStride(0), stages(EShLanguageMask(0)), type(nullptr)
755     {
756     }
757
758     const TType* type;
759 };
760
761 class  TReflection;
762 class  TIoMapper;
763 struct TVarEntryInfo;
764
765 // Allows to customize the binding layout after linking.
766 // All used uniform variables will invoke at least validateBinding.
767 // If validateBinding returned true then the other resolveBinding,
768 // resolveSet, and resolveLocation are invoked to resolve the binding
769 // and descriptor set index respectively.
770 //
771 // Invocations happen in a particular order:
772 // 1) all shader inputs
773 // 2) all shader outputs
774 // 3) all uniforms with binding and set already defined
775 // 4) all uniforms with binding but no set defined
776 // 5) all uniforms with set but no binding defined
777 // 6) all uniforms with no binding and no set defined
778 //
779 // mapIO will use this resolver in two phases. The first
780 // phase is a notification phase, calling the corresponging
781 // notifiy callbacks, this phase ends with a call to endNotifications.
782 // Phase two starts directly after the call to endNotifications
783 // and calls all other callbacks to validate and to get the
784 // bindings, sets, locations, component and color indices.
785 //
786 // NOTE: that still limit checks are applied to bindings and sets
787 // and may result in an error.
788 class TIoMapResolver
789 {
790 public:
791     virtual ~TIoMapResolver() {}
792
793     // Should return true if the resulting/current binding would be okay.
794     // Basic idea is to do aliasing binding checks with this.
795     virtual bool validateBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
796     // Should return a value >= 0 if the current binding should be overridden.
797     // Return -1 if the current binding (including no binding) should be kept.
798     virtual int resolveBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
799     // Should return a value >= 0 if the current set should be overridden.
800     // Return -1 if the current set (including no set) should be kept.
801     virtual int resolveSet(EShLanguage stage, TVarEntryInfo& ent) = 0;
802     // Should return a value >= 0 if the current location should be overridden.
803     // Return -1 if the current location (including no location) should be kept.
804     virtual int resolveUniformLocation(EShLanguage stage, TVarEntryInfo& ent) = 0;
805     // Should return true if the resulting/current setup would be okay.
806     // Basic idea is to do aliasing checks and reject invalid semantic names.
807     virtual bool validateInOut(EShLanguage stage, TVarEntryInfo& ent) = 0;
808     // Should return a value >= 0 if the current location should be overridden.
809     // Return -1 if the current location (including no location) should be kept.
810     virtual int resolveInOutLocation(EShLanguage stage, TVarEntryInfo& ent) = 0;
811     // Should return a value >= 0 if the current component index should be overridden.
812     // Return -1 if the current component index (including no index) should be kept.
813     virtual int resolveInOutComponent(EShLanguage stage, TVarEntryInfo& ent) = 0;
814     // Should return a value >= 0 if the current color index should be overridden.
815     // Return -1 if the current color index (including no index) should be kept.
816     virtual int resolveInOutIndex(EShLanguage stage, TVarEntryInfo& ent) = 0;
817     // Notification of a uniform variable
818     virtual void notifyBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
819     // Notification of a in or out variable
820     virtual void notifyInOut(EShLanguage stage, TVarEntryInfo& ent) = 0;
821     // Called by mapIO when it starts its notify pass for the given stage
822     virtual void beginNotifications(EShLanguage stage) = 0;
823     // Called by mapIO when it has finished the notify pass
824     virtual void endNotifications(EShLanguage stage) = 0;
825     // Called by mipIO when it starts its resolve pass for the given stage
826     virtual void beginResolve(EShLanguage stage) = 0;
827     // Called by mapIO when it has finished the resolve pass
828     virtual void endResolve(EShLanguage stage) = 0;
829     // Called by mapIO when it starts its symbol collect for teh given stage
830     virtual void beginCollect(EShLanguage stage) = 0;
831     // Called by mapIO when it has finished the symbol collect
832     virtual void endCollect(EShLanguage stage) = 0;
833     // Called by TSlotCollector to resolve storage locations or bindings
834     virtual void reserverStorageSlot(TVarEntryInfo& ent, TInfoSink& infoSink) = 0;
835     // Called by TSlotCollector to resolve resource locations or bindings
836     virtual void reserverResourceSlot(TVarEntryInfo& ent, TInfoSink& infoSink) = 0;
837     // Called by mapIO.addStage to set shader stage mask to mark a stage be added to this pipeline
838     virtual void addStage(EShLanguage stage, TIntermediate& stageIntermediate) = 0;
839 };
840
841 #endif // !GLSLANG_WEB && !GLSLANG_ANGLE
842
843 // Make one TProgram per set of shaders that will get linked together.  Add all
844 // the shaders that are to be linked together.  After calling shader.parse()
845 // for all shaders, call link().
846 //
847 // N.B.: Destruct a linked program *before* destructing the shaders linked into it.
848 //
849 class TProgram {
850 public:
851     GLSLANG_EXPORT TProgram();
852     GLSLANG_EXPORT virtual ~TProgram();
853     void addShader(TShader* shader) { stages[shader->stage].push_back(shader); }
854     std::list<TShader*>& getShaders(EShLanguage stage) { return stages[stage]; }
855     // Link Validation interface
856     GLSLANG_EXPORT bool link(EShMessages);
857     GLSLANG_EXPORT const char* getInfoLog();
858     GLSLANG_EXPORT const char* getInfoDebugLog();
859
860     TIntermediate* getIntermediate(EShLanguage stage) const { return intermediate[stage]; }
861
862 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
863
864     // Reflection Interface
865
866     // call first, to do liveness analysis, index mapping, etc.; returns false on failure
867     GLSLANG_EXPORT bool buildReflection(int opts = EShReflectionDefault);
868     GLSLANG_EXPORT unsigned getLocalSize(int dim) const;                  // return dim'th local size
869     GLSLANG_EXPORT int getReflectionIndex(const char *name) const;
870     GLSLANG_EXPORT int getReflectionPipeIOIndex(const char* name, const bool inOrOut) const;
871     GLSLANG_EXPORT int getNumUniformVariables() const;
872     GLSLANG_EXPORT const TObjectReflection& getUniform(int index) const;
873     GLSLANG_EXPORT int getNumUniformBlocks() const;
874     GLSLANG_EXPORT const TObjectReflection& getUniformBlock(int index) const;
875     GLSLANG_EXPORT int getNumPipeInputs() const;
876     GLSLANG_EXPORT const TObjectReflection& getPipeInput(int index) const;
877     GLSLANG_EXPORT int getNumPipeOutputs() const;
878     GLSLANG_EXPORT const TObjectReflection& getPipeOutput(int index) const;
879     GLSLANG_EXPORT int getNumBufferVariables() const;
880     GLSLANG_EXPORT const TObjectReflection& getBufferVariable(int index) const;
881     GLSLANG_EXPORT int getNumBufferBlocks() const;
882     GLSLANG_EXPORT const TObjectReflection& getBufferBlock(int index) const;
883     GLSLANG_EXPORT int getNumAtomicCounters() const;
884     GLSLANG_EXPORT const TObjectReflection& getAtomicCounter(int index) const;
885
886     // Legacy Reflection Interface - expressed in terms of above interface
887
888     // can be used for glGetProgramiv(GL_ACTIVE_UNIFORMS)
889     int getNumLiveUniformVariables() const             { return getNumUniformVariables(); }
890
891     // can be used for glGetProgramiv(GL_ACTIVE_UNIFORM_BLOCKS)
892     int getNumLiveUniformBlocks() const                { return getNumUniformBlocks(); }
893
894     // can be used for glGetProgramiv(GL_ACTIVE_ATTRIBUTES)
895     int getNumLiveAttributes() const                   { return getNumPipeInputs(); }
896
897     // can be used for glGetUniformIndices()
898     int getUniformIndex(const char *name) const        { return getReflectionIndex(name); }
899
900     int getPipeIOIndex(const char *name, const bool inOrOut) const
901                                                        { return getReflectionPipeIOIndex(name, inOrOut); }
902
903     // can be used for "name" part of glGetActiveUniform()
904     const char *getUniformName(int index) const        { return getUniform(index).name.c_str(); }
905
906     // returns the binding number
907     int getUniformBinding(int index) const             { return getUniform(index).getBinding(); }
908
909     // returns Shaders Stages where a Uniform is present
910     EShLanguageMask getUniformStages(int index) const  { return getUniform(index).stages; }
911
912     // can be used for glGetActiveUniformsiv(GL_UNIFORM_BLOCK_INDEX)
913     int getUniformBlockIndex(int index) const          { return getUniform(index).index; }
914
915     // can be used for glGetActiveUniformsiv(GL_UNIFORM_TYPE)
916     int getUniformType(int index) const                { return getUniform(index).glDefineType; }
917
918     // can be used for glGetActiveUniformsiv(GL_UNIFORM_OFFSET)
919     int getUniformBufferOffset(int index) const        { return getUniform(index).offset; }
920
921     // can be used for glGetActiveUniformsiv(GL_UNIFORM_SIZE)
922     int getUniformArraySize(int index) const           { return getUniform(index).size; }
923
924     // returns a TType*
925     const TType *getUniformTType(int index) const      { return getUniform(index).getType(); }
926
927     // can be used for glGetActiveUniformBlockName()
928     const char *getUniformBlockName(int index) const   { return getUniformBlock(index).name.c_str(); }
929
930     // can be used for glGetActiveUniformBlockiv(UNIFORM_BLOCK_DATA_SIZE)
931     int getUniformBlockSize(int index) const           { return getUniformBlock(index).size; }
932
933     // returns the block binding number
934     int getUniformBlockBinding(int index) const        { return getUniformBlock(index).getBinding(); }
935
936     // returns block index of associated counter.
937     int getUniformBlockCounterIndex(int index) const   { return getUniformBlock(index).counterIndex; }
938
939     // returns a TType*
940     const TType *getUniformBlockTType(int index) const { return getUniformBlock(index).getType(); }
941
942     // can be used for glGetActiveAttrib()
943     const char *getAttributeName(int index) const      { return getPipeInput(index).name.c_str(); }
944
945     // can be used for glGetActiveAttrib()
946     int getAttributeType(int index) const              { return getPipeInput(index).glDefineType; }
947
948     // returns a TType*
949     const TType *getAttributeTType(int index) const    { return getPipeInput(index).getType(); }
950
951     GLSLANG_EXPORT void dumpReflection();
952     // I/O mapping: apply base offsets and map live unbound variables
953     // If resolver is not provided it uses the previous approach
954     // and respects auto assignment and offsets.
955     GLSLANG_EXPORT bool mapIO(TIoMapResolver* pResolver = nullptr, TIoMapper* pIoMapper = nullptr);
956 #endif // !GLSLANG_WEB && !GLSLANG_ANGLE
957
958 protected:
959     GLSLANG_EXPORT bool linkStage(EShLanguage, EShMessages);
960     GLSLANG_EXPORT bool crossStageCheck(EShMessages);
961
962     TPoolAllocator* pool;
963     std::list<TShader*> stages[EShLangCount];
964     TIntermediate* intermediate[EShLangCount];
965     bool newedIntermediate[EShLangCount];      // track which intermediate were "new" versus reusing a singleton unit in a stage
966     TInfoSink* infoSink;
967 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
968     TReflection* reflection;
969 #endif
970     bool linked;
971
972 private:
973     TProgram(TProgram&);
974     TProgram& operator=(TProgram&);
975 };
976
977 } // end namespace glslang
978
979 #endif // _COMPILER_INTERFACE_INCLUDED_