• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2008, 2009 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 #include <inttypes.h> /* for PRIx64 macro */
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <assert.h>
28 
29 #include "main/context.h"
30 #include "main/debug_output.h"
31 #include "main/formats.h"
32 #include "main/shaderobj.h"
33 #include "util/u_atomic.h" /* for p_atomic_cmpxchg */
34 #include "util/ralloc.h"
35 #include "util/disk_cache.h"
36 #include "util/mesa-blake3.h"
37 #include "ast.h"
38 #include "glsl_parser_extras.h"
39 #include "glsl_parser.h"
40 #include "glsl_to_nir.h"
41 #include "ir_optimization.h"
42 #include "builtin_functions.h"
43 
44 /**
45  * Format a short human-readable description of the given GLSL version.
46  */
47 const char *
glsl_compute_version_string(void * mem_ctx,bool is_es,unsigned version)48 glsl_compute_version_string(void *mem_ctx, bool is_es, unsigned version)
49 {
50    return ralloc_asprintf(mem_ctx, "GLSL%s %d.%02d", is_es ? " ES" : "",
51                           version / 100, version % 100);
52 }
53 
54 
55 static const unsigned known_desktop_glsl_versions[] =
56    { 110, 120, 130, 140, 150, 330, 400, 410, 420, 430, 440, 450, 460 };
57 static const unsigned known_desktop_gl_versions[] =
58    {  20,  21,  30,  31,  32,  33,  40,  41,  42,  43,  44,  45, 46 };
59 
60 
_mesa_glsl_parse_state(struct gl_context * _ctx,gl_shader_stage stage,void * mem_ctx)61 _mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *_ctx,
62 					       gl_shader_stage stage,
63                                                void *mem_ctx)
64    : ctx(_ctx), exts(&_ctx->Extensions), consts(&_ctx->Const),
65      api(_ctx->API), cs_input_local_size_specified(false), cs_input_local_size(),
66      switch_state(), warnings_enabled(true)
67 {
68    assert(stage < MESA_SHADER_STAGES);
69    this->stage = stage;
70 
71    this->scanner = NULL;
72    this->translation_unit.make_empty();
73    this->symbols = new(mem_ctx) glsl_symbol_table;
74 
75    this->linalloc = linear_context(this);
76 
77    this->info_log = ralloc_strdup(mem_ctx, "");
78    this->error = false;
79    this->loop_nesting_ast = NULL;
80 
81    this->uses_builtin_functions = false;
82 
83    /* Set default language version and extensions */
84    this->language_version = 110;
85    this->forced_language_version = ctx->Const.ForceGLSLVersion;
86    if (ctx->Const.GLSLZeroInit == 1) {
87       this->zero_init = (1u << ir_var_auto) | (1u << ir_var_temporary) | (1u << ir_var_shader_out);
88    } else if (ctx->Const.GLSLZeroInit == 2) {
89       this->zero_init = (1u << ir_var_auto) | (1u << ir_var_temporary) | (1u << ir_var_function_out);
90    } else {
91       this->zero_init = 0;
92    }
93    this->gl_version = 20;
94    this->compat_shader = true;
95    this->es_shader = false;
96    this->ARB_texture_rectangle_enable = true;
97 
98    /* OpenGL ES 2.0 has different defaults from desktop GL. */
99    if (_mesa_is_gles2(ctx)) {
100       this->language_version = 100;
101       this->es_shader = true;
102       this->ARB_texture_rectangle_enable = false;
103    }
104 
105    this->extensions = &ctx->Extensions;
106 
107    this->Const.MaxLights = ctx->Const.MaxLights;
108    this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
109    this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
110    this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
111    this->Const.MaxVertexAttribs = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs;
112    this->Const.MaxVertexUniformComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents;
113    this->Const.MaxVertexTextureImageUnits = ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits;
114    this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
115    this->Const.MaxTextureImageUnits = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits;
116    this->Const.MaxFragmentUniformComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents;
117    this->Const.MinProgramTexelOffset = ctx->Const.MinProgramTexelOffset;
118    this->Const.MaxProgramTexelOffset = ctx->Const.MaxProgramTexelOffset;
119 
120    this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
121 
122    this->Const.MaxDualSourceDrawBuffers = ctx->Const.MaxDualSourceDrawBuffers;
123 
124    /* 1.50 constants */
125    this->Const.MaxVertexOutputComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents;
126    this->Const.MaxGeometryInputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxInputComponents;
127    this->Const.MaxGeometryOutputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxOutputComponents;
128    this->Const.MaxGeometryShaderInvocations = ctx->Const.MaxGeometryShaderInvocations;
129    this->Const.MaxFragmentInputComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents;
130    this->Const.MaxGeometryTextureImageUnits = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits;
131    this->Const.MaxGeometryOutputVertices = ctx->Const.MaxGeometryOutputVertices;
132    this->Const.MaxGeometryTotalOutputComponents = ctx->Const.MaxGeometryTotalOutputComponents;
133    this->Const.MaxGeometryUniformComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxUniformComponents;
134 
135    this->Const.MaxVertexAtomicCounters = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAtomicCounters;
136    this->Const.MaxTessControlAtomicCounters = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxAtomicCounters;
137    this->Const.MaxTessEvaluationAtomicCounters = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxAtomicCounters;
138    this->Const.MaxGeometryAtomicCounters = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxAtomicCounters;
139    this->Const.MaxFragmentAtomicCounters = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAtomicCounters;
140    this->Const.MaxComputeAtomicCounters = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxAtomicCounters;
141    this->Const.MaxCombinedAtomicCounters = ctx->Const.MaxCombinedAtomicCounters;
142    this->Const.MaxAtomicBufferBindings = ctx->Const.MaxAtomicBufferBindings;
143    this->Const.MaxVertexAtomicCounterBuffers =
144       ctx->Const.Program[MESA_SHADER_VERTEX].MaxAtomicBuffers;
145    this->Const.MaxTessControlAtomicCounterBuffers =
146       ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxAtomicBuffers;
147    this->Const.MaxTessEvaluationAtomicCounterBuffers =
148       ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxAtomicBuffers;
149    this->Const.MaxGeometryAtomicCounterBuffers =
150       ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxAtomicBuffers;
151    this->Const.MaxFragmentAtomicCounterBuffers =
152       ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAtomicBuffers;
153    this->Const.MaxComputeAtomicCounterBuffers =
154       ctx->Const.Program[MESA_SHADER_COMPUTE].MaxAtomicBuffers;
155    this->Const.MaxCombinedAtomicCounterBuffers =
156       ctx->Const.MaxCombinedAtomicBuffers;
157    this->Const.MaxAtomicCounterBufferSize =
158       ctx->Const.MaxAtomicBufferSize;
159 
160    /* ARB_enhanced_layouts constants */
161    this->Const.MaxTransformFeedbackBuffers = ctx->Const.MaxTransformFeedbackBuffers;
162    this->Const.MaxTransformFeedbackInterleavedComponents = ctx->Const.MaxTransformFeedbackInterleavedComponents;
163 
164    /* Compute shader constants */
165    for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupCount); i++)
166       this->Const.MaxComputeWorkGroupCount[i] = ctx->Const.MaxComputeWorkGroupCount[i];
167    for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupSize); i++)
168       this->Const.MaxComputeWorkGroupSize[i] = ctx->Const.MaxComputeWorkGroupSize[i];
169 
170    this->Const.MaxComputeTextureImageUnits = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits;
171    this->Const.MaxComputeUniformComponents = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents;
172 
173    this->Const.MaxImageUnits = ctx->Const.MaxImageUnits;
174    this->Const.MaxCombinedShaderOutputResources = ctx->Const.MaxCombinedShaderOutputResources;
175    this->Const.MaxImageSamples = ctx->Const.MaxImageSamples;
176    this->Const.MaxVertexImageUniforms = ctx->Const.Program[MESA_SHADER_VERTEX].MaxImageUniforms;
177    this->Const.MaxTessControlImageUniforms = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxImageUniforms;
178    this->Const.MaxTessEvaluationImageUniforms = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxImageUniforms;
179    this->Const.MaxGeometryImageUniforms = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxImageUniforms;
180    this->Const.MaxFragmentImageUniforms = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxImageUniforms;
181    this->Const.MaxComputeImageUniforms = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxImageUniforms;
182    this->Const.MaxCombinedImageUniforms = ctx->Const.MaxCombinedImageUniforms;
183 
184    /* ARB_viewport_array */
185    this->Const.MaxViewports = ctx->Const.MaxViewports;
186 
187    /* tessellation shader constants */
188    this->Const.MaxPatchVertices = ctx->Const.MaxPatchVertices;
189    this->Const.MaxTessGenLevel = ctx->Const.MaxTessGenLevel;
190    this->Const.MaxTessControlInputComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxInputComponents;
191    this->Const.MaxTessControlOutputComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxOutputComponents;
192    this->Const.MaxTessControlTextureImageUnits = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxTextureImageUnits;
193    this->Const.MaxTessEvaluationInputComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxInputComponents;
194    this->Const.MaxTessEvaluationOutputComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxOutputComponents;
195    this->Const.MaxTessEvaluationTextureImageUnits = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxTextureImageUnits;
196    this->Const.MaxTessPatchComponents = ctx->Const.MaxTessPatchComponents;
197    this->Const.MaxTessControlTotalOutputComponents = ctx->Const.MaxTessControlTotalOutputComponents;
198    this->Const.MaxTessControlUniformComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxUniformComponents;
199    this->Const.MaxTessEvaluationUniformComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxUniformComponents;
200 
201    /* GL 4.5 / OES_sample_variables */
202    this->Const.MaxSamples = ctx->Const.MaxSamples;
203 
204    this->current_function = NULL;
205    this->toplevel_ir = NULL;
206    this->found_return = false;
207    this->found_begin_interlock = false;
208    this->found_end_interlock = false;
209    this->all_invariant = false;
210    this->user_structures = NULL;
211    this->num_user_structures = 0;
212    this->num_subroutines = 0;
213    this->subroutines = NULL;
214    this->num_subroutine_types = 0;
215    this->subroutine_types = NULL;
216 
217    /* supported_versions should be large enough to support the known desktop
218     * GLSL versions plus 4 GLES versions (ES 1.00, ES 3.00, ES 3.10, ES 3.20)
219     */
220    STATIC_ASSERT((ARRAY_SIZE(known_desktop_glsl_versions) + 4) ==
221                  ARRAY_SIZE(this->supported_versions));
222 
223    /* Populate the list of supported GLSL versions */
224    /* FINISHME: Once the OpenGL 3.0 'forward compatible' context or
225     * the OpenGL 3.2 Core context is supported, this logic will need
226     * change.  Older versions of GLSL are no longer supported
227     * outside the compatibility contexts of 3.x.
228     */
229    this->num_supported_versions = 0;
230    if (_mesa_is_desktop_gl(ctx)) {
231       for (unsigned i = 0; i < ARRAY_SIZE(known_desktop_glsl_versions); i++) {
232          if (known_desktop_glsl_versions[i] <= ctx->Const.GLSLVersion) {
233             this->supported_versions[this->num_supported_versions].ver
234                = known_desktop_glsl_versions[i];
235             this->supported_versions[this->num_supported_versions].gl_ver
236                = known_desktop_gl_versions[i];
237             this->supported_versions[this->num_supported_versions].es = false;
238             this->num_supported_versions++;
239          }
240       }
241    }
242    if (_mesa_is_gles2_compatible(ctx)) {
243       this->supported_versions[this->num_supported_versions].ver = 100;
244       this->supported_versions[this->num_supported_versions].gl_ver = 20;
245       this->supported_versions[this->num_supported_versions].es = true;
246       this->num_supported_versions++;
247    }
248    if (_mesa_is_gles3_compatible(ctx)) {
249       this->supported_versions[this->num_supported_versions].ver = 300;
250       this->supported_versions[this->num_supported_versions].gl_ver = 30;
251       this->supported_versions[this->num_supported_versions].es = true;
252       this->num_supported_versions++;
253    }
254    if (_mesa_is_gles31_compatible(ctx)) {
255       this->supported_versions[this->num_supported_versions].ver = 310;
256       this->supported_versions[this->num_supported_versions].gl_ver = 31;
257       this->supported_versions[this->num_supported_versions].es = true;
258       this->num_supported_versions++;
259    }
260    if (_mesa_is_gles32_compatible(ctx)) {
261       this->supported_versions[this->num_supported_versions].ver = 320;
262       this->supported_versions[this->num_supported_versions].gl_ver = 32;
263       this->supported_versions[this->num_supported_versions].es = true;
264       this->num_supported_versions++;
265    }
266 
267    /* Create a string for use in error messages to tell the user which GLSL
268     * versions are supported.
269     */
270    char *supported = ralloc_strdup(this, "");
271    for (unsigned i = 0; i < this->num_supported_versions; i++) {
272       unsigned ver = this->supported_versions[i].ver;
273       const char *const prefix = (i == 0)
274 	 ? ""
275 	 : ((i == this->num_supported_versions - 1) ? ", and " : ", ");
276       const char *const suffix = (this->supported_versions[i].es) ? " ES" : "";
277 
278       ralloc_asprintf_append(& supported, "%s%u.%02u%s",
279 			     prefix,
280 			     ver / 100, ver % 100,
281 			     suffix);
282    }
283 
284    this->supported_version_string = supported;
285 
286    if (ctx->Const.ForceGLSLExtensionsWarn)
287       _mesa_glsl_process_extension("all", NULL, "warn", NULL, this);
288 
289    this->default_uniform_qualifier = new(this) ast_type_qualifier();
290    this->default_uniform_qualifier->flags.q.shared = 1;
291    this->default_uniform_qualifier->flags.q.column_major = 1;
292 
293    this->default_shader_storage_qualifier = new(this) ast_type_qualifier();
294    this->default_shader_storage_qualifier->flags.q.shared = 1;
295    this->default_shader_storage_qualifier->flags.q.column_major = 1;
296 
297    this->fs_uses_gl_fragcoord = false;
298    this->fs_redeclares_gl_fragcoord = false;
299    this->fs_origin_upper_left = false;
300    this->fs_pixel_center_integer = false;
301    this->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers = false;
302 
303    this->gs_input_prim_type_specified = false;
304    this->tcs_output_vertices_specified = false;
305    this->gs_input_size = 0;
306    this->in_qualifier = new(this) ast_type_qualifier();
307    this->out_qualifier = new(this) ast_type_qualifier();
308    this->fs_early_fragment_tests = false;
309    this->fs_inner_coverage = false;
310    this->fs_post_depth_coverage = false;
311    this->fs_pixel_interlock_ordered = false;
312    this->fs_pixel_interlock_unordered = false;
313    this->fs_sample_interlock_ordered = false;
314    this->fs_sample_interlock_unordered = false;
315    this->fs_blend_support = 0;
316    memset(this->atomic_counter_offsets, 0,
317           sizeof(this->atomic_counter_offsets));
318    this->allow_extension_directive_midshader =
319       ctx->Const.AllowGLSLExtensionDirectiveMidShader;
320    this->alias_shader_extension =
321       ctx->Const.AliasShaderExtension;
322    this->allow_vertex_texture_bias =
323       ctx->Const.AllowVertexTextureBias;
324    this->allow_glsl_120_subset_in_110 =
325       ctx->Const.AllowGLSL120SubsetIn110;
326    this->allow_builtin_variable_redeclaration =
327       ctx->Const.AllowGLSLBuiltinVariableRedeclaration;
328    this->ignore_write_to_readonly_var =
329       ctx->Const.GLSLIgnoreWriteToReadonlyVar;
330 
331    this->cs_input_local_size_variable_specified = false;
332 
333    /* ARB_bindless_texture */
334    this->bindless_sampler_specified = false;
335    this->bindless_image_specified = false;
336    this->bound_sampler_specified = false;
337    this->bound_image_specified = false;
338 
339    this->language_version = this->forced_language_version ?
340       this->forced_language_version : this->language_version;
341    set_valid_gl_and_glsl_versions(NULL);
342 }
343 
344 /**
345  * Determine whether the current GLSL version is sufficiently high to support
346  * a certain feature, and generate an error message if it isn't.
347  *
348  * \param required_glsl_version and \c required_glsl_es_version are
349  * interpreted as they are in _mesa_glsl_parse_state::is_version().
350  *
351  * \param locp is the parser location where the error should be reported.
352  *
353  * \param fmt (and additional arguments) constitute a printf-style error
354  * message to report if the version check fails.  Information about the
355  * current and required GLSL versions will be appended.  So, for example, if
356  * the GLSL version being compiled is 1.20, and check_version(130, 300, locp,
357  * "foo unsupported") is called, the error message will be "foo unsupported in
358  * GLSL 1.20 (GLSL 1.30 or GLSL 3.00 ES required)".
359  */
360 bool
check_version(unsigned required_glsl_version,unsigned required_glsl_es_version,YYLTYPE * locp,const char * fmt,...)361 _mesa_glsl_parse_state::check_version(unsigned required_glsl_version,
362                                       unsigned required_glsl_es_version,
363                                       YYLTYPE *locp, const char *fmt, ...)
364 {
365    if (this->is_version(required_glsl_version, required_glsl_es_version))
366       return true;
367 
368    va_list args;
369    va_start(args, fmt);
370    char *problem = ralloc_vasprintf(this, fmt, args);
371    va_end(args);
372    const char *glsl_version_string
373       = glsl_compute_version_string(this, false, required_glsl_version);
374    const char *glsl_es_version_string
375       = glsl_compute_version_string(this, true, required_glsl_es_version);
376    const char *requirement_string = "";
377    if (required_glsl_version && required_glsl_es_version) {
378       requirement_string = ralloc_asprintf(this, " (%s or %s required)",
379                                            glsl_version_string,
380                                            glsl_es_version_string);
381    } else if (required_glsl_version) {
382       requirement_string = ralloc_asprintf(this, " (%s required)",
383                                            glsl_version_string);
384    } else if (required_glsl_es_version) {
385       requirement_string = ralloc_asprintf(this, " (%s required)",
386                                            glsl_es_version_string);
387    }
388    _mesa_glsl_error(locp, this, "%s in %s%s",
389                     problem, this->get_version_string(),
390                     requirement_string);
391 
392    return false;
393 }
394 
395 /**
396  * This makes sure any GLSL versions defined or overridden are valid. If not it
397  * sets a valid value.
398  */
399 void
set_valid_gl_and_glsl_versions(YYLTYPE * locp)400 _mesa_glsl_parse_state::set_valid_gl_and_glsl_versions(YYLTYPE *locp)
401 {
402    bool supported = false;
403    for (unsigned i = 0; i < this->num_supported_versions; i++) {
404       if (this->supported_versions[i].ver == this->language_version
405           && this->supported_versions[i].es == this->es_shader) {
406          this->gl_version = this->supported_versions[i].gl_ver;
407          supported = true;
408          break;
409       }
410    }
411 
412    if (!supported) {
413       if (locp) {
414          _mesa_glsl_error(locp, this, "%s is not supported. "
415                           "Supported versions are: %s",
416                           this->get_version_string(),
417                           this->supported_version_string);
418       }
419 
420       /* On exit, the language_version must be set to a valid value.
421        * Later calls to _mesa_glsl_initialize_types will misbehave if
422        * the version is invalid.
423        */
424       switch (this->api) {
425       case API_OPENGL_COMPAT:
426       case API_OPENGL_CORE:
427 	 this->language_version = this->consts->GLSLVersion;
428 	 break;
429 
430       case API_OPENGLES:
431 	 FALLTHROUGH;
432 
433       case API_OPENGLES2:
434 	 this->language_version = 100;
435 	 break;
436       }
437    }
438 }
439 
440 /**
441  * Process a GLSL #version directive.
442  *
443  * \param version is the integer that follows the #version token.
444  *
445  * \param ident is a string identifier that follows the integer, if any is
446  * present.  Otherwise NULL.
447  */
448 void
process_version_directive(YYLTYPE * locp,int version,const char * ident)449 _mesa_glsl_parse_state::process_version_directive(YYLTYPE *locp, int version,
450                                                   const char *ident)
451 {
452    bool es_token_present = false;
453    bool compat_token_present = false;
454    if (ident) {
455       if (strcmp(ident, "es") == 0) {
456          es_token_present = true;
457       } else if (version >= 150) {
458          if (strcmp(ident, "core") == 0) {
459             /* Accept the token.  There's no need to record that this is
460              * a core profile shader since that's the only profile we support.
461              */
462          } else if (strcmp(ident, "compatibility") == 0) {
463             compat_token_present = true;
464 
465             if (this->api != API_OPENGL_COMPAT &&
466                 !this->consts->AllowGLSLCompatShaders) {
467                _mesa_glsl_error(locp, this,
468                                 "the compatibility profile is not supported");
469             }
470          } else {
471             _mesa_glsl_error(locp, this,
472                              "\"%s\" is not a valid shading language profile; "
473                              "if present, it must be \"core\"", ident);
474          }
475       } else {
476          _mesa_glsl_error(locp, this,
477                           "illegal text following version number");
478       }
479    }
480 
481    this->es_shader = es_token_present;
482    if (version == 100) {
483       if (es_token_present) {
484          _mesa_glsl_error(locp, this,
485                           "GLSL 1.00 ES should be selected using "
486                           "`#version 100'");
487       } else {
488          this->es_shader = true;
489       }
490    }
491 
492    if (this->es_shader) {
493       this->ARB_texture_rectangle_enable = false;
494    }
495 
496    if (this->forced_language_version)
497       this->language_version = this->forced_language_version;
498    else
499       this->language_version = version;
500 
501    this->compat_shader = compat_token_present ||
502                          this->consts->ForceCompatShaders ||
503                          (this->api == API_OPENGL_COMPAT &&
504                           this->language_version == 140) ||
505                          (!this->es_shader && this->language_version < 140);
506 
507    set_valid_gl_and_glsl_versions(locp);
508 }
509 
510 
511 /* This helper function will append the given message to the shader's
512    info log and report it via GL_ARB_debug_output. Per that extension,
513    'type' is one of the enum values classifying the message, and
514    'id' is the implementation-defined ID of the given message. */
515 static void
_mesa_glsl_msg(const YYLTYPE * locp,_mesa_glsl_parse_state * state,GLenum type,const char * fmt,va_list ap)516 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
517                GLenum type, const char *fmt, va_list ap)
518 {
519    bool error = (type == MESA_DEBUG_TYPE_ERROR);
520    GLuint msg_id = 0;
521 
522    assert(state->info_log != NULL);
523 
524    /* Get the offset that the new message will be written to. */
525    int msg_offset = strlen(state->info_log);
526 
527    if (locp->path) {
528       ralloc_asprintf_append(&state->info_log, "\"%s\"", locp->path);
529    } else {
530       ralloc_asprintf_append(&state->info_log, "%u", locp->source);
531    }
532    ralloc_asprintf_append(&state->info_log, ":%u(%u): %s: ",
533                           locp->first_line, locp->first_column,
534                           error ? "error" : "warning");
535 
536    ralloc_vasprintf_append(&state->info_log, fmt, ap);
537 
538    const char *const msg = &state->info_log[msg_offset];
539    struct gl_context *ctx = state->ctx;
540 
541    /* Report the error via GL_ARB_debug_output. */
542    _mesa_shader_debug(ctx, type, &msg_id, msg);
543 
544    ralloc_strcat(&state->info_log, "\n");
545 }
546 
547 void
_mesa_glsl_error(YYLTYPE * locp,_mesa_glsl_parse_state * state,const char * fmt,...)548 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
549 		 const char *fmt, ...)
550 {
551    va_list ap;
552 
553    state->error = true;
554 
555    va_start(ap, fmt);
556    _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_ERROR, fmt, ap);
557    va_end(ap);
558 }
559 
560 
561 void
_mesa_glsl_warning(const YYLTYPE * locp,_mesa_glsl_parse_state * state,const char * fmt,...)562 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
563 		   const char *fmt, ...)
564 {
565    if (state->warnings_enabled) {
566       va_list ap;
567 
568       va_start(ap, fmt);
569       _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_OTHER, fmt, ap);
570       va_end(ap);
571    }
572 }
573 
574 
575 /**
576  * Enum representing the possible behaviors that can be specified in
577  * an #extension directive.
578  */
579 enum ext_behavior {
580    extension_disable,
581    extension_enable,
582    extension_require,
583    extension_warn
584 };
585 
586 /**
587  * Element type for _mesa_glsl_supported_extensions
588  */
589 struct _mesa_glsl_extension {
590    /**
591     * Name of the extension when referred to in a GLSL extension
592     * statement
593     */
594    const char *name;
595 
596    /**
597     * Whether this extension is a part of AEP
598     */
599    bool aep;
600 
601    /**
602     * Predicate that checks whether the relevant extension is available for
603     * this context.
604     */
605    bool (*available_pred)(const _mesa_glsl_parse_state *,
606                           gl_api api, uint8_t version);
607 
608    /**
609     * Flag in the _mesa_glsl_parse_state struct that should be set
610     * when this extension is enabled.
611     *
612     * See note in _mesa_glsl_extension::supported_flag about "pointer
613     * to member" types.
614     */
615    bool _mesa_glsl_parse_state::* enable_flag;
616 
617    /**
618     * Flag in the _mesa_glsl_parse_state struct that should be set
619     * when the shader requests "warn" behavior for this extension.
620     *
621     * See note in _mesa_glsl_extension::supported_flag about "pointer
622     * to member" types.
623     */
624    bool _mesa_glsl_parse_state::* warn_flag;
625 
626 
627    bool compatible_with_state(const _mesa_glsl_parse_state *state,
628                               gl_api api, uint8_t gl_version) const;
629    void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
630 };
631 
632 /** Checks if the context supports a user-facing extension */
633 #define EXT(name_str, driver_cap, ...) \
634 static UNUSED bool \
635 has_##name_str(const _mesa_glsl_parse_state *state, gl_api api, uint8_t version) \
636 { \
637    return state->exts->driver_cap && (version >= \
638           _mesa_extension_table[MESA_EXTENSION_##name_str].version[api]); \
639 }
640 #include "main/extensions_table.h"
641 #undef EXT
642 
643 static unsigned
mesa_stage_to_gl_stage_bit(unsigned stage)644 mesa_stage_to_gl_stage_bit(unsigned stage)
645 {
646    switch (stage) {
647    case MESA_SHADER_VERTEX:
648       return GL_VERTEX_SHADER_BIT;
649    case MESA_SHADER_TESS_CTRL:
650       return GL_TESS_CONTROL_SHADER_BIT;
651    case MESA_SHADER_TESS_EVAL:
652       return GL_TESS_EVALUATION_SHADER_BIT;
653    case MESA_SHADER_GEOMETRY:
654       return GL_GEOMETRY_SHADER_BIT;
655    case MESA_SHADER_FRAGMENT:
656       return GL_FRAGMENT_SHADER_BIT;
657    case MESA_SHADER_COMPUTE:
658       return GL_COMPUTE_SHADER_BIT;
659    default:
660       unreachable("glsl parser: invalid shader stage");
661    }
662 }
663 
664 #define HAS_SUBGROUP_EXT(name, feature) \
665 static bool \
666 has_KHR_shader_subgroup_##name(const _mesa_glsl_parse_state *state, gl_api api, uint8_t version) \
667 { \
668    unsigned stage = mesa_stage_to_gl_stage_bit(state->stage); \
669    return state->exts->KHR_shader_subgroup && \
670       (version >= _mesa_extension_table[MESA_EXTENSION_KHR_shader_subgroup].version[api]) && \
671       (state->consts->ShaderSubgroupSupportedStages & stage) && \
672       (state->consts->ShaderSubgroupSupportedFeatures & GL_SUBGROUP_FEATURE_##feature##_BIT_KHR); \
673 }
674 
HAS_SUBGROUP_EXT(basic,BASIC)675 HAS_SUBGROUP_EXT(basic, BASIC)
676 HAS_SUBGROUP_EXT(vote, VOTE)
677 HAS_SUBGROUP_EXT(arithmetic, ARITHMETIC)
678 HAS_SUBGROUP_EXT(ballot, BALLOT)
679 HAS_SUBGROUP_EXT(shuffle, SHUFFLE)
680 HAS_SUBGROUP_EXT(shuffle_relative, SHUFFLE_RELATIVE)
681 HAS_SUBGROUP_EXT(clustered, CLUSTERED)
682 HAS_SUBGROUP_EXT(quad_, QUAD)
683 
684 static bool
685 has_KHR_shader_subgroup_quad(const _mesa_glsl_parse_state *state, gl_api api, uint8_t version)
686 {
687    return has_KHR_shader_subgroup_quad_(state, api, version) &&
688       ((state->stage == MESA_SHADER_FRAGMENT || state->stage == MESA_SHADER_COMPUTE) ||
689        state->consts->ShaderSubgroupQuadAllStages);
690 }
691 
692 #define EXT(NAME)                                           \
693    { "GL_" #NAME, false, has_##NAME,                        \
694      &_mesa_glsl_parse_state::NAME##_enable,                \
695      &_mesa_glsl_parse_state::NAME##_warn }
696 
697 #define EXT_AEP(NAME)                                       \
698    { "GL_" #NAME, true, has_##NAME,                         \
699      &_mesa_glsl_parse_state::NAME##_enable,                \
700      &_mesa_glsl_parse_state::NAME##_warn }
701 
702 /**
703  * Table of extensions that can be enabled/disabled within a shader,
704  * and the conditions under which they are supported.
705  */
706 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
707    /* ARB extensions go here, sorted alphabetically.
708     */
709    EXT(ARB_ES3_1_compatibility),
710    EXT(ARB_ES3_2_compatibility),
711    EXT(ARB_arrays_of_arrays),
712    EXT(ARB_bindless_texture),
713    EXT(ARB_compatibility),
714    EXT(ARB_compute_shader),
715    EXT(ARB_compute_variable_group_size),
716    EXT(ARB_conservative_depth),
717    EXT(ARB_cull_distance),
718    EXT(ARB_derivative_control),
719    EXT(ARB_draw_buffers),
720    EXT(ARB_draw_instanced),
721    EXT(ARB_enhanced_layouts),
722    EXT(ARB_explicit_attrib_location),
723    EXT(ARB_explicit_uniform_location),
724    EXT(ARB_fragment_coord_conventions),
725    EXT(ARB_fragment_layer_viewport),
726    EXT(ARB_fragment_shader_interlock),
727    EXT(ARB_gpu_shader5),
728    EXT(ARB_gpu_shader_fp64),
729    EXT(ARB_gpu_shader_int64),
730    EXT(ARB_post_depth_coverage),
731    EXT(ARB_sample_shading),
732    EXT(ARB_separate_shader_objects),
733    EXT(ARB_shader_atomic_counter_ops),
734    EXT(ARB_shader_atomic_counters),
735    EXT(ARB_shader_ballot),
736    EXT(ARB_shader_bit_encoding),
737    EXT(ARB_shader_clock),
738    EXT(ARB_shader_draw_parameters),
739    EXT(ARB_shader_group_vote),
740    EXT(ARB_shader_image_load_store),
741    EXT(ARB_shader_image_size),
742    EXT(ARB_shader_precision),
743    EXT(ARB_shader_stencil_export),
744    EXT(ARB_shader_storage_buffer_object),
745    EXT(ARB_shader_subroutine),
746    EXT(ARB_shader_texture_image_samples),
747    EXT(ARB_shader_texture_lod),
748    EXT(ARB_shader_viewport_layer_array),
749    EXT(ARB_shading_language_420pack),
750    EXT(ARB_shading_language_include),
751    EXT(ARB_shading_language_packing),
752    EXT(ARB_sparse_texture2),
753    EXT(ARB_sparse_texture_clamp),
754    EXT(ARB_tessellation_shader),
755    EXT(ARB_texture_cube_map_array),
756    EXT(ARB_texture_gather),
757    EXT(ARB_texture_multisample),
758    EXT(ARB_texture_query_levels),
759    EXT(ARB_texture_query_lod),
760    EXT(ARB_texture_rectangle),
761    EXT(ARB_uniform_buffer_object),
762    EXT(ARB_vertex_attrib_64bit),
763    EXT(ARB_viewport_array),
764 
765    /* KHR extensions go here, sorted alphabetically.
766     */
767    EXT_AEP(KHR_blend_equation_advanced),
768    EXT(KHR_shader_subgroup_arithmetic),
769    EXT(KHR_shader_subgroup_ballot),
770    EXT(KHR_shader_subgroup_basic),
771    EXT(KHR_shader_subgroup_clustered),
772    EXT(KHR_shader_subgroup_quad),
773    EXT(KHR_shader_subgroup_shuffle),
774    EXT(KHR_shader_subgroup_shuffle_relative),
775    EXT(KHR_shader_subgroup_vote),
776 
777    /* OES extensions go here, sorted alphabetically.
778     */
779    EXT(OES_EGL_image_external),
780    EXT(OES_EGL_image_external_essl3),
781    EXT(OES_geometry_point_size),
782    EXT(OES_geometry_shader),
783    EXT(OES_gpu_shader5),
784    EXT(OES_primitive_bounding_box),
785    EXT_AEP(OES_sample_variables),
786    EXT_AEP(OES_shader_image_atomic),
787    EXT(OES_shader_io_blocks),
788    EXT_AEP(OES_shader_multisample_interpolation),
789    EXT(OES_standard_derivatives),
790    EXT(OES_tessellation_point_size),
791    EXT(OES_tessellation_shader),
792    EXT(OES_texture_3D),
793    EXT(OES_texture_buffer),
794    EXT(OES_texture_cube_map_array),
795    EXT_AEP(OES_texture_storage_multisample_2d_array),
796    EXT(OES_viewport_array),
797 
798    /* All other extensions go here, sorted alphabetically.
799     */
800    EXT(AMD_conservative_depth),
801    EXT(AMD_gpu_shader_half_float),
802    EXT(AMD_gpu_shader_int64),
803    EXT(AMD_shader_stencil_export),
804    EXT(AMD_shader_trinary_minmax),
805    EXT(AMD_texture_texture4),
806    EXT(AMD_vertex_shader_layer),
807    EXT(AMD_vertex_shader_viewport_index),
808    EXT(ANDROID_extension_pack_es31a),
809    EXT(ARM_shader_framebuffer_fetch_depth_stencil),
810    EXT(EXT_blend_func_extended),
811    EXT(EXT_demote_to_helper_invocation),
812    EXT(EXT_frag_depth),
813    EXT(EXT_draw_buffers),
814    EXT(EXT_draw_instanced),
815    EXT(EXT_clip_cull_distance),
816    EXT(EXT_conservative_depth),
817    EXT(EXT_geometry_point_size),
818    EXT_AEP(EXT_geometry_shader),
819    EXT(EXT_gpu_shader4),
820    EXT_AEP(EXT_gpu_shader5),
821    EXT_AEP(EXT_primitive_bounding_box),
822    EXT(EXT_separate_shader_objects),
823    EXT(EXT_shader_framebuffer_fetch),
824    EXT(EXT_shader_framebuffer_fetch_non_coherent),
825    EXT(EXT_shader_group_vote),
826    EXT(EXT_shader_image_load_formatted),
827    EXT(EXT_shader_image_load_store),
828    EXT(EXT_shader_implicit_conversions),
829    EXT(EXT_shader_integer_mix),
830    EXT_AEP(EXT_shader_io_blocks),
831    EXT(EXT_shader_samples_identical),
832    EXT(EXT_shadow_samplers),
833    EXT(EXT_tessellation_point_size),
834    EXT_AEP(EXT_tessellation_shader),
835    EXT(EXT_texture_array),
836    EXT_AEP(EXT_texture_buffer),
837    EXT_AEP(EXT_texture_cube_map_array),
838    EXT(EXT_texture_query_lod),
839    EXT(EXT_texture_shadow_lod),
840    EXT(INTEL_conservative_rasterization),
841    EXT(INTEL_shader_atomic_float_minmax),
842    EXT(INTEL_shader_integer_functions2),
843    EXT(MESA_shader_integer_functions),
844    EXT(NV_compute_shader_derivatives),
845    EXT(NV_fragment_shader_interlock),
846    EXT(NV_image_formats),
847    EXT(NV_shader_atomic_float),
848    EXT(NV_shader_atomic_int64),
849    EXT(NV_shader_noperspective_interpolation),
850    EXT(NV_viewport_array2),
851    EXT(OVR_multiview),
852    EXT(OVR_multiview2),
853 };
854 
855 #undef EXT
856 
857 
858 /**
859  * Determine whether a given extension is compatible with the target,
860  * API, and extension information in the current parser state.
861  */
compatible_with_state(const _mesa_glsl_parse_state * state,gl_api api,uint8_t gl_version) const862 bool _mesa_glsl_extension::compatible_with_state(
863       const _mesa_glsl_parse_state *state, gl_api api, uint8_t gl_version) const
864 {
865    return this->available_pred(state, api, gl_version);
866 }
867 
868 /**
869  * Set the appropriate flags in the parser state to establish the
870  * given behavior for this extension.
871  */
set_flags(_mesa_glsl_parse_state * state,ext_behavior behavior) const872 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
873                                      ext_behavior behavior) const
874 {
875    /* Note: the ->* operator indexes into state by the
876     * offsets this->enable_flag and this->warn_flag.  See
877     * _mesa_glsl_extension::supported_flag for more info.
878     */
879    state->*(this->enable_flag) = (behavior != extension_disable);
880    state->*(this->warn_flag)   = (behavior == extension_warn);
881 }
882 
883 /**
884  * Check alias_shader_extension for any aliased shader extensions
885  */
find_extension_alias(_mesa_glsl_parse_state * state,const char * name)886 static const char *find_extension_alias(_mesa_glsl_parse_state *state, const char *name)
887 {
888    char *exts, *field, *ext_alias = NULL;
889 
890    /* Copy alias_shader_extension because strtok() is destructive. */
891    exts = strdup(state->alias_shader_extension);
892    if (exts) {
893       for (field = strtok(exts, ","); field != NULL; field = strtok(NULL, ",")) {
894          if(strncmp(name, field, strlen(name)) == 0) {
895             field = strstr(field, ":");
896             if(field) {
897                ext_alias = strdup(field + 1);
898             }
899             break;
900          }
901       }
902 
903       free(exts);
904    }
905    return ext_alias;
906 }
907 
908 /**
909  * Find an extension by name in _mesa_glsl_supported_extensions.  If
910  * the name is not found, return NULL.
911  */
find_extension(_mesa_glsl_parse_state * state,const char * name)912 static const _mesa_glsl_extension *find_extension(_mesa_glsl_parse_state *state, const char *name)
913 {
914    const char *ext_alias = NULL;
915    if (state->alias_shader_extension) {
916       ext_alias = find_extension_alias(state, name);
917       name = ext_alias ? ext_alias : name;
918    }
919 
920    for (unsigned i = 0; i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
921       if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
922          free((void *)ext_alias);
923          return &_mesa_glsl_supported_extensions[i];
924       }
925    }
926 
927    free((void *)ext_alias);
928    return NULL;
929 }
930 
931 bool
_mesa_glsl_process_extension(const char * name,YYLTYPE * name_locp,const char * behavior_string,YYLTYPE * behavior_locp,_mesa_glsl_parse_state * state)932 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
933 			     const char *behavior_string, YYLTYPE *behavior_locp,
934 			     _mesa_glsl_parse_state *state)
935 {
936    uint8_t gl_version = state->exts->Version;
937    gl_api api = state->api;
938    ext_behavior behavior;
939    if (strcmp(behavior_string, "warn") == 0) {
940       behavior = extension_warn;
941    } else if (strcmp(behavior_string, "require") == 0) {
942       behavior = extension_require;
943    } else if (strcmp(behavior_string, "enable") == 0) {
944       behavior = extension_enable;
945    } else if (strcmp(behavior_string, "disable") == 0) {
946       behavior = extension_disable;
947    } else {
948       _mesa_glsl_error(behavior_locp, state,
949 		       "unknown extension behavior `%s'",
950 		       behavior_string);
951       return false;
952    }
953 
954    /* If we're in a desktop context but with an ES shader, use an ES API enum
955     * to verify extension availability.
956     */
957    if (state->es_shader && api != API_OPENGLES2)
958       api = API_OPENGLES2;
959    /* Use the language-version derived GL version to extension checks, unless
960     * we're using meta, which sets the version to the max.
961     */
962    if (gl_version != 0xff)
963       gl_version = state->gl_version;
964 
965    if (strcmp(name, "all") == 0) {
966       if ((behavior == extension_enable) || (behavior == extension_require)) {
967 	 _mesa_glsl_error(name_locp, state, "cannot %s all extensions",
968 			  (behavior == extension_enable)
969 			  ? "enable" : "require");
970 	 return false;
971       } else {
972          for (unsigned i = 0;
973               i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
974             const _mesa_glsl_extension *extension
975                = &_mesa_glsl_supported_extensions[i];
976             if (extension->compatible_with_state(state, api, gl_version)) {
977                _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
978             }
979          }
980       }
981    } else {
982       const _mesa_glsl_extension *extension = find_extension(state, name);
983       if (extension &&
984           (extension->compatible_with_state(state, api, gl_version) ||
985            (state->consts->AllowGLSLCompatShaders &&
986             extension->compatible_with_state(state, API_OPENGL_COMPAT, gl_version)))) {
987          extension->set_flags(state, behavior);
988          if (extension->available_pred == has_ANDROID_extension_pack_es31a) {
989             for (unsigned i = 0;
990                  i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
991                const _mesa_glsl_extension *extension =
992                   &_mesa_glsl_supported_extensions[i];
993 
994                if (!extension->aep)
995                   continue;
996                /* AEP should not be enabled if all of the sub-extensions can't
997                 * also be enabled. This is not the proper layer to do such
998                 * error-checking though.
999                 */
1000                assert(extension->compatible_with_state(state, api, gl_version));
1001                extension->set_flags(state, behavior);
1002             }
1003          } else if (extension->available_pred == has_KHR_shader_subgroup_vote ||
1004                     extension->available_pred == has_KHR_shader_subgroup_arithmetic ||
1005                     extension->available_pred == has_KHR_shader_subgroup_ballot ||
1006                     extension->available_pred == has_KHR_shader_subgroup_shuffle ||
1007                     extension->available_pred == has_KHR_shader_subgroup_shuffle_relative ||
1008                     extension->available_pred == has_KHR_shader_subgroup_clustered ||
1009                     extension->available_pred == has_KHR_shader_subgroup_quad) {
1010             /* GLSL KHR_shader_subgroup spec says when any of above subgroup extension
1011              * is enabled, KHR_shader_subgroup_basic extension is also implicitly enabled.
1012              */
1013             for (unsigned i = 0; i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
1014                const _mesa_glsl_extension *extension = &_mesa_glsl_supported_extensions[i];
1015                if (extension->available_pred == has_KHR_shader_subgroup_basic) {
1016                   assert(extension->compatible_with_state(state, api, gl_version));
1017                   extension->set_flags(state, behavior);
1018                }
1019             }
1020          }
1021       } else {
1022          static const char fmt[] = "extension `%s' unsupported in %s shader";
1023 
1024          if (behavior == extension_require) {
1025             _mesa_glsl_error(name_locp, state, fmt,
1026                              name, _mesa_shader_stage_to_string(state->stage));
1027             return false;
1028          } else {
1029             _mesa_glsl_warning(name_locp, state, fmt,
1030                                name, _mesa_shader_stage_to_string(state->stage));
1031          }
1032       }
1033    }
1034 
1035    if (state->OVR_multiview2_enable)
1036       state->OVR_multiview_enable = true;
1037 
1038    return true;
1039 }
1040 
1041 /**
1042  * Recurses through <type> and <expr> if <expr> is an aggregate initializer
1043  * and sets <expr>'s <constructor_type> field to <type>. Gives later functions
1044  * (process_array_constructor, et al) sufficient information to do type
1045  * checking.
1046  *
1047  * Operates on assignments involving an aggregate initializer. E.g.,
1048  *
1049  * vec4 pos = {1.0, -1.0, 0.0, 1.0};
1050  *
1051  * or more ridiculously,
1052  *
1053  * struct S {
1054  *     vec4 v[2];
1055  * };
1056  *
1057  * struct {
1058  *     S a[2], b;
1059  *     int c;
1060  * } aggregate = {
1061  *     {
1062  *         {
1063  *             {
1064  *                 {1.0, 2.0, 3.0, 4.0}, // a[0].v[0]
1065  *                 {5.0, 6.0, 7.0, 8.0}  // a[0].v[1]
1066  *             } // a[0].v
1067  *         }, // a[0]
1068  *         {
1069  *             {
1070  *                 {1.0, 2.0, 3.0, 4.0}, // a[1].v[0]
1071  *                 {5.0, 6.0, 7.0, 8.0}  // a[1].v[1]
1072  *             } // a[1].v
1073  *         } // a[1]
1074  *     }, // a
1075  *     {
1076  *         {
1077  *             {1.0, 2.0, 3.0, 4.0}, // b.v[0]
1078  *             {5.0, 6.0, 7.0, 8.0}  // b.v[1]
1079  *         } // b.v
1080  *     }, // b
1081  *     4 // c
1082  * };
1083  *
1084  * This pass is necessary because the right-hand side of <type> e = { ... }
1085  * doesn't contain sufficient information to determine if the types match.
1086  */
1087 void
_mesa_ast_set_aggregate_type(const glsl_type * type,ast_expression * expr)1088 _mesa_ast_set_aggregate_type(const glsl_type *type,
1089                              ast_expression *expr)
1090 {
1091    ast_aggregate_initializer *ai = (ast_aggregate_initializer *)expr;
1092    ai->constructor_type = type;
1093 
1094    /* If the aggregate is an array, recursively set its elements' types. */
1095    if (glsl_type_is_array(type)) {
1096       /* Each array element has the type type->fields.array.
1097        *
1098        * E.g., if <type> if struct S[2] we want to set each element's type to
1099        * struct S.
1100        */
1101       for (exec_node *expr_node = ai->expressions.get_head_raw();
1102            !expr_node->is_tail_sentinel();
1103            expr_node = expr_node->next) {
1104          ast_expression *expr = exec_node_data(ast_expression, expr_node,
1105                                                link);
1106 
1107          if (expr->oper == ast_aggregate)
1108             _mesa_ast_set_aggregate_type(type->fields.array, expr);
1109       }
1110 
1111    /* If the aggregate is a struct, recursively set its fields' types. */
1112    } else if (glsl_type_is_struct(type)) {
1113       exec_node *expr_node = ai->expressions.get_head_raw();
1114 
1115       /* Iterate through the struct's fields. */
1116       for (unsigned i = 0; !expr_node->is_tail_sentinel() && i < type->length;
1117            i++, expr_node = expr_node->next) {
1118          ast_expression *expr = exec_node_data(ast_expression, expr_node,
1119                                                link);
1120 
1121          if (expr->oper == ast_aggregate) {
1122             _mesa_ast_set_aggregate_type(type->fields.structure[i].type, expr);
1123          }
1124       }
1125    /* If the aggregate is a matrix, set its columns' types. */
1126    } else if (glsl_type_is_matrix(type)) {
1127       for (exec_node *expr_node = ai->expressions.get_head_raw();
1128            !expr_node->is_tail_sentinel();
1129            expr_node = expr_node->next) {
1130          ast_expression *expr = exec_node_data(ast_expression, expr_node,
1131                                                link);
1132 
1133          if (expr->oper == ast_aggregate)
1134             _mesa_ast_set_aggregate_type(glsl_get_column_type(type), expr);
1135       }
1136    }
1137 }
1138 
1139 void
_mesa_ast_process_interface_block(YYLTYPE * locp,_mesa_glsl_parse_state * state,ast_interface_block * const block,const struct ast_type_qualifier & q)1140 _mesa_ast_process_interface_block(YYLTYPE *locp,
1141                                   _mesa_glsl_parse_state *state,
1142                                   ast_interface_block *const block,
1143                                   const struct ast_type_qualifier &q)
1144 {
1145    if (q.flags.q.buffer) {
1146       if (!state->has_shader_storage_buffer_objects()) {
1147          _mesa_glsl_error(locp, state,
1148                           "#version 430 / GL_ARB_shader_storage_buffer_object "
1149                           "required for defining shader storage blocks");
1150       } else if (state->ARB_shader_storage_buffer_object_warn) {
1151          _mesa_glsl_warning(locp, state,
1152                             "#version 430 / GL_ARB_shader_storage_buffer_object "
1153                             "required for defining shader storage blocks");
1154       }
1155    } else if (q.flags.q.uniform) {
1156       if (!state->has_uniform_buffer_objects()) {
1157          _mesa_glsl_error(locp, state,
1158                           "#version 140 / GL_ARB_uniform_buffer_object "
1159                           "required for defining uniform blocks");
1160       } else if (state->ARB_uniform_buffer_object_warn) {
1161          _mesa_glsl_warning(locp, state,
1162                             "#version 140 / GL_ARB_uniform_buffer_object "
1163                             "required for defining uniform blocks");
1164       }
1165    } else {
1166       if (!state->has_shader_io_blocks()) {
1167          if (state->es_shader) {
1168             _mesa_glsl_error(locp, state,
1169                              "GL_OES_shader_io_blocks or #version 320 "
1170                              "required for using interface blocks");
1171          } else {
1172             _mesa_glsl_error(locp, state,
1173                              "#version 150 required for using "
1174                              "interface blocks");
1175          }
1176       }
1177    }
1178 
1179    /* From the GLSL 1.50.11 spec, section 4.3.7 ("Interface Blocks"):
1180     * "It is illegal to have an input block in a vertex shader
1181     *  or an output block in a fragment shader"
1182     */
1183    if ((state->stage == MESA_SHADER_VERTEX) && q.flags.q.in) {
1184       _mesa_glsl_error(locp, state,
1185                        "`in' interface block is not allowed for "
1186                        "a vertex shader");
1187    } else if ((state->stage == MESA_SHADER_FRAGMENT) && q.flags.q.out) {
1188       _mesa_glsl_error(locp, state,
1189                        "`out' interface block is not allowed for "
1190                        "a fragment shader");
1191    }
1192 
1193    /* Since block arrays require names, and both features are added in
1194     * the same language versions, we don't have to explicitly
1195     * version-check both things.
1196     */
1197    if (block->instance_name != NULL) {
1198       state->check_version(150, 300, locp, "interface blocks with "
1199                            "an instance name are not allowed");
1200    }
1201 
1202    ast_type_qualifier::bitset_t interface_type_mask;
1203    struct ast_type_qualifier temp_type_qualifier;
1204 
1205    /* Get a bitmask containing only the in/out/uniform/buffer
1206     * flags, allowing us to ignore other irrelevant flags like
1207     * interpolation qualifiers.
1208     */
1209    temp_type_qualifier.flags.i = 0;
1210    temp_type_qualifier.flags.q.uniform = true;
1211    temp_type_qualifier.flags.q.in = true;
1212    temp_type_qualifier.flags.q.out = true;
1213    temp_type_qualifier.flags.q.buffer = true;
1214    temp_type_qualifier.flags.q.patch = true;
1215    interface_type_mask = temp_type_qualifier.flags.i;
1216 
1217    /* Get the block's interface qualifier.  The interface_qualifier
1218     * production rule guarantees that only one bit will be set (and
1219     * it will be in/out/uniform).
1220     */
1221    ast_type_qualifier::bitset_t block_interface_qualifier = q.flags.i;
1222 
1223    block->default_layout.flags.i |= block_interface_qualifier;
1224 
1225    if (state->stage == MESA_SHADER_GEOMETRY &&
1226        state->has_explicit_attrib_stream() &&
1227        block->default_layout.flags.q.out) {
1228       /* Assign global layout's stream value. */
1229       block->default_layout.flags.q.stream = 1;
1230       block->default_layout.flags.q.explicit_stream = 0;
1231       block->default_layout.stream = state->out_qualifier->stream;
1232    }
1233 
1234    if (state->has_enhanced_layouts() && block->default_layout.flags.q.out &&
1235        state->exts->ARB_transform_feedback3) {
1236       /* Assign global layout's xfb_buffer value. */
1237       block->default_layout.flags.q.xfb_buffer = 1;
1238       block->default_layout.flags.q.explicit_xfb_buffer = 0;
1239       block->default_layout.xfb_buffer = state->out_qualifier->xfb_buffer;
1240    }
1241 
1242    foreach_list_typed (ast_declarator_list, member, link, &block->declarations) {
1243       ast_type_qualifier& qualifier = member->type->qualifier;
1244       if ((qualifier.flags.i & interface_type_mask) == 0) {
1245          /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
1246           * "If no optional qualifier is used in a member declaration, the
1247           *  qualifier of the variable is just in, out, or uniform as declared
1248           *  by interface-qualifier."
1249           */
1250          qualifier.flags.i |= block_interface_qualifier;
1251       } else if ((qualifier.flags.i & interface_type_mask) !=
1252                  block_interface_qualifier) {
1253          /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
1254           * "If optional qualifiers are used, they can include interpolation
1255           *  and storage qualifiers and they must declare an input, output,
1256           *  or uniform variable consistent with the interface qualifier of
1257           *  the block."
1258           */
1259          _mesa_glsl_error(locp, state,
1260                           "uniform/in/out qualifier on "
1261                           "interface block member does not match "
1262                           "the interface block");
1263       }
1264 
1265       if (!(q.flags.q.in || q.flags.q.out) && qualifier.flags.q.invariant)
1266          _mesa_glsl_error(locp, state,
1267                           "invariant qualifiers can be used only "
1268                           "in interface block members for shader "
1269                           "inputs or outputs");
1270    }
1271 }
1272 
1273 static void
_mesa_ast_type_qualifier_print(const struct ast_type_qualifier * q)1274 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
1275 {
1276    if (q->is_subroutine_decl())
1277       printf("subroutine ");
1278 
1279    if (q->subroutine_list) {
1280       printf("subroutine (");
1281       q->subroutine_list->print();
1282       printf(")");
1283    }
1284 
1285    if (q->flags.q.constant)
1286       printf("const ");
1287 
1288    if (q->flags.q.invariant)
1289       printf("invariant ");
1290 
1291    if (q->flags.q.attribute)
1292       printf("attribute ");
1293 
1294    if (q->flags.q.varying)
1295       printf("varying ");
1296 
1297    if (q->flags.q.in && q->flags.q.out)
1298       printf("inout ");
1299    else {
1300       if (q->flags.q.in)
1301 	 printf("in ");
1302 
1303       if (q->flags.q.out)
1304 	 printf("out ");
1305    }
1306 
1307    if (q->flags.q.centroid)
1308       printf("centroid ");
1309    if (q->flags.q.sample)
1310       printf("sample ");
1311    if (q->flags.q.patch)
1312       printf("patch ");
1313    if (q->flags.q.uniform)
1314       printf("uniform ");
1315    if (q->flags.q.buffer)
1316       printf("buffer ");
1317    if (q->flags.q.smooth)
1318       printf("smooth ");
1319    if (q->flags.q.flat)
1320       printf("flat ");
1321    if (q->flags.q.noperspective)
1322       printf("noperspective ");
1323 }
1324 
1325 
1326 void
print(void) const1327 ast_node::print(void) const
1328 {
1329    printf("unhandled node ");
1330 }
1331 
1332 
ast_node(void)1333 ast_node::ast_node(void)
1334 {
1335    this->location.path = NULL;
1336    this->location.source = 0;
1337    this->location.first_line = 0;
1338    this->location.first_column = 0;
1339    this->location.last_line = 0;
1340    this->location.last_column = 0;
1341 }
1342 
1343 
1344 static void
ast_opt_array_dimensions_print(const ast_array_specifier * array_specifier)1345 ast_opt_array_dimensions_print(const ast_array_specifier *array_specifier)
1346 {
1347    if (array_specifier)
1348       array_specifier->print();
1349 }
1350 
1351 
1352 void
print(void) const1353 ast_compound_statement::print(void) const
1354 {
1355    printf("{\n");
1356 
1357    foreach_list_typed(ast_node, ast, link, &this->statements) {
1358       ast->print();
1359    }
1360 
1361    printf("}\n");
1362 }
1363 
1364 
ast_compound_statement(int new_scope,ast_node * statements)1365 ast_compound_statement::ast_compound_statement(int new_scope,
1366 					       ast_node *statements)
1367 {
1368    this->new_scope = new_scope;
1369 
1370    if (statements != NULL) {
1371       this->statements.push_degenerate_list_at_head(&statements->link);
1372    }
1373 }
1374 
1375 
1376 void
print(void) const1377 ast_expression::print(void) const
1378 {
1379    switch (oper) {
1380    case ast_assign:
1381    case ast_mul_assign:
1382    case ast_div_assign:
1383    case ast_mod_assign:
1384    case ast_add_assign:
1385    case ast_sub_assign:
1386    case ast_ls_assign:
1387    case ast_rs_assign:
1388    case ast_and_assign:
1389    case ast_xor_assign:
1390    case ast_or_assign:
1391       subexpressions[0]->print();
1392       printf("%s ", operator_string(oper));
1393       subexpressions[1]->print();
1394       break;
1395 
1396    case ast_field_selection:
1397       subexpressions[0]->print();
1398       printf(". %s ", primary_expression.identifier);
1399       break;
1400 
1401    case ast_plus:
1402    case ast_neg:
1403    case ast_bit_not:
1404    case ast_logic_not:
1405    case ast_pre_inc:
1406    case ast_pre_dec:
1407       printf("%s ", operator_string(oper));
1408       subexpressions[0]->print();
1409       break;
1410 
1411    case ast_post_inc:
1412    case ast_post_dec:
1413       subexpressions[0]->print();
1414       printf("%s ", operator_string(oper));
1415       break;
1416 
1417    case ast_conditional:
1418       subexpressions[0]->print();
1419       printf("? ");
1420       subexpressions[1]->print();
1421       printf(": ");
1422       subexpressions[2]->print();
1423       break;
1424 
1425    case ast_array_index:
1426       subexpressions[0]->print();
1427       printf("[ ");
1428       subexpressions[1]->print();
1429       printf("] ");
1430       break;
1431 
1432    case ast_function_call: {
1433       subexpressions[0]->print();
1434       printf("( ");
1435 
1436       foreach_list_typed (ast_node, ast, link, &this->expressions) {
1437 	 if (&ast->link != this->expressions.get_head())
1438 	    printf(", ");
1439 
1440 	 ast->print();
1441       }
1442 
1443       printf(") ");
1444       break;
1445    }
1446 
1447    case ast_identifier:
1448       printf("%s ", primary_expression.identifier);
1449       break;
1450 
1451    case ast_int_constant:
1452       printf("%d ", primary_expression.int_constant);
1453       break;
1454 
1455    case ast_uint_constant:
1456       printf("%u ", primary_expression.uint_constant);
1457       break;
1458 
1459    case ast_float_constant:
1460       printf("%f ", primary_expression.float_constant);
1461       break;
1462 
1463    case ast_double_constant:
1464       printf("%f ", primary_expression.double_constant);
1465       break;
1466 
1467    case ast_int64_constant:
1468       printf("%" PRId64 " ", primary_expression.int64_constant);
1469       break;
1470 
1471    case ast_uint64_constant:
1472       printf("%" PRIu64 " ", primary_expression.uint64_constant);
1473       break;
1474 
1475    case ast_bool_constant:
1476       printf("%s ",
1477 	     primary_expression.bool_constant
1478 	     ? "true" : "false");
1479       break;
1480 
1481    case ast_sequence: {
1482       printf("( ");
1483       foreach_list_typed (ast_node, ast, link, & this->expressions) {
1484 	 if (&ast->link != this->expressions.get_head())
1485 	    printf(", ");
1486 
1487 	 ast->print();
1488       }
1489       printf(") ");
1490       break;
1491    }
1492 
1493    case ast_aggregate: {
1494       printf("{ ");
1495       foreach_list_typed (ast_node, ast, link, & this->expressions) {
1496 	 if (&ast->link != this->expressions.get_head())
1497 	    printf(", ");
1498 
1499 	 ast->print();
1500       }
1501       printf("} ");
1502       break;
1503    }
1504 
1505    default:
1506       assert(0);
1507       break;
1508    }
1509 }
1510 
ast_expression(int oper,ast_expression * ex0,ast_expression * ex1,ast_expression * ex2)1511 ast_expression::ast_expression(int oper,
1512 			       ast_expression *ex0,
1513 			       ast_expression *ex1,
1514 			       ast_expression *ex2) :
1515    primary_expression()
1516 {
1517    this->oper = ast_operators(oper);
1518    this->subexpressions[0] = ex0;
1519    this->subexpressions[1] = ex1;
1520    this->subexpressions[2] = ex2;
1521    this->non_lvalue_description = NULL;
1522    this->is_lhs = false;
1523 }
1524 
1525 
1526 void
print(void) const1527 ast_expression_statement::print(void) const
1528 {
1529    if (expression)
1530       expression->print();
1531 
1532    printf("; ");
1533 }
1534 
1535 
ast_expression_statement(ast_expression * ex)1536 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
1537    expression(ex)
1538 {
1539    /* empty */
1540 }
1541 
1542 
1543 void
print(void) const1544 ast_function::print(void) const
1545 {
1546    return_type->print();
1547    printf(" %s (", identifier);
1548 
1549    foreach_list_typed(ast_node, ast, link, & this->parameters) {
1550       ast->print();
1551    }
1552 
1553    printf(")");
1554 }
1555 
1556 
ast_function(void)1557 ast_function::ast_function(void)
1558    : return_type(NULL), identifier(NULL), is_definition(false),
1559      signature(NULL)
1560 {
1561    /* empty */
1562 }
1563 
1564 
1565 void
print(void) const1566 ast_fully_specified_type::print(void) const
1567 {
1568    _mesa_ast_type_qualifier_print(& qualifier);
1569    specifier->print();
1570 }
1571 
1572 
1573 void
print(void) const1574 ast_parameter_declarator::print(void) const
1575 {
1576    type->print();
1577    if (identifier)
1578       printf("%s ", identifier);
1579    ast_opt_array_dimensions_print(array_specifier);
1580 }
1581 
1582 
1583 void
print(void) const1584 ast_function_definition::print(void) const
1585 {
1586    prototype->print();
1587    body->print();
1588 }
1589 
1590 
1591 void
print(void) const1592 ast_declaration::print(void) const
1593 {
1594    printf("%s ", identifier);
1595    ast_opt_array_dimensions_print(array_specifier);
1596 
1597    if (initializer) {
1598       printf("= ");
1599       initializer->print();
1600    }
1601 }
1602 
1603 
ast_declaration(const char * identifier,ast_array_specifier * array_specifier,ast_expression * initializer)1604 ast_declaration::ast_declaration(const char *identifier,
1605 				 ast_array_specifier *array_specifier,
1606 				 ast_expression *initializer)
1607 {
1608    this->identifier = identifier;
1609    this->array_specifier = array_specifier;
1610    this->initializer = initializer;
1611 }
1612 
1613 
1614 void
print(void) const1615 ast_declarator_list::print(void) const
1616 {
1617    assert(type || invariant);
1618 
1619    if (type)
1620       type->print();
1621    else if (invariant)
1622       printf("invariant ");
1623    else
1624       printf("precise ");
1625 
1626    foreach_list_typed (ast_node, ast, link, & this->declarations) {
1627       if (&ast->link != this->declarations.get_head())
1628 	 printf(", ");
1629 
1630       ast->print();
1631    }
1632 
1633    printf("; ");
1634 }
1635 
1636 
ast_declarator_list(ast_fully_specified_type * type)1637 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
1638 {
1639    this->type = type;
1640    this->invariant = false;
1641    this->precise = false;
1642 }
1643 
1644 void
print(void) const1645 ast_jump_statement::print(void) const
1646 {
1647    switch (mode) {
1648    case ast_continue:
1649       printf("continue; ");
1650       break;
1651    case ast_break:
1652       printf("break; ");
1653       break;
1654    case ast_return:
1655       printf("return ");
1656       if (opt_return_value)
1657 	 opt_return_value->print();
1658 
1659       printf("; ");
1660       break;
1661    case ast_discard:
1662       printf("discard; ");
1663       break;
1664    }
1665 }
1666 
1667 
ast_jump_statement(int mode,ast_expression * return_value)1668 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
1669    : opt_return_value(NULL)
1670 {
1671    this->mode = ast_jump_modes(mode);
1672 
1673    if (mode == ast_return)
1674       opt_return_value = return_value;
1675 }
1676 
1677 
1678 void
print(void) const1679 ast_demote_statement::print(void) const
1680 {
1681    printf("demote; ");
1682 }
1683 
1684 
1685 void
print(void) const1686 ast_selection_statement::print(void) const
1687 {
1688    printf("if ( ");
1689    condition->print();
1690    printf(") ");
1691 
1692    then_statement->print();
1693 
1694    if (else_statement) {
1695       printf("else ");
1696       else_statement->print();
1697    }
1698 }
1699 
1700 
ast_selection_statement(ast_expression * condition,ast_node * then_statement,ast_node * else_statement)1701 ast_selection_statement::ast_selection_statement(ast_expression *condition,
1702 						 ast_node *then_statement,
1703 						 ast_node *else_statement)
1704 {
1705    this->condition = condition;
1706    this->then_statement = then_statement;
1707    this->else_statement = else_statement;
1708 }
1709 
1710 
1711 void
print(void) const1712 ast_switch_statement::print(void) const
1713 {
1714    printf("switch ( ");
1715    test_expression->print();
1716    printf(") ");
1717 
1718    body->print();
1719 }
1720 
1721 
ast_switch_statement(ast_expression * test_expression,ast_node * body)1722 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
1723 					   ast_node *body)
1724 {
1725    this->test_expression = test_expression;
1726    this->body = body;
1727    this->test_val = NULL;
1728 }
1729 
1730 
1731 void
print(void) const1732 ast_switch_body::print(void) const
1733 {
1734    printf("{\n");
1735    if (stmts != NULL) {
1736       stmts->print();
1737    }
1738    printf("}\n");
1739 }
1740 
1741 
ast_switch_body(ast_case_statement_list * stmts)1742 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
1743 {
1744    this->stmts = stmts;
1745 }
1746 
1747 
print(void) const1748 void ast_case_label::print(void) const
1749 {
1750    if (test_value != NULL) {
1751       printf("case ");
1752       test_value->print();
1753       printf(": ");
1754    } else {
1755       printf("default: ");
1756    }
1757 }
1758 
1759 
ast_case_label(ast_expression * test_value)1760 ast_case_label::ast_case_label(ast_expression *test_value)
1761 {
1762    this->test_value = test_value;
1763 }
1764 
1765 
print(void) const1766 void ast_case_label_list::print(void) const
1767 {
1768    foreach_list_typed(ast_node, ast, link, & this->labels) {
1769       ast->print();
1770    }
1771    printf("\n");
1772 }
1773 
1774 
ast_case_label_list(void)1775 ast_case_label_list::ast_case_label_list(void)
1776 {
1777 }
1778 
1779 
print(void) const1780 void ast_case_statement::print(void) const
1781 {
1782    labels->print();
1783    foreach_list_typed(ast_node, ast, link, & this->stmts) {
1784       ast->print();
1785       printf("\n");
1786    }
1787 }
1788 
1789 
ast_case_statement(ast_case_label_list * labels)1790 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
1791 {
1792    this->labels = labels;
1793 }
1794 
1795 
print(void) const1796 void ast_case_statement_list::print(void) const
1797 {
1798    foreach_list_typed(ast_node, ast, link, & this->cases) {
1799       ast->print();
1800    }
1801 }
1802 
1803 
ast_case_statement_list(void)1804 ast_case_statement_list::ast_case_statement_list(void)
1805 {
1806 }
1807 
1808 
1809 void
print(void) const1810 ast_iteration_statement::print(void) const
1811 {
1812    switch (mode) {
1813    case ast_for:
1814       printf("for( ");
1815       if (init_statement)
1816 	 init_statement->print();
1817       printf("; ");
1818 
1819       if (condition)
1820 	 condition->print();
1821       printf("; ");
1822 
1823       if (rest_expression)
1824 	 rest_expression->print();
1825       printf(") ");
1826 
1827       body->print();
1828       break;
1829 
1830    case ast_while:
1831       printf("while ( ");
1832       if (condition)
1833 	 condition->print();
1834       printf(") ");
1835       body->print();
1836       break;
1837 
1838    case ast_do_while:
1839       printf("do ");
1840       body->print();
1841       printf("while ( ");
1842       if (condition)
1843 	 condition->print();
1844       printf("); ");
1845       break;
1846    }
1847 }
1848 
1849 
ast_iteration_statement(int mode,ast_node * init,ast_node * condition,ast_expression * rest_expression,ast_node * body)1850 ast_iteration_statement::ast_iteration_statement(int mode,
1851 						 ast_node *init,
1852 						 ast_node *condition,
1853 						 ast_expression *rest_expression,
1854 						 ast_node *body)
1855 {
1856    this->mode = ast_iteration_modes(mode);
1857    this->init_statement = init;
1858    this->condition = condition;
1859    this->rest_expression = rest_expression;
1860    this->body = body;
1861 }
1862 
1863 
1864 void
print(void) const1865 ast_struct_specifier::print(void) const
1866 {
1867    printf("struct %s { ", name);
1868    foreach_list_typed(ast_node, ast, link, &this->declarations) {
1869       ast->print();
1870    }
1871    printf("} ");
1872 }
1873 
1874 
ast_struct_specifier(const char * identifier,ast_declarator_list * declarator_list)1875 ast_struct_specifier::ast_struct_specifier(const char *identifier,
1876 					   ast_declarator_list *declarator_list)
1877    : name(identifier), layout(NULL), declarations(), is_declaration(true),
1878      type(NULL)
1879 {
1880    this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1881 }
1882 
print(void) const1883 void ast_subroutine_list::print(void) const
1884 {
1885    foreach_list_typed (ast_node, ast, link, & this->declarations) {
1886       if (&ast->link != this->declarations.get_head())
1887          printf(", ");
1888       ast->print();
1889    }
1890 }
1891 
1892 static void
set_shader_inout_layout(struct gl_shader * shader,struct _mesa_glsl_parse_state * state)1893 set_shader_inout_layout(struct gl_shader *shader,
1894 		     struct _mesa_glsl_parse_state *state)
1895 {
1896    /* Should have been prevented by the parser. */
1897    if (shader->Stage != MESA_SHADER_GEOMETRY &&
1898        shader->Stage != MESA_SHADER_TESS_EVAL &&
1899        shader->Stage != MESA_SHADER_COMPUTE) {
1900       assert(!state->in_qualifier->flags.i);
1901    }
1902 
1903    if (shader->Stage != MESA_SHADER_COMPUTE) {
1904       /* Should have been prevented by the parser. */
1905       assert(!state->cs_input_local_size_specified);
1906       assert(!state->cs_input_local_size_variable_specified);
1907       assert(state->cs_derivative_group == DERIVATIVE_GROUP_NONE);
1908    }
1909 
1910    if (shader->Stage != MESA_SHADER_FRAGMENT) {
1911       /* Should have been prevented by the parser. */
1912       assert(!state->fs_uses_gl_fragcoord);
1913       assert(!state->fs_redeclares_gl_fragcoord);
1914       assert(!state->fs_pixel_center_integer);
1915       assert(!state->fs_origin_upper_left);
1916       assert(!state->fs_early_fragment_tests);
1917       assert(!state->fs_inner_coverage);
1918       assert(!state->fs_post_depth_coverage);
1919       assert(!state->fs_pixel_interlock_ordered);
1920       assert(!state->fs_pixel_interlock_unordered);
1921       assert(!state->fs_sample_interlock_ordered);
1922       assert(!state->fs_sample_interlock_unordered);
1923    }
1924 
1925    for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1926       if (state->out_qualifier->out_xfb_stride[i]) {
1927          unsigned xfb_stride;
1928          if (state->out_qualifier->out_xfb_stride[i]->
1929                 process_qualifier_constant(state, "xfb_stride", &xfb_stride,
1930                 true)) {
1931             shader->TransformFeedbackBufferStride[i] = xfb_stride;
1932          }
1933       }
1934    }
1935 
1936    switch (shader->Stage) {
1937    case MESA_SHADER_TESS_CTRL:
1938       shader->info.TessCtrl.VerticesOut = 0;
1939       if (state->tcs_output_vertices_specified) {
1940          unsigned vertices;
1941          if (state->out_qualifier->vertices->
1942                process_qualifier_constant(state, "vertices", &vertices,
1943                                           false)) {
1944 
1945             YYLTYPE loc = state->out_qualifier->vertices->get_location();
1946             if (vertices > state->Const.MaxPatchVertices) {
1947                _mesa_glsl_error(&loc, state, "vertices (%d) exceeds "
1948                                 "GL_MAX_PATCH_VERTICES", vertices);
1949             }
1950             shader->info.TessCtrl.VerticesOut = vertices;
1951          }
1952       }
1953       break;
1954    case MESA_SHADER_TESS_EVAL:
1955       shader->info.TessEval._PrimitiveMode = TESS_PRIMITIVE_UNSPECIFIED;
1956       if (state->in_qualifier->flags.q.prim_type) {
1957          switch (state->in_qualifier->prim_type) {
1958          case GL_TRIANGLES:
1959             shader->info.TessEval._PrimitiveMode = TESS_PRIMITIVE_TRIANGLES;
1960             break;
1961          case GL_QUADS:
1962             shader->info.TessEval._PrimitiveMode = TESS_PRIMITIVE_QUADS;
1963             break;
1964          case GL_ISOLINES:
1965             shader->info.TessEval._PrimitiveMode = TESS_PRIMITIVE_ISOLINES;
1966             break;
1967          }
1968       }
1969 
1970       shader->info.TessEval.Spacing = TESS_SPACING_UNSPECIFIED;
1971       if (state->in_qualifier->flags.q.vertex_spacing)
1972          shader->info.TessEval.Spacing = state->in_qualifier->vertex_spacing;
1973 
1974       shader->info.TessEval.VertexOrder = 0;
1975       if (state->in_qualifier->flags.q.ordering)
1976          shader->info.TessEval.VertexOrder = state->in_qualifier->ordering;
1977 
1978       shader->info.TessEval.PointMode = -1;
1979       if (state->in_qualifier->flags.q.point_mode)
1980          shader->info.TessEval.PointMode = state->in_qualifier->point_mode;
1981       break;
1982    case MESA_SHADER_GEOMETRY:
1983       shader->info.Geom.VerticesOut = -1;
1984       if (state->out_qualifier->flags.q.max_vertices) {
1985          unsigned qual_max_vertices;
1986          if (state->out_qualifier->max_vertices->
1987                process_qualifier_constant(state, "max_vertices",
1988                                           &qual_max_vertices, true)) {
1989 
1990             if (qual_max_vertices > state->Const.MaxGeometryOutputVertices) {
1991                YYLTYPE loc = state->out_qualifier->max_vertices->get_location();
1992                _mesa_glsl_error(&loc, state,
1993                                 "maximum output vertices (%d) exceeds "
1994                                 "GL_MAX_GEOMETRY_OUTPUT_VERTICES",
1995                                 qual_max_vertices);
1996             }
1997             shader->info.Geom.VerticesOut = qual_max_vertices;
1998          }
1999       }
2000 
2001       if (state->gs_input_prim_type_specified) {
2002          shader->info.Geom.InputType =
2003             gl_to_mesa_prim(state->in_qualifier->prim_type);
2004       } else {
2005          shader->info.Geom.InputType = MESA_PRIM_UNKNOWN;
2006       }
2007 
2008       if (state->out_qualifier->flags.q.prim_type) {
2009          shader->info.Geom.OutputType =
2010             gl_to_mesa_prim(state->out_qualifier->prim_type);
2011       } else {
2012          shader->info.Geom.OutputType = MESA_PRIM_UNKNOWN;
2013       }
2014 
2015       shader->info.Geom.Invocations = 0;
2016       if (state->in_qualifier->flags.q.invocations) {
2017          unsigned invocations;
2018          if (state->in_qualifier->invocations->
2019                process_qualifier_constant(state, "invocations",
2020                                           &invocations, false)) {
2021 
2022             YYLTYPE loc = state->in_qualifier->invocations->get_location();
2023             if (invocations > state->Const.MaxGeometryShaderInvocations) {
2024                _mesa_glsl_error(&loc, state,
2025                                 "invocations (%d) exceeds "
2026                                 "GL_MAX_GEOMETRY_SHADER_INVOCATIONS",
2027                                 invocations);
2028             }
2029             shader->info.Geom.Invocations = invocations;
2030          }
2031       }
2032       break;
2033 
2034    case MESA_SHADER_COMPUTE:
2035       if (state->cs_input_local_size_specified) {
2036          for (int i = 0; i < 3; i++)
2037             shader->info.Comp.LocalSize[i] = state->cs_input_local_size[i];
2038       } else {
2039          for (int i = 0; i < 3; i++)
2040             shader->info.Comp.LocalSize[i] = 0;
2041       }
2042 
2043       shader->info.Comp.LocalSizeVariable =
2044          state->cs_input_local_size_variable_specified;
2045 
2046       shader->info.Comp.DerivativeGroup = state->cs_derivative_group;
2047 
2048       if (state->NV_compute_shader_derivatives_enable) {
2049          /* We allow multiple cs_input_layout nodes, but do not store them in
2050           * a convenient place, so for now live with an empty location error.
2051           */
2052          YYLTYPE loc = {0};
2053          if (shader->info.Comp.DerivativeGroup == DERIVATIVE_GROUP_QUADS) {
2054             if (shader->info.Comp.LocalSize[0] % 2 != 0) {
2055                _mesa_glsl_error(&loc, state, "derivative_group_quadsNV must be used with a "
2056                                 "local group size whose first dimension "
2057                                 "is a multiple of 2\n");
2058             }
2059             if (shader->info.Comp.LocalSize[1] % 2 != 0) {
2060                _mesa_glsl_error(&loc, state, "derivative_group_quadsNV must be used with a "
2061                                 "local group size whose second dimension "
2062                                 "is a multiple of 2\n");
2063             }
2064          } else if (shader->info.Comp.DerivativeGroup == DERIVATIVE_GROUP_LINEAR) {
2065             if ((shader->info.Comp.LocalSize[0] *
2066                  shader->info.Comp.LocalSize[1] *
2067                  shader->info.Comp.LocalSize[2]) % 4 != 0) {
2068                _mesa_glsl_error(&loc, state, "derivative_group_linearNV must be used with a "
2069                             "local group size whose total number of invocations "
2070                             "is a multiple of 4\n");
2071             }
2072          }
2073       }
2074 
2075       break;
2076 
2077    case MESA_SHADER_FRAGMENT:
2078       shader->redeclares_gl_fragcoord = state->fs_redeclares_gl_fragcoord;
2079       shader->uses_gl_fragcoord = state->fs_uses_gl_fragcoord;
2080       shader->pixel_center_integer = state->fs_pixel_center_integer;
2081       shader->origin_upper_left = state->fs_origin_upper_left;
2082       shader->ARB_fragment_coord_conventions_enable =
2083          state->ARB_fragment_coord_conventions_enable;
2084       shader->EarlyFragmentTests = state->fs_early_fragment_tests;
2085       shader->InnerCoverage = state->fs_inner_coverage;
2086       shader->PostDepthCoverage = state->fs_post_depth_coverage;
2087       shader->PixelInterlockOrdered = state->fs_pixel_interlock_ordered;
2088       shader->PixelInterlockUnordered = state->fs_pixel_interlock_unordered;
2089       shader->SampleInterlockOrdered = state->fs_sample_interlock_ordered;
2090       shader->SampleInterlockUnordered = state->fs_sample_interlock_unordered;
2091       shader->BlendSupport = state->fs_blend_support;
2092       break;
2093 
2094    default:
2095       /* Nothing to do. */
2096       break;
2097    }
2098 
2099    shader->view_mask = state->view_mask;
2100    shader->bindless_sampler = state->bindless_sampler_specified;
2101    shader->bindless_image = state->bindless_image_specified;
2102    shader->bound_sampler = state->bound_sampler_specified;
2103    shader->bound_image = state->bound_image_specified;
2104    shader->redeclares_gl_layer = state->redeclares_gl_layer;
2105    shader->layer_viewport_relative = state->layer_viewport_relative;
2106 }
2107 
2108 extern "C" {
2109 
2110 static void
assign_subroutine_indexes(struct _mesa_glsl_parse_state * state)2111 assign_subroutine_indexes(struct _mesa_glsl_parse_state *state)
2112 {
2113    int j, k;
2114    int index = 0;
2115 
2116    for (j = 0; j < state->num_subroutines; j++) {
2117       while (state->subroutines[j]->subroutine_index == -1) {
2118          for (k = 0; k < state->num_subroutines; k++) {
2119             if (state->subroutines[k]->subroutine_index == index)
2120                break;
2121             else if (k == state->num_subroutines - 1) {
2122                state->subroutines[j]->subroutine_index = index;
2123             }
2124          }
2125          index++;
2126       }
2127    }
2128 }
2129 
2130 static void
add_builtin_defines(struct _mesa_glsl_parse_state * state,void (* add_builtin_define)(struct glcpp_parser *,const char *,int),struct glcpp_parser * data,unsigned version,bool es)2131 add_builtin_defines(struct _mesa_glsl_parse_state *state,
2132                     void (*add_builtin_define)(struct glcpp_parser *, const char *, int),
2133                     struct glcpp_parser *data,
2134                     unsigned version,
2135                     bool es)
2136 {
2137    unsigned gl_version = state->exts->Version;
2138    gl_api api = state->api;
2139 
2140    if (gl_version != 0xff) {
2141       unsigned i;
2142       for (i = 0; i < state->num_supported_versions; i++) {
2143          if (state->supported_versions[i].ver == version &&
2144              state->supported_versions[i].es == es) {
2145             gl_version = state->supported_versions[i].gl_ver;
2146             break;
2147          }
2148       }
2149 
2150       if (i == state->num_supported_versions)
2151          return;
2152    }
2153 
2154    if (es)
2155       api = API_OPENGLES2;
2156 
2157    for (unsigned i = 0;
2158         i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
2159       const _mesa_glsl_extension *extension
2160          = &_mesa_glsl_supported_extensions[i];
2161       if (extension->compatible_with_state(state, api, gl_version)) {
2162          add_builtin_define(data, extension->name, 1);
2163       }
2164    }
2165 }
2166 
2167 /* Implements parsing checks that we can't do during parsing */
2168 static void
do_late_parsing_checks(struct _mesa_glsl_parse_state * state)2169 do_late_parsing_checks(struct _mesa_glsl_parse_state *state)
2170 {
2171    if (state->stage == MESA_SHADER_COMPUTE && !state->has_compute_shader()) {
2172       YYLTYPE loc;
2173       memset(&loc, 0, sizeof(loc));
2174       _mesa_glsl_error(&loc, state, "Compute shaders require "
2175                        "GLSL 4.30 or GLSL ES 3.10");
2176    }
2177 }
2178 
2179 static void
opt_shader(const struct gl_constants * consts,const struct gl_extensions * exts,struct gl_shader * shader)2180 opt_shader(const struct gl_constants *consts,
2181            const struct gl_extensions *exts,
2182            struct gl_shader *shader)
2183 {
2184    assert(shader->CompileStatus != COMPILE_FAILURE &&
2185           !shader->ir->is_empty());
2186 
2187    const struct gl_shader_compiler_options *options =
2188       &consts->ShaderCompilerOptions[shader->Stage];
2189 
2190    /* Do some optimization at compile time to reduce shader IR size
2191     * and reduce later work if the same shader is linked multiple times.
2192     *
2193     * Run it just once, since NIR will do the real optimization.
2194     */
2195    do_common_optimization(shader->ir, false, options, consts->NativeIntegers);
2196 
2197    validate_ir_tree(shader->ir);
2198 
2199    enum ir_variable_mode other;
2200    switch (shader->Stage) {
2201    case MESA_SHADER_VERTEX:
2202       other = ir_var_shader_in;
2203       break;
2204    case MESA_SHADER_FRAGMENT:
2205       other = ir_var_shader_out;
2206       break;
2207    default:
2208       /* Something invalid to ensure optimize_dead_builtin_uniforms
2209        * doesn't remove anything other than uniforms or constants.
2210        */
2211       other = ir_var_mode_count;
2212       break;
2213    }
2214 
2215    optimize_dead_builtin_variables(shader->ir, other);
2216 
2217    lower_vector_derefs(shader);
2218 
2219    lower_packing_builtins(shader->ir, exts->ARB_shading_language_packing,
2220                           exts->ARB_gpu_shader5,
2221                           consts->GLSLHasHalfFloatPacking);
2222    do_mat_op_to_vec(shader->ir);
2223 
2224    lower_instructions(shader->ir, consts->ForceGLSLAbsSqrt,
2225                       exts->ARB_gpu_shader5);
2226 
2227    do_vec_index_to_cond_assign(shader->ir);
2228 
2229    validate_ir_tree(shader->ir);
2230 
2231    /* Retain any live IR, but trash the rest. */
2232    reparent_ir(shader->ir, shader->ir);
2233 }
2234 
2235 static bool
can_skip_compile(struct gl_context * ctx,struct gl_shader * shader,const char * source,const blake3_hash source_blake3,bool force_recompile,bool source_has_shader_include)2236 can_skip_compile(struct gl_context *ctx, struct gl_shader *shader,
2237                  const char *source, const blake3_hash source_blake3,
2238                  bool force_recompile, bool source_has_shader_include)
2239 {
2240    if (!force_recompile) {
2241       if (ctx->Cache) {
2242          char buf[41];
2243          disk_cache_compute_key(ctx->Cache, source, strlen(source),
2244                                 shader->disk_cache_sha1);
2245          if (disk_cache_has_key(ctx->Cache, shader->disk_cache_sha1)) {
2246             /* We've seen this shader before and know it compiles */
2247             if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
2248                _mesa_sha1_format(buf, shader->disk_cache_sha1);
2249                fprintf(stderr, "deferring compile of shader: %s\n", buf);
2250             }
2251             shader->CompileStatus = COMPILE_SKIPPED;
2252 
2253             free((void *)shader->FallbackSource);
2254 
2255             /* Copy pre-processed shader include to fallback source otherwise
2256              * we have no guarantee the shader include source tree has not
2257              * changed.
2258              */
2259             if (source_has_shader_include) {
2260                shader->FallbackSource = strdup(source);
2261                memcpy(shader->fallback_source_blake3, source_blake3,
2262                       BLAKE3_OUT_LEN);
2263             } else {
2264                shader->FallbackSource = NULL;
2265             }
2266             memcpy(shader->compiled_source_blake3, source_blake3,
2267                    BLAKE3_OUT_LEN);
2268             return true;
2269          }
2270       }
2271    } else {
2272       /* We should only ever end up here if a re-compile has been forced by a
2273        * shader cache miss. In which case we can skip the compile if its
2274        * already been done by a previous fallback or the initial compile call.
2275        */
2276       if (shader->CompileStatus == COMPILE_SUCCESS)
2277          return true;
2278    }
2279 
2280    return false;
2281 }
2282 
2283 static void
log_compile_skip(struct gl_context * ctx,struct gl_shader * shader)2284 log_compile_skip(struct gl_context *ctx, struct gl_shader *shader)
2285 {
2286    if (ctx->_Shader->Flags & GLSL_DUMP) {
2287       _mesa_log("No GLSL IR for shader %d (shader may be from cache)\n",
2288                 shader->Name);
2289    }
2290 }
2291 
2292 void
_mesa_glsl_compile_shader(struct gl_context * ctx,struct gl_shader * shader,FILE * dump_ir_file,bool dump_ast,bool dump_hir,bool force_recompile)2293 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader,
2294                           FILE *dump_ir_file, bool dump_ast, bool dump_hir,
2295                           bool force_recompile)
2296 {
2297    const char *source;
2298    const uint8_t *source_blake3;
2299 
2300    if (force_recompile && shader->FallbackSource) {
2301       source = shader->FallbackSource;
2302       source_blake3 = shader->fallback_source_blake3;
2303    } else {
2304       source = shader->Source;
2305       source_blake3 = shader->source_blake3;
2306    }
2307 
2308    /* Note this will be true for shaders the have #include inside comments
2309     * however that should be rare enough not to worry about.
2310     */
2311    bool source_has_shader_include =
2312       strstr(source, "#include") == NULL ? false : true;
2313 
2314    /* If there was no shader include we can check the shader cache and skip
2315     * compilation before we run the preprocessor. We never skip compiling
2316     * shaders that use ARB_shading_language_include because we would need to
2317     * keep duplicate copies of the shader include source tree and paths.
2318     */
2319    if (!source_has_shader_include &&
2320        can_skip_compile(ctx, shader, source, source_blake3, force_recompile,
2321                         false)) {
2322       log_compile_skip(ctx, shader);
2323       return;
2324    }
2325 
2326     struct _mesa_glsl_parse_state *state =
2327       new(shader) _mesa_glsl_parse_state(ctx, shader->Stage, shader);
2328 
2329    if (ctx->Const.GenerateTemporaryNames)
2330       (void) p_atomic_cmpxchg(&ir_variable::temporaries_allocate_names,
2331                               false, true);
2332 
2333    if (!source_has_shader_include || !force_recompile) {
2334       state->error = glcpp_preprocess(state, &source, &state->info_log,
2335                                       add_builtin_defines, state, ctx);
2336    }
2337 
2338    /* Now that we have run the preprocessor we can check the shader cache and
2339     * skip compilation if possible for those shaders that contained a shader
2340     * include.
2341     */
2342    if (source_has_shader_include &&
2343        can_skip_compile(ctx, shader, source, source_blake3, force_recompile,
2344                         true)) {
2345       log_compile_skip(ctx, shader);
2346       return;
2347    }
2348 
2349    if (!state->error) {
2350      _mesa_glsl_lexer_ctor(state, source);
2351      _mesa_glsl_parse(state);
2352      _mesa_glsl_lexer_dtor(state);
2353      do_late_parsing_checks(state);
2354    }
2355 
2356    if (dump_ast) {
2357       foreach_list_typed(ast_node, ast, link, &state->translation_unit) {
2358          ast->print();
2359       }
2360       printf("\n\n");
2361    }
2362 
2363    ralloc_free(shader->ir);
2364    ralloc_free(shader->nir);
2365    shader->nir = NULL;
2366    shader->ir = new(shader) exec_list;
2367    if (!state->error && !state->translation_unit.is_empty())
2368       _mesa_ast_to_hir(shader->ir, state);
2369 
2370    if (!state->error) {
2371       validate_ir_tree(shader->ir);
2372 
2373       /* Print out the unoptimized IR. */
2374       if (dump_hir) {
2375          _mesa_print_ir(stdout, shader->ir, state);
2376       }
2377    }
2378 
2379    if (shader->InfoLog)
2380       ralloc_free(shader->InfoLog);
2381 
2382    if (!state->error)
2383       set_shader_inout_layout(shader, state);
2384 
2385    shader->CompileStatus = state->error ? COMPILE_FAILURE : COMPILE_SUCCESS;
2386    shader->InfoLog = state->info_log;
2387    shader->Version = state->language_version;
2388    shader->IsES = state->es_shader;
2389    shader->has_implicit_conversions = state->has_implicit_conversions();
2390    shader->has_implicit_int_to_uint_conversion =
2391       state->has_implicit_int_to_uint_conversion();
2392    shader->KHR_shader_subgroup_basic_enable = state->KHR_shader_subgroup_basic_enable;
2393 
2394    struct gl_shader_compiler_options *options =
2395       &ctx->Const.ShaderCompilerOptions[shader->Stage];
2396 
2397    if (!state->error && !shader->ir->is_empty()) {
2398       if (state->es_shader &&
2399           (options->LowerPrecisionFloat16 || options->LowerPrecisionInt16))
2400          lower_precision(options, shader->ir);
2401       lower_builtins(shader->ir);
2402       assign_subroutine_indexes(state);
2403       lower_subroutine(shader->ir, state);
2404       opt_shader(&ctx->Const, &ctx->Extensions, shader);
2405    }
2406 
2407    if (!force_recompile) {
2408       free((void *)shader->FallbackSource);
2409 
2410       /* Copy pre-processed shader include to fallback source otherwise we
2411        * have no guarantee the shader include source tree has not changed.
2412        */
2413       if (source_has_shader_include) {
2414          shader->FallbackSource = strdup(source);
2415          memcpy(shader->fallback_source_blake3, source_blake3, BLAKE3_OUT_LEN);
2416       } else {
2417          shader->FallbackSource = NULL;
2418       }
2419    }
2420 
2421    delete state->symbols;
2422    ralloc_free(state);
2423 
2424    if (ctx->_Shader && ctx->_Shader->Flags & GLSL_DUMP) {
2425       if (shader->CompileStatus) {
2426          assert(shader->ir);
2427          _mesa_log("GLSL IR for shader %d:\n", shader->Name);
2428          _mesa_print_ir(mesa_log_get_file(), shader->ir, NULL);
2429          _mesa_log("\n\n");
2430       } else {
2431          _mesa_log("GLSL shader %d failed to compile.\n", shader->Name);
2432       }
2433       if (shader->InfoLog && shader->InfoLog[0] != 0) {
2434          _mesa_log("GLSL shader %d info log:\n", shader->Name);
2435          _mesa_log("%s\n", shader->InfoLog);
2436       }
2437    }
2438 
2439    if (dump_ir_file) {
2440       if (shader->CompileStatus) {
2441          assert(shader->ir);
2442          _mesa_print_ir(dump_ir_file, shader->ir, NULL);
2443       }
2444    }
2445 
2446    if (shader->CompileStatus == COMPILE_SUCCESS) {
2447       memcpy(shader->compiled_source_blake3, source_blake3, BLAKE3_OUT_LEN);
2448 
2449       shader->nir = glsl_to_nir(shader, options->NirOptions, source_blake3);
2450    }
2451 
2452    if (ctx->Cache && shader->CompileStatus == COMPILE_SUCCESS) {
2453       char sha1_buf[41];
2454       disk_cache_put_key(ctx->Cache, shader->disk_cache_sha1);
2455       if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
2456          _mesa_sha1_format(sha1_buf, shader->disk_cache_sha1);
2457          fprintf(stderr, "marking shader: %s\n", sha1_buf);
2458       }
2459    }
2460 }
2461 
2462 } /* extern "C" */
2463 /**
2464  * Do the set of common optimizations passes
2465  *
2466  * \param ir                          List of instructions to be optimized
2467  * \param linked                      Is the shader linked?  This enables
2468  *                                    optimizations passes that remove code at
2469  *                                    global scope and could cause linking to
2470  *                                    fail.
2471  * \param uniform_locations_assigned  Have locations already been assigned for
2472  *                                    uniforms?  This prevents the declarations
2473  *                                    of unused uniforms from being removed.
2474  *                                    The setting of this flag only matters if
2475  *                                    \c linked is \c true.
2476  * \param options                     The driver's preferred shader options.
2477  * \param native_integers             Selects optimizations that depend on the
2478  *                                    implementations supporting integers
2479  *                                    natively (as opposed to supporting
2480  *                                    integers in floating point registers).
2481  */
2482 bool
do_common_optimization(exec_list * ir,bool linked,const struct gl_shader_compiler_options * options,bool native_integers)2483 do_common_optimization(exec_list *ir, bool linked,
2484                        const struct gl_shader_compiler_options *options,
2485                        bool native_integers)
2486 {
2487    const bool debug = false;
2488    bool progress = false;
2489 
2490 #define OPT(PASS, ...) do {                                             \
2491       if (debug) {                                                      \
2492          fprintf(stderr, "START GLSL optimization %s\n", #PASS);        \
2493          const bool opt_progress = PASS(__VA_ARGS__);                   \
2494          progress = opt_progress || progress;                           \
2495          if (opt_progress)                                              \
2496             _mesa_print_ir(stderr, ir, NULL);                           \
2497          fprintf(stderr, "GLSL optimization %s: %s progress\n",         \
2498                  #PASS, opt_progress ? "made" : "no");                  \
2499       } else {                                                          \
2500          progress = PASS(__VA_ARGS__) || progress;                      \
2501       }                                                                 \
2502    } while (false)
2503 
2504    OPT(propagate_invariance, ir);
2505    OPT(do_if_simplification, ir);
2506    OPT(opt_flatten_nested_if_blocks, ir);
2507 
2508    if (options->OptimizeForAOS && !linked)
2509       OPT(opt_flip_matrices, ir);
2510 
2511    OPT(do_dead_code_unlinked, ir);
2512    OPT(do_tree_grafting, ir);
2513    OPT(do_minmax_prune, ir);
2514    OPT(do_rebalance_tree, ir);
2515    OPT(do_algebraic, ir, native_integers, options);
2516    OPT(do_lower_jumps, ir, true, options->EmitNoCont);
2517 
2518    /* If an optimization pass fails to preserve the invariant flag, calling
2519     * the pass only once earlier may result in incorrect code generation. Always call
2520     * propagate_invariance() last to avoid this possibility.
2521     */
2522    OPT(propagate_invariance, ir);
2523 
2524 #undef OPT
2525 
2526    return progress;
2527 }
2528