mesa: Move the common _mesa_glsl_compile_shader() code to glsl/.
[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 extern "C" {
29 #include "main/core.h" /* for struct gl_context */
30 #include "main/context.h"
31 #include "main/shaderobj.h"
32 }
33
34 #include "ralloc.h"
35 #include "ast.h"
36 #include "glsl_parser_extras.h"
37 #include "glsl_parser.h"
38 #include "ir_optimization.h"
39 #include "loop_analysis.h"
40
41 /**
42 * Format a short human-readable description of the given GLSL version.
43 */
44 const char *
45 glsl_compute_version_string(void *mem_ctx, bool is_es, unsigned version)
46 {
47 return ralloc_asprintf(mem_ctx, "GLSL%s %d.%02d", is_es ? " ES" : "",
48 version / 100, version % 100);
49 }
50
51
52 static unsigned known_desktop_glsl_versions[] =
53 { 110, 120, 130, 140, 150, 330, 400, 410, 420, 430 };
54
55
56 _mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *_ctx,
57 GLenum target, void *mem_ctx)
58 : ctx(_ctx)
59 {
60 switch (target) {
61 case GL_VERTEX_SHADER: this->target = vertex_shader; break;
62 case GL_FRAGMENT_SHADER: this->target = fragment_shader; break;
63 case GL_GEOMETRY_SHADER: this->target = geometry_shader; break;
64 }
65
66 this->scanner = NULL;
67 this->translation_unit.make_empty();
68 this->symbols = new(mem_ctx) glsl_symbol_table;
69 this->info_log = ralloc_strdup(mem_ctx, "");
70 this->error = false;
71 this->loop_nesting_ast = NULL;
72 this->switch_state.switch_nesting_ast = NULL;
73
74 this->num_builtins_to_link = 0;
75
76 /* Set default language version and extensions */
77 this->language_version = 110;
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.VertexProgram.MaxAttribs;
95 this->Const.MaxVertexUniformComponents = ctx->Const.VertexProgram.MaxUniformComponents;
96 this->Const.MaxVaryingFloats = ctx->Const.MaxVarying * 4;
97 this->Const.MaxVertexTextureImageUnits = ctx->Const.VertexProgram.MaxTextureImageUnits;
98 this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
99 this->Const.MaxTextureImageUnits = ctx->Const.FragmentProgram.MaxTextureImageUnits;
100 this->Const.MaxFragmentUniformComponents = ctx->Const.FragmentProgram.MaxUniformComponents;
101 this->Const.MinProgramTexelOffset = ctx->Const.MinProgramTexelOffset;
102 this->Const.MaxProgramTexelOffset = ctx->Const.MaxProgramTexelOffset;
103
104 this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
105
106 /* Populate the list of supported GLSL versions */
107 /* FINISHME: Once the OpenGL 3.0 'forward compatible' context or
108 * the OpenGL 3.2 Core context is supported, this logic will need
109 * change. Older versions of GLSL are no longer supported
110 * outside the compatibility contexts of 3.x.
111 */
112 this->num_supported_versions = 0;
113 if (_mesa_is_desktop_gl(ctx)) {
114 for (unsigned i = 0; i < ARRAY_SIZE(known_desktop_glsl_versions); i++) {
115 if (known_desktop_glsl_versions[i] <= ctx->Const.GLSLVersion) {
116 this->supported_versions[this->num_supported_versions].ver
117 = known_desktop_glsl_versions[i];
118 this->supported_versions[this->num_supported_versions].es = false;
119 this->num_supported_versions++;
120 }
121 }
122 }
123 if (ctx->API == API_OPENGLES2 || ctx->Extensions.ARB_ES2_compatibility) {
124 this->supported_versions[this->num_supported_versions].ver = 100;
125 this->supported_versions[this->num_supported_versions].es = true;
126 this->num_supported_versions++;
127 }
128 if (_mesa_is_gles3(ctx) || ctx->Extensions.ARB_ES3_compatibility) {
129 this->supported_versions[this->num_supported_versions].ver = 300;
130 this->supported_versions[this->num_supported_versions].es = true;
131 this->num_supported_versions++;
132 }
133 assert(this->num_supported_versions
134 <= ARRAY_SIZE(this->supported_versions));
135
136 /* Create a string for use in error messages to tell the user which GLSL
137 * versions are supported.
138 */
139 char *supported = ralloc_strdup(this, "");
140 for (unsigned i = 0; i < this->num_supported_versions; i++) {
141 unsigned ver = this->supported_versions[i].ver;
142 const char *const prefix = (i == 0)
143 ? ""
144 : ((i == this->num_supported_versions - 1) ? ", and " : ", ");
145 const char *const suffix = (this->supported_versions[i].es) ? " ES" : "";
146
147 ralloc_asprintf_append(& supported, "%s%u.%02u%s",
148 prefix,
149 ver / 100, ver % 100,
150 suffix);
151 }
152
153 this->supported_version_string = supported;
154
155 if (ctx->Const.ForceGLSLExtensionsWarn)
156 _mesa_glsl_process_extension("all", NULL, "warn", NULL, this);
157
158 this->default_uniform_qualifier = new(this) ast_type_qualifier();
159 this->default_uniform_qualifier->flags.q.shared = 1;
160 this->default_uniform_qualifier->flags.q.column_major = 1;
161 }
162
163 /**
164 * Determine whether the current GLSL version is sufficiently high to support
165 * a certain feature, and generate an error message if it isn't.
166 *
167 * \param required_glsl_version and \c required_glsl_es_version are
168 * interpreted as they are in _mesa_glsl_parse_state::is_version().
169 *
170 * \param locp is the parser location where the error should be reported.
171 *
172 * \param fmt (and additional arguments) constitute a printf-style error
173 * message to report if the version check fails. Information about the
174 * current and required GLSL versions will be appended. So, for example, if
175 * the GLSL version being compiled is 1.20, and check_version(130, 300, locp,
176 * "foo unsupported") is called, the error message will be "foo unsupported in
177 * GLSL 1.20 (GLSL 1.30 or GLSL 3.00 ES required)".
178 */
179 bool
180 _mesa_glsl_parse_state::check_version(unsigned required_glsl_version,
181 unsigned required_glsl_es_version,
182 YYLTYPE *locp, const char *fmt, ...)
183 {
184 if (this->is_version(required_glsl_version, required_glsl_es_version))
185 return true;
186
187 va_list args;
188 va_start(args, fmt);
189 char *problem = ralloc_vasprintf(this, fmt, args);
190 va_end(args);
191 const char *glsl_version_string
192 = glsl_compute_version_string(this, false, required_glsl_version);
193 const char *glsl_es_version_string
194 = glsl_compute_version_string(this, true, required_glsl_es_version);
195 const char *requirement_string = "";
196 if (required_glsl_version && required_glsl_es_version) {
197 requirement_string = ralloc_asprintf(this, " (%s or %s required)",
198 glsl_version_string,
199 glsl_es_version_string);
200 } else if (required_glsl_version) {
201 requirement_string = ralloc_asprintf(this, " (%s required)",
202 glsl_version_string);
203 } else if (required_glsl_es_version) {
204 requirement_string = ralloc_asprintf(this, " (%s required)",
205 glsl_es_version_string);
206 }
207 _mesa_glsl_error(locp, this, "%s in %s%s.",
208 problem, this->get_version_string(),
209 requirement_string);
210
211 return false;
212 }
213
214 /**
215 * Process a GLSL #version directive.
216 *
217 * \param version is the integer that follows the #version token.
218 *
219 * \param ident is a string identifier that follows the integer, if any is
220 * present. Otherwise NULL.
221 */
222 void
223 _mesa_glsl_parse_state::process_version_directive(YYLTYPE *locp, int version,
224 const char *ident)
225 {
226 bool es_token_present = false;
227 if (ident) {
228 if (strcmp(ident, "es") == 0) {
229 es_token_present = true;
230 } else if (version >= 150) {
231 if (strcmp(ident, "core") == 0) {
232 /* Accept the token. There's no need to record that this is
233 * a core profile shader since that's the only profile we support.
234 */
235 } else if (strcmp(ident, "compatibility") == 0) {
236 _mesa_glsl_error(locp, this,
237 "The compatibility profile is not supported.\n");
238 } else {
239 _mesa_glsl_error(locp, this,
240 "\"%s\" is not a valid shading language profile; "
241 "if present, it must be \"core\".\n", ident);
242 }
243 } else {
244 _mesa_glsl_error(locp, this,
245 "Illegal text following version number\n");
246 }
247 }
248
249 this->es_shader = es_token_present;
250 if (version == 100) {
251 if (es_token_present) {
252 _mesa_glsl_error(locp, this,
253 "GLSL 1.00 ES should be selected using "
254 "`#version 100'\n");
255 } else {
256 this->es_shader = true;
257 }
258 }
259
260 this->language_version = version;
261
262 bool supported = false;
263 for (unsigned i = 0; i < this->num_supported_versions; i++) {
264 if (this->supported_versions[i].ver == (unsigned) version
265 && this->supported_versions[i].es == this->es_shader) {
266 supported = true;
267 break;
268 }
269 }
270
271 if (!supported) {
272 _mesa_glsl_error(locp, this, "%s is not supported. "
273 "Supported versions are: %s\n",
274 this->get_version_string(),
275 this->supported_version_string);
276
277 /* On exit, the language_version must be set to a valid value.
278 * Later calls to _mesa_glsl_initialize_types will misbehave if
279 * the version is invalid.
280 */
281 switch (this->ctx->API) {
282 case API_OPENGL_COMPAT:
283 case API_OPENGL_CORE:
284 this->language_version = this->ctx->Const.GLSLVersion;
285 break;
286
287 case API_OPENGLES:
288 assert(!"Should not get here.");
289 /* FALLTHROUGH */
290
291 case API_OPENGLES2:
292 this->language_version = 100;
293 break;
294 }
295 }
296
297 if (this->language_version >= 140) {
298 this->ARB_uniform_buffer_object_enable = true;
299 }
300
301 if (this->language_version == 300 && this->es_shader) {
302 this->ARB_explicit_attrib_location_enable = true;
303 }
304 }
305
306 extern "C" {
307
308 /**
309 * The most common use of _mesa_glsl_shader_target_name(), which is
310 * shared with C code in Mesa core to translate a GLenum to a short
311 * shader stage name in debug printouts.
312 *
313 * It recognizes the PROGRAM variants of the names so it can be used
314 * with a struct gl_program->Target, not just a struct
315 * gl_shader->Type.
316 */
317 const char *
318 _mesa_glsl_shader_target_name(GLenum type)
319 {
320 switch (type) {
321 case GL_VERTEX_SHADER:
322 case GL_VERTEX_PROGRAM_ARB:
323 return "vertex";
324 case GL_FRAGMENT_SHADER:
325 case GL_FRAGMENT_PROGRAM_ARB:
326 return "fragment";
327 case GL_GEOMETRY_SHADER:
328 return "geometry";
329 default:
330 assert(!"Should not get here.");
331 return "unknown";
332 }
333 }
334
335 } /* extern "C" */
336
337 /**
338 * Overloaded C++ variant usable within the compiler for translating
339 * our internal enum into short stage names.
340 */
341 const char *
342 _mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target)
343 {
344 switch (target) {
345 case vertex_shader: return "vertex";
346 case fragment_shader: return "fragment";
347 case geometry_shader: return "geometry";
348 }
349
350 assert(!"Should not get here.");
351 return "unknown";
352 }
353
354 /* This helper function will append the given message to the shader's
355 info log and report it via GL_ARB_debug_output. Per that extension,
356 'type' is one of the enum values classifying the message, and
357 'id' is the implementation-defined ID of the given message. */
358 static void
359 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
360 GLenum type, const char *fmt, va_list ap)
361 {
362 bool error = (type == MESA_DEBUG_TYPE_ERROR);
363 GLuint msg_id = 0;
364
365 assert(state->info_log != NULL);
366
367 /* Get the offset that the new message will be written to. */
368 int msg_offset = strlen(state->info_log);
369
370 ralloc_asprintf_append(&state->info_log, "%u:%u(%u): %s: ",
371 locp->source,
372 locp->first_line,
373 locp->first_column,
374 error ? "error" : "warning");
375 ralloc_vasprintf_append(&state->info_log, fmt, ap);
376
377 const char *const msg = &state->info_log[msg_offset];
378 struct gl_context *ctx = state->ctx;
379
380 /* Report the error via GL_ARB_debug_output. */
381 _mesa_shader_debug(ctx, type, &msg_id, msg, strlen(msg));
382
383 ralloc_strcat(&state->info_log, "\n");
384 }
385
386 void
387 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
388 const char *fmt, ...)
389 {
390 va_list ap;
391
392 state->error = true;
393
394 va_start(ap, fmt);
395 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_ERROR, fmt, ap);
396 va_end(ap);
397 }
398
399
400 void
401 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
402 const char *fmt, ...)
403 {
404 va_list ap;
405
406 va_start(ap, fmt);
407 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_OTHER, fmt, ap);
408 va_end(ap);
409 }
410
411
412 /**
413 * Enum representing the possible behaviors that can be specified in
414 * an #extension directive.
415 */
416 enum ext_behavior {
417 extension_disable,
418 extension_enable,
419 extension_require,
420 extension_warn
421 };
422
423 /**
424 * Element type for _mesa_glsl_supported_extensions
425 */
426 struct _mesa_glsl_extension {
427 /**
428 * Name of the extension when referred to in a GLSL extension
429 * statement
430 */
431 const char *name;
432
433 /** True if this extension is available to vertex shaders */
434 bool avail_in_VS;
435
436 /** True if this extension is available to geometry shaders */
437 bool avail_in_GS;
438
439 /** True if this extension is available to fragment shaders */
440 bool avail_in_FS;
441
442 /** True if this extension is available to desktop GL shaders */
443 bool avail_in_GL;
444
445 /** True if this extension is available to GLES shaders */
446 bool avail_in_ES;
447
448 /**
449 * Flag in the gl_extensions struct indicating whether this
450 * extension is supported by the driver, or
451 * &gl_extensions::dummy_true if supported by all drivers.
452 *
453 * Note: the type (GLboolean gl_extensions::*) is a "pointer to
454 * member" type, the type-safe alternative to the "offsetof" macro.
455 * In a nutshell:
456 *
457 * - foo bar::* p declares p to be an "offset" to a field of type
458 * foo that exists within struct bar
459 * - &bar::baz computes the "offset" of field baz within struct bar
460 * - x.*p accesses the field of x that exists at "offset" p
461 * - x->*p is equivalent to (*x).*p
462 */
463 const GLboolean gl_extensions::* supported_flag;
464
465 /**
466 * Flag in the _mesa_glsl_parse_state struct that should be set
467 * when this extension is enabled.
468 *
469 * See note in _mesa_glsl_extension::supported_flag about "pointer
470 * to member" types.
471 */
472 bool _mesa_glsl_parse_state::* enable_flag;
473
474 /**
475 * Flag in the _mesa_glsl_parse_state struct that should be set
476 * when the shader requests "warn" behavior for this extension.
477 *
478 * See note in _mesa_glsl_extension::supported_flag about "pointer
479 * to member" types.
480 */
481 bool _mesa_glsl_parse_state::* warn_flag;
482
483
484 bool compatible_with_state(const _mesa_glsl_parse_state *state) const;
485 void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
486 };
487
488 #define EXT(NAME, VS, GS, FS, GL, ES, SUPPORTED_FLAG) \
489 { "GL_" #NAME, VS, GS, FS, GL, ES, &gl_extensions::SUPPORTED_FLAG, \
490 &_mesa_glsl_parse_state::NAME##_enable, \
491 &_mesa_glsl_parse_state::NAME##_warn }
492
493 /**
494 * Table of extensions that can be enabled/disabled within a shader,
495 * and the conditions under which they are supported.
496 */
497 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
498 /* target availability API availability */
499 /* name VS GS FS GL ES supported flag */
500 EXT(ARB_conservative_depth, false, false, true, true, false, ARB_conservative_depth),
501 EXT(ARB_draw_buffers, false, false, true, true, false, dummy_true),
502 EXT(ARB_draw_instanced, true, false, false, true, false, ARB_draw_instanced),
503 EXT(ARB_explicit_attrib_location, true, false, true, true, false, ARB_explicit_attrib_location),
504 EXT(ARB_fragment_coord_conventions, true, false, true, true, false, ARB_fragment_coord_conventions),
505 EXT(ARB_texture_rectangle, true, false, true, true, false, dummy_true),
506 EXT(EXT_texture_array, true, false, true, true, false, EXT_texture_array),
507 EXT(ARB_shader_texture_lod, true, false, true, true, false, ARB_shader_texture_lod),
508 EXT(ARB_shader_stencil_export, false, false, true, true, false, ARB_shader_stencil_export),
509 EXT(AMD_conservative_depth, false, false, true, true, false, ARB_conservative_depth),
510 EXT(AMD_shader_stencil_export, false, false, true, true, false, ARB_shader_stencil_export),
511 EXT(OES_texture_3D, true, false, true, false, true, EXT_texture3D),
512 EXT(OES_EGL_image_external, true, false, true, false, true, OES_EGL_image_external),
513 EXT(ARB_shader_bit_encoding, true, true, true, true, false, ARB_shader_bit_encoding),
514 EXT(ARB_uniform_buffer_object, true, false, true, true, false, ARB_uniform_buffer_object),
515 EXT(OES_standard_derivatives, false, false, true, false, true, OES_standard_derivatives),
516 EXT(ARB_texture_cube_map_array, true, false, true, true, false, ARB_texture_cube_map_array),
517 EXT(ARB_shading_language_packing, true, false, true, true, false, ARB_shading_language_packing),
518 EXT(ARB_shading_language_420pack, true, true, true, true, false, ARB_shading_language_420pack),
519 EXT(ARB_texture_multisample, true, false, true, true, false, ARB_texture_multisample),
520 EXT(ARB_texture_query_lod, false, false, true, true, false, ARB_texture_query_lod),
521 EXT(ARB_gpu_shader5, true, true, true, true, false, ARB_gpu_shader5),
522 EXT(AMD_vertex_shader_layer, true, false, false, true, false, AMD_vertex_shader_layer),
523 };
524
525 #undef EXT
526
527
528 /**
529 * Determine whether a given extension is compatible with the target,
530 * API, and extension information in the current parser state.
531 */
532 bool _mesa_glsl_extension::compatible_with_state(const _mesa_glsl_parse_state *
533 state) const
534 {
535 /* Check that this extension matches the type of shader we are
536 * compiling to.
537 */
538 switch (state->target) {
539 case vertex_shader:
540 if (!this->avail_in_VS) {
541 return false;
542 }
543 break;
544 case geometry_shader:
545 if (!this->avail_in_GS) {
546 return false;
547 }
548 break;
549 case fragment_shader:
550 if (!this->avail_in_FS) {
551 return false;
552 }
553 break;
554 default:
555 assert (!"Unrecognized shader target");
556 return false;
557 }
558
559 /* Check that this extension matches whether we are compiling
560 * for desktop GL or GLES.
561 */
562 if (state->es_shader) {
563 if (!this->avail_in_ES) return false;
564 } else {
565 if (!this->avail_in_GL) return false;
566 }
567
568 /* Check that this extension is supported by the OpenGL
569 * implementation.
570 *
571 * Note: the ->* operator indexes into state->extensions by the
572 * offset this->supported_flag. See
573 * _mesa_glsl_extension::supported_flag for more info.
574 */
575 return state->extensions->*(this->supported_flag);
576 }
577
578 /**
579 * Set the appropriate flags in the parser state to establish the
580 * given behavior for this extension.
581 */
582 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
583 ext_behavior behavior) const
584 {
585 /* Note: the ->* operator indexes into state by the
586 * offsets this->enable_flag and this->warn_flag. See
587 * _mesa_glsl_extension::supported_flag for more info.
588 */
589 state->*(this->enable_flag) = (behavior != extension_disable);
590 state->*(this->warn_flag) = (behavior == extension_warn);
591 }
592
593 /**
594 * Find an extension by name in _mesa_glsl_supported_extensions. If
595 * the name is not found, return NULL.
596 */
597 static const _mesa_glsl_extension *find_extension(const char *name)
598 {
599 for (unsigned i = 0; i < Elements(_mesa_glsl_supported_extensions); ++i) {
600 if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
601 return &_mesa_glsl_supported_extensions[i];
602 }
603 }
604 return NULL;
605 }
606
607
608 bool
609 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
610 const char *behavior_string, YYLTYPE *behavior_locp,
611 _mesa_glsl_parse_state *state)
612 {
613 ext_behavior behavior;
614 if (strcmp(behavior_string, "warn") == 0) {
615 behavior = extension_warn;
616 } else if (strcmp(behavior_string, "require") == 0) {
617 behavior = extension_require;
618 } else if (strcmp(behavior_string, "enable") == 0) {
619 behavior = extension_enable;
620 } else if (strcmp(behavior_string, "disable") == 0) {
621 behavior = extension_disable;
622 } else {
623 _mesa_glsl_error(behavior_locp, state,
624 "Unknown extension behavior `%s'",
625 behavior_string);
626 return false;
627 }
628
629 if (strcmp(name, "all") == 0) {
630 if ((behavior == extension_enable) || (behavior == extension_require)) {
631 _mesa_glsl_error(name_locp, state, "Cannot %s all extensions",
632 (behavior == extension_enable)
633 ? "enable" : "require");
634 return false;
635 } else {
636 for (unsigned i = 0;
637 i < Elements(_mesa_glsl_supported_extensions); ++i) {
638 const _mesa_glsl_extension *extension
639 = &_mesa_glsl_supported_extensions[i];
640 if (extension->compatible_with_state(state)) {
641 _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
642 }
643 }
644 }
645 } else {
646 const _mesa_glsl_extension *extension = find_extension(name);
647 if (extension && extension->compatible_with_state(state)) {
648 extension->set_flags(state, behavior);
649 } else {
650 static const char *const fmt = "extension `%s' unsupported in %s shader";
651
652 if (behavior == extension_require) {
653 _mesa_glsl_error(name_locp, state, fmt,
654 name, _mesa_glsl_shader_target_name(state->target));
655 return false;
656 } else {
657 _mesa_glsl_warning(name_locp, state, fmt,
658 name, _mesa_glsl_shader_target_name(state->target));
659 }
660 }
661 }
662
663 return true;
664 }
665
666 void
667 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
668 {
669 if (q->flags.q.constant)
670 printf("const ");
671
672 if (q->flags.q.invariant)
673 printf("invariant ");
674
675 if (q->flags.q.attribute)
676 printf("attribute ");
677
678 if (q->flags.q.varying)
679 printf("varying ");
680
681 if (q->flags.q.in && q->flags.q.out)
682 printf("inout ");
683 else {
684 if (q->flags.q.in)
685 printf("in ");
686
687 if (q->flags.q.out)
688 printf("out ");
689 }
690
691 if (q->flags.q.centroid)
692 printf("centroid ");
693 if (q->flags.q.uniform)
694 printf("uniform ");
695 if (q->flags.q.smooth)
696 printf("smooth ");
697 if (q->flags.q.flat)
698 printf("flat ");
699 if (q->flags.q.noperspective)
700 printf("noperspective ");
701 }
702
703
704 void
705 ast_node::print(void) const
706 {
707 printf("unhandled node ");
708 }
709
710
711 ast_node::ast_node(void)
712 {
713 this->location.source = 0;
714 this->location.line = 0;
715 this->location.column = 0;
716 }
717
718
719 static void
720 ast_opt_array_size_print(bool is_array, const ast_expression *array_size)
721 {
722 if (is_array) {
723 printf("[ ");
724
725 if (array_size)
726 array_size->print();
727
728 printf("] ");
729 }
730 }
731
732
733 void
734 ast_compound_statement::print(void) const
735 {
736 printf("{\n");
737
738 foreach_list_const(n, &this->statements) {
739 ast_node *ast = exec_node_data(ast_node, n, link);
740 ast->print();
741 }
742
743 printf("}\n");
744 }
745
746
747 ast_compound_statement::ast_compound_statement(int new_scope,
748 ast_node *statements)
749 {
750 this->new_scope = new_scope;
751
752 if (statements != NULL) {
753 this->statements.push_degenerate_list_at_head(&statements->link);
754 }
755 }
756
757
758 void
759 ast_expression::print(void) const
760 {
761 switch (oper) {
762 case ast_assign:
763 case ast_mul_assign:
764 case ast_div_assign:
765 case ast_mod_assign:
766 case ast_add_assign:
767 case ast_sub_assign:
768 case ast_ls_assign:
769 case ast_rs_assign:
770 case ast_and_assign:
771 case ast_xor_assign:
772 case ast_or_assign:
773 subexpressions[0]->print();
774 printf("%s ", operator_string(oper));
775 subexpressions[1]->print();
776 break;
777
778 case ast_field_selection:
779 subexpressions[0]->print();
780 printf(". %s ", primary_expression.identifier);
781 break;
782
783 case ast_plus:
784 case ast_neg:
785 case ast_bit_not:
786 case ast_logic_not:
787 case ast_pre_inc:
788 case ast_pre_dec:
789 printf("%s ", operator_string(oper));
790 subexpressions[0]->print();
791 break;
792
793 case ast_post_inc:
794 case ast_post_dec:
795 subexpressions[0]->print();
796 printf("%s ", operator_string(oper));
797 break;
798
799 case ast_conditional:
800 subexpressions[0]->print();
801 printf("? ");
802 subexpressions[1]->print();
803 printf(": ");
804 subexpressions[2]->print();
805 break;
806
807 case ast_array_index:
808 subexpressions[0]->print();
809 printf("[ ");
810 subexpressions[1]->print();
811 printf("] ");
812 break;
813
814 case ast_function_call: {
815 subexpressions[0]->print();
816 printf("( ");
817
818 foreach_list_const (n, &this->expressions) {
819 if (n != this->expressions.get_head())
820 printf(", ");
821
822 ast_node *ast = exec_node_data(ast_node, n, link);
823 ast->print();
824 }
825
826 printf(") ");
827 break;
828 }
829
830 case ast_identifier:
831 printf("%s ", primary_expression.identifier);
832 break;
833
834 case ast_int_constant:
835 printf("%d ", primary_expression.int_constant);
836 break;
837
838 case ast_uint_constant:
839 printf("%u ", primary_expression.uint_constant);
840 break;
841
842 case ast_float_constant:
843 printf("%f ", primary_expression.float_constant);
844 break;
845
846 case ast_bool_constant:
847 printf("%s ",
848 primary_expression.bool_constant
849 ? "true" : "false");
850 break;
851
852 case ast_sequence: {
853 printf("( ");
854 foreach_list_const(n, & this->expressions) {
855 if (n != this->expressions.get_head())
856 printf(", ");
857
858 ast_node *ast = exec_node_data(ast_node, n, link);
859 ast->print();
860 }
861 printf(") ");
862 break;
863 }
864
865 default:
866 assert(0);
867 break;
868 }
869 }
870
871 ast_expression::ast_expression(int oper,
872 ast_expression *ex0,
873 ast_expression *ex1,
874 ast_expression *ex2)
875 {
876 this->oper = ast_operators(oper);
877 this->subexpressions[0] = ex0;
878 this->subexpressions[1] = ex1;
879 this->subexpressions[2] = ex2;
880 this->non_lvalue_description = NULL;
881 }
882
883
884 void
885 ast_expression_statement::print(void) const
886 {
887 if (expression)
888 expression->print();
889
890 printf("; ");
891 }
892
893
894 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
895 expression(ex)
896 {
897 /* empty */
898 }
899
900
901 void
902 ast_function::print(void) const
903 {
904 return_type->print();
905 printf(" %s (", identifier);
906
907 foreach_list_const(n, & this->parameters) {
908 ast_node *ast = exec_node_data(ast_node, n, link);
909 ast->print();
910 }
911
912 printf(")");
913 }
914
915
916 ast_function::ast_function(void)
917 : is_definition(false), signature(NULL)
918 {
919 /* empty */
920 }
921
922
923 void
924 ast_fully_specified_type::print(void) const
925 {
926 _mesa_ast_type_qualifier_print(& qualifier);
927 specifier->print();
928 }
929
930
931 void
932 ast_parameter_declarator::print(void) const
933 {
934 type->print();
935 if (identifier)
936 printf("%s ", identifier);
937 ast_opt_array_size_print(is_array, array_size);
938 }
939
940
941 void
942 ast_function_definition::print(void) const
943 {
944 prototype->print();
945 body->print();
946 }
947
948
949 void
950 ast_declaration::print(void) const
951 {
952 printf("%s ", identifier);
953 ast_opt_array_size_print(is_array, array_size);
954
955 if (initializer) {
956 printf("= ");
957 initializer->print();
958 }
959 }
960
961
962 ast_declaration::ast_declaration(const char *identifier, int is_array,
963 ast_expression *array_size,
964 ast_expression *initializer)
965 {
966 this->identifier = identifier;
967 this->is_array = is_array;
968 this->array_size = array_size;
969 this->initializer = initializer;
970 }
971
972
973 void
974 ast_declarator_list::print(void) const
975 {
976 assert(type || invariant);
977
978 if (type)
979 type->print();
980 else
981 printf("invariant ");
982
983 foreach_list_const (ptr, & this->declarations) {
984 if (ptr != this->declarations.get_head())
985 printf(", ");
986
987 ast_node *ast = exec_node_data(ast_node, ptr, link);
988 ast->print();
989 }
990
991 printf("; ");
992 }
993
994
995 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
996 {
997 this->type = type;
998 this->invariant = false;
999 this->ubo_qualifiers_valid = false;
1000 }
1001
1002 void
1003 ast_jump_statement::print(void) const
1004 {
1005 switch (mode) {
1006 case ast_continue:
1007 printf("continue; ");
1008 break;
1009 case ast_break:
1010 printf("break; ");
1011 break;
1012 case ast_return:
1013 printf("return ");
1014 if (opt_return_value)
1015 opt_return_value->print();
1016
1017 printf("; ");
1018 break;
1019 case ast_discard:
1020 printf("discard; ");
1021 break;
1022 }
1023 }
1024
1025
1026 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
1027 {
1028 this->mode = ast_jump_modes(mode);
1029
1030 if (mode == ast_return)
1031 opt_return_value = return_value;
1032 }
1033
1034
1035 void
1036 ast_selection_statement::print(void) const
1037 {
1038 printf("if ( ");
1039 condition->print();
1040 printf(") ");
1041
1042 then_statement->print();
1043
1044 if (else_statement) {
1045 printf("else ");
1046 else_statement->print();
1047 }
1048
1049 }
1050
1051
1052 ast_selection_statement::ast_selection_statement(ast_expression *condition,
1053 ast_node *then_statement,
1054 ast_node *else_statement)
1055 {
1056 this->condition = condition;
1057 this->then_statement = then_statement;
1058 this->else_statement = else_statement;
1059 }
1060
1061
1062 void
1063 ast_switch_statement::print(void) const
1064 {
1065 printf("switch ( ");
1066 test_expression->print();
1067 printf(") ");
1068
1069 body->print();
1070 }
1071
1072
1073 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
1074 ast_node *body)
1075 {
1076 this->test_expression = test_expression;
1077 this->body = body;
1078 }
1079
1080
1081 void
1082 ast_switch_body::print(void) const
1083 {
1084 printf("{\n");
1085 if (stmts != NULL) {
1086 stmts->print();
1087 }
1088 printf("}\n");
1089 }
1090
1091
1092 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
1093 {
1094 this->stmts = stmts;
1095 }
1096
1097
1098 void ast_case_label::print(void) const
1099 {
1100 if (test_value != NULL) {
1101 printf("case ");
1102 test_value->print();
1103 printf(": ");
1104 } else {
1105 printf("default: ");
1106 }
1107 }
1108
1109
1110 ast_case_label::ast_case_label(ast_expression *test_value)
1111 {
1112 this->test_value = test_value;
1113 }
1114
1115
1116 void ast_case_label_list::print(void) const
1117 {
1118 foreach_list_const(n, & this->labels) {
1119 ast_node *ast = exec_node_data(ast_node, n, link);
1120 ast->print();
1121 }
1122 printf("\n");
1123 }
1124
1125
1126 ast_case_label_list::ast_case_label_list(void)
1127 {
1128 }
1129
1130
1131 void ast_case_statement::print(void) const
1132 {
1133 labels->print();
1134 foreach_list_const(n, & this->stmts) {
1135 ast_node *ast = exec_node_data(ast_node, n, link);
1136 ast->print();
1137 printf("\n");
1138 }
1139 }
1140
1141
1142 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
1143 {
1144 this->labels = labels;
1145 }
1146
1147
1148 void ast_case_statement_list::print(void) const
1149 {
1150 foreach_list_const(n, & this->cases) {
1151 ast_node *ast = exec_node_data(ast_node, n, link);
1152 ast->print();
1153 }
1154 }
1155
1156
1157 ast_case_statement_list::ast_case_statement_list(void)
1158 {
1159 }
1160
1161
1162 void
1163 ast_iteration_statement::print(void) const
1164 {
1165 switch (mode) {
1166 case ast_for:
1167 printf("for( ");
1168 if (init_statement)
1169 init_statement->print();
1170 printf("; ");
1171
1172 if (condition)
1173 condition->print();
1174 printf("; ");
1175
1176 if (rest_expression)
1177 rest_expression->print();
1178 printf(") ");
1179
1180 body->print();
1181 break;
1182
1183 case ast_while:
1184 printf("while ( ");
1185 if (condition)
1186 condition->print();
1187 printf(") ");
1188 body->print();
1189 break;
1190
1191 case ast_do_while:
1192 printf("do ");
1193 body->print();
1194 printf("while ( ");
1195 if (condition)
1196 condition->print();
1197 printf("); ");
1198 break;
1199 }
1200 }
1201
1202
1203 ast_iteration_statement::ast_iteration_statement(int mode,
1204 ast_node *init,
1205 ast_node *condition,
1206 ast_expression *rest_expression,
1207 ast_node *body)
1208 {
1209 this->mode = ast_iteration_modes(mode);
1210 this->init_statement = init;
1211 this->condition = condition;
1212 this->rest_expression = rest_expression;
1213 this->body = body;
1214 }
1215
1216
1217 void
1218 ast_struct_specifier::print(void) const
1219 {
1220 printf("struct %s { ", name);
1221 foreach_list_const(n, &this->declarations) {
1222 ast_node *ast = exec_node_data(ast_node, n, link);
1223 ast->print();
1224 }
1225 printf("} ");
1226 }
1227
1228
1229 ast_struct_specifier::ast_struct_specifier(const char *identifier,
1230 ast_declarator_list *declarator_list)
1231 {
1232 if (identifier == NULL) {
1233 static unsigned anon_count = 1;
1234 identifier = ralloc_asprintf(this, "#anon_struct_%04x", anon_count);
1235 anon_count++;
1236 }
1237 name = identifier;
1238 this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1239 }
1240
1241 extern "C" {
1242
1243 void
1244 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader,
1245 bool dump_ast, bool dump_hir)
1246 {
1247 struct _mesa_glsl_parse_state *state =
1248 new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
1249 const char *source = shader->Source;
1250
1251 state->error = glcpp_preprocess(state, &source, &state->info_log,
1252 &ctx->Extensions, ctx);
1253
1254 if (!state->error) {
1255 _mesa_glsl_lexer_ctor(state, source);
1256 _mesa_glsl_parse(state);
1257 _mesa_glsl_lexer_dtor(state);
1258 }
1259
1260 if (dump_ast) {
1261 foreach_list_const(n, &state->translation_unit) {
1262 ast_node *ast = exec_node_data(ast_node, n, link);
1263 ast->print();
1264 }
1265 printf("\n\n");
1266 }
1267
1268 ralloc_free(shader->ir);
1269 shader->ir = new(shader) exec_list;
1270 if (!state->error && !state->translation_unit.is_empty())
1271 _mesa_ast_to_hir(shader->ir, state);
1272
1273 if (!state->error) {
1274 validate_ir_tree(shader->ir);
1275
1276 /* Print out the unoptimized IR. */
1277 if (dump_hir) {
1278 _mesa_print_ir(shader->ir, state);
1279 }
1280 }
1281
1282
1283 if (!state->error && !shader->ir->is_empty()) {
1284 struct gl_shader_compiler_options *options =
1285 &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
1286
1287 /* Do some optimization at compile time to reduce shader IR size
1288 * and reduce later work if the same shader is linked multiple times
1289 */
1290 while (do_common_optimization(shader->ir, false, false, 32, options))
1291 ;
1292
1293 validate_ir_tree(shader->ir);
1294 }
1295
1296 if (shader->InfoLog)
1297 ralloc_free(shader->InfoLog);
1298
1299 shader->symbols = state->symbols;
1300 shader->CompileStatus = !state->error;
1301 shader->InfoLog = state->info_log;
1302 shader->Version = state->language_version;
1303 shader->InfoLog = state->info_log;
1304 shader->IsES = state->es_shader;
1305
1306 memcpy(shader->builtins_to_link, state->builtins_to_link,
1307 sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
1308 shader->num_builtins_to_link = state->num_builtins_to_link;
1309
1310 if (shader->UniformBlocks)
1311 ralloc_free(shader->UniformBlocks);
1312 shader->NumUniformBlocks = state->num_uniform_blocks;
1313 shader->UniformBlocks = state->uniform_blocks;
1314 ralloc_steal(shader, shader->UniformBlocks);
1315
1316 /* Retain any live IR, but trash the rest. */
1317 reparent_ir(shader->ir, shader->ir);
1318
1319 ralloc_free(state);
1320 }
1321
1322 } /* extern "C" */
1323 /**
1324 * Do the set of common optimizations passes
1325 *
1326 * \param ir List of instructions to be optimized
1327 * \param linked Is the shader linked? This enables
1328 * optimizations passes that remove code at
1329 * global scope and could cause linking to
1330 * fail.
1331 * \param uniform_locations_assigned Have locations already been assigned for
1332 * uniforms? This prevents the declarations
1333 * of unused uniforms from being removed.
1334 * The setting of this flag only matters if
1335 * \c linked is \c true.
1336 * \param max_unroll_iterations Maximum number of loop iterations to be
1337 * unrolled. Setting to 0 disables loop
1338 * unrolling.
1339 * \param options The driver's preferred shader options.
1340 */
1341 bool
1342 do_common_optimization(exec_list *ir, bool linked,
1343 bool uniform_locations_assigned,
1344 unsigned max_unroll_iterations,
1345 const struct gl_shader_compiler_options *options)
1346 {
1347 GLboolean progress = GL_FALSE;
1348
1349 progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
1350
1351 if (linked) {
1352 progress = do_function_inlining(ir) || progress;
1353 progress = do_dead_functions(ir) || progress;
1354 progress = do_structure_splitting(ir) || progress;
1355 }
1356 progress = do_if_simplification(ir) || progress;
1357 progress = opt_flatten_nested_if_blocks(ir) || progress;
1358 progress = do_copy_propagation(ir) || progress;
1359 progress = do_copy_propagation_elements(ir) || progress;
1360
1361 if (options->PreferDP4 && !linked)
1362 progress = opt_flip_matrices(ir) || progress;
1363
1364 if (linked)
1365 progress = do_dead_code(ir, uniform_locations_assigned) || progress;
1366 else
1367 progress = do_dead_code_unlinked(ir) || progress;
1368 progress = do_dead_code_local(ir) || progress;
1369 progress = do_tree_grafting(ir) || progress;
1370 progress = do_constant_propagation(ir) || progress;
1371 if (linked)
1372 progress = do_constant_variable(ir) || progress;
1373 else
1374 progress = do_constant_variable_unlinked(ir) || progress;
1375 progress = do_constant_folding(ir) || progress;
1376 progress = do_algebraic(ir) || progress;
1377 progress = do_lower_jumps(ir) || progress;
1378 progress = do_vec_index_to_swizzle(ir) || progress;
1379 progress = lower_vector_insert(ir, false) || progress;
1380 progress = do_swizzle_swizzle(ir) || progress;
1381 progress = do_noop_swizzle(ir) || progress;
1382
1383 progress = optimize_split_arrays(ir, linked) || progress;
1384 progress = optimize_redundant_jumps(ir) || progress;
1385
1386 loop_state *ls = analyze_loop_variables(ir);
1387 if (ls->loop_found) {
1388 progress = set_loop_controls(ir, ls) || progress;
1389 progress = unroll_loops(ir, ls, max_unroll_iterations) || progress;
1390 }
1391 delete ls;
1392
1393 return progress;
1394 }
1395
1396 extern "C" {
1397
1398 /**
1399 * To be called at GL teardown time, this frees compiler datastructures.
1400 *
1401 * After calling this, any previously compiled shaders and shader
1402 * programs would be invalid. So this should happen at approximately
1403 * program exit.
1404 */
1405 void
1406 _mesa_destroy_shader_compiler(void)
1407 {
1408 _mesa_destroy_shader_compiler_caches();
1409
1410 _mesa_glsl_release_types();
1411 }
1412
1413 /**
1414 * Releases compiler caches to trade off performance for memory.
1415 *
1416 * Intended to be used with glReleaseShaderCompiler().
1417 */
1418 void
1419 _mesa_destroy_shader_compiler_caches(void)
1420 {
1421 _mesa_glsl_release_functions();
1422 }
1423
1424 }