2 * Copyright © 2010 Intel Corporation
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:
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
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.
26 * Convert abstract syntax to to high-level intermediate reprensentation (HIR).
28 * During the conversion to HIR, the majority of the symantic checking is
29 * preformed on the program. This includes:
31 * * Symbol table management
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.
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.
48 * As a result, my preference is to put as little C code as possible in the
49 * parser (and lexer) sources.
52 #include "main/core.h" /* for struct gl_extensions */
53 #include "glsl_symbol_table.h"
54 #include "glsl_parser_extras.h"
56 #include "glsl_types.h"
60 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
62 _mesa_glsl_initialize_variables(instructions, state);
64 state->symbols->language_version = state->language_version;
66 state->current_function = NULL;
68 state->toplevel_ir = instructions;
70 /* Section 4.2 of the GLSL 1.20 specification states:
71 * "The built-in functions are scoped in a scope outside the global scope
72 * users declare global variables in. That is, a shader's global scope,
73 * available for user-defined functions and global variables, is nested
74 * inside the scope containing the built-in functions."
76 * Since built-in functions like ftransform() access built-in variables,
77 * it follows that those must be in the outer scope as well.
79 * We push scope here to create this nesting effect...but don't pop.
80 * This way, a shader's globals are still in the symbol table for use
83 state->symbols->push_scope();
85 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
86 ast->hir(instructions, state);
88 detect_recursion_unlinked(state, instructions);
90 state->toplevel_ir = NULL;
95 * If a conversion is available, convert one operand to a different type
97 * The \c from \c ir_rvalue is converted "in place".
99 * \param to Type that the operand it to be converted to
100 * \param from Operand that is being converted
101 * \param state GLSL compiler state
104 * If a conversion is possible (or unnecessary), \c true is returned.
105 * Otherwise \c false is returned.
108 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
109 struct _mesa_glsl_parse_state *state)
112 if (to->base_type == from->type->base_type)
115 /* This conversion was added in GLSL 1.20. If the compilation mode is
116 * GLSL 1.10, the conversion is skipped.
118 if (state->language_version < 120)
121 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
123 * "There are no implicit array or structure conversions. For
124 * example, an array of int cannot be implicitly converted to an
125 * array of float. There are no implicit conversions between
126 * signed and unsigned integers."
128 /* FINISHME: The above comment is partially a lie. There is int/uint
129 * FINISHME: conversion for immediate constants.
131 if (!to->is_float() || !from->type->is_numeric())
134 /* Convert to a floating point type with the same number of components
135 * as the original type - i.e. int to float, not int to vec4.
137 to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
138 from->type->matrix_columns);
140 switch (from->type->base_type) {
142 from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
145 from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
148 from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
158 static const struct glsl_type *
159 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
161 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
163 const glsl_type *type_a = value_a->type;
164 const glsl_type *type_b = value_b->type;
166 /* From GLSL 1.50 spec, page 56:
168 * "The arithmetic binary operators add (+), subtract (-),
169 * multiply (*), and divide (/) operate on integer and
170 * floating-point scalars, vectors, and matrices."
172 if (!type_a->is_numeric() || !type_b->is_numeric()) {
173 _mesa_glsl_error(loc, state,
174 "Operands to arithmetic operators must be numeric");
175 return glsl_type::error_type;
179 /* "If one operand is floating-point based and the other is
180 * not, then the conversions from Section 4.1.10 "Implicit
181 * Conversions" are applied to the non-floating-point-based operand."
183 if (!apply_implicit_conversion(type_a, value_b, state)
184 && !apply_implicit_conversion(type_b, value_a, state)) {
185 _mesa_glsl_error(loc, state,
186 "Could not implicitly convert operands to "
187 "arithmetic operator");
188 return glsl_type::error_type;
190 type_a = value_a->type;
191 type_b = value_b->type;
193 /* "If the operands are integer types, they must both be signed or
196 * From this rule and the preceeding conversion it can be inferred that
197 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
198 * The is_numeric check above already filtered out the case where either
199 * type is not one of these, so now the base types need only be tested for
202 if (type_a->base_type != type_b->base_type) {
203 _mesa_glsl_error(loc, state,
204 "base type mismatch for arithmetic operator");
205 return glsl_type::error_type;
208 /* "All arithmetic binary operators result in the same fundamental type
209 * (signed integer, unsigned integer, or floating-point) as the
210 * operands they operate on, after operand type conversion. After
211 * conversion, the following cases are valid
213 * * The two operands are scalars. In this case the operation is
214 * applied, resulting in a scalar."
216 if (type_a->is_scalar() && type_b->is_scalar())
219 /* "* One operand is a scalar, and the other is a vector or matrix.
220 * In this case, the scalar operation is applied independently to each
221 * component of the vector or matrix, resulting in the same size
224 if (type_a->is_scalar()) {
225 if (!type_b->is_scalar())
227 } else if (type_b->is_scalar()) {
231 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
232 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
235 assert(!type_a->is_scalar());
236 assert(!type_b->is_scalar());
238 /* "* The two operands are vectors of the same size. In this case, the
239 * operation is done component-wise resulting in the same size
242 if (type_a->is_vector() && type_b->is_vector()) {
243 if (type_a == type_b) {
246 _mesa_glsl_error(loc, state,
247 "vector size mismatch for arithmetic operator");
248 return glsl_type::error_type;
252 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
253 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
254 * <vector, vector> have been handled. At least one of the operands must
255 * be matrix. Further, since there are no integer matrix types, the base
256 * type of both operands must be float.
258 assert(type_a->is_matrix() || type_b->is_matrix());
259 assert(type_a->base_type == GLSL_TYPE_FLOAT);
260 assert(type_b->base_type == GLSL_TYPE_FLOAT);
262 /* "* The operator is add (+), subtract (-), or divide (/), and the
263 * operands are matrices with the same number of rows and the same
264 * number of columns. In this case, the operation is done component-
265 * wise resulting in the same size matrix."
266 * * The operator is multiply (*), where both operands are matrices or
267 * one operand is a vector and the other a matrix. A right vector
268 * operand is treated as a column vector and a left vector operand as a
269 * row vector. In all these cases, it is required that the number of
270 * columns of the left operand is equal to the number of rows of the
271 * right operand. Then, the multiply (*) operation does a linear
272 * algebraic multiply, yielding an object that has the same number of
273 * rows as the left operand and the same number of columns as the right
274 * operand. Section 5.10 "Vector and Matrix Operations" explains in
275 * more detail how vectors and matrices are operated on."
278 if (type_a == type_b)
281 if (type_a->is_matrix() && type_b->is_matrix()) {
282 /* Matrix multiply. The columns of A must match the rows of B. Given
283 * the other previously tested constraints, this means the vector type
284 * of a row from A must be the same as the vector type of a column from
287 if (type_a->row_type() == type_b->column_type()) {
288 /* The resulting matrix has the number of columns of matrix B and
289 * the number of rows of matrix A. We get the row count of A by
290 * looking at the size of a vector that makes up a column. The
291 * transpose (size of a row) is done for B.
293 const glsl_type *const type =
294 glsl_type::get_instance(type_a->base_type,
295 type_a->column_type()->vector_elements,
296 type_b->row_type()->vector_elements);
297 assert(type != glsl_type::error_type);
301 } else if (type_a->is_matrix()) {
302 /* A is a matrix and B is a column vector. Columns of A must match
303 * rows of B. Given the other previously tested constraints, this
304 * means the vector type of a row from A must be the same as the
305 * vector the type of B.
307 if (type_a->row_type() == type_b) {
308 /* The resulting vector has a number of elements equal to
309 * the number of rows of matrix A. */
310 const glsl_type *const type =
311 glsl_type::get_instance(type_a->base_type,
312 type_a->column_type()->vector_elements,
314 assert(type != glsl_type::error_type);
319 assert(type_b->is_matrix());
321 /* A is a row vector and B is a matrix. Columns of A must match rows
322 * of B. Given the other previously tested constraints, this means
323 * the type of A must be the same as the vector type of a column from
326 if (type_a == type_b->column_type()) {
327 /* The resulting vector has a number of elements equal to
328 * the number of columns of matrix B. */
329 const glsl_type *const type =
330 glsl_type::get_instance(type_a->base_type,
331 type_b->row_type()->vector_elements,
333 assert(type != glsl_type::error_type);
339 _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
340 return glsl_type::error_type;
344 /* "All other cases are illegal."
346 _mesa_glsl_error(loc, state, "type mismatch");
347 return glsl_type::error_type;
351 static const struct glsl_type *
352 unary_arithmetic_result_type(const struct glsl_type *type,
353 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
355 /* From GLSL 1.50 spec, page 57:
357 * "The arithmetic unary operators negate (-), post- and pre-increment
358 * and decrement (-- and ++) operate on integer or floating-point
359 * values (including vectors and matrices). All unary operators work
360 * component-wise on their operands. These result with the same type
363 if (!type->is_numeric()) {
364 _mesa_glsl_error(loc, state,
365 "Operands to arithmetic operators must be numeric");
366 return glsl_type::error_type;
373 * \brief Return the result type of a bit-logic operation.
375 * If the given types to the bit-logic operator are invalid, return
376 * glsl_type::error_type.
378 * \param type_a Type of LHS of bit-logic op
379 * \param type_b Type of RHS of bit-logic op
381 static const struct glsl_type *
382 bit_logic_result_type(const struct glsl_type *type_a,
383 const struct glsl_type *type_b,
385 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
387 if (state->language_version < 130) {
388 _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
389 return glsl_type::error_type;
392 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
394 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
395 * (|). The operands must be of type signed or unsigned integers or
398 if (!type_a->is_integer()) {
399 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
400 ast_expression::operator_string(op));
401 return glsl_type::error_type;
403 if (!type_b->is_integer()) {
404 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
405 ast_expression::operator_string(op));
406 return glsl_type::error_type;
409 /* "The fundamental types of the operands (signed or unsigned) must
412 if (type_a->base_type != type_b->base_type) {
413 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
414 "base type", ast_expression::operator_string(op));
415 return glsl_type::error_type;
418 /* "The operands cannot be vectors of differing size." */
419 if (type_a->is_vector() &&
420 type_b->is_vector() &&
421 type_a->vector_elements != type_b->vector_elements) {
422 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
423 "different sizes", ast_expression::operator_string(op));
424 return glsl_type::error_type;
427 /* "If one operand is a scalar and the other a vector, the scalar is
428 * applied component-wise to the vector, resulting in the same type as
429 * the vector. The fundamental types of the operands [...] will be the
430 * resulting fundamental type."
432 if (type_a->is_scalar())
438 static const struct glsl_type *
439 modulus_result_type(const struct glsl_type *type_a,
440 const struct glsl_type *type_b,
441 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
443 if (state->language_version < 130) {
444 _mesa_glsl_error(loc, state,
445 "operator '%%' is reserved in %s",
446 state->version_string);
447 return glsl_type::error_type;
450 /* From GLSL 1.50 spec, page 56:
451 * "The operator modulus (%) operates on signed or unsigned integers or
452 * integer vectors. The operand types must both be signed or both be
455 if (!type_a->is_integer()) {
456 _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer.");
457 return glsl_type::error_type;
459 if (!type_b->is_integer()) {
460 _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer.");
461 return glsl_type::error_type;
463 if (type_a->base_type != type_b->base_type) {
464 _mesa_glsl_error(loc, state,
465 "operands of %% must have the same base type");
466 return glsl_type::error_type;
469 /* "The operands cannot be vectors of differing size. If one operand is
470 * a scalar and the other vector, then the scalar is applied component-
471 * wise to the vector, resulting in the same type as the vector. If both
472 * are vectors of the same size, the result is computed component-wise."
474 if (type_a->is_vector()) {
475 if (!type_b->is_vector()
476 || (type_a->vector_elements == type_b->vector_elements))
481 /* "The operator modulus (%) is not defined for any other data types
482 * (non-integer types)."
484 _mesa_glsl_error(loc, state, "type mismatch");
485 return glsl_type::error_type;
489 static const struct glsl_type *
490 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
491 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
493 const glsl_type *type_a = value_a->type;
494 const glsl_type *type_b = value_b->type;
496 /* From GLSL 1.50 spec, page 56:
497 * "The relational operators greater than (>), less than (<), greater
498 * than or equal (>=), and less than or equal (<=) operate only on
499 * scalar integer and scalar floating-point expressions."
501 if (!type_a->is_numeric()
502 || !type_b->is_numeric()
503 || !type_a->is_scalar()
504 || !type_b->is_scalar()) {
505 _mesa_glsl_error(loc, state,
506 "Operands to relational operators must be scalar and "
508 return glsl_type::error_type;
511 /* "Either the operands' types must match, or the conversions from
512 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
513 * operand, after which the types must match."
515 if (!apply_implicit_conversion(type_a, value_b, state)
516 && !apply_implicit_conversion(type_b, value_a, state)) {
517 _mesa_glsl_error(loc, state,
518 "Could not implicitly convert operands to "
519 "relational operator");
520 return glsl_type::error_type;
522 type_a = value_a->type;
523 type_b = value_b->type;
525 if (type_a->base_type != type_b->base_type) {
526 _mesa_glsl_error(loc, state, "base type mismatch");
527 return glsl_type::error_type;
530 /* "The result is scalar Boolean."
532 return glsl_type::bool_type;
536 * \brief Return the result type of a bit-shift operation.
538 * If the given types to the bit-shift operator are invalid, return
539 * glsl_type::error_type.
541 * \param type_a Type of LHS of bit-shift op
542 * \param type_b Type of RHS of bit-shift op
544 static const struct glsl_type *
545 shift_result_type(const struct glsl_type *type_a,
546 const struct glsl_type *type_b,
548 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
550 if (state->language_version < 130) {
551 _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
552 return glsl_type::error_type;
555 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
557 * "The shift operators (<<) and (>>). For both operators, the operands
558 * must be signed or unsigned integers or integer vectors. One operand
559 * can be signed while the other is unsigned."
561 if (!type_a->is_integer()) {
562 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
563 "integer vector", ast_expression::operator_string(op));
564 return glsl_type::error_type;
567 if (!type_b->is_integer()) {
568 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
569 "integer vector", ast_expression::operator_string(op));
570 return glsl_type::error_type;
573 /* "If the first operand is a scalar, the second operand has to be
576 if (type_a->is_scalar() && !type_b->is_scalar()) {
577 _mesa_glsl_error(loc, state, "If the first operand of %s is scalar, the "
578 "second must be scalar as well",
579 ast_expression::operator_string(op));
580 return glsl_type::error_type;
583 /* If both operands are vectors, check that they have same number of
586 if (type_a->is_vector() &&
587 type_b->is_vector() &&
588 type_a->vector_elements != type_b->vector_elements) {
589 _mesa_glsl_error(loc, state, "Vector operands to operator %s must "
590 "have same number of elements",
591 ast_expression::operator_string(op));
592 return glsl_type::error_type;
595 /* "In all cases, the resulting type will be the same type as the left
602 * Validates that a value can be assigned to a location with a specified type
604 * Validates that \c rhs can be assigned to some location. If the types are
605 * not an exact match but an automatic conversion is possible, \c rhs will be
609 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
610 * Otherwise the actual RHS to be assigned will be returned. This may be
611 * \c rhs, or it may be \c rhs after some type conversion.
614 * In addition to being used for assignments, this function is used to
615 * type-check return values.
618 validate_assignment(struct _mesa_glsl_parse_state *state,
619 const glsl_type *lhs_type, ir_rvalue *rhs,
622 /* If there is already some error in the RHS, just return it. Anything
623 * else will lead to an avalanche of error message back to the user.
625 if (rhs->type->is_error())
628 /* If the types are identical, the assignment can trivially proceed.
630 if (rhs->type == lhs_type)
633 /* If the array element types are the same and the size of the LHS is zero,
634 * the assignment is okay for initializers embedded in variable
637 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
638 * is handled by ir_dereference::is_lvalue.
640 if (is_initializer && lhs_type->is_array() && rhs->type->is_array()
641 && (lhs_type->element_type() == rhs->type->element_type())
642 && (lhs_type->array_size() == 0)) {
646 /* Check for implicit conversion in GLSL 1.20 */
647 if (apply_implicit_conversion(lhs_type, rhs, state)) {
648 if (rhs->type == lhs_type)
656 mark_whole_array_access(ir_rvalue *access)
658 ir_dereference_variable *deref = access->as_dereference_variable();
660 if (deref && deref->var) {
661 deref->var->max_array_access = deref->type->length - 1;
666 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
667 ir_rvalue *lhs, ir_rvalue *rhs, bool is_initializer,
671 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
673 if (!error_emitted) {
674 if (lhs->variable_referenced() != NULL
675 && lhs->variable_referenced()->read_only) {
676 _mesa_glsl_error(&lhs_loc, state,
677 "assignment to read-only variable '%s'",
678 lhs->variable_referenced()->name);
679 error_emitted = true;
681 } else if (state->language_version <= 110 && lhs->type->is_array()) {
682 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
684 * "Other binary or unary expressions, non-dereferenced
685 * arrays, function names, swizzles with repeated fields,
686 * and constants cannot be l-values."
688 _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
689 "allowed in GLSL 1.10 or GLSL ES 1.00.");
690 error_emitted = true;
691 } else if (!lhs->is_lvalue()) {
692 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
693 error_emitted = true;
698 validate_assignment(state, lhs->type, rhs, is_initializer);
699 if (new_rhs == NULL) {
700 _mesa_glsl_error(& lhs_loc, state, "type mismatch");
704 /* If the LHS array was not declared with a size, it takes it size from
705 * the RHS. If the LHS is an l-value and a whole array, it must be a
706 * dereference of a variable. Any other case would require that the LHS
707 * is either not an l-value or not a whole array.
709 if (lhs->type->array_size() == 0) {
710 ir_dereference *const d = lhs->as_dereference();
714 ir_variable *const var = d->variable_referenced();
718 if (var->max_array_access >= unsigned(rhs->type->array_size())) {
719 /* FINISHME: This should actually log the location of the RHS. */
720 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
722 var->max_array_access);
725 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
726 rhs->type->array_size());
729 mark_whole_array_access(rhs);
730 mark_whole_array_access(lhs);
733 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
734 * but not post_inc) need the converted assigned value as an rvalue
735 * to handle things like:
739 * So we always just store the computed value being assigned to a
740 * temporary and return a deref of that temporary. If the rvalue
741 * ends up not being used, the temp will get copy-propagated out.
743 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
745 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
746 instructions->push_tail(var);
747 instructions->push_tail(new(ctx) ir_assignment(deref_var,
750 deref_var = new(ctx) ir_dereference_variable(var);
753 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
755 return new(ctx) ir_dereference_variable(var);
759 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
761 void *ctx = ralloc_parent(lvalue);
764 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
766 instructions->push_tail(var);
767 var->mode = ir_var_auto;
769 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
772 /* Once we've created this temporary, mark it read only so it's no
773 * longer considered an lvalue.
775 var->read_only = true;
777 return new(ctx) ir_dereference_variable(var);
782 ast_node::hir(exec_list *instructions,
783 struct _mesa_glsl_parse_state *state)
792 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
795 ir_rvalue *cmp = NULL;
797 if (operation == ir_binop_all_equal)
798 join_op = ir_binop_logic_and;
800 join_op = ir_binop_logic_or;
802 switch (op0->type->base_type) {
803 case GLSL_TYPE_FLOAT:
807 return new(mem_ctx) ir_expression(operation, op0, op1);
809 case GLSL_TYPE_ARRAY: {
810 for (unsigned int i = 0; i < op0->type->length; i++) {
811 ir_rvalue *e0, *e1, *result;
813 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
814 new(mem_ctx) ir_constant(i));
815 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
816 new(mem_ctx) ir_constant(i));
817 result = do_comparison(mem_ctx, operation, e0, e1);
820 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
826 mark_whole_array_access(op0);
827 mark_whole_array_access(op1);
831 case GLSL_TYPE_STRUCT: {
832 for (unsigned int i = 0; i < op0->type->length; i++) {
833 ir_rvalue *e0, *e1, *result;
834 const char *field_name = op0->type->fields.structure[i].name;
836 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
838 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
840 result = do_comparison(mem_ctx, operation, e0, e1);
843 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
851 case GLSL_TYPE_ERROR:
853 case GLSL_TYPE_SAMPLER:
854 /* I assume a comparison of a struct containing a sampler just
855 * ignores the sampler present in the type.
860 assert(!"Should not get here.");
865 cmp = new(mem_ctx) ir_constant(true);
870 /* For logical operations, we want to ensure that the operands are
871 * scalar booleans. If it isn't, emit an error and return a constant
872 * boolean to avoid triggering cascading error messages.
875 get_scalar_boolean_operand(exec_list *instructions,
876 struct _mesa_glsl_parse_state *state,
877 ast_expression *parent_expr,
879 const char *operand_name,
882 ast_expression *expr = parent_expr->subexpressions[operand];
884 ir_rvalue *val = expr->hir(instructions, state);
886 if (val->type->is_boolean() && val->type->is_scalar())
889 if (!*error_emitted) {
890 YYLTYPE loc = expr->get_location();
891 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
893 parent_expr->operator_string(parent_expr->oper));
894 *error_emitted = true;
897 return new(ctx) ir_constant(true);
901 * If name refers to a builtin array whose maximum allowed size is less than
902 * size, report an error and return true. Otherwise return false.
905 check_builtin_array_max_size(const char *name, unsigned size,
906 YYLTYPE loc, struct _mesa_glsl_parse_state *state)
908 if ((strcmp("gl_TexCoord", name) == 0)
909 && (size > state->Const.MaxTextureCoords)) {
910 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
912 * "The size [of gl_TexCoord] can be at most
913 * gl_MaxTextureCoords."
915 _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
916 "be larger than gl_MaxTextureCoords (%u)\n",
917 state->Const.MaxTextureCoords);
919 } else if (strcmp("gl_ClipDistance", name) == 0
920 && size > state->Const.MaxClipPlanes) {
921 /* From section 7.1 (Vertex Shader Special Variables) of the
924 * "The gl_ClipDistance array is predeclared as unsized and
925 * must be sized by the shader either redeclaring it with a
926 * size or indexing it only with integral constant
927 * expressions. ... The size can be at most
928 * gl_MaxClipDistances."
930 _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
931 "be larger than gl_MaxClipDistances (%u)\n",
932 state->Const.MaxClipPlanes);
939 ast_expression::hir(exec_list *instructions,
940 struct _mesa_glsl_parse_state *state)
943 static const int operations[AST_NUM_OPERATORS] = {
944 -1, /* ast_assign doesn't convert to ir_expression. */
945 -1, /* ast_plus doesn't convert to ir_expression. */
969 /* Note: The following block of expression types actually convert
970 * to multiple IR instructions.
972 ir_binop_mul, /* ast_mul_assign */
973 ir_binop_div, /* ast_div_assign */
974 ir_binop_mod, /* ast_mod_assign */
975 ir_binop_add, /* ast_add_assign */
976 ir_binop_sub, /* ast_sub_assign */
977 ir_binop_lshift, /* ast_ls_assign */
978 ir_binop_rshift, /* ast_rs_assign */
979 ir_binop_bit_and, /* ast_and_assign */
980 ir_binop_bit_xor, /* ast_xor_assign */
981 ir_binop_bit_or, /* ast_or_assign */
983 -1, /* ast_conditional doesn't convert to ir_expression. */
984 ir_binop_add, /* ast_pre_inc. */
985 ir_binop_sub, /* ast_pre_dec. */
986 ir_binop_add, /* ast_post_inc. */
987 ir_binop_sub, /* ast_post_dec. */
988 -1, /* ast_field_selection doesn't conv to ir_expression. */
989 -1, /* ast_array_index doesn't convert to ir_expression. */
990 -1, /* ast_function_call doesn't conv to ir_expression. */
991 -1, /* ast_identifier doesn't convert to ir_expression. */
992 -1, /* ast_int_constant doesn't convert to ir_expression. */
993 -1, /* ast_uint_constant doesn't conv to ir_expression. */
994 -1, /* ast_float_constant doesn't conv to ir_expression. */
995 -1, /* ast_bool_constant doesn't conv to ir_expression. */
996 -1, /* ast_sequence doesn't convert to ir_expression. */
998 ir_rvalue *result = NULL;
1000 const struct glsl_type *type; /* a temporary variable for switch cases */
1001 bool error_emitted = false;
1004 loc = this->get_location();
1006 switch (this->oper) {
1008 op[0] = this->subexpressions[0]->hir(instructions, state);
1009 op[1] = this->subexpressions[1]->hir(instructions, state);
1011 result = do_assignment(instructions, state, op[0], op[1], false,
1012 this->subexpressions[0]->get_location());
1013 error_emitted = result->type->is_error();
1018 op[0] = this->subexpressions[0]->hir(instructions, state);
1020 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1022 error_emitted = type->is_error();
1028 op[0] = this->subexpressions[0]->hir(instructions, state);
1030 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1032 error_emitted = type->is_error();
1034 result = new(ctx) ir_expression(operations[this->oper], type,
1042 op[0] = this->subexpressions[0]->hir(instructions, state);
1043 op[1] = this->subexpressions[1]->hir(instructions, state);
1045 type = arithmetic_result_type(op[0], op[1],
1046 (this->oper == ast_mul),
1048 error_emitted = type->is_error();
1050 result = new(ctx) ir_expression(operations[this->oper], type,
1055 op[0] = this->subexpressions[0]->hir(instructions, state);
1056 op[1] = this->subexpressions[1]->hir(instructions, state);
1058 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1060 assert(operations[this->oper] == ir_binop_mod);
1062 result = new(ctx) ir_expression(operations[this->oper], type,
1064 error_emitted = type->is_error();
1069 if (state->language_version < 130) {
1070 _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
1071 operator_string(this->oper));
1072 error_emitted = true;
1075 op[0] = this->subexpressions[0]->hir(instructions, state);
1076 op[1] = this->subexpressions[1]->hir(instructions, state);
1077 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1079 result = new(ctx) ir_expression(operations[this->oper], type,
1081 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1088 op[0] = this->subexpressions[0]->hir(instructions, state);
1089 op[1] = this->subexpressions[1]->hir(instructions, state);
1091 type = relational_result_type(op[0], op[1], state, & loc);
1093 /* The relational operators must either generate an error or result
1094 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1096 assert(type->is_error()
1097 || ((type->base_type == GLSL_TYPE_BOOL)
1098 && type->is_scalar()));
1100 result = new(ctx) ir_expression(operations[this->oper], type,
1102 error_emitted = type->is_error();
1107 op[0] = this->subexpressions[0]->hir(instructions, state);
1108 op[1] = this->subexpressions[1]->hir(instructions, state);
1110 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1112 * "The equality operators equal (==), and not equal (!=)
1113 * operate on all types. They result in a scalar Boolean. If
1114 * the operand types do not match, then there must be a
1115 * conversion from Section 4.1.10 "Implicit Conversions"
1116 * applied to one operand that can make them match, in which
1117 * case this conversion is done."
1119 if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1120 && !apply_implicit_conversion(op[1]->type, op[0], state))
1121 || (op[0]->type != op[1]->type)) {
1122 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1123 "type", (this->oper == ast_equal) ? "==" : "!=");
1124 error_emitted = true;
1125 } else if ((state->language_version <= 110)
1126 && (op[0]->type->is_array() || op[1]->type->is_array())) {
1127 _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
1129 error_emitted = true;
1132 if (error_emitted) {
1133 result = new(ctx) ir_constant(false);
1135 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1136 assert(result->type == glsl_type::bool_type);
1143 op[0] = this->subexpressions[0]->hir(instructions, state);
1144 op[1] = this->subexpressions[1]->hir(instructions, state);
1145 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1147 result = new(ctx) ir_expression(operations[this->oper], type,
1149 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1153 op[0] = this->subexpressions[0]->hir(instructions, state);
1155 if (state->language_version < 130) {
1156 _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
1157 error_emitted = true;
1160 if (!op[0]->type->is_integer()) {
1161 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1162 error_emitted = true;
1166 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1169 case ast_logic_and: {
1170 exec_list rhs_instructions;
1171 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1172 "LHS", &error_emitted);
1173 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1174 "RHS", &error_emitted);
1176 ir_constant *op0_const = op[0]->constant_expression_value();
1178 if (op0_const->value.b[0]) {
1179 instructions->append_list(&rhs_instructions);
1184 type = glsl_type::bool_type;
1186 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1189 instructions->push_tail(tmp);
1191 ir_if *const stmt = new(ctx) ir_if(op[0]);
1192 instructions->push_tail(stmt);
1194 stmt->then_instructions.append_list(&rhs_instructions);
1195 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1196 ir_assignment *const then_assign =
1197 new(ctx) ir_assignment(then_deref, op[1], NULL);
1198 stmt->then_instructions.push_tail(then_assign);
1200 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1201 ir_assignment *const else_assign =
1202 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
1203 stmt->else_instructions.push_tail(else_assign);
1205 result = new(ctx) ir_dereference_variable(tmp);
1211 case ast_logic_or: {
1212 exec_list rhs_instructions;
1213 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1214 "LHS", &error_emitted);
1215 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1216 "RHS", &error_emitted);
1218 ir_constant *op0_const = op[0]->constant_expression_value();
1220 if (op0_const->value.b[0]) {
1225 type = glsl_type::bool_type;
1227 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1230 instructions->push_tail(tmp);
1232 ir_if *const stmt = new(ctx) ir_if(op[0]);
1233 instructions->push_tail(stmt);
1235 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1236 ir_assignment *const then_assign =
1237 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
1238 stmt->then_instructions.push_tail(then_assign);
1240 stmt->else_instructions.append_list(&rhs_instructions);
1241 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1242 ir_assignment *const else_assign =
1243 new(ctx) ir_assignment(else_deref, op[1], NULL);
1244 stmt->else_instructions.push_tail(else_assign);
1246 result = new(ctx) ir_dereference_variable(tmp);
1253 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1255 * "The logical binary operators and (&&), or ( | | ), and
1256 * exclusive or (^^). They operate only on two Boolean
1257 * expressions and result in a Boolean expression."
1259 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1261 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1264 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1269 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1270 "operand", &error_emitted);
1272 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1276 case ast_mul_assign:
1277 case ast_div_assign:
1278 case ast_add_assign:
1279 case ast_sub_assign: {
1280 op[0] = this->subexpressions[0]->hir(instructions, state);
1281 op[1] = this->subexpressions[1]->hir(instructions, state);
1283 type = arithmetic_result_type(op[0], op[1],
1284 (this->oper == ast_mul_assign),
1287 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1290 result = do_assignment(instructions, state,
1291 op[0]->clone(ctx, NULL), temp_rhs, false,
1292 this->subexpressions[0]->get_location());
1293 error_emitted = (op[0]->type->is_error());
1295 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1296 * explicitly test for this because none of the binary expression
1297 * operators allow array operands either.
1303 case ast_mod_assign: {
1304 op[0] = this->subexpressions[0]->hir(instructions, state);
1305 op[1] = this->subexpressions[1]->hir(instructions, state);
1307 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1309 assert(operations[this->oper] == ir_binop_mod);
1311 ir_rvalue *temp_rhs;
1312 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1315 result = do_assignment(instructions, state,
1316 op[0]->clone(ctx, NULL), temp_rhs, false,
1317 this->subexpressions[0]->get_location());
1318 error_emitted = type->is_error();
1323 case ast_rs_assign: {
1324 op[0] = this->subexpressions[0]->hir(instructions, state);
1325 op[1] = this->subexpressions[1]->hir(instructions, state);
1326 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1328 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1329 type, op[0], op[1]);
1330 result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1332 this->subexpressions[0]->get_location());
1333 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1337 case ast_and_assign:
1338 case ast_xor_assign:
1339 case ast_or_assign: {
1340 op[0] = this->subexpressions[0]->hir(instructions, state);
1341 op[1] = this->subexpressions[1]->hir(instructions, state);
1342 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1344 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1345 type, op[0], op[1]);
1346 result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1348 this->subexpressions[0]->get_location());
1349 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1353 case ast_conditional: {
1354 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1356 * "The ternary selection operator (?:). It operates on three
1357 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1358 * first expression, which must result in a scalar Boolean."
1360 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1361 "condition", &error_emitted);
1363 /* The :? operator is implemented by generating an anonymous temporary
1364 * followed by an if-statement. The last instruction in each branch of
1365 * the if-statement assigns a value to the anonymous temporary. This
1366 * temporary is the r-value of the expression.
1368 exec_list then_instructions;
1369 exec_list else_instructions;
1371 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1372 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1374 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1376 * "The second and third expressions can be any type, as
1377 * long their types match, or there is a conversion in
1378 * Section 4.1.10 "Implicit Conversions" that can be applied
1379 * to one of the expressions to make their types match. This
1380 * resulting matching type is the type of the entire
1383 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1384 && !apply_implicit_conversion(op[2]->type, op[1], state))
1385 || (op[1]->type != op[2]->type)) {
1386 YYLTYPE loc = this->subexpressions[1]->get_location();
1388 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1389 "operator must have matching types.");
1390 error_emitted = true;
1391 type = glsl_type::error_type;
1396 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1398 * "The second and third expressions must be the same type, but can
1399 * be of any type other than an array."
1401 if ((state->language_version <= 110) && type->is_array()) {
1402 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1403 "operator must not be arrays.");
1404 error_emitted = true;
1407 ir_constant *cond_val = op[0]->constant_expression_value();
1408 ir_constant *then_val = op[1]->constant_expression_value();
1409 ir_constant *else_val = op[2]->constant_expression_value();
1411 if (then_instructions.is_empty()
1412 && else_instructions.is_empty()
1413 && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1414 result = (cond_val->value.b[0]) ? then_val : else_val;
1416 ir_variable *const tmp =
1417 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1418 instructions->push_tail(tmp);
1420 ir_if *const stmt = new(ctx) ir_if(op[0]);
1421 instructions->push_tail(stmt);
1423 then_instructions.move_nodes_to(& stmt->then_instructions);
1424 ir_dereference *const then_deref =
1425 new(ctx) ir_dereference_variable(tmp);
1426 ir_assignment *const then_assign =
1427 new(ctx) ir_assignment(then_deref, op[1], NULL);
1428 stmt->then_instructions.push_tail(then_assign);
1430 else_instructions.move_nodes_to(& stmt->else_instructions);
1431 ir_dereference *const else_deref =
1432 new(ctx) ir_dereference_variable(tmp);
1433 ir_assignment *const else_assign =
1434 new(ctx) ir_assignment(else_deref, op[2], NULL);
1435 stmt->else_instructions.push_tail(else_assign);
1437 result = new(ctx) ir_dereference_variable(tmp);
1444 op[0] = this->subexpressions[0]->hir(instructions, state);
1445 if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1446 op[1] = new(ctx) ir_constant(1.0f);
1448 op[1] = new(ctx) ir_constant(1);
1450 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1452 ir_rvalue *temp_rhs;
1453 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1456 result = do_assignment(instructions, state,
1457 op[0]->clone(ctx, NULL), temp_rhs, false,
1458 this->subexpressions[0]->get_location());
1459 error_emitted = op[0]->type->is_error();
1464 case ast_post_dec: {
1465 op[0] = this->subexpressions[0]->hir(instructions, state);
1466 if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1467 op[1] = new(ctx) ir_constant(1.0f);
1469 op[1] = new(ctx) ir_constant(1);
1471 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1473 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1475 ir_rvalue *temp_rhs;
1476 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1479 /* Get a temporary of a copy of the lvalue before it's modified.
1480 * This may get thrown away later.
1482 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1484 (void)do_assignment(instructions, state,
1485 op[0]->clone(ctx, NULL), temp_rhs, false,
1486 this->subexpressions[0]->get_location());
1488 error_emitted = op[0]->type->is_error();
1492 case ast_field_selection:
1493 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1496 case ast_array_index: {
1497 YYLTYPE index_loc = subexpressions[1]->get_location();
1499 op[0] = subexpressions[0]->hir(instructions, state);
1500 op[1] = subexpressions[1]->hir(instructions, state);
1502 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1504 ir_rvalue *const array = op[0];
1506 result = new(ctx) ir_dereference_array(op[0], op[1]);
1508 /* Do not use op[0] after this point. Use array.
1516 if (!array->type->is_array()
1517 && !array->type->is_matrix()
1518 && !array->type->is_vector()) {
1519 _mesa_glsl_error(& index_loc, state,
1520 "cannot dereference non-array / non-matrix / "
1522 error_emitted = true;
1525 if (!op[1]->type->is_integer()) {
1526 _mesa_glsl_error(& index_loc, state,
1527 "array index must be integer type");
1528 error_emitted = true;
1529 } else if (!op[1]->type->is_scalar()) {
1530 _mesa_glsl_error(& index_loc, state,
1531 "array index must be scalar");
1532 error_emitted = true;
1535 /* If the array index is a constant expression and the array has a
1536 * declared size, ensure that the access is in-bounds. If the array
1537 * index is not a constant expression, ensure that the array has a
1540 ir_constant *const const_index = op[1]->constant_expression_value();
1541 if (const_index != NULL) {
1542 const int idx = const_index->value.i[0];
1543 const char *type_name;
1546 if (array->type->is_matrix()) {
1547 type_name = "matrix";
1548 } else if (array->type->is_vector()) {
1549 type_name = "vector";
1551 type_name = "array";
1554 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
1556 * "It is illegal to declare an array with a size, and then
1557 * later (in the same shader) index the same array with an
1558 * integral constant expression greater than or equal to the
1559 * declared size. It is also illegal to index an array with a
1560 * negative constant expression."
1562 if (array->type->is_matrix()) {
1563 if (array->type->row_type()->vector_elements <= idx) {
1564 bound = array->type->row_type()->vector_elements;
1566 } else if (array->type->is_vector()) {
1567 if (array->type->vector_elements <= idx) {
1568 bound = array->type->vector_elements;
1571 if ((array->type->array_size() > 0)
1572 && (array->type->array_size() <= idx)) {
1573 bound = array->type->array_size();
1578 _mesa_glsl_error(& loc, state, "%s index must be < %u",
1580 error_emitted = true;
1581 } else if (idx < 0) {
1582 _mesa_glsl_error(& loc, state, "%s index must be >= 0",
1584 error_emitted = true;
1587 if (array->type->is_array()) {
1588 /* If the array is a variable dereference, it dereferences the
1589 * whole array, by definition. Use this to get the variable.
1591 * FINISHME: Should some methods for getting / setting / testing
1592 * FINISHME: array access limits be added to ir_dereference?
1594 ir_variable *const v = array->whole_variable_referenced();
1595 if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
1596 v->max_array_access = idx;
1598 /* Check whether this access will, as a side effect, implicitly
1599 * cause the size of a built-in array to be too large.
1601 if (check_builtin_array_max_size(v->name, idx+1, loc, state))
1602 error_emitted = true;
1605 } else if (array->type->array_size() == 0) {
1606 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
1608 if (array->type->is_array()) {
1609 /* whole_variable_referenced can return NULL if the array is a
1610 * member of a structure. In this case it is safe to not update
1611 * the max_array_access field because it is never used for fields
1614 ir_variable *v = array->whole_variable_referenced();
1616 v->max_array_access = array->type->array_size() - 1;
1620 /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
1622 * "Samplers aggregated into arrays within a shader (using square
1623 * brackets [ ]) can only be indexed with integral constant
1624 * expressions [...]."
1626 * This restriction was added in GLSL 1.30. Shaders using earlier version
1627 * of the language should not be rejected by the compiler front-end for
1628 * using this construct. This allows useful things such as using a loop
1629 * counter as the index to an array of samplers. If the loop in unrolled,
1630 * the code should compile correctly. Instead, emit a warning.
1632 if (array->type->is_array() &&
1633 array->type->element_type()->is_sampler() &&
1634 const_index == NULL) {
1636 if (state->language_version == 100) {
1637 _mesa_glsl_warning(&loc, state,
1638 "sampler arrays indexed with non-constant "
1639 "expressions is optional in GLSL ES 1.00");
1640 } else if (state->language_version < 130) {
1641 _mesa_glsl_warning(&loc, state,
1642 "sampler arrays indexed with non-constant "
1643 "expressions is forbidden in GLSL 1.30 and "
1646 _mesa_glsl_error(&loc, state,
1647 "sampler arrays indexed with non-constant "
1648 "expressions is forbidden in GLSL 1.30 and "
1650 error_emitted = true;
1655 result->type = glsl_type::error_type;
1660 case ast_function_call:
1661 /* Should *NEVER* get here. ast_function_call should always be handled
1662 * by ast_function_expression::hir.
1667 case ast_identifier: {
1668 /* ast_identifier can appear several places in a full abstract syntax
1669 * tree. This particular use must be at location specified in the grammar
1670 * as 'variable_identifier'.
1673 state->symbols->get_variable(this->primary_expression.identifier);
1675 result = new(ctx) ir_dereference_variable(var);
1680 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1681 this->primary_expression.identifier);
1683 error_emitted = true;
1688 case ast_int_constant:
1689 result = new(ctx) ir_constant(this->primary_expression.int_constant);
1692 case ast_uint_constant:
1693 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1696 case ast_float_constant:
1697 result = new(ctx) ir_constant(this->primary_expression.float_constant);
1700 case ast_bool_constant:
1701 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1704 case ast_sequence: {
1705 /* It should not be possible to generate a sequence in the AST without
1706 * any expressions in it.
1708 assert(!this->expressions.is_empty());
1710 /* The r-value of a sequence is the last expression in the sequence. If
1711 * the other expressions in the sequence do not have side-effects (and
1712 * therefore add instructions to the instruction list), they get dropped
1715 exec_node *previous_tail_pred = NULL;
1716 YYLTYPE previous_operand_loc = loc;
1718 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1719 /* If one of the operands of comma operator does not generate any
1720 * code, we want to emit a warning. At each pass through the loop
1721 * previous_tail_pred will point to the last instruction in the
1722 * stream *before* processing the previous operand. Naturally,
1723 * instructions->tail_pred will point to the last instruction in the
1724 * stream *after* processing the previous operand. If the two
1725 * pointers match, then the previous operand had no effect.
1727 * The warning behavior here differs slightly from GCC. GCC will
1728 * only emit a warning if none of the left-hand operands have an
1729 * effect. However, it will emit a warning for each. I believe that
1730 * there are some cases in C (especially with GCC extensions) where
1731 * it is useful to have an intermediate step in a sequence have no
1732 * effect, but I don't think these cases exist in GLSL. Either way,
1733 * it would be a giant hassle to replicate that behavior.
1735 if (previous_tail_pred == instructions->tail_pred) {
1736 _mesa_glsl_warning(&previous_operand_loc, state,
1737 "left-hand operand of comma expression has "
1741 /* tail_pred is directly accessed instead of using the get_tail()
1742 * method for performance reasons. get_tail() has extra code to
1743 * return NULL when the list is empty. We don't care about that
1744 * here, so using tail_pred directly is fine.
1746 previous_tail_pred = instructions->tail_pred;
1747 previous_operand_loc = ast->get_location();
1749 result = ast->hir(instructions, state);
1752 /* Any errors should have already been emitted in the loop above.
1754 error_emitted = true;
1758 type = NULL; /* use result->type, not type. */
1759 assert(result != NULL);
1761 if (result->type->is_error() && !error_emitted)
1762 _mesa_glsl_error(& loc, state, "type mismatch");
1769 ast_expression_statement::hir(exec_list *instructions,
1770 struct _mesa_glsl_parse_state *state)
1772 /* It is possible to have expression statements that don't have an
1773 * expression. This is the solitary semicolon:
1775 * for (i = 0; i < 5; i++)
1778 * In this case the expression will be NULL. Test for NULL and don't do
1779 * anything in that case.
1781 if (expression != NULL)
1782 expression->hir(instructions, state);
1784 /* Statements do not have r-values.
1791 ast_compound_statement::hir(exec_list *instructions,
1792 struct _mesa_glsl_parse_state *state)
1795 state->symbols->push_scope();
1797 foreach_list_typed (ast_node, ast, link, &this->statements)
1798 ast->hir(instructions, state);
1801 state->symbols->pop_scope();
1803 /* Compound statements do not have r-values.
1809 static const glsl_type *
1810 process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
1811 struct _mesa_glsl_parse_state *state)
1813 unsigned length = 0;
1815 /* FINISHME: Reject delcarations of multidimensional arrays. */
1817 if (array_size != NULL) {
1818 exec_list dummy_instructions;
1819 ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1820 YYLTYPE loc = array_size->get_location();
1823 if (!ir->type->is_integer()) {
1824 _mesa_glsl_error(& loc, state, "array size must be integer type");
1825 } else if (!ir->type->is_scalar()) {
1826 _mesa_glsl_error(& loc, state, "array size must be scalar type");
1828 ir_constant *const size = ir->constant_expression_value();
1831 _mesa_glsl_error(& loc, state, "array size must be a "
1832 "constant valued expression");
1833 } else if (size->value.i[0] <= 0) {
1834 _mesa_glsl_error(& loc, state, "array size must be > 0");
1836 assert(size->type == ir->type);
1837 length = size->value.u[0];
1839 /* If the array size is const (and we've verified that
1840 * it is) then no instructions should have been emitted
1841 * when we converted it to HIR. If they were emitted,
1842 * then either the array size isn't const after all, or
1843 * we are emitting unnecessary instructions.
1845 assert(dummy_instructions.is_empty());
1849 } else if (state->es_shader) {
1850 /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
1851 * array declarations have been removed from the language.
1853 _mesa_glsl_error(loc, state, "unsized array declarations are not "
1854 "allowed in GLSL ES 1.00.");
1857 return glsl_type::get_array_instance(base, length);
1862 ast_type_specifier::glsl_type(const char **name,
1863 struct _mesa_glsl_parse_state *state) const
1865 const struct glsl_type *type;
1867 type = state->symbols->get_type(this->type_name);
1868 *name = this->type_name;
1870 if (this->is_array) {
1871 YYLTYPE loc = this->get_location();
1872 type = process_array_type(&loc, type, this->array_size, state);
1880 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
1882 struct _mesa_glsl_parse_state *state,
1885 if (qual->flags.q.invariant) {
1887 _mesa_glsl_error(loc, state,
1888 "variable `%s' may not be redeclared "
1889 "`invariant' after being used",
1896 if (qual->flags.q.constant || qual->flags.q.attribute
1897 || qual->flags.q.uniform
1898 || (qual->flags.q.varying && (state->target == fragment_shader)))
1901 if (qual->flags.q.centroid)
1904 if (qual->flags.q.attribute && state->target != vertex_shader) {
1905 var->type = glsl_type::error_type;
1906 _mesa_glsl_error(loc, state,
1907 "`attribute' variables may not be declared in the "
1909 _mesa_glsl_shader_target_name(state->target));
1912 /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
1914 * "The varying qualifier can be used only with the data types
1915 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
1918 if (qual->flags.q.varying) {
1919 const glsl_type *non_array_type;
1921 if (var->type && var->type->is_array())
1922 non_array_type = var->type->fields.array;
1924 non_array_type = var->type;
1926 if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
1927 var->type = glsl_type::error_type;
1928 _mesa_glsl_error(loc, state,
1929 "varying variables must be of base type float");
1933 /* If there is no qualifier that changes the mode of the variable, leave
1934 * the setting alone.
1936 if (qual->flags.q.in && qual->flags.q.out)
1937 var->mode = ir_var_inout;
1938 else if (qual->flags.q.attribute || qual->flags.q.in
1939 || (qual->flags.q.varying && (state->target == fragment_shader)))
1940 var->mode = ir_var_in;
1941 else if (qual->flags.q.out
1942 || (qual->flags.q.varying && (state->target == vertex_shader)))
1943 var->mode = ir_var_out;
1944 else if (qual->flags.q.uniform)
1945 var->mode = ir_var_uniform;
1947 if (state->all_invariant && (state->current_function == NULL)) {
1948 switch (state->target) {
1950 if (var->mode == ir_var_out)
1951 var->invariant = true;
1953 case geometry_shader:
1954 if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
1955 var->invariant = true;
1957 case fragment_shader:
1958 if (var->mode == ir_var_in)
1959 var->invariant = true;
1964 if (qual->flags.q.flat)
1965 var->interpolation = INTERP_QUALIFIER_FLAT;
1966 else if (qual->flags.q.noperspective)
1967 var->interpolation = INTERP_QUALIFIER_NOPERSPECTIVE;
1968 else if (qual->flags.q.smooth)
1969 var->interpolation = INTERP_QUALIFIER_SMOOTH;
1971 var->interpolation = INTERP_QUALIFIER_NONE;
1973 var->pixel_center_integer = qual->flags.q.pixel_center_integer;
1974 var->origin_upper_left = qual->flags.q.origin_upper_left;
1975 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
1976 && (strcmp(var->name, "gl_FragCoord") != 0)) {
1977 const char *const qual_string = (qual->flags.q.origin_upper_left)
1978 ? "origin_upper_left" : "pixel_center_integer";
1980 _mesa_glsl_error(loc, state,
1981 "layout qualifier `%s' can only be applied to "
1982 "fragment shader input `gl_FragCoord'",
1986 if (qual->flags.q.explicit_location) {
1987 const bool global_scope = (state->current_function == NULL);
1989 const char *string = "";
1991 /* In the vertex shader only shader inputs can be given explicit
1994 * In the fragment shader only shader outputs can be given explicit
1997 switch (state->target) {
1999 if (!global_scope || (var->mode != ir_var_in)) {
2005 case geometry_shader:
2006 _mesa_glsl_error(loc, state,
2007 "geometry shader variables cannot be given "
2008 "explicit locations\n");
2011 case fragment_shader:
2012 if (!global_scope || (var->mode != ir_var_out)) {
2020 _mesa_glsl_error(loc, state,
2021 "only %s shader %s variables can be given an "
2022 "explicit location\n",
2023 _mesa_glsl_shader_target_name(state->target),
2026 var->explicit_location = true;
2028 /* This bit of silliness is needed because invalid explicit locations
2029 * are supposed to be flagged during linking. Small negative values
2030 * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
2031 * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
2032 * The linker needs to be able to differentiate these cases. This
2033 * ensures that negative values stay negative.
2035 if (qual->location >= 0) {
2036 var->location = (state->target == vertex_shader)
2037 ? (qual->location + VERT_ATTRIB_GENERIC0)
2038 : (qual->location + FRAG_RESULT_DATA0);
2040 var->location = qual->location;
2045 /* Does the declaration use the 'layout' keyword?
2047 const bool uses_layout = qual->flags.q.pixel_center_integer
2048 || qual->flags.q.origin_upper_left
2049 || qual->flags.q.explicit_location;
2051 /* Does the declaration use the deprecated 'attribute' or 'varying'
2054 const bool uses_deprecated_qualifier = qual->flags.q.attribute
2055 || qual->flags.q.varying;
2057 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2058 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2059 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2060 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2061 * These extensions and all following extensions that add the 'layout'
2062 * keyword have been modified to require the use of 'in' or 'out'.
2064 * The following extension do not allow the deprecated keywords:
2066 * GL_AMD_conservative_depth
2067 * GL_ARB_gpu_shader5
2068 * GL_ARB_separate_shader_objects
2069 * GL_ARB_tesselation_shader
2070 * GL_ARB_transform_feedback3
2071 * GL_ARB_uniform_buffer_object
2073 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2074 * allow layout with the deprecated keywords.
2076 const bool relaxed_layout_qualifier_checking =
2077 state->ARB_fragment_coord_conventions_enable;
2079 if (uses_layout && uses_deprecated_qualifier) {
2080 if (relaxed_layout_qualifier_checking) {
2081 _mesa_glsl_warning(loc, state,
2082 "`layout' qualifier may not be used with "
2083 "`attribute' or `varying'");
2085 _mesa_glsl_error(loc, state,
2086 "`layout' qualifier may not be used with "
2087 "`attribute' or `varying'");
2091 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2092 * AMD_conservative_depth.
2094 int depth_layout_count = qual->flags.q.depth_any
2095 + qual->flags.q.depth_greater
2096 + qual->flags.q.depth_less
2097 + qual->flags.q.depth_unchanged;
2098 if (depth_layout_count > 0
2099 && !state->AMD_conservative_depth_enable) {
2100 _mesa_glsl_error(loc, state,
2101 "extension GL_AMD_conservative_depth must be enabled "
2102 "to use depth layout qualifiers");
2103 } else if (depth_layout_count > 0
2104 && strcmp(var->name, "gl_FragDepth") != 0) {
2105 _mesa_glsl_error(loc, state,
2106 "depth layout qualifiers can be applied only to "
2108 } else if (depth_layout_count > 1
2109 && strcmp(var->name, "gl_FragDepth") == 0) {
2110 _mesa_glsl_error(loc, state,
2111 "at most one depth layout qualifier can be applied to "
2114 if (qual->flags.q.depth_any)
2115 var->depth_layout = ir_depth_layout_any;
2116 else if (qual->flags.q.depth_greater)
2117 var->depth_layout = ir_depth_layout_greater;
2118 else if (qual->flags.q.depth_less)
2119 var->depth_layout = ir_depth_layout_less;
2120 else if (qual->flags.q.depth_unchanged)
2121 var->depth_layout = ir_depth_layout_unchanged;
2123 var->depth_layout = ir_depth_layout_none;
2127 * Get the variable that is being redeclared by this declaration
2129 * Semantic checks to verify the validity of the redeclaration are also
2130 * performed. If semantic checks fail, compilation error will be emitted via
2131 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2134 * A pointer to an existing variable in the current scope if the declaration
2135 * is a redeclaration, \c NULL otherwise.
2138 get_variable_being_redeclared(ir_variable *var, ast_declaration *decl,
2139 struct _mesa_glsl_parse_state *state)
2141 /* Check if this declaration is actually a re-declaration, either to
2142 * resize an array or add qualifiers to an existing variable.
2144 * This is allowed for variables in the current scope, or when at
2145 * global scope (for built-ins in the implicit outer scope).
2147 ir_variable *earlier = state->symbols->get_variable(decl->identifier);
2148 if (earlier == NULL ||
2149 (state->current_function != NULL &&
2150 !state->symbols->name_declared_this_scope(decl->identifier))) {
2155 YYLTYPE loc = decl->get_location();
2157 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2159 * "It is legal to declare an array without a size and then
2160 * later re-declare the same name as an array of the same
2161 * type and specify a size."
2163 if ((earlier->type->array_size() == 0)
2164 && var->type->is_array()
2165 && (var->type->element_type() == earlier->type->element_type())) {
2166 /* FINISHME: This doesn't match the qualifiers on the two
2167 * FINISHME: declarations. It's not 100% clear whether this is
2168 * FINISHME: required or not.
2171 const unsigned size = unsigned(var->type->array_size());
2172 check_builtin_array_max_size(var->name, size, loc, state);
2173 if ((size > 0) && (size <= earlier->max_array_access)) {
2174 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2176 earlier->max_array_access);
2179 earlier->type = var->type;
2182 } else if (state->ARB_fragment_coord_conventions_enable
2183 && strcmp(var->name, "gl_FragCoord") == 0
2184 && earlier->type == var->type
2185 && earlier->mode == var->mode) {
2186 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2189 earlier->origin_upper_left = var->origin_upper_left;
2190 earlier->pixel_center_integer = var->pixel_center_integer;
2192 /* According to section 4.3.7 of the GLSL 1.30 spec,
2193 * the following built-in varaibles can be redeclared with an
2194 * interpolation qualifier:
2197 * * gl_FrontSecondaryColor
2198 * * gl_BackSecondaryColor
2200 * * gl_SecondaryColor
2202 } else if (state->language_version >= 130
2203 && (strcmp(var->name, "gl_FrontColor") == 0
2204 || strcmp(var->name, "gl_BackColor") == 0
2205 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2206 || strcmp(var->name, "gl_BackSecondaryColor") == 0
2207 || strcmp(var->name, "gl_Color") == 0
2208 || strcmp(var->name, "gl_SecondaryColor") == 0)
2209 && earlier->type == var->type
2210 && earlier->mode == var->mode) {
2211 earlier->interpolation = var->interpolation;
2213 /* Layout qualifiers for gl_FragDepth. */
2214 } else if (state->AMD_conservative_depth_enable
2215 && strcmp(var->name, "gl_FragDepth") == 0
2216 && earlier->type == var->type
2217 && earlier->mode == var->mode) {
2219 /** From the AMD_conservative_depth spec:
2220 * Within any shader, the first redeclarations of gl_FragDepth
2221 * must appear before any use of gl_FragDepth.
2223 if (earlier->used) {
2224 _mesa_glsl_error(&loc, state,
2225 "the first redeclaration of gl_FragDepth "
2226 "must appear before any use of gl_FragDepth");
2229 /* Prevent inconsistent redeclaration of depth layout qualifier. */
2230 if (earlier->depth_layout != ir_depth_layout_none
2231 && earlier->depth_layout != var->depth_layout) {
2232 _mesa_glsl_error(&loc, state,
2233 "gl_FragDepth: depth layout is declared here "
2234 "as '%s, but it was previously declared as "
2236 depth_layout_string(var->depth_layout),
2237 depth_layout_string(earlier->depth_layout));
2240 earlier->depth_layout = var->depth_layout;
2243 _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
2250 * Generate the IR for an initializer in a variable declaration
2253 process_initializer(ir_variable *var, ast_declaration *decl,
2254 ast_fully_specified_type *type,
2255 exec_list *initializer_instructions,
2256 struct _mesa_glsl_parse_state *state)
2258 ir_rvalue *result = NULL;
2260 YYLTYPE initializer_loc = decl->initializer->get_location();
2262 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2264 * "All uniform variables are read-only and are initialized either
2265 * directly by an application via API commands, or indirectly by
2268 if ((state->language_version <= 110)
2269 && (var->mode == ir_var_uniform)) {
2270 _mesa_glsl_error(& initializer_loc, state,
2271 "cannot initialize uniforms in GLSL 1.10");
2274 if (var->type->is_sampler()) {
2275 _mesa_glsl_error(& initializer_loc, state,
2276 "cannot initialize samplers");
2279 if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
2280 _mesa_glsl_error(& initializer_loc, state,
2281 "cannot initialize %s shader input / %s",
2282 _mesa_glsl_shader_target_name(state->target),
2283 (state->target == vertex_shader)
2284 ? "attribute" : "varying");
2287 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2288 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions,
2291 /* Calculate the constant value if this is a const or uniform
2294 if (type->qualifier.flags.q.constant
2295 || type->qualifier.flags.q.uniform) {
2296 ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs, true);
2297 if (new_rhs != NULL) {
2300 ir_constant *constant_value = rhs->constant_expression_value();
2301 if (!constant_value) {
2302 _mesa_glsl_error(& initializer_loc, state,
2303 "initializer of %s variable `%s' must be a "
2304 "constant expression",
2305 (type->qualifier.flags.q.constant)
2306 ? "const" : "uniform",
2308 if (var->type->is_numeric()) {
2309 /* Reduce cascading errors. */
2310 var->constant_value = ir_constant::zero(state, var->type);
2313 rhs = constant_value;
2314 var->constant_value = constant_value;
2317 _mesa_glsl_error(&initializer_loc, state,
2318 "initializer of type %s cannot be assigned to "
2319 "variable of type %s",
2320 rhs->type->name, var->type->name);
2321 if (var->type->is_numeric()) {
2322 /* Reduce cascading errors. */
2323 var->constant_value = ir_constant::zero(state, var->type);
2328 if (rhs && !rhs->type->is_error()) {
2329 bool temp = var->read_only;
2330 if (type->qualifier.flags.q.constant)
2331 var->read_only = false;
2333 /* Never emit code to initialize a uniform.
2335 const glsl_type *initializer_type;
2336 if (!type->qualifier.flags.q.uniform) {
2337 result = do_assignment(initializer_instructions, state,
2339 type->get_location());
2340 initializer_type = result->type;
2342 initializer_type = rhs->type;
2344 /* If the declared variable is an unsized array, it must inherrit
2345 * its full type from the initializer. A declaration such as
2347 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2351 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2353 * The assignment generated in the if-statement (below) will also
2354 * automatically handle this case for non-uniforms.
2356 * If the declared variable is not an array, the types must
2357 * already match exactly. As a result, the type assignment
2358 * here can be done unconditionally. For non-uniforms the call
2359 * to do_assignment can change the type of the initializer (via
2360 * the implicit conversion rules). For uniforms the initializer
2361 * must be a constant expression, and the type of that expression
2362 * was validated above.
2364 var->type = initializer_type;
2366 var->read_only = temp;
2373 ast_declarator_list::hir(exec_list *instructions,
2374 struct _mesa_glsl_parse_state *state)
2377 const struct glsl_type *decl_type;
2378 const char *type_name = NULL;
2379 ir_rvalue *result = NULL;
2380 YYLTYPE loc = this->get_location();
2382 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
2384 * "To ensure that a particular output variable is invariant, it is
2385 * necessary to use the invariant qualifier. It can either be used to
2386 * qualify a previously declared variable as being invariant
2388 * invariant gl_Position; // make existing gl_Position be invariant"
2390 * In these cases the parser will set the 'invariant' flag in the declarator
2391 * list, and the type will be NULL.
2393 if (this->invariant) {
2394 assert(this->type == NULL);
2396 if (state->current_function != NULL) {
2397 _mesa_glsl_error(& loc, state,
2398 "All uses of `invariant' keyword must be at global "
2402 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2403 assert(!decl->is_array);
2404 assert(decl->array_size == NULL);
2405 assert(decl->initializer == NULL);
2407 ir_variable *const earlier =
2408 state->symbols->get_variable(decl->identifier);
2409 if (earlier == NULL) {
2410 _mesa_glsl_error(& loc, state,
2411 "Undeclared variable `%s' cannot be marked "
2412 "invariant\n", decl->identifier);
2413 } else if ((state->target == vertex_shader)
2414 && (earlier->mode != ir_var_out)) {
2415 _mesa_glsl_error(& loc, state,
2416 "`%s' cannot be marked invariant, vertex shader "
2417 "outputs only\n", decl->identifier);
2418 } else if ((state->target == fragment_shader)
2419 && (earlier->mode != ir_var_in)) {
2420 _mesa_glsl_error(& loc, state,
2421 "`%s' cannot be marked invariant, fragment shader "
2422 "inputs only\n", decl->identifier);
2423 } else if (earlier->used) {
2424 _mesa_glsl_error(& loc, state,
2425 "variable `%s' may not be redeclared "
2426 "`invariant' after being used",
2429 earlier->invariant = true;
2433 /* Invariant redeclarations do not have r-values.
2438 assert(this->type != NULL);
2439 assert(!this->invariant);
2441 /* The type specifier may contain a structure definition. Process that
2442 * before any of the variable declarations.
2444 (void) this->type->specifier->hir(instructions, state);
2446 decl_type = this->type->specifier->glsl_type(& type_name, state);
2447 if (this->declarations.is_empty()) {
2448 if (decl_type != NULL) {
2449 /* Warn if this empty declaration is not for declaring a structure.
2451 if (this->type->specifier->structure == NULL) {
2452 _mesa_glsl_warning(&loc, state, "empty declaration");
2455 _mesa_glsl_error(& loc, state, "incomplete declaration");
2459 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2460 const struct glsl_type *var_type;
2463 /* FINISHME: Emit a warning if a variable declaration shadows a
2464 * FINISHME: declaration at a higher scope.
2467 if ((decl_type == NULL) || decl_type->is_void()) {
2468 if (type_name != NULL) {
2469 _mesa_glsl_error(& loc, state,
2470 "invalid type `%s' in declaration of `%s'",
2471 type_name, decl->identifier);
2473 _mesa_glsl_error(& loc, state,
2474 "invalid type in declaration of `%s'",
2480 if (decl->is_array) {
2481 var_type = process_array_type(&loc, decl_type, decl->array_size,
2484 var_type = decl_type;
2487 var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
2489 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
2491 * "Global variables can only use the qualifiers const,
2492 * attribute, uni form, or varying. Only one may be
2495 * Local variables can only use the qualifier const."
2497 * This is relaxed in GLSL 1.30. It is also relaxed by any extension
2498 * that adds the 'layout' keyword.
2500 if ((state->language_version < 130)
2501 && !state->ARB_explicit_attrib_location_enable
2502 && !state->ARB_fragment_coord_conventions_enable) {
2503 if (this->type->qualifier.flags.q.out) {
2504 _mesa_glsl_error(& loc, state,
2505 "`out' qualifier in declaration of `%s' "
2506 "only valid for function parameters in %s.",
2507 decl->identifier, state->version_string);
2509 if (this->type->qualifier.flags.q.in) {
2510 _mesa_glsl_error(& loc, state,
2511 "`in' qualifier in declaration of `%s' "
2512 "only valid for function parameters in %s.",
2513 decl->identifier, state->version_string);
2515 /* FINISHME: Test for other invalid qualifiers. */
2518 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
2521 if (this->type->qualifier.flags.q.invariant) {
2522 if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
2523 var->mode == ir_var_inout)) {
2524 /* FINISHME: Note that this doesn't work for invariant on
2525 * a function signature outval
2527 _mesa_glsl_error(& loc, state,
2528 "`%s' cannot be marked invariant, vertex shader "
2529 "outputs only\n", var->name);
2530 } else if ((state->target == fragment_shader) &&
2531 !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
2532 /* FINISHME: Note that this doesn't work for invariant on
2533 * a function signature inval
2535 _mesa_glsl_error(& loc, state,
2536 "`%s' cannot be marked invariant, fragment shader "
2537 "inputs only\n", var->name);
2541 if (state->current_function != NULL) {
2542 const char *mode = NULL;
2543 const char *extra = "";
2545 /* There is no need to check for 'inout' here because the parser will
2546 * only allow that in function parameter lists.
2548 if (this->type->qualifier.flags.q.attribute) {
2550 } else if (this->type->qualifier.flags.q.uniform) {
2552 } else if (this->type->qualifier.flags.q.varying) {
2554 } else if (this->type->qualifier.flags.q.in) {
2556 extra = " or in function parameter list";
2557 } else if (this->type->qualifier.flags.q.out) {
2559 extra = " or in function parameter list";
2563 _mesa_glsl_error(& loc, state,
2564 "%s variable `%s' must be declared at "
2566 mode, var->name, extra);
2568 } else if (var->mode == ir_var_in) {
2569 var->read_only = true;
2571 if (state->target == vertex_shader) {
2572 bool error_emitted = false;
2574 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
2576 * "Vertex shader inputs can only be float, floating-point
2577 * vectors, matrices, signed and unsigned integers and integer
2578 * vectors. Vertex shader inputs can also form arrays of these
2579 * types, but not structures."
2581 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
2583 * "Vertex shader inputs can only be float, floating-point
2584 * vectors, matrices, signed and unsigned integers and integer
2585 * vectors. They cannot be arrays or structures."
2587 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
2589 * "The attribute qualifier can be used only with float,
2590 * floating-point vectors, and matrices. Attribute variables
2591 * cannot be declared as arrays or structures."
2593 const glsl_type *check_type = var->type->is_array()
2594 ? var->type->fields.array : var->type;
2596 switch (check_type->base_type) {
2597 case GLSL_TYPE_FLOAT:
2599 case GLSL_TYPE_UINT:
2601 if (state->language_version > 120)
2605 _mesa_glsl_error(& loc, state,
2606 "vertex shader input / attribute cannot have "
2608 var->type->is_array() ? "array of " : "",
2610 error_emitted = true;
2613 if (!error_emitted && (state->language_version <= 130)
2614 && var->type->is_array()) {
2615 _mesa_glsl_error(& loc, state,
2616 "vertex shader input / attribute cannot have "
2618 error_emitted = true;
2623 /* Integer vertex outputs must be qualified with 'flat'.
2625 * From section 4.3.6 of the GLSL 1.30 spec:
2626 * "If a vertex output is a signed or unsigned integer or integer
2627 * vector, then it must be qualified with the interpolation qualifier
2630 if (state->language_version >= 130
2631 && state->target == vertex_shader
2632 && state->current_function == NULL
2633 && var->type->is_integer()
2634 && var->mode == ir_var_out
2635 && var->interpolation != INTERP_QUALIFIER_FLAT) {
2637 _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
2638 "then it must be qualified with 'flat'");
2642 /* Interpolation qualifiers cannot be applied to 'centroid' and
2643 * 'centroid varying'.
2645 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2646 * "interpolation qualifiers may only precede the qualifiers in,
2647 * centroid in, out, or centroid out in a declaration. They do not apply
2648 * to the deprecated storage qualifiers varying or centroid varying."
2650 if (state->language_version >= 130
2651 && this->type->qualifier.has_interpolation()
2652 && this->type->qualifier.flags.q.varying) {
2654 const char *i = this->type->qualifier.interpolation_string();
2657 if (this->type->qualifier.flags.q.centroid)
2658 s = "centroid varying";
2662 _mesa_glsl_error(&loc, state,
2663 "qualifier '%s' cannot be applied to the "
2664 "deprecated storage qualifier '%s'", i, s);
2668 /* Interpolation qualifiers can only apply to vertex shader outputs and
2669 * fragment shader inputs.
2671 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2672 * "Outputs from a vertex shader (out) and inputs to a fragment
2673 * shader (in) can be further qualified with one or more of these
2674 * interpolation qualifiers"
2676 if (state->language_version >= 130
2677 && this->type->qualifier.has_interpolation()) {
2679 const char *i = this->type->qualifier.interpolation_string();
2682 switch (state->target) {
2684 if (this->type->qualifier.flags.q.in) {
2685 _mesa_glsl_error(&loc, state,
2686 "qualifier '%s' cannot be applied to vertex "
2687 "shader inputs", i);
2690 case fragment_shader:
2691 if (this->type->qualifier.flags.q.out) {
2692 _mesa_glsl_error(&loc, state,
2693 "qualifier '%s' cannot be applied to fragment "
2694 "shader outputs", i);
2703 /* From section 4.3.4 of the GLSL 1.30 spec:
2704 * "It is an error to use centroid in in a vertex shader."
2706 if (state->language_version >= 130
2707 && this->type->qualifier.flags.q.centroid
2708 && this->type->qualifier.flags.q.in
2709 && state->target == vertex_shader) {
2711 _mesa_glsl_error(&loc, state,
2712 "'centroid in' cannot be used in a vertex shader");
2716 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
2718 if (this->type->specifier->precision != ast_precision_none
2719 && state->language_version != 100
2720 && state->language_version < 130) {
2722 _mesa_glsl_error(&loc, state,
2723 "precision qualifiers are supported only in GLSL ES "
2724 "1.00, and GLSL 1.30 and later");
2728 /* Precision qualifiers only apply to floating point and integer types.
2730 * From section 4.5.2 of the GLSL 1.30 spec:
2731 * "Any floating point or any integer declaration can have the type
2732 * preceded by one of these precision qualifiers [...] Literal
2733 * constants do not have precision qualifiers. Neither do Boolean
2736 * In GLSL ES, sampler types are also allowed.
2738 * From page 87 of the GLSL ES spec:
2739 * "RESOLUTION: Allow sampler types to take a precision qualifier."
2741 if (this->type->specifier->precision != ast_precision_none
2742 && !var->type->is_float()
2743 && !var->type->is_integer()
2744 && !(var->type->is_sampler() && state->es_shader)
2745 && !(var->type->is_array()
2746 && (var->type->fields.array->is_float()
2747 || var->type->fields.array->is_integer()))) {
2749 _mesa_glsl_error(&loc, state,
2750 "precision qualifiers apply only to floating point"
2751 "%s types", state->es_shader ? ", integer, and sampler"
2755 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2757 * "[Sampler types] can only be declared as function
2758 * parameters or uniform variables (see Section 4.3.5
2761 if (var_type->contains_sampler() &&
2762 !this->type->qualifier.flags.q.uniform) {
2763 _mesa_glsl_error(&loc, state, "samplers must be declared uniform");
2766 /* Process the initializer and add its instructions to a temporary
2767 * list. This list will be added to the instruction stream (below) after
2768 * the declaration is added. This is done because in some cases (such as
2769 * redeclarations) the declaration may not actually be added to the
2770 * instruction stream.
2772 exec_list initializer_instructions;
2773 ir_variable *earlier = get_variable_being_redeclared(var, decl, state);
2775 if (decl->initializer != NULL) {
2776 result = process_initializer((earlier == NULL) ? var : earlier,
2778 &initializer_instructions, state);
2781 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
2783 * "It is an error to write to a const variable outside of
2784 * its declaration, so they must be initialized when
2787 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
2788 _mesa_glsl_error(& loc, state,
2789 "const declaration of `%s' must be initialized",
2793 /* If the declaration is not a redeclaration, there are a few additional
2794 * semantic checks that must be applied. In addition, variable that was
2795 * created for the declaration should be added to the IR stream.
2797 if (earlier == NULL) {
2798 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2800 * "Identifiers starting with "gl_" are reserved for use by
2801 * OpenGL, and may not be declared in a shader as either a
2802 * variable or a function."
2804 if (strncmp(decl->identifier, "gl_", 3) == 0)
2805 _mesa_glsl_error(& loc, state,
2806 "identifier `%s' uses reserved `gl_' prefix",
2808 else if (strstr(decl->identifier, "__")) {
2809 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
2812 * "In addition, all identifiers containing two
2813 * consecutive underscores (__) are reserved as
2814 * possible future keywords."
2816 _mesa_glsl_error(& loc, state,
2817 "identifier `%s' uses reserved `__' string",
2821 /* Add the variable to the symbol table. Note that the initializer's
2822 * IR was already processed earlier (though it hasn't been emitted
2823 * yet), without the variable in scope.
2825 * This differs from most C-like languages, but it follows the GLSL
2826 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
2829 * "Within a declaration, the scope of a name starts immediately
2830 * after the initializer if present or immediately after the name
2831 * being declared if not."
2833 if (!state->symbols->add_variable(var)) {
2834 YYLTYPE loc = this->get_location();
2835 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
2836 "current scope", decl->identifier);
2840 /* Push the variable declaration to the top. It means that all the
2841 * variable declarations will appear in a funny last-to-first order,
2842 * but otherwise we run into trouble if a function is prototyped, a
2843 * global var is decled, then the function is defined with usage of
2844 * the global var. See glslparsertest's CorrectModule.frag.
2846 instructions->push_head(var);
2849 instructions->append_list(&initializer_instructions);
2853 /* Generally, variable declarations do not have r-values. However,
2854 * one is used for the declaration in
2856 * while (bool b = some_condition()) {
2860 * so we return the rvalue from the last seen declaration here.
2867 ast_parameter_declarator::hir(exec_list *instructions,
2868 struct _mesa_glsl_parse_state *state)
2871 const struct glsl_type *type;
2872 const char *name = NULL;
2873 YYLTYPE loc = this->get_location();
2875 type = this->type->specifier->glsl_type(& name, state);
2879 _mesa_glsl_error(& loc, state,
2880 "invalid type `%s' in declaration of `%s'",
2881 name, this->identifier);
2883 _mesa_glsl_error(& loc, state,
2884 "invalid type in declaration of `%s'",
2888 type = glsl_type::error_type;
2891 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
2893 * "Functions that accept no input arguments need not use void in the
2894 * argument list because prototypes (or definitions) are required and
2895 * therefore there is no ambiguity when an empty argument list "( )" is
2896 * declared. The idiom "(void)" as a parameter list is provided for
2899 * Placing this check here prevents a void parameter being set up
2900 * for a function, which avoids tripping up checks for main taking
2901 * parameters and lookups of an unnamed symbol.
2903 if (type->is_void()) {
2904 if (this->identifier != NULL)
2905 _mesa_glsl_error(& loc, state,
2906 "named parameter cannot have type `void'");
2912 if (formal_parameter && (this->identifier == NULL)) {
2913 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
2917 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
2918 * call already handled the "vec4[..] foo" case.
2920 if (this->is_array) {
2921 type = process_array_type(&loc, type, this->array_size, state);
2924 if (type->array_size() == 0) {
2925 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
2926 "a declared size.");
2927 type = glsl_type::error_type;
2931 ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
2933 /* Apply any specified qualifiers to the parameter declaration. Note that
2934 * for function parameters the default mode is 'in'.
2936 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
2938 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2940 * "Samplers cannot be treated as l-values; hence cannot be used
2941 * as out or inout function parameters, nor can they be assigned
2944 if ((var->mode == ir_var_inout || var->mode == ir_var_out)
2945 && type->contains_sampler()) {
2946 _mesa_glsl_error(&loc, state, "out and inout parameters cannot contain samplers");
2947 type = glsl_type::error_type;
2950 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
2952 * "When calling a function, expressions that do not evaluate to
2953 * l-values cannot be passed to parameters declared as out or inout."
2955 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
2957 * "Other binary or unary expressions, non-dereferenced arrays,
2958 * function names, swizzles with repeated fields, and constants
2959 * cannot be l-values."
2961 * So for GLSL 1.10, passing an array as an out or inout parameter is not
2962 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
2964 if ((var->mode == ir_var_inout || var->mode == ir_var_out)
2965 && type->is_array() && state->language_version == 110) {
2966 _mesa_glsl_error(&loc, state, "Arrays cannot be out or inout parameters in GLSL 1.10");
2967 type = glsl_type::error_type;
2970 instructions->push_tail(var);
2972 /* Parameter declarations do not have r-values.
2979 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
2981 exec_list *ir_parameters,
2982 _mesa_glsl_parse_state *state)
2984 ast_parameter_declarator *void_param = NULL;
2987 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
2988 param->formal_parameter = formal;
2989 param->hir(ir_parameters, state);
2997 if ((void_param != NULL) && (count > 1)) {
2998 YYLTYPE loc = void_param->get_location();
3000 _mesa_glsl_error(& loc, state,
3001 "`void' parameter must be only parameter");
3007 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
3009 /* IR invariants disallow function declarations or definitions
3010 * nested within other function definitions. But there is no
3011 * requirement about the relative order of function declarations
3012 * and definitions with respect to one another. So simply insert
3013 * the new ir_function block at the end of the toplevel instruction
3016 state->toplevel_ir->push_tail(f);
3021 ast_function::hir(exec_list *instructions,
3022 struct _mesa_glsl_parse_state *state)
3025 ir_function *f = NULL;
3026 ir_function_signature *sig = NULL;
3027 exec_list hir_parameters;
3029 const char *const name = identifier;
3031 /* New functions are always added to the top-level IR instruction stream,
3032 * so this instruction list pointer is ignored. See also emit_function
3035 (void) instructions;
3037 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
3039 * "Function declarations (prototypes) cannot occur inside of functions;
3040 * they must be at global scope, or for the built-in functions, outside
3041 * the global scope."
3043 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
3045 * "User defined functions may only be defined within the global scope."
3047 * Note that this language does not appear in GLSL 1.10.
3049 if ((state->current_function != NULL) && (state->language_version != 110)) {
3050 YYLTYPE loc = this->get_location();
3051 _mesa_glsl_error(&loc, state,
3052 "declaration of function `%s' not allowed within "
3053 "function body", name);
3056 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3058 * "Identifiers starting with "gl_" are reserved for use by
3059 * OpenGL, and may not be declared in a shader as either a
3060 * variable or a function."
3062 if (strncmp(name, "gl_", 3) == 0) {
3063 YYLTYPE loc = this->get_location();
3064 _mesa_glsl_error(&loc, state,
3065 "identifier `%s' uses reserved `gl_' prefix", name);
3068 /* Convert the list of function parameters to HIR now so that they can be
3069 * used below to compare this function's signature with previously seen
3070 * signatures for functions with the same name.
3072 ast_parameter_declarator::parameters_to_hir(& this->parameters,
3074 & hir_parameters, state);
3076 const char *return_type_name;
3077 const glsl_type *return_type =
3078 this->return_type->specifier->glsl_type(& return_type_name, state);
3081 YYLTYPE loc = this->get_location();
3082 _mesa_glsl_error(&loc, state,
3083 "function `%s' has undeclared return type `%s'",
3084 name, return_type_name);
3085 return_type = glsl_type::error_type;
3088 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3089 * "No qualifier is allowed on the return type of a function."
3091 if (this->return_type->has_qualifiers()) {
3092 YYLTYPE loc = this->get_location();
3093 _mesa_glsl_error(& loc, state,
3094 "function `%s' return type has qualifiers", name);
3097 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3099 * "[Sampler types] can only be declared as function parameters
3100 * or uniform variables (see Section 4.3.5 "Uniform")".
3102 if (return_type->contains_sampler()) {
3103 YYLTYPE loc = this->get_location();
3104 _mesa_glsl_error(&loc, state,
3105 "function `%s' return type can't contain a sampler",
3109 /* Verify that this function's signature either doesn't match a previously
3110 * seen signature for a function with the same name, or, if a match is found,
3111 * that the previously seen signature does not have an associated definition.
3113 f = state->symbols->get_function(name);
3114 if (f != NULL && (state->es_shader || f->has_user_signature())) {
3115 sig = f->exact_matching_signature(&hir_parameters);
3117 const char *badvar = sig->qualifiers_match(&hir_parameters);
3118 if (badvar != NULL) {
3119 YYLTYPE loc = this->get_location();
3121 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
3122 "qualifiers don't match prototype", name, badvar);
3125 if (sig->return_type != return_type) {
3126 YYLTYPE loc = this->get_location();
3128 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
3129 "match prototype", name);
3132 if (is_definition && sig->is_defined) {
3133 YYLTYPE loc = this->get_location();
3135 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
3139 f = new(ctx) ir_function(name);
3140 if (!state->symbols->add_function(f)) {
3141 /* This function name shadows a non-function use of the same name. */
3142 YYLTYPE loc = this->get_location();
3144 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
3145 "non-function", name);
3149 emit_function(state, f);
3152 /* Verify the return type of main() */
3153 if (strcmp(name, "main") == 0) {
3154 if (! return_type->is_void()) {
3155 YYLTYPE loc = this->get_location();
3157 _mesa_glsl_error(& loc, state, "main() must return void");
3160 if (!hir_parameters.is_empty()) {
3161 YYLTYPE loc = this->get_location();
3163 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
3167 /* Finish storing the information about this new function in its signature.
3170 sig = new(ctx) ir_function_signature(return_type);
3171 f->add_signature(sig);
3174 sig->replace_parameters(&hir_parameters);
3177 /* Function declarations (prototypes) do not have r-values.
3184 ast_function_definition::hir(exec_list *instructions,
3185 struct _mesa_glsl_parse_state *state)
3187 prototype->is_definition = true;
3188 prototype->hir(instructions, state);
3190 ir_function_signature *signature = prototype->signature;
3191 if (signature == NULL)
3194 assert(state->current_function == NULL);
3195 state->current_function = signature;
3196 state->found_return = false;
3198 /* Duplicate parameters declared in the prototype as concrete variables.
3199 * Add these to the symbol table.
3201 state->symbols->push_scope();
3202 foreach_iter(exec_list_iterator, iter, signature->parameters) {
3203 ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
3205 assert(var != NULL);
3207 /* The only way a parameter would "exist" is if two parameters have
3210 if (state->symbols->name_declared_this_scope(var->name)) {
3211 YYLTYPE loc = this->get_location();
3213 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
3215 state->symbols->add_variable(var);
3219 /* Convert the body of the function to HIR. */
3220 this->body->hir(&signature->body, state);
3221 signature->is_defined = true;
3223 state->symbols->pop_scope();
3225 assert(state->current_function == signature);
3226 state->current_function = NULL;
3228 if (!signature->return_type->is_void() && !state->found_return) {
3229 YYLTYPE loc = this->get_location();
3230 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
3231 "%s, but no return statement",
3232 signature->function_name(),
3233 signature->return_type->name);
3236 /* Function definitions do not have r-values.
3243 ast_jump_statement::hir(exec_list *instructions,
3244 struct _mesa_glsl_parse_state *state)
3251 assert(state->current_function);
3253 if (opt_return_value) {
3254 ir_rvalue *const ret = opt_return_value->hir(instructions, state);
3256 /* The value of the return type can be NULL if the shader says
3257 * 'return foo();' and foo() is a function that returns void.
3259 * NOTE: The GLSL spec doesn't say that this is an error. The type
3260 * of the return value is void. If the return type of the function is
3261 * also void, then this should compile without error. Seriously.
3263 const glsl_type *const ret_type =
3264 (ret == NULL) ? glsl_type::void_type : ret->type;
3266 /* Implicit conversions are not allowed for return values. */
3267 if (state->current_function->return_type != ret_type) {
3268 YYLTYPE loc = this->get_location();
3270 _mesa_glsl_error(& loc, state,
3271 "`return' with wrong type %s, in function `%s' "
3274 state->current_function->function_name(),
3275 state->current_function->return_type->name);
3278 inst = new(ctx) ir_return(ret);
3280 if (state->current_function->return_type->base_type !=
3282 YYLTYPE loc = this->get_location();
3284 _mesa_glsl_error(& loc, state,
3285 "`return' with no value, in function %s returning "
3287 state->current_function->function_name());
3289 inst = new(ctx) ir_return;
3292 state->found_return = true;
3293 instructions->push_tail(inst);
3298 if (state->target != fragment_shader) {
3299 YYLTYPE loc = this->get_location();
3301 _mesa_glsl_error(& loc, state,
3302 "`discard' may only appear in a fragment shader");
3304 instructions->push_tail(new(ctx) ir_discard);
3309 /* FINISHME: Handle switch-statements. They cannot contain 'continue',
3310 * FINISHME: and they use a different IR instruction for 'break'.
3312 /* FINISHME: Correctly handle the nesting. If a switch-statement is
3313 * FINISHME: inside a loop, a 'continue' is valid and will bind to the
3316 if (state->loop_or_switch_nesting == NULL) {
3317 YYLTYPE loc = this->get_location();
3319 _mesa_glsl_error(& loc, state,
3320 "`%s' may only appear in a loop",
3321 (mode == ast_break) ? "break" : "continue");
3323 ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
3325 /* Inline the for loop expression again, since we don't know
3326 * where near the end of the loop body the normal copy of it
3327 * is going to be placed.
3329 if (mode == ast_continue &&
3330 state->loop_or_switch_nesting_ast->rest_expression) {
3331 state->loop_or_switch_nesting_ast->rest_expression->hir(instructions,
3336 ir_loop_jump *const jump =
3337 new(ctx) ir_loop_jump((mode == ast_break)
3338 ? ir_loop_jump::jump_break
3339 : ir_loop_jump::jump_continue);
3340 instructions->push_tail(jump);
3347 /* Jump instructions do not have r-values.
3354 ast_selection_statement::hir(exec_list *instructions,
3355 struct _mesa_glsl_parse_state *state)
3359 ir_rvalue *const condition = this->condition->hir(instructions, state);
3361 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
3363 * "Any expression whose type evaluates to a Boolean can be used as the
3364 * conditional expression bool-expression. Vector types are not accepted
3365 * as the expression to if."
3367 * The checks are separated so that higher quality diagnostics can be
3368 * generated for cases where both rules are violated.
3370 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
3371 YYLTYPE loc = this->condition->get_location();
3373 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
3377 ir_if *const stmt = new(ctx) ir_if(condition);
3379 if (then_statement != NULL) {
3380 state->symbols->push_scope();
3381 then_statement->hir(& stmt->then_instructions, state);
3382 state->symbols->pop_scope();
3385 if (else_statement != NULL) {
3386 state->symbols->push_scope();
3387 else_statement->hir(& stmt->else_instructions, state);
3388 state->symbols->pop_scope();
3391 instructions->push_tail(stmt);
3393 /* if-statements do not have r-values.
3400 ast_iteration_statement::condition_to_hir(ir_loop *stmt,
3401 struct _mesa_glsl_parse_state *state)
3405 if (condition != NULL) {
3406 ir_rvalue *const cond =
3407 condition->hir(& stmt->body_instructions, state);
3410 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
3411 YYLTYPE loc = condition->get_location();
3413 _mesa_glsl_error(& loc, state,
3414 "loop condition must be scalar boolean");
3416 /* As the first code in the loop body, generate a block that looks
3417 * like 'if (!condition) break;' as the loop termination condition.
3419 ir_rvalue *const not_cond =
3420 new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
3423 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
3425 ir_jump *const break_stmt =
3426 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
3428 if_stmt->then_instructions.push_tail(break_stmt);
3429 stmt->body_instructions.push_tail(if_stmt);
3436 ast_iteration_statement::hir(exec_list *instructions,
3437 struct _mesa_glsl_parse_state *state)
3441 /* For-loops and while-loops start a new scope, but do-while loops do not.
3443 if (mode != ast_do_while)
3444 state->symbols->push_scope();
3446 if (init_statement != NULL)
3447 init_statement->hir(instructions, state);
3449 ir_loop *const stmt = new(ctx) ir_loop();
3450 instructions->push_tail(stmt);
3452 /* Track the current loop and / or switch-statement nesting.
3454 ir_instruction *const nesting = state->loop_or_switch_nesting;
3455 ast_iteration_statement *nesting_ast = state->loop_or_switch_nesting_ast;
3457 state->loop_or_switch_nesting = stmt;
3458 state->loop_or_switch_nesting_ast = this;
3460 if (mode != ast_do_while)
3461 condition_to_hir(stmt, state);
3464 body->hir(& stmt->body_instructions, state);
3466 if (rest_expression != NULL)
3467 rest_expression->hir(& stmt->body_instructions, state);
3469 if (mode == ast_do_while)
3470 condition_to_hir(stmt, state);
3472 if (mode != ast_do_while)
3473 state->symbols->pop_scope();
3475 /* Restore previous nesting before returning.
3477 state->loop_or_switch_nesting = nesting;
3478 state->loop_or_switch_nesting_ast = nesting_ast;
3480 /* Loops do not have r-values.
3487 ast_type_specifier::hir(exec_list *instructions,
3488 struct _mesa_glsl_parse_state *state)
3490 if (!this->is_precision_statement && this->structure == NULL)
3493 YYLTYPE loc = this->get_location();
3495 if (this->precision != ast_precision_none
3496 && state->language_version != 100
3497 && state->language_version < 130) {
3498 _mesa_glsl_error(&loc, state,
3499 "precision qualifiers exist only in "
3500 "GLSL ES 1.00, and GLSL 1.30 and later");
3503 if (this->precision != ast_precision_none
3504 && this->structure != NULL) {
3505 _mesa_glsl_error(&loc, state,
3506 "precision qualifiers do not apply to structures");
3510 /* If this is a precision statement, check that the type to which it is
3511 * applied is either float or int.
3513 * From section 4.5.3 of the GLSL 1.30 spec:
3514 * "The precision statement
3515 * precision precision-qualifier type;
3516 * can be used to establish a default precision qualifier. The type
3517 * field can be either int or float [...]. Any other types or
3518 * qualifiers will result in an error.
3520 if (this->is_precision_statement) {
3521 assert(this->precision != ast_precision_none);
3522 assert(this->structure == NULL); /* The check for structures was
3523 * performed above. */
3524 if (this->is_array) {
3525 _mesa_glsl_error(&loc, state,
3526 "default precision statements do not apply to "
3530 if (this->type_specifier != ast_float
3531 && this->type_specifier != ast_int) {
3532 _mesa_glsl_error(&loc, state,
3533 "default precision statements apply only to types "
3538 /* FINISHME: Translate precision statements into IR. */
3542 if (this->structure != NULL)
3543 return this->structure->hir(instructions, state);
3550 ast_struct_specifier::hir(exec_list *instructions,
3551 struct _mesa_glsl_parse_state *state)
3553 unsigned decl_count = 0;
3555 /* Make an initial pass over the list of structure fields to determine how
3556 * many there are. Each element in this list is an ast_declarator_list.
3557 * This means that we actually need to count the number of elements in the
3558 * 'declarations' list in each of the elements.
3560 foreach_list_typed (ast_declarator_list, decl_list, link,
3561 &this->declarations) {
3562 foreach_list_const (decl_ptr, & decl_list->declarations) {
3567 /* Allocate storage for the structure fields and process the field
3568 * declarations. As the declarations are processed, try to also convert
3569 * the types to HIR. This ensures that structure definitions embedded in
3570 * other structure definitions are processed.
3572 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
3576 foreach_list_typed (ast_declarator_list, decl_list, link,
3577 &this->declarations) {
3578 const char *type_name;
3580 decl_list->type->specifier->hir(instructions, state);
3582 /* Section 10.9 of the GLSL ES 1.00 specification states that
3583 * embedded structure definitions have been removed from the language.
3585 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
3586 YYLTYPE loc = this->get_location();
3587 _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
3588 "not allowed in GLSL ES 1.00.");
3591 const glsl_type *decl_type =
3592 decl_list->type->specifier->glsl_type(& type_name, state);
3594 foreach_list_typed (ast_declaration, decl, link,
3595 &decl_list->declarations) {
3596 const struct glsl_type *field_type = decl_type;
3597 if (decl->is_array) {
3598 YYLTYPE loc = decl->get_location();
3599 field_type = process_array_type(&loc, decl_type, decl->array_size,
3602 fields[i].type = (field_type != NULL)
3603 ? field_type : glsl_type::error_type;
3604 fields[i].name = decl->identifier;
3609 assert(i == decl_count);
3611 const glsl_type *t =
3612 glsl_type::get_record_instance(fields, decl_count, this->name);
3614 YYLTYPE loc = this->get_location();
3615 if (!state->symbols->add_type(name, t)) {
3616 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
3618 const glsl_type **s = reralloc(state, state->user_structures,
3620 state->num_user_structures + 1);
3622 s[state->num_user_structures] = t;
3623 state->user_structures = s;
3624 state->num_user_structures++;
3628 /* Structure type definitions do not have r-values.