glsl: Do not call lhs->variable_referenced() multiple times
[mesa.git] / src / glsl / ast_to_hir.cpp
1 /*
2 * Copyright © 2010 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
24 /**
25 * \file ast_to_hir.c
26 * Convert abstract syntax to to high-level intermediate reprensentation (HIR).
27 *
28 * During the conversion to HIR, the majority of the symantic checking is
29 * preformed on the program. This includes:
30 *
31 * * Symbol table management
32 * * Type checking
33 * * Function binding
34 *
35 * The majority of this work could be done during parsing, and the parser could
36 * probably generate HIR directly. However, this results in frequent changes
37 * to the parser code. Since we do not assume that every system this complier
38 * is built on will have Flex and Bison installed, we have to store the code
39 * generated by these tools in our version control system. In other parts of
40 * the system we've seen problems where a parser was changed but the generated
41 * code was not committed, merge conflicts where created because two developers
42 * had slightly different versions of Bison installed, etc.
43 *
44 * I have also noticed that running Bison generated parsers in GDB is very
45 * irritating. When you get a segfault on '$$ = $1->foo', you can't very
46 * well 'print $1' in GDB.
47 *
48 * As a result, my preference is to put as little C code as possible in the
49 * parser (and lexer) sources.
50 */
51
52 #include "main/core.h" /* for struct gl_extensions */
53 #include "glsl_symbol_table.h"
54 #include "glsl_parser_extras.h"
55 #include "ast.h"
56 #include "glsl_types.h"
57 #include "program/hash_table.h"
58 #include "ir.h"
59 #include "ir_builder.h"
60
61 using namespace ir_builder;
62
63 static void
64 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
65 exec_list *instructions);
66 static void
67 remove_per_vertex_blocks(exec_list *instructions,
68 _mesa_glsl_parse_state *state, ir_variable_mode mode);
69
70
71 void
72 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
73 {
74 _mesa_glsl_initialize_variables(instructions, state);
75
76 state->symbols->separate_function_namespace = state->language_version == 110;
77
78 state->current_function = NULL;
79
80 state->toplevel_ir = instructions;
81
82 state->gs_input_prim_type_specified = false;
83 state->cs_input_local_size_specified = false;
84
85 /* Section 4.2 of the GLSL 1.20 specification states:
86 * "The built-in functions are scoped in a scope outside the global scope
87 * users declare global variables in. That is, a shader's global scope,
88 * available for user-defined functions and global variables, is nested
89 * inside the scope containing the built-in functions."
90 *
91 * Since built-in functions like ftransform() access built-in variables,
92 * it follows that those must be in the outer scope as well.
93 *
94 * We push scope here to create this nesting effect...but don't pop.
95 * This way, a shader's globals are still in the symbol table for use
96 * by the linker.
97 */
98 state->symbols->push_scope();
99
100 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
101 ast->hir(instructions, state);
102
103 detect_recursion_unlinked(state, instructions);
104 detect_conflicting_assignments(state, instructions);
105
106 state->toplevel_ir = NULL;
107
108 /* Move all of the variable declarations to the front of the IR list, and
109 * reverse the order. This has the (intended!) side effect that vertex
110 * shader inputs and fragment shader outputs will appear in the IR in the
111 * same order that they appeared in the shader code. This results in the
112 * locations being assigned in the declared order. Many (arguably buggy)
113 * applications depend on this behavior, and it matches what nearly all
114 * other drivers do.
115 */
116 foreach_list_safe(node, instructions) {
117 ir_variable *const var = ((ir_instruction *) node)->as_variable();
118
119 if (var == NULL)
120 continue;
121
122 var->remove();
123 instructions->push_head(var);
124 }
125
126 /* Figure out if gl_FragCoord is actually used in fragment shader */
127 ir_variable *const var = state->symbols->get_variable("gl_FragCoord");
128 if (var != NULL)
129 state->fs_uses_gl_fragcoord = var->data.used;
130
131 /* From section 7.1 (Built-In Language Variables) of the GLSL 4.10 spec:
132 *
133 * If multiple shaders using members of a built-in block belonging to
134 * the same interface are linked together in the same program, they
135 * must all redeclare the built-in block in the same way, as described
136 * in section 4.3.7 "Interface Blocks" for interface block matching, or
137 * a link error will result.
138 *
139 * The phrase "using members of a built-in block" implies that if two
140 * shaders are linked together and one of them *does not use* any members
141 * of the built-in block, then that shader does not need to have a matching
142 * redeclaration of the built-in block.
143 *
144 * This appears to be a clarification to the behaviour established for
145 * gl_PerVertex by GLSL 1.50, therefore implement it regardless of GLSL
146 * version.
147 *
148 * The definition of "interface" in section 4.3.7 that applies here is as
149 * follows:
150 *
151 * The boundary between adjacent programmable pipeline stages: This
152 * spans all the outputs in all compilation units of the first stage
153 * and all the inputs in all compilation units of the second stage.
154 *
155 * Therefore this rule applies to both inter- and intra-stage linking.
156 *
157 * The easiest way to implement this is to check whether the shader uses
158 * gl_PerVertex right after ast-to-ir conversion, and if it doesn't, simply
159 * remove all the relevant variable declaration from the IR, so that the
160 * linker won't see them and complain about mismatches.
161 */
162 remove_per_vertex_blocks(instructions, state, ir_var_shader_in);
163 remove_per_vertex_blocks(instructions, state, ir_var_shader_out);
164 }
165
166
167 /**
168 * If a conversion is available, convert one operand to a different type
169 *
170 * The \c from \c ir_rvalue is converted "in place".
171 *
172 * \param to Type that the operand it to be converted to
173 * \param from Operand that is being converted
174 * \param state GLSL compiler state
175 *
176 * \return
177 * If a conversion is possible (or unnecessary), \c true is returned.
178 * Otherwise \c false is returned.
179 */
180 bool
181 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
182 struct _mesa_glsl_parse_state *state)
183 {
184 void *ctx = state;
185 if (to->base_type == from->type->base_type)
186 return true;
187
188 /* This conversion was added in GLSL 1.20. If the compilation mode is
189 * GLSL 1.10, the conversion is skipped.
190 */
191 if (!state->is_version(120, 0))
192 return false;
193
194 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
195 *
196 * "There are no implicit array or structure conversions. For
197 * example, an array of int cannot be implicitly converted to an
198 * array of float. There are no implicit conversions between
199 * signed and unsigned integers."
200 */
201 /* FINISHME: The above comment is partially a lie. There is int/uint
202 * FINISHME: conversion for immediate constants.
203 */
204 if (!to->is_float() || !from->type->is_numeric())
205 return false;
206
207 /* Convert to a floating point type with the same number of components
208 * as the original type - i.e. int to float, not int to vec4.
209 */
210 to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
211 from->type->matrix_columns);
212
213 switch (from->type->base_type) {
214 case GLSL_TYPE_INT:
215 from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
216 break;
217 case GLSL_TYPE_UINT:
218 from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
219 break;
220 case GLSL_TYPE_BOOL:
221 from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
222 break;
223 default:
224 assert(0);
225 }
226
227 return true;
228 }
229
230
231 static const struct glsl_type *
232 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
233 bool multiply,
234 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
235 {
236 const glsl_type *type_a = value_a->type;
237 const glsl_type *type_b = value_b->type;
238
239 /* From GLSL 1.50 spec, page 56:
240 *
241 * "The arithmetic binary operators add (+), subtract (-),
242 * multiply (*), and divide (/) operate on integer and
243 * floating-point scalars, vectors, and matrices."
244 */
245 if (!type_a->is_numeric() || !type_b->is_numeric()) {
246 _mesa_glsl_error(loc, state,
247 "operands to arithmetic operators must be numeric");
248 return glsl_type::error_type;
249 }
250
251
252 /* "If one operand is floating-point based and the other is
253 * not, then the conversions from Section 4.1.10 "Implicit
254 * Conversions" are applied to the non-floating-point-based operand."
255 */
256 if (!apply_implicit_conversion(type_a, value_b, state)
257 && !apply_implicit_conversion(type_b, value_a, state)) {
258 _mesa_glsl_error(loc, state,
259 "could not implicitly convert operands to "
260 "arithmetic operator");
261 return glsl_type::error_type;
262 }
263 type_a = value_a->type;
264 type_b = value_b->type;
265
266 /* "If the operands are integer types, they must both be signed or
267 * both be unsigned."
268 *
269 * From this rule and the preceeding conversion it can be inferred that
270 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
271 * The is_numeric check above already filtered out the case where either
272 * type is not one of these, so now the base types need only be tested for
273 * equality.
274 */
275 if (type_a->base_type != type_b->base_type) {
276 _mesa_glsl_error(loc, state,
277 "base type mismatch for arithmetic operator");
278 return glsl_type::error_type;
279 }
280
281 /* "All arithmetic binary operators result in the same fundamental type
282 * (signed integer, unsigned integer, or floating-point) as the
283 * operands they operate on, after operand type conversion. After
284 * conversion, the following cases are valid
285 *
286 * * The two operands are scalars. In this case the operation is
287 * applied, resulting in a scalar."
288 */
289 if (type_a->is_scalar() && type_b->is_scalar())
290 return type_a;
291
292 /* "* One operand is a scalar, and the other is a vector or matrix.
293 * In this case, the scalar operation is applied independently to each
294 * component of the vector or matrix, resulting in the same size
295 * vector or matrix."
296 */
297 if (type_a->is_scalar()) {
298 if (!type_b->is_scalar())
299 return type_b;
300 } else if (type_b->is_scalar()) {
301 return type_a;
302 }
303
304 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
305 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
306 * handled.
307 */
308 assert(!type_a->is_scalar());
309 assert(!type_b->is_scalar());
310
311 /* "* The two operands are vectors of the same size. In this case, the
312 * operation is done component-wise resulting in the same size
313 * vector."
314 */
315 if (type_a->is_vector() && type_b->is_vector()) {
316 if (type_a == type_b) {
317 return type_a;
318 } else {
319 _mesa_glsl_error(loc, state,
320 "vector size mismatch for arithmetic operator");
321 return glsl_type::error_type;
322 }
323 }
324
325 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
326 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
327 * <vector, vector> have been handled. At least one of the operands must
328 * be matrix. Further, since there are no integer matrix types, the base
329 * type of both operands must be float.
330 */
331 assert(type_a->is_matrix() || type_b->is_matrix());
332 assert(type_a->base_type == GLSL_TYPE_FLOAT);
333 assert(type_b->base_type == GLSL_TYPE_FLOAT);
334
335 /* "* The operator is add (+), subtract (-), or divide (/), and the
336 * operands are matrices with the same number of rows and the same
337 * number of columns. In this case, the operation is done component-
338 * wise resulting in the same size matrix."
339 * * The operator is multiply (*), where both operands are matrices or
340 * one operand is a vector and the other a matrix. A right vector
341 * operand is treated as a column vector and a left vector operand as a
342 * row vector. In all these cases, it is required that the number of
343 * columns of the left operand is equal to the number of rows of the
344 * right operand. Then, the multiply (*) operation does a linear
345 * algebraic multiply, yielding an object that has the same number of
346 * rows as the left operand and the same number of columns as the right
347 * operand. Section 5.10 "Vector and Matrix Operations" explains in
348 * more detail how vectors and matrices are operated on."
349 */
350 if (! multiply) {
351 if (type_a == type_b)
352 return type_a;
353 } else {
354 if (type_a->is_matrix() && type_b->is_matrix()) {
355 /* Matrix multiply. The columns of A must match the rows of B. Given
356 * the other previously tested constraints, this means the vector type
357 * of a row from A must be the same as the vector type of a column from
358 * B.
359 */
360 if (type_a->row_type() == type_b->column_type()) {
361 /* The resulting matrix has the number of columns of matrix B and
362 * the number of rows of matrix A. We get the row count of A by
363 * looking at the size of a vector that makes up a column. The
364 * transpose (size of a row) is done for B.
365 */
366 const glsl_type *const type =
367 glsl_type::get_instance(type_a->base_type,
368 type_a->column_type()->vector_elements,
369 type_b->row_type()->vector_elements);
370 assert(type != glsl_type::error_type);
371
372 return type;
373 }
374 } else if (type_a->is_matrix()) {
375 /* A is a matrix and B is a column vector. Columns of A must match
376 * rows of B. Given the other previously tested constraints, this
377 * means the vector type of a row from A must be the same as the
378 * vector the type of B.
379 */
380 if (type_a->row_type() == type_b) {
381 /* The resulting vector has a number of elements equal to
382 * the number of rows of matrix A. */
383 const glsl_type *const type =
384 glsl_type::get_instance(type_a->base_type,
385 type_a->column_type()->vector_elements,
386 1);
387 assert(type != glsl_type::error_type);
388
389 return type;
390 }
391 } else {
392 assert(type_b->is_matrix());
393
394 /* A is a row vector and B is a matrix. Columns of A must match rows
395 * of B. Given the other previously tested constraints, this means
396 * the type of A must be the same as the vector type of a column from
397 * B.
398 */
399 if (type_a == type_b->column_type()) {
400 /* The resulting vector has a number of elements equal to
401 * the number of columns of matrix B. */
402 const glsl_type *const type =
403 glsl_type::get_instance(type_a->base_type,
404 type_b->row_type()->vector_elements,
405 1);
406 assert(type != glsl_type::error_type);
407
408 return type;
409 }
410 }
411
412 _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
413 return glsl_type::error_type;
414 }
415
416
417 /* "All other cases are illegal."
418 */
419 _mesa_glsl_error(loc, state, "type mismatch");
420 return glsl_type::error_type;
421 }
422
423
424 static const struct glsl_type *
425 unary_arithmetic_result_type(const struct glsl_type *type,
426 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
427 {
428 /* From GLSL 1.50 spec, page 57:
429 *
430 * "The arithmetic unary operators negate (-), post- and pre-increment
431 * and decrement (-- and ++) operate on integer or floating-point
432 * values (including vectors and matrices). All unary operators work
433 * component-wise on their operands. These result with the same type
434 * they operated on."
435 */
436 if (!type->is_numeric()) {
437 _mesa_glsl_error(loc, state,
438 "operands to arithmetic operators must be numeric");
439 return glsl_type::error_type;
440 }
441
442 return type;
443 }
444
445 /**
446 * \brief Return the result type of a bit-logic operation.
447 *
448 * If the given types to the bit-logic operator are invalid, return
449 * glsl_type::error_type.
450 *
451 * \param type_a Type of LHS of bit-logic op
452 * \param type_b Type of RHS of bit-logic op
453 */
454 static const struct glsl_type *
455 bit_logic_result_type(const struct glsl_type *type_a,
456 const struct glsl_type *type_b,
457 ast_operators op,
458 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
459 {
460 if (!state->check_bitwise_operations_allowed(loc)) {
461 return glsl_type::error_type;
462 }
463
464 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
465 *
466 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
467 * (|). The operands must be of type signed or unsigned integers or
468 * integer vectors."
469 */
470 if (!type_a->is_integer()) {
471 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
472 ast_expression::operator_string(op));
473 return glsl_type::error_type;
474 }
475 if (!type_b->is_integer()) {
476 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
477 ast_expression::operator_string(op));
478 return glsl_type::error_type;
479 }
480
481 /* "The fundamental types of the operands (signed or unsigned) must
482 * match,"
483 */
484 if (type_a->base_type != type_b->base_type) {
485 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
486 "base type", ast_expression::operator_string(op));
487 return glsl_type::error_type;
488 }
489
490 /* "The operands cannot be vectors of differing size." */
491 if (type_a->is_vector() &&
492 type_b->is_vector() &&
493 type_a->vector_elements != type_b->vector_elements) {
494 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
495 "different sizes", ast_expression::operator_string(op));
496 return glsl_type::error_type;
497 }
498
499 /* "If one operand is a scalar and the other a vector, the scalar is
500 * applied component-wise to the vector, resulting in the same type as
501 * the vector. The fundamental types of the operands [...] will be the
502 * resulting fundamental type."
503 */
504 if (type_a->is_scalar())
505 return type_b;
506 else
507 return type_a;
508 }
509
510 static const struct glsl_type *
511 modulus_result_type(const struct glsl_type *type_a,
512 const struct glsl_type *type_b,
513 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
514 {
515 if (!state->check_version(130, 300, loc, "operator '%%' is reserved")) {
516 return glsl_type::error_type;
517 }
518
519 /* From GLSL 1.50 spec, page 56:
520 * "The operator modulus (%) operates on signed or unsigned integers or
521 * integer vectors. The operand types must both be signed or both be
522 * unsigned."
523 */
524 if (!type_a->is_integer()) {
525 _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer");
526 return glsl_type::error_type;
527 }
528 if (!type_b->is_integer()) {
529 _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer");
530 return glsl_type::error_type;
531 }
532 if (type_a->base_type != type_b->base_type) {
533 _mesa_glsl_error(loc, state,
534 "operands of %% must have the same base type");
535 return glsl_type::error_type;
536 }
537
538 /* "The operands cannot be vectors of differing size. If one operand is
539 * a scalar and the other vector, then the scalar is applied component-
540 * wise to the vector, resulting in the same type as the vector. If both
541 * are vectors of the same size, the result is computed component-wise."
542 */
543 if (type_a->is_vector()) {
544 if (!type_b->is_vector()
545 || (type_a->vector_elements == type_b->vector_elements))
546 return type_a;
547 } else
548 return type_b;
549
550 /* "The operator modulus (%) is not defined for any other data types
551 * (non-integer types)."
552 */
553 _mesa_glsl_error(loc, state, "type mismatch");
554 return glsl_type::error_type;
555 }
556
557
558 static const struct glsl_type *
559 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
560 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
561 {
562 const glsl_type *type_a = value_a->type;
563 const glsl_type *type_b = value_b->type;
564
565 /* From GLSL 1.50 spec, page 56:
566 * "The relational operators greater than (>), less than (<), greater
567 * than or equal (>=), and less than or equal (<=) operate only on
568 * scalar integer and scalar floating-point expressions."
569 */
570 if (!type_a->is_numeric()
571 || !type_b->is_numeric()
572 || !type_a->is_scalar()
573 || !type_b->is_scalar()) {
574 _mesa_glsl_error(loc, state,
575 "operands to relational operators must be scalar and "
576 "numeric");
577 return glsl_type::error_type;
578 }
579
580 /* "Either the operands' types must match, or the conversions from
581 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
582 * operand, after which the types must match."
583 */
584 if (!apply_implicit_conversion(type_a, value_b, state)
585 && !apply_implicit_conversion(type_b, value_a, state)) {
586 _mesa_glsl_error(loc, state,
587 "could not implicitly convert operands to "
588 "relational operator");
589 return glsl_type::error_type;
590 }
591 type_a = value_a->type;
592 type_b = value_b->type;
593
594 if (type_a->base_type != type_b->base_type) {
595 _mesa_glsl_error(loc, state, "base type mismatch");
596 return glsl_type::error_type;
597 }
598
599 /* "The result is scalar Boolean."
600 */
601 return glsl_type::bool_type;
602 }
603
604 /**
605 * \brief Return the result type of a bit-shift operation.
606 *
607 * If the given types to the bit-shift operator are invalid, return
608 * glsl_type::error_type.
609 *
610 * \param type_a Type of LHS of bit-shift op
611 * \param type_b Type of RHS of bit-shift op
612 */
613 static const struct glsl_type *
614 shift_result_type(const struct glsl_type *type_a,
615 const struct glsl_type *type_b,
616 ast_operators op,
617 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
618 {
619 if (!state->check_bitwise_operations_allowed(loc)) {
620 return glsl_type::error_type;
621 }
622
623 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
624 *
625 * "The shift operators (<<) and (>>). For both operators, the operands
626 * must be signed or unsigned integers or integer vectors. One operand
627 * can be signed while the other is unsigned."
628 */
629 if (!type_a->is_integer()) {
630 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
631 "integer vector", ast_expression::operator_string(op));
632 return glsl_type::error_type;
633
634 }
635 if (!type_b->is_integer()) {
636 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
637 "integer vector", ast_expression::operator_string(op));
638 return glsl_type::error_type;
639 }
640
641 /* "If the first operand is a scalar, the second operand has to be
642 * a scalar as well."
643 */
644 if (type_a->is_scalar() && !type_b->is_scalar()) {
645 _mesa_glsl_error(loc, state, "if the first operand of %s is scalar, the "
646 "second must be scalar as well",
647 ast_expression::operator_string(op));
648 return glsl_type::error_type;
649 }
650
651 /* If both operands are vectors, check that they have same number of
652 * elements.
653 */
654 if (type_a->is_vector() &&
655 type_b->is_vector() &&
656 type_a->vector_elements != type_b->vector_elements) {
657 _mesa_glsl_error(loc, state, "vector operands to operator %s must "
658 "have same number of elements",
659 ast_expression::operator_string(op));
660 return glsl_type::error_type;
661 }
662
663 /* "In all cases, the resulting type will be the same type as the left
664 * operand."
665 */
666 return type_a;
667 }
668
669 /**
670 * Validates that a value can be assigned to a location with a specified type
671 *
672 * Validates that \c rhs can be assigned to some location. If the types are
673 * not an exact match but an automatic conversion is possible, \c rhs will be
674 * converted.
675 *
676 * \return
677 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
678 * Otherwise the actual RHS to be assigned will be returned. This may be
679 * \c rhs, or it may be \c rhs after some type conversion.
680 *
681 * \note
682 * In addition to being used for assignments, this function is used to
683 * type-check return values.
684 */
685 ir_rvalue *
686 validate_assignment(struct _mesa_glsl_parse_state *state,
687 YYLTYPE loc, const glsl_type *lhs_type,
688 ir_rvalue *rhs, bool is_initializer)
689 {
690 /* If there is already some error in the RHS, just return it. Anything
691 * else will lead to an avalanche of error message back to the user.
692 */
693 if (rhs->type->is_error())
694 return rhs;
695
696 /* If the types are identical, the assignment can trivially proceed.
697 */
698 if (rhs->type == lhs_type)
699 return rhs;
700
701 /* If the array element types are the same and the LHS is unsized,
702 * the assignment is okay for initializers embedded in variable
703 * declarations.
704 *
705 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
706 * is handled by ir_dereference::is_lvalue.
707 */
708 if (lhs_type->is_unsized_array() && rhs->type->is_array()
709 && (lhs_type->element_type() == rhs->type->element_type())) {
710 if (is_initializer) {
711 return rhs;
712 } else {
713 _mesa_glsl_error(&loc, state,
714 "implicitly sized arrays cannot be assigned");
715 return NULL;
716 }
717 }
718
719 /* Check for implicit conversion in GLSL 1.20 */
720 if (apply_implicit_conversion(lhs_type, rhs, state)) {
721 if (rhs->type == lhs_type)
722 return rhs;
723 }
724
725 _mesa_glsl_error(&loc, state,
726 "%s of type %s cannot be assigned to "
727 "variable of type %s",
728 is_initializer ? "initializer" : "value",
729 rhs->type->name, lhs_type->name);
730
731 return NULL;
732 }
733
734 static void
735 mark_whole_array_access(ir_rvalue *access)
736 {
737 ir_dereference_variable *deref = access->as_dereference_variable();
738
739 if (deref && deref->var) {
740 deref->var->data.max_array_access = deref->type->length - 1;
741 }
742 }
743
744 static bool
745 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
746 const char *non_lvalue_description,
747 ir_rvalue *lhs, ir_rvalue *rhs,
748 ir_rvalue **out_rvalue, bool needs_rvalue,
749 bool is_initializer,
750 YYLTYPE lhs_loc)
751 {
752 void *ctx = state;
753 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
754 ir_rvalue *extract_channel = NULL;
755
756 /* If the assignment LHS comes back as an ir_binop_vector_extract
757 * expression, move it to the RHS as an ir_triop_vector_insert.
758 */
759 if (lhs->ir_type == ir_type_expression) {
760 ir_expression *const lhs_expr = lhs->as_expression();
761
762 if (unlikely(lhs_expr->operation == ir_binop_vector_extract)) {
763 ir_rvalue *new_rhs =
764 validate_assignment(state, lhs_loc, lhs->type,
765 rhs, is_initializer);
766
767 if (new_rhs == NULL) {
768 return lhs;
769 } else {
770 /* This converts:
771 * - LHS: (expression float vector_extract <vec> <channel>)
772 * - RHS: <scalar>
773 * into:
774 * - LHS: <vec>
775 * - RHS: (expression vec2 vector_insert <vec> <channel> <scalar>)
776 *
777 * The LHS type is now a vector instead of a scalar. Since GLSL
778 * allows assignments to be used as rvalues, we need to re-extract
779 * the channel from assignment_temp when returning the rvalue.
780 */
781 extract_channel = lhs_expr->operands[1];
782 rhs = new(ctx) ir_expression(ir_triop_vector_insert,
783 lhs_expr->operands[0]->type,
784 lhs_expr->operands[0],
785 new_rhs,
786 extract_channel);
787 lhs = lhs_expr->operands[0]->clone(ctx, NULL);
788 }
789 }
790 }
791
792 ir_variable *lhs_var = lhs->variable_referenced();
793 if (lhs_var)
794 lhs_var->data.assigned = true;
795
796 if (!error_emitted) {
797 if (non_lvalue_description != NULL) {
798 _mesa_glsl_error(&lhs_loc, state,
799 "assignment to %s",
800 non_lvalue_description);
801 error_emitted = true;
802 } else if (lhs_var != NULL && lhs_var->data.read_only) {
803 _mesa_glsl_error(&lhs_loc, state,
804 "assignment to read-only variable '%s'",
805 lhs_var->name);
806 error_emitted = true;
807 } else if (lhs->type->is_array() &&
808 !state->check_version(120, 300, &lhs_loc,
809 "whole array assignment forbidden")) {
810 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
811 *
812 * "Other binary or unary expressions, non-dereferenced
813 * arrays, function names, swizzles with repeated fields,
814 * and constants cannot be l-values."
815 *
816 * The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.
817 */
818 error_emitted = true;
819 } else if (!lhs->is_lvalue()) {
820 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
821 error_emitted = true;
822 }
823 }
824
825 ir_rvalue *new_rhs =
826 validate_assignment(state, lhs_loc, lhs->type, rhs, is_initializer);
827 if (new_rhs != NULL) {
828 rhs = new_rhs;
829
830 /* If the LHS array was not declared with a size, it takes it size from
831 * the RHS. If the LHS is an l-value and a whole array, it must be a
832 * dereference of a variable. Any other case would require that the LHS
833 * is either not an l-value or not a whole array.
834 */
835 if (lhs->type->is_unsized_array()) {
836 ir_dereference *const d = lhs->as_dereference();
837
838 assert(d != NULL);
839
840 ir_variable *const var = d->variable_referenced();
841
842 assert(var != NULL);
843
844 if (var->data.max_array_access >= unsigned(rhs->type->array_size())) {
845 /* FINISHME: This should actually log the location of the RHS. */
846 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
847 "previous access",
848 var->data.max_array_access);
849 }
850
851 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
852 rhs->type->array_size());
853 d->type = var->type;
854 }
855 if (lhs->type->is_array()) {
856 mark_whole_array_access(rhs);
857 mark_whole_array_access(lhs);
858 }
859 }
860
861 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
862 * but not post_inc) need the converted assigned value as an rvalue
863 * to handle things like:
864 *
865 * i = j += 1;
866 */
867 if (needs_rvalue) {
868 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
869 ir_var_temporary);
870 instructions->push_tail(var);
871 instructions->push_tail(assign(var, rhs));
872
873 if (!error_emitted) {
874 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
875 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));
876 }
877 ir_rvalue *rvalue = new(ctx) ir_dereference_variable(var);
878
879 if (extract_channel) {
880 rvalue = new(ctx) ir_expression(ir_binop_vector_extract,
881 rvalue,
882 extract_channel->clone(ctx, NULL));
883 }
884
885 *out_rvalue = rvalue;
886 } else {
887 if (!error_emitted)
888 instructions->push_tail(new(ctx) ir_assignment(lhs, rhs));
889 *out_rvalue = NULL;
890 }
891
892 return error_emitted;
893 }
894
895 static ir_rvalue *
896 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
897 {
898 void *ctx = ralloc_parent(lvalue);
899 ir_variable *var;
900
901 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
902 ir_var_temporary);
903 instructions->push_tail(var);
904 var->data.mode = ir_var_auto;
905
906 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
907 lvalue));
908
909 return new(ctx) ir_dereference_variable(var);
910 }
911
912
913 ir_rvalue *
914 ast_node::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
915 {
916 (void) instructions;
917 (void) state;
918
919 return NULL;
920 }
921
922 void
923 ast_function_expression::hir_no_rvalue(exec_list *instructions,
924 struct _mesa_glsl_parse_state *state)
925 {
926 (void)hir(instructions, state);
927 }
928
929 void
930 ast_aggregate_initializer::hir_no_rvalue(exec_list *instructions,
931 struct _mesa_glsl_parse_state *state)
932 {
933 (void)hir(instructions, state);
934 }
935
936 static ir_rvalue *
937 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
938 {
939 int join_op;
940 ir_rvalue *cmp = NULL;
941
942 if (operation == ir_binop_all_equal)
943 join_op = ir_binop_logic_and;
944 else
945 join_op = ir_binop_logic_or;
946
947 switch (op0->type->base_type) {
948 case GLSL_TYPE_FLOAT:
949 case GLSL_TYPE_UINT:
950 case GLSL_TYPE_INT:
951 case GLSL_TYPE_BOOL:
952 return new(mem_ctx) ir_expression(operation, op0, op1);
953
954 case GLSL_TYPE_ARRAY: {
955 for (unsigned int i = 0; i < op0->type->length; i++) {
956 ir_rvalue *e0, *e1, *result;
957
958 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
959 new(mem_ctx) ir_constant(i));
960 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
961 new(mem_ctx) ir_constant(i));
962 result = do_comparison(mem_ctx, operation, e0, e1);
963
964 if (cmp) {
965 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
966 } else {
967 cmp = result;
968 }
969 }
970
971 mark_whole_array_access(op0);
972 mark_whole_array_access(op1);
973 break;
974 }
975
976 case GLSL_TYPE_STRUCT: {
977 for (unsigned int i = 0; i < op0->type->length; i++) {
978 ir_rvalue *e0, *e1, *result;
979 const char *field_name = op0->type->fields.structure[i].name;
980
981 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
982 field_name);
983 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
984 field_name);
985 result = do_comparison(mem_ctx, operation, e0, e1);
986
987 if (cmp) {
988 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
989 } else {
990 cmp = result;
991 }
992 }
993 break;
994 }
995
996 case GLSL_TYPE_ERROR:
997 case GLSL_TYPE_VOID:
998 case GLSL_TYPE_SAMPLER:
999 case GLSL_TYPE_IMAGE:
1000 case GLSL_TYPE_INTERFACE:
1001 case GLSL_TYPE_ATOMIC_UINT:
1002 /* I assume a comparison of a struct containing a sampler just
1003 * ignores the sampler present in the type.
1004 */
1005 break;
1006 }
1007
1008 if (cmp == NULL)
1009 cmp = new(mem_ctx) ir_constant(true);
1010
1011 return cmp;
1012 }
1013
1014 /* For logical operations, we want to ensure that the operands are
1015 * scalar booleans. If it isn't, emit an error and return a constant
1016 * boolean to avoid triggering cascading error messages.
1017 */
1018 ir_rvalue *
1019 get_scalar_boolean_operand(exec_list *instructions,
1020 struct _mesa_glsl_parse_state *state,
1021 ast_expression *parent_expr,
1022 int operand,
1023 const char *operand_name,
1024 bool *error_emitted)
1025 {
1026 ast_expression *expr = parent_expr->subexpressions[operand];
1027 void *ctx = state;
1028 ir_rvalue *val = expr->hir(instructions, state);
1029
1030 if (val->type->is_boolean() && val->type->is_scalar())
1031 return val;
1032
1033 if (!*error_emitted) {
1034 YYLTYPE loc = expr->get_location();
1035 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
1036 operand_name,
1037 parent_expr->operator_string(parent_expr->oper));
1038 *error_emitted = true;
1039 }
1040
1041 return new(ctx) ir_constant(true);
1042 }
1043
1044 /**
1045 * If name refers to a builtin array whose maximum allowed size is less than
1046 * size, report an error and return true. Otherwise return false.
1047 */
1048 void
1049 check_builtin_array_max_size(const char *name, unsigned size,
1050 YYLTYPE loc, struct _mesa_glsl_parse_state *state)
1051 {
1052 if ((strcmp("gl_TexCoord", name) == 0)
1053 && (size > state->Const.MaxTextureCoords)) {
1054 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
1055 *
1056 * "The size [of gl_TexCoord] can be at most
1057 * gl_MaxTextureCoords."
1058 */
1059 _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
1060 "be larger than gl_MaxTextureCoords (%u)",
1061 state->Const.MaxTextureCoords);
1062 } else if (strcmp("gl_ClipDistance", name) == 0
1063 && size > state->Const.MaxClipPlanes) {
1064 /* From section 7.1 (Vertex Shader Special Variables) of the
1065 * GLSL 1.30 spec:
1066 *
1067 * "The gl_ClipDistance array is predeclared as unsized and
1068 * must be sized by the shader either redeclaring it with a
1069 * size or indexing it only with integral constant
1070 * expressions. ... The size can be at most
1071 * gl_MaxClipDistances."
1072 */
1073 _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
1074 "be larger than gl_MaxClipDistances (%u)",
1075 state->Const.MaxClipPlanes);
1076 }
1077 }
1078
1079 /**
1080 * Create the constant 1, of a which is appropriate for incrementing and
1081 * decrementing values of the given GLSL type. For example, if type is vec4,
1082 * this creates a constant value of 1.0 having type float.
1083 *
1084 * If the given type is invalid for increment and decrement operators, return
1085 * a floating point 1--the error will be detected later.
1086 */
1087 static ir_rvalue *
1088 constant_one_for_inc_dec(void *ctx, const glsl_type *type)
1089 {
1090 switch (type->base_type) {
1091 case GLSL_TYPE_UINT:
1092 return new(ctx) ir_constant((unsigned) 1);
1093 case GLSL_TYPE_INT:
1094 return new(ctx) ir_constant(1);
1095 default:
1096 case GLSL_TYPE_FLOAT:
1097 return new(ctx) ir_constant(1.0f);
1098 }
1099 }
1100
1101 ir_rvalue *
1102 ast_expression::hir(exec_list *instructions,
1103 struct _mesa_glsl_parse_state *state)
1104 {
1105 return do_hir(instructions, state, true);
1106 }
1107
1108 void
1109 ast_expression::hir_no_rvalue(exec_list *instructions,
1110 struct _mesa_glsl_parse_state *state)
1111 {
1112 do_hir(instructions, state, false);
1113 }
1114
1115 ir_rvalue *
1116 ast_expression::do_hir(exec_list *instructions,
1117 struct _mesa_glsl_parse_state *state,
1118 bool needs_rvalue)
1119 {
1120 void *ctx = state;
1121 static const int operations[AST_NUM_OPERATORS] = {
1122 -1, /* ast_assign doesn't convert to ir_expression. */
1123 -1, /* ast_plus doesn't convert to ir_expression. */
1124 ir_unop_neg,
1125 ir_binop_add,
1126 ir_binop_sub,
1127 ir_binop_mul,
1128 ir_binop_div,
1129 ir_binop_mod,
1130 ir_binop_lshift,
1131 ir_binop_rshift,
1132 ir_binop_less,
1133 ir_binop_greater,
1134 ir_binop_lequal,
1135 ir_binop_gequal,
1136 ir_binop_all_equal,
1137 ir_binop_any_nequal,
1138 ir_binop_bit_and,
1139 ir_binop_bit_xor,
1140 ir_binop_bit_or,
1141 ir_unop_bit_not,
1142 ir_binop_logic_and,
1143 ir_binop_logic_xor,
1144 ir_binop_logic_or,
1145 ir_unop_logic_not,
1146
1147 /* Note: The following block of expression types actually convert
1148 * to multiple IR instructions.
1149 */
1150 ir_binop_mul, /* ast_mul_assign */
1151 ir_binop_div, /* ast_div_assign */
1152 ir_binop_mod, /* ast_mod_assign */
1153 ir_binop_add, /* ast_add_assign */
1154 ir_binop_sub, /* ast_sub_assign */
1155 ir_binop_lshift, /* ast_ls_assign */
1156 ir_binop_rshift, /* ast_rs_assign */
1157 ir_binop_bit_and, /* ast_and_assign */
1158 ir_binop_bit_xor, /* ast_xor_assign */
1159 ir_binop_bit_or, /* ast_or_assign */
1160
1161 -1, /* ast_conditional doesn't convert to ir_expression. */
1162 ir_binop_add, /* ast_pre_inc. */
1163 ir_binop_sub, /* ast_pre_dec. */
1164 ir_binop_add, /* ast_post_inc. */
1165 ir_binop_sub, /* ast_post_dec. */
1166 -1, /* ast_field_selection doesn't conv to ir_expression. */
1167 -1, /* ast_array_index doesn't convert to ir_expression. */
1168 -1, /* ast_function_call doesn't conv to ir_expression. */
1169 -1, /* ast_identifier doesn't convert to ir_expression. */
1170 -1, /* ast_int_constant doesn't convert to ir_expression. */
1171 -1, /* ast_uint_constant doesn't conv to ir_expression. */
1172 -1, /* ast_float_constant doesn't conv to ir_expression. */
1173 -1, /* ast_bool_constant doesn't conv to ir_expression. */
1174 -1, /* ast_sequence doesn't convert to ir_expression. */
1175 };
1176 ir_rvalue *result = NULL;
1177 ir_rvalue *op[3];
1178 const struct glsl_type *type; /* a temporary variable for switch cases */
1179 bool error_emitted = false;
1180 YYLTYPE loc;
1181
1182 loc = this->get_location();
1183
1184 switch (this->oper) {
1185 case ast_aggregate:
1186 assert(!"ast_aggregate: Should never get here.");
1187 break;
1188
1189 case ast_assign: {
1190 op[0] = this->subexpressions[0]->hir(instructions, state);
1191 op[1] = this->subexpressions[1]->hir(instructions, state);
1192
1193 error_emitted =
1194 do_assignment(instructions, state,
1195 this->subexpressions[0]->non_lvalue_description,
1196 op[0], op[1], &result, needs_rvalue, false,
1197 this->subexpressions[0]->get_location());
1198 break;
1199 }
1200
1201 case ast_plus:
1202 op[0] = this->subexpressions[0]->hir(instructions, state);
1203
1204 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1205
1206 error_emitted = type->is_error();
1207
1208 result = op[0];
1209 break;
1210
1211 case ast_neg:
1212 op[0] = this->subexpressions[0]->hir(instructions, state);
1213
1214 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1215
1216 error_emitted = type->is_error();
1217
1218 result = new(ctx) ir_expression(operations[this->oper], type,
1219 op[0], NULL);
1220 break;
1221
1222 case ast_add:
1223 case ast_sub:
1224 case ast_mul:
1225 case ast_div:
1226 op[0] = this->subexpressions[0]->hir(instructions, state);
1227 op[1] = this->subexpressions[1]->hir(instructions, state);
1228
1229 type = arithmetic_result_type(op[0], op[1],
1230 (this->oper == ast_mul),
1231 state, & loc);
1232 error_emitted = type->is_error();
1233
1234 result = new(ctx) ir_expression(operations[this->oper], type,
1235 op[0], op[1]);
1236 break;
1237
1238 case ast_mod:
1239 op[0] = this->subexpressions[0]->hir(instructions, state);
1240 op[1] = this->subexpressions[1]->hir(instructions, state);
1241
1242 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1243
1244 assert(operations[this->oper] == ir_binop_mod);
1245
1246 result = new(ctx) ir_expression(operations[this->oper], type,
1247 op[0], op[1]);
1248 error_emitted = type->is_error();
1249 break;
1250
1251 case ast_lshift:
1252 case ast_rshift:
1253 if (!state->check_bitwise_operations_allowed(&loc)) {
1254 error_emitted = true;
1255 }
1256
1257 op[0] = this->subexpressions[0]->hir(instructions, state);
1258 op[1] = this->subexpressions[1]->hir(instructions, state);
1259 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1260 &loc);
1261 result = new(ctx) ir_expression(operations[this->oper], type,
1262 op[0], op[1]);
1263 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1264 break;
1265
1266 case ast_less:
1267 case ast_greater:
1268 case ast_lequal:
1269 case ast_gequal:
1270 op[0] = this->subexpressions[0]->hir(instructions, state);
1271 op[1] = this->subexpressions[1]->hir(instructions, state);
1272
1273 type = relational_result_type(op[0], op[1], state, & loc);
1274
1275 /* The relational operators must either generate an error or result
1276 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1277 */
1278 assert(type->is_error()
1279 || ((type->base_type == GLSL_TYPE_BOOL)
1280 && type->is_scalar()));
1281
1282 result = new(ctx) ir_expression(operations[this->oper], type,
1283 op[0], op[1]);
1284 error_emitted = type->is_error();
1285 break;
1286
1287 case ast_nequal:
1288 case ast_equal:
1289 op[0] = this->subexpressions[0]->hir(instructions, state);
1290 op[1] = this->subexpressions[1]->hir(instructions, state);
1291
1292 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1293 *
1294 * "The equality operators equal (==), and not equal (!=)
1295 * operate on all types. They result in a scalar Boolean. If
1296 * the operand types do not match, then there must be a
1297 * conversion from Section 4.1.10 "Implicit Conversions"
1298 * applied to one operand that can make them match, in which
1299 * case this conversion is done."
1300 */
1301 if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1302 && !apply_implicit_conversion(op[1]->type, op[0], state))
1303 || (op[0]->type != op[1]->type)) {
1304 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1305 "type", (this->oper == ast_equal) ? "==" : "!=");
1306 error_emitted = true;
1307 } else if ((op[0]->type->is_array() || op[1]->type->is_array()) &&
1308 !state->check_version(120, 300, &loc,
1309 "array comparisons forbidden")) {
1310 error_emitted = true;
1311 } else if ((op[0]->type->contains_opaque() ||
1312 op[1]->type->contains_opaque())) {
1313 _mesa_glsl_error(&loc, state, "opaque type comparisons forbidden");
1314 error_emitted = true;
1315 }
1316
1317 if (error_emitted) {
1318 result = new(ctx) ir_constant(false);
1319 } else {
1320 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1321 assert(result->type == glsl_type::bool_type);
1322 }
1323 break;
1324
1325 case ast_bit_and:
1326 case ast_bit_xor:
1327 case ast_bit_or:
1328 op[0] = this->subexpressions[0]->hir(instructions, state);
1329 op[1] = this->subexpressions[1]->hir(instructions, state);
1330 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1331 state, &loc);
1332 result = new(ctx) ir_expression(operations[this->oper], type,
1333 op[0], op[1]);
1334 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1335 break;
1336
1337 case ast_bit_not:
1338 op[0] = this->subexpressions[0]->hir(instructions, state);
1339
1340 if (!state->check_bitwise_operations_allowed(&loc)) {
1341 error_emitted = true;
1342 }
1343
1344 if (!op[0]->type->is_integer()) {
1345 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1346 error_emitted = true;
1347 }
1348
1349 type = error_emitted ? glsl_type::error_type : op[0]->type;
1350 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1351 break;
1352
1353 case ast_logic_and: {
1354 exec_list rhs_instructions;
1355 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1356 "LHS", &error_emitted);
1357 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1358 "RHS", &error_emitted);
1359
1360 if (rhs_instructions.is_empty()) {
1361 result = new(ctx) ir_expression(ir_binop_logic_and, op[0], op[1]);
1362 type = result->type;
1363 } else {
1364 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1365 "and_tmp",
1366 ir_var_temporary);
1367 instructions->push_tail(tmp);
1368
1369 ir_if *const stmt = new(ctx) ir_if(op[0]);
1370 instructions->push_tail(stmt);
1371
1372 stmt->then_instructions.append_list(&rhs_instructions);
1373 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1374 ir_assignment *const then_assign =
1375 new(ctx) ir_assignment(then_deref, op[1]);
1376 stmt->then_instructions.push_tail(then_assign);
1377
1378 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1379 ir_assignment *const else_assign =
1380 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false));
1381 stmt->else_instructions.push_tail(else_assign);
1382
1383 result = new(ctx) ir_dereference_variable(tmp);
1384 type = tmp->type;
1385 }
1386 break;
1387 }
1388
1389 case ast_logic_or: {
1390 exec_list rhs_instructions;
1391 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1392 "LHS", &error_emitted);
1393 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1394 "RHS", &error_emitted);
1395
1396 if (rhs_instructions.is_empty()) {
1397 result = new(ctx) ir_expression(ir_binop_logic_or, op[0], op[1]);
1398 type = result->type;
1399 } else {
1400 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1401 "or_tmp",
1402 ir_var_temporary);
1403 instructions->push_tail(tmp);
1404
1405 ir_if *const stmt = new(ctx) ir_if(op[0]);
1406 instructions->push_tail(stmt);
1407
1408 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1409 ir_assignment *const then_assign =
1410 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true));
1411 stmt->then_instructions.push_tail(then_assign);
1412
1413 stmt->else_instructions.append_list(&rhs_instructions);
1414 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1415 ir_assignment *const else_assign =
1416 new(ctx) ir_assignment(else_deref, op[1]);
1417 stmt->else_instructions.push_tail(else_assign);
1418
1419 result = new(ctx) ir_dereference_variable(tmp);
1420 type = tmp->type;
1421 }
1422 break;
1423 }
1424
1425 case ast_logic_xor:
1426 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1427 *
1428 * "The logical binary operators and (&&), or ( | | ), and
1429 * exclusive or (^^). They operate only on two Boolean
1430 * expressions and result in a Boolean expression."
1431 */
1432 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1433 &error_emitted);
1434 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1435 &error_emitted);
1436
1437 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1438 op[0], op[1]);
1439 break;
1440
1441 case ast_logic_not:
1442 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1443 "operand", &error_emitted);
1444
1445 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1446 op[0], NULL);
1447 break;
1448
1449 case ast_mul_assign:
1450 case ast_div_assign:
1451 case ast_add_assign:
1452 case ast_sub_assign: {
1453 op[0] = this->subexpressions[0]->hir(instructions, state);
1454 op[1] = this->subexpressions[1]->hir(instructions, state);
1455
1456 type = arithmetic_result_type(op[0], op[1],
1457 (this->oper == ast_mul_assign),
1458 state, & loc);
1459
1460 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1461 op[0], op[1]);
1462
1463 error_emitted =
1464 do_assignment(instructions, state,
1465 this->subexpressions[0]->non_lvalue_description,
1466 op[0]->clone(ctx, NULL), temp_rhs,
1467 &result, needs_rvalue, false,
1468 this->subexpressions[0]->get_location());
1469
1470 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1471 * explicitly test for this because none of the binary expression
1472 * operators allow array operands either.
1473 */
1474
1475 break;
1476 }
1477
1478 case ast_mod_assign: {
1479 op[0] = this->subexpressions[0]->hir(instructions, state);
1480 op[1] = this->subexpressions[1]->hir(instructions, state);
1481
1482 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1483
1484 assert(operations[this->oper] == ir_binop_mod);
1485
1486 ir_rvalue *temp_rhs;
1487 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1488 op[0], op[1]);
1489
1490 error_emitted =
1491 do_assignment(instructions, state,
1492 this->subexpressions[0]->non_lvalue_description,
1493 op[0]->clone(ctx, NULL), temp_rhs,
1494 &result, needs_rvalue, false,
1495 this->subexpressions[0]->get_location());
1496 break;
1497 }
1498
1499 case ast_ls_assign:
1500 case ast_rs_assign: {
1501 op[0] = this->subexpressions[0]->hir(instructions, state);
1502 op[1] = this->subexpressions[1]->hir(instructions, state);
1503 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1504 &loc);
1505 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1506 type, op[0], op[1]);
1507 error_emitted =
1508 do_assignment(instructions, state,
1509 this->subexpressions[0]->non_lvalue_description,
1510 op[0]->clone(ctx, NULL), temp_rhs,
1511 &result, needs_rvalue, false,
1512 this->subexpressions[0]->get_location());
1513 break;
1514 }
1515
1516 case ast_and_assign:
1517 case ast_xor_assign:
1518 case ast_or_assign: {
1519 op[0] = this->subexpressions[0]->hir(instructions, state);
1520 op[1] = this->subexpressions[1]->hir(instructions, state);
1521 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1522 state, &loc);
1523 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1524 type, op[0], op[1]);
1525 error_emitted =
1526 do_assignment(instructions, state,
1527 this->subexpressions[0]->non_lvalue_description,
1528 op[0]->clone(ctx, NULL), temp_rhs,
1529 &result, needs_rvalue, false,
1530 this->subexpressions[0]->get_location());
1531 break;
1532 }
1533
1534 case ast_conditional: {
1535 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1536 *
1537 * "The ternary selection operator (?:). It operates on three
1538 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1539 * first expression, which must result in a scalar Boolean."
1540 */
1541 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1542 "condition", &error_emitted);
1543
1544 /* The :? operator is implemented by generating an anonymous temporary
1545 * followed by an if-statement. The last instruction in each branch of
1546 * the if-statement assigns a value to the anonymous temporary. This
1547 * temporary is the r-value of the expression.
1548 */
1549 exec_list then_instructions;
1550 exec_list else_instructions;
1551
1552 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1553 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1554
1555 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1556 *
1557 * "The second and third expressions can be any type, as
1558 * long their types match, or there is a conversion in
1559 * Section 4.1.10 "Implicit Conversions" that can be applied
1560 * to one of the expressions to make their types match. This
1561 * resulting matching type is the type of the entire
1562 * expression."
1563 */
1564 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1565 && !apply_implicit_conversion(op[2]->type, op[1], state))
1566 || (op[1]->type != op[2]->type)) {
1567 YYLTYPE loc = this->subexpressions[1]->get_location();
1568
1569 _mesa_glsl_error(& loc, state, "second and third operands of ?: "
1570 "operator must have matching types");
1571 error_emitted = true;
1572 type = glsl_type::error_type;
1573 } else {
1574 type = op[1]->type;
1575 }
1576
1577 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1578 *
1579 * "The second and third expressions must be the same type, but can
1580 * be of any type other than an array."
1581 */
1582 if (type->is_array() &&
1583 !state->check_version(120, 300, &loc,
1584 "second and third operands of ?: operator "
1585 "cannot be arrays")) {
1586 error_emitted = true;
1587 }
1588
1589 ir_constant *cond_val = op[0]->constant_expression_value();
1590 ir_constant *then_val = op[1]->constant_expression_value();
1591 ir_constant *else_val = op[2]->constant_expression_value();
1592
1593 if (then_instructions.is_empty()
1594 && else_instructions.is_empty()
1595 && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1596 result = (cond_val->value.b[0]) ? then_val : else_val;
1597 } else {
1598 ir_variable *const tmp =
1599 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1600 instructions->push_tail(tmp);
1601
1602 ir_if *const stmt = new(ctx) ir_if(op[0]);
1603 instructions->push_tail(stmt);
1604
1605 then_instructions.move_nodes_to(& stmt->then_instructions);
1606 ir_dereference *const then_deref =
1607 new(ctx) ir_dereference_variable(tmp);
1608 ir_assignment *const then_assign =
1609 new(ctx) ir_assignment(then_deref, op[1]);
1610 stmt->then_instructions.push_tail(then_assign);
1611
1612 else_instructions.move_nodes_to(& stmt->else_instructions);
1613 ir_dereference *const else_deref =
1614 new(ctx) ir_dereference_variable(tmp);
1615 ir_assignment *const else_assign =
1616 new(ctx) ir_assignment(else_deref, op[2]);
1617 stmt->else_instructions.push_tail(else_assign);
1618
1619 result = new(ctx) ir_dereference_variable(tmp);
1620 }
1621 break;
1622 }
1623
1624 case ast_pre_inc:
1625 case ast_pre_dec: {
1626 this->non_lvalue_description = (this->oper == ast_pre_inc)
1627 ? "pre-increment operation" : "pre-decrement operation";
1628
1629 op[0] = this->subexpressions[0]->hir(instructions, state);
1630 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1631
1632 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1633
1634 ir_rvalue *temp_rhs;
1635 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1636 op[0], op[1]);
1637
1638 error_emitted =
1639 do_assignment(instructions, state,
1640 this->subexpressions[0]->non_lvalue_description,
1641 op[0]->clone(ctx, NULL), temp_rhs,
1642 &result, needs_rvalue, false,
1643 this->subexpressions[0]->get_location());
1644 break;
1645 }
1646
1647 case ast_post_inc:
1648 case ast_post_dec: {
1649 this->non_lvalue_description = (this->oper == ast_post_inc)
1650 ? "post-increment operation" : "post-decrement operation";
1651 op[0] = this->subexpressions[0]->hir(instructions, state);
1652 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1653
1654 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1655
1656 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1657
1658 ir_rvalue *temp_rhs;
1659 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1660 op[0], op[1]);
1661
1662 /* Get a temporary of a copy of the lvalue before it's modified.
1663 * This may get thrown away later.
1664 */
1665 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1666
1667 ir_rvalue *junk_rvalue;
1668 error_emitted =
1669 do_assignment(instructions, state,
1670 this->subexpressions[0]->non_lvalue_description,
1671 op[0]->clone(ctx, NULL), temp_rhs,
1672 &junk_rvalue, false, false,
1673 this->subexpressions[0]->get_location());
1674
1675 break;
1676 }
1677
1678 case ast_field_selection:
1679 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1680 break;
1681
1682 case ast_array_index: {
1683 YYLTYPE index_loc = subexpressions[1]->get_location();
1684
1685 op[0] = subexpressions[0]->hir(instructions, state);
1686 op[1] = subexpressions[1]->hir(instructions, state);
1687
1688 result = _mesa_ast_array_index_to_hir(ctx, state, op[0], op[1],
1689 loc, index_loc);
1690
1691 if (result->type->is_error())
1692 error_emitted = true;
1693
1694 break;
1695 }
1696
1697 case ast_function_call:
1698 /* Should *NEVER* get here. ast_function_call should always be handled
1699 * by ast_function_expression::hir.
1700 */
1701 assert(0);
1702 break;
1703
1704 case ast_identifier: {
1705 /* ast_identifier can appear several places in a full abstract syntax
1706 * tree. This particular use must be at location specified in the grammar
1707 * as 'variable_identifier'.
1708 */
1709 ir_variable *var =
1710 state->symbols->get_variable(this->primary_expression.identifier);
1711
1712 if (var != NULL) {
1713 var->data.used = true;
1714 result = new(ctx) ir_dereference_variable(var);
1715 } else {
1716 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1717 this->primary_expression.identifier);
1718
1719 result = ir_rvalue::error_value(ctx);
1720 error_emitted = true;
1721 }
1722 break;
1723 }
1724
1725 case ast_int_constant:
1726 result = new(ctx) ir_constant(this->primary_expression.int_constant);
1727 break;
1728
1729 case ast_uint_constant:
1730 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1731 break;
1732
1733 case ast_float_constant:
1734 result = new(ctx) ir_constant(this->primary_expression.float_constant);
1735 break;
1736
1737 case ast_bool_constant:
1738 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1739 break;
1740
1741 case ast_sequence: {
1742 /* It should not be possible to generate a sequence in the AST without
1743 * any expressions in it.
1744 */
1745 assert(!this->expressions.is_empty());
1746
1747 /* The r-value of a sequence is the last expression in the sequence. If
1748 * the other expressions in the sequence do not have side-effects (and
1749 * therefore add instructions to the instruction list), they get dropped
1750 * on the floor.
1751 */
1752 exec_node *previous_tail_pred = NULL;
1753 YYLTYPE previous_operand_loc = loc;
1754
1755 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1756 /* If one of the operands of comma operator does not generate any
1757 * code, we want to emit a warning. At each pass through the loop
1758 * previous_tail_pred will point to the last instruction in the
1759 * stream *before* processing the previous operand. Naturally,
1760 * instructions->tail_pred will point to the last instruction in the
1761 * stream *after* processing the previous operand. If the two
1762 * pointers match, then the previous operand had no effect.
1763 *
1764 * The warning behavior here differs slightly from GCC. GCC will
1765 * only emit a warning if none of the left-hand operands have an
1766 * effect. However, it will emit a warning for each. I believe that
1767 * there are some cases in C (especially with GCC extensions) where
1768 * it is useful to have an intermediate step in a sequence have no
1769 * effect, but I don't think these cases exist in GLSL. Either way,
1770 * it would be a giant hassle to replicate that behavior.
1771 */
1772 if (previous_tail_pred == instructions->tail_pred) {
1773 _mesa_glsl_warning(&previous_operand_loc, state,
1774 "left-hand operand of comma expression has "
1775 "no effect");
1776 }
1777
1778 /* tail_pred is directly accessed instead of using the get_tail()
1779 * method for performance reasons. get_tail() has extra code to
1780 * return NULL when the list is empty. We don't care about that
1781 * here, so using tail_pred directly is fine.
1782 */
1783 previous_tail_pred = instructions->tail_pred;
1784 previous_operand_loc = ast->get_location();
1785
1786 result = ast->hir(instructions, state);
1787 }
1788
1789 /* Any errors should have already been emitted in the loop above.
1790 */
1791 error_emitted = true;
1792 break;
1793 }
1794 }
1795 type = NULL; /* use result->type, not type. */
1796 assert(result != NULL || !needs_rvalue);
1797
1798 if (result && result->type->is_error() && !error_emitted)
1799 _mesa_glsl_error(& loc, state, "type mismatch");
1800
1801 return result;
1802 }
1803
1804
1805 ir_rvalue *
1806 ast_expression_statement::hir(exec_list *instructions,
1807 struct _mesa_glsl_parse_state *state)
1808 {
1809 /* It is possible to have expression statements that don't have an
1810 * expression. This is the solitary semicolon:
1811 *
1812 * for (i = 0; i < 5; i++)
1813 * ;
1814 *
1815 * In this case the expression will be NULL. Test for NULL and don't do
1816 * anything in that case.
1817 */
1818 if (expression != NULL)
1819 expression->hir_no_rvalue(instructions, state);
1820
1821 /* Statements do not have r-values.
1822 */
1823 return NULL;
1824 }
1825
1826
1827 ir_rvalue *
1828 ast_compound_statement::hir(exec_list *instructions,
1829 struct _mesa_glsl_parse_state *state)
1830 {
1831 if (new_scope)
1832 state->symbols->push_scope();
1833
1834 foreach_list_typed (ast_node, ast, link, &this->statements)
1835 ast->hir(instructions, state);
1836
1837 if (new_scope)
1838 state->symbols->pop_scope();
1839
1840 /* Compound statements do not have r-values.
1841 */
1842 return NULL;
1843 }
1844
1845 /**
1846 * Evaluate the given exec_node (which should be an ast_node representing
1847 * a single array dimension) and return its integer value.
1848 */
1849 static unsigned
1850 process_array_size(exec_node *node,
1851 struct _mesa_glsl_parse_state *state)
1852 {
1853 exec_list dummy_instructions;
1854
1855 ast_node *array_size = exec_node_data(ast_node, node, link);
1856 ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1857 YYLTYPE loc = array_size->get_location();
1858
1859 if (ir == NULL) {
1860 _mesa_glsl_error(& loc, state,
1861 "array size could not be resolved");
1862 return 0;
1863 }
1864
1865 if (!ir->type->is_integer()) {
1866 _mesa_glsl_error(& loc, state,
1867 "array size must be integer type");
1868 return 0;
1869 }
1870
1871 if (!ir->type->is_scalar()) {
1872 _mesa_glsl_error(& loc, state,
1873 "array size must be scalar type");
1874 return 0;
1875 }
1876
1877 ir_constant *const size = ir->constant_expression_value();
1878 if (size == NULL) {
1879 _mesa_glsl_error(& loc, state, "array size must be a "
1880 "constant valued expression");
1881 return 0;
1882 }
1883
1884 if (size->value.i[0] <= 0) {
1885 _mesa_glsl_error(& loc, state, "array size must be > 0");
1886 return 0;
1887 }
1888
1889 assert(size->type == ir->type);
1890
1891 /* If the array size is const (and we've verified that
1892 * it is) then no instructions should have been emitted
1893 * when we converted it to HIR. If they were emitted,
1894 * then either the array size isn't const after all, or
1895 * we are emitting unnecessary instructions.
1896 */
1897 assert(dummy_instructions.is_empty());
1898
1899 return size->value.u[0];
1900 }
1901
1902 static const glsl_type *
1903 process_array_type(YYLTYPE *loc, const glsl_type *base,
1904 ast_array_specifier *array_specifier,
1905 struct _mesa_glsl_parse_state *state)
1906 {
1907 const glsl_type *array_type = base;
1908
1909 if (array_specifier != NULL) {
1910 if (base->is_array()) {
1911
1912 /* From page 19 (page 25) of the GLSL 1.20 spec:
1913 *
1914 * "Only one-dimensional arrays may be declared."
1915 */
1916 if (!state->ARB_arrays_of_arrays_enable) {
1917 _mesa_glsl_error(loc, state,
1918 "invalid array of `%s'"
1919 "GL_ARB_arrays_of_arrays "
1920 "required for defining arrays of arrays",
1921 base->name);
1922 return glsl_type::error_type;
1923 }
1924
1925 if (base->length == 0) {
1926 _mesa_glsl_error(loc, state,
1927 "only the outermost array dimension can "
1928 "be unsized",
1929 base->name);
1930 return glsl_type::error_type;
1931 }
1932 }
1933
1934 for (exec_node *node = array_specifier->array_dimensions.tail_pred;
1935 !node->is_head_sentinel(); node = node->prev) {
1936 unsigned array_size = process_array_size(node, state);
1937 array_type = glsl_type::get_array_instance(array_type, array_size);
1938 }
1939
1940 if (array_specifier->is_unsized_array)
1941 array_type = glsl_type::get_array_instance(array_type, 0);
1942 }
1943
1944 return array_type;
1945 }
1946
1947
1948 const glsl_type *
1949 ast_type_specifier::glsl_type(const char **name,
1950 struct _mesa_glsl_parse_state *state) const
1951 {
1952 const struct glsl_type *type;
1953
1954 type = state->symbols->get_type(this->type_name);
1955 *name = this->type_name;
1956
1957 YYLTYPE loc = this->get_location();
1958 type = process_array_type(&loc, type, this->array_specifier, state);
1959
1960 return type;
1961 }
1962
1963 const glsl_type *
1964 ast_fully_specified_type::glsl_type(const char **name,
1965 struct _mesa_glsl_parse_state *state) const
1966 {
1967 const struct glsl_type *type = this->specifier->glsl_type(name, state);
1968
1969 if (type == NULL)
1970 return NULL;
1971
1972 if (type->base_type == GLSL_TYPE_FLOAT
1973 && state->es_shader
1974 && state->stage == MESA_SHADER_FRAGMENT
1975 && this->qualifier.precision == ast_precision_none
1976 && state->symbols->get_variable("#default precision") == NULL) {
1977 YYLTYPE loc = this->get_location();
1978 _mesa_glsl_error(&loc, state,
1979 "no precision specified this scope for type `%s'",
1980 type->name);
1981 }
1982
1983 return type;
1984 }
1985
1986 /**
1987 * Determine whether a toplevel variable declaration declares a varying. This
1988 * function operates by examining the variable's mode and the shader target,
1989 * so it correctly identifies linkage variables regardless of whether they are
1990 * declared using the deprecated "varying" syntax or the new "in/out" syntax.
1991 *
1992 * Passing a non-toplevel variable declaration (e.g. a function parameter) to
1993 * this function will produce undefined results.
1994 */
1995 static bool
1996 is_varying_var(ir_variable *var, gl_shader_stage target)
1997 {
1998 switch (target) {
1999 case MESA_SHADER_VERTEX:
2000 return var->data.mode == ir_var_shader_out;
2001 case MESA_SHADER_FRAGMENT:
2002 return var->data.mode == ir_var_shader_in;
2003 default:
2004 return var->data.mode == ir_var_shader_out || var->data.mode == ir_var_shader_in;
2005 }
2006 }
2007
2008
2009 /**
2010 * Matrix layout qualifiers are only allowed on certain types
2011 */
2012 static void
2013 validate_matrix_layout_for_type(struct _mesa_glsl_parse_state *state,
2014 YYLTYPE *loc,
2015 const glsl_type *type,
2016 ir_variable *var)
2017 {
2018 if (var && !var->is_in_uniform_block()) {
2019 /* Layout qualifiers may only apply to interface blocks and fields in
2020 * them.
2021 */
2022 _mesa_glsl_error(loc, state,
2023 "uniform block layout qualifiers row_major and "
2024 "column_major may not be applied to variables "
2025 "outside of uniform blocks");
2026 } else if (!type->is_matrix()) {
2027 /* The OpenGL ES 3.0 conformance tests did not originally allow
2028 * matrix layout qualifiers on non-matrices. However, the OpenGL
2029 * 4.4 and OpenGL ES 3.0 (revision TBD) specifications were
2030 * amended to specifically allow these layouts on all types. Emit
2031 * a warning so that people know their code may not be portable.
2032 */
2033 _mesa_glsl_warning(loc, state,
2034 "uniform block layout qualifiers row_major and "
2035 "column_major applied to non-matrix types may "
2036 "be rejected by older compilers");
2037 } else if (type->is_record()) {
2038 /* We allow 'layout(row_major)' on structure types because it's the only
2039 * way to get row-major layouts on matrices contained in structures.
2040 */
2041 _mesa_glsl_warning(loc, state,
2042 "uniform block layout qualifiers row_major and "
2043 "column_major applied to structure types is not "
2044 "strictly conformant and may be rejected by other "
2045 "compilers");
2046 }
2047 }
2048
2049 static bool
2050 validate_binding_qualifier(struct _mesa_glsl_parse_state *state,
2051 YYLTYPE *loc,
2052 ir_variable *var,
2053 const ast_type_qualifier *qual)
2054 {
2055 if (var->data.mode != ir_var_uniform) {
2056 _mesa_glsl_error(loc, state,
2057 "the \"binding\" qualifier only applies to uniforms");
2058 return false;
2059 }
2060
2061 if (qual->binding < 0) {
2062 _mesa_glsl_error(loc, state, "binding values must be >= 0");
2063 return false;
2064 }
2065
2066 const struct gl_context *const ctx = state->ctx;
2067 unsigned elements = var->type->is_array() ? var->type->length : 1;
2068 unsigned max_index = qual->binding + elements - 1;
2069
2070 if (var->type->is_interface()) {
2071 /* UBOs. From page 60 of the GLSL 4.20 specification:
2072 * "If the binding point for any uniform block instance is less than zero,
2073 * or greater than or equal to the implementation-dependent maximum
2074 * number of uniform buffer bindings, a compilation error will occur.
2075 * When the binding identifier is used with a uniform block instanced as
2076 * an array of size N, all elements of the array from binding through
2077 * binding + N – 1 must be within this range."
2078 *
2079 * The implementation-dependent maximum is GL_MAX_UNIFORM_BUFFER_BINDINGS.
2080 */
2081 if (max_index >= ctx->Const.MaxUniformBufferBindings) {
2082 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d UBOs exceeds "
2083 "the maximum number of UBO binding points (%d)",
2084 qual->binding, elements,
2085 ctx->Const.MaxUniformBufferBindings);
2086 return false;
2087 }
2088 } else if (var->type->is_sampler() ||
2089 (var->type->is_array() && var->type->fields.array->is_sampler())) {
2090 /* Samplers. From page 63 of the GLSL 4.20 specification:
2091 * "If the binding is less than zero, or greater than or equal to the
2092 * implementation-dependent maximum supported number of units, a
2093 * compilation error will occur. When the binding identifier is used
2094 * with an array of size N, all elements of the array from binding
2095 * through binding + N - 1 must be within this range."
2096 */
2097 unsigned limit = ctx->Const.Program[state->stage].MaxTextureImageUnits;
2098
2099 if (max_index >= limit) {
2100 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d samplers "
2101 "exceeds the maximum number of texture image units "
2102 "(%d)", qual->binding, elements, limit);
2103
2104 return false;
2105 }
2106 } else if (var->type->contains_atomic()) {
2107 assert(ctx->Const.MaxAtomicBufferBindings <= MAX_COMBINED_ATOMIC_BUFFERS);
2108 if (unsigned(qual->binding) >= ctx->Const.MaxAtomicBufferBindings) {
2109 _mesa_glsl_error(loc, state, "layout(binding = %d) exceeds the "
2110 " maximum number of atomic counter buffer bindings"
2111 "(%d)", qual->binding,
2112 ctx->Const.MaxAtomicBufferBindings);
2113
2114 return false;
2115 }
2116 } else {
2117 _mesa_glsl_error(loc, state,
2118 "the \"binding\" qualifier only applies to uniform "
2119 "blocks, samplers, atomic counters, or arrays thereof");
2120 return false;
2121 }
2122
2123 return true;
2124 }
2125
2126
2127 static glsl_interp_qualifier
2128 interpret_interpolation_qualifier(const struct ast_type_qualifier *qual,
2129 ir_variable_mode mode,
2130 struct _mesa_glsl_parse_state *state,
2131 YYLTYPE *loc)
2132 {
2133 glsl_interp_qualifier interpolation;
2134 if (qual->flags.q.flat)
2135 interpolation = INTERP_QUALIFIER_FLAT;
2136 else if (qual->flags.q.noperspective)
2137 interpolation = INTERP_QUALIFIER_NOPERSPECTIVE;
2138 else if (qual->flags.q.smooth)
2139 interpolation = INTERP_QUALIFIER_SMOOTH;
2140 else
2141 interpolation = INTERP_QUALIFIER_NONE;
2142
2143 if (interpolation != INTERP_QUALIFIER_NONE) {
2144 if (mode != ir_var_shader_in && mode != ir_var_shader_out) {
2145 _mesa_glsl_error(loc, state,
2146 "interpolation qualifier `%s' can only be applied to "
2147 "shader inputs or outputs.",
2148 interpolation_string(interpolation));
2149
2150 }
2151
2152 if ((state->stage == MESA_SHADER_VERTEX && mode == ir_var_shader_in) ||
2153 (state->stage == MESA_SHADER_FRAGMENT && mode == ir_var_shader_out)) {
2154 _mesa_glsl_error(loc, state,
2155 "interpolation qualifier `%s' cannot be applied to "
2156 "vertex shader inputs or fragment shader outputs",
2157 interpolation_string(interpolation));
2158 }
2159 }
2160
2161 return interpolation;
2162 }
2163
2164
2165 static void
2166 validate_explicit_location(const struct ast_type_qualifier *qual,
2167 ir_variable *var,
2168 struct _mesa_glsl_parse_state *state,
2169 YYLTYPE *loc)
2170 {
2171 bool fail = false;
2172
2173 /* Between GL_ARB_explicit_attrib_location an
2174 * GL_ARB_separate_shader_objects, the inputs and outputs of any shader
2175 * stage can be assigned explicit locations. The checking here associates
2176 * the correct extension with the correct stage's input / output:
2177 *
2178 * input output
2179 * ----- ------
2180 * vertex explicit_loc sso
2181 * geometry sso sso
2182 * fragment sso explicit_loc
2183 */
2184 switch (state->stage) {
2185 case MESA_SHADER_VERTEX:
2186 if (var->data.mode == ir_var_shader_in) {
2187 if (!state->check_explicit_attrib_location_allowed(loc, var))
2188 return;
2189
2190 break;
2191 }
2192
2193 if (var->data.mode == ir_var_shader_out) {
2194 if (!state->check_separate_shader_objects_allowed(loc, var))
2195 return;
2196
2197 break;
2198 }
2199
2200 fail = true;
2201 break;
2202
2203 case MESA_SHADER_GEOMETRY:
2204 if (var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) {
2205 if (!state->check_separate_shader_objects_allowed(loc, var))
2206 return;
2207
2208 break;
2209 }
2210
2211 fail = true;
2212 break;
2213
2214 case MESA_SHADER_FRAGMENT:
2215 if (var->data.mode == ir_var_shader_in) {
2216 if (!state->check_separate_shader_objects_allowed(loc, var))
2217 return;
2218
2219 break;
2220 }
2221
2222 if (var->data.mode == ir_var_shader_out) {
2223 if (!state->check_explicit_attrib_location_allowed(loc, var))
2224 return;
2225
2226 break;
2227 }
2228
2229 fail = true;
2230 break;
2231
2232 case MESA_SHADER_COMPUTE:
2233 _mesa_glsl_error(loc, state,
2234 "compute shader variables cannot be given "
2235 "explicit locations");
2236 return;
2237 };
2238
2239 if (fail) {
2240 _mesa_glsl_error(loc, state,
2241 "%s cannot be given an explicit location in %s shader",
2242 mode_string(var),
2243 _mesa_shader_stage_to_string(state->stage));
2244 } else {
2245 var->data.explicit_location = true;
2246
2247 /* This bit of silliness is needed because invalid explicit locations
2248 * are supposed to be flagged during linking. Small negative values
2249 * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
2250 * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
2251 * The linker needs to be able to differentiate these cases. This
2252 * ensures that negative values stay negative.
2253 */
2254 if (qual->location >= 0) {
2255 switch (state->stage) {
2256 case MESA_SHADER_VERTEX:
2257 var->data.location = (var->data.mode == ir_var_shader_in)
2258 ? (qual->location + VERT_ATTRIB_GENERIC0)
2259 : (qual->location + VARYING_SLOT_VAR0);
2260 break;
2261
2262 case MESA_SHADER_GEOMETRY:
2263 var->data.location = qual->location + VARYING_SLOT_VAR0;
2264 break;
2265
2266 case MESA_SHADER_FRAGMENT:
2267 var->data.location = (var->data.mode == ir_var_shader_out)
2268 ? (qual->location + FRAG_RESULT_DATA0)
2269 : (qual->location + VARYING_SLOT_VAR0);
2270 break;
2271 case MESA_SHADER_COMPUTE:
2272 assert(!"Unexpected shader type");
2273 break;
2274 }
2275 } else {
2276 var->data.location = qual->location;
2277 }
2278
2279 if (qual->flags.q.explicit_index) {
2280 /* From the GLSL 4.30 specification, section 4.4.2 (Output
2281 * Layout Qualifiers):
2282 *
2283 * "It is also a compile-time error if a fragment shader
2284 * sets a layout index to less than 0 or greater than 1."
2285 *
2286 * Older specifications don't mandate a behavior; we take
2287 * this as a clarification and always generate the error.
2288 */
2289 if (qual->index < 0 || qual->index > 1) {
2290 _mesa_glsl_error(loc, state,
2291 "explicit index may only be 0 or 1");
2292 } else {
2293 var->data.explicit_index = true;
2294 var->data.index = qual->index;
2295 }
2296 }
2297 }
2298 }
2299
2300 static void
2301 apply_image_qualifier_to_variable(const struct ast_type_qualifier *qual,
2302 ir_variable *var,
2303 struct _mesa_glsl_parse_state *state,
2304 YYLTYPE *loc)
2305 {
2306 const glsl_type *base_type =
2307 (var->type->is_array() ? var->type->element_type() : var->type);
2308
2309 if (base_type->is_image()) {
2310 if (var->data.mode != ir_var_uniform &&
2311 var->data.mode != ir_var_function_in) {
2312 _mesa_glsl_error(loc, state, "image variables may only be declared as "
2313 "function parameters or uniform-qualified "
2314 "global variables");
2315 }
2316
2317 var->data.image.read_only |= qual->flags.q.read_only;
2318 var->data.image.write_only |= qual->flags.q.write_only;
2319 var->data.image.coherent |= qual->flags.q.coherent;
2320 var->data.image._volatile |= qual->flags.q._volatile;
2321 var->data.image.restrict_flag |= qual->flags.q.restrict_flag;
2322 var->data.read_only = true;
2323
2324 if (qual->flags.q.explicit_image_format) {
2325 if (var->data.mode == ir_var_function_in) {
2326 _mesa_glsl_error(loc, state, "format qualifiers cannot be "
2327 "used on image function parameters");
2328 }
2329
2330 if (qual->image_base_type != base_type->sampler_type) {
2331 _mesa_glsl_error(loc, state, "format qualifier doesn't match the "
2332 "base data type of the image");
2333 }
2334
2335 var->data.image.format = qual->image_format;
2336 } else {
2337 if (var->data.mode == ir_var_uniform && !qual->flags.q.write_only) {
2338 _mesa_glsl_error(loc, state, "uniforms not qualified with "
2339 "`writeonly' must have a format layout "
2340 "qualifier");
2341 }
2342
2343 var->data.image.format = GL_NONE;
2344 }
2345 }
2346 }
2347
2348 static inline const char*
2349 get_layout_qualifier_string(bool origin_upper_left, bool pixel_center_integer)
2350 {
2351 if (origin_upper_left && pixel_center_integer)
2352 return "origin_upper_left, pixel_center_integer";
2353 else if (origin_upper_left)
2354 return "origin_upper_left";
2355 else if (pixel_center_integer)
2356 return "pixel_center_integer";
2357 else
2358 return " ";
2359 }
2360
2361 static inline bool
2362 is_conflicting_fragcoord_redeclaration(struct _mesa_glsl_parse_state *state,
2363 const struct ast_type_qualifier *qual)
2364 {
2365 /* If gl_FragCoord was previously declared, and the qualifiers were
2366 * different in any way, return true.
2367 */
2368 if (state->fs_redeclares_gl_fragcoord) {
2369 return (state->fs_pixel_center_integer != qual->flags.q.pixel_center_integer
2370 || state->fs_origin_upper_left != qual->flags.q.origin_upper_left);
2371 }
2372
2373 return false;
2374 }
2375
2376 static void
2377 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
2378 ir_variable *var,
2379 struct _mesa_glsl_parse_state *state,
2380 YYLTYPE *loc,
2381 bool is_parameter)
2382 {
2383 STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));
2384
2385 if (qual->flags.q.invariant) {
2386 if (var->data.used) {
2387 _mesa_glsl_error(loc, state,
2388 "variable `%s' may not be redeclared "
2389 "`invariant' after being used",
2390 var->name);
2391 } else {
2392 var->data.invariant = 1;
2393 }
2394 }
2395
2396 if (qual->flags.q.constant || qual->flags.q.attribute
2397 || qual->flags.q.uniform
2398 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2399 var->data.read_only = 1;
2400
2401 if (qual->flags.q.centroid)
2402 var->data.centroid = 1;
2403
2404 if (qual->flags.q.sample)
2405 var->data.sample = 1;
2406
2407 if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {
2408 var->type = glsl_type::error_type;
2409 _mesa_glsl_error(loc, state,
2410 "`attribute' variables may not be declared in the "
2411 "%s shader",
2412 _mesa_shader_stage_to_string(state->stage));
2413 }
2414
2415 /* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:
2416 *
2417 * "However, the const qualifier cannot be used with out or inout."
2418 *
2419 * The same section of the GLSL 4.40 spec further clarifies this saying:
2420 *
2421 * "The const qualifier cannot be used with out or inout, or a
2422 * compile-time error results."
2423 */
2424 if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {
2425 _mesa_glsl_error(loc, state,
2426 "`const' may not be applied to `out' or `inout' "
2427 "function parameters");
2428 }
2429
2430 /* If there is no qualifier that changes the mode of the variable, leave
2431 * the setting alone.
2432 */
2433 if (qual->flags.q.in && qual->flags.q.out)
2434 var->data.mode = ir_var_function_inout;
2435 else if (qual->flags.q.in)
2436 var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;
2437 else if (qual->flags.q.attribute
2438 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2439 var->data.mode = ir_var_shader_in;
2440 else if (qual->flags.q.out)
2441 var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;
2442 else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))
2443 var->data.mode = ir_var_shader_out;
2444 else if (qual->flags.q.uniform)
2445 var->data.mode = ir_var_uniform;
2446
2447 if (!is_parameter && is_varying_var(var, state->stage)) {
2448 /* User-defined ins/outs are not permitted in compute shaders. */
2449 if (state->stage == MESA_SHADER_COMPUTE) {
2450 _mesa_glsl_error(loc, state,
2451 "user-defined input and output variables are not "
2452 "permitted in compute shaders");
2453 }
2454
2455 /* This variable is being used to link data between shader stages (in
2456 * pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type
2457 * that is allowed for such purposes.
2458 *
2459 * From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
2460 *
2461 * "The varying qualifier can be used only with the data types
2462 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
2463 * these."
2464 *
2465 * This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From
2466 * page 31 (page 37 of the PDF) of the GLSL 1.30 spec:
2467 *
2468 * "Fragment inputs can only be signed and unsigned integers and
2469 * integer vectors, float, floating-point vectors, matrices, or
2470 * arrays of these. Structures cannot be input.
2471 *
2472 * Similar text exists in the section on vertex shader outputs.
2473 *
2474 * Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES
2475 * 3.00 spec allows structs as well. Varying structs are also allowed
2476 * in GLSL 1.50.
2477 */
2478 switch (var->type->get_scalar_type()->base_type) {
2479 case GLSL_TYPE_FLOAT:
2480 /* Ok in all GLSL versions */
2481 break;
2482 case GLSL_TYPE_UINT:
2483 case GLSL_TYPE_INT:
2484 if (state->is_version(130, 300))
2485 break;
2486 _mesa_glsl_error(loc, state,
2487 "varying variables must be of base type float in %s",
2488 state->get_version_string());
2489 break;
2490 case GLSL_TYPE_STRUCT:
2491 if (state->is_version(150, 300))
2492 break;
2493 _mesa_glsl_error(loc, state,
2494 "varying variables may not be of type struct");
2495 break;
2496 default:
2497 _mesa_glsl_error(loc, state, "illegal type for a varying variable");
2498 break;
2499 }
2500 }
2501
2502 if (state->all_invariant && (state->current_function == NULL)) {
2503 switch (state->stage) {
2504 case MESA_SHADER_VERTEX:
2505 if (var->data.mode == ir_var_shader_out)
2506 var->data.invariant = true;
2507 break;
2508 case MESA_SHADER_GEOMETRY:
2509 if ((var->data.mode == ir_var_shader_in)
2510 || (var->data.mode == ir_var_shader_out))
2511 var->data.invariant = true;
2512 break;
2513 case MESA_SHADER_FRAGMENT:
2514 if (var->data.mode == ir_var_shader_in)
2515 var->data.invariant = true;
2516 break;
2517 case MESA_SHADER_COMPUTE:
2518 /* Invariance isn't meaningful in compute shaders. */
2519 break;
2520 }
2521 }
2522
2523 var->data.interpolation =
2524 interpret_interpolation_qualifier(qual, (ir_variable_mode) var->data.mode,
2525 state, loc);
2526
2527 var->data.pixel_center_integer = qual->flags.q.pixel_center_integer;
2528 var->data.origin_upper_left = qual->flags.q.origin_upper_left;
2529 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
2530 && (strcmp(var->name, "gl_FragCoord") != 0)) {
2531 const char *const qual_string = (qual->flags.q.origin_upper_left)
2532 ? "origin_upper_left" : "pixel_center_integer";
2533
2534 _mesa_glsl_error(loc, state,
2535 "layout qualifier `%s' can only be applied to "
2536 "fragment shader input `gl_FragCoord'",
2537 qual_string);
2538 }
2539
2540 if (var->name != NULL && strcmp(var->name, "gl_FragCoord") == 0) {
2541
2542 /* Section 4.3.8.1, page 39 of GLSL 1.50 spec says:
2543 *
2544 * "Within any shader, the first redeclarations of gl_FragCoord
2545 * must appear before any use of gl_FragCoord."
2546 *
2547 * Generate a compiler error if above condition is not met by the
2548 * fragment shader.
2549 */
2550 ir_variable *earlier = state->symbols->get_variable("gl_FragCoord");
2551 if (earlier != NULL &&
2552 earlier->data.used &&
2553 !state->fs_redeclares_gl_fragcoord) {
2554 _mesa_glsl_error(loc, state,
2555 "gl_FragCoord used before its first redeclaration "
2556 "in fragment shader");
2557 }
2558
2559 /* Make sure all gl_FragCoord redeclarations specify the same layout
2560 * qualifiers.
2561 */
2562 if (is_conflicting_fragcoord_redeclaration(state, qual)) {
2563 const char *const qual_string =
2564 get_layout_qualifier_string(qual->flags.q.origin_upper_left,
2565 qual->flags.q.pixel_center_integer);
2566
2567 const char *const state_string =
2568 get_layout_qualifier_string(state->fs_origin_upper_left,
2569 state->fs_pixel_center_integer);
2570
2571 _mesa_glsl_error(loc, state,
2572 "gl_FragCoord redeclared with different layout "
2573 "qualifiers (%s) and (%s) ",
2574 state_string,
2575 qual_string);
2576 }
2577 state->fs_origin_upper_left = qual->flags.q.origin_upper_left;
2578 state->fs_pixel_center_integer = qual->flags.q.pixel_center_integer;
2579 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers =
2580 !qual->flags.q.origin_upper_left && !qual->flags.q.pixel_center_integer;
2581 state->fs_redeclares_gl_fragcoord =
2582 state->fs_origin_upper_left ||
2583 state->fs_pixel_center_integer ||
2584 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers;
2585 }
2586
2587 if (qual->flags.q.explicit_location) {
2588 validate_explicit_location(qual, var, state, loc);
2589 } else if (qual->flags.q.explicit_index) {
2590 _mesa_glsl_error(loc, state, "explicit index requires explicit location");
2591 }
2592
2593 if (qual->flags.q.explicit_binding &&
2594 validate_binding_qualifier(state, loc, var, qual)) {
2595 var->data.explicit_binding = true;
2596 var->data.binding = qual->binding;
2597 }
2598
2599 if (var->type->contains_atomic()) {
2600 if (var->data.mode == ir_var_uniform) {
2601 if (var->data.explicit_binding) {
2602 unsigned *offset =
2603 &state->atomic_counter_offsets[var->data.binding];
2604
2605 if (*offset % ATOMIC_COUNTER_SIZE)
2606 _mesa_glsl_error(loc, state,
2607 "misaligned atomic counter offset");
2608
2609 var->data.atomic.offset = *offset;
2610 *offset += var->type->atomic_size();
2611
2612 } else {
2613 _mesa_glsl_error(loc, state,
2614 "atomic counters require explicit binding point");
2615 }
2616 } else if (var->data.mode != ir_var_function_in) {
2617 _mesa_glsl_error(loc, state, "atomic counters may only be declared as "
2618 "function parameters or uniform-qualified "
2619 "global variables");
2620 }
2621 }
2622
2623 /* Does the declaration use the deprecated 'attribute' or 'varying'
2624 * keywords?
2625 */
2626 const bool uses_deprecated_qualifier = qual->flags.q.attribute
2627 || qual->flags.q.varying;
2628
2629 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2630 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2631 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2632 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2633 * These extensions and all following extensions that add the 'layout'
2634 * keyword have been modified to require the use of 'in' or 'out'.
2635 *
2636 * The following extension do not allow the deprecated keywords:
2637 *
2638 * GL_AMD_conservative_depth
2639 * GL_ARB_conservative_depth
2640 * GL_ARB_gpu_shader5
2641 * GL_ARB_separate_shader_objects
2642 * GL_ARB_tesselation_shader
2643 * GL_ARB_transform_feedback3
2644 * GL_ARB_uniform_buffer_object
2645 *
2646 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2647 * allow layout with the deprecated keywords.
2648 */
2649 const bool relaxed_layout_qualifier_checking =
2650 state->ARB_fragment_coord_conventions_enable;
2651
2652 if (qual->has_layout() && uses_deprecated_qualifier) {
2653 if (relaxed_layout_qualifier_checking) {
2654 _mesa_glsl_warning(loc, state,
2655 "`layout' qualifier may not be used with "
2656 "`attribute' or `varying'");
2657 } else {
2658 _mesa_glsl_error(loc, state,
2659 "`layout' qualifier may not be used with "
2660 "`attribute' or `varying'");
2661 }
2662 }
2663
2664 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2665 * AMD_conservative_depth.
2666 */
2667 int depth_layout_count = qual->flags.q.depth_any
2668 + qual->flags.q.depth_greater
2669 + qual->flags.q.depth_less
2670 + qual->flags.q.depth_unchanged;
2671 if (depth_layout_count > 0
2672 && !state->AMD_conservative_depth_enable
2673 && !state->ARB_conservative_depth_enable) {
2674 _mesa_glsl_error(loc, state,
2675 "extension GL_AMD_conservative_depth or "
2676 "GL_ARB_conservative_depth must be enabled "
2677 "to use depth layout qualifiers");
2678 } else if (depth_layout_count > 0
2679 && strcmp(var->name, "gl_FragDepth") != 0) {
2680 _mesa_glsl_error(loc, state,
2681 "depth layout qualifiers can be applied only to "
2682 "gl_FragDepth");
2683 } else if (depth_layout_count > 1
2684 && strcmp(var->name, "gl_FragDepth") == 0) {
2685 _mesa_glsl_error(loc, state,
2686 "at most one depth layout qualifier can be applied to "
2687 "gl_FragDepth");
2688 }
2689 if (qual->flags.q.depth_any)
2690 var->data.depth_layout = ir_depth_layout_any;
2691 else if (qual->flags.q.depth_greater)
2692 var->data.depth_layout = ir_depth_layout_greater;
2693 else if (qual->flags.q.depth_less)
2694 var->data.depth_layout = ir_depth_layout_less;
2695 else if (qual->flags.q.depth_unchanged)
2696 var->data.depth_layout = ir_depth_layout_unchanged;
2697 else
2698 var->data.depth_layout = ir_depth_layout_none;
2699
2700 if (qual->flags.q.std140 ||
2701 qual->flags.q.packed ||
2702 qual->flags.q.shared) {
2703 _mesa_glsl_error(loc, state,
2704 "uniform block layout qualifiers std140, packed, and "
2705 "shared can only be applied to uniform blocks, not "
2706 "members");
2707 }
2708
2709 if (qual->flags.q.row_major || qual->flags.q.column_major) {
2710 validate_matrix_layout_for_type(state, loc, var->type, var);
2711 }
2712
2713 if (var->type->contains_image())
2714 apply_image_qualifier_to_variable(qual, var, state, loc);
2715 }
2716
2717 /**
2718 * Get the variable that is being redeclared by this declaration
2719 *
2720 * Semantic checks to verify the validity of the redeclaration are also
2721 * performed. If semantic checks fail, compilation error will be emitted via
2722 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2723 *
2724 * \returns
2725 * A pointer to an existing variable in the current scope if the declaration
2726 * is a redeclaration, \c NULL otherwise.
2727 */
2728 static ir_variable *
2729 get_variable_being_redeclared(ir_variable *var, YYLTYPE loc,
2730 struct _mesa_glsl_parse_state *state,
2731 bool allow_all_redeclarations)
2732 {
2733 /* Check if this declaration is actually a re-declaration, either to
2734 * resize an array or add qualifiers to an existing variable.
2735 *
2736 * This is allowed for variables in the current scope, or when at
2737 * global scope (for built-ins in the implicit outer scope).
2738 */
2739 ir_variable *earlier = state->symbols->get_variable(var->name);
2740 if (earlier == NULL ||
2741 (state->current_function != NULL &&
2742 !state->symbols->name_declared_this_scope(var->name))) {
2743 return NULL;
2744 }
2745
2746
2747 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2748 *
2749 * "It is legal to declare an array without a size and then
2750 * later re-declare the same name as an array of the same
2751 * type and specify a size."
2752 */
2753 if (earlier->type->is_unsized_array() && var->type->is_array()
2754 && (var->type->element_type() == earlier->type->element_type())) {
2755 /* FINISHME: This doesn't match the qualifiers on the two
2756 * FINISHME: declarations. It's not 100% clear whether this is
2757 * FINISHME: required or not.
2758 */
2759
2760 const unsigned size = unsigned(var->type->array_size());
2761 check_builtin_array_max_size(var->name, size, loc, state);
2762 if ((size > 0) && (size <= earlier->data.max_array_access)) {
2763 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2764 "previous access",
2765 earlier->data.max_array_access);
2766 }
2767
2768 earlier->type = var->type;
2769 delete var;
2770 var = NULL;
2771 } else if ((state->ARB_fragment_coord_conventions_enable ||
2772 state->is_version(150, 0))
2773 && strcmp(var->name, "gl_FragCoord") == 0
2774 && earlier->type == var->type
2775 && earlier->data.mode == var->data.mode) {
2776 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2777 * qualifiers.
2778 */
2779 earlier->data.origin_upper_left = var->data.origin_upper_left;
2780 earlier->data.pixel_center_integer = var->data.pixel_center_integer;
2781
2782 /* According to section 4.3.7 of the GLSL 1.30 spec,
2783 * the following built-in varaibles can be redeclared with an
2784 * interpolation qualifier:
2785 * * gl_FrontColor
2786 * * gl_BackColor
2787 * * gl_FrontSecondaryColor
2788 * * gl_BackSecondaryColor
2789 * * gl_Color
2790 * * gl_SecondaryColor
2791 */
2792 } else if (state->is_version(130, 0)
2793 && (strcmp(var->name, "gl_FrontColor") == 0
2794 || strcmp(var->name, "gl_BackColor") == 0
2795 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2796 || strcmp(var->name, "gl_BackSecondaryColor") == 0
2797 || strcmp(var->name, "gl_Color") == 0
2798 || strcmp(var->name, "gl_SecondaryColor") == 0)
2799 && earlier->type == var->type
2800 && earlier->data.mode == var->data.mode) {
2801 earlier->data.interpolation = var->data.interpolation;
2802
2803 /* Layout qualifiers for gl_FragDepth. */
2804 } else if ((state->AMD_conservative_depth_enable ||
2805 state->ARB_conservative_depth_enable)
2806 && strcmp(var->name, "gl_FragDepth") == 0
2807 && earlier->type == var->type
2808 && earlier->data.mode == var->data.mode) {
2809
2810 /** From the AMD_conservative_depth spec:
2811 * Within any shader, the first redeclarations of gl_FragDepth
2812 * must appear before any use of gl_FragDepth.
2813 */
2814 if (earlier->data.used) {
2815 _mesa_glsl_error(&loc, state,
2816 "the first redeclaration of gl_FragDepth "
2817 "must appear before any use of gl_FragDepth");
2818 }
2819
2820 /* Prevent inconsistent redeclaration of depth layout qualifier. */
2821 if (earlier->data.depth_layout != ir_depth_layout_none
2822 && earlier->data.depth_layout != var->data.depth_layout) {
2823 _mesa_glsl_error(&loc, state,
2824 "gl_FragDepth: depth layout is declared here "
2825 "as '%s, but it was previously declared as "
2826 "'%s'",
2827 depth_layout_string(var->data.depth_layout),
2828 depth_layout_string(earlier->data.depth_layout));
2829 }
2830
2831 earlier->data.depth_layout = var->data.depth_layout;
2832
2833 } else if (allow_all_redeclarations) {
2834 if (earlier->data.mode != var->data.mode) {
2835 _mesa_glsl_error(&loc, state,
2836 "redeclaration of `%s' with incorrect qualifiers",
2837 var->name);
2838 } else if (earlier->type != var->type) {
2839 _mesa_glsl_error(&loc, state,
2840 "redeclaration of `%s' has incorrect type",
2841 var->name);
2842 }
2843 } else {
2844 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
2845 }
2846
2847 return earlier;
2848 }
2849
2850 /**
2851 * Generate the IR for an initializer in a variable declaration
2852 */
2853 ir_rvalue *
2854 process_initializer(ir_variable *var, ast_declaration *decl,
2855 ast_fully_specified_type *type,
2856 exec_list *initializer_instructions,
2857 struct _mesa_glsl_parse_state *state)
2858 {
2859 ir_rvalue *result = NULL;
2860
2861 YYLTYPE initializer_loc = decl->initializer->get_location();
2862
2863 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2864 *
2865 * "All uniform variables are read-only and are initialized either
2866 * directly by an application via API commands, or indirectly by
2867 * OpenGL."
2868 */
2869 if (var->data.mode == ir_var_uniform) {
2870 state->check_version(120, 0, &initializer_loc,
2871 "cannot initialize uniforms");
2872 }
2873
2874 /* From section 4.1.7 of the GLSL 4.40 spec:
2875 *
2876 * "Opaque variables [...] are initialized only through the
2877 * OpenGL API; they cannot be declared with an initializer in a
2878 * shader."
2879 */
2880 if (var->type->contains_opaque()) {
2881 _mesa_glsl_error(& initializer_loc, state,
2882 "cannot initialize opaque variable");
2883 }
2884
2885 if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {
2886 _mesa_glsl_error(& initializer_loc, state,
2887 "cannot initialize %s shader input / %s",
2888 _mesa_shader_stage_to_string(state->stage),
2889 (state->stage == MESA_SHADER_VERTEX)
2890 ? "attribute" : "varying");
2891 }
2892
2893 /* If the initializer is an ast_aggregate_initializer, recursively store
2894 * type information from the LHS into it, so that its hir() function can do
2895 * type checking.
2896 */
2897 if (decl->initializer->oper == ast_aggregate)
2898 _mesa_ast_set_aggregate_type(var->type, decl->initializer);
2899
2900 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2901 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions, state);
2902
2903 /* Calculate the constant value if this is a const or uniform
2904 * declaration.
2905 */
2906 if (type->qualifier.flags.q.constant
2907 || type->qualifier.flags.q.uniform) {
2908 ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,
2909 var->type, rhs, true);
2910 if (new_rhs != NULL) {
2911 rhs = new_rhs;
2912
2913 ir_constant *constant_value = rhs->constant_expression_value();
2914 if (!constant_value) {
2915 /* If ARB_shading_language_420pack is enabled, initializers of
2916 * const-qualified local variables do not have to be constant
2917 * expressions. Const-qualified global variables must still be
2918 * initialized with constant expressions.
2919 */
2920 if (!state->ARB_shading_language_420pack_enable
2921 || state->current_function == NULL) {
2922 _mesa_glsl_error(& initializer_loc, state,
2923 "initializer of %s variable `%s' must be a "
2924 "constant expression",
2925 (type->qualifier.flags.q.constant)
2926 ? "const" : "uniform",
2927 decl->identifier);
2928 if (var->type->is_numeric()) {
2929 /* Reduce cascading errors. */
2930 var->constant_value = ir_constant::zero(state, var->type);
2931 }
2932 }
2933 } else {
2934 rhs = constant_value;
2935 var->constant_value = constant_value;
2936 }
2937 } else {
2938 if (var->type->is_numeric()) {
2939 /* Reduce cascading errors. */
2940 var->constant_value = ir_constant::zero(state, var->type);
2941 }
2942 }
2943 }
2944
2945 if (rhs && !rhs->type->is_error()) {
2946 bool temp = var->data.read_only;
2947 if (type->qualifier.flags.q.constant)
2948 var->data.read_only = false;
2949
2950 /* Never emit code to initialize a uniform.
2951 */
2952 const glsl_type *initializer_type;
2953 if (!type->qualifier.flags.q.uniform) {
2954 do_assignment(initializer_instructions, state,
2955 NULL,
2956 lhs, rhs,
2957 &result, true,
2958 true,
2959 type->get_location());
2960 initializer_type = result->type;
2961 } else
2962 initializer_type = rhs->type;
2963
2964 var->constant_initializer = rhs->constant_expression_value();
2965 var->data.has_initializer = true;
2966
2967 /* If the declared variable is an unsized array, it must inherrit
2968 * its full type from the initializer. A declaration such as
2969 *
2970 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2971 *
2972 * becomes
2973 *
2974 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2975 *
2976 * The assignment generated in the if-statement (below) will also
2977 * automatically handle this case for non-uniforms.
2978 *
2979 * If the declared variable is not an array, the types must
2980 * already match exactly. As a result, the type assignment
2981 * here can be done unconditionally. For non-uniforms the call
2982 * to do_assignment can change the type of the initializer (via
2983 * the implicit conversion rules). For uniforms the initializer
2984 * must be a constant expression, and the type of that expression
2985 * was validated above.
2986 */
2987 var->type = initializer_type;
2988
2989 var->data.read_only = temp;
2990 }
2991
2992 return result;
2993 }
2994
2995
2996 /**
2997 * Do additional processing necessary for geometry shader input declarations
2998 * (this covers both interface blocks arrays and bare input variables).
2999 */
3000 static void
3001 handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,
3002 YYLTYPE loc, ir_variable *var)
3003 {
3004 unsigned num_vertices = 0;
3005 if (state->gs_input_prim_type_specified) {
3006 num_vertices = vertices_per_prim(state->in_qualifier->prim_type);
3007 }
3008
3009 /* Geometry shader input variables must be arrays. Caller should have
3010 * reported an error for this.
3011 */
3012 if (!var->type->is_array()) {
3013 assert(state->error);
3014
3015 /* To avoid cascading failures, short circuit the checks below. */
3016 return;
3017 }
3018
3019 if (var->type->is_unsized_array()) {
3020 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:
3021 *
3022 * All geometry shader input unsized array declarations will be
3023 * sized by an earlier input layout qualifier, when present, as per
3024 * the following table.
3025 *
3026 * Followed by a table mapping each allowed input layout qualifier to
3027 * the corresponding input length.
3028 */
3029 if (num_vertices != 0)
3030 var->type = glsl_type::get_array_instance(var->type->fields.array,
3031 num_vertices);
3032 } else {
3033 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec
3034 * includes the following examples of compile-time errors:
3035 *
3036 * // code sequence within one shader...
3037 * in vec4 Color1[]; // size unknown
3038 * ...Color1.length()...// illegal, length() unknown
3039 * in vec4 Color2[2]; // size is 2
3040 * ...Color1.length()...// illegal, Color1 still has no size
3041 * in vec4 Color3[3]; // illegal, input sizes are inconsistent
3042 * layout(lines) in; // legal, input size is 2, matching
3043 * in vec4 Color4[3]; // illegal, contradicts layout
3044 * ...
3045 *
3046 * To detect the case illustrated by Color3, we verify that the size of
3047 * an explicitly-sized array matches the size of any previously declared
3048 * explicitly-sized array. To detect the case illustrated by Color4, we
3049 * verify that the size of an explicitly-sized array is consistent with
3050 * any previously declared input layout.
3051 */
3052 if (num_vertices != 0 && var->type->length != num_vertices) {
3053 _mesa_glsl_error(&loc, state,
3054 "geometry shader input size contradicts previously"
3055 " declared layout (size is %u, but layout requires a"
3056 " size of %u)", var->type->length, num_vertices);
3057 } else if (state->gs_input_size != 0 &&
3058 var->type->length != state->gs_input_size) {
3059 _mesa_glsl_error(&loc, state,
3060 "geometry shader input sizes are "
3061 "inconsistent (size is %u, but a previous "
3062 "declaration has size %u)",
3063 var->type->length, state->gs_input_size);
3064 } else {
3065 state->gs_input_size = var->type->length;
3066 }
3067 }
3068 }
3069
3070
3071 void
3072 validate_identifier(const char *identifier, YYLTYPE loc,
3073 struct _mesa_glsl_parse_state *state)
3074 {
3075 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3076 *
3077 * "Identifiers starting with "gl_" are reserved for use by
3078 * OpenGL, and may not be declared in a shader as either a
3079 * variable or a function."
3080 */
3081 if (strncmp(identifier, "gl_", 3) == 0) {
3082 _mesa_glsl_error(&loc, state,
3083 "identifier `%s' uses reserved `gl_' prefix",
3084 identifier);
3085 } else if (strstr(identifier, "__")) {
3086 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
3087 * spec:
3088 *
3089 * "In addition, all identifiers containing two
3090 * consecutive underscores (__) are reserved as
3091 * possible future keywords."
3092 *
3093 * The intention is that names containing __ are reserved for internal
3094 * use by the implementation, and names prefixed with GL_ are reserved
3095 * for use by Khronos. Names simply containing __ are dangerous to use,
3096 * but should be allowed.
3097 *
3098 * A future version of the GLSL specification will clarify this.
3099 */
3100 _mesa_glsl_warning(&loc, state,
3101 "identifier `%s' uses reserved `__' string",
3102 identifier);
3103 }
3104 }
3105
3106
3107 ir_rvalue *
3108 ast_declarator_list::hir(exec_list *instructions,
3109 struct _mesa_glsl_parse_state *state)
3110 {
3111 void *ctx = state;
3112 const struct glsl_type *decl_type;
3113 const char *type_name = NULL;
3114 ir_rvalue *result = NULL;
3115 YYLTYPE loc = this->get_location();
3116
3117 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
3118 *
3119 * "To ensure that a particular output variable is invariant, it is
3120 * necessary to use the invariant qualifier. It can either be used to
3121 * qualify a previously declared variable as being invariant
3122 *
3123 * invariant gl_Position; // make existing gl_Position be invariant"
3124 *
3125 * In these cases the parser will set the 'invariant' flag in the declarator
3126 * list, and the type will be NULL.
3127 */
3128 if (this->invariant) {
3129 assert(this->type == NULL);
3130
3131 if (state->current_function != NULL) {
3132 _mesa_glsl_error(& loc, state,
3133 "all uses of `invariant' keyword must be at global "
3134 "scope");
3135 }
3136
3137 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3138 assert(decl->array_specifier == NULL);
3139 assert(decl->initializer == NULL);
3140
3141 ir_variable *const earlier =
3142 state->symbols->get_variable(decl->identifier);
3143 if (earlier == NULL) {
3144 _mesa_glsl_error(& loc, state,
3145 "undeclared variable `%s' cannot be marked "
3146 "invariant", decl->identifier);
3147 } else if (!is_varying_var(earlier, state->stage)) {
3148 _mesa_glsl_error(&loc, state,
3149 "`%s' cannot be marked invariant; interfaces between "
3150 "shader stages only.", decl->identifier);
3151 } else if (earlier->data.used) {
3152 _mesa_glsl_error(& loc, state,
3153 "variable `%s' may not be redeclared "
3154 "`invariant' after being used",
3155 earlier->name);
3156 } else {
3157 earlier->data.invariant = true;
3158 }
3159 }
3160
3161 /* Invariant redeclarations do not have r-values.
3162 */
3163 return NULL;
3164 }
3165
3166 assert(this->type != NULL);
3167 assert(!this->invariant);
3168
3169 /* The type specifier may contain a structure definition. Process that
3170 * before any of the variable declarations.
3171 */
3172 (void) this->type->specifier->hir(instructions, state);
3173
3174 decl_type = this->type->glsl_type(& type_name, state);
3175
3176 /* An offset-qualified atomic counter declaration sets the default
3177 * offset for the next declaration within the same atomic counter
3178 * buffer.
3179 */
3180 if (decl_type && decl_type->contains_atomic()) {
3181 if (type->qualifier.flags.q.explicit_binding &&
3182 type->qualifier.flags.q.explicit_offset)
3183 state->atomic_counter_offsets[type->qualifier.binding] =
3184 type->qualifier.offset;
3185 }
3186
3187 if (this->declarations.is_empty()) {
3188 /* If there is no structure involved in the program text, there are two
3189 * possible scenarios:
3190 *
3191 * - The program text contained something like 'vec4;'. This is an
3192 * empty declaration. It is valid but weird. Emit a warning.
3193 *
3194 * - The program text contained something like 'S;' and 'S' is not the
3195 * name of a known structure type. This is both invalid and weird.
3196 * Emit an error.
3197 *
3198 * - The program text contained something like 'mediump float;'
3199 * when the programmer probably meant 'precision mediump
3200 * float;' Emit a warning with a description of what they
3201 * probably meant to do.
3202 *
3203 * Note that if decl_type is NULL and there is a structure involved,
3204 * there must have been some sort of error with the structure. In this
3205 * case we assume that an error was already generated on this line of
3206 * code for the structure. There is no need to generate an additional,
3207 * confusing error.
3208 */
3209 assert(this->type->specifier->structure == NULL || decl_type != NULL
3210 || state->error);
3211
3212 if (decl_type == NULL) {
3213 _mesa_glsl_error(&loc, state,
3214 "invalid type `%s' in empty declaration",
3215 type_name);
3216 } else if (decl_type->base_type == GLSL_TYPE_ATOMIC_UINT) {
3217 /* Empty atomic counter declarations are allowed and useful
3218 * to set the default offset qualifier.
3219 */
3220 return NULL;
3221 } else if (this->type->qualifier.precision != ast_precision_none) {
3222 if (this->type->specifier->structure != NULL) {
3223 _mesa_glsl_error(&loc, state,
3224 "precision qualifiers can't be applied "
3225 "to structures");
3226 } else {
3227 static const char *const precision_names[] = {
3228 "highp",
3229 "highp",
3230 "mediump",
3231 "lowp"
3232 };
3233
3234 _mesa_glsl_warning(&loc, state,
3235 "empty declaration with precision qualifier, "
3236 "to set the default precision, use "
3237 "`precision %s %s;'",
3238 precision_names[this->type->qualifier.precision],
3239 type_name);
3240 }
3241 } else if (this->type->specifier->structure == NULL) {
3242 _mesa_glsl_warning(&loc, state, "empty declaration");
3243 }
3244 }
3245
3246 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3247 const struct glsl_type *var_type;
3248 ir_variable *var;
3249
3250 /* FINISHME: Emit a warning if a variable declaration shadows a
3251 * FINISHME: declaration at a higher scope.
3252 */
3253
3254 if ((decl_type == NULL) || decl_type->is_void()) {
3255 if (type_name != NULL) {
3256 _mesa_glsl_error(& loc, state,
3257 "invalid type `%s' in declaration of `%s'",
3258 type_name, decl->identifier);
3259 } else {
3260 _mesa_glsl_error(& loc, state,
3261 "invalid type in declaration of `%s'",
3262 decl->identifier);
3263 }
3264 continue;
3265 }
3266
3267 var_type = process_array_type(&loc, decl_type, decl->array_specifier,
3268 state);
3269
3270 var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
3271
3272 /* The 'varying in' and 'varying out' qualifiers can only be used with
3273 * ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support
3274 * yet.
3275 */
3276 if (this->type->qualifier.flags.q.varying) {
3277 if (this->type->qualifier.flags.q.in) {
3278 _mesa_glsl_error(& loc, state,
3279 "`varying in' qualifier in declaration of "
3280 "`%s' only valid for geometry shaders using "
3281 "ARB_geometry_shader4 or EXT_geometry_shader4",
3282 decl->identifier);
3283 } else if (this->type->qualifier.flags.q.out) {
3284 _mesa_glsl_error(& loc, state,
3285 "`varying out' qualifier in declaration of "
3286 "`%s' only valid for geometry shaders using "
3287 "ARB_geometry_shader4 or EXT_geometry_shader4",
3288 decl->identifier);
3289 }
3290 }
3291
3292 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
3293 *
3294 * "Global variables can only use the qualifiers const,
3295 * attribute, uniform, or varying. Only one may be
3296 * specified.
3297 *
3298 * Local variables can only use the qualifier const."
3299 *
3300 * This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by
3301 * any extension that adds the 'layout' keyword.
3302 */
3303 if (!state->is_version(130, 300)
3304 && !state->has_explicit_attrib_location()
3305 && !state->has_separate_shader_objects()
3306 && !state->ARB_fragment_coord_conventions_enable) {
3307 if (this->type->qualifier.flags.q.out) {
3308 _mesa_glsl_error(& loc, state,
3309 "`out' qualifier in declaration of `%s' "
3310 "only valid for function parameters in %s",
3311 decl->identifier, state->get_version_string());
3312 }
3313 if (this->type->qualifier.flags.q.in) {
3314 _mesa_glsl_error(& loc, state,
3315 "`in' qualifier in declaration of `%s' "
3316 "only valid for function parameters in %s",
3317 decl->identifier, state->get_version_string());
3318 }
3319 /* FINISHME: Test for other invalid qualifiers. */
3320 }
3321
3322 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
3323 & loc, false);
3324
3325 if (this->type->qualifier.flags.q.invariant) {
3326 if (!is_varying_var(var, state->stage)) {
3327 _mesa_glsl_error(&loc, state,
3328 "`%s' cannot be marked invariant; interfaces between "
3329 "shader stages only", var->name);
3330 }
3331 }
3332
3333 if (state->current_function != NULL) {
3334 const char *mode = NULL;
3335 const char *extra = "";
3336
3337 /* There is no need to check for 'inout' here because the parser will
3338 * only allow that in function parameter lists.
3339 */
3340 if (this->type->qualifier.flags.q.attribute) {
3341 mode = "attribute";
3342 } else if (this->type->qualifier.flags.q.uniform) {
3343 mode = "uniform";
3344 } else if (this->type->qualifier.flags.q.varying) {
3345 mode = "varying";
3346 } else if (this->type->qualifier.flags.q.in) {
3347 mode = "in";
3348 extra = " or in function parameter list";
3349 } else if (this->type->qualifier.flags.q.out) {
3350 mode = "out";
3351 extra = " or in function parameter list";
3352 }
3353
3354 if (mode) {
3355 _mesa_glsl_error(& loc, state,
3356 "%s variable `%s' must be declared at "
3357 "global scope%s",
3358 mode, var->name, extra);
3359 }
3360 } else if (var->data.mode == ir_var_shader_in) {
3361 var->data.read_only = true;
3362
3363 if (state->stage == MESA_SHADER_VERTEX) {
3364 bool error_emitted = false;
3365
3366 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
3367 *
3368 * "Vertex shader inputs can only be float, floating-point
3369 * vectors, matrices, signed and unsigned integers and integer
3370 * vectors. Vertex shader inputs can also form arrays of these
3371 * types, but not structures."
3372 *
3373 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
3374 *
3375 * "Vertex shader inputs can only be float, floating-point
3376 * vectors, matrices, signed and unsigned integers and integer
3377 * vectors. They cannot be arrays or structures."
3378 *
3379 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
3380 *
3381 * "The attribute qualifier can be used only with float,
3382 * floating-point vectors, and matrices. Attribute variables
3383 * cannot be declared as arrays or structures."
3384 *
3385 * From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:
3386 *
3387 * "Vertex shader inputs can only be float, floating-point
3388 * vectors, matrices, signed and unsigned integers and integer
3389 * vectors. Vertex shader inputs cannot be arrays or
3390 * structures."
3391 */
3392 const glsl_type *check_type = var->type;
3393 while (check_type->is_array())
3394 check_type = check_type->element_type();
3395
3396 switch (check_type->base_type) {
3397 case GLSL_TYPE_FLOAT:
3398 break;
3399 case GLSL_TYPE_UINT:
3400 case GLSL_TYPE_INT:
3401 if (state->is_version(120, 300))
3402 break;
3403 /* FALLTHROUGH */
3404 default:
3405 _mesa_glsl_error(& loc, state,
3406 "vertex shader input / attribute cannot have "
3407 "type %s`%s'",
3408 var->type->is_array() ? "array of " : "",
3409 check_type->name);
3410 error_emitted = true;
3411 }
3412
3413 if (!error_emitted && var->type->is_array() &&
3414 !state->check_version(150, 0, &loc,
3415 "vertex shader input / attribute "
3416 "cannot have array type")) {
3417 error_emitted = true;
3418 }
3419 } else if (state->stage == MESA_SHADER_GEOMETRY) {
3420 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
3421 *
3422 * Geometry shader input variables get the per-vertex values
3423 * written out by vertex shader output variables of the same
3424 * names. Since a geometry shader operates on a set of
3425 * vertices, each input varying variable (or input block, see
3426 * interface blocks below) needs to be declared as an array.
3427 */
3428 if (!var->type->is_array()) {
3429 _mesa_glsl_error(&loc, state,
3430 "geometry shader inputs must be arrays");
3431 }
3432
3433 handle_geometry_shader_input_decl(state, loc, var);
3434 }
3435 }
3436
3437 /* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,
3438 * so must integer vertex outputs.
3439 *
3440 * From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:
3441 * "Fragment shader inputs that are signed or unsigned integers or
3442 * integer vectors must be qualified with the interpolation qualifier
3443 * flat."
3444 *
3445 * From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:
3446 * "Fragment shader inputs that are, or contain, signed or unsigned
3447 * integers or integer vectors must be qualified with the
3448 * interpolation qualifier flat."
3449 *
3450 * From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:
3451 * "Vertex shader outputs that are, or contain, signed or unsigned
3452 * integers or integer vectors must be qualified with the
3453 * interpolation qualifier flat."
3454 *
3455 * Note that prior to GLSL 1.50, this requirement applied to vertex
3456 * outputs rather than fragment inputs. That creates problems in the
3457 * presence of geometry shaders, so we adopt the GLSL 1.50 rule for all
3458 * desktop GL shaders. For GLSL ES shaders, we follow the spec and
3459 * apply the restriction to both vertex outputs and fragment inputs.
3460 *
3461 * Note also that the desktop GLSL specs are missing the text "or
3462 * contain"; this is presumably an oversight, since there is no
3463 * reasonable way to interpolate a fragment shader input that contains
3464 * an integer.
3465 */
3466 if (state->is_version(130, 300) &&
3467 var->type->contains_integer() &&
3468 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
3469 ((state->stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_in)
3470 || (state->stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_out
3471 && state->es_shader))) {
3472 const char *var_type = (state->stage == MESA_SHADER_VERTEX) ?
3473 "vertex output" : "fragment input";
3474 _mesa_glsl_error(&loc, state, "if a %s is (or contains) "
3475 "an integer, then it must be qualified with 'flat'",
3476 var_type);
3477 }
3478
3479
3480 /* Interpolation qualifiers cannot be applied to 'centroid' and
3481 * 'centroid varying'.
3482 *
3483 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3484 * "interpolation qualifiers may only precede the qualifiers in,
3485 * centroid in, out, or centroid out in a declaration. They do not apply
3486 * to the deprecated storage qualifiers varying or centroid varying."
3487 *
3488 * These deprecated storage qualifiers do not exist in GLSL ES 3.00.
3489 */
3490 if (state->is_version(130, 0)
3491 && this->type->qualifier.has_interpolation()
3492 && this->type->qualifier.flags.q.varying) {
3493
3494 const char *i = this->type->qualifier.interpolation_string();
3495 assert(i != NULL);
3496 const char *s;
3497 if (this->type->qualifier.flags.q.centroid)
3498 s = "centroid varying";
3499 else
3500 s = "varying";
3501
3502 _mesa_glsl_error(&loc, state,
3503 "qualifier '%s' cannot be applied to the "
3504 "deprecated storage qualifier '%s'", i, s);
3505 }
3506
3507
3508 /* Interpolation qualifiers can only apply to vertex shader outputs and
3509 * fragment shader inputs.
3510 *
3511 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3512 * "Outputs from a vertex shader (out) and inputs to a fragment
3513 * shader (in) can be further qualified with one or more of these
3514 * interpolation qualifiers"
3515 *
3516 * From page 31 (page 37 of the PDF) of the GLSL ES 3.00 spec:
3517 * "These interpolation qualifiers may only precede the qualifiers
3518 * in, centroid in, out, or centroid out in a declaration. They do
3519 * not apply to inputs into a vertex shader or outputs from a
3520 * fragment shader."
3521 */
3522 if (state->is_version(130, 300)
3523 && this->type->qualifier.has_interpolation()) {
3524
3525 const char *i = this->type->qualifier.interpolation_string();
3526 assert(i != NULL);
3527
3528 switch (state->stage) {
3529 case MESA_SHADER_VERTEX:
3530 if (this->type->qualifier.flags.q.in) {
3531 _mesa_glsl_error(&loc, state,
3532 "qualifier '%s' cannot be applied to vertex "
3533 "shader inputs", i);
3534 }
3535 break;
3536 case MESA_SHADER_FRAGMENT:
3537 if (this->type->qualifier.flags.q.out) {
3538 _mesa_glsl_error(&loc, state,
3539 "qualifier '%s' cannot be applied to fragment "
3540 "shader outputs", i);
3541 }
3542 break;
3543 default:
3544 break;
3545 }
3546 }
3547
3548
3549 /* From section 4.3.4 of the GLSL 1.30 spec:
3550 * "It is an error to use centroid in in a vertex shader."
3551 *
3552 * From section 4.3.4 of the GLSL ES 3.00 spec:
3553 * "It is an error to use centroid in or interpolation qualifiers in
3554 * a vertex shader input."
3555 */
3556 if (state->is_version(130, 300)
3557 && this->type->qualifier.flags.q.centroid
3558 && this->type->qualifier.flags.q.in
3559 && state->stage == MESA_SHADER_VERTEX) {
3560
3561 _mesa_glsl_error(&loc, state,
3562 "'centroid in' cannot be used in a vertex shader");
3563 }
3564
3565 if (state->stage == MESA_SHADER_VERTEX
3566 && this->type->qualifier.flags.q.sample
3567 && this->type->qualifier.flags.q.in) {
3568
3569 _mesa_glsl_error(&loc, state,
3570 "'sample in' cannot be used in a vertex shader");
3571 }
3572
3573 /* Section 4.3.6 of the GLSL 1.30 specification states:
3574 * "It is an error to use centroid out in a fragment shader."
3575 *
3576 * The GL_ARB_shading_language_420pack extension specification states:
3577 * "It is an error to use auxiliary storage qualifiers or interpolation
3578 * qualifiers on an output in a fragment shader."
3579 */
3580 if (state->stage == MESA_SHADER_FRAGMENT &&
3581 this->type->qualifier.flags.q.out &&
3582 this->type->qualifier.has_auxiliary_storage()) {
3583 _mesa_glsl_error(&loc, state,
3584 "auxiliary storage qualifiers cannot be used on "
3585 "fragment shader outputs");
3586 }
3587
3588 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
3589 */
3590 if (this->type->qualifier.precision != ast_precision_none) {
3591 state->check_precision_qualifiers_allowed(&loc);
3592 }
3593
3594
3595 /* Precision qualifiers apply to floating point, integer and sampler
3596 * types.
3597 *
3598 * Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:
3599 * "Any floating point or any integer declaration can have the type
3600 * preceded by one of these precision qualifiers [...] Literal
3601 * constants do not have precision qualifiers. Neither do Boolean
3602 * variables.
3603 *
3604 * Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.30
3605 * spec also says:
3606 *
3607 * "Precision qualifiers are added for code portability with OpenGL
3608 * ES, not for functionality. They have the same syntax as in OpenGL
3609 * ES."
3610 *
3611 * Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:
3612 *
3613 * "uniform lowp sampler2D sampler;
3614 * highp vec2 coord;
3615 * ...
3616 * lowp vec4 col = texture2D (sampler, coord);
3617 * // texture2D returns lowp"
3618 *
3619 * From this, we infer that GLSL 1.30 (and later) should allow precision
3620 * qualifiers on sampler types just like float and integer types.
3621 */
3622 if (this->type->qualifier.precision != ast_precision_none
3623 && !var->type->is_float()
3624 && !var->type->is_integer()
3625 && !var->type->is_record()
3626 && !var->type->is_sampler()
3627 && !(var->type->is_array()
3628 && (var->type->fields.array->is_float()
3629 || var->type->fields.array->is_integer()))) {
3630
3631 _mesa_glsl_error(&loc, state,
3632 "precision qualifiers apply only to floating point"
3633 ", integer and sampler types");
3634 }
3635
3636 /* From section 4.1.7 of the GLSL 4.40 spec:
3637 *
3638 * "[Opaque types] can only be declared as function
3639 * parameters or uniform-qualified variables."
3640 */
3641 if (var_type->contains_opaque() &&
3642 !this->type->qualifier.flags.q.uniform) {
3643 _mesa_glsl_error(&loc, state,
3644 "opaque variables must be declared uniform");
3645 }
3646
3647 /* Process the initializer and add its instructions to a temporary
3648 * list. This list will be added to the instruction stream (below) after
3649 * the declaration is added. This is done because in some cases (such as
3650 * redeclarations) the declaration may not actually be added to the
3651 * instruction stream.
3652 */
3653 exec_list initializer_instructions;
3654 ir_variable *earlier =
3655 get_variable_being_redeclared(var, decl->get_location(), state,
3656 false /* allow_all_redeclarations */);
3657 if (earlier != NULL) {
3658 if (strncmp(var->name, "gl_", 3) == 0 &&
3659 earlier->data.how_declared == ir_var_declared_in_block) {
3660 _mesa_glsl_error(&loc, state,
3661 "`%s' has already been redeclared using "
3662 "gl_PerVertex", var->name);
3663 }
3664 earlier->data.how_declared = ir_var_declared_normally;
3665 }
3666
3667 if (decl->initializer != NULL) {
3668 result = process_initializer((earlier == NULL) ? var : earlier,
3669 decl, this->type,
3670 &initializer_instructions, state);
3671 }
3672
3673 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
3674 *
3675 * "It is an error to write to a const variable outside of
3676 * its declaration, so they must be initialized when
3677 * declared."
3678 */
3679 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
3680 _mesa_glsl_error(& loc, state,
3681 "const declaration of `%s' must be initialized",
3682 decl->identifier);
3683 }
3684
3685 if (state->es_shader) {
3686 const glsl_type *const t = (earlier == NULL)
3687 ? var->type : earlier->type;
3688
3689 if (t->is_unsized_array())
3690 /* Section 10.17 of the GLSL ES 1.00 specification states that
3691 * unsized array declarations have been removed from the language.
3692 * Arrays that are sized using an initializer are still explicitly
3693 * sized. However, GLSL ES 1.00 does not allow array
3694 * initializers. That is only allowed in GLSL ES 3.00.
3695 *
3696 * Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:
3697 *
3698 * "An array type can also be formed without specifying a size
3699 * if the definition includes an initializer:
3700 *
3701 * float x[] = float[2] (1.0, 2.0); // declares an array of size 2
3702 * float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 3
3703 *
3704 * float a[5];
3705 * float b[] = a;"
3706 */
3707 _mesa_glsl_error(& loc, state,
3708 "unsized array declarations are not allowed in "
3709 "GLSL ES");
3710 }
3711
3712 /* If the declaration is not a redeclaration, there are a few additional
3713 * semantic checks that must be applied. In addition, variable that was
3714 * created for the declaration should be added to the IR stream.
3715 */
3716 if (earlier == NULL) {
3717 validate_identifier(decl->identifier, loc, state);
3718
3719 /* Add the variable to the symbol table. Note that the initializer's
3720 * IR was already processed earlier (though it hasn't been emitted
3721 * yet), without the variable in scope.
3722 *
3723 * This differs from most C-like languages, but it follows the GLSL
3724 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
3725 * spec:
3726 *
3727 * "Within a declaration, the scope of a name starts immediately
3728 * after the initializer if present or immediately after the name
3729 * being declared if not."
3730 */
3731 if (!state->symbols->add_variable(var)) {
3732 YYLTYPE loc = this->get_location();
3733 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
3734 "current scope", decl->identifier);
3735 continue;
3736 }
3737
3738 /* Push the variable declaration to the top. It means that all the
3739 * variable declarations will appear in a funny last-to-first order,
3740 * but otherwise we run into trouble if a function is prototyped, a
3741 * global var is decled, then the function is defined with usage of
3742 * the global var. See glslparsertest's CorrectModule.frag.
3743 */
3744 instructions->push_head(var);
3745 }
3746
3747 instructions->append_list(&initializer_instructions);
3748 }
3749
3750
3751 /* Generally, variable declarations do not have r-values. However,
3752 * one is used for the declaration in
3753 *
3754 * while (bool b = some_condition()) {
3755 * ...
3756 * }
3757 *
3758 * so we return the rvalue from the last seen declaration here.
3759 */
3760 return result;
3761 }
3762
3763
3764 ir_rvalue *
3765 ast_parameter_declarator::hir(exec_list *instructions,
3766 struct _mesa_glsl_parse_state *state)
3767 {
3768 void *ctx = state;
3769 const struct glsl_type *type;
3770 const char *name = NULL;
3771 YYLTYPE loc = this->get_location();
3772
3773 type = this->type->glsl_type(& name, state);
3774
3775 if (type == NULL) {
3776 if (name != NULL) {
3777 _mesa_glsl_error(& loc, state,
3778 "invalid type `%s' in declaration of `%s'",
3779 name, this->identifier);
3780 } else {
3781 _mesa_glsl_error(& loc, state,
3782 "invalid type in declaration of `%s'",
3783 this->identifier);
3784 }
3785
3786 type = glsl_type::error_type;
3787 }
3788
3789 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
3790 *
3791 * "Functions that accept no input arguments need not use void in the
3792 * argument list because prototypes (or definitions) are required and
3793 * therefore there is no ambiguity when an empty argument list "( )" is
3794 * declared. The idiom "(void)" as a parameter list is provided for
3795 * convenience."
3796 *
3797 * Placing this check here prevents a void parameter being set up
3798 * for a function, which avoids tripping up checks for main taking
3799 * parameters and lookups of an unnamed symbol.
3800 */
3801 if (type->is_void()) {
3802 if (this->identifier != NULL)
3803 _mesa_glsl_error(& loc, state,
3804 "named parameter cannot have type `void'");
3805
3806 is_void = true;
3807 return NULL;
3808 }
3809
3810 if (formal_parameter && (this->identifier == NULL)) {
3811 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
3812 return NULL;
3813 }
3814
3815 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
3816 * call already handled the "vec4[..] foo" case.
3817 */
3818 type = process_array_type(&loc, type, this->array_specifier, state);
3819
3820 if (!type->is_error() && type->is_unsized_array()) {
3821 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
3822 "a declared size");
3823 type = glsl_type::error_type;
3824 }
3825
3826 is_void = false;
3827 ir_variable *var = new(ctx)
3828 ir_variable(type, this->identifier, ir_var_function_in);
3829
3830 /* Apply any specified qualifiers to the parameter declaration. Note that
3831 * for function parameters the default mode is 'in'.
3832 */
3833 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,
3834 true);
3835
3836 /* From section 4.1.7 of the GLSL 4.40 spec:
3837 *
3838 * "Opaque variables cannot be treated as l-values; hence cannot
3839 * be used as out or inout function parameters, nor can they be
3840 * assigned into."
3841 */
3842 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
3843 && type->contains_opaque()) {
3844 _mesa_glsl_error(&loc, state, "out and inout parameters cannot "
3845 "contain opaque variables");
3846 type = glsl_type::error_type;
3847 }
3848
3849 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
3850 *
3851 * "When calling a function, expressions that do not evaluate to
3852 * l-values cannot be passed to parameters declared as out or inout."
3853 *
3854 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
3855 *
3856 * "Other binary or unary expressions, non-dereferenced arrays,
3857 * function names, swizzles with repeated fields, and constants
3858 * cannot be l-values."
3859 *
3860 * So for GLSL 1.10, passing an array as an out or inout parameter is not
3861 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
3862 */
3863 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
3864 && type->is_array()
3865 && !state->check_version(120, 100, &loc,
3866 "arrays cannot be out or inout parameters")) {
3867 type = glsl_type::error_type;
3868 }
3869
3870 instructions->push_tail(var);
3871
3872 /* Parameter declarations do not have r-values.
3873 */
3874 return NULL;
3875 }
3876
3877
3878 void
3879 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
3880 bool formal,
3881 exec_list *ir_parameters,
3882 _mesa_glsl_parse_state *state)
3883 {
3884 ast_parameter_declarator *void_param = NULL;
3885 unsigned count = 0;
3886
3887 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
3888 param->formal_parameter = formal;
3889 param->hir(ir_parameters, state);
3890
3891 if (param->is_void)
3892 void_param = param;
3893
3894 count++;
3895 }
3896
3897 if ((void_param != NULL) && (count > 1)) {
3898 YYLTYPE loc = void_param->get_location();
3899
3900 _mesa_glsl_error(& loc, state,
3901 "`void' parameter must be only parameter");
3902 }
3903 }
3904
3905
3906 void
3907 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
3908 {
3909 /* IR invariants disallow function declarations or definitions
3910 * nested within other function definitions. But there is no
3911 * requirement about the relative order of function declarations
3912 * and definitions with respect to one another. So simply insert
3913 * the new ir_function block at the end of the toplevel instruction
3914 * list.
3915 */
3916 state->toplevel_ir->push_tail(f);
3917 }
3918
3919
3920 ir_rvalue *
3921 ast_function::hir(exec_list *instructions,
3922 struct _mesa_glsl_parse_state *state)
3923 {
3924 void *ctx = state;
3925 ir_function *f = NULL;
3926 ir_function_signature *sig = NULL;
3927 exec_list hir_parameters;
3928
3929 const char *const name = identifier;
3930
3931 /* New functions are always added to the top-level IR instruction stream,
3932 * so this instruction list pointer is ignored. See also emit_function
3933 * (called below).
3934 */
3935 (void) instructions;
3936
3937 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
3938 *
3939 * "Function declarations (prototypes) cannot occur inside of functions;
3940 * they must be at global scope, or for the built-in functions, outside
3941 * the global scope."
3942 *
3943 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
3944 *
3945 * "User defined functions may only be defined within the global scope."
3946 *
3947 * Note that this language does not appear in GLSL 1.10.
3948 */
3949 if ((state->current_function != NULL) &&
3950 state->is_version(120, 100)) {
3951 YYLTYPE loc = this->get_location();
3952 _mesa_glsl_error(&loc, state,
3953 "declaration of function `%s' not allowed within "
3954 "function body", name);
3955 }
3956
3957 validate_identifier(name, this->get_location(), state);
3958
3959 /* Convert the list of function parameters to HIR now so that they can be
3960 * used below to compare this function's signature with previously seen
3961 * signatures for functions with the same name.
3962 */
3963 ast_parameter_declarator::parameters_to_hir(& this->parameters,
3964 is_definition,
3965 & hir_parameters, state);
3966
3967 const char *return_type_name;
3968 const glsl_type *return_type =
3969 this->return_type->glsl_type(& return_type_name, state);
3970
3971 if (!return_type) {
3972 YYLTYPE loc = this->get_location();
3973 _mesa_glsl_error(&loc, state,
3974 "function `%s' has undeclared return type `%s'",
3975 name, return_type_name);
3976 return_type = glsl_type::error_type;
3977 }
3978
3979 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3980 * "No qualifier is allowed on the return type of a function."
3981 */
3982 if (this->return_type->has_qualifiers()) {
3983 YYLTYPE loc = this->get_location();
3984 _mesa_glsl_error(& loc, state,
3985 "function `%s' return type has qualifiers", name);
3986 }
3987
3988 /* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:
3989 *
3990 * "Arrays are allowed as arguments and as the return type. In both
3991 * cases, the array must be explicitly sized."
3992 */
3993 if (return_type->is_unsized_array()) {
3994 YYLTYPE loc = this->get_location();
3995 _mesa_glsl_error(& loc, state,
3996 "function `%s' return type array must be explicitly "
3997 "sized", name);
3998 }
3999
4000 /* From section 4.1.7 of the GLSL 4.40 spec:
4001 *
4002 * "[Opaque types] can only be declared as function parameters
4003 * or uniform-qualified variables."
4004 */
4005 if (return_type->contains_opaque()) {
4006 YYLTYPE loc = this->get_location();
4007 _mesa_glsl_error(&loc, state,
4008 "function `%s' return type can't contain an opaque type",
4009 name);
4010 }
4011
4012 /* Verify that this function's signature either doesn't match a previously
4013 * seen signature for a function with the same name, or, if a match is found,
4014 * that the previously seen signature does not have an associated definition.
4015 */
4016 f = state->symbols->get_function(name);
4017 if (f != NULL && (state->es_shader || f->has_user_signature())) {
4018 sig = f->exact_matching_signature(state, &hir_parameters);
4019 if (sig != NULL) {
4020 const char *badvar = sig->qualifiers_match(&hir_parameters);
4021 if (badvar != NULL) {
4022 YYLTYPE loc = this->get_location();
4023
4024 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
4025 "qualifiers don't match prototype", name, badvar);
4026 }
4027
4028 if (sig->return_type != return_type) {
4029 YYLTYPE loc = this->get_location();
4030
4031 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
4032 "match prototype", name);
4033 }
4034
4035 if (sig->is_defined) {
4036 if (is_definition) {
4037 YYLTYPE loc = this->get_location();
4038 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
4039 } else {
4040 /* We just encountered a prototype that exactly matches a
4041 * function that's already been defined. This is redundant,
4042 * and we should ignore it.
4043 */
4044 return NULL;
4045 }
4046 }
4047 }
4048 } else {
4049 f = new(ctx) ir_function(name);
4050 if (!state->symbols->add_function(f)) {
4051 /* This function name shadows a non-function use of the same name. */
4052 YYLTYPE loc = this->get_location();
4053
4054 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
4055 "non-function", name);
4056 return NULL;
4057 }
4058
4059 emit_function(state, f);
4060 }
4061
4062 /* Verify the return type of main() */
4063 if (strcmp(name, "main") == 0) {
4064 if (! return_type->is_void()) {
4065 YYLTYPE loc = this->get_location();
4066
4067 _mesa_glsl_error(& loc, state, "main() must return void");
4068 }
4069
4070 if (!hir_parameters.is_empty()) {
4071 YYLTYPE loc = this->get_location();
4072
4073 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
4074 }
4075 }
4076
4077 /* Finish storing the information about this new function in its signature.
4078 */
4079 if (sig == NULL) {
4080 sig = new(ctx) ir_function_signature(return_type);
4081 f->add_signature(sig);
4082 }
4083
4084 sig->replace_parameters(&hir_parameters);
4085 signature = sig;
4086
4087 /* Function declarations (prototypes) do not have r-values.
4088 */
4089 return NULL;
4090 }
4091
4092
4093 ir_rvalue *
4094 ast_function_definition::hir(exec_list *instructions,
4095 struct _mesa_glsl_parse_state *state)
4096 {
4097 prototype->is_definition = true;
4098 prototype->hir(instructions, state);
4099
4100 ir_function_signature *signature = prototype->signature;
4101 if (signature == NULL)
4102 return NULL;
4103
4104 assert(state->current_function == NULL);
4105 state->current_function = signature;
4106 state->found_return = false;
4107
4108 /* Duplicate parameters declared in the prototype as concrete variables.
4109 * Add these to the symbol table.
4110 */
4111 state->symbols->push_scope();
4112 foreach_list(n, &signature->parameters) {
4113 ir_variable *const var = ((ir_instruction *) n)->as_variable();
4114
4115 assert(var != NULL);
4116
4117 /* The only way a parameter would "exist" is if two parameters have
4118 * the same name.
4119 */
4120 if (state->symbols->name_declared_this_scope(var->name)) {
4121 YYLTYPE loc = this->get_location();
4122
4123 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
4124 } else {
4125 state->symbols->add_variable(var);
4126 }
4127 }
4128
4129 /* Convert the body of the function to HIR. */
4130 this->body->hir(&signature->body, state);
4131 signature->is_defined = true;
4132
4133 state->symbols->pop_scope();
4134
4135 assert(state->current_function == signature);
4136 state->current_function = NULL;
4137
4138 if (!signature->return_type->is_void() && !state->found_return) {
4139 YYLTYPE loc = this->get_location();
4140 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
4141 "%s, but no return statement",
4142 signature->function_name(),
4143 signature->return_type->name);
4144 }
4145
4146 /* Function definitions do not have r-values.
4147 */
4148 return NULL;
4149 }
4150
4151
4152 ir_rvalue *
4153 ast_jump_statement::hir(exec_list *instructions,
4154 struct _mesa_glsl_parse_state *state)
4155 {
4156 void *ctx = state;
4157
4158 switch (mode) {
4159 case ast_return: {
4160 ir_return *inst;
4161 assert(state->current_function);
4162
4163 if (opt_return_value) {
4164 ir_rvalue *ret = opt_return_value->hir(instructions, state);
4165
4166 /* The value of the return type can be NULL if the shader says
4167 * 'return foo();' and foo() is a function that returns void.
4168 *
4169 * NOTE: The GLSL spec doesn't say that this is an error. The type
4170 * of the return value is void. If the return type of the function is
4171 * also void, then this should compile without error. Seriously.
4172 */
4173 const glsl_type *const ret_type =
4174 (ret == NULL) ? glsl_type::void_type : ret->type;
4175
4176 /* Implicit conversions are not allowed for return values prior to
4177 * ARB_shading_language_420pack.
4178 */
4179 if (state->current_function->return_type != ret_type) {
4180 YYLTYPE loc = this->get_location();
4181
4182 if (state->ARB_shading_language_420pack_enable) {
4183 if (!apply_implicit_conversion(state->current_function->return_type,
4184 ret, state)) {
4185 _mesa_glsl_error(& loc, state,
4186 "could not implicitly convert return value "
4187 "to %s, in function `%s'",
4188 state->current_function->return_type->name,
4189 state->current_function->function_name());
4190 }
4191 } else {
4192 _mesa_glsl_error(& loc, state,
4193 "`return' with wrong type %s, in function `%s' "
4194 "returning %s",
4195 ret_type->name,
4196 state->current_function->function_name(),
4197 state->current_function->return_type->name);
4198 }
4199 } else if (state->current_function->return_type->base_type ==
4200 GLSL_TYPE_VOID) {
4201 YYLTYPE loc = this->get_location();
4202
4203 /* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.20
4204 * specs add a clarification:
4205 *
4206 * "A void function can only use return without a return argument, even if
4207 * the return argument has void type. Return statements only accept values:
4208 *
4209 * void func1() { }
4210 * void func2() { return func1(); } // illegal return statement"
4211 */
4212 _mesa_glsl_error(& loc, state,
4213 "void functions can only use `return' without a "
4214 "return argument");
4215 }
4216
4217 inst = new(ctx) ir_return(ret);
4218 } else {
4219 if (state->current_function->return_type->base_type !=
4220 GLSL_TYPE_VOID) {
4221 YYLTYPE loc = this->get_location();
4222
4223 _mesa_glsl_error(& loc, state,
4224 "`return' with no value, in function %s returning "
4225 "non-void",
4226 state->current_function->function_name());
4227 }
4228 inst = new(ctx) ir_return;
4229 }
4230
4231 state->found_return = true;
4232 instructions->push_tail(inst);
4233 break;
4234 }
4235
4236 case ast_discard:
4237 if (state->stage != MESA_SHADER_FRAGMENT) {
4238 YYLTYPE loc = this->get_location();
4239
4240 _mesa_glsl_error(& loc, state,
4241 "`discard' may only appear in a fragment shader");
4242 }
4243 instructions->push_tail(new(ctx) ir_discard);
4244 break;
4245
4246 case ast_break:
4247 case ast_continue:
4248 if (mode == ast_continue &&
4249 state->loop_nesting_ast == NULL) {
4250 YYLTYPE loc = this->get_location();
4251
4252 _mesa_glsl_error(& loc, state, "continue may only appear in a loop");
4253 } else if (mode == ast_break &&
4254 state->loop_nesting_ast == NULL &&
4255 state->switch_state.switch_nesting_ast == NULL) {
4256 YYLTYPE loc = this->get_location();
4257
4258 _mesa_glsl_error(& loc, state,
4259 "break may only appear in a loop or a switch");
4260 } else {
4261 /* For a loop, inline the for loop expression again, since we don't
4262 * know where near the end of the loop body the normal copy of it is
4263 * going to be placed. Same goes for the condition for a do-while
4264 * loop.
4265 */
4266 if (state->loop_nesting_ast != NULL &&
4267 mode == ast_continue) {
4268 if (state->loop_nesting_ast->rest_expression) {
4269 state->loop_nesting_ast->rest_expression->hir(instructions,
4270 state);
4271 }
4272 if (state->loop_nesting_ast->mode ==
4273 ast_iteration_statement::ast_do_while) {
4274 state->loop_nesting_ast->condition_to_hir(instructions, state);
4275 }
4276 }
4277
4278 if (state->switch_state.is_switch_innermost &&
4279 mode == ast_break) {
4280 /* Force break out of switch by setting is_break switch state.
4281 */
4282 ir_variable *const is_break_var = state->switch_state.is_break_var;
4283 ir_dereference_variable *const deref_is_break_var =
4284 new(ctx) ir_dereference_variable(is_break_var);
4285 ir_constant *const true_val = new(ctx) ir_constant(true);
4286 ir_assignment *const set_break_var =
4287 new(ctx) ir_assignment(deref_is_break_var, true_val);
4288
4289 instructions->push_tail(set_break_var);
4290 }
4291 else {
4292 ir_loop_jump *const jump =
4293 new(ctx) ir_loop_jump((mode == ast_break)
4294 ? ir_loop_jump::jump_break
4295 : ir_loop_jump::jump_continue);
4296 instructions->push_tail(jump);
4297 }
4298 }
4299
4300 break;
4301 }
4302
4303 /* Jump instructions do not have r-values.
4304 */
4305 return NULL;
4306 }
4307
4308
4309 ir_rvalue *
4310 ast_selection_statement::hir(exec_list *instructions,
4311 struct _mesa_glsl_parse_state *state)
4312 {
4313 void *ctx = state;
4314
4315 ir_rvalue *const condition = this->condition->hir(instructions, state);
4316
4317 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
4318 *
4319 * "Any expression whose type evaluates to a Boolean can be used as the
4320 * conditional expression bool-expression. Vector types are not accepted
4321 * as the expression to if."
4322 *
4323 * The checks are separated so that higher quality diagnostics can be
4324 * generated for cases where both rules are violated.
4325 */
4326 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
4327 YYLTYPE loc = this->condition->get_location();
4328
4329 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
4330 "boolean");
4331 }
4332
4333 ir_if *const stmt = new(ctx) ir_if(condition);
4334
4335 if (then_statement != NULL) {
4336 state->symbols->push_scope();
4337 then_statement->hir(& stmt->then_instructions, state);
4338 state->symbols->pop_scope();
4339 }
4340
4341 if (else_statement != NULL) {
4342 state->symbols->push_scope();
4343 else_statement->hir(& stmt->else_instructions, state);
4344 state->symbols->pop_scope();
4345 }
4346
4347 instructions->push_tail(stmt);
4348
4349 /* if-statements do not have r-values.
4350 */
4351 return NULL;
4352 }
4353
4354
4355 ir_rvalue *
4356 ast_switch_statement::hir(exec_list *instructions,
4357 struct _mesa_glsl_parse_state *state)
4358 {
4359 void *ctx = state;
4360
4361 ir_rvalue *const test_expression =
4362 this->test_expression->hir(instructions, state);
4363
4364 /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
4365 *
4366 * "The type of init-expression in a switch statement must be a
4367 * scalar integer."
4368 */
4369 if (!test_expression->type->is_scalar() ||
4370 !test_expression->type->is_integer()) {
4371 YYLTYPE loc = this->test_expression->get_location();
4372
4373 _mesa_glsl_error(& loc,
4374 state,
4375 "switch-statement expression must be scalar "
4376 "integer");
4377 }
4378
4379 /* Track the switch-statement nesting in a stack-like manner.
4380 */
4381 struct glsl_switch_state saved = state->switch_state;
4382
4383 state->switch_state.is_switch_innermost = true;
4384 state->switch_state.switch_nesting_ast = this;
4385 state->switch_state.labels_ht = hash_table_ctor(0, hash_table_pointer_hash,
4386 hash_table_pointer_compare);
4387 state->switch_state.previous_default = NULL;
4388
4389 /* Initalize is_fallthru state to false.
4390 */
4391 ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
4392 state->switch_state.is_fallthru_var =
4393 new(ctx) ir_variable(glsl_type::bool_type,
4394 "switch_is_fallthru_tmp",
4395 ir_var_temporary);
4396 instructions->push_tail(state->switch_state.is_fallthru_var);
4397
4398 ir_dereference_variable *deref_is_fallthru_var =
4399 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4400 instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
4401 is_fallthru_val));
4402
4403 /* Initalize is_break state to false.
4404 */
4405 ir_rvalue *const is_break_val = new (ctx) ir_constant(false);
4406 state->switch_state.is_break_var =
4407 new(ctx) ir_variable(glsl_type::bool_type,
4408 "switch_is_break_tmp",
4409 ir_var_temporary);
4410 instructions->push_tail(state->switch_state.is_break_var);
4411
4412 ir_dereference_variable *deref_is_break_var =
4413 new(ctx) ir_dereference_variable(state->switch_state.is_break_var);
4414 instructions->push_tail(new(ctx) ir_assignment(deref_is_break_var,
4415 is_break_val));
4416
4417 /* Cache test expression.
4418 */
4419 test_to_hir(instructions, state);
4420
4421 /* Emit code for body of switch stmt.
4422 */
4423 body->hir(instructions, state);
4424
4425 hash_table_dtor(state->switch_state.labels_ht);
4426
4427 state->switch_state = saved;
4428
4429 /* Switch statements do not have r-values. */
4430 return NULL;
4431 }
4432
4433
4434 void
4435 ast_switch_statement::test_to_hir(exec_list *instructions,
4436 struct _mesa_glsl_parse_state *state)
4437 {
4438 void *ctx = state;
4439
4440 /* Cache value of test expression. */
4441 ir_rvalue *const test_val =
4442 test_expression->hir(instructions,
4443 state);
4444
4445 state->switch_state.test_var = new(ctx) ir_variable(test_val->type,
4446 "switch_test_tmp",
4447 ir_var_temporary);
4448 ir_dereference_variable *deref_test_var =
4449 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4450
4451 instructions->push_tail(state->switch_state.test_var);
4452 instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));
4453 }
4454
4455
4456 ir_rvalue *
4457 ast_switch_body::hir(exec_list *instructions,
4458 struct _mesa_glsl_parse_state *state)
4459 {
4460 if (stmts != NULL)
4461 stmts->hir(instructions, state);
4462
4463 /* Switch bodies do not have r-values. */
4464 return NULL;
4465 }
4466
4467 ir_rvalue *
4468 ast_case_statement_list::hir(exec_list *instructions,
4469 struct _mesa_glsl_parse_state *state)
4470 {
4471 foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases)
4472 case_stmt->hir(instructions, state);
4473
4474 /* Case statements do not have r-values. */
4475 return NULL;
4476 }
4477
4478 ir_rvalue *
4479 ast_case_statement::hir(exec_list *instructions,
4480 struct _mesa_glsl_parse_state *state)
4481 {
4482 labels->hir(instructions, state);
4483
4484 /* Conditionally set fallthru state based on break state. */
4485 ir_constant *const false_val = new(state) ir_constant(false);
4486 ir_dereference_variable *const deref_is_fallthru_var =
4487 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
4488 ir_dereference_variable *const deref_is_break_var =
4489 new(state) ir_dereference_variable(state->switch_state.is_break_var);
4490 ir_assignment *const reset_fallthru_on_break =
4491 new(state) ir_assignment(deref_is_fallthru_var,
4492 false_val,
4493 deref_is_break_var);
4494 instructions->push_tail(reset_fallthru_on_break);
4495
4496 /* Guard case statements depending on fallthru state. */
4497 ir_dereference_variable *const deref_fallthru_guard =
4498 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
4499 ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
4500
4501 foreach_list_typed (ast_node, stmt, link, & this->stmts)
4502 stmt->hir(& test_fallthru->then_instructions, state);
4503
4504 instructions->push_tail(test_fallthru);
4505
4506 /* Case statements do not have r-values. */
4507 return NULL;
4508 }
4509
4510
4511 ir_rvalue *
4512 ast_case_label_list::hir(exec_list *instructions,
4513 struct _mesa_glsl_parse_state *state)
4514 {
4515 foreach_list_typed (ast_case_label, label, link, & this->labels)
4516 label->hir(instructions, state);
4517
4518 /* Case labels do not have r-values. */
4519 return NULL;
4520 }
4521
4522 ir_rvalue *
4523 ast_case_label::hir(exec_list *instructions,
4524 struct _mesa_glsl_parse_state *state)
4525 {
4526 void *ctx = state;
4527
4528 ir_dereference_variable *deref_fallthru_var =
4529 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4530
4531 ir_rvalue *const true_val = new(ctx) ir_constant(true);
4532
4533 /* If not default case, ... */
4534 if (this->test_value != NULL) {
4535 /* Conditionally set fallthru state based on
4536 * comparison of cached test expression value to case label.
4537 */
4538 ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
4539 ir_constant *label_const = label_rval->constant_expression_value();
4540
4541 if (!label_const) {
4542 YYLTYPE loc = this->test_value->get_location();
4543
4544 _mesa_glsl_error(& loc, state,
4545 "switch statement case label must be a "
4546 "constant expression");
4547
4548 /* Stuff a dummy value in to allow processing to continue. */
4549 label_const = new(ctx) ir_constant(0);
4550 } else {
4551 ast_expression *previous_label = (ast_expression *)
4552 hash_table_find(state->switch_state.labels_ht,
4553 (void *)(uintptr_t)label_const->value.u[0]);
4554
4555 if (previous_label) {
4556 YYLTYPE loc = this->test_value->get_location();
4557 _mesa_glsl_error(& loc, state, "duplicate case value");
4558
4559 loc = previous_label->get_location();
4560 _mesa_glsl_error(& loc, state, "this is the previous case label");
4561 } else {
4562 hash_table_insert(state->switch_state.labels_ht,
4563 this->test_value,
4564 (void *)(uintptr_t)label_const->value.u[0]);
4565 }
4566 }
4567
4568 ir_dereference_variable *deref_test_var =
4569 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4570
4571 ir_rvalue *const test_cond = new(ctx) ir_expression(ir_binop_all_equal,
4572 label_const,
4573 deref_test_var);
4574
4575 ir_assignment *set_fallthru_on_test =
4576 new(ctx) ir_assignment(deref_fallthru_var, true_val, test_cond);
4577
4578 instructions->push_tail(set_fallthru_on_test);
4579 } else { /* default case */
4580 if (state->switch_state.previous_default) {
4581 YYLTYPE loc = this->get_location();
4582 _mesa_glsl_error(& loc, state,
4583 "multiple default labels in one switch");
4584
4585 loc = state->switch_state.previous_default->get_location();
4586 _mesa_glsl_error(& loc, state, "this is the first default label");
4587 }
4588 state->switch_state.previous_default = this;
4589
4590 /* Set falltrhu state. */
4591 ir_assignment *set_fallthru =
4592 new(ctx) ir_assignment(deref_fallthru_var, true_val);
4593
4594 instructions->push_tail(set_fallthru);
4595 }
4596
4597 /* Case statements do not have r-values. */
4598 return NULL;
4599 }
4600
4601 void
4602 ast_iteration_statement::condition_to_hir(exec_list *instructions,
4603 struct _mesa_glsl_parse_state *state)
4604 {
4605 void *ctx = state;
4606
4607 if (condition != NULL) {
4608 ir_rvalue *const cond =
4609 condition->hir(instructions, state);
4610
4611 if ((cond == NULL)
4612 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
4613 YYLTYPE loc = condition->get_location();
4614
4615 _mesa_glsl_error(& loc, state,
4616 "loop condition must be scalar boolean");
4617 } else {
4618 /* As the first code in the loop body, generate a block that looks
4619 * like 'if (!condition) break;' as the loop termination condition.
4620 */
4621 ir_rvalue *const not_cond =
4622 new(ctx) ir_expression(ir_unop_logic_not, cond);
4623
4624 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
4625
4626 ir_jump *const break_stmt =
4627 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
4628
4629 if_stmt->then_instructions.push_tail(break_stmt);
4630 instructions->push_tail(if_stmt);
4631 }
4632 }
4633 }
4634
4635
4636 ir_rvalue *
4637 ast_iteration_statement::hir(exec_list *instructions,
4638 struct _mesa_glsl_parse_state *state)
4639 {
4640 void *ctx = state;
4641
4642 /* For-loops and while-loops start a new scope, but do-while loops do not.
4643 */
4644 if (mode != ast_do_while)
4645 state->symbols->push_scope();
4646
4647 if (init_statement != NULL)
4648 init_statement->hir(instructions, state);
4649
4650 ir_loop *const stmt = new(ctx) ir_loop();
4651 instructions->push_tail(stmt);
4652
4653 /* Track the current loop nesting. */
4654 ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
4655
4656 state->loop_nesting_ast = this;
4657
4658 /* Likewise, indicate that following code is closest to a loop,
4659 * NOT closest to a switch.
4660 */
4661 bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
4662 state->switch_state.is_switch_innermost = false;
4663
4664 if (mode != ast_do_while)
4665 condition_to_hir(&stmt->body_instructions, state);
4666
4667 if (body != NULL)
4668 body->hir(& stmt->body_instructions, state);
4669
4670 if (rest_expression != NULL)
4671 rest_expression->hir(& stmt->body_instructions, state);
4672
4673 if (mode == ast_do_while)
4674 condition_to_hir(&stmt->body_instructions, state);
4675
4676 if (mode != ast_do_while)
4677 state->symbols->pop_scope();
4678
4679 /* Restore previous nesting before returning. */
4680 state->loop_nesting_ast = nesting_ast;
4681 state->switch_state.is_switch_innermost = saved_is_switch_innermost;
4682
4683 /* Loops do not have r-values.
4684 */
4685 return NULL;
4686 }
4687
4688
4689 /**
4690 * Determine if the given type is valid for establishing a default precision
4691 * qualifier.
4692 *
4693 * From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):
4694 *
4695 * "The precision statement
4696 *
4697 * precision precision-qualifier type;
4698 *
4699 * can be used to establish a default precision qualifier. The type field
4700 * can be either int or float or any of the sampler types, and the
4701 * precision-qualifier can be lowp, mediump, or highp."
4702 *
4703 * GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision
4704 * qualifiers on sampler types, but this seems like an oversight (since the
4705 * intention of including these in GLSL 1.30 is to allow compatibility with ES
4706 * shaders). So we allow int, float, and all sampler types regardless of GLSL
4707 * version.
4708 */
4709 static bool
4710 is_valid_default_precision_type(const struct glsl_type *const type)
4711 {
4712 if (type == NULL)
4713 return false;
4714
4715 switch (type->base_type) {
4716 case GLSL_TYPE_INT:
4717 case GLSL_TYPE_FLOAT:
4718 /* "int" and "float" are valid, but vectors and matrices are not. */
4719 return type->vector_elements == 1 && type->matrix_columns == 1;
4720 case GLSL_TYPE_SAMPLER:
4721 return true;
4722 default:
4723 return false;
4724 }
4725 }
4726
4727
4728 ir_rvalue *
4729 ast_type_specifier::hir(exec_list *instructions,
4730 struct _mesa_glsl_parse_state *state)
4731 {
4732 if (this->default_precision == ast_precision_none && this->structure == NULL)
4733 return NULL;
4734
4735 YYLTYPE loc = this->get_location();
4736
4737 /* If this is a precision statement, check that the type to which it is
4738 * applied is either float or int.
4739 *
4740 * From section 4.5.3 of the GLSL 1.30 spec:
4741 * "The precision statement
4742 * precision precision-qualifier type;
4743 * can be used to establish a default precision qualifier. The type
4744 * field can be either int or float [...]. Any other types or
4745 * qualifiers will result in an error.
4746 */
4747 if (this->default_precision != ast_precision_none) {
4748 if (!state->check_precision_qualifiers_allowed(&loc))
4749 return NULL;
4750
4751 if (this->structure != NULL) {
4752 _mesa_glsl_error(&loc, state,
4753 "precision qualifiers do not apply to structures");
4754 return NULL;
4755 }
4756
4757 if (this->array_specifier != NULL) {
4758 _mesa_glsl_error(&loc, state,
4759 "default precision statements do not apply to "
4760 "arrays");
4761 return NULL;
4762 }
4763
4764 const struct glsl_type *const type =
4765 state->symbols->get_type(this->type_name);
4766 if (!is_valid_default_precision_type(type)) {
4767 _mesa_glsl_error(&loc, state,
4768 "default precision statements apply only to "
4769 "float, int, and sampler types");
4770 return NULL;
4771 }
4772
4773 if (type->base_type == GLSL_TYPE_FLOAT
4774 && state->es_shader
4775 && state->stage == MESA_SHADER_FRAGMENT) {
4776 /* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.00
4777 * spec says:
4778 *
4779 * "The fragment language has no default precision qualifier for
4780 * floating point types."
4781 *
4782 * As a result, we have to track whether or not default precision has
4783 * been specified for float in GLSL ES fragment shaders.
4784 *
4785 * Earlier in that same section, the spec says:
4786 *
4787 * "Non-precision qualified declarations will use the precision
4788 * qualifier specified in the most recent precision statement
4789 * that is still in scope. The precision statement has the same
4790 * scoping rules as variable declarations. If it is declared
4791 * inside a compound statement, its effect stops at the end of
4792 * the innermost statement it was declared in. Precision
4793 * statements in nested scopes override precision statements in
4794 * outer scopes. Multiple precision statements for the same basic
4795 * type can appear inside the same scope, with later statements
4796 * overriding earlier statements within that scope."
4797 *
4798 * Default precision specifications follow the same scope rules as
4799 * variables. So, we can track the state of the default float
4800 * precision in the symbol table, and the rules will just work. This
4801 * is a slight abuse of the symbol table, but it has the semantics
4802 * that we want.
4803 */
4804 ir_variable *const junk =
4805 new(state) ir_variable(type, "#default precision",
4806 ir_var_temporary);
4807
4808 state->symbols->add_variable(junk);
4809 }
4810
4811 /* FINISHME: Translate precision statements into IR. */
4812 return NULL;
4813 }
4814
4815 /* _mesa_ast_set_aggregate_type() sets the <structure> field so that
4816 * process_record_constructor() can do type-checking on C-style initializer
4817 * expressions of structs, but ast_struct_specifier should only be translated
4818 * to HIR if it is declaring the type of a structure.
4819 *
4820 * The ->is_declaration field is false for initializers of variables
4821 * declared separately from the struct's type definition.
4822 *
4823 * struct S { ... }; (is_declaration = true)
4824 * struct T { ... } t = { ... }; (is_declaration = true)
4825 * S s = { ... }; (is_declaration = false)
4826 */
4827 if (this->structure != NULL && this->structure->is_declaration)
4828 return this->structure->hir(instructions, state);
4829
4830 return NULL;
4831 }
4832
4833
4834 /**
4835 * Process a structure or interface block tree into an array of structure fields
4836 *
4837 * After parsing, where there are some syntax differnces, structures and
4838 * interface blocks are almost identical. They are similar enough that the
4839 * AST for each can be processed the same way into a set of
4840 * \c glsl_struct_field to describe the members.
4841 *
4842 * If we're processing an interface block, var_mode should be the type of the
4843 * interface block (ir_var_shader_in, ir_var_shader_out, or ir_var_uniform).
4844 * If we're processing a structure, var_mode should be ir_var_auto.
4845 *
4846 * \return
4847 * The number of fields processed. A pointer to the array structure fields is
4848 * stored in \c *fields_ret.
4849 */
4850 unsigned
4851 ast_process_structure_or_interface_block(exec_list *instructions,
4852 struct _mesa_glsl_parse_state *state,
4853 exec_list *declarations,
4854 YYLTYPE &loc,
4855 glsl_struct_field **fields_ret,
4856 bool is_interface,
4857 bool block_row_major,
4858 bool allow_reserved_names,
4859 ir_variable_mode var_mode)
4860 {
4861 unsigned decl_count = 0;
4862
4863 /* Make an initial pass over the list of fields to determine how
4864 * many there are. Each element in this list is an ast_declarator_list.
4865 * This means that we actually need to count the number of elements in the
4866 * 'declarations' list in each of the elements.
4867 */
4868 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
4869 foreach_list_const (decl_ptr, & decl_list->declarations) {
4870 decl_count++;
4871 }
4872 }
4873
4874 /* Allocate storage for the fields and process the field
4875 * declarations. As the declarations are processed, try to also convert
4876 * the types to HIR. This ensures that structure definitions embedded in
4877 * other structure definitions or in interface blocks are processed.
4878 */
4879 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
4880 decl_count);
4881
4882 unsigned i = 0;
4883 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
4884 const char *type_name;
4885
4886 decl_list->type->specifier->hir(instructions, state);
4887
4888 /* Section 10.9 of the GLSL ES 1.00 specification states that
4889 * embedded structure definitions have been removed from the language.
4890 */
4891 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
4892 _mesa_glsl_error(&loc, state, "embedded structure definitions are "
4893 "not allowed in GLSL ES 1.00");
4894 }
4895
4896 const glsl_type *decl_type =
4897 decl_list->type->glsl_type(& type_name, state);
4898
4899 foreach_list_typed (ast_declaration, decl, link,
4900 &decl_list->declarations) {
4901 if (!allow_reserved_names)
4902 validate_identifier(decl->identifier, loc, state);
4903
4904 /* From section 4.3.9 of the GLSL 4.40 spec:
4905 *
4906 * "[In interface blocks] opaque types are not allowed."
4907 *
4908 * It should be impossible for decl_type to be NULL here. Cases that
4909 * might naturally lead to decl_type being NULL, especially for the
4910 * is_interface case, will have resulted in compilation having
4911 * already halted due to a syntax error.
4912 */
4913 const struct glsl_type *field_type =
4914 decl_type != NULL ? decl_type : glsl_type::error_type;
4915
4916 if (is_interface && field_type->contains_opaque()) {
4917 YYLTYPE loc = decl_list->get_location();
4918 _mesa_glsl_error(&loc, state,
4919 "uniform in non-default uniform block contains "
4920 "opaque variable");
4921 }
4922
4923 if (field_type->contains_atomic()) {
4924 /* FINISHME: Add a spec quotation here once updated spec
4925 * FINISHME: language is available. See Khronos bug #10903
4926 * FINISHME: on whether atomic counters are allowed in
4927 * FINISHME: structures.
4928 */
4929 YYLTYPE loc = decl_list->get_location();
4930 _mesa_glsl_error(&loc, state, "atomic counter in structure or "
4931 "uniform block");
4932 }
4933
4934 if (field_type->contains_image()) {
4935 /* FINISHME: Same problem as with atomic counters.
4936 * FINISHME: Request clarification from Khronos and add
4937 * FINISHME: spec quotation here.
4938 */
4939 YYLTYPE loc = decl_list->get_location();
4940 _mesa_glsl_error(&loc, state,
4941 "image in structure or uniform block");
4942 }
4943
4944 const struct ast_type_qualifier *const qual =
4945 & decl_list->type->qualifier;
4946 if (qual->flags.q.std140 ||
4947 qual->flags.q.packed ||
4948 qual->flags.q.shared) {
4949 _mesa_glsl_error(&loc, state,
4950 "uniform block layout qualifiers std140, packed, and "
4951 "shared can only be applied to uniform blocks, not "
4952 "members");
4953 }
4954
4955 field_type = process_array_type(&loc, decl_type,
4956 decl->array_specifier, state);
4957 fields[i].type = field_type;
4958 fields[i].name = decl->identifier;
4959 fields[i].location = -1;
4960 fields[i].interpolation =
4961 interpret_interpolation_qualifier(qual, var_mode, state, &loc);
4962 fields[i].centroid = qual->flags.q.centroid ? 1 : 0;
4963 fields[i].sample = qual->flags.q.sample ? 1 : 0;
4964
4965 if (qual->flags.q.row_major || qual->flags.q.column_major) {
4966 if (!qual->flags.q.uniform) {
4967 _mesa_glsl_error(&loc, state,
4968 "row_major and column_major can only be "
4969 "applied to uniform interface blocks");
4970 } else
4971 validate_matrix_layout_for_type(state, &loc, field_type, NULL);
4972 }
4973
4974 if (qual->flags.q.uniform && qual->has_interpolation()) {
4975 _mesa_glsl_error(&loc, state,
4976 "interpolation qualifiers cannot be used "
4977 "with uniform interface blocks");
4978 }
4979
4980 if (field_type->is_matrix() ||
4981 (field_type->is_array() && field_type->fields.array->is_matrix())) {
4982 fields[i].row_major = block_row_major;
4983 if (qual->flags.q.row_major)
4984 fields[i].row_major = true;
4985 else if (qual->flags.q.column_major)
4986 fields[i].row_major = false;
4987 }
4988
4989 i++;
4990 }
4991 }
4992
4993 assert(i == decl_count);
4994
4995 *fields_ret = fields;
4996 return decl_count;
4997 }
4998
4999
5000 ir_rvalue *
5001 ast_struct_specifier::hir(exec_list *instructions,
5002 struct _mesa_glsl_parse_state *state)
5003 {
5004 YYLTYPE loc = this->get_location();
5005
5006 /* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:
5007 *
5008 * "Anonymous structures are not supported; so embedded structures must
5009 * have a declarator. A name given to an embedded struct is scoped at
5010 * the same level as the struct it is embedded in."
5011 *
5012 * The same section of the GLSL 1.20 spec says:
5013 *
5014 * "Anonymous structures are not supported. Embedded structures are not
5015 * supported.
5016 *
5017 * struct S { float f; };
5018 * struct T {
5019 * S; // Error: anonymous structures disallowed
5020 * struct { ... }; // Error: embedded structures disallowed
5021 * S s; // Okay: nested structures with name are allowed
5022 * };"
5023 *
5024 * The GLSL ES 1.00 and 3.00 specs have similar langauge and examples. So,
5025 * we allow embedded structures in 1.10 only.
5026 */
5027 if (state->language_version != 110 && state->struct_specifier_depth != 0)
5028 _mesa_glsl_error(&loc, state,
5029 "embedded structure declartions are not allowed");
5030
5031 state->struct_specifier_depth++;
5032
5033 glsl_struct_field *fields;
5034 unsigned decl_count =
5035 ast_process_structure_or_interface_block(instructions,
5036 state,
5037 &this->declarations,
5038 loc,
5039 &fields,
5040 false,
5041 false,
5042 false /* allow_reserved_names */,
5043 ir_var_auto);
5044
5045 validate_identifier(this->name, loc, state);
5046
5047 const glsl_type *t =
5048 glsl_type::get_record_instance(fields, decl_count, this->name);
5049
5050 if (!state->symbols->add_type(name, t)) {
5051 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
5052 } else {
5053 const glsl_type **s = reralloc(state, state->user_structures,
5054 const glsl_type *,
5055 state->num_user_structures + 1);
5056 if (s != NULL) {
5057 s[state->num_user_structures] = t;
5058 state->user_structures = s;
5059 state->num_user_structures++;
5060 }
5061 }
5062
5063 state->struct_specifier_depth--;
5064
5065 /* Structure type definitions do not have r-values.
5066 */
5067 return NULL;
5068 }
5069
5070
5071 /**
5072 * Visitor class which detects whether a given interface block has been used.
5073 */
5074 class interface_block_usage_visitor : public ir_hierarchical_visitor
5075 {
5076 public:
5077 interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)
5078 : mode(mode), block(block), found(false)
5079 {
5080 }
5081
5082 virtual ir_visitor_status visit(ir_dereference_variable *ir)
5083 {
5084 if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {
5085 found = true;
5086 return visit_stop;
5087 }
5088 return visit_continue;
5089 }
5090
5091 bool usage_found() const
5092 {
5093 return this->found;
5094 }
5095
5096 private:
5097 ir_variable_mode mode;
5098 const glsl_type *block;
5099 bool found;
5100 };
5101
5102
5103 ir_rvalue *
5104 ast_interface_block::hir(exec_list *instructions,
5105 struct _mesa_glsl_parse_state *state)
5106 {
5107 YYLTYPE loc = this->get_location();
5108
5109 /* The ast_interface_block has a list of ast_declarator_lists. We
5110 * need to turn those into ir_variables with an association
5111 * with this uniform block.
5112 */
5113 enum glsl_interface_packing packing;
5114 if (this->layout.flags.q.shared) {
5115 packing = GLSL_INTERFACE_PACKING_SHARED;
5116 } else if (this->layout.flags.q.packed) {
5117 packing = GLSL_INTERFACE_PACKING_PACKED;
5118 } else {
5119 /* The default layout is std140.
5120 */
5121 packing = GLSL_INTERFACE_PACKING_STD140;
5122 }
5123
5124 ir_variable_mode var_mode;
5125 const char *iface_type_name;
5126 if (this->layout.flags.q.in) {
5127 var_mode = ir_var_shader_in;
5128 iface_type_name = "in";
5129 } else if (this->layout.flags.q.out) {
5130 var_mode = ir_var_shader_out;
5131 iface_type_name = "out";
5132 } else if (this->layout.flags.q.uniform) {
5133 var_mode = ir_var_uniform;
5134 iface_type_name = "uniform";
5135 } else {
5136 var_mode = ir_var_auto;
5137 iface_type_name = "UNKNOWN";
5138 assert(!"interface block layout qualifier not found!");
5139 }
5140
5141 bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;
5142 bool block_row_major = this->layout.flags.q.row_major;
5143 exec_list declared_variables;
5144 glsl_struct_field *fields;
5145 unsigned int num_variables =
5146 ast_process_structure_or_interface_block(&declared_variables,
5147 state,
5148 &this->declarations,
5149 loc,
5150 &fields,
5151 true,
5152 block_row_major,
5153 redeclaring_per_vertex,
5154 var_mode);
5155
5156 if (!redeclaring_per_vertex)
5157 validate_identifier(this->block_name, loc, state);
5158
5159 const glsl_type *earlier_per_vertex = NULL;
5160 if (redeclaring_per_vertex) {
5161 /* Find the previous declaration of gl_PerVertex. If we're redeclaring
5162 * the named interface block gl_in, we can find it by looking at the
5163 * previous declaration of gl_in. Otherwise we can find it by looking
5164 * at the previous decalartion of any of the built-in outputs,
5165 * e.g. gl_Position.
5166 *
5167 * Also check that the instance name and array-ness of the redeclaration
5168 * are correct.
5169 */
5170 switch (var_mode) {
5171 case ir_var_shader_in:
5172 if (ir_variable *earlier_gl_in =
5173 state->symbols->get_variable("gl_in")) {
5174 earlier_per_vertex = earlier_gl_in->get_interface_type();
5175 } else {
5176 _mesa_glsl_error(&loc, state,
5177 "redeclaration of gl_PerVertex input not allowed "
5178 "in the %s shader",
5179 _mesa_shader_stage_to_string(state->stage));
5180 }
5181 if (this->instance_name == NULL ||
5182 strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL) {
5183 _mesa_glsl_error(&loc, state,
5184 "gl_PerVertex input must be redeclared as "
5185 "gl_in[]");
5186 }
5187 break;
5188 case ir_var_shader_out:
5189 if (ir_variable *earlier_gl_Position =
5190 state->symbols->get_variable("gl_Position")) {
5191 earlier_per_vertex = earlier_gl_Position->get_interface_type();
5192 } else {
5193 _mesa_glsl_error(&loc, state,
5194 "redeclaration of gl_PerVertex output not "
5195 "allowed in the %s shader",
5196 _mesa_shader_stage_to_string(state->stage));
5197 }
5198 if (this->instance_name != NULL) {
5199 _mesa_glsl_error(&loc, state,
5200 "gl_PerVertex input may not be redeclared with "
5201 "an instance name");
5202 }
5203 break;
5204 default:
5205 _mesa_glsl_error(&loc, state,
5206 "gl_PerVertex must be declared as an input or an "
5207 "output");
5208 break;
5209 }
5210
5211 if (earlier_per_vertex == NULL) {
5212 /* An error has already been reported. Bail out to avoid null
5213 * dereferences later in this function.
5214 */
5215 return NULL;
5216 }
5217
5218 /* Copy locations from the old gl_PerVertex interface block. */
5219 for (unsigned i = 0; i < num_variables; i++) {
5220 int j = earlier_per_vertex->field_index(fields[i].name);
5221 if (j == -1) {
5222 _mesa_glsl_error(&loc, state,
5223 "redeclaration of gl_PerVertex must be a subset "
5224 "of the built-in members of gl_PerVertex");
5225 } else {
5226 fields[i].location =
5227 earlier_per_vertex->fields.structure[j].location;
5228 fields[i].interpolation =
5229 earlier_per_vertex->fields.structure[j].interpolation;
5230 fields[i].centroid =
5231 earlier_per_vertex->fields.structure[j].centroid;
5232 fields[i].sample =
5233 earlier_per_vertex->fields.structure[j].sample;
5234 }
5235 }
5236
5237 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10
5238 * spec:
5239 *
5240 * If a built-in interface block is redeclared, it must appear in
5241 * the shader before any use of any member included in the built-in
5242 * declaration, or a compilation error will result.
5243 *
5244 * This appears to be a clarification to the behaviour established for
5245 * gl_PerVertex by GLSL 1.50, therefore we implement this behaviour
5246 * regardless of GLSL version.
5247 */
5248 interface_block_usage_visitor v(var_mode, earlier_per_vertex);
5249 v.run(instructions);
5250 if (v.usage_found()) {
5251 _mesa_glsl_error(&loc, state,
5252 "redeclaration of a built-in interface block must "
5253 "appear before any use of any member of the "
5254 "interface block");
5255 }
5256 }
5257
5258 const glsl_type *block_type =
5259 glsl_type::get_interface_instance(fields,
5260 num_variables,
5261 packing,
5262 this->block_name);
5263
5264 if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {
5265 YYLTYPE loc = this->get_location();
5266 _mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "
5267 "already taken in the current scope",
5268 this->block_name, iface_type_name);
5269 }
5270
5271 /* Since interface blocks cannot contain statements, it should be
5272 * impossible for the block to generate any instructions.
5273 */
5274 assert(declared_variables.is_empty());
5275
5276 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
5277 *
5278 * Geometry shader input variables get the per-vertex values written
5279 * out by vertex shader output variables of the same names. Since a
5280 * geometry shader operates on a set of vertices, each input varying
5281 * variable (or input block, see interface blocks below) needs to be
5282 * declared as an array.
5283 */
5284 if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&
5285 var_mode == ir_var_shader_in) {
5286 _mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");
5287 }
5288
5289 /* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec
5290 * says:
5291 *
5292 * "If an instance name (instance-name) is used, then it puts all the
5293 * members inside a scope within its own name space, accessed with the
5294 * field selector ( . ) operator (analogously to structures)."
5295 */
5296 if (this->instance_name) {
5297 if (redeclaring_per_vertex) {
5298 /* When a built-in in an unnamed interface block is redeclared,
5299 * get_variable_being_redeclared() calls
5300 * check_builtin_array_max_size() to make sure that built-in array
5301 * variables aren't redeclared to illegal sizes. But we're looking
5302 * at a redeclaration of a named built-in interface block. So we
5303 * have to manually call check_builtin_array_max_size() for all parts
5304 * of the interface that are arrays.
5305 */
5306 for (unsigned i = 0; i < num_variables; i++) {
5307 if (fields[i].type->is_array()) {
5308 const unsigned size = fields[i].type->array_size();
5309 check_builtin_array_max_size(fields[i].name, size, loc, state);
5310 }
5311 }
5312 } else {
5313 validate_identifier(this->instance_name, loc, state);
5314 }
5315
5316 ir_variable *var;
5317
5318 if (this->array_specifier != NULL) {
5319 /* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:
5320 *
5321 * For uniform blocks declared an array, each individual array
5322 * element corresponds to a separate buffer object backing one
5323 * instance of the block. As the array size indicates the number
5324 * of buffer objects needed, uniform block array declarations
5325 * must specify an array size.
5326 *
5327 * And a few paragraphs later:
5328 *
5329 * Geometry shader input blocks must be declared as arrays and
5330 * follow the array declaration and linking rules for all
5331 * geometry shader inputs. All other input and output block
5332 * arrays must specify an array size.
5333 *
5334 * The upshot of this is that the only circumstance where an
5335 * interface array size *doesn't* need to be specified is on a
5336 * geometry shader input.
5337 */
5338 if (this->array_specifier->is_unsized_array &&
5339 (state->stage != MESA_SHADER_GEOMETRY || !this->layout.flags.q.in)) {
5340 _mesa_glsl_error(&loc, state,
5341 "only geometry shader inputs may be unsized "
5342 "instance block arrays");
5343
5344 }
5345
5346 const glsl_type *block_array_type =
5347 process_array_type(&loc, block_type, this->array_specifier, state);
5348
5349 var = new(state) ir_variable(block_array_type,
5350 this->instance_name,
5351 var_mode);
5352 } else {
5353 var = new(state) ir_variable(block_type,
5354 this->instance_name,
5355 var_mode);
5356 }
5357
5358 if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)
5359 handle_geometry_shader_input_decl(state, loc, var);
5360
5361 if (ir_variable *earlier =
5362 state->symbols->get_variable(this->instance_name)) {
5363 if (!redeclaring_per_vertex) {
5364 _mesa_glsl_error(&loc, state, "`%s' redeclared",
5365 this->instance_name);
5366 }
5367 earlier->data.how_declared = ir_var_declared_normally;
5368 earlier->type = var->type;
5369 earlier->reinit_interface_type(block_type);
5370 delete var;
5371 } else {
5372 /* Propagate the "binding" keyword into this UBO's fields;
5373 * the UBO declaration itself doesn't get an ir_variable unless it
5374 * has an instance name. This is ugly.
5375 */
5376 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
5377 var->data.binding = this->layout.binding;
5378
5379 state->symbols->add_variable(var);
5380 instructions->push_tail(var);
5381 }
5382 } else {
5383 /* In order to have an array size, the block must also be declared with
5384 * an instance name.
5385 */
5386 assert(this->array_specifier == NULL);
5387
5388 for (unsigned i = 0; i < num_variables; i++) {
5389 ir_variable *var =
5390 new(state) ir_variable(fields[i].type,
5391 ralloc_strdup(state, fields[i].name),
5392 var_mode);
5393 var->data.interpolation = fields[i].interpolation;
5394 var->data.centroid = fields[i].centroid;
5395 var->data.sample = fields[i].sample;
5396 var->init_interface_type(block_type);
5397
5398 if (redeclaring_per_vertex) {
5399 ir_variable *earlier =
5400 get_variable_being_redeclared(var, loc, state,
5401 true /* allow_all_redeclarations */);
5402 if (strncmp(var->name, "gl_", 3) != 0 || earlier == NULL) {
5403 _mesa_glsl_error(&loc, state,
5404 "redeclaration of gl_PerVertex can only "
5405 "include built-in variables");
5406 } else if (earlier->data.how_declared == ir_var_declared_normally) {
5407 _mesa_glsl_error(&loc, state,
5408 "`%s' has already been redeclared", var->name);
5409 } else {
5410 earlier->data.how_declared = ir_var_declared_in_block;
5411 earlier->reinit_interface_type(block_type);
5412 }
5413 continue;
5414 }
5415
5416 if (state->symbols->get_variable(var->name) != NULL)
5417 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
5418
5419 /* Propagate the "binding" keyword into this UBO's fields;
5420 * the UBO declaration itself doesn't get an ir_variable unless it
5421 * has an instance name. This is ugly.
5422 */
5423 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
5424 var->data.binding = this->layout.binding;
5425
5426 state->symbols->add_variable(var);
5427 instructions->push_tail(var);
5428 }
5429
5430 if (redeclaring_per_vertex && block_type != earlier_per_vertex) {
5431 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:
5432 *
5433 * It is also a compilation error ... to redeclare a built-in
5434 * block and then use a member from that built-in block that was
5435 * not included in the redeclaration.
5436 *
5437 * This appears to be a clarification to the behaviour established
5438 * for gl_PerVertex by GLSL 1.50, therefore we implement this
5439 * behaviour regardless of GLSL version.
5440 *
5441 * To prevent the shader from using a member that was not included in
5442 * the redeclaration, we disable any ir_variables that are still
5443 * associated with the old declaration of gl_PerVertex (since we've
5444 * already updated all of the variables contained in the new
5445 * gl_PerVertex to point to it).
5446 *
5447 * As a side effect this will prevent
5448 * validate_intrastage_interface_blocks() from getting confused and
5449 * thinking there are conflicting definitions of gl_PerVertex in the
5450 * shader.
5451 */
5452 foreach_list_safe(node, instructions) {
5453 ir_variable *const var = ((ir_instruction *) node)->as_variable();
5454 if (var != NULL &&
5455 var->get_interface_type() == earlier_per_vertex &&
5456 var->data.mode == var_mode) {
5457 if (var->data.how_declared == ir_var_declared_normally) {
5458 _mesa_glsl_error(&loc, state,
5459 "redeclaration of gl_PerVertex cannot "
5460 "follow a redeclaration of `%s'",
5461 var->name);
5462 }
5463 state->symbols->disable_variable(var->name);
5464 var->remove();
5465 }
5466 }
5467 }
5468 }
5469
5470 return NULL;
5471 }
5472
5473
5474 ir_rvalue *
5475 ast_gs_input_layout::hir(exec_list *instructions,
5476 struct _mesa_glsl_parse_state *state)
5477 {
5478 YYLTYPE loc = this->get_location();
5479
5480 /* If any geometry input layout declaration preceded this one, make sure it
5481 * was consistent with this one.
5482 */
5483 if (state->gs_input_prim_type_specified &&
5484 state->in_qualifier->prim_type != this->prim_type) {
5485 _mesa_glsl_error(&loc, state,
5486 "geometry shader input layout does not match"
5487 " previous declaration");
5488 return NULL;
5489 }
5490
5491 /* If any shader inputs occurred before this declaration and specified an
5492 * array size, make sure the size they specified is consistent with the
5493 * primitive type.
5494 */
5495 unsigned num_vertices = vertices_per_prim(this->prim_type);
5496 if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {
5497 _mesa_glsl_error(&loc, state,
5498 "this geometry shader input layout implies %u vertices"
5499 " per primitive, but a previous input is declared"
5500 " with size %u", num_vertices, state->gs_input_size);
5501 return NULL;
5502 }
5503
5504 state->gs_input_prim_type_specified = true;
5505
5506 /* If any shader inputs occurred before this declaration and did not
5507 * specify an array size, their size is determined now.
5508 */
5509 foreach_list (node, instructions) {
5510 ir_variable *var = ((ir_instruction *) node)->as_variable();
5511 if (var == NULL || var->data.mode != ir_var_shader_in)
5512 continue;
5513
5514 /* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an
5515 * array; skip it.
5516 */
5517
5518 if (var->type->is_unsized_array()) {
5519 if (var->data.max_array_access >= num_vertices) {
5520 _mesa_glsl_error(&loc, state,
5521 "this geometry shader input layout implies %u"
5522 " vertices, but an access to element %u of input"
5523 " `%s' already exists", num_vertices,
5524 var->data.max_array_access, var->name);
5525 } else {
5526 var->type = glsl_type::get_array_instance(var->type->fields.array,
5527 num_vertices);
5528 }
5529 }
5530 }
5531
5532 return NULL;
5533 }
5534
5535
5536 ir_rvalue *
5537 ast_cs_input_layout::hir(exec_list *instructions,
5538 struct _mesa_glsl_parse_state *state)
5539 {
5540 YYLTYPE loc = this->get_location();
5541
5542 /* If any compute input layout declaration preceded this one, make sure it
5543 * was consistent with this one.
5544 */
5545 if (state->cs_input_local_size_specified) {
5546 for (int i = 0; i < 3; i++) {
5547 if (state->cs_input_local_size[i] != this->local_size[i]) {
5548 _mesa_glsl_error(&loc, state,
5549 "compute shader input layout does not match"
5550 " previous declaration");
5551 return NULL;
5552 }
5553 }
5554 }
5555
5556 /* From the ARB_compute_shader specification:
5557 *
5558 * If the local size of the shader in any dimension is greater
5559 * than the maximum size supported by the implementation for that
5560 * dimension, a compile-time error results.
5561 *
5562 * It is not clear from the spec how the error should be reported if
5563 * the total size of the work group exceeds
5564 * MAX_COMPUTE_WORK_GROUP_INVOCATIONS, but it seems reasonable to
5565 * report it at compile time as well.
5566 */
5567 GLuint64 total_invocations = 1;
5568 for (int i = 0; i < 3; i++) {
5569 if (this->local_size[i] > state->ctx->Const.MaxComputeWorkGroupSize[i]) {
5570 _mesa_glsl_error(&loc, state,
5571 "local_size_%c exceeds MAX_COMPUTE_WORK_GROUP_SIZE"
5572 " (%d)", 'x' + i,
5573 state->ctx->Const.MaxComputeWorkGroupSize[i]);
5574 break;
5575 }
5576 total_invocations *= this->local_size[i];
5577 if (total_invocations >
5578 state->ctx->Const.MaxComputeWorkGroupInvocations) {
5579 _mesa_glsl_error(&loc, state,
5580 "product of local_sizes exceeds "
5581 "MAX_COMPUTE_WORK_GROUP_INVOCATIONS (%d)",
5582 state->ctx->Const.MaxComputeWorkGroupInvocations);
5583 break;
5584 }
5585 }
5586
5587 state->cs_input_local_size_specified = true;
5588 for (int i = 0; i < 3; i++)
5589 state->cs_input_local_size[i] = this->local_size[i];
5590
5591 /* We may now declare the built-in constant gl_WorkGroupSize (see
5592 * builtin_variable_generator::generate_constants() for why we didn't
5593 * declare it earlier).
5594 */
5595 ir_variable *var = new(state->symbols)
5596 ir_variable(glsl_type::ivec3_type, "gl_WorkGroupSize", ir_var_auto);
5597 var->data.how_declared = ir_var_declared_implicitly;
5598 var->data.read_only = true;
5599 instructions->push_tail(var);
5600 state->symbols->add_variable(var);
5601 ir_constant_data data;
5602 memset(&data, 0, sizeof(data));
5603 for (int i = 0; i < 3; i++)
5604 data.i[i] = this->local_size[i];
5605 var->constant_value = new(var) ir_constant(glsl_type::ivec3_type, &data);
5606 var->constant_initializer =
5607 new(var) ir_constant(glsl_type::ivec3_type, &data);
5608 var->data.has_initializer = true;
5609
5610 return NULL;
5611 }
5612
5613
5614 static void
5615 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
5616 exec_list *instructions)
5617 {
5618 bool gl_FragColor_assigned = false;
5619 bool gl_FragData_assigned = false;
5620 bool user_defined_fs_output_assigned = false;
5621 ir_variable *user_defined_fs_output = NULL;
5622
5623 /* It would be nice to have proper location information. */
5624 YYLTYPE loc;
5625 memset(&loc, 0, sizeof(loc));
5626
5627 foreach_list(node, instructions) {
5628 ir_variable *var = ((ir_instruction *)node)->as_variable();
5629
5630 if (!var || !var->data.assigned)
5631 continue;
5632
5633 if (strcmp(var->name, "gl_FragColor") == 0)
5634 gl_FragColor_assigned = true;
5635 else if (strcmp(var->name, "gl_FragData") == 0)
5636 gl_FragData_assigned = true;
5637 else if (strncmp(var->name, "gl_", 3) != 0) {
5638 if (state->stage == MESA_SHADER_FRAGMENT &&
5639 var->data.mode == ir_var_shader_out) {
5640 user_defined_fs_output_assigned = true;
5641 user_defined_fs_output = var;
5642 }
5643 }
5644 }
5645
5646 /* From the GLSL 1.30 spec:
5647 *
5648 * "If a shader statically assigns a value to gl_FragColor, it
5649 * may not assign a value to any element of gl_FragData. If a
5650 * shader statically writes a value to any element of
5651 * gl_FragData, it may not assign a value to
5652 * gl_FragColor. That is, a shader may assign values to either
5653 * gl_FragColor or gl_FragData, but not both. Multiple shaders
5654 * linked together must also consistently write just one of
5655 * these variables. Similarly, if user declared output
5656 * variables are in use (statically assigned to), then the
5657 * built-in variables gl_FragColor and gl_FragData may not be
5658 * assigned to. These incorrect usages all generate compile
5659 * time errors."
5660 */
5661 if (gl_FragColor_assigned && gl_FragData_assigned) {
5662 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5663 "`gl_FragColor' and `gl_FragData'");
5664 } else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {
5665 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5666 "`gl_FragColor' and `%s'",
5667 user_defined_fs_output->name);
5668 } else if (gl_FragData_assigned && user_defined_fs_output_assigned) {
5669 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5670 "`gl_FragData' and `%s'",
5671 user_defined_fs_output->name);
5672 }
5673 }
5674
5675
5676 static void
5677 remove_per_vertex_blocks(exec_list *instructions,
5678 _mesa_glsl_parse_state *state, ir_variable_mode mode)
5679 {
5680 /* Find the gl_PerVertex interface block of the appropriate (in/out) mode,
5681 * if it exists in this shader type.
5682 */
5683 const glsl_type *per_vertex = NULL;
5684 switch (mode) {
5685 case ir_var_shader_in:
5686 if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))
5687 per_vertex = gl_in->get_interface_type();
5688 break;
5689 case ir_var_shader_out:
5690 if (ir_variable *gl_Position =
5691 state->symbols->get_variable("gl_Position")) {
5692 per_vertex = gl_Position->get_interface_type();
5693 }
5694 break;
5695 default:
5696 assert(!"Unexpected mode");
5697 break;
5698 }
5699
5700 /* If we didn't find a built-in gl_PerVertex interface block, then we don't
5701 * need to do anything.
5702 */
5703 if (per_vertex == NULL)
5704 return;
5705
5706 /* If the interface block is used by the shader, then we don't need to do
5707 * anything.
5708 */
5709 interface_block_usage_visitor v(mode, per_vertex);
5710 v.run(instructions);
5711 if (v.usage_found())
5712 return;
5713
5714 /* Remove any ir_variable declarations that refer to the interface block
5715 * we're removing.
5716 */
5717 foreach_list_safe(node, instructions) {
5718 ir_variable *const var = ((ir_instruction *) node)->as_variable();
5719 if (var != NULL && var->get_interface_type() == per_vertex &&
5720 var->data.mode == mode) {
5721 state->symbols->disable_variable(var->name);
5722 var->remove();
5723 }
5724 }
5725 }