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