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