1 //
2 // Copyright 2002 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 #ifndef GLSLANG_SHADERLANG_H_
7 #define GLSLANG_SHADERLANG_H_
8 
9 #include <stddef.h>
10 
11 #include "KHR/khrplatform.h"
12 
13 #include <array>
14 #include <map>
15 #include <set>
16 #include <string>
17 #include <vector>
18 
19 //
20 // This is the platform independent interface between an OGL driver
21 // and the shading language compiler.
22 //
23 
24 // Note: make sure to increment ANGLE_SH_VERSION when changing ShaderVars.h
25 #include "ShaderVars.h"
26 
27 // Version number for shader translation API.
28 // It is incremented every time the API changes.
29 #define ANGLE_SH_VERSION 261
30 
31 enum ShShaderSpec
32 {
33     SH_GLES2_SPEC,
34     SH_WEBGL_SPEC,
35 
36     SH_GLES3_SPEC,
37     SH_WEBGL2_SPEC,
38 
39     SH_GLES3_1_SPEC,
40     SH_WEBGL3_SPEC,
41 
42     SH_GLES3_2_SPEC,
43 
44     SH_GL_CORE_SPEC,
45     SH_GL_COMPATIBILITY_SPEC,
46 };
47 
48 enum ShShaderOutput
49 {
50     // ESSL output only supported in some configurations.
51     SH_ESSL_OUTPUT = 0x8B45,
52 
53     // GLSL output only supported in some configurations.
54     SH_GLSL_COMPATIBILITY_OUTPUT = 0x8B46,
55     // Note: GL introduced core profiles in 1.5.
56     SH_GLSL_130_OUTPUT      = 0x8B47,
57     SH_GLSL_140_OUTPUT      = 0x8B80,
58     SH_GLSL_150_CORE_OUTPUT = 0x8B81,
59     SH_GLSL_330_CORE_OUTPUT = 0x8B82,
60     SH_GLSL_400_CORE_OUTPUT = 0x8B83,
61     SH_GLSL_410_CORE_OUTPUT = 0x8B84,
62     SH_GLSL_420_CORE_OUTPUT = 0x8B85,
63     SH_GLSL_430_CORE_OUTPUT = 0x8B86,
64     SH_GLSL_440_CORE_OUTPUT = 0x8B87,
65     SH_GLSL_450_CORE_OUTPUT = 0x8B88,
66 
67     // Prefer using these to specify HLSL output type:
68     SH_HLSL_3_0_OUTPUT       = 0x8B48,  // D3D 9
69     SH_HLSL_4_1_OUTPUT       = 0x8B49,  // D3D 11
70     SH_HLSL_4_0_FL9_3_OUTPUT = 0x8B4A,  // D3D 11 feature level 9_3
71 
72     // Output SPIR-V for the Vulkan backend.
73     SH_SPIRV_VULKAN_OUTPUT = 0x8B4B,
74 
75     // Output SPIR-V to be cross compiled to Metal.
76     SH_SPIRV_METAL_OUTPUT = 0x8B4C,
77 
78     // Output for MSL
79     SH_MSL_METAL_OUTPUT = 0x8B4D,
80 };
81 
82 // Compile options.
83 // The Compile options type is defined in ShaderVars.h, to allow ANGLE to import the ShaderVars
84 // header without needing the ShaderLang header. This avoids some conflicts with glslang.
85 
86 const ShCompileOptions SH_VALIDATE               = 0;
87 const ShCompileOptions SH_VALIDATE_LOOP_INDEXING = UINT64_C(1) << 0;
88 const ShCompileOptions SH_INTERMEDIATE_TREE      = UINT64_C(1) << 1;
89 const ShCompileOptions SH_OBJECT_CODE            = UINT64_C(1) << 2;
90 const ShCompileOptions SH_VARIABLES              = UINT64_C(1) << 3;
91 const ShCompileOptions SH_LINE_DIRECTIVES        = UINT64_C(1) << 4;
92 const ShCompileOptions SH_SOURCE_PATH            = UINT64_C(1) << 5;
93 
94 // If requested, validates the AST after every transformation.  Useful for debugging.
95 const ShCompileOptions SH_VALIDATE_AST = UINT64_C(1) << 6;
96 
97 // Due to spec difference between GLSL 4.1 or lower and ESSL3, some platforms (for example, Mac OSX
98 // core profile) require a variable's "invariant"/"centroid" qualifiers to match between vertex and
99 // fragment shader. A simple solution to allow such shaders to link is to omit the two qualifiers.
100 // AMD driver in Linux requires invariant qualifier to match between vertex and fragment shaders,
101 // while ESSL3 disallows invariant qualifier in fragment shader and GLSL >= 4.2 doesn't require
102 // invariant qualifier to match between shaders. Remove invariant qualifier from vertex shader to
103 // workaround AMD driver bug.
104 // Note that the two flags take effect on ESSL3 input shaders translated to GLSL 4.1 or lower and to
105 // GLSL 4.2 or newer on Linux AMD.
106 // TODO(zmo): This is not a good long-term solution. Simply dropping these qualifiers may break some
107 // developers' content. A more complex workaround of dynamically generating, compiling, and
108 // re-linking shaders that use these qualifiers should be implemented.
109 const ShCompileOptions SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3 = UINT64_C(1) << 7;
110 
111 // This flag works around bug in Intel Mac drivers related to abs(i) where
112 // i is an integer.
113 const ShCompileOptions SH_EMULATE_ABS_INT_FUNCTION = UINT64_C(1) << 8;
114 
115 // Enforce the GLSL 1.017 Appendix A section 7 packing restrictions.
116 // This flag only enforces (and can only enforce) the packing
117 // restrictions for uniform variables in both vertex and fragment
118 // shaders. ShCheckVariablesWithinPackingLimits() lets embedders
119 // enforce the packing restrictions for varying variables during
120 // program link time.
121 const ShCompileOptions SH_ENFORCE_PACKING_RESTRICTIONS = UINT64_C(1) << 9;
122 
123 // This flag ensures all indirect (expression-based) array indexing
124 // is clamped to the bounds of the array. This ensures, for example,
125 // that you cannot read off the end of a uniform, whether an array
126 // vec234, or mat234 type.
127 const ShCompileOptions SH_CLAMP_INDIRECT_ARRAY_BOUNDS = UINT64_C(1) << 10;
128 
129 // This flag limits the complexity of an expression.
130 const ShCompileOptions SH_LIMIT_EXPRESSION_COMPLEXITY = UINT64_C(1) << 11;
131 
132 // This flag limits the depth of the call stack.
133 const ShCompileOptions SH_LIMIT_CALL_STACK_DEPTH = UINT64_C(1) << 12;
134 
135 // This flag initializes gl_Position to vec4(0,0,0,0) at the
136 // beginning of the vertex shader's main(), and has no effect in the
137 // fragment shader. It is intended as a workaround for drivers which
138 // incorrectly fail to link programs if gl_Position is not written.
139 const ShCompileOptions SH_INIT_GL_POSITION = UINT64_C(1) << 13;
140 
141 // This flag replaces
142 //   "a && b" with "a ? b : false",
143 //   "a || b" with "a ? true : b".
144 // This is to work around a MacOSX driver bug that |b| is executed
145 // independent of |a|'s value.
146 const ShCompileOptions SH_UNFOLD_SHORT_CIRCUIT = UINT64_C(1) << 14;
147 
148 // This flag initializes output variables to 0 at the beginning of main().
149 // It is to avoid undefined behaviors.
150 const ShCompileOptions SH_INIT_OUTPUT_VARIABLES = UINT64_C(1) << 15;
151 
152 // This flag scalarizes vec/ivec/bvec/mat constructor args.
153 // It is intended as a workaround for Linux/Mac driver bugs.
154 const ShCompileOptions SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS = UINT64_C(1) << 16;
155 
156 // This flag overwrites a struct name with a unique prefix.
157 // It is intended as a workaround for drivers that do not handle
158 // struct scopes correctly, including all Mac drivers and Linux AMD.
159 const ShCompileOptions SH_REGENERATE_STRUCT_NAMES = UINT64_C(1) << 17;
160 
161 // This flag works around bugs in Mac drivers related to do-while by
162 // transforming them into an other construct.
163 const ShCompileOptions SH_REWRITE_DO_WHILE_LOOPS = UINT64_C(1) << 18;
164 
165 // This flag works around a bug in the HLSL compiler optimizer that folds certain
166 // constant pow expressions incorrectly. Only applies to the HLSL back-end. It works
167 // by expanding the integer pow expressions into a series of multiplies.
168 const ShCompileOptions SH_EXPAND_SELECT_HLSL_INTEGER_POW_EXPRESSIONS = UINT64_C(1) << 19;
169 
170 // Flatten "#pragma STDGL invariant(all)" into the declarations of
171 // varying variables and built-in GLSL variables. This compiler
172 // option is enabled automatically when needed.
173 const ShCompileOptions SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL = UINT64_C(1) << 20;
174 
175 // Some drivers do not take into account the base level of the texture in the results of the
176 // HLSL GetDimensions builtin.  This flag instructs the compiler to manually add the base level
177 // offsetting.
178 const ShCompileOptions SH_HLSL_GET_DIMENSIONS_IGNORES_BASE_LEVEL = UINT64_C(1) << 21;
179 
180 // This flag works around an issue in translating GLSL function texelFetchOffset on
181 // INTEL drivers. It works by translating texelFetchOffset into texelFetch.
182 const ShCompileOptions SH_REWRITE_TEXELFETCHOFFSET_TO_TEXELFETCH = UINT64_C(1) << 22;
183 
184 // This flag works around condition bug of for and while loops in Intel Mac OSX drivers.
185 // Condition calculation is not correct. Rewrite it from "CONDITION" to "CONDITION && true".
186 const ShCompileOptions SH_ADD_AND_TRUE_TO_LOOP_CONDITION = UINT64_C(1) << 23;
187 
188 // This flag works around a bug in evaluating unary minus operator on integer on some INTEL
189 // drivers. It works by translating -(int) into ~(int) + 1.
190 const ShCompileOptions SH_REWRITE_INTEGER_UNARY_MINUS_OPERATOR = UINT64_C(1) << 24;
191 
192 // This flag works around a bug in evaluating isnan() on some INTEL D3D and Mac OSX drivers.
193 // It works by using an expression to emulate this function.
194 const ShCompileOptions SH_EMULATE_ISNAN_FLOAT_FUNCTION = UINT64_C(1) << 25;
195 
196 // This flag will use all uniforms of unused std140 and shared uniform blocks at the
197 // beginning of the vertex/fragment shader's main(). It is intended as a workaround for Mac
198 // drivers with shader version 4.10. In those drivers, they will treat unused
199 // std140 and shared uniform blocks' members as inactive. However, WebGL2.0 based on
200 // OpenGL ES3.0.4 requires all members of a named uniform block declared with a shared or std140
201 // layout qualifier to be considered active. The uniform block itself is also considered active.
202 const ShCompileOptions SH_USE_UNUSED_STANDARD_SHARED_BLOCKS = UINT64_C(1) << 26;
203 
204 // This flag works around a bug in unary minus operator on float numbers on Intel
205 // Mac OSX 10.11 drivers. It works by translating -float into 0.0 - float.
206 const ShCompileOptions SH_REWRITE_FLOAT_UNARY_MINUS_OPERATOR = UINT64_C(1) << 27;
207 
208 // This flag works around a bug in evaluating atan(y, x) on some NVIDIA OpenGL drivers.
209 // It works by using an expression to emulate this function.
210 const ShCompileOptions SH_EMULATE_ATAN2_FLOAT_FUNCTION = UINT64_C(1) << 28;
211 
212 // Set to initialize uninitialized local and global temporary variables. Should only be used with
213 // GLSL output. In HLSL output variables are initialized regardless of if this flag is set.
214 const ShCompileOptions SH_INITIALIZE_UNINITIALIZED_LOCALS = UINT64_C(1) << 29;
215 
216 // The flag modifies the shader in the following way:
217 // Every occurrence of gl_InstanceID is replaced by the global temporary variable InstanceID.
218 // Every occurrence of gl_ViewID_OVR is replaced by the varying variable ViewID_OVR.
219 // At the beginning of the body of main() in a vertex shader the following initializers are added:
220 // ViewID_OVR = uint(gl_InstanceID) % num_views;
221 // InstanceID = gl_InstanceID / num_views;
222 // ViewID_OVR is added as a varying variable to both the vertex and fragment shaders.
223 const ShCompileOptions SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW = UINT64_C(1) << 30;
224 
225 // With the flag enabled the GLSL/ESSL vertex shader is modified to include code for viewport
226 // selection in the following way:
227 // - Code to enable the extension ARB_shader_viewport_layer_array/NV_viewport_array2 is included.
228 // - Code to select the viewport index or layer is inserted at the beginning of main after
229 // ViewID_OVR's initialization.
230 // - A declaration of the uniform multiviewBaseViewLayerIndex.
231 // Note: The SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW flag also has to be enabled to have the
232 // temporary variable ViewID_OVR declared and initialized.
233 const ShCompileOptions SH_SELECT_VIEW_IN_NV_GLSL_VERTEX_SHADER = UINT64_C(1) << 31;
234 
235 // If the flag is enabled, gl_PointSize is clamped to the maximum point size specified in
236 // ShBuiltInResources in vertex shaders.
237 const ShCompileOptions SH_CLAMP_POINT_SIZE = UINT64_C(1) << 32;
238 
239 // Turn some arithmetic operations that operate on a float vector-scalar pair into vector-vector
240 // operations. This is done recursively. Some scalar binary operations inside vector constructors
241 // are also turned into vector operations.
242 //
243 // This is targeted to work around a bug in NVIDIA OpenGL drivers that was reproducible on NVIDIA
244 // driver version 387.92. It works around the most common occurrences of the bug.
245 const ShCompileOptions SH_REWRITE_VECTOR_SCALAR_ARITHMETIC = UINT64_C(1) << 33;
246 
247 // Don't use loops to initialize uninitialized variables. Only has an effect if some kind of
248 // variable initialization is turned on.
249 const ShCompileOptions SH_DONT_USE_LOOPS_TO_INITIALIZE_VARIABLES = UINT64_C(1) << 34;
250 
251 // Don't use D3D constant register zero when allocating space for uniforms. This is targeted to work
252 // around a bug in NVIDIA D3D driver version 388.59 where in very specific cases the driver would
253 // not handle constant register zero correctly. Only has an effect on HLSL translation.
254 const ShCompileOptions SH_SKIP_D3D_CONSTANT_REGISTER_ZERO = UINT64_C(1) << 35;
255 
256 // Clamp gl_FragDepth to the range [0.0, 1.0] in case it is statically used.
257 const ShCompileOptions SH_CLAMP_FRAG_DEPTH = UINT64_C(1) << 36;
258 
259 // Rewrite expressions like "v.x = z = expression;". Works around a bug in NVIDIA OpenGL drivers
260 // prior to version 397.31.
261 const ShCompileOptions SH_REWRITE_REPEATED_ASSIGN_TO_SWIZZLED = UINT64_C(1) << 37;
262 
263 // Rewrite gl_DrawID as a uniform int
264 const ShCompileOptions SH_EMULATE_GL_DRAW_ID = UINT64_C(1) << 38;
265 
266 // This flag initializes shared variables to 0.
267 // It is to avoid ompute shaders being able to read undefined values that could be coming from
268 // another webpage/application.
269 const ShCompileOptions SH_INIT_SHARED_VARIABLES = UINT64_C(1) << 39;
270 
271 // Forces the value returned from an atomic operations to be always be resolved. This is targeted to
272 // workaround a bug in NVIDIA D3D driver where the return value from
273 // RWByteAddressBuffer.InterlockedAdd does not get resolved when used in the .yzw components of a
274 // RWByteAddressBuffer.Store operation. Only has an effect on HLSL translation.
275 // http://anglebug.com/3246
276 const ShCompileOptions SH_FORCE_ATOMIC_VALUE_RESOLUTION = UINT64_C(1) << 40;
277 
278 // Rewrite gl_BaseVertex and gl_BaseInstance as uniform int
279 const ShCompileOptions SH_EMULATE_GL_BASE_VERTEX_BASE_INSTANCE = UINT64_C(1) << 41;
280 
281 // Emulate seamful cube map sampling for OpenGL ES2.0.  Currently only applies to the Vulkan
282 // backend, as is done after samplers are moved out of structs.  Can likely be made to work on
283 // the other backends as well.
284 const ShCompileOptions SH_EMULATE_SEAMFUL_CUBE_MAP_SAMPLING = UINT64_C(1) << 42;
285 
286 // This flag controls how to translate WEBGL_video_texture sampling function.
287 const ShCompileOptions SH_TAKE_VIDEO_TEXTURE_AS_EXTERNAL_OES = UINT64_C(1) << 43;
288 
289 // This flag works around a inconsistent behavior in Mac AMD driver where gl_VertexID doesn't
290 // include base vertex value. It replaces gl_VertexID with (gl_VertexID + angle_BaseVertex)
291 // when angle_BaseVertex is available.
292 const ShCompileOptions SH_ADD_BASE_VERTEX_TO_VERTEX_ID = UINT64_C(1) << 44;
293 
294 // This works around the dynamic lvalue indexing of swizzled vectors on various platforms.
295 const ShCompileOptions SH_REMOVE_DYNAMIC_INDEXING_OF_SWIZZLED_VECTOR = UINT64_C(1) << 45;
296 
297 // This flag works around a slow fxc compile performance issue with dynamic uniform indexing.
298 const ShCompileOptions SH_ALLOW_TRANSLATE_UNIFORM_BLOCK_TO_STRUCTUREDBUFFER = UINT64_C(1) << 46;
299 
300 // This flag indicates whether Bresenham line raster emulation code should be generated.  This
301 // emulation is necessary if the backend uses a differnet algorithm to draw lines.  Currently only
302 // implemented for the Vulkan backend.
303 const ShCompileOptions SH_ADD_BRESENHAM_LINE_RASTER_EMULATION = UINT64_C(1) << 47;
304 
305 // This flag allows disabling ARB_texture_rectangle on a per-compile basis. This is necessary
306 // for WebGL contexts becuase ARB_texture_rectangle may be necessary for the WebGL implementation
307 // internally but shouldn't be exposed to WebGL user code.
308 const ShCompileOptions SH_DISABLE_ARB_TEXTURE_RECTANGLE = UINT64_C(1) << 48;
309 
310 // This flag works around a driver bug by rewriting uses of row-major matrices
311 // as column-major in ESSL 3.00 and greater shaders.
312 const ShCompileOptions SH_REWRITE_ROW_MAJOR_MATRICES = UINT64_C(1) << 49;
313 
314 // Drop any explicit precision qualifiers from shader.
315 const ShCompileOptions SH_IGNORE_PRECISION_QUALIFIERS = UINT64_C(1) << 50;
316 
317 // Allow compiler to do early fragment tests as an optimization.
318 const ShCompileOptions SH_EARLY_FRAGMENT_TESTS_OPTIMIZATION = UINT64_C(1) << 51;
319 
320 // Allow compiler to insert Android pre-rotation code.
321 const ShCompileOptions SH_ADD_PRE_ROTATION = UINT64_C(1) << 52;
322 
323 const ShCompileOptions SH_FORCE_SHADER_PRECISION_HIGHP_TO_MEDIUMP = UINT64_C(1) << 53;
324 
325 // Allow compiler to use specialization constant to do pre-rotation and y flip.
326 const ShCompileOptions SH_USE_SPECIALIZATION_CONSTANT = UINT64_C(1) << 54;
327 
328 // Ask compiler to generate Vulkan transform feedback emulation support code.
329 const ShCompileOptions SH_ADD_VULKAN_XFB_EMULATION_SUPPORT_CODE = UINT64_C(1) << 55;
330 
331 // Ask compiler to generate Vulkan transform feedback support code when using the
332 // VK_EXT_transform_feedback extension.
333 const ShCompileOptions SH_ADD_VULKAN_XFB_EXTENSION_SUPPORT_CODE = UINT64_C(1) << 56;
334 
335 // This flag initializes fragment shader's output variables to zero at the beginning of the fragment
336 // shader's main(). It is intended as a workaround for drivers which get context lost if
337 // gl_FragColor is not written.
338 const ShCompileOptions SH_INIT_FRAGMENT_OUTPUT_VARIABLES = UINT64_C(1) << 57;
339 
340 // Transitory flag to select between producing SPIR-V directly vs using glslang.  Ignored in
341 // non-assert-enabled builds to avoid increasing ANGLE's binary size while both generators coexist.
342 const ShCompileOptions SH_GENERATE_SPIRV_DIRECTLY = UINT64_C(1) << 58;
343 
344 // Generate workarounds in SPIR-V for buggy code.
345 const ShCompileOptions SH_GENERATE_SPIRV_WORKAROUNDS = UINT64_C(1) << 59;
346 
347 // The 64 bits hash function. The first parameter is the input string; the
348 // second parameter is the string length.
349 using ShHashFunction64 = khronos_uint64_t (*)(const char *, size_t);
350 
351 //
352 // Implementation dependent built-in resources (constants and extensions).
353 // The names for these resources has been obtained by stripping gl_/GL_.
354 //
355 struct ShBuiltInResources
356 {
357     // Constants.
358     int MaxVertexAttribs;
359     int MaxVertexUniformVectors;
360     int MaxVaryingVectors;
361     int MaxVertexTextureImageUnits;
362     int MaxCombinedTextureImageUnits;
363     int MaxTextureImageUnits;
364     int MaxFragmentUniformVectors;
365     int MaxDrawBuffers;
366 
367     // Extensions.
368     // Set to 1 to enable the extension, else 0.
369     int OES_standard_derivatives;
370     int OES_EGL_image_external;
371     int OES_EGL_image_external_essl3;
372     int NV_EGL_stream_consumer_external;
373     int ARB_texture_rectangle;
374     int EXT_blend_func_extended;
375     int EXT_draw_buffers;
376     int EXT_frag_depth;
377     int EXT_shader_texture_lod;
378     int WEBGL_debug_shader_precision;
379     int EXT_shader_framebuffer_fetch;
380     int EXT_shader_framebuffer_fetch_non_coherent;
381     int NV_shader_framebuffer_fetch;
382     int NV_shader_noperspective_interpolation;
383     int ARM_shader_framebuffer_fetch;
384     int OVR_multiview;
385     int OVR_multiview2;
386     int EXT_multisampled_render_to_texture;
387     int EXT_multisampled_render_to_texture2;
388     int EXT_YUV_target;
389     int EXT_geometry_shader;
390     int OES_geometry_shader;
391     int OES_shader_io_blocks;
392     int EXT_shader_io_blocks;
393     int EXT_gpu_shader5;
394     int EXT_shader_non_constant_global_initializers;
395     int OES_texture_storage_multisample_2d_array;
396     int OES_texture_3D;
397     int ANGLE_texture_multisample;
398     int ANGLE_multi_draw;
399     int ANGLE_base_vertex_base_instance;
400     int WEBGL_video_texture;
401     int APPLE_clip_distance;
402     int OES_texture_cube_map_array;
403     int EXT_texture_cube_map_array;
404     int EXT_shadow_samplers;
405     int OES_shader_multisample_interpolation;
406     int OES_shader_image_atomic;
407     int EXT_tessellation_shader;
408     int OES_texture_buffer;
409     int EXT_texture_buffer;
410     int OES_sample_variables;
411     int EXT_clip_cull_distance;
412 
413     // Set to 1 to enable replacing GL_EXT_draw_buffers #extension directives
414     // with GL_NV_draw_buffers in ESSL output. This flag can be used to emulate
415     // EXT_draw_buffers by using it in combination with GLES3.0 glDrawBuffers
416     // function. This applies to Tegra K1 devices.
417     int NV_draw_buffers;
418 
419     // Set to 1 if highp precision is supported in the ESSL 1.00 version of the
420     // fragment language. Does not affect versions of the language where highp
421     // support is mandatory.
422     // Default is 0.
423     int FragmentPrecisionHigh;
424 
425     // GLSL ES 3.0 constants.
426     int MaxVertexOutputVectors;
427     int MaxFragmentInputVectors;
428     int MinProgramTexelOffset;
429     int MaxProgramTexelOffset;
430 
431     // Extension constants.
432 
433     // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT for OpenGL ES output context.
434     // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS for OpenGL output context.
435     // GLES SL version 100 gl_MaxDualSourceDrawBuffersEXT value for EXT_blend_func_extended.
436     int MaxDualSourceDrawBuffers;
437 
438     // Value of GL_MAX_VIEWS_OVR.
439     int MaxViewsOVR;
440 
441     // Name Hashing.
442     // Set a 64 bit hash function to enable user-defined name hashing.
443     // Default is NULL.
444     ShHashFunction64 HashFunction;
445 
446     // The maximum complexity an expression can be when SH_LIMIT_EXPRESSION_COMPLEXITY is turned on.
447     int MaxExpressionComplexity;
448 
449     // The maximum depth a call stack can be.
450     int MaxCallStackDepth;
451 
452     // The maximum number of parameters a function can have when SH_LIMIT_EXPRESSION_COMPLEXITY is
453     // turned on.
454     int MaxFunctionParameters;
455 
456     // GLES 3.1 constants
457 
458     // texture gather offset constraints.
459     int MinProgramTextureGatherOffset;
460     int MaxProgramTextureGatherOffset;
461 
462     // maximum number of available image units
463     int MaxImageUnits;
464 
465     // OES_sample_variables constant
466     // maximum number of available samples
467     int MaxSamples;
468 
469     // maximum number of image uniforms in a vertex shader
470     int MaxVertexImageUniforms;
471 
472     // maximum number of image uniforms in a fragment shader
473     int MaxFragmentImageUniforms;
474 
475     // maximum number of image uniforms in a compute shader
476     int MaxComputeImageUniforms;
477 
478     // maximum total number of image uniforms in a program
479     int MaxCombinedImageUniforms;
480 
481     // maximum number of uniform locations
482     int MaxUniformLocations;
483 
484     // maximum number of ssbos and images in a shader
485     int MaxCombinedShaderOutputResources;
486 
487     // maximum number of groups in each dimension
488     std::array<int, 3> MaxComputeWorkGroupCount;
489     // maximum number of threads per work group in each dimension
490     std::array<int, 3> MaxComputeWorkGroupSize;
491 
492     // maximum number of total uniform components
493     int MaxComputeUniformComponents;
494 
495     // maximum number of texture image units in a compute shader
496     int MaxComputeTextureImageUnits;
497 
498     // maximum number of atomic counters in a compute shader
499     int MaxComputeAtomicCounters;
500 
501     // maximum number of atomic counter buffers in a compute shader
502     int MaxComputeAtomicCounterBuffers;
503 
504     // maximum number of atomic counters in a vertex shader
505     int MaxVertexAtomicCounters;
506 
507     // maximum number of atomic counters in a fragment shader
508     int MaxFragmentAtomicCounters;
509 
510     // maximum number of atomic counters in a program
511     int MaxCombinedAtomicCounters;
512 
513     // maximum binding for an atomic counter
514     int MaxAtomicCounterBindings;
515 
516     // maximum number of atomic counter buffers in a vertex shader
517     int MaxVertexAtomicCounterBuffers;
518 
519     // maximum number of atomic counter buffers in a fragment shader
520     int MaxFragmentAtomicCounterBuffers;
521 
522     // maximum number of atomic counter buffers in a program
523     int MaxCombinedAtomicCounterBuffers;
524 
525     // maximum number of buffer object storage in machine units
526     int MaxAtomicCounterBufferSize;
527 
528     // maximum number of uniform block bindings
529     int MaxUniformBufferBindings;
530 
531     // maximum number of shader storage buffer bindings
532     int MaxShaderStorageBufferBindings;
533 
534     // maximum point size (higher limit from ALIASED_POINT_SIZE_RANGE)
535     float MaxPointSize;
536 
537     // EXT_geometry_shader constants
538     int MaxGeometryUniformComponents;
539     int MaxGeometryUniformBlocks;
540     int MaxGeometryInputComponents;
541     int MaxGeometryOutputComponents;
542     int MaxGeometryOutputVertices;
543     int MaxGeometryTotalOutputComponents;
544     int MaxGeometryTextureImageUnits;
545     int MaxGeometryAtomicCounterBuffers;
546     int MaxGeometryAtomicCounters;
547     int MaxGeometryShaderStorageBlocks;
548     int MaxGeometryShaderInvocations;
549     int MaxGeometryImageUniforms;
550 
551     // EXT_tessellation_shader constants
552     int MaxTessControlInputComponents;
553     int MaxTessControlOutputComponents;
554     int MaxTessControlTextureImageUnits;
555     int MaxTessControlUniformComponents;
556     int MaxTessControlTotalOutputComponents;
557     int MaxTessControlImageUniforms;
558     int MaxTessControlAtomicCounters;
559     int MaxTessControlAtomicCounterBuffers;
560 
561     int MaxTessPatchComponents;
562     int MaxPatchVertices;
563     int MaxTessGenLevel;
564 
565     int MaxTessEvaluationInputComponents;
566     int MaxTessEvaluationOutputComponents;
567     int MaxTessEvaluationTextureImageUnits;
568     int MaxTessEvaluationUniformComponents;
569     int MaxTessEvaluationImageUniforms;
570     int MaxTessEvaluationAtomicCounters;
571     int MaxTessEvaluationAtomicCounterBuffers;
572 
573     // Subpixel bits used in rasterization.
574     int SubPixelBits;
575 
576     // APPLE_clip_distance/EXT_clip_cull_distance constant
577     int MaxClipDistances;
578     int MaxCullDistances;
579     int MaxCombinedClipAndCullDistances;
580 
581     // Direct-to-metal backend constants:
582 
583     // Binding index for driver uniforms:
584     int DriverUniformsBindingIndex;
585     // Binding index for default uniforms:
586     int DefaultUniformsBindingIndex;
587     // Binding index for UBO's argument buffer
588     int UBOArgumentBufferBindingIndex;
589 };
590 
591 //
592 // ShHandle held by but opaque to the driver.  It is allocated,
593 // managed, and de-allocated by the compiler. Its contents
594 // are defined by and used by the compiler.
595 //
596 // If handle creation fails, 0 will be returned.
597 //
598 using ShHandle = void *;
599 
600 namespace sh
601 {
602 using BinaryBlob = std::vector<uint32_t>;
603 
604 //
605 // Driver must call this first, once, before doing any other compiler operations.
606 // If the function succeeds, the return value is true, else false.
607 //
608 bool Initialize();
609 //
610 // Driver should call this at shutdown.
611 // If the function succeeds, the return value is true, else false.
612 //
613 bool Finalize();
614 
615 //
616 // Initialize built-in resources with minimum expected values.
617 // Parameters:
618 // resources: The object to initialize. Will be comparable with memcmp.
619 //
620 void InitBuiltInResources(ShBuiltInResources *resources);
621 
622 //
623 // Returns the a concatenated list of the items in ShBuiltInResources as a null-terminated string.
624 // This function must be updated whenever ShBuiltInResources is changed.
625 // Parameters:
626 // handle: Specifies the handle of the compiler to be used.
627 const std::string &GetBuiltInResourcesString(const ShHandle handle);
628 
629 //
630 // Driver calls these to create and destroy compiler objects.
631 //
632 // Returns the handle of constructed compiler, null if the requested compiler is not supported.
633 // Parameters:
634 // type: Specifies the type of shader - GL_FRAGMENT_SHADER or GL_VERTEX_SHADER.
635 // spec: Specifies the language spec the compiler must conform to - SH_GLES2_SPEC or SH_WEBGL_SPEC.
636 // output: Specifies the output code type - for example SH_ESSL_OUTPUT, SH_GLSL_OUTPUT,
637 //         SH_HLSL_3_0_OUTPUT or SH_HLSL_4_1_OUTPUT. Note: Each output type may only
638 //         be supported in some configurations.
639 // resources: Specifies the built-in resources.
640 ShHandle ConstructCompiler(sh::GLenum type,
641                            ShShaderSpec spec,
642                            ShShaderOutput output,
643                            const ShBuiltInResources *resources);
644 void Destruct(ShHandle handle);
645 
646 //
647 // Compiles the given shader source.
648 // If the function succeeds, the return value is true, else false.
649 // Parameters:
650 // handle: Specifies the handle of compiler to be used.
651 // shaderStrings: Specifies an array of pointers to null-terminated strings containing the shader
652 // source code.
653 // numStrings: Specifies the number of elements in shaderStrings array.
654 // compileOptions: A mask containing the following parameters:
655 // SH_VALIDATE: Validates shader to ensure that it conforms to the spec
656 //              specified during compiler construction.
657 // SH_VALIDATE_LOOP_INDEXING: Validates loop and indexing in the shader to
658 //                            ensure that they do not exceed the minimum
659 //                            functionality mandated in GLSL 1.0 spec,
660 //                            Appendix A, Section 4 and 5.
661 //                            There is no need to specify this parameter when
662 //                            compiling for WebGL - it is implied.
663 // SH_INTERMEDIATE_TREE: Writes intermediate tree to info log.
664 //                       Can be queried by calling sh::GetInfoLog().
665 // SH_OBJECT_CODE: Translates intermediate tree to glsl or hlsl shader, or SPIR-V binary.
666 //                 Can be queried by calling sh::GetObjectCode().
667 // SH_VARIABLES: Extracts attributes, uniforms, and varyings.
668 //               Can be queried by calling ShGetVariableInfo().
669 //
670 bool Compile(const ShHandle handle,
671              const char *const shaderStrings[],
672              size_t numStrings,
673              ShCompileOptions compileOptions);
674 
675 // Clears the results from the previous compilation.
676 void ClearResults(const ShHandle handle);
677 
678 // Return the version of the shader language.
679 int GetShaderVersion(const ShHandle handle);
680 
681 // Return the currently set language output type.
682 ShShaderOutput GetShaderOutputType(const ShHandle handle);
683 
684 // Returns null-terminated information log for a compiled shader.
685 // Parameters:
686 // handle: Specifies the compiler
687 const std::string &GetInfoLog(const ShHandle handle);
688 
689 // Returns null-terminated object code for a compiled shader.  Only valid for output types that
690 // generate human-readable code (GLSL, ESSL or HLSL).
691 // Parameters:
692 // handle: Specifies the compiler
693 const std::string &GetObjectCode(const ShHandle handle);
694 
695 // Returns object binary blob for a compiled shader.  Only valid for output types that
696 // generate binary blob (SPIR-V).
697 // Parameters:
698 // handle: Specifies the compiler
699 const BinaryBlob &GetObjectBinaryBlob(const ShHandle handle);
700 
701 // Returns a (original_name, hash) map containing all the user defined names in the shader,
702 // including variable names, function names, struct names, and struct field names.
703 // Parameters:
704 // handle: Specifies the compiler
705 const std::map<std::string, std::string> *GetNameHashingMap(const ShHandle handle);
706 
707 // Shader variable inspection.
708 // Returns a pointer to a list of variables of the designated type.
709 // (See ShaderVars.h for type definitions, included above)
710 // Returns NULL on failure.
711 // Parameters:
712 // handle: Specifies the compiler
713 const std::vector<sh::ShaderVariable> *GetUniforms(const ShHandle handle);
714 const std::vector<sh::ShaderVariable> *GetVaryings(const ShHandle handle);
715 const std::vector<sh::ShaderVariable> *GetInputVaryings(const ShHandle handle);
716 const std::vector<sh::ShaderVariable> *GetOutputVaryings(const ShHandle handle);
717 const std::vector<sh::ShaderVariable> *GetAttributes(const ShHandle handle);
718 const std::vector<sh::ShaderVariable> *GetOutputVariables(const ShHandle handle);
719 const std::vector<sh::InterfaceBlock> *GetInterfaceBlocks(const ShHandle handle);
720 const std::vector<sh::InterfaceBlock> *GetUniformBlocks(const ShHandle handle);
721 const std::vector<sh::InterfaceBlock> *GetShaderStorageBlocks(const ShHandle handle);
722 sh::WorkGroupSize GetComputeShaderLocalGroupSize(const ShHandle handle);
723 // Returns the number of views specified through the num_views layout qualifier. If num_views is
724 // not set, the function returns -1.
725 int GetVertexShaderNumViews(const ShHandle handle);
726 // Returns true if compiler has injected instructions for early fragment tests as an optimization
727 bool HasEarlyFragmentTestsOptimization(const ShHandle handle);
728 
729 // Returns specialization constant usage bits
730 uint32_t GetShaderSpecConstUsageBits(const ShHandle handle);
731 
732 // Returns true if the passed in variables pack in maxVectors followingthe packing rules from the
733 // GLSL 1.017 spec, Appendix A, section 7.
734 // Returns false otherwise. Also look at the SH_ENFORCE_PACKING_RESTRICTIONS
735 // flag above.
736 // Parameters:
737 // maxVectors: the available rows of registers.
738 // variables: an array of variables.
739 bool CheckVariablesWithinPackingLimits(int maxVectors,
740                                        const std::vector<sh::ShaderVariable> &variables);
741 
742 // Gives the compiler-assigned register for a shader storage block.
743 // The method writes the value to the output variable "indexOut".
744 // Returns true if it found a valid shader storage block, false otherwise.
745 // Parameters:
746 // handle: Specifies the compiler
747 // shaderStorageBlockName: Specifies the shader storage block
748 // indexOut: output variable that stores the assigned register
749 bool GetShaderStorageBlockRegister(const ShHandle handle,
750                                    const std::string &shaderStorageBlockName,
751                                    unsigned int *indexOut);
752 
753 // Gives the compiler-assigned register for a uniform block.
754 // The method writes the value to the output variable "indexOut".
755 // Returns true if it found a valid uniform block, false otherwise.
756 // Parameters:
757 // handle: Specifies the compiler
758 // uniformBlockName: Specifies the uniform block
759 // indexOut: output variable that stores the assigned register
760 bool GetUniformBlockRegister(const ShHandle handle,
761                              const std::string &uniformBlockName,
762                              unsigned int *indexOut);
763 
764 bool ShouldUniformBlockUseStructuredBuffer(const ShHandle handle,
765                                            const std::string &uniformBlockName);
766 const std::set<std::string> *GetSlowCompilingUniformBlockSet(const ShHandle handle);
767 
768 // Gives a map from uniform names to compiler-assigned registers in the default uniform block.
769 // Note that the map contains also registers of samplers that have been extracted from structs.
770 const std::map<std::string, unsigned int> *GetUniformRegisterMap(const ShHandle handle);
771 
772 // Sampler, image and atomic counters share registers(t type and u type),
773 // GetReadonlyImage2DRegisterIndex and GetImage2DRegisterIndex return the first index into
774 // a range of reserved registers for image2D/iimage2D/uimage2D variables.
775 // Parameters: handle: Specifies the compiler
776 unsigned int GetReadonlyImage2DRegisterIndex(const ShHandle handle);
777 unsigned int GetImage2DRegisterIndex(const ShHandle handle);
778 
779 // The method records these used function names related with image2D/iimage2D/uimage2D, these
780 // functions will be dynamically generated.
781 // Parameters:
782 // handle: Specifies the compiler
783 const std::set<std::string> *GetUsedImage2DFunctionNames(const ShHandle handle);
784 
785 bool HasValidGeometryShaderInputPrimitiveType(const ShHandle handle);
786 bool HasValidGeometryShaderOutputPrimitiveType(const ShHandle handle);
787 bool HasValidGeometryShaderMaxVertices(const ShHandle handle);
788 bool HasValidTessGenMode(const ShHandle handle);
789 bool HasValidTessGenSpacing(const ShHandle handle);
790 bool HasValidTessGenVertexOrder(const ShHandle handle);
791 bool HasValidTessGenPointMode(const ShHandle handle);
792 GLenum GetGeometryShaderInputPrimitiveType(const ShHandle handle);
793 GLenum GetGeometryShaderOutputPrimitiveType(const ShHandle handle);
794 int GetGeometryShaderInvocations(const ShHandle handle);
795 int GetGeometryShaderMaxVertices(const ShHandle handle);
796 unsigned int GetShaderSharedMemorySize(const ShHandle handle);
797 int GetTessControlShaderVertices(const ShHandle handle);
798 GLenum GetTessGenMode(const ShHandle handle);
799 GLenum GetTessGenSpacing(const ShHandle handle);
800 GLenum GetTessGenVertexOrder(const ShHandle handle);
801 GLenum GetTessGenPointMode(const ShHandle handle);
802 
803 //
804 // Helper function to identify specs that are based on the WebGL spec.
805 //
IsWebGLBasedSpec(ShShaderSpec spec)806 inline bool IsWebGLBasedSpec(ShShaderSpec spec)
807 {
808     return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
809 }
810 
811 //
812 // Helper function to identify DesktopGL specs
813 //
IsDesktopGLSpec(ShShaderSpec spec)814 inline bool IsDesktopGLSpec(ShShaderSpec spec)
815 {
816     return spec == SH_GL_CORE_SPEC || spec == SH_GL_COMPATIBILITY_SPEC;
817 }
818 
819 // Can't prefix with just _ because then we might introduce a double underscore, which is not safe
820 // in GLSL (ESSL 3.00.6 section 3.8: All identifiers containing a double underscore are reserved for
821 // use by the underlying implementation). u is short for user-defined.
822 extern const char kUserDefinedNamePrefix[];
823 
824 namespace vk
825 {
826 
827 // Specialization constant ids
828 enum class SpecializationConstantId : uint32_t
829 {
830     LineRasterEmulation = 0,
831     SurfaceRotation     = 1,
832     DrawableWidth       = 2,
833     DrawableHeight      = 3,
834 
835     InvalidEnum = 4,
836     EnumCount   = InvalidEnum,
837 };
838 
839 enum class SurfaceRotation : uint32_t
840 {
841     Identity,
842     Rotated90Degrees,
843     Rotated180Degrees,
844     Rotated270Degrees,
845     FlippedIdentity,
846     FlippedRotated90Degrees,
847     FlippedRotated180Degrees,
848     FlippedRotated270Degrees,
849 
850     InvalidEnum,
851     EnumCount = InvalidEnum,
852 };
853 
854 enum class SpecConstUsage : uint32_t
855 {
856     LineRasterEmulation = 0,
857     YFlip               = 1,
858     Rotation            = 2,
859     DrawableSize        = 3,
860 
861     InvalidEnum = 4,
862     EnumCount   = InvalidEnum,
863 };
864 
865 // Interface block name containing the aggregate default uniforms
866 extern const char kDefaultUniformsNameVS[];
867 extern const char kDefaultUniformsNameTCS[];
868 extern const char kDefaultUniformsNameTES[];
869 extern const char kDefaultUniformsNameGS[];
870 extern const char kDefaultUniformsNameFS[];
871 extern const char kDefaultUniformsNameCS[];
872 
873 // Interface block and variable names containing driver uniforms
874 extern const char kDriverUniformsBlockName[];
875 extern const char kDriverUniformsVarName[];
876 
877 // Interface block array name used for atomic counter emulation
878 extern const char kAtomicCountersBlockName[];
879 
880 // Line raster emulation varying
881 extern const char kLineRasterEmulationPosition[];
882 
883 // Transform feedback emulation support
884 extern const char kXfbEmulationGetOffsetsFunctionName[];
885 extern const char kXfbEmulationCaptureFunctionName[];
886 extern const char kXfbEmulationBufferBlockName[];
887 extern const char kXfbEmulationBufferName[];
888 extern const char kXfbEmulationBufferFieldName[];
889 
890 // Transform feedback extension support
891 extern const char kXfbExtensionPositionOutName[];
892 
893 // EXT_shader_framebuffer_fetch and EXT_shader_framebuffer_fetch_non_coherent
894 extern const char kInputAttachmentName[];
895 
896 }  // namespace vk
897 
898 namespace mtl
899 {
900 // Specialization constant to enable GL_SAMPLE_COVERAGE_VALUE emulation.
901 extern const char kCoverageMaskEnabledConstName[];
902 
903 // Specialization constant to emulate rasterizer discard.
904 extern const char kRasterizerDiscardEnabledConstName[];
905 }  // namespace mtl
906 
907 // For backends that use glslang (the Vulkan shader compiler), i.e. Vulkan and Metal, call these to
908 // initialize and finalize glslang itself.  This can be called independently from Initialize() and
909 // Finalize().
910 void InitializeGlslang();
911 void FinalizeGlslang();
912 
913 }  // namespace sh
914 
915 #endif  // GLSLANG_SHADERLANG_H_
916