tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

ShaderLang.h (40904B)


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