glsl: allow ForceGLSLVersion to override #version directives
[mesa.git] / src / glsl / glsl_parser_extras.cpp
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 <stdio.h>
24 #include <stdarg.h>
25 #include <string.h>
26 #include <assert.h>
27
28 #include "main/core.h" /* for struct gl_context */
29 #include "main/context.h"
30 #include "main/shaderobj.h"
31 #include "util/u_atomic.h" /* for p_atomic_cmpxchg */
32 #include "util/ralloc.h"
33 #include "ast.h"
34 #include "glsl_parser_extras.h"
35 #include "glsl_parser.h"
36 #include "ir_optimization.h"
37 #include "loop_analysis.h"
38
39 /**
40 * Format a short human-readable description of the given GLSL version.
41 */
42 const char *
43 glsl_compute_version_string(void *mem_ctx, bool is_es, unsigned version)
44 {
45 return ralloc_asprintf(mem_ctx, "GLSL%s %d.%02d", is_es ? " ES" : "",
46 version / 100, version % 100);
47 }
48
49
50 static const unsigned known_desktop_glsl_versions[] =
51 { 110, 120, 130, 140, 150, 330, 400, 410, 420, 430, 440, 450 };
52
53
54 _mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *_ctx,
55 gl_shader_stage stage,
56 void *mem_ctx)
57 : ctx(_ctx), cs_input_local_size_specified(false), cs_input_local_size(),
58 switch_state()
59 {
60 assert(stage < MESA_SHADER_STAGES);
61 this->stage = stage;
62
63 this->scanner = NULL;
64 this->translation_unit.make_empty();
65 this->symbols = new(mem_ctx) glsl_symbol_table;
66
67 this->info_log = ralloc_strdup(mem_ctx, "");
68 this->error = false;
69 this->loop_nesting_ast = NULL;
70
71 this->struct_specifier_depth = 0;
72
73 this->uses_builtin_functions = false;
74
75 /* Set default language version and extensions */
76 this->language_version = 110;
77 this->forced_language_version = ctx->Const.ForceGLSLVersion;
78 this->es_shader = false;
79 this->ARB_texture_rectangle_enable = true;
80
81 /* OpenGL ES 2.0 has different defaults from desktop GL. */
82 if (ctx->API == API_OPENGLES2) {
83 this->language_version = 100;
84 this->es_shader = true;
85 this->ARB_texture_rectangle_enable = false;
86 }
87
88 this->extensions = &ctx->Extensions;
89
90 this->Const.MaxLights = ctx->Const.MaxLights;
91 this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
92 this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
93 this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
94 this->Const.MaxVertexAttribs = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs;
95 this->Const.MaxVertexUniformComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents;
96 this->Const.MaxVertexTextureImageUnits = ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits;
97 this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
98 this->Const.MaxTextureImageUnits = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits;
99 this->Const.MaxFragmentUniformComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents;
100 this->Const.MinProgramTexelOffset = ctx->Const.MinProgramTexelOffset;
101 this->Const.MaxProgramTexelOffset = ctx->Const.MaxProgramTexelOffset;
102
103 this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
104
105 /* 1.50 constants */
106 this->Const.MaxVertexOutputComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents;
107 this->Const.MaxGeometryInputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxInputComponents;
108 this->Const.MaxGeometryOutputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxOutputComponents;
109 this->Const.MaxFragmentInputComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents;
110 this->Const.MaxGeometryTextureImageUnits = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits;
111 this->Const.MaxGeometryOutputVertices = ctx->Const.MaxGeometryOutputVertices;
112 this->Const.MaxGeometryTotalOutputComponents = ctx->Const.MaxGeometryTotalOutputComponents;
113 this->Const.MaxGeometryUniformComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxUniformComponents;
114
115 this->Const.MaxVertexAtomicCounters = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAtomicCounters;
116 this->Const.MaxGeometryAtomicCounters = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxAtomicCounters;
117 this->Const.MaxFragmentAtomicCounters = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAtomicCounters;
118 this->Const.MaxCombinedAtomicCounters = ctx->Const.MaxCombinedAtomicCounters;
119 this->Const.MaxAtomicBufferBindings = ctx->Const.MaxAtomicBufferBindings;
120
121 /* Compute shader constants */
122 for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupCount); i++)
123 this->Const.MaxComputeWorkGroupCount[i] = ctx->Const.MaxComputeWorkGroupCount[i];
124 for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupSize); i++)
125 this->Const.MaxComputeWorkGroupSize[i] = ctx->Const.MaxComputeWorkGroupSize[i];
126
127 this->Const.MaxImageUnits = ctx->Const.MaxImageUnits;
128 this->Const.MaxCombinedImageUnitsAndFragmentOutputs = ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs;
129 this->Const.MaxImageSamples = ctx->Const.MaxImageSamples;
130 this->Const.MaxVertexImageUniforms = ctx->Const.Program[MESA_SHADER_VERTEX].MaxImageUniforms;
131 this->Const.MaxGeometryImageUniforms = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxImageUniforms;
132 this->Const.MaxFragmentImageUniforms = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxImageUniforms;
133 this->Const.MaxCombinedImageUniforms = ctx->Const.MaxCombinedImageUniforms;
134
135 /* ARB_viewport_array */
136 this->Const.MaxViewports = ctx->Const.MaxViewports;
137
138 this->current_function = NULL;
139 this->toplevel_ir = NULL;
140 this->found_return = false;
141 this->all_invariant = false;
142 this->user_structures = NULL;
143 this->num_user_structures = 0;
144
145 /* supported_versions should be large enough to support the known desktop
146 * GLSL versions plus 2 GLES versions (ES2 & ES3)
147 */
148 STATIC_ASSERT((ARRAY_SIZE(known_desktop_glsl_versions) + 2) ==
149 ARRAY_SIZE(this->supported_versions));
150
151 /* Populate the list of supported GLSL versions */
152 /* FINISHME: Once the OpenGL 3.0 'forward compatible' context or
153 * the OpenGL 3.2 Core context is supported, this logic will need
154 * change. Older versions of GLSL are no longer supported
155 * outside the compatibility contexts of 3.x.
156 */
157 this->num_supported_versions = 0;
158 if (_mesa_is_desktop_gl(ctx)) {
159 for (unsigned i = 0; i < ARRAY_SIZE(known_desktop_glsl_versions); i++) {
160 if (known_desktop_glsl_versions[i] <= ctx->Const.GLSLVersion) {
161 this->supported_versions[this->num_supported_versions].ver
162 = known_desktop_glsl_versions[i];
163 this->supported_versions[this->num_supported_versions].es = false;
164 this->num_supported_versions++;
165 }
166 }
167 }
168 if (ctx->API == API_OPENGLES2 || ctx->Extensions.ARB_ES2_compatibility) {
169 this->supported_versions[this->num_supported_versions].ver = 100;
170 this->supported_versions[this->num_supported_versions].es = true;
171 this->num_supported_versions++;
172 }
173 if (_mesa_is_gles3(ctx) || ctx->Extensions.ARB_ES3_compatibility) {
174 this->supported_versions[this->num_supported_versions].ver = 300;
175 this->supported_versions[this->num_supported_versions].es = true;
176 this->num_supported_versions++;
177 }
178
179 /* Create a string for use in error messages to tell the user which GLSL
180 * versions are supported.
181 */
182 char *supported = ralloc_strdup(this, "");
183 for (unsigned i = 0; i < this->num_supported_versions; i++) {
184 unsigned ver = this->supported_versions[i].ver;
185 const char *const prefix = (i == 0)
186 ? ""
187 : ((i == this->num_supported_versions - 1) ? ", and " : ", ");
188 const char *const suffix = (this->supported_versions[i].es) ? " ES" : "";
189
190 ralloc_asprintf_append(& supported, "%s%u.%02u%s",
191 prefix,
192 ver / 100, ver % 100,
193 suffix);
194 }
195
196 this->supported_version_string = supported;
197
198 if (ctx->Const.ForceGLSLExtensionsWarn)
199 _mesa_glsl_process_extension("all", NULL, "warn", NULL, this);
200
201 this->default_uniform_qualifier = new(this) ast_type_qualifier();
202 this->default_uniform_qualifier->flags.q.shared = 1;
203 this->default_uniform_qualifier->flags.q.column_major = 1;
204
205 this->fs_uses_gl_fragcoord = false;
206 this->fs_redeclares_gl_fragcoord = false;
207 this->fs_origin_upper_left = false;
208 this->fs_pixel_center_integer = false;
209 this->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers = false;
210
211 this->gs_input_prim_type_specified = false;
212 this->gs_input_size = 0;
213 this->in_qualifier = new(this) ast_type_qualifier();
214 this->out_qualifier = new(this) ast_type_qualifier();
215 this->early_fragment_tests = false;
216 memset(this->atomic_counter_offsets, 0,
217 sizeof(this->atomic_counter_offsets));
218 this->allow_extension_directive_midshader =
219 ctx->Const.AllowGLSLExtensionDirectiveMidShader;
220 }
221
222 /**
223 * Determine whether the current GLSL version is sufficiently high to support
224 * a certain feature, and generate an error message if it isn't.
225 *
226 * \param required_glsl_version and \c required_glsl_es_version are
227 * interpreted as they are in _mesa_glsl_parse_state::is_version().
228 *
229 * \param locp is the parser location where the error should be reported.
230 *
231 * \param fmt (and additional arguments) constitute a printf-style error
232 * message to report if the version check fails. Information about the
233 * current and required GLSL versions will be appended. So, for example, if
234 * the GLSL version being compiled is 1.20, and check_version(130, 300, locp,
235 * "foo unsupported") is called, the error message will be "foo unsupported in
236 * GLSL 1.20 (GLSL 1.30 or GLSL 3.00 ES required)".
237 */
238 bool
239 _mesa_glsl_parse_state::check_version(unsigned required_glsl_version,
240 unsigned required_glsl_es_version,
241 YYLTYPE *locp, const char *fmt, ...)
242 {
243 if (this->is_version(required_glsl_version, required_glsl_es_version))
244 return true;
245
246 va_list args;
247 va_start(args, fmt);
248 char *problem = ralloc_vasprintf(this, fmt, args);
249 va_end(args);
250 const char *glsl_version_string
251 = glsl_compute_version_string(this, false, required_glsl_version);
252 const char *glsl_es_version_string
253 = glsl_compute_version_string(this, true, required_glsl_es_version);
254 const char *requirement_string = "";
255 if (required_glsl_version && required_glsl_es_version) {
256 requirement_string = ralloc_asprintf(this, " (%s or %s required)",
257 glsl_version_string,
258 glsl_es_version_string);
259 } else if (required_glsl_version) {
260 requirement_string = ralloc_asprintf(this, " (%s required)",
261 glsl_version_string);
262 } else if (required_glsl_es_version) {
263 requirement_string = ralloc_asprintf(this, " (%s required)",
264 glsl_es_version_string);
265 }
266 _mesa_glsl_error(locp, this, "%s in %s%s",
267 problem, this->get_version_string(),
268 requirement_string);
269
270 return false;
271 }
272
273 /**
274 * Process a GLSL #version directive.
275 *
276 * \param version is the integer that follows the #version token.
277 *
278 * \param ident is a string identifier that follows the integer, if any is
279 * present. Otherwise NULL.
280 */
281 void
282 _mesa_glsl_parse_state::process_version_directive(YYLTYPE *locp, int version,
283 const char *ident)
284 {
285 bool es_token_present = false;
286 if (ident) {
287 if (strcmp(ident, "es") == 0) {
288 es_token_present = true;
289 } else if (version >= 150) {
290 if (strcmp(ident, "core") == 0) {
291 /* Accept the token. There's no need to record that this is
292 * a core profile shader since that's the only profile we support.
293 */
294 } else if (strcmp(ident, "compatibility") == 0) {
295 _mesa_glsl_error(locp, this,
296 "the compatibility profile is not supported");
297 } else {
298 _mesa_glsl_error(locp, this,
299 "\"%s\" is not a valid shading language profile; "
300 "if present, it must be \"core\"", ident);
301 }
302 } else {
303 _mesa_glsl_error(locp, this,
304 "illegal text following version number");
305 }
306 }
307
308 this->es_shader = es_token_present;
309 if (version == 100) {
310 if (es_token_present) {
311 _mesa_glsl_error(locp, this,
312 "GLSL 1.00 ES should be selected using "
313 "`#version 100'");
314 } else {
315 this->es_shader = true;
316 }
317 }
318
319 if (this->es_shader) {
320 this->ARB_texture_rectangle_enable = false;
321 }
322
323 if (this->forced_language_version)
324 this->language_version = this->forced_language_version;
325 else
326 this->language_version = version;
327
328 bool supported = false;
329 for (unsigned i = 0; i < this->num_supported_versions; i++) {
330 if (this->supported_versions[i].ver == this->language_version
331 && this->supported_versions[i].es == this->es_shader) {
332 supported = true;
333 break;
334 }
335 }
336
337 if (!supported) {
338 _mesa_glsl_error(locp, this, "%s is not supported. "
339 "Supported versions are: %s",
340 this->get_version_string(),
341 this->supported_version_string);
342
343 /* On exit, the language_version must be set to a valid value.
344 * Later calls to _mesa_glsl_initialize_types will misbehave if
345 * the version is invalid.
346 */
347 switch (this->ctx->API) {
348 case API_OPENGL_COMPAT:
349 case API_OPENGL_CORE:
350 this->language_version = this->ctx->Const.GLSLVersion;
351 break;
352
353 case API_OPENGLES:
354 assert(!"Should not get here.");
355 /* FALLTHROUGH */
356
357 case API_OPENGLES2:
358 this->language_version = 100;
359 break;
360 }
361 }
362 }
363
364
365 /**
366 * Translate a gl_shader_stage to a short shader stage name for debug
367 * printouts and error messages.
368 */
369 const char *
370 _mesa_shader_stage_to_string(unsigned stage)
371 {
372 switch (stage) {
373 case MESA_SHADER_VERTEX: return "vertex";
374 case MESA_SHADER_FRAGMENT: return "fragment";
375 case MESA_SHADER_GEOMETRY: return "geometry";
376 case MESA_SHADER_COMPUTE: return "compute";
377 }
378
379 unreachable("Unknown shader stage.");
380 }
381
382 /**
383 * Translate a gl_shader_stage to a shader stage abbreviation (VS, GS, FS)
384 * for debug printouts and error messages.
385 */
386 const char *
387 _mesa_shader_stage_to_abbrev(unsigned stage)
388 {
389 switch (stage) {
390 case MESA_SHADER_VERTEX: return "VS";
391 case MESA_SHADER_FRAGMENT: return "FS";
392 case MESA_SHADER_GEOMETRY: return "GS";
393 case MESA_SHADER_COMPUTE: return "CS";
394 }
395
396 unreachable("Unknown shader stage.");
397 }
398
399 /* This helper function will append the given message to the shader's
400 info log and report it via GL_ARB_debug_output. Per that extension,
401 'type' is one of the enum values classifying the message, and
402 'id' is the implementation-defined ID of the given message. */
403 static void
404 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
405 GLenum type, const char *fmt, va_list ap)
406 {
407 bool error = (type == MESA_DEBUG_TYPE_ERROR);
408 GLuint msg_id = 0;
409
410 assert(state->info_log != NULL);
411
412 /* Get the offset that the new message will be written to. */
413 int msg_offset = strlen(state->info_log);
414
415 ralloc_asprintf_append(&state->info_log, "%u:%u(%u): %s: ",
416 locp->source,
417 locp->first_line,
418 locp->first_column,
419 error ? "error" : "warning");
420 ralloc_vasprintf_append(&state->info_log, fmt, ap);
421
422 const char *const msg = &state->info_log[msg_offset];
423 struct gl_context *ctx = state->ctx;
424
425 /* Report the error via GL_ARB_debug_output. */
426 _mesa_shader_debug(ctx, type, &msg_id, msg, strlen(msg));
427
428 ralloc_strcat(&state->info_log, "\n");
429 }
430
431 void
432 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
433 const char *fmt, ...)
434 {
435 va_list ap;
436
437 state->error = true;
438
439 va_start(ap, fmt);
440 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_ERROR, fmt, ap);
441 va_end(ap);
442 }
443
444
445 void
446 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
447 const char *fmt, ...)
448 {
449 va_list ap;
450
451 va_start(ap, fmt);
452 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_OTHER, fmt, ap);
453 va_end(ap);
454 }
455
456
457 /**
458 * Enum representing the possible behaviors that can be specified in
459 * an #extension directive.
460 */
461 enum ext_behavior {
462 extension_disable,
463 extension_enable,
464 extension_require,
465 extension_warn
466 };
467
468 /**
469 * Element type for _mesa_glsl_supported_extensions
470 */
471 struct _mesa_glsl_extension {
472 /**
473 * Name of the extension when referred to in a GLSL extension
474 * statement
475 */
476 const char *name;
477
478 /** True if this extension is available to desktop GL shaders */
479 bool avail_in_GL;
480
481 /** True if this extension is available to GLES shaders */
482 bool avail_in_ES;
483
484 /**
485 * Flag in the gl_extensions struct indicating whether this
486 * extension is supported by the driver, or
487 * &gl_extensions::dummy_true if supported by all drivers.
488 *
489 * Note: the type (GLboolean gl_extensions::*) is a "pointer to
490 * member" type, the type-safe alternative to the "offsetof" macro.
491 * In a nutshell:
492 *
493 * - foo bar::* p declares p to be an "offset" to a field of type
494 * foo that exists within struct bar
495 * - &bar::baz computes the "offset" of field baz within struct bar
496 * - x.*p accesses the field of x that exists at "offset" p
497 * - x->*p is equivalent to (*x).*p
498 */
499 const GLboolean gl_extensions::* supported_flag;
500
501 /**
502 * Flag in the _mesa_glsl_parse_state struct that should be set
503 * when this extension is enabled.
504 *
505 * See note in _mesa_glsl_extension::supported_flag about "pointer
506 * to member" types.
507 */
508 bool _mesa_glsl_parse_state::* enable_flag;
509
510 /**
511 * Flag in the _mesa_glsl_parse_state struct that should be set
512 * when the shader requests "warn" behavior for this extension.
513 *
514 * See note in _mesa_glsl_extension::supported_flag about "pointer
515 * to member" types.
516 */
517 bool _mesa_glsl_parse_state::* warn_flag;
518
519
520 bool compatible_with_state(const _mesa_glsl_parse_state *state) const;
521 void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
522 };
523
524 #define EXT(NAME, GL, ES, SUPPORTED_FLAG) \
525 { "GL_" #NAME, GL, ES, &gl_extensions::SUPPORTED_FLAG, \
526 &_mesa_glsl_parse_state::NAME##_enable, \
527 &_mesa_glsl_parse_state::NAME##_warn }
528
529 /**
530 * Table of extensions that can be enabled/disabled within a shader,
531 * and the conditions under which they are supported.
532 */
533 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
534 /* API availability */
535 /* name GL ES supported flag */
536
537 /* ARB extensions go here, sorted alphabetically.
538 */
539 EXT(ARB_arrays_of_arrays, true, false, ARB_arrays_of_arrays),
540 EXT(ARB_compute_shader, true, false, ARB_compute_shader),
541 EXT(ARB_conservative_depth, true, false, ARB_conservative_depth),
542 EXT(ARB_derivative_control, true, false, ARB_derivative_control),
543 EXT(ARB_draw_buffers, true, false, dummy_true),
544 EXT(ARB_draw_instanced, true, false, ARB_draw_instanced),
545 EXT(ARB_explicit_attrib_location, true, false, ARB_explicit_attrib_location),
546 EXT(ARB_explicit_uniform_location, true, false, ARB_explicit_uniform_location),
547 EXT(ARB_fragment_coord_conventions, true, false, ARB_fragment_coord_conventions),
548 EXT(ARB_fragment_layer_viewport, true, false, ARB_fragment_layer_viewport),
549 EXT(ARB_gpu_shader5, true, false, ARB_gpu_shader5),
550 EXT(ARB_gpu_shader_fp64, true, false, ARB_gpu_shader_fp64),
551 EXT(ARB_sample_shading, true, false, ARB_sample_shading),
552 EXT(ARB_separate_shader_objects, true, false, dummy_true),
553 EXT(ARB_shader_atomic_counters, true, false, ARB_shader_atomic_counters),
554 EXT(ARB_shader_bit_encoding, true, false, ARB_shader_bit_encoding),
555 EXT(ARB_shader_image_load_store, true, false, ARB_shader_image_load_store),
556 EXT(ARB_shader_precision, true, false, ARB_shader_precision),
557 EXT(ARB_shader_stencil_export, true, false, ARB_shader_stencil_export),
558 EXT(ARB_shader_texture_lod, true, false, ARB_shader_texture_lod),
559 EXT(ARB_shading_language_420pack, true, false, ARB_shading_language_420pack),
560 EXT(ARB_shading_language_packing, true, false, ARB_shading_language_packing),
561 EXT(ARB_texture_cube_map_array, true, false, ARB_texture_cube_map_array),
562 EXT(ARB_texture_gather, true, false, ARB_texture_gather),
563 EXT(ARB_texture_multisample, true, false, ARB_texture_multisample),
564 EXT(ARB_texture_query_levels, true, false, ARB_texture_query_levels),
565 EXT(ARB_texture_query_lod, true, false, ARB_texture_query_lod),
566 EXT(ARB_texture_rectangle, true, false, dummy_true),
567 EXT(ARB_uniform_buffer_object, true, false, ARB_uniform_buffer_object),
568 EXT(ARB_viewport_array, true, false, ARB_viewport_array),
569
570 /* KHR extensions go here, sorted alphabetically.
571 */
572
573 /* OES extensions go here, sorted alphabetically.
574 */
575 EXT(OES_EGL_image_external, false, true, OES_EGL_image_external),
576 EXT(OES_standard_derivatives, false, true, OES_standard_derivatives),
577 EXT(OES_texture_3D, false, true, EXT_texture3D),
578
579 /* All other extensions go here, sorted alphabetically.
580 */
581 EXT(AMD_conservative_depth, true, false, ARB_conservative_depth),
582 EXT(AMD_shader_stencil_export, true, false, ARB_shader_stencil_export),
583 EXT(AMD_shader_trinary_minmax, true, false, dummy_true),
584 EXT(AMD_vertex_shader_layer, true, false, AMD_vertex_shader_layer),
585 EXT(AMD_vertex_shader_viewport_index, true, false, AMD_vertex_shader_viewport_index),
586 EXT(EXT_draw_buffers, false, true, dummy_true),
587 EXT(EXT_separate_shader_objects, false, true, dummy_true),
588 EXT(EXT_shader_integer_mix, true, true, EXT_shader_integer_mix),
589 EXT(EXT_texture_array, true, false, EXT_texture_array),
590 };
591
592 #undef EXT
593
594
595 /**
596 * Determine whether a given extension is compatible with the target,
597 * API, and extension information in the current parser state.
598 */
599 bool _mesa_glsl_extension::compatible_with_state(const _mesa_glsl_parse_state *
600 state) const
601 {
602 /* Check that this extension matches whether we are compiling
603 * for desktop GL or GLES.
604 */
605 if (state->es_shader) {
606 if (!this->avail_in_ES) return false;
607 } else {
608 if (!this->avail_in_GL) return false;
609 }
610
611 /* Check that this extension is supported by the OpenGL
612 * implementation.
613 *
614 * Note: the ->* operator indexes into state->extensions by the
615 * offset this->supported_flag. See
616 * _mesa_glsl_extension::supported_flag for more info.
617 */
618 return state->extensions->*(this->supported_flag);
619 }
620
621 /**
622 * Set the appropriate flags in the parser state to establish the
623 * given behavior for this extension.
624 */
625 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
626 ext_behavior behavior) const
627 {
628 /* Note: the ->* operator indexes into state by the
629 * offsets this->enable_flag and this->warn_flag. See
630 * _mesa_glsl_extension::supported_flag for more info.
631 */
632 state->*(this->enable_flag) = (behavior != extension_disable);
633 state->*(this->warn_flag) = (behavior == extension_warn);
634 }
635
636 /**
637 * Find an extension by name in _mesa_glsl_supported_extensions. If
638 * the name is not found, return NULL.
639 */
640 static const _mesa_glsl_extension *find_extension(const char *name)
641 {
642 for (unsigned i = 0; i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
643 if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
644 return &_mesa_glsl_supported_extensions[i];
645 }
646 }
647 return NULL;
648 }
649
650
651 bool
652 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
653 const char *behavior_string, YYLTYPE *behavior_locp,
654 _mesa_glsl_parse_state *state)
655 {
656 ext_behavior behavior;
657 if (strcmp(behavior_string, "warn") == 0) {
658 behavior = extension_warn;
659 } else if (strcmp(behavior_string, "require") == 0) {
660 behavior = extension_require;
661 } else if (strcmp(behavior_string, "enable") == 0) {
662 behavior = extension_enable;
663 } else if (strcmp(behavior_string, "disable") == 0) {
664 behavior = extension_disable;
665 } else {
666 _mesa_glsl_error(behavior_locp, state,
667 "unknown extension behavior `%s'",
668 behavior_string);
669 return false;
670 }
671
672 if (strcmp(name, "all") == 0) {
673 if ((behavior == extension_enable) || (behavior == extension_require)) {
674 _mesa_glsl_error(name_locp, state, "cannot %s all extensions",
675 (behavior == extension_enable)
676 ? "enable" : "require");
677 return false;
678 } else {
679 for (unsigned i = 0;
680 i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
681 const _mesa_glsl_extension *extension
682 = &_mesa_glsl_supported_extensions[i];
683 if (extension->compatible_with_state(state)) {
684 _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
685 }
686 }
687 }
688 } else {
689 const _mesa_glsl_extension *extension = find_extension(name);
690 if (extension && extension->compatible_with_state(state)) {
691 extension->set_flags(state, behavior);
692 } else {
693 static const char fmt[] = "extension `%s' unsupported in %s shader";
694
695 if (behavior == extension_require) {
696 _mesa_glsl_error(name_locp, state, fmt,
697 name, _mesa_shader_stage_to_string(state->stage));
698 return false;
699 } else {
700 _mesa_glsl_warning(name_locp, state, fmt,
701 name, _mesa_shader_stage_to_string(state->stage));
702 }
703 }
704 }
705
706 return true;
707 }
708
709
710 /**
711 * Recurses through <type> and <expr> if <expr> is an aggregate initializer
712 * and sets <expr>'s <constructor_type> field to <type>. Gives later functions
713 * (process_array_constructor, et al) sufficient information to do type
714 * checking.
715 *
716 * Operates on assignments involving an aggregate initializer. E.g.,
717 *
718 * vec4 pos = {1.0, -1.0, 0.0, 1.0};
719 *
720 * or more ridiculously,
721 *
722 * struct S {
723 * vec4 v[2];
724 * };
725 *
726 * struct {
727 * S a[2], b;
728 * int c;
729 * } aggregate = {
730 * {
731 * {
732 * {
733 * {1.0, 2.0, 3.0, 4.0}, // a[0].v[0]
734 * {5.0, 6.0, 7.0, 8.0} // a[0].v[1]
735 * } // a[0].v
736 * }, // a[0]
737 * {
738 * {
739 * {1.0, 2.0, 3.0, 4.0}, // a[1].v[0]
740 * {5.0, 6.0, 7.0, 8.0} // a[1].v[1]
741 * } // a[1].v
742 * } // a[1]
743 * }, // a
744 * {
745 * {
746 * {1.0, 2.0, 3.0, 4.0}, // b.v[0]
747 * {5.0, 6.0, 7.0, 8.0} // b.v[1]
748 * } // b.v
749 * }, // b
750 * 4 // c
751 * };
752 *
753 * This pass is necessary because the right-hand side of <type> e = { ... }
754 * doesn't contain sufficient information to determine if the types match.
755 */
756 void
757 _mesa_ast_set_aggregate_type(const glsl_type *type,
758 ast_expression *expr)
759 {
760 ast_aggregate_initializer *ai = (ast_aggregate_initializer *)expr;
761 ai->constructor_type = type;
762
763 /* If the aggregate is an array, recursively set its elements' types. */
764 if (type->is_array()) {
765 /* Each array element has the type type->element_type().
766 *
767 * E.g., if <type> if struct S[2] we want to set each element's type to
768 * struct S.
769 */
770 for (exec_node *expr_node = ai->expressions.head;
771 !expr_node->is_tail_sentinel();
772 expr_node = expr_node->next) {
773 ast_expression *expr = exec_node_data(ast_expression, expr_node,
774 link);
775
776 if (expr->oper == ast_aggregate)
777 _mesa_ast_set_aggregate_type(type->element_type(), expr);
778 }
779
780 /* If the aggregate is a struct, recursively set its fields' types. */
781 } else if (type->is_record()) {
782 exec_node *expr_node = ai->expressions.head;
783
784 /* Iterate through the struct's fields. */
785 for (unsigned i = 0; !expr_node->is_tail_sentinel() && i < type->length;
786 i++, expr_node = expr_node->next) {
787 ast_expression *expr = exec_node_data(ast_expression, expr_node,
788 link);
789
790 if (expr->oper == ast_aggregate) {
791 _mesa_ast_set_aggregate_type(type->fields.structure[i].type, expr);
792 }
793 }
794 /* If the aggregate is a matrix, set its columns' types. */
795 } else if (type->is_matrix()) {
796 for (exec_node *expr_node = ai->expressions.head;
797 !expr_node->is_tail_sentinel();
798 expr_node = expr_node->next) {
799 ast_expression *expr = exec_node_data(ast_expression, expr_node,
800 link);
801
802 if (expr->oper == ast_aggregate)
803 _mesa_ast_set_aggregate_type(type->column_type(), expr);
804 }
805 }
806 }
807
808
809 void
810 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
811 {
812 if (q->flags.q.constant)
813 printf("const ");
814
815 if (q->flags.q.invariant)
816 printf("invariant ");
817
818 if (q->flags.q.attribute)
819 printf("attribute ");
820
821 if (q->flags.q.varying)
822 printf("varying ");
823
824 if (q->flags.q.in && q->flags.q.out)
825 printf("inout ");
826 else {
827 if (q->flags.q.in)
828 printf("in ");
829
830 if (q->flags.q.out)
831 printf("out ");
832 }
833
834 if (q->flags.q.centroid)
835 printf("centroid ");
836 if (q->flags.q.sample)
837 printf("sample ");
838 if (q->flags.q.uniform)
839 printf("uniform ");
840 if (q->flags.q.smooth)
841 printf("smooth ");
842 if (q->flags.q.flat)
843 printf("flat ");
844 if (q->flags.q.noperspective)
845 printf("noperspective ");
846 }
847
848
849 void
850 ast_node::print(void) const
851 {
852 printf("unhandled node ");
853 }
854
855
856 ast_node::ast_node(void)
857 {
858 this->location.source = 0;
859 this->location.first_line = 0;
860 this->location.first_column = 0;
861 this->location.last_line = 0;
862 this->location.last_column = 0;
863 }
864
865
866 static void
867 ast_opt_array_dimensions_print(const ast_array_specifier *array_specifier)
868 {
869 if (array_specifier)
870 array_specifier->print();
871 }
872
873
874 void
875 ast_compound_statement::print(void) const
876 {
877 printf("{\n");
878
879 foreach_list_typed(ast_node, ast, link, &this->statements) {
880 ast->print();
881 }
882
883 printf("}\n");
884 }
885
886
887 ast_compound_statement::ast_compound_statement(int new_scope,
888 ast_node *statements)
889 {
890 this->new_scope = new_scope;
891
892 if (statements != NULL) {
893 this->statements.push_degenerate_list_at_head(&statements->link);
894 }
895 }
896
897
898 void
899 ast_expression::print(void) const
900 {
901 switch (oper) {
902 case ast_assign:
903 case ast_mul_assign:
904 case ast_div_assign:
905 case ast_mod_assign:
906 case ast_add_assign:
907 case ast_sub_assign:
908 case ast_ls_assign:
909 case ast_rs_assign:
910 case ast_and_assign:
911 case ast_xor_assign:
912 case ast_or_assign:
913 subexpressions[0]->print();
914 printf("%s ", operator_string(oper));
915 subexpressions[1]->print();
916 break;
917
918 case ast_field_selection:
919 subexpressions[0]->print();
920 printf(". %s ", primary_expression.identifier);
921 break;
922
923 case ast_plus:
924 case ast_neg:
925 case ast_bit_not:
926 case ast_logic_not:
927 case ast_pre_inc:
928 case ast_pre_dec:
929 printf("%s ", operator_string(oper));
930 subexpressions[0]->print();
931 break;
932
933 case ast_post_inc:
934 case ast_post_dec:
935 subexpressions[0]->print();
936 printf("%s ", operator_string(oper));
937 break;
938
939 case ast_conditional:
940 subexpressions[0]->print();
941 printf("? ");
942 subexpressions[1]->print();
943 printf(": ");
944 subexpressions[2]->print();
945 break;
946
947 case ast_array_index:
948 subexpressions[0]->print();
949 printf("[ ");
950 subexpressions[1]->print();
951 printf("] ");
952 break;
953
954 case ast_function_call: {
955 subexpressions[0]->print();
956 printf("( ");
957
958 foreach_list_typed (ast_node, ast, link, &this->expressions) {
959 if (&ast->link != this->expressions.get_head())
960 printf(", ");
961
962 ast->print();
963 }
964
965 printf(") ");
966 break;
967 }
968
969 case ast_identifier:
970 printf("%s ", primary_expression.identifier);
971 break;
972
973 case ast_int_constant:
974 printf("%d ", primary_expression.int_constant);
975 break;
976
977 case ast_uint_constant:
978 printf("%u ", primary_expression.uint_constant);
979 break;
980
981 case ast_float_constant:
982 printf("%f ", primary_expression.float_constant);
983 break;
984
985 case ast_double_constant:
986 printf("%f ", primary_expression.double_constant);
987 break;
988
989 case ast_bool_constant:
990 printf("%s ",
991 primary_expression.bool_constant
992 ? "true" : "false");
993 break;
994
995 case ast_sequence: {
996 printf("( ");
997 foreach_list_typed (ast_node, ast, link, & this->expressions) {
998 if (&ast->link != this->expressions.get_head())
999 printf(", ");
1000
1001 ast->print();
1002 }
1003 printf(") ");
1004 break;
1005 }
1006
1007 case ast_aggregate: {
1008 printf("{ ");
1009 foreach_list_typed (ast_node, ast, link, & this->expressions) {
1010 if (&ast->link != this->expressions.get_head())
1011 printf(", ");
1012
1013 ast->print();
1014 }
1015 printf("} ");
1016 break;
1017 }
1018
1019 default:
1020 assert(0);
1021 break;
1022 }
1023 }
1024
1025 ast_expression::ast_expression(int oper,
1026 ast_expression *ex0,
1027 ast_expression *ex1,
1028 ast_expression *ex2) :
1029 primary_expression()
1030 {
1031 this->oper = ast_operators(oper);
1032 this->subexpressions[0] = ex0;
1033 this->subexpressions[1] = ex1;
1034 this->subexpressions[2] = ex2;
1035 this->non_lvalue_description = NULL;
1036 }
1037
1038
1039 void
1040 ast_expression_statement::print(void) const
1041 {
1042 if (expression)
1043 expression->print();
1044
1045 printf("; ");
1046 }
1047
1048
1049 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
1050 expression(ex)
1051 {
1052 /* empty */
1053 }
1054
1055
1056 void
1057 ast_function::print(void) const
1058 {
1059 return_type->print();
1060 printf(" %s (", identifier);
1061
1062 foreach_list_typed(ast_node, ast, link, & this->parameters) {
1063 ast->print();
1064 }
1065
1066 printf(")");
1067 }
1068
1069
1070 ast_function::ast_function(void)
1071 : return_type(NULL), identifier(NULL), is_definition(false),
1072 signature(NULL)
1073 {
1074 /* empty */
1075 }
1076
1077
1078 void
1079 ast_fully_specified_type::print(void) const
1080 {
1081 _mesa_ast_type_qualifier_print(& qualifier);
1082 specifier->print();
1083 }
1084
1085
1086 void
1087 ast_parameter_declarator::print(void) const
1088 {
1089 type->print();
1090 if (identifier)
1091 printf("%s ", identifier);
1092 ast_opt_array_dimensions_print(array_specifier);
1093 }
1094
1095
1096 void
1097 ast_function_definition::print(void) const
1098 {
1099 prototype->print();
1100 body->print();
1101 }
1102
1103
1104 void
1105 ast_declaration::print(void) const
1106 {
1107 printf("%s ", identifier);
1108 ast_opt_array_dimensions_print(array_specifier);
1109
1110 if (initializer) {
1111 printf("= ");
1112 initializer->print();
1113 }
1114 }
1115
1116
1117 ast_declaration::ast_declaration(const char *identifier,
1118 ast_array_specifier *array_specifier,
1119 ast_expression *initializer)
1120 {
1121 this->identifier = identifier;
1122 this->array_specifier = array_specifier;
1123 this->initializer = initializer;
1124 }
1125
1126
1127 void
1128 ast_declarator_list::print(void) const
1129 {
1130 assert(type || invariant);
1131
1132 if (type)
1133 type->print();
1134 else if (invariant)
1135 printf("invariant ");
1136 else
1137 printf("precise ");
1138
1139 foreach_list_typed (ast_node, ast, link, & this->declarations) {
1140 if (&ast->link != this->declarations.get_head())
1141 printf(", ");
1142
1143 ast->print();
1144 }
1145
1146 printf("; ");
1147 }
1148
1149
1150 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
1151 {
1152 this->type = type;
1153 this->invariant = false;
1154 this->precise = false;
1155 }
1156
1157 void
1158 ast_jump_statement::print(void) const
1159 {
1160 switch (mode) {
1161 case ast_continue:
1162 printf("continue; ");
1163 break;
1164 case ast_break:
1165 printf("break; ");
1166 break;
1167 case ast_return:
1168 printf("return ");
1169 if (opt_return_value)
1170 opt_return_value->print();
1171
1172 printf("; ");
1173 break;
1174 case ast_discard:
1175 printf("discard; ");
1176 break;
1177 }
1178 }
1179
1180
1181 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
1182 : opt_return_value(NULL)
1183 {
1184 this->mode = ast_jump_modes(mode);
1185
1186 if (mode == ast_return)
1187 opt_return_value = return_value;
1188 }
1189
1190
1191 void
1192 ast_selection_statement::print(void) const
1193 {
1194 printf("if ( ");
1195 condition->print();
1196 printf(") ");
1197
1198 then_statement->print();
1199
1200 if (else_statement) {
1201 printf("else ");
1202 else_statement->print();
1203 }
1204
1205 }
1206
1207
1208 ast_selection_statement::ast_selection_statement(ast_expression *condition,
1209 ast_node *then_statement,
1210 ast_node *else_statement)
1211 {
1212 this->condition = condition;
1213 this->then_statement = then_statement;
1214 this->else_statement = else_statement;
1215 }
1216
1217
1218 void
1219 ast_switch_statement::print(void) const
1220 {
1221 printf("switch ( ");
1222 test_expression->print();
1223 printf(") ");
1224
1225 body->print();
1226 }
1227
1228
1229 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
1230 ast_node *body)
1231 {
1232 this->test_expression = test_expression;
1233 this->body = body;
1234 }
1235
1236
1237 void
1238 ast_switch_body::print(void) const
1239 {
1240 printf("{\n");
1241 if (stmts != NULL) {
1242 stmts->print();
1243 }
1244 printf("}\n");
1245 }
1246
1247
1248 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
1249 {
1250 this->stmts = stmts;
1251 }
1252
1253
1254 void ast_case_label::print(void) const
1255 {
1256 if (test_value != NULL) {
1257 printf("case ");
1258 test_value->print();
1259 printf(": ");
1260 } else {
1261 printf("default: ");
1262 }
1263 }
1264
1265
1266 ast_case_label::ast_case_label(ast_expression *test_value)
1267 {
1268 this->test_value = test_value;
1269 }
1270
1271
1272 void ast_case_label_list::print(void) const
1273 {
1274 foreach_list_typed(ast_node, ast, link, & this->labels) {
1275 ast->print();
1276 }
1277 printf("\n");
1278 }
1279
1280
1281 ast_case_label_list::ast_case_label_list(void)
1282 {
1283 }
1284
1285
1286 void ast_case_statement::print(void) const
1287 {
1288 labels->print();
1289 foreach_list_typed(ast_node, ast, link, & this->stmts) {
1290 ast->print();
1291 printf("\n");
1292 }
1293 }
1294
1295
1296 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
1297 {
1298 this->labels = labels;
1299 }
1300
1301
1302 void ast_case_statement_list::print(void) const
1303 {
1304 foreach_list_typed(ast_node, ast, link, & this->cases) {
1305 ast->print();
1306 }
1307 }
1308
1309
1310 ast_case_statement_list::ast_case_statement_list(void)
1311 {
1312 }
1313
1314
1315 void
1316 ast_iteration_statement::print(void) const
1317 {
1318 switch (mode) {
1319 case ast_for:
1320 printf("for( ");
1321 if (init_statement)
1322 init_statement->print();
1323 printf("; ");
1324
1325 if (condition)
1326 condition->print();
1327 printf("; ");
1328
1329 if (rest_expression)
1330 rest_expression->print();
1331 printf(") ");
1332
1333 body->print();
1334 break;
1335
1336 case ast_while:
1337 printf("while ( ");
1338 if (condition)
1339 condition->print();
1340 printf(") ");
1341 body->print();
1342 break;
1343
1344 case ast_do_while:
1345 printf("do ");
1346 body->print();
1347 printf("while ( ");
1348 if (condition)
1349 condition->print();
1350 printf("); ");
1351 break;
1352 }
1353 }
1354
1355
1356 ast_iteration_statement::ast_iteration_statement(int mode,
1357 ast_node *init,
1358 ast_node *condition,
1359 ast_expression *rest_expression,
1360 ast_node *body)
1361 {
1362 this->mode = ast_iteration_modes(mode);
1363 this->init_statement = init;
1364 this->condition = condition;
1365 this->rest_expression = rest_expression;
1366 this->body = body;
1367 }
1368
1369
1370 void
1371 ast_struct_specifier::print(void) const
1372 {
1373 printf("struct %s { ", name);
1374 foreach_list_typed(ast_node, ast, link, &this->declarations) {
1375 ast->print();
1376 }
1377 printf("} ");
1378 }
1379
1380
1381 ast_struct_specifier::ast_struct_specifier(const char *identifier,
1382 ast_declarator_list *declarator_list)
1383 {
1384 if (identifier == NULL) {
1385 static mtx_t mutex = _MTX_INITIALIZER_NP;
1386 static unsigned anon_count = 1;
1387 unsigned count;
1388
1389 mtx_lock(&mutex);
1390 count = anon_count++;
1391 mtx_unlock(&mutex);
1392
1393 identifier = ralloc_asprintf(this, "#anon_struct_%04x", count);
1394 }
1395 name = identifier;
1396 this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1397 is_declaration = true;
1398 }
1399
1400 static void
1401 set_shader_inout_layout(struct gl_shader *shader,
1402 struct _mesa_glsl_parse_state *state)
1403 {
1404 if (shader->Stage != MESA_SHADER_GEOMETRY) {
1405 /* Should have been prevented by the parser. */
1406 assert(!state->in_qualifier->flags.i);
1407 assert(!state->out_qualifier->flags.i);
1408 }
1409
1410 if (shader->Stage != MESA_SHADER_COMPUTE) {
1411 /* Should have been prevented by the parser. */
1412 assert(!state->cs_input_local_size_specified);
1413 }
1414
1415 if (shader->Stage != MESA_SHADER_FRAGMENT) {
1416 /* Should have been prevented by the parser. */
1417 assert(!state->fs_uses_gl_fragcoord);
1418 assert(!state->fs_redeclares_gl_fragcoord);
1419 assert(!state->fs_pixel_center_integer);
1420 assert(!state->fs_origin_upper_left);
1421 }
1422
1423 switch (shader->Stage) {
1424 case MESA_SHADER_GEOMETRY:
1425 shader->Geom.VerticesOut = 0;
1426 if (state->out_qualifier->flags.q.max_vertices)
1427 shader->Geom.VerticesOut = state->out_qualifier->max_vertices;
1428
1429 if (state->gs_input_prim_type_specified) {
1430 shader->Geom.InputType = state->in_qualifier->prim_type;
1431 } else {
1432 shader->Geom.InputType = PRIM_UNKNOWN;
1433 }
1434
1435 if (state->out_qualifier->flags.q.prim_type) {
1436 shader->Geom.OutputType = state->out_qualifier->prim_type;
1437 } else {
1438 shader->Geom.OutputType = PRIM_UNKNOWN;
1439 }
1440
1441 shader->Geom.Invocations = 0;
1442 if (state->in_qualifier->flags.q.invocations)
1443 shader->Geom.Invocations = state->in_qualifier->invocations;
1444 break;
1445
1446 case MESA_SHADER_COMPUTE:
1447 if (state->cs_input_local_size_specified) {
1448 for (int i = 0; i < 3; i++)
1449 shader->Comp.LocalSize[i] = state->cs_input_local_size[i];
1450 } else {
1451 for (int i = 0; i < 3; i++)
1452 shader->Comp.LocalSize[i] = 0;
1453 }
1454 break;
1455
1456 case MESA_SHADER_FRAGMENT:
1457 shader->redeclares_gl_fragcoord = state->fs_redeclares_gl_fragcoord;
1458 shader->uses_gl_fragcoord = state->fs_uses_gl_fragcoord;
1459 shader->pixel_center_integer = state->fs_pixel_center_integer;
1460 shader->origin_upper_left = state->fs_origin_upper_left;
1461 shader->ARB_fragment_coord_conventions_enable =
1462 state->ARB_fragment_coord_conventions_enable;
1463 break;
1464
1465 default:
1466 /* Nothing to do. */
1467 break;
1468 }
1469 }
1470
1471 extern "C" {
1472
1473 void
1474 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader,
1475 bool dump_ast, bool dump_hir)
1476 {
1477 struct _mesa_glsl_parse_state *state =
1478 new(shader) _mesa_glsl_parse_state(ctx, shader->Stage, shader);
1479 const char *source = shader->Source;
1480
1481 if (ctx->Const.GenerateTemporaryNames)
1482 (void) p_atomic_cmpxchg(&ir_variable::temporaries_allocate_names,
1483 false, true);
1484
1485 state->error = glcpp_preprocess(state, &source, &state->info_log,
1486 &ctx->Extensions, ctx);
1487
1488 if (!state->error) {
1489 _mesa_glsl_lexer_ctor(state, source);
1490 _mesa_glsl_parse(state);
1491 _mesa_glsl_lexer_dtor(state);
1492 }
1493
1494 if (dump_ast) {
1495 foreach_list_typed(ast_node, ast, link, &state->translation_unit) {
1496 ast->print();
1497 }
1498 printf("\n\n");
1499 }
1500
1501 ralloc_free(shader->ir);
1502 shader->ir = new(shader) exec_list;
1503 if (!state->error && !state->translation_unit.is_empty())
1504 _mesa_ast_to_hir(shader->ir, state);
1505
1506 if (!state->error) {
1507 validate_ir_tree(shader->ir);
1508
1509 /* Print out the unoptimized IR. */
1510 if (dump_hir) {
1511 _mesa_print_ir(stdout, shader->ir, state);
1512 }
1513 }
1514
1515
1516 if (!state->error && !shader->ir->is_empty()) {
1517 struct gl_shader_compiler_options *options =
1518 &ctx->Const.ShaderCompilerOptions[shader->Stage];
1519
1520 /* Do some optimization at compile time to reduce shader IR size
1521 * and reduce later work if the same shader is linked multiple times
1522 */
1523 while (do_common_optimization(shader->ir, false, false, options,
1524 ctx->Const.NativeIntegers))
1525 ;
1526
1527 validate_ir_tree(shader->ir);
1528
1529 enum ir_variable_mode other;
1530 switch (shader->Stage) {
1531 case MESA_SHADER_VERTEX:
1532 other = ir_var_shader_in;
1533 break;
1534 case MESA_SHADER_FRAGMENT:
1535 other = ir_var_shader_out;
1536 break;
1537 default:
1538 /* Something invalid to ensure optimize_dead_builtin_uniforms
1539 * doesn't remove anything other than uniforms or constants.
1540 */
1541 other = ir_var_mode_count;
1542 break;
1543 }
1544
1545 optimize_dead_builtin_variables(shader->ir, other);
1546
1547 validate_ir_tree(shader->ir);
1548 }
1549
1550 if (shader->InfoLog)
1551 ralloc_free(shader->InfoLog);
1552
1553 shader->symbols = new(shader->ir) glsl_symbol_table;
1554 shader->CompileStatus = !state->error;
1555 shader->InfoLog = state->info_log;
1556 shader->Version = state->language_version;
1557 shader->IsES = state->es_shader;
1558 shader->uses_builtin_functions = state->uses_builtin_functions;
1559
1560 if (!state->error)
1561 set_shader_inout_layout(shader, state);
1562
1563 /* Retain any live IR, but trash the rest. */
1564 reparent_ir(shader->ir, shader->ir);
1565
1566 /* Destroy the symbol table. Create a new symbol table that contains only
1567 * the variables and functions that still exist in the IR. The symbol
1568 * table will be used later during linking.
1569 *
1570 * There must NOT be any freed objects still referenced by the symbol
1571 * table. That could cause the linker to dereference freed memory.
1572 *
1573 * We don't have to worry about types or interface-types here because those
1574 * are fly-weights that are looked up by glsl_type.
1575 */
1576 foreach_in_list (ir_instruction, ir, shader->ir) {
1577 switch (ir->ir_type) {
1578 case ir_type_function:
1579 shader->symbols->add_function((ir_function *) ir);
1580 break;
1581 case ir_type_variable: {
1582 ir_variable *const var = (ir_variable *) ir;
1583
1584 if (var->data.mode != ir_var_temporary)
1585 shader->symbols->add_variable(var);
1586 break;
1587 }
1588 default:
1589 break;
1590 }
1591 }
1592
1593 delete state->symbols;
1594 ralloc_free(state);
1595 }
1596
1597 } /* extern "C" */
1598 /**
1599 * Do the set of common optimizations passes
1600 *
1601 * \param ir List of instructions to be optimized
1602 * \param linked Is the shader linked? This enables
1603 * optimizations passes that remove code at
1604 * global scope and could cause linking to
1605 * fail.
1606 * \param uniform_locations_assigned Have locations already been assigned for
1607 * uniforms? This prevents the declarations
1608 * of unused uniforms from being removed.
1609 * The setting of this flag only matters if
1610 * \c linked is \c true.
1611 * \param max_unroll_iterations Maximum number of loop iterations to be
1612 * unrolled. Setting to 0 disables loop
1613 * unrolling.
1614 * \param options The driver's preferred shader options.
1615 */
1616 bool
1617 do_common_optimization(exec_list *ir, bool linked,
1618 bool uniform_locations_assigned,
1619 const struct gl_shader_compiler_options *options,
1620 bool native_integers)
1621 {
1622 GLboolean progress = GL_FALSE;
1623
1624 progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
1625
1626 if (linked) {
1627 progress = do_function_inlining(ir) || progress;
1628 progress = do_dead_functions(ir) || progress;
1629 progress = do_structure_splitting(ir) || progress;
1630 }
1631 progress = do_if_simplification(ir) || progress;
1632 progress = opt_flatten_nested_if_blocks(ir) || progress;
1633 progress = opt_conditional_discard(ir) || progress;
1634 progress = do_copy_propagation(ir) || progress;
1635 progress = do_copy_propagation_elements(ir) || progress;
1636
1637 if (options->OptimizeForAOS && !linked)
1638 progress = opt_flip_matrices(ir) || progress;
1639
1640 if (linked && options->OptimizeForAOS) {
1641 progress = do_vectorize(ir) || progress;
1642 }
1643
1644 if (linked)
1645 progress = do_dead_code(ir, uniform_locations_assigned) || progress;
1646 else
1647 progress = do_dead_code_unlinked(ir) || progress;
1648 progress = do_dead_code_local(ir) || progress;
1649 progress = do_tree_grafting(ir) || progress;
1650 progress = do_constant_propagation(ir) || progress;
1651 if (linked)
1652 progress = do_constant_variable(ir) || progress;
1653 else
1654 progress = do_constant_variable_unlinked(ir) || progress;
1655 progress = do_constant_folding(ir) || progress;
1656 progress = do_minmax_prune(ir) || progress;
1657 progress = do_cse(ir) || progress;
1658 progress = do_rebalance_tree(ir) || progress;
1659 progress = do_algebraic(ir, native_integers, options) || progress;
1660 progress = do_lower_jumps(ir) || progress;
1661 progress = do_vec_index_to_swizzle(ir) || progress;
1662 progress = lower_vector_insert(ir, false) || progress;
1663 progress = do_swizzle_swizzle(ir) || progress;
1664 progress = do_noop_swizzle(ir) || progress;
1665
1666 progress = optimize_split_arrays(ir, linked) || progress;
1667 progress = optimize_redundant_jumps(ir) || progress;
1668
1669 loop_state *ls = analyze_loop_variables(ir);
1670 if (ls->loop_found) {
1671 progress = set_loop_controls(ir, ls) || progress;
1672 progress = unroll_loops(ir, ls, options) || progress;
1673 }
1674 delete ls;
1675
1676 return progress;
1677 }
1678
1679 extern "C" {
1680
1681 /**
1682 * To be called at GL teardown time, this frees compiler datastructures.
1683 *
1684 * After calling this, any previously compiled shaders and shader
1685 * programs would be invalid. So this should happen at approximately
1686 * program exit.
1687 */
1688 void
1689 _mesa_destroy_shader_compiler(void)
1690 {
1691 _mesa_destroy_shader_compiler_caches();
1692
1693 _mesa_glsl_release_types();
1694 }
1695
1696 /**
1697 * Releases compiler caches to trade off performance for memory.
1698 *
1699 * Intended to be used with glReleaseShaderCompiler().
1700 */
1701 void
1702 _mesa_destroy_shader_compiler_caches(void)
1703 {
1704 _mesa_glsl_release_builtin_functions();
1705 }
1706
1707 }