revert between 56095 -> 55830 in arch
[AROS.git] / workbench / libs / mesa / src / glsl / ast_to_hir.cpp
blob620286aae665b1f7f6158405c361b0b764795514
1 /*
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
13 * Software.
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.
24 /**
25 * \file ast_to_hir.c
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
32 * * Type checking
33 * * Function binding
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"
55 #include "ast.h"
56 #include "glsl_types.h"
57 #include "ir.h"
59 void
60 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
62 _mesa_glsl_initialize_variables(instructions, state);
63 _mesa_glsl_initialize_functions(state);
65 state->symbols->language_version = state->language_version;
67 state->current_function = NULL;
69 /* Section 4.2 of the GLSL 1.20 specification states:
70 * "The built-in functions are scoped in a scope outside the global scope
71 * users declare global variables in. That is, a shader's global scope,
72 * available for user-defined functions and global variables, is nested
73 * inside the scope containing the built-in functions."
75 * Since built-in functions like ftransform() access built-in variables,
76 * it follows that those must be in the outer scope as well.
78 * We push scope here to create this nesting effect...but don't pop.
79 * This way, a shader's globals are still in the symbol table for use
80 * by the linker.
82 state->symbols->push_scope();
84 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
85 ast->hir(instructions, state);
87 detect_recursion_unlinked(state, instructions);
91 /**
92 * If a conversion is available, convert one operand to a different type
94 * The \c from \c ir_rvalue is converted "in place".
96 * \param to Type that the operand it to be converted to
97 * \param from Operand that is being converted
98 * \param state GLSL compiler state
100 * \return
101 * If a conversion is possible (or unnecessary), \c true is returned.
102 * Otherwise \c false is returned.
104 bool
105 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
106 struct _mesa_glsl_parse_state *state)
108 void *ctx = state;
109 if (to->base_type == from->type->base_type)
110 return true;
112 /* This conversion was added in GLSL 1.20. If the compilation mode is
113 * GLSL 1.10, the conversion is skipped.
115 if (state->language_version < 120)
116 return false;
118 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
120 * "There are no implicit array or structure conversions. For
121 * example, an array of int cannot be implicitly converted to an
122 * array of float. There are no implicit conversions between
123 * signed and unsigned integers."
125 /* FINISHME: The above comment is partially a lie. There is int/uint
126 * FINISHME: conversion for immediate constants.
128 if (!to->is_float() || !from->type->is_numeric())
129 return false;
131 /* Convert to a floating point type with the same number of components
132 * as the original type - i.e. int to float, not int to vec4.
134 to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
135 from->type->matrix_columns);
137 switch (from->type->base_type) {
138 case GLSL_TYPE_INT:
139 from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
140 break;
141 case GLSL_TYPE_UINT:
142 from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
143 break;
144 case GLSL_TYPE_BOOL:
145 from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
146 break;
147 default:
148 assert(0);
151 return true;
155 static const struct glsl_type *
156 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
157 bool multiply,
158 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
160 const glsl_type *type_a = value_a->type;
161 const glsl_type *type_b = value_b->type;
163 /* From GLSL 1.50 spec, page 56:
165 * "The arithmetic binary operators add (+), subtract (-),
166 * multiply (*), and divide (/) operate on integer and
167 * floating-point scalars, vectors, and matrices."
169 if (!type_a->is_numeric() || !type_b->is_numeric()) {
170 _mesa_glsl_error(loc, state,
171 "Operands to arithmetic operators must be numeric");
172 return glsl_type::error_type;
176 /* "If one operand is floating-point based and the other is
177 * not, then the conversions from Section 4.1.10 "Implicit
178 * Conversions" are applied to the non-floating-point-based operand."
180 if (!apply_implicit_conversion(type_a, value_b, state)
181 && !apply_implicit_conversion(type_b, value_a, state)) {
182 _mesa_glsl_error(loc, state,
183 "Could not implicitly convert operands to "
184 "arithmetic operator");
185 return glsl_type::error_type;
187 type_a = value_a->type;
188 type_b = value_b->type;
190 /* "If the operands are integer types, they must both be signed or
191 * both be unsigned."
193 * From this rule and the preceeding conversion it can be inferred that
194 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
195 * The is_numeric check above already filtered out the case where either
196 * type is not one of these, so now the base types need only be tested for
197 * equality.
199 if (type_a->base_type != type_b->base_type) {
200 _mesa_glsl_error(loc, state,
201 "base type mismatch for arithmetic operator");
202 return glsl_type::error_type;
205 /* "All arithmetic binary operators result in the same fundamental type
206 * (signed integer, unsigned integer, or floating-point) as the
207 * operands they operate on, after operand type conversion. After
208 * conversion, the following cases are valid
210 * * The two operands are scalars. In this case the operation is
211 * applied, resulting in a scalar."
213 if (type_a->is_scalar() && type_b->is_scalar())
214 return type_a;
216 /* "* One operand is a scalar, and the other is a vector or matrix.
217 * In this case, the scalar operation is applied independently to each
218 * component of the vector or matrix, resulting in the same size
219 * vector or matrix."
221 if (type_a->is_scalar()) {
222 if (!type_b->is_scalar())
223 return type_b;
224 } else if (type_b->is_scalar()) {
225 return type_a;
228 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
229 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
230 * handled.
232 assert(!type_a->is_scalar());
233 assert(!type_b->is_scalar());
235 /* "* The two operands are vectors of the same size. In this case, the
236 * operation is done component-wise resulting in the same size
237 * vector."
239 if (type_a->is_vector() && type_b->is_vector()) {
240 if (type_a == type_b) {
241 return type_a;
242 } else {
243 _mesa_glsl_error(loc, state,
244 "vector size mismatch for arithmetic operator");
245 return glsl_type::error_type;
249 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
250 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
251 * <vector, vector> have been handled. At least one of the operands must
252 * be matrix. Further, since there are no integer matrix types, the base
253 * type of both operands must be float.
255 assert(type_a->is_matrix() || type_b->is_matrix());
256 assert(type_a->base_type == GLSL_TYPE_FLOAT);
257 assert(type_b->base_type == GLSL_TYPE_FLOAT);
259 /* "* The operator is add (+), subtract (-), or divide (/), and the
260 * operands are matrices with the same number of rows and the same
261 * number of columns. In this case, the operation is done component-
262 * wise resulting in the same size matrix."
263 * * The operator is multiply (*), where both operands are matrices or
264 * one operand is a vector and the other a matrix. A right vector
265 * operand is treated as a column vector and a left vector operand as a
266 * row vector. In all these cases, it is required that the number of
267 * columns of the left operand is equal to the number of rows of the
268 * right operand. Then, the multiply (*) operation does a linear
269 * algebraic multiply, yielding an object that has the same number of
270 * rows as the left operand and the same number of columns as the right
271 * operand. Section 5.10 "Vector and Matrix Operations" explains in
272 * more detail how vectors and matrices are operated on."
274 if (! multiply) {
275 if (type_a == type_b)
276 return type_a;
277 } else {
278 if (type_a->is_matrix() && type_b->is_matrix()) {
279 /* Matrix multiply. The columns of A must match the rows of B. Given
280 * the other previously tested constraints, this means the vector type
281 * of a row from A must be the same as the vector type of a column from
282 * B.
284 if (type_a->row_type() == type_b->column_type()) {
285 /* The resulting matrix has the number of columns of matrix B and
286 * the number of rows of matrix A. We get the row count of A by
287 * looking at the size of a vector that makes up a column. The
288 * transpose (size of a row) is done for B.
290 const glsl_type *const type =
291 glsl_type::get_instance(type_a->base_type,
292 type_a->column_type()->vector_elements,
293 type_b->row_type()->vector_elements);
294 assert(type != glsl_type::error_type);
296 return type;
298 } else if (type_a->is_matrix()) {
299 /* A is a matrix and B is a column vector. Columns of A must match
300 * rows of B. Given the other previously tested constraints, this
301 * means the vector type of a row from A must be the same as the
302 * vector the type of B.
304 if (type_a->row_type() == type_b) {
305 /* The resulting vector has a number of elements equal to
306 * the number of rows of matrix A. */
307 const glsl_type *const type =
308 glsl_type::get_instance(type_a->base_type,
309 type_a->column_type()->vector_elements,
311 assert(type != glsl_type::error_type);
313 return type;
315 } else {
316 assert(type_b->is_matrix());
318 /* A is a row vector and B is a matrix. Columns of A must match rows
319 * of B. Given the other previously tested constraints, this means
320 * the type of A must be the same as the vector type of a column from
321 * B.
323 if (type_a == type_b->column_type()) {
324 /* The resulting vector has a number of elements equal to
325 * the number of columns of matrix B. */
326 const glsl_type *const type =
327 glsl_type::get_instance(type_a->base_type,
328 type_b->row_type()->vector_elements,
330 assert(type != glsl_type::error_type);
332 return type;
336 _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
337 return glsl_type::error_type;
341 /* "All other cases are illegal."
343 _mesa_glsl_error(loc, state, "type mismatch");
344 return glsl_type::error_type;
348 static const struct glsl_type *
349 unary_arithmetic_result_type(const struct glsl_type *type,
350 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
352 /* From GLSL 1.50 spec, page 57:
354 * "The arithmetic unary operators negate (-), post- and pre-increment
355 * and decrement (-- and ++) operate on integer or floating-point
356 * values (including vectors and matrices). All unary operators work
357 * component-wise on their operands. These result with the same type
358 * they operated on."
360 if (!type->is_numeric()) {
361 _mesa_glsl_error(loc, state,
362 "Operands to arithmetic operators must be numeric");
363 return glsl_type::error_type;
366 return type;
370 * \brief Return the result type of a bit-logic operation.
372 * If the given types to the bit-logic operator are invalid, return
373 * glsl_type::error_type.
375 * \param type_a Type of LHS of bit-logic op
376 * \param type_b Type of RHS of bit-logic op
378 static const struct glsl_type *
379 bit_logic_result_type(const struct glsl_type *type_a,
380 const struct glsl_type *type_b,
381 ast_operators op,
382 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
384 if (state->language_version < 130) {
385 _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
386 return glsl_type::error_type;
389 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
391 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
392 * (|). The operands must be of type signed or unsigned integers or
393 * integer vectors."
395 if (!type_a->is_integer()) {
396 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
397 ast_expression::operator_string(op));
398 return glsl_type::error_type;
400 if (!type_b->is_integer()) {
401 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
402 ast_expression::operator_string(op));
403 return glsl_type::error_type;
406 /* "The fundamental types of the operands (signed or unsigned) must
407 * match,"
409 if (type_a->base_type != type_b->base_type) {
410 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
411 "base type", ast_expression::operator_string(op));
412 return glsl_type::error_type;
415 /* "The operands cannot be vectors of differing size." */
416 if (type_a->is_vector() &&
417 type_b->is_vector() &&
418 type_a->vector_elements != type_b->vector_elements) {
419 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
420 "different sizes", ast_expression::operator_string(op));
421 return glsl_type::error_type;
424 /* "If one operand is a scalar and the other a vector, the scalar is
425 * applied component-wise to the vector, resulting in the same type as
426 * the vector. The fundamental types of the operands [...] will be the
427 * resulting fundamental type."
429 if (type_a->is_scalar())
430 return type_b;
431 else
432 return type_a;
435 static const struct glsl_type *
436 modulus_result_type(const struct glsl_type *type_a,
437 const struct glsl_type *type_b,
438 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
440 if (state->language_version < 130) {
441 _mesa_glsl_error(loc, state,
442 "operator '%%' is reserved in %s",
443 state->version_string);
444 return glsl_type::error_type;
447 /* From GLSL 1.50 spec, page 56:
448 * "The operator modulus (%) operates on signed or unsigned integers or
449 * integer vectors. The operand types must both be signed or both be
450 * unsigned."
452 if (!type_a->is_integer() || !type_b->is_integer()
453 || (type_a->base_type != type_b->base_type)) {
454 _mesa_glsl_error(loc, state, "type mismatch");
455 return glsl_type::error_type;
458 /* "The operands cannot be vectors of differing size. If one operand is
459 * a scalar and the other vector, then the scalar is applied component-
460 * wise to the vector, resulting in the same type as the vector. If both
461 * are vectors of the same size, the result is computed component-wise."
463 if (type_a->is_vector()) {
464 if (!type_b->is_vector()
465 || (type_a->vector_elements == type_b->vector_elements))
466 return type_a;
467 } else
468 return type_b;
470 /* "The operator modulus (%) is not defined for any other data types
471 * (non-integer types)."
473 _mesa_glsl_error(loc, state, "type mismatch");
474 return glsl_type::error_type;
478 static const struct glsl_type *
479 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
480 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
482 const glsl_type *type_a = value_a->type;
483 const glsl_type *type_b = value_b->type;
485 /* From GLSL 1.50 spec, page 56:
486 * "The relational operators greater than (>), less than (<), greater
487 * than or equal (>=), and less than or equal (<=) operate only on
488 * scalar integer and scalar floating-point expressions."
490 if (!type_a->is_numeric()
491 || !type_b->is_numeric()
492 || !type_a->is_scalar()
493 || !type_b->is_scalar()) {
494 _mesa_glsl_error(loc, state,
495 "Operands to relational operators must be scalar and "
496 "numeric");
497 return glsl_type::error_type;
500 /* "Either the operands' types must match, or the conversions from
501 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
502 * operand, after which the types must match."
504 if (!apply_implicit_conversion(type_a, value_b, state)
505 && !apply_implicit_conversion(type_b, value_a, state)) {
506 _mesa_glsl_error(loc, state,
507 "Could not implicitly convert operands to "
508 "relational operator");
509 return glsl_type::error_type;
511 type_a = value_a->type;
512 type_b = value_b->type;
514 if (type_a->base_type != type_b->base_type) {
515 _mesa_glsl_error(loc, state, "base type mismatch");
516 return glsl_type::error_type;
519 /* "The result is scalar Boolean."
521 return glsl_type::bool_type;
525 * \brief Return the result type of a bit-shift operation.
527 * If the given types to the bit-shift operator are invalid, return
528 * glsl_type::error_type.
530 * \param type_a Type of LHS of bit-shift op
531 * \param type_b Type of RHS of bit-shift op
533 static const struct glsl_type *
534 shift_result_type(const struct glsl_type *type_a,
535 const struct glsl_type *type_b,
536 ast_operators op,
537 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
539 if (state->language_version < 130) {
540 _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
541 return glsl_type::error_type;
544 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
546 * "The shift operators (<<) and (>>). For both operators, the operands
547 * must be signed or unsigned integers or integer vectors. One operand
548 * can be signed while the other is unsigned."
550 if (!type_a->is_integer()) {
551 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
552 "integer vector", ast_expression::operator_string(op));
553 return glsl_type::error_type;
556 if (!type_b->is_integer()) {
557 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
558 "integer vector", ast_expression::operator_string(op));
559 return glsl_type::error_type;
562 /* "If the first operand is a scalar, the second operand has to be
563 * a scalar as well."
565 if (type_a->is_scalar() && !type_b->is_scalar()) {
566 _mesa_glsl_error(loc, state, "If the first operand of %s is scalar, the "
567 "second must be scalar as well",
568 ast_expression::operator_string(op));
569 return glsl_type::error_type;
572 /* If both operands are vectors, check that they have same number of
573 * elements.
575 if (type_a->is_vector() &&
576 type_b->is_vector() &&
577 type_a->vector_elements != type_b->vector_elements) {
578 _mesa_glsl_error(loc, state, "Vector operands to operator %s must "
579 "have same number of elements",
580 ast_expression::operator_string(op));
581 return glsl_type::error_type;
584 /* "In all cases, the resulting type will be the same type as the left
585 * operand."
587 return type_a;
591 * Validates that a value can be assigned to a location with a specified type
593 * Validates that \c rhs can be assigned to some location. If the types are
594 * not an exact match but an automatic conversion is possible, \c rhs will be
595 * converted.
597 * \return
598 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
599 * Otherwise the actual RHS to be assigned will be returned. This may be
600 * \c rhs, or it may be \c rhs after some type conversion.
602 * \note
603 * In addition to being used for assignments, this function is used to
604 * type-check return values.
606 ir_rvalue *
607 validate_assignment(struct _mesa_glsl_parse_state *state,
608 const glsl_type *lhs_type, ir_rvalue *rhs,
609 bool is_initializer)
611 /* If there is already some error in the RHS, just return it. Anything
612 * else will lead to an avalanche of error message back to the user.
614 if (rhs->type->is_error())
615 return rhs;
617 /* If the types are identical, the assignment can trivially proceed.
619 if (rhs->type == lhs_type)
620 return rhs;
622 /* If the array element types are the same and the size of the LHS is zero,
623 * the assignment is okay for initializers embedded in variable
624 * declarations.
626 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
627 * is handled by ir_dereference::is_lvalue.
629 if (is_initializer && lhs_type->is_array() && rhs->type->is_array()
630 && (lhs_type->element_type() == rhs->type->element_type())
631 && (lhs_type->array_size() == 0)) {
632 return rhs;
635 /* Check for implicit conversion in GLSL 1.20 */
636 if (apply_implicit_conversion(lhs_type, rhs, state)) {
637 if (rhs->type == lhs_type)
638 return rhs;
641 return NULL;
644 ir_rvalue *
645 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
646 ir_rvalue *lhs, ir_rvalue *rhs, bool is_initializer,
647 YYLTYPE lhs_loc)
649 void *ctx = state;
650 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
652 if (!error_emitted) {
653 if (lhs->variable_referenced() != NULL
654 && lhs->variable_referenced()->read_only) {
655 _mesa_glsl_error(&lhs_loc, state,
656 "assignment to read-only variable '%s'",
657 lhs->variable_referenced()->name);
658 error_emitted = true;
660 } else if (!lhs->is_lvalue()) {
661 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
662 error_emitted = true;
665 if (state->es_shader && lhs->type->is_array()) {
666 _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
667 "allowed in GLSL ES 1.00.");
668 error_emitted = true;
672 ir_rvalue *new_rhs =
673 validate_assignment(state, lhs->type, rhs, is_initializer);
674 if (new_rhs == NULL) {
675 _mesa_glsl_error(& lhs_loc, state, "type mismatch");
676 } else {
677 rhs = new_rhs;
679 /* If the LHS array was not declared with a size, it takes it size from
680 * the RHS. If the LHS is an l-value and a whole array, it must be a
681 * dereference of a variable. Any other case would require that the LHS
682 * is either not an l-value or not a whole array.
684 if (lhs->type->array_size() == 0) {
685 ir_dereference *const d = lhs->as_dereference();
687 assert(d != NULL);
689 ir_variable *const var = d->variable_referenced();
691 assert(var != NULL);
693 if (var->max_array_access >= unsigned(rhs->type->array_size())) {
694 /* FINISHME: This should actually log the location of the RHS. */
695 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
696 "previous access",
697 var->max_array_access);
700 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
701 rhs->type->array_size());
702 d->type = var->type;
706 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
707 * but not post_inc) need the converted assigned value as an rvalue
708 * to handle things like:
710 * i = j += 1;
712 * So we always just store the computed value being assigned to a
713 * temporary and return a deref of that temporary. If the rvalue
714 * ends up not being used, the temp will get copy-propagated out.
716 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
717 ir_var_temporary);
718 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
719 instructions->push_tail(var);
720 instructions->push_tail(new(ctx) ir_assignment(deref_var,
721 rhs,
722 NULL));
723 deref_var = new(ctx) ir_dereference_variable(var);
725 if (!error_emitted)
726 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
728 return new(ctx) ir_dereference_variable(var);
731 static ir_rvalue *
732 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
734 void *ctx = ralloc_parent(lvalue);
735 ir_variable *var;
737 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
738 ir_var_temporary);
739 instructions->push_tail(var);
740 var->mode = ir_var_auto;
742 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
743 lvalue, NULL));
745 /* Once we've created this temporary, mark it read only so it's no
746 * longer considered an lvalue.
748 var->read_only = true;
750 return new(ctx) ir_dereference_variable(var);
754 ir_rvalue *
755 ast_node::hir(exec_list *instructions,
756 struct _mesa_glsl_parse_state *state)
758 (void) instructions;
759 (void) state;
761 return NULL;
764 static void
765 mark_whole_array_access(ir_rvalue *access)
767 ir_dereference_variable *deref = access->as_dereference_variable();
769 if (deref) {
770 deref->var->max_array_access = deref->type->length - 1;
774 static ir_rvalue *
775 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
777 int join_op;
778 ir_rvalue *cmp = NULL;
780 if (operation == ir_binop_all_equal)
781 join_op = ir_binop_logic_and;
782 else
783 join_op = ir_binop_logic_or;
785 switch (op0->type->base_type) {
786 case GLSL_TYPE_FLOAT:
787 case GLSL_TYPE_UINT:
788 case GLSL_TYPE_INT:
789 case GLSL_TYPE_BOOL:
790 return new(mem_ctx) ir_expression(operation, op0, op1);
792 case GLSL_TYPE_ARRAY: {
793 for (unsigned int i = 0; i < op0->type->length; i++) {
794 ir_rvalue *e0, *e1, *result;
796 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
797 new(mem_ctx) ir_constant(i));
798 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
799 new(mem_ctx) ir_constant(i));
800 result = do_comparison(mem_ctx, operation, e0, e1);
802 if (cmp) {
803 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
804 } else {
805 cmp = result;
809 mark_whole_array_access(op0);
810 mark_whole_array_access(op1);
811 break;
814 case GLSL_TYPE_STRUCT: {
815 for (unsigned int i = 0; i < op0->type->length; i++) {
816 ir_rvalue *e0, *e1, *result;
817 const char *field_name = op0->type->fields.structure[i].name;
819 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
820 field_name);
821 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
822 field_name);
823 result = do_comparison(mem_ctx, operation, e0, e1);
825 if (cmp) {
826 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
827 } else {
828 cmp = result;
831 break;
834 case GLSL_TYPE_ERROR:
835 case GLSL_TYPE_VOID:
836 case GLSL_TYPE_SAMPLER:
837 /* I assume a comparison of a struct containing a sampler just
838 * ignores the sampler present in the type.
840 break;
842 default:
843 assert(!"Should not get here.");
844 break;
847 if (cmp == NULL)
848 cmp = new(mem_ctx) ir_constant(true);
850 return cmp;
853 /* For logical operations, we want to ensure that the operands are
854 * scalar booleans. If it isn't, emit an error and return a constant
855 * boolean to avoid triggering cascading error messages.
857 ir_rvalue *
858 get_scalar_boolean_operand(exec_list *instructions,
859 struct _mesa_glsl_parse_state *state,
860 ast_expression *parent_expr,
861 int operand,
862 const char *operand_name,
863 bool *error_emitted)
865 ast_expression *expr = parent_expr->subexpressions[operand];
866 void *ctx = state;
867 ir_rvalue *val = expr->hir(instructions, state);
869 if (val->type->is_boolean() && val->type->is_scalar())
870 return val;
872 if (!*error_emitted) {
873 YYLTYPE loc = expr->get_location();
874 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
875 operand_name,
876 parent_expr->operator_string(parent_expr->oper));
877 *error_emitted = true;
880 return new(ctx) ir_constant(true);
883 ir_rvalue *
884 ast_expression::hir(exec_list *instructions,
885 struct _mesa_glsl_parse_state *state)
887 void *ctx = state;
888 static const int operations[AST_NUM_OPERATORS] = {
889 -1, /* ast_assign doesn't convert to ir_expression. */
890 -1, /* ast_plus doesn't convert to ir_expression. */
891 ir_unop_neg,
892 ir_binop_add,
893 ir_binop_sub,
894 ir_binop_mul,
895 ir_binop_div,
896 ir_binop_mod,
897 ir_binop_lshift,
898 ir_binop_rshift,
899 ir_binop_less,
900 ir_binop_greater,
901 ir_binop_lequal,
902 ir_binop_gequal,
903 ir_binop_all_equal,
904 ir_binop_any_nequal,
905 ir_binop_bit_and,
906 ir_binop_bit_xor,
907 ir_binop_bit_or,
908 ir_unop_bit_not,
909 ir_binop_logic_and,
910 ir_binop_logic_xor,
911 ir_binop_logic_or,
912 ir_unop_logic_not,
914 /* Note: The following block of expression types actually convert
915 * to multiple IR instructions.
917 ir_binop_mul, /* ast_mul_assign */
918 ir_binop_div, /* ast_div_assign */
919 ir_binop_mod, /* ast_mod_assign */
920 ir_binop_add, /* ast_add_assign */
921 ir_binop_sub, /* ast_sub_assign */
922 ir_binop_lshift, /* ast_ls_assign */
923 ir_binop_rshift, /* ast_rs_assign */
924 ir_binop_bit_and, /* ast_and_assign */
925 ir_binop_bit_xor, /* ast_xor_assign */
926 ir_binop_bit_or, /* ast_or_assign */
928 -1, /* ast_conditional doesn't convert to ir_expression. */
929 ir_binop_add, /* ast_pre_inc. */
930 ir_binop_sub, /* ast_pre_dec. */
931 ir_binop_add, /* ast_post_inc. */
932 ir_binop_sub, /* ast_post_dec. */
933 -1, /* ast_field_selection doesn't conv to ir_expression. */
934 -1, /* ast_array_index doesn't convert to ir_expression. */
935 -1, /* ast_function_call doesn't conv to ir_expression. */
936 -1, /* ast_identifier doesn't convert to ir_expression. */
937 -1, /* ast_int_constant doesn't convert to ir_expression. */
938 -1, /* ast_uint_constant doesn't conv to ir_expression. */
939 -1, /* ast_float_constant doesn't conv to ir_expression. */
940 -1, /* ast_bool_constant doesn't conv to ir_expression. */
941 -1, /* ast_sequence doesn't convert to ir_expression. */
943 ir_rvalue *result = NULL;
944 ir_rvalue *op[3];
945 const struct glsl_type *type; /* a temporary variable for switch cases */
946 bool error_emitted = false;
947 YYLTYPE loc;
949 loc = this->get_location();
951 switch (this->oper) {
952 case ast_assign: {
953 op[0] = this->subexpressions[0]->hir(instructions, state);
954 op[1] = this->subexpressions[1]->hir(instructions, state);
956 result = do_assignment(instructions, state, op[0], op[1], false,
957 this->subexpressions[0]->get_location());
958 error_emitted = result->type->is_error();
959 break;
962 case ast_plus:
963 op[0] = this->subexpressions[0]->hir(instructions, state);
965 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
967 error_emitted = type->is_error();
969 result = op[0];
970 break;
972 case ast_neg:
973 op[0] = this->subexpressions[0]->hir(instructions, state);
975 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
977 error_emitted = type->is_error();
979 result = new(ctx) ir_expression(operations[this->oper], type,
980 op[0], NULL);
981 break;
983 case ast_add:
984 case ast_sub:
985 case ast_mul:
986 case ast_div:
987 op[0] = this->subexpressions[0]->hir(instructions, state);
988 op[1] = this->subexpressions[1]->hir(instructions, state);
990 type = arithmetic_result_type(op[0], op[1],
991 (this->oper == ast_mul),
992 state, & loc);
993 error_emitted = type->is_error();
995 result = new(ctx) ir_expression(operations[this->oper], type,
996 op[0], op[1]);
997 break;
999 case ast_mod:
1000 op[0] = this->subexpressions[0]->hir(instructions, state);
1001 op[1] = this->subexpressions[1]->hir(instructions, state);
1003 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1005 assert(operations[this->oper] == ir_binop_mod);
1007 result = new(ctx) ir_expression(operations[this->oper], type,
1008 op[0], op[1]);
1009 error_emitted = type->is_error();
1010 break;
1012 case ast_lshift:
1013 case ast_rshift:
1014 if (state->language_version < 130) {
1015 _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
1016 operator_string(this->oper));
1017 error_emitted = true;
1020 op[0] = this->subexpressions[0]->hir(instructions, state);
1021 op[1] = this->subexpressions[1]->hir(instructions, state);
1022 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1023 &loc);
1024 result = new(ctx) ir_expression(operations[this->oper], type,
1025 op[0], op[1]);
1026 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1027 break;
1029 case ast_less:
1030 case ast_greater:
1031 case ast_lequal:
1032 case ast_gequal:
1033 op[0] = this->subexpressions[0]->hir(instructions, state);
1034 op[1] = this->subexpressions[1]->hir(instructions, state);
1036 type = relational_result_type(op[0], op[1], state, & loc);
1038 /* The relational operators must either generate an error or result
1039 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1041 assert(type->is_error()
1042 || ((type->base_type == GLSL_TYPE_BOOL)
1043 && type->is_scalar()));
1045 result = new(ctx) ir_expression(operations[this->oper], type,
1046 op[0], op[1]);
1047 error_emitted = type->is_error();
1048 break;
1050 case ast_nequal:
1051 case ast_equal:
1052 op[0] = this->subexpressions[0]->hir(instructions, state);
1053 op[1] = this->subexpressions[1]->hir(instructions, state);
1055 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1057 * "The equality operators equal (==), and not equal (!=)
1058 * operate on all types. They result in a scalar Boolean. If
1059 * the operand types do not match, then there must be a
1060 * conversion from Section 4.1.10 "Implicit Conversions"
1061 * applied to one operand that can make them match, in which
1062 * case this conversion is done."
1064 if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1065 && !apply_implicit_conversion(op[1]->type, op[0], state))
1066 || (op[0]->type != op[1]->type)) {
1067 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1068 "type", (this->oper == ast_equal) ? "==" : "!=");
1069 error_emitted = true;
1070 } else if ((state->language_version <= 110)
1071 && (op[0]->type->is_array() || op[1]->type->is_array())) {
1072 _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
1073 "GLSL 1.10");
1074 error_emitted = true;
1077 if (error_emitted) {
1078 result = new(ctx) ir_constant(false);
1079 } else {
1080 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1081 assert(result->type == glsl_type::bool_type);
1083 break;
1085 case ast_bit_and:
1086 case ast_bit_xor:
1087 case ast_bit_or:
1088 op[0] = this->subexpressions[0]->hir(instructions, state);
1089 op[1] = this->subexpressions[1]->hir(instructions, state);
1090 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1091 state, &loc);
1092 result = new(ctx) ir_expression(operations[this->oper], type,
1093 op[0], op[1]);
1094 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1095 break;
1097 case ast_bit_not:
1098 op[0] = this->subexpressions[0]->hir(instructions, state);
1100 if (state->language_version < 130) {
1101 _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
1102 error_emitted = true;
1105 if (!op[0]->type->is_integer()) {
1106 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1107 error_emitted = true;
1110 type = op[0]->type;
1111 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1112 break;
1114 case ast_logic_and: {
1115 exec_list rhs_instructions;
1116 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1117 "LHS", &error_emitted);
1118 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1119 "RHS", &error_emitted);
1121 ir_constant *op0_const = op[0]->constant_expression_value();
1122 if (op0_const) {
1123 if (op0_const->value.b[0]) {
1124 instructions->append_list(&rhs_instructions);
1125 result = op[1];
1126 } else {
1127 result = op0_const;
1129 type = glsl_type::bool_type;
1130 } else {
1131 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1132 "and_tmp",
1133 ir_var_temporary);
1134 instructions->push_tail(tmp);
1136 ir_if *const stmt = new(ctx) ir_if(op[0]);
1137 instructions->push_tail(stmt);
1139 stmt->then_instructions.append_list(&rhs_instructions);
1140 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1141 ir_assignment *const then_assign =
1142 new(ctx) ir_assignment(then_deref, op[1], NULL);
1143 stmt->then_instructions.push_tail(then_assign);
1145 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1146 ir_assignment *const else_assign =
1147 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
1148 stmt->else_instructions.push_tail(else_assign);
1150 result = new(ctx) ir_dereference_variable(tmp);
1151 type = tmp->type;
1153 break;
1156 case ast_logic_or: {
1157 exec_list rhs_instructions;
1158 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1159 "LHS", &error_emitted);
1160 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1161 "RHS", &error_emitted);
1163 ir_constant *op0_const = op[0]->constant_expression_value();
1164 if (op0_const) {
1165 if (op0_const->value.b[0]) {
1166 result = op0_const;
1167 } else {
1168 result = op[1];
1170 type = glsl_type::bool_type;
1171 } else {
1172 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1173 "or_tmp",
1174 ir_var_temporary);
1175 instructions->push_tail(tmp);
1177 ir_if *const stmt = new(ctx) ir_if(op[0]);
1178 instructions->push_tail(stmt);
1180 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1181 ir_assignment *const then_assign =
1182 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
1183 stmt->then_instructions.push_tail(then_assign);
1185 stmt->else_instructions.append_list(&rhs_instructions);
1186 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1187 ir_assignment *const else_assign =
1188 new(ctx) ir_assignment(else_deref, op[1], NULL);
1189 stmt->else_instructions.push_tail(else_assign);
1191 result = new(ctx) ir_dereference_variable(tmp);
1192 type = tmp->type;
1194 break;
1197 case ast_logic_xor:
1198 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1200 * "The logical binary operators and (&&), or ( | | ), and
1201 * exclusive or (^^). They operate only on two Boolean
1202 * expressions and result in a Boolean expression."
1204 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1205 &error_emitted);
1206 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1207 &error_emitted);
1209 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1210 op[0], op[1]);
1211 break;
1213 case ast_logic_not:
1214 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1215 "operand", &error_emitted);
1217 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1218 op[0], NULL);
1219 break;
1221 case ast_mul_assign:
1222 case ast_div_assign:
1223 case ast_add_assign:
1224 case ast_sub_assign: {
1225 op[0] = this->subexpressions[0]->hir(instructions, state);
1226 op[1] = this->subexpressions[1]->hir(instructions, state);
1228 type = arithmetic_result_type(op[0], op[1],
1229 (this->oper == ast_mul_assign),
1230 state, & loc);
1232 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1233 op[0], op[1]);
1235 result = do_assignment(instructions, state,
1236 op[0]->clone(ctx, NULL), temp_rhs, false,
1237 this->subexpressions[0]->get_location());
1238 error_emitted = (op[0]->type->is_error());
1240 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1241 * explicitly test for this because none of the binary expression
1242 * operators allow array operands either.
1245 break;
1248 case ast_mod_assign: {
1249 op[0] = this->subexpressions[0]->hir(instructions, state);
1250 op[1] = this->subexpressions[1]->hir(instructions, state);
1252 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1254 assert(operations[this->oper] == ir_binop_mod);
1256 ir_rvalue *temp_rhs;
1257 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1258 op[0], op[1]);
1260 result = do_assignment(instructions, state,
1261 op[0]->clone(ctx, NULL), temp_rhs, false,
1262 this->subexpressions[0]->get_location());
1263 error_emitted = type->is_error();
1264 break;
1267 case ast_ls_assign:
1268 case ast_rs_assign: {
1269 op[0] = this->subexpressions[0]->hir(instructions, state);
1270 op[1] = this->subexpressions[1]->hir(instructions, state);
1271 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1272 &loc);
1273 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1274 type, op[0], op[1]);
1275 result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1276 temp_rhs, false,
1277 this->subexpressions[0]->get_location());
1278 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1279 break;
1282 case ast_and_assign:
1283 case ast_xor_assign:
1284 case ast_or_assign: {
1285 op[0] = this->subexpressions[0]->hir(instructions, state);
1286 op[1] = this->subexpressions[1]->hir(instructions, state);
1287 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1288 state, &loc);
1289 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1290 type, op[0], op[1]);
1291 result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1292 temp_rhs, false,
1293 this->subexpressions[0]->get_location());
1294 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1295 break;
1298 case ast_conditional: {
1299 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1301 * "The ternary selection operator (?:). It operates on three
1302 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1303 * first expression, which must result in a scalar Boolean."
1305 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1306 "condition", &error_emitted);
1308 /* The :? operator is implemented by generating an anonymous temporary
1309 * followed by an if-statement. The last instruction in each branch of
1310 * the if-statement assigns a value to the anonymous temporary. This
1311 * temporary is the r-value of the expression.
1313 exec_list then_instructions;
1314 exec_list else_instructions;
1316 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1317 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1319 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1321 * "The second and third expressions can be any type, as
1322 * long their types match, or there is a conversion in
1323 * Section 4.1.10 "Implicit Conversions" that can be applied
1324 * to one of the expressions to make their types match. This
1325 * resulting matching type is the type of the entire
1326 * expression."
1328 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1329 && !apply_implicit_conversion(op[2]->type, op[1], state))
1330 || (op[1]->type != op[2]->type)) {
1331 YYLTYPE loc = this->subexpressions[1]->get_location();
1333 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1334 "operator must have matching types.");
1335 error_emitted = true;
1336 type = glsl_type::error_type;
1337 } else {
1338 type = op[1]->type;
1341 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1343 * "The second and third expressions must be the same type, but can
1344 * be of any type other than an array."
1346 if ((state->language_version <= 110) && type->is_array()) {
1347 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1348 "operator must not be arrays.");
1349 error_emitted = true;
1352 ir_constant *cond_val = op[0]->constant_expression_value();
1353 ir_constant *then_val = op[1]->constant_expression_value();
1354 ir_constant *else_val = op[2]->constant_expression_value();
1356 if (then_instructions.is_empty()
1357 && else_instructions.is_empty()
1358 && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1359 result = (cond_val->value.b[0]) ? then_val : else_val;
1360 } else {
1361 ir_variable *const tmp =
1362 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1363 instructions->push_tail(tmp);
1365 ir_if *const stmt = new(ctx) ir_if(op[0]);
1366 instructions->push_tail(stmt);
1368 then_instructions.move_nodes_to(& stmt->then_instructions);
1369 ir_dereference *const then_deref =
1370 new(ctx) ir_dereference_variable(tmp);
1371 ir_assignment *const then_assign =
1372 new(ctx) ir_assignment(then_deref, op[1], NULL);
1373 stmt->then_instructions.push_tail(then_assign);
1375 else_instructions.move_nodes_to(& stmt->else_instructions);
1376 ir_dereference *const else_deref =
1377 new(ctx) ir_dereference_variable(tmp);
1378 ir_assignment *const else_assign =
1379 new(ctx) ir_assignment(else_deref, op[2], NULL);
1380 stmt->else_instructions.push_tail(else_assign);
1382 result = new(ctx) ir_dereference_variable(tmp);
1384 break;
1387 case ast_pre_inc:
1388 case ast_pre_dec: {
1389 op[0] = this->subexpressions[0]->hir(instructions, state);
1390 if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1391 op[1] = new(ctx) ir_constant(1.0f);
1392 else
1393 op[1] = new(ctx) ir_constant(1);
1395 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1397 ir_rvalue *temp_rhs;
1398 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1399 op[0], op[1]);
1401 result = do_assignment(instructions, state,
1402 op[0]->clone(ctx, NULL), temp_rhs, false,
1403 this->subexpressions[0]->get_location());
1404 error_emitted = op[0]->type->is_error();
1405 break;
1408 case ast_post_inc:
1409 case ast_post_dec: {
1410 op[0] = this->subexpressions[0]->hir(instructions, state);
1411 if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1412 op[1] = new(ctx) ir_constant(1.0f);
1413 else
1414 op[1] = new(ctx) ir_constant(1);
1416 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1418 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1420 ir_rvalue *temp_rhs;
1421 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1422 op[0], op[1]);
1424 /* Get a temporary of a copy of the lvalue before it's modified.
1425 * This may get thrown away later.
1427 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1429 (void)do_assignment(instructions, state,
1430 op[0]->clone(ctx, NULL), temp_rhs, false,
1431 this->subexpressions[0]->get_location());
1433 error_emitted = op[0]->type->is_error();
1434 break;
1437 case ast_field_selection:
1438 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1439 break;
1441 case ast_array_index: {
1442 YYLTYPE index_loc = subexpressions[1]->get_location();
1444 op[0] = subexpressions[0]->hir(instructions, state);
1445 op[1] = subexpressions[1]->hir(instructions, state);
1447 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1449 ir_rvalue *const array = op[0];
1451 result = new(ctx) ir_dereference_array(op[0], op[1]);
1453 /* Do not use op[0] after this point. Use array.
1455 op[0] = NULL;
1458 if (error_emitted)
1459 break;
1461 if (!array->type->is_array()
1462 && !array->type->is_matrix()
1463 && !array->type->is_vector()) {
1464 _mesa_glsl_error(& index_loc, state,
1465 "cannot dereference non-array / non-matrix / "
1466 "non-vector");
1467 error_emitted = true;
1470 if (!op[1]->type->is_integer()) {
1471 _mesa_glsl_error(& index_loc, state,
1472 "array index must be integer type");
1473 error_emitted = true;
1474 } else if (!op[1]->type->is_scalar()) {
1475 _mesa_glsl_error(& index_loc, state,
1476 "array index must be scalar");
1477 error_emitted = true;
1480 /* If the array index is a constant expression and the array has a
1481 * declared size, ensure that the access is in-bounds. If the array
1482 * index is not a constant expression, ensure that the array has a
1483 * declared size.
1485 ir_constant *const const_index = op[1]->constant_expression_value();
1486 if (const_index != NULL) {
1487 const int idx = const_index->value.i[0];
1488 const char *type_name;
1489 unsigned bound = 0;
1491 if (array->type->is_matrix()) {
1492 type_name = "matrix";
1493 } else if (array->type->is_vector()) {
1494 type_name = "vector";
1495 } else {
1496 type_name = "array";
1499 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
1501 * "It is illegal to declare an array with a size, and then
1502 * later (in the same shader) index the same array with an
1503 * integral constant expression greater than or equal to the
1504 * declared size. It is also illegal to index an array with a
1505 * negative constant expression."
1507 if (array->type->is_matrix()) {
1508 if (array->type->row_type()->vector_elements <= idx) {
1509 bound = array->type->row_type()->vector_elements;
1511 } else if (array->type->is_vector()) {
1512 if (array->type->vector_elements <= idx) {
1513 bound = array->type->vector_elements;
1515 } else {
1516 if ((array->type->array_size() > 0)
1517 && (array->type->array_size() <= idx)) {
1518 bound = array->type->array_size();
1522 if (bound > 0) {
1523 _mesa_glsl_error(& loc, state, "%s index must be < %u",
1524 type_name, bound);
1525 error_emitted = true;
1526 } else if (idx < 0) {
1527 _mesa_glsl_error(& loc, state, "%s index must be >= 0",
1528 type_name);
1529 error_emitted = true;
1532 if (array->type->is_array()) {
1533 /* If the array is a variable dereference, it dereferences the
1534 * whole array, by definition. Use this to get the variable.
1536 * FINISHME: Should some methods for getting / setting / testing
1537 * FINISHME: array access limits be added to ir_dereference?
1539 ir_variable *const v = array->whole_variable_referenced();
1540 if ((v != NULL) && (unsigned(idx) > v->max_array_access))
1541 v->max_array_access = idx;
1543 } else if (array->type->array_size() == 0) {
1544 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
1545 } else {
1546 if (array->type->is_array()) {
1547 /* whole_variable_referenced can return NULL if the array is a
1548 * member of a structure. In this case it is safe to not update
1549 * the max_array_access field because it is never used for fields
1550 * of structures.
1552 ir_variable *v = array->whole_variable_referenced();
1553 if (v != NULL)
1554 v->max_array_access = array->type->array_size() - 1;
1558 /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
1560 * "Samplers aggregated into arrays within a shader (using square
1561 * brackets [ ]) can only be indexed with integral constant
1562 * expressions [...]."
1564 * This restriction was added in GLSL 1.30. Shaders using earlier version
1565 * of the language should not be rejected by the compiler front-end for
1566 * using this construct. This allows useful things such as using a loop
1567 * counter as the index to an array of samplers. If the loop in unrolled,
1568 * the code should compile correctly. Instead, emit a warning.
1570 if (array->type->is_array() &&
1571 array->type->element_type()->is_sampler() &&
1572 const_index == NULL) {
1574 if (state->language_version == 100) {
1575 _mesa_glsl_warning(&loc, state,
1576 "sampler arrays indexed with non-constant "
1577 "expressions is optional in GLSL ES 1.00");
1578 } else if (state->language_version < 130) {
1579 _mesa_glsl_warning(&loc, state,
1580 "sampler arrays indexed with non-constant "
1581 "expressions is forbidden in GLSL 1.30 and "
1582 "later");
1583 } else {
1584 _mesa_glsl_error(&loc, state,
1585 "sampler arrays indexed with non-constant "
1586 "expressions is forbidden in GLSL 1.30 and "
1587 "later");
1588 error_emitted = true;
1592 if (error_emitted)
1593 result->type = glsl_type::error_type;
1595 break;
1598 case ast_function_call:
1599 /* Should *NEVER* get here. ast_function_call should always be handled
1600 * by ast_function_expression::hir.
1602 assert(0);
1603 break;
1605 case ast_identifier: {
1606 /* ast_identifier can appear several places in a full abstract syntax
1607 * tree. This particular use must be at location specified in the grammar
1608 * as 'variable_identifier'.
1610 ir_variable *var =
1611 state->symbols->get_variable(this->primary_expression.identifier);
1613 result = new(ctx) ir_dereference_variable(var);
1615 if (var != NULL) {
1616 var->used = true;
1617 } else {
1618 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1619 this->primary_expression.identifier);
1621 error_emitted = true;
1623 break;
1626 case ast_int_constant:
1627 result = new(ctx) ir_constant(this->primary_expression.int_constant);
1628 break;
1630 case ast_uint_constant:
1631 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1632 break;
1634 case ast_float_constant:
1635 result = new(ctx) ir_constant(this->primary_expression.float_constant);
1636 break;
1638 case ast_bool_constant:
1639 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1640 break;
1642 case ast_sequence: {
1643 /* It should not be possible to generate a sequence in the AST without
1644 * any expressions in it.
1646 assert(!this->expressions.is_empty());
1648 /* The r-value of a sequence is the last expression in the sequence. If
1649 * the other expressions in the sequence do not have side-effects (and
1650 * therefore add instructions to the instruction list), they get dropped
1651 * on the floor.
1653 exec_node *previous_tail_pred = NULL;
1654 YYLTYPE previous_operand_loc = loc;
1656 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1657 /* If one of the operands of comma operator does not generate any
1658 * code, we want to emit a warning. At each pass through the loop
1659 * previous_tail_pred will point to the last instruction in the
1660 * stream *before* processing the previous operand. Naturally,
1661 * instructions->tail_pred will point to the last instruction in the
1662 * stream *after* processing the previous operand. If the two
1663 * pointers match, then the previous operand had no effect.
1665 * The warning behavior here differs slightly from GCC. GCC will
1666 * only emit a warning if none of the left-hand operands have an
1667 * effect. However, it will emit a warning for each. I believe that
1668 * there are some cases in C (especially with GCC extensions) where
1669 * it is useful to have an intermediate step in a sequence have no
1670 * effect, but I don't think these cases exist in GLSL. Either way,
1671 * it would be a giant hassle to replicate that behavior.
1673 if (previous_tail_pred == instructions->tail_pred) {
1674 _mesa_glsl_warning(&previous_operand_loc, state,
1675 "left-hand operand of comma expression has "
1676 "no effect");
1679 /* tail_pred is directly accessed instead of using the get_tail()
1680 * method for performance reasons. get_tail() has extra code to
1681 * return NULL when the list is empty. We don't care about that
1682 * here, so using tail_pred directly is fine.
1684 previous_tail_pred = instructions->tail_pred;
1685 previous_operand_loc = ast->get_location();
1687 result = ast->hir(instructions, state);
1690 /* Any errors should have already been emitted in the loop above.
1692 error_emitted = true;
1693 break;
1696 type = NULL; /* use result->type, not type. */
1697 assert(result != NULL);
1699 if (result->type->is_error() && !error_emitted)
1700 _mesa_glsl_error(& loc, state, "type mismatch");
1702 return result;
1706 ir_rvalue *
1707 ast_expression_statement::hir(exec_list *instructions,
1708 struct _mesa_glsl_parse_state *state)
1710 /* It is possible to have expression statements that don't have an
1711 * expression. This is the solitary semicolon:
1713 * for (i = 0; i < 5; i++)
1716 * In this case the expression will be NULL. Test for NULL and don't do
1717 * anything in that case.
1719 if (expression != NULL)
1720 expression->hir(instructions, state);
1722 /* Statements do not have r-values.
1724 return NULL;
1728 ir_rvalue *
1729 ast_compound_statement::hir(exec_list *instructions,
1730 struct _mesa_glsl_parse_state *state)
1732 if (new_scope)
1733 state->symbols->push_scope();
1735 foreach_list_typed (ast_node, ast, link, &this->statements)
1736 ast->hir(instructions, state);
1738 if (new_scope)
1739 state->symbols->pop_scope();
1741 /* Compound statements do not have r-values.
1743 return NULL;
1747 static const glsl_type *
1748 process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
1749 struct _mesa_glsl_parse_state *state)
1751 unsigned length = 0;
1753 /* FINISHME: Reject delcarations of multidimensional arrays. */
1755 if (array_size != NULL) {
1756 exec_list dummy_instructions;
1757 ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1758 YYLTYPE loc = array_size->get_location();
1760 /* FINISHME: Verify that the grammar forbids side-effects in array
1761 * FINISHME: sizes. i.e., 'vec4 [x = 12] data'
1763 assert(dummy_instructions.is_empty());
1765 if (ir != NULL) {
1766 if (!ir->type->is_integer()) {
1767 _mesa_glsl_error(& loc, state, "array size must be integer type");
1768 } else if (!ir->type->is_scalar()) {
1769 _mesa_glsl_error(& loc, state, "array size must be scalar type");
1770 } else {
1771 ir_constant *const size = ir->constant_expression_value();
1773 if (size == NULL) {
1774 _mesa_glsl_error(& loc, state, "array size must be a "
1775 "constant valued expression");
1776 } else if (size->value.i[0] <= 0) {
1777 _mesa_glsl_error(& loc, state, "array size must be > 0");
1778 } else {
1779 assert(size->type == ir->type);
1780 length = size->value.u[0];
1784 } else if (state->es_shader) {
1785 /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
1786 * array declarations have been removed from the language.
1788 _mesa_glsl_error(loc, state, "unsized array declarations are not "
1789 "allowed in GLSL ES 1.00.");
1792 return glsl_type::get_array_instance(base, length);
1796 const glsl_type *
1797 ast_type_specifier::glsl_type(const char **name,
1798 struct _mesa_glsl_parse_state *state) const
1800 const struct glsl_type *type;
1802 type = state->symbols->get_type(this->type_name);
1803 *name = this->type_name;
1805 if (this->is_array) {
1806 YYLTYPE loc = this->get_location();
1807 type = process_array_type(&loc, type, this->array_size, state);
1810 return type;
1814 static void
1815 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
1816 ir_variable *var,
1817 struct _mesa_glsl_parse_state *state,
1818 YYLTYPE *loc)
1820 if (qual->flags.q.invariant) {
1821 if (var->used) {
1822 _mesa_glsl_error(loc, state,
1823 "variable `%s' may not be redeclared "
1824 "`invariant' after being used",
1825 var->name);
1826 } else {
1827 var->invariant = 1;
1831 if (qual->flags.q.constant || qual->flags.q.attribute
1832 || qual->flags.q.uniform
1833 || (qual->flags.q.varying && (state->target == fragment_shader)))
1834 var->read_only = 1;
1836 if (qual->flags.q.centroid)
1837 var->centroid = 1;
1839 if (qual->flags.q.attribute && state->target != vertex_shader) {
1840 var->type = glsl_type::error_type;
1841 _mesa_glsl_error(loc, state,
1842 "`attribute' variables may not be declared in the "
1843 "%s shader",
1844 _mesa_glsl_shader_target_name(state->target));
1847 /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
1849 * "The varying qualifier can be used only with the data types
1850 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
1851 * these."
1853 if (qual->flags.q.varying) {
1854 const glsl_type *non_array_type;
1856 if (var->type && var->type->is_array())
1857 non_array_type = var->type->fields.array;
1858 else
1859 non_array_type = var->type;
1861 if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
1862 var->type = glsl_type::error_type;
1863 _mesa_glsl_error(loc, state,
1864 "varying variables must be of base type float");
1868 /* If there is no qualifier that changes the mode of the variable, leave
1869 * the setting alone.
1871 if (qual->flags.q.in && qual->flags.q.out)
1872 var->mode = ir_var_inout;
1873 else if (qual->flags.q.attribute || qual->flags.q.in
1874 || (qual->flags.q.varying && (state->target == fragment_shader)))
1875 var->mode = ir_var_in;
1876 else if (qual->flags.q.out
1877 || (qual->flags.q.varying && (state->target == vertex_shader)))
1878 var->mode = ir_var_out;
1879 else if (qual->flags.q.uniform)
1880 var->mode = ir_var_uniform;
1882 if (state->all_invariant && (state->current_function == NULL)) {
1883 switch (state->target) {
1884 case vertex_shader:
1885 if (var->mode == ir_var_out)
1886 var->invariant = true;
1887 break;
1888 case geometry_shader:
1889 if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
1890 var->invariant = true;
1891 break;
1892 case fragment_shader:
1893 if (var->mode == ir_var_in)
1894 var->invariant = true;
1895 break;
1899 if (qual->flags.q.flat)
1900 var->interpolation = ir_var_flat;
1901 else if (qual->flags.q.noperspective)
1902 var->interpolation = ir_var_noperspective;
1903 else
1904 var->interpolation = ir_var_smooth;
1906 var->pixel_center_integer = qual->flags.q.pixel_center_integer;
1907 var->origin_upper_left = qual->flags.q.origin_upper_left;
1908 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
1909 && (strcmp(var->name, "gl_FragCoord") != 0)) {
1910 const char *const qual_string = (qual->flags.q.origin_upper_left)
1911 ? "origin_upper_left" : "pixel_center_integer";
1913 _mesa_glsl_error(loc, state,
1914 "layout qualifier `%s' can only be applied to "
1915 "fragment shader input `gl_FragCoord'",
1916 qual_string);
1919 if (qual->flags.q.explicit_location) {
1920 const bool global_scope = (state->current_function == NULL);
1921 bool fail = false;
1922 const char *string = "";
1924 /* In the vertex shader only shader inputs can be given explicit
1925 * locations.
1927 * In the fragment shader only shader outputs can be given explicit
1928 * locations.
1930 switch (state->target) {
1931 case vertex_shader:
1932 if (!global_scope || (var->mode != ir_var_in)) {
1933 fail = true;
1934 string = "input";
1936 break;
1938 case geometry_shader:
1939 _mesa_glsl_error(loc, state,
1940 "geometry shader variables cannot be given "
1941 "explicit locations\n");
1942 break;
1944 case fragment_shader:
1945 if (!global_scope || (var->mode != ir_var_out)) {
1946 fail = true;
1947 string = "output";
1949 break;
1952 if (fail) {
1953 _mesa_glsl_error(loc, state,
1954 "only %s shader %s variables can be given an "
1955 "explicit location\n",
1956 _mesa_glsl_shader_target_name(state->target),
1957 string);
1958 } else {
1959 var->explicit_location = true;
1961 /* This bit of silliness is needed because invalid explicit locations
1962 * are supposed to be flagged during linking. Small negative values
1963 * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
1964 * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
1965 * The linker needs to be able to differentiate these cases. This
1966 * ensures that negative values stay negative.
1968 if (qual->location >= 0) {
1969 var->location = (state->target == vertex_shader)
1970 ? (qual->location + VERT_ATTRIB_GENERIC0)
1971 : (qual->location + FRAG_RESULT_DATA0);
1972 } else {
1973 var->location = qual->location;
1978 /* Does the declaration use the 'layout' keyword?
1980 const bool uses_layout = qual->flags.q.pixel_center_integer
1981 || qual->flags.q.origin_upper_left
1982 || qual->flags.q.explicit_location;
1984 /* Does the declaration use the deprecated 'attribute' or 'varying'
1985 * keywords?
1987 const bool uses_deprecated_qualifier = qual->flags.q.attribute
1988 || qual->flags.q.varying;
1990 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
1991 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
1992 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
1993 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
1994 * These extensions and all following extensions that add the 'layout'
1995 * keyword have been modified to require the use of 'in' or 'out'.
1997 * The following extension do not allow the deprecated keywords:
1999 * GL_AMD_conservative_depth
2000 * GL_ARB_gpu_shader5
2001 * GL_ARB_separate_shader_objects
2002 * GL_ARB_tesselation_shader
2003 * GL_ARB_transform_feedback3
2004 * GL_ARB_uniform_buffer_object
2006 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2007 * allow layout with the deprecated keywords.
2009 const bool relaxed_layout_qualifier_checking =
2010 state->ARB_fragment_coord_conventions_enable;
2012 if (uses_layout && uses_deprecated_qualifier) {
2013 if (relaxed_layout_qualifier_checking) {
2014 _mesa_glsl_warning(loc, state,
2015 "`layout' qualifier may not be used with "
2016 "`attribute' or `varying'");
2017 } else {
2018 _mesa_glsl_error(loc, state,
2019 "`layout' qualifier may not be used with "
2020 "`attribute' or `varying'");
2024 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2025 * AMD_conservative_depth.
2027 int depth_layout_count = qual->flags.q.depth_any
2028 + qual->flags.q.depth_greater
2029 + qual->flags.q.depth_less
2030 + qual->flags.q.depth_unchanged;
2031 if (depth_layout_count > 0
2032 && !state->AMD_conservative_depth_enable) {
2033 _mesa_glsl_error(loc, state,
2034 "extension GL_AMD_conservative_depth must be enabled "
2035 "to use depth layout qualifiers");
2036 } else if (depth_layout_count > 0
2037 && strcmp(var->name, "gl_FragDepth") != 0) {
2038 _mesa_glsl_error(loc, state,
2039 "depth layout qualifiers can be applied only to "
2040 "gl_FragDepth");
2041 } else if (depth_layout_count > 1
2042 && strcmp(var->name, "gl_FragDepth") == 0) {
2043 _mesa_glsl_error(loc, state,
2044 "at most one depth layout qualifier can be applied to "
2045 "gl_FragDepth");
2047 if (qual->flags.q.depth_any)
2048 var->depth_layout = ir_depth_layout_any;
2049 else if (qual->flags.q.depth_greater)
2050 var->depth_layout = ir_depth_layout_greater;
2051 else if (qual->flags.q.depth_less)
2052 var->depth_layout = ir_depth_layout_less;
2053 else if (qual->flags.q.depth_unchanged)
2054 var->depth_layout = ir_depth_layout_unchanged;
2055 else
2056 var->depth_layout = ir_depth_layout_none;
2058 if (var->type->is_array() && state->language_version != 110) {
2059 var->array_lvalue = true;
2064 * Get the variable that is being redeclared by this declaration
2066 * Semantic checks to verify the validity of the redeclaration are also
2067 * performed. If semantic checks fail, compilation error will be emitted via
2068 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2070 * \returns
2071 * A pointer to an existing variable in the current scope if the declaration
2072 * is a redeclaration, \c NULL otherwise.
2074 ir_variable *
2075 get_variable_being_redeclared(ir_variable *var, ast_declaration *decl,
2076 struct _mesa_glsl_parse_state *state)
2078 /* Check if this declaration is actually a re-declaration, either to
2079 * resize an array or add qualifiers to an existing variable.
2081 * This is allowed for variables in the current scope, or when at
2082 * global scope (for built-ins in the implicit outer scope).
2084 ir_variable *earlier = state->symbols->get_variable(decl->identifier);
2085 if (earlier == NULL ||
2086 (state->current_function != NULL &&
2087 !state->symbols->name_declared_this_scope(decl->identifier))) {
2088 return NULL;
2092 YYLTYPE loc = decl->get_location();
2094 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2096 * "It is legal to declare an array without a size and then
2097 * later re-declare the same name as an array of the same
2098 * type and specify a size."
2100 if ((earlier->type->array_size() == 0)
2101 && var->type->is_array()
2102 && (var->type->element_type() == earlier->type->element_type())) {
2103 /* FINISHME: This doesn't match the qualifiers on the two
2104 * FINISHME: declarations. It's not 100% clear whether this is
2105 * FINISHME: required or not.
2108 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
2110 * "The size [of gl_TexCoord] can be at most
2111 * gl_MaxTextureCoords."
2113 const unsigned size = unsigned(var->type->array_size());
2114 if ((strcmp("gl_TexCoord", var->name) == 0)
2115 && (size > state->Const.MaxTextureCoords)) {
2116 _mesa_glsl_error(& loc, state, "`gl_TexCoord' array size cannot "
2117 "be larger than gl_MaxTextureCoords (%u)\n",
2118 state->Const.MaxTextureCoords);
2119 } else if ((size > 0) && (size <= earlier->max_array_access)) {
2120 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2121 "previous access",
2122 earlier->max_array_access);
2125 earlier->type = var->type;
2126 delete var;
2127 var = NULL;
2128 } else if (state->ARB_fragment_coord_conventions_enable
2129 && strcmp(var->name, "gl_FragCoord") == 0
2130 && earlier->type == var->type
2131 && earlier->mode == var->mode) {
2132 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2133 * qualifiers.
2135 earlier->origin_upper_left = var->origin_upper_left;
2136 earlier->pixel_center_integer = var->pixel_center_integer;
2138 /* According to section 4.3.7 of the GLSL 1.30 spec,
2139 * the following built-in varaibles can be redeclared with an
2140 * interpolation qualifier:
2141 * * gl_FrontColor
2142 * * gl_BackColor
2143 * * gl_FrontSecondaryColor
2144 * * gl_BackSecondaryColor
2145 * * gl_Color
2146 * * gl_SecondaryColor
2148 } else if (state->language_version >= 130
2149 && (strcmp(var->name, "gl_FrontColor") == 0
2150 || strcmp(var->name, "gl_BackColor") == 0
2151 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2152 || strcmp(var->name, "gl_BackSecondaryColor") == 0
2153 || strcmp(var->name, "gl_Color") == 0
2154 || strcmp(var->name, "gl_SecondaryColor") == 0)
2155 && earlier->type == var->type
2156 && earlier->mode == var->mode) {
2157 earlier->interpolation = var->interpolation;
2159 /* Layout qualifiers for gl_FragDepth. */
2160 } else if (state->AMD_conservative_depth_enable
2161 && strcmp(var->name, "gl_FragDepth") == 0
2162 && earlier->type == var->type
2163 && earlier->mode == var->mode) {
2165 /** From the AMD_conservative_depth spec:
2166 * Within any shader, the first redeclarations of gl_FragDepth
2167 * must appear before any use of gl_FragDepth.
2169 if (earlier->used) {
2170 _mesa_glsl_error(&loc, state,
2171 "the first redeclaration of gl_FragDepth "
2172 "must appear before any use of gl_FragDepth");
2175 /* Prevent inconsistent redeclaration of depth layout qualifier. */
2176 if (earlier->depth_layout != ir_depth_layout_none
2177 && earlier->depth_layout != var->depth_layout) {
2178 _mesa_glsl_error(&loc, state,
2179 "gl_FragDepth: depth layout is declared here "
2180 "as '%s, but it was previously declared as "
2181 "'%s'",
2182 depth_layout_string(var->depth_layout),
2183 depth_layout_string(earlier->depth_layout));
2186 earlier->depth_layout = var->depth_layout;
2188 } else {
2189 _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
2192 return earlier;
2196 * Generate the IR for an initializer in a variable declaration
2198 ir_rvalue *
2199 process_initializer(ir_variable *var, ast_declaration *decl,
2200 ast_fully_specified_type *type,
2201 exec_list *initializer_instructions,
2202 struct _mesa_glsl_parse_state *state)
2204 ir_rvalue *result = NULL;
2206 YYLTYPE initializer_loc = decl->initializer->get_location();
2208 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2210 * "All uniform variables are read-only and are initialized either
2211 * directly by an application via API commands, or indirectly by
2212 * OpenGL."
2214 if ((state->language_version <= 110)
2215 && (var->mode == ir_var_uniform)) {
2216 _mesa_glsl_error(& initializer_loc, state,
2217 "cannot initialize uniforms in GLSL 1.10");
2220 if (var->type->is_sampler()) {
2221 _mesa_glsl_error(& initializer_loc, state,
2222 "cannot initialize samplers");
2225 if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
2226 _mesa_glsl_error(& initializer_loc, state,
2227 "cannot initialize %s shader input / %s",
2228 _mesa_glsl_shader_target_name(state->target),
2229 (state->target == vertex_shader)
2230 ? "attribute" : "varying");
2233 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2234 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions,
2235 state);
2237 /* Calculate the constant value if this is a const or uniform
2238 * declaration.
2240 if (type->qualifier.flags.q.constant
2241 || type->qualifier.flags.q.uniform) {
2242 ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs, true);
2243 if (new_rhs != NULL) {
2244 rhs = new_rhs;
2246 ir_constant *constant_value = rhs->constant_expression_value();
2247 if (!constant_value) {
2248 _mesa_glsl_error(& initializer_loc, state,
2249 "initializer of %s variable `%s' must be a "
2250 "constant expression",
2251 (type->qualifier.flags.q.constant)
2252 ? "const" : "uniform",
2253 decl->identifier);
2254 if (var->type->is_numeric()) {
2255 /* Reduce cascading errors. */
2256 var->constant_value = ir_constant::zero(state, var->type);
2258 } else {
2259 rhs = constant_value;
2260 var->constant_value = constant_value;
2262 } else {
2263 _mesa_glsl_error(&initializer_loc, state,
2264 "initializer of type %s cannot be assigned to "
2265 "variable of type %s",
2266 rhs->type->name, var->type->name);
2267 if (var->type->is_numeric()) {
2268 /* Reduce cascading errors. */
2269 var->constant_value = ir_constant::zero(state, var->type);
2274 if (rhs && !rhs->type->is_error()) {
2275 bool temp = var->read_only;
2276 if (type->qualifier.flags.q.constant)
2277 var->read_only = false;
2279 /* Never emit code to initialize a uniform.
2281 const glsl_type *initializer_type;
2282 if (!type->qualifier.flags.q.uniform) {
2283 result = do_assignment(initializer_instructions, state,
2284 lhs, rhs, true,
2285 type->get_location());
2286 initializer_type = result->type;
2287 } else
2288 initializer_type = rhs->type;
2290 /* If the declared variable is an unsized array, it must inherrit
2291 * its full type from the initializer. A declaration such as
2293 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2295 * becomes
2297 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2299 * The assignment generated in the if-statement (below) will also
2300 * automatically handle this case for non-uniforms.
2302 * If the declared variable is not an array, the types must
2303 * already match exactly. As a result, the type assignment
2304 * here can be done unconditionally. For non-uniforms the call
2305 * to do_assignment can change the type of the initializer (via
2306 * the implicit conversion rules). For uniforms the initializer
2307 * must be a constant expression, and the type of that expression
2308 * was validated above.
2310 var->type = initializer_type;
2312 var->read_only = temp;
2315 return result;
2318 ir_rvalue *
2319 ast_declarator_list::hir(exec_list *instructions,
2320 struct _mesa_glsl_parse_state *state)
2322 void *ctx = state;
2323 const struct glsl_type *decl_type;
2324 const char *type_name = NULL;
2325 ir_rvalue *result = NULL;
2326 YYLTYPE loc = this->get_location();
2328 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
2330 * "To ensure that a particular output variable is invariant, it is
2331 * necessary to use the invariant qualifier. It can either be used to
2332 * qualify a previously declared variable as being invariant
2334 * invariant gl_Position; // make existing gl_Position be invariant"
2336 * In these cases the parser will set the 'invariant' flag in the declarator
2337 * list, and the type will be NULL.
2339 if (this->invariant) {
2340 assert(this->type == NULL);
2342 if (state->current_function != NULL) {
2343 _mesa_glsl_error(& loc, state,
2344 "All uses of `invariant' keyword must be at global "
2345 "scope\n");
2348 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2349 assert(!decl->is_array);
2350 assert(decl->array_size == NULL);
2351 assert(decl->initializer == NULL);
2353 ir_variable *const earlier =
2354 state->symbols->get_variable(decl->identifier);
2355 if (earlier == NULL) {
2356 _mesa_glsl_error(& loc, state,
2357 "Undeclared variable `%s' cannot be marked "
2358 "invariant\n", decl->identifier);
2359 } else if ((state->target == vertex_shader)
2360 && (earlier->mode != ir_var_out)) {
2361 _mesa_glsl_error(& loc, state,
2362 "`%s' cannot be marked invariant, vertex shader "
2363 "outputs only\n", decl->identifier);
2364 } else if ((state->target == fragment_shader)
2365 && (earlier->mode != ir_var_in)) {
2366 _mesa_glsl_error(& loc, state,
2367 "`%s' cannot be marked invariant, fragment shader "
2368 "inputs only\n", decl->identifier);
2369 } else if (earlier->used) {
2370 _mesa_glsl_error(& loc, state,
2371 "variable `%s' may not be redeclared "
2372 "`invariant' after being used",
2373 earlier->name);
2374 } else {
2375 earlier->invariant = true;
2379 /* Invariant redeclarations do not have r-values.
2381 return NULL;
2384 assert(this->type != NULL);
2385 assert(!this->invariant);
2387 /* The type specifier may contain a structure definition. Process that
2388 * before any of the variable declarations.
2390 (void) this->type->specifier->hir(instructions, state);
2392 decl_type = this->type->specifier->glsl_type(& type_name, state);
2393 if (this->declarations.is_empty()) {
2394 /* The only valid case where the declaration list can be empty is when
2395 * the declaration is setting the default precision of a built-in type
2396 * (e.g., 'precision highp vec4;').
2399 if (decl_type != NULL) {
2400 } else {
2401 _mesa_glsl_error(& loc, state, "incomplete declaration");
2405 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2406 const struct glsl_type *var_type;
2407 ir_variable *var;
2409 /* FINISHME: Emit a warning if a variable declaration shadows a
2410 * FINISHME: declaration at a higher scope.
2413 if ((decl_type == NULL) || decl_type->is_void()) {
2414 if (type_name != NULL) {
2415 _mesa_glsl_error(& loc, state,
2416 "invalid type `%s' in declaration of `%s'",
2417 type_name, decl->identifier);
2418 } else {
2419 _mesa_glsl_error(& loc, state,
2420 "invalid type in declaration of `%s'",
2421 decl->identifier);
2423 continue;
2426 if (decl->is_array) {
2427 var_type = process_array_type(&loc, decl_type, decl->array_size,
2428 state);
2429 } else {
2430 var_type = decl_type;
2433 var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
2435 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
2437 * "Global variables can only use the qualifiers const,
2438 * attribute, uni form, or varying. Only one may be
2439 * specified.
2441 * Local variables can only use the qualifier const."
2443 * This is relaxed in GLSL 1.30. It is also relaxed by any extension
2444 * that adds the 'layout' keyword.
2446 if ((state->language_version < 130)
2447 && !state->ARB_explicit_attrib_location_enable
2448 && !state->ARB_fragment_coord_conventions_enable) {
2449 if (this->type->qualifier.flags.q.out) {
2450 _mesa_glsl_error(& loc, state,
2451 "`out' qualifier in declaration of `%s' "
2452 "only valid for function parameters in %s.",
2453 decl->identifier, state->version_string);
2455 if (this->type->qualifier.flags.q.in) {
2456 _mesa_glsl_error(& loc, state,
2457 "`in' qualifier in declaration of `%s' "
2458 "only valid for function parameters in %s.",
2459 decl->identifier, state->version_string);
2461 /* FINISHME: Test for other invalid qualifiers. */
2464 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
2465 & loc);
2467 if (this->type->qualifier.flags.q.invariant) {
2468 if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
2469 var->mode == ir_var_inout)) {
2470 /* FINISHME: Note that this doesn't work for invariant on
2471 * a function signature outval
2473 _mesa_glsl_error(& loc, state,
2474 "`%s' cannot be marked invariant, vertex shader "
2475 "outputs only\n", var->name);
2476 } else if ((state->target == fragment_shader) &&
2477 !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
2478 /* FINISHME: Note that this doesn't work for invariant on
2479 * a function signature inval
2481 _mesa_glsl_error(& loc, state,
2482 "`%s' cannot be marked invariant, fragment shader "
2483 "inputs only\n", var->name);
2487 if (state->current_function != NULL) {
2488 const char *mode = NULL;
2489 const char *extra = "";
2491 /* There is no need to check for 'inout' here because the parser will
2492 * only allow that in function parameter lists.
2494 if (this->type->qualifier.flags.q.attribute) {
2495 mode = "attribute";
2496 } else if (this->type->qualifier.flags.q.uniform) {
2497 mode = "uniform";
2498 } else if (this->type->qualifier.flags.q.varying) {
2499 mode = "varying";
2500 } else if (this->type->qualifier.flags.q.in) {
2501 mode = "in";
2502 extra = " or in function parameter list";
2503 } else if (this->type->qualifier.flags.q.out) {
2504 mode = "out";
2505 extra = " or in function parameter list";
2508 if (mode) {
2509 _mesa_glsl_error(& loc, state,
2510 "%s variable `%s' must be declared at "
2511 "global scope%s",
2512 mode, var->name, extra);
2514 } else if (var->mode == ir_var_in) {
2515 var->read_only = true;
2517 if (state->target == vertex_shader) {
2518 bool error_emitted = false;
2520 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
2522 * "Vertex shader inputs can only be float, floating-point
2523 * vectors, matrices, signed and unsigned integers and integer
2524 * vectors. Vertex shader inputs can also form arrays of these
2525 * types, but not structures."
2527 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
2529 * "Vertex shader inputs can only be float, floating-point
2530 * vectors, matrices, signed and unsigned integers and integer
2531 * vectors. They cannot be arrays or structures."
2533 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
2535 * "The attribute qualifier can be used only with float,
2536 * floating-point vectors, and matrices. Attribute variables
2537 * cannot be declared as arrays or structures."
2539 const glsl_type *check_type = var->type->is_array()
2540 ? var->type->fields.array : var->type;
2542 switch (check_type->base_type) {
2543 case GLSL_TYPE_FLOAT:
2544 break;
2545 case GLSL_TYPE_UINT:
2546 case GLSL_TYPE_INT:
2547 if (state->language_version > 120)
2548 break;
2549 /* FALLTHROUGH */
2550 default:
2551 _mesa_glsl_error(& loc, state,
2552 "vertex shader input / attribute cannot have "
2553 "type %s`%s'",
2554 var->type->is_array() ? "array of " : "",
2555 check_type->name);
2556 error_emitted = true;
2559 if (!error_emitted && (state->language_version <= 130)
2560 && var->type->is_array()) {
2561 _mesa_glsl_error(& loc, state,
2562 "vertex shader input / attribute cannot have "
2563 "array type");
2564 error_emitted = true;
2569 /* Integer vertex outputs must be qualified with 'flat'.
2571 * From section 4.3.6 of the GLSL 1.30 spec:
2572 * "If a vertex output is a signed or unsigned integer or integer
2573 * vector, then it must be qualified with the interpolation qualifier
2574 * flat."
2576 if (state->language_version >= 130
2577 && state->target == vertex_shader
2578 && state->current_function == NULL
2579 && var->type->is_integer()
2580 && var->mode == ir_var_out
2581 && var->interpolation != ir_var_flat) {
2583 _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
2584 "then it must be qualified with 'flat'");
2588 /* Interpolation qualifiers cannot be applied to 'centroid' and
2589 * 'centroid varying'.
2591 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2592 * "interpolation qualifiers may only precede the qualifiers in,
2593 * centroid in, out, or centroid out in a declaration. They do not apply
2594 * to the deprecated storage qualifiers varying or centroid varying."
2596 if (state->language_version >= 130
2597 && this->type->qualifier.has_interpolation()
2598 && this->type->qualifier.flags.q.varying) {
2600 const char *i = this->type->qualifier.interpolation_string();
2601 assert(i != NULL);
2602 const char *s;
2603 if (this->type->qualifier.flags.q.centroid)
2604 s = "centroid varying";
2605 else
2606 s = "varying";
2608 _mesa_glsl_error(&loc, state,
2609 "qualifier '%s' cannot be applied to the "
2610 "deprecated storage qualifier '%s'", i, s);
2614 /* Interpolation qualifiers can only apply to vertex shader outputs and
2615 * fragment shader inputs.
2617 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2618 * "Outputs from a vertex shader (out) and inputs to a fragment
2619 * shader (in) can be further qualified with one or more of these
2620 * interpolation qualifiers"
2622 if (state->language_version >= 130
2623 && this->type->qualifier.has_interpolation()) {
2625 const char *i = this->type->qualifier.interpolation_string();
2626 assert(i != NULL);
2628 switch (state->target) {
2629 case vertex_shader:
2630 if (this->type->qualifier.flags.q.in) {
2631 _mesa_glsl_error(&loc, state,
2632 "qualifier '%s' cannot be applied to vertex "
2633 "shader inputs", i);
2635 break;
2636 case fragment_shader:
2637 if (this->type->qualifier.flags.q.out) {
2638 _mesa_glsl_error(&loc, state,
2639 "qualifier '%s' cannot be applied to fragment "
2640 "shader outputs", i);
2642 break;
2643 default:
2644 assert(0);
2649 /* From section 4.3.4 of the GLSL 1.30 spec:
2650 * "It is an error to use centroid in in a vertex shader."
2652 if (state->language_version >= 130
2653 && this->type->qualifier.flags.q.centroid
2654 && this->type->qualifier.flags.q.in
2655 && state->target == vertex_shader) {
2657 _mesa_glsl_error(&loc, state,
2658 "'centroid in' cannot be used in a vertex shader");
2662 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
2664 if (this->type->specifier->precision != ast_precision_none
2665 && state->language_version != 100
2666 && state->language_version < 130) {
2668 _mesa_glsl_error(&loc, state,
2669 "precision qualifiers are supported only in GLSL ES "
2670 "1.00, and GLSL 1.30 and later");
2674 /* Precision qualifiers only apply to floating point and integer types.
2676 * From section 4.5.2 of the GLSL 1.30 spec:
2677 * "Any floating point or any integer declaration can have the type
2678 * preceded by one of these precision qualifiers [...] Literal
2679 * constants do not have precision qualifiers. Neither do Boolean
2680 * variables.
2682 * In GLSL ES, sampler types are also allowed.
2684 * From page 87 of the GLSL ES spec:
2685 * "RESOLUTION: Allow sampler types to take a precision qualifier."
2687 if (this->type->specifier->precision != ast_precision_none
2688 && !var->type->is_float()
2689 && !var->type->is_integer()
2690 && !(var->type->is_sampler() && state->es_shader)
2691 && !(var->type->is_array()
2692 && (var->type->fields.array->is_float()
2693 || var->type->fields.array->is_integer()))) {
2695 _mesa_glsl_error(&loc, state,
2696 "precision qualifiers apply only to floating point"
2697 "%s types", state->es_shader ? ", integer, and sampler"
2698 : "and integer");
2701 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2703 * "[Sampler types] can only be declared as function
2704 * parameters or uniform variables (see Section 4.3.5
2705 * "Uniform")".
2707 if (var_type->contains_sampler() &&
2708 !this->type->qualifier.flags.q.uniform) {
2709 _mesa_glsl_error(&loc, state, "samplers must be declared uniform");
2712 /* Process the initializer and add its instructions to a temporary
2713 * list. This list will be added to the instruction stream (below) after
2714 * the declaration is added. This is done because in some cases (such as
2715 * redeclarations) the declaration may not actually be added to the
2716 * instruction stream.
2718 exec_list initializer_instructions;
2719 ir_variable *earlier = get_variable_being_redeclared(var, decl, state);
2721 if (decl->initializer != NULL) {
2722 result = process_initializer((earlier == NULL) ? var : earlier,
2723 decl, this->type,
2724 &initializer_instructions, state);
2727 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
2729 * "It is an error to write to a const variable outside of
2730 * its declaration, so they must be initialized when
2731 * declared."
2733 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
2734 _mesa_glsl_error(& loc, state,
2735 "const declaration of `%s' must be initialized",
2736 decl->identifier);
2739 /* If the declaration is not a redeclaration, there are a few additional
2740 * semantic checks that must be applied. In addition, variable that was
2741 * created for the declaration should be added to the IR stream.
2743 if (earlier == NULL) {
2744 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2746 * "Identifiers starting with "gl_" are reserved for use by
2747 * OpenGL, and may not be declared in a shader as either a
2748 * variable or a function."
2750 if (strncmp(decl->identifier, "gl_", 3) == 0)
2751 _mesa_glsl_error(& loc, state,
2752 "identifier `%s' uses reserved `gl_' prefix",
2753 decl->identifier);
2755 /* Add the variable to the symbol table. Note that the initializer's
2756 * IR was already processed earlier (though it hasn't been emitted
2757 * yet), without the variable in scope.
2759 * This differs from most C-like languages, but it follows the GLSL
2760 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
2761 * spec:
2763 * "Within a declaration, the scope of a name starts immediately
2764 * after the initializer if present or immediately after the name
2765 * being declared if not."
2767 if (!state->symbols->add_variable(var)) {
2768 YYLTYPE loc = this->get_location();
2769 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
2770 "current scope", decl->identifier);
2771 continue;
2774 /* Push the variable declaration to the top. It means that all the
2775 * variable declarations will appear in a funny last-to-first order,
2776 * but otherwise we run into trouble if a function is prototyped, a
2777 * global var is decled, then the function is defined with usage of
2778 * the global var. See glslparsertest's CorrectModule.frag.
2780 instructions->push_head(var);
2783 instructions->append_list(&initializer_instructions);
2787 /* Generally, variable declarations do not have r-values. However,
2788 * one is used for the declaration in
2790 * while (bool b = some_condition()) {
2791 * ...
2794 * so we return the rvalue from the last seen declaration here.
2796 return result;
2800 ir_rvalue *
2801 ast_parameter_declarator::hir(exec_list *instructions,
2802 struct _mesa_glsl_parse_state *state)
2804 void *ctx = state;
2805 const struct glsl_type *type;
2806 const char *name = NULL;
2807 YYLTYPE loc = this->get_location();
2809 type = this->type->specifier->glsl_type(& name, state);
2811 if (type == NULL) {
2812 if (name != NULL) {
2813 _mesa_glsl_error(& loc, state,
2814 "invalid type `%s' in declaration of `%s'",
2815 name, this->identifier);
2816 } else {
2817 _mesa_glsl_error(& loc, state,
2818 "invalid type in declaration of `%s'",
2819 this->identifier);
2822 type = glsl_type::error_type;
2825 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
2827 * "Functions that accept no input arguments need not use void in the
2828 * argument list because prototypes (or definitions) are required and
2829 * therefore there is no ambiguity when an empty argument list "( )" is
2830 * declared. The idiom "(void)" as a parameter list is provided for
2831 * convenience."
2833 * Placing this check here prevents a void parameter being set up
2834 * for a function, which avoids tripping up checks for main taking
2835 * parameters and lookups of an unnamed symbol.
2837 if (type->is_void()) {
2838 if (this->identifier != NULL)
2839 _mesa_glsl_error(& loc, state,
2840 "named parameter cannot have type `void'");
2842 is_void = true;
2843 return NULL;
2846 if (formal_parameter && (this->identifier == NULL)) {
2847 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
2848 return NULL;
2851 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
2852 * call already handled the "vec4[..] foo" case.
2854 if (this->is_array) {
2855 type = process_array_type(&loc, type, this->array_size, state);
2858 if (type->array_size() == 0) {
2859 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
2860 "a declared size.");
2861 type = glsl_type::error_type;
2864 is_void = false;
2865 ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
2867 /* Apply any specified qualifiers to the parameter declaration. Note that
2868 * for function parameters the default mode is 'in'.
2870 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
2872 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2874 * "Samplers cannot be treated as l-values; hence cannot be used
2875 * as out or inout function parameters, nor can they be assigned
2876 * into."
2878 if ((var->mode == ir_var_inout || var->mode == ir_var_out)
2879 && type->contains_sampler()) {
2880 _mesa_glsl_error(&loc, state, "out and inout parameters cannot contain samplers");
2881 type = glsl_type::error_type;
2884 instructions->push_tail(var);
2886 /* Parameter declarations do not have r-values.
2888 return NULL;
2892 void
2893 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
2894 bool formal,
2895 exec_list *ir_parameters,
2896 _mesa_glsl_parse_state *state)
2898 ast_parameter_declarator *void_param = NULL;
2899 unsigned count = 0;
2901 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
2902 param->formal_parameter = formal;
2903 param->hir(ir_parameters, state);
2905 if (param->is_void)
2906 void_param = param;
2908 count++;
2911 if ((void_param != NULL) && (count > 1)) {
2912 YYLTYPE loc = void_param->get_location();
2914 _mesa_glsl_error(& loc, state,
2915 "`void' parameter must be only parameter");
2920 void
2921 emit_function(_mesa_glsl_parse_state *state, exec_list *instructions,
2922 ir_function *f)
2924 /* Emit the new function header */
2925 if (state->current_function == NULL) {
2926 instructions->push_tail(f);
2927 } else {
2928 /* IR invariants disallow function declarations or definitions nested
2929 * within other function definitions. Insert the new ir_function
2930 * block in the instruction sequence before the ir_function block
2931 * containing the current ir_function_signature.
2933 ir_function *const curr =
2934 const_cast<ir_function *>(state->current_function->function());
2936 curr->insert_before(f);
2941 ir_rvalue *
2942 ast_function::hir(exec_list *instructions,
2943 struct _mesa_glsl_parse_state *state)
2945 void *ctx = state;
2946 ir_function *f = NULL;
2947 ir_function_signature *sig = NULL;
2948 exec_list hir_parameters;
2950 const char *const name = identifier;
2952 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
2954 * "Function declarations (prototypes) cannot occur inside of functions;
2955 * they must be at global scope, or for the built-in functions, outside
2956 * the global scope."
2958 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
2960 * "User defined functions may only be defined within the global scope."
2962 * Note that this language does not appear in GLSL 1.10.
2964 if ((state->current_function != NULL) && (state->language_version != 110)) {
2965 YYLTYPE loc = this->get_location();
2966 _mesa_glsl_error(&loc, state,
2967 "declaration of function `%s' not allowed within "
2968 "function body", name);
2971 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2973 * "Identifiers starting with "gl_" are reserved for use by
2974 * OpenGL, and may not be declared in a shader as either a
2975 * variable or a function."
2977 if (strncmp(name, "gl_", 3) == 0) {
2978 YYLTYPE loc = this->get_location();
2979 _mesa_glsl_error(&loc, state,
2980 "identifier `%s' uses reserved `gl_' prefix", name);
2983 /* Convert the list of function parameters to HIR now so that they can be
2984 * used below to compare this function's signature with previously seen
2985 * signatures for functions with the same name.
2987 ast_parameter_declarator::parameters_to_hir(& this->parameters,
2988 is_definition,
2989 & hir_parameters, state);
2991 const char *return_type_name;
2992 const glsl_type *return_type =
2993 this->return_type->specifier->glsl_type(& return_type_name, state);
2995 if (!return_type) {
2996 YYLTYPE loc = this->get_location();
2997 _mesa_glsl_error(&loc, state,
2998 "function `%s' has undeclared return type `%s'",
2999 name, return_type_name);
3000 return_type = glsl_type::error_type;
3003 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3004 * "No qualifier is allowed on the return type of a function."
3006 if (this->return_type->has_qualifiers()) {
3007 YYLTYPE loc = this->get_location();
3008 _mesa_glsl_error(& loc, state,
3009 "function `%s' return type has qualifiers", name);
3012 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3014 * "[Sampler types] can only be declared as function parameters
3015 * or uniform variables (see Section 4.3.5 "Uniform")".
3017 if (return_type->contains_sampler()) {
3018 YYLTYPE loc = this->get_location();
3019 _mesa_glsl_error(&loc, state,
3020 "function `%s' return type can't contain a sampler",
3021 name);
3024 /* Verify that this function's signature either doesn't match a previously
3025 * seen signature for a function with the same name, or, if a match is found,
3026 * that the previously seen signature does not have an associated definition.
3028 f = state->symbols->get_function(name);
3029 if (f != NULL && (state->es_shader || f->has_user_signature())) {
3030 sig = f->exact_matching_signature(&hir_parameters);
3031 if (sig != NULL) {
3032 const char *badvar = sig->qualifiers_match(&hir_parameters);
3033 if (badvar != NULL) {
3034 YYLTYPE loc = this->get_location();
3036 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
3037 "qualifiers don't match prototype", name, badvar);
3040 if (sig->return_type != return_type) {
3041 YYLTYPE loc = this->get_location();
3043 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
3044 "match prototype", name);
3047 if (is_definition && sig->is_defined) {
3048 YYLTYPE loc = this->get_location();
3050 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
3053 } else {
3054 f = new(ctx) ir_function(name);
3055 if (!state->symbols->add_function(f)) {
3056 /* This function name shadows a non-function use of the same name. */
3057 YYLTYPE loc = this->get_location();
3059 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
3060 "non-function", name);
3061 return NULL;
3064 emit_function(state, instructions, f);
3067 /* Verify the return type of main() */
3068 if (strcmp(name, "main") == 0) {
3069 if (! return_type->is_void()) {
3070 YYLTYPE loc = this->get_location();
3072 _mesa_glsl_error(& loc, state, "main() must return void");
3075 if (!hir_parameters.is_empty()) {
3076 YYLTYPE loc = this->get_location();
3078 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
3082 /* Finish storing the information about this new function in its signature.
3084 if (sig == NULL) {
3085 sig = new(ctx) ir_function_signature(return_type);
3086 f->add_signature(sig);
3089 sig->replace_parameters(&hir_parameters);
3090 signature = sig;
3092 /* Function declarations (prototypes) do not have r-values.
3094 return NULL;
3098 ir_rvalue *
3099 ast_function_definition::hir(exec_list *instructions,
3100 struct _mesa_glsl_parse_state *state)
3102 prototype->is_definition = true;
3103 prototype->hir(instructions, state);
3105 ir_function_signature *signature = prototype->signature;
3106 if (signature == NULL)
3107 return NULL;
3109 assert(state->current_function == NULL);
3110 state->current_function = signature;
3111 state->found_return = false;
3113 /* Duplicate parameters declared in the prototype as concrete variables.
3114 * Add these to the symbol table.
3116 state->symbols->push_scope();
3117 foreach_iter(exec_list_iterator, iter, signature->parameters) {
3118 ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
3120 assert(var != NULL);
3122 /* The only way a parameter would "exist" is if two parameters have
3123 * the same name.
3125 if (state->symbols->name_declared_this_scope(var->name)) {
3126 YYLTYPE loc = this->get_location();
3128 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
3129 } else {
3130 state->symbols->add_variable(var);
3134 /* Convert the body of the function to HIR. */
3135 this->body->hir(&signature->body, state);
3136 signature->is_defined = true;
3138 state->symbols->pop_scope();
3140 assert(state->current_function == signature);
3141 state->current_function = NULL;
3143 if (!signature->return_type->is_void() && !state->found_return) {
3144 YYLTYPE loc = this->get_location();
3145 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
3146 "%s, but no return statement",
3147 signature->function_name(),
3148 signature->return_type->name);
3151 /* Function definitions do not have r-values.
3153 return NULL;
3157 ir_rvalue *
3158 ast_jump_statement::hir(exec_list *instructions,
3159 struct _mesa_glsl_parse_state *state)
3161 void *ctx = state;
3163 switch (mode) {
3164 case ast_return: {
3165 ir_return *inst;
3166 assert(state->current_function);
3168 if (opt_return_value) {
3169 ir_rvalue *const ret = opt_return_value->hir(instructions, state);
3171 /* The value of the return type can be NULL if the shader says
3172 * 'return foo();' and foo() is a function that returns void.
3174 * NOTE: The GLSL spec doesn't say that this is an error. The type
3175 * of the return value is void. If the return type of the function is
3176 * also void, then this should compile without error. Seriously.
3178 const glsl_type *const ret_type =
3179 (ret == NULL) ? glsl_type::void_type : ret->type;
3181 /* Implicit conversions are not allowed for return values. */
3182 if (state->current_function->return_type != ret_type) {
3183 YYLTYPE loc = this->get_location();
3185 _mesa_glsl_error(& loc, state,
3186 "`return' with wrong type %s, in function `%s' "
3187 "returning %s",
3188 ret_type->name,
3189 state->current_function->function_name(),
3190 state->current_function->return_type->name);
3193 inst = new(ctx) ir_return(ret);
3194 } else {
3195 if (state->current_function->return_type->base_type !=
3196 GLSL_TYPE_VOID) {
3197 YYLTYPE loc = this->get_location();
3199 _mesa_glsl_error(& loc, state,
3200 "`return' with no value, in function %s returning "
3201 "non-void",
3202 state->current_function->function_name());
3204 inst = new(ctx) ir_return;
3207 state->found_return = true;
3208 instructions->push_tail(inst);
3209 break;
3212 case ast_discard:
3213 if (state->target != fragment_shader) {
3214 YYLTYPE loc = this->get_location();
3216 _mesa_glsl_error(& loc, state,
3217 "`discard' may only appear in a fragment shader");
3219 instructions->push_tail(new(ctx) ir_discard);
3220 break;
3222 case ast_break:
3223 case ast_continue:
3224 /* FINISHME: Handle switch-statements. They cannot contain 'continue',
3225 * FINISHME: and they use a different IR instruction for 'break'.
3227 /* FINISHME: Correctly handle the nesting. If a switch-statement is
3228 * FINISHME: inside a loop, a 'continue' is valid and will bind to the
3229 * FINISHME: loop.
3231 if (state->loop_or_switch_nesting == NULL) {
3232 YYLTYPE loc = this->get_location();
3234 _mesa_glsl_error(& loc, state,
3235 "`%s' may only appear in a loop",
3236 (mode == ast_break) ? "break" : "continue");
3237 } else {
3238 ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
3240 /* Inline the for loop expression again, since we don't know
3241 * where near the end of the loop body the normal copy of it
3242 * is going to be placed.
3244 if (mode == ast_continue &&
3245 state->loop_or_switch_nesting_ast->rest_expression) {
3246 state->loop_or_switch_nesting_ast->rest_expression->hir(instructions,
3247 state);
3250 if (loop != NULL) {
3251 ir_loop_jump *const jump =
3252 new(ctx) ir_loop_jump((mode == ast_break)
3253 ? ir_loop_jump::jump_break
3254 : ir_loop_jump::jump_continue);
3255 instructions->push_tail(jump);
3259 break;
3262 /* Jump instructions do not have r-values.
3264 return NULL;
3268 ir_rvalue *
3269 ast_selection_statement::hir(exec_list *instructions,
3270 struct _mesa_glsl_parse_state *state)
3272 void *ctx = state;
3274 ir_rvalue *const condition = this->condition->hir(instructions, state);
3276 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
3278 * "Any expression whose type evaluates to a Boolean can be used as the
3279 * conditional expression bool-expression. Vector types are not accepted
3280 * as the expression to if."
3282 * The checks are separated so that higher quality diagnostics can be
3283 * generated for cases where both rules are violated.
3285 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
3286 YYLTYPE loc = this->condition->get_location();
3288 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
3289 "boolean");
3292 ir_if *const stmt = new(ctx) ir_if(condition);
3294 if (then_statement != NULL) {
3295 state->symbols->push_scope();
3296 then_statement->hir(& stmt->then_instructions, state);
3297 state->symbols->pop_scope();
3300 if (else_statement != NULL) {
3301 state->symbols->push_scope();
3302 else_statement->hir(& stmt->else_instructions, state);
3303 state->symbols->pop_scope();
3306 instructions->push_tail(stmt);
3308 /* if-statements do not have r-values.
3310 return NULL;
3314 void
3315 ast_iteration_statement::condition_to_hir(ir_loop *stmt,
3316 struct _mesa_glsl_parse_state *state)
3318 void *ctx = state;
3320 if (condition != NULL) {
3321 ir_rvalue *const cond =
3322 condition->hir(& stmt->body_instructions, state);
3324 if ((cond == NULL)
3325 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
3326 YYLTYPE loc = condition->get_location();
3328 _mesa_glsl_error(& loc, state,
3329 "loop condition must be scalar boolean");
3330 } else {
3331 /* As the first code in the loop body, generate a block that looks
3332 * like 'if (!condition) break;' as the loop termination condition.
3334 ir_rvalue *const not_cond =
3335 new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
3336 NULL);
3338 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
3340 ir_jump *const break_stmt =
3341 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
3343 if_stmt->then_instructions.push_tail(break_stmt);
3344 stmt->body_instructions.push_tail(if_stmt);
3350 ir_rvalue *
3351 ast_iteration_statement::hir(exec_list *instructions,
3352 struct _mesa_glsl_parse_state *state)
3354 void *ctx = state;
3356 /* For-loops and while-loops start a new scope, but do-while loops do not.
3358 if (mode != ast_do_while)
3359 state->symbols->push_scope();
3361 if (init_statement != NULL)
3362 init_statement->hir(instructions, state);
3364 ir_loop *const stmt = new(ctx) ir_loop();
3365 instructions->push_tail(stmt);
3367 /* Track the current loop and / or switch-statement nesting.
3369 ir_instruction *const nesting = state->loop_or_switch_nesting;
3370 ast_iteration_statement *nesting_ast = state->loop_or_switch_nesting_ast;
3372 state->loop_or_switch_nesting = stmt;
3373 state->loop_or_switch_nesting_ast = this;
3375 if (mode != ast_do_while)
3376 condition_to_hir(stmt, state);
3378 if (body != NULL)
3379 body->hir(& stmt->body_instructions, state);
3381 if (rest_expression != NULL)
3382 rest_expression->hir(& stmt->body_instructions, state);
3384 if (mode == ast_do_while)
3385 condition_to_hir(stmt, state);
3387 if (mode != ast_do_while)
3388 state->symbols->pop_scope();
3390 /* Restore previous nesting before returning.
3392 state->loop_or_switch_nesting = nesting;
3393 state->loop_or_switch_nesting_ast = nesting_ast;
3395 /* Loops do not have r-values.
3397 return NULL;
3401 ir_rvalue *
3402 ast_type_specifier::hir(exec_list *instructions,
3403 struct _mesa_glsl_parse_state *state)
3405 if (!this->is_precision_statement && this->structure == NULL)
3406 return NULL;
3408 YYLTYPE loc = this->get_location();
3410 if (this->precision != ast_precision_none
3411 && state->language_version != 100
3412 && state->language_version < 130) {
3413 _mesa_glsl_error(&loc, state,
3414 "precision qualifiers exist only in "
3415 "GLSL ES 1.00, and GLSL 1.30 and later");
3416 return NULL;
3418 if (this->precision != ast_precision_none
3419 && this->structure != NULL) {
3420 _mesa_glsl_error(&loc, state,
3421 "precision qualifiers do not apply to structures");
3422 return NULL;
3425 /* If this is a precision statement, check that the type to which it is
3426 * applied is either float or int.
3428 * From section 4.5.3 of the GLSL 1.30 spec:
3429 * "The precision statement
3430 * precision precision-qualifier type;
3431 * can be used to establish a default precision qualifier. The type
3432 * field can be either int or float [...]. Any other types or
3433 * qualifiers will result in an error.
3435 if (this->is_precision_statement) {
3436 assert(this->precision != ast_precision_none);
3437 assert(this->structure == NULL); /* The check for structures was
3438 * performed above. */
3439 if (this->is_array) {
3440 _mesa_glsl_error(&loc, state,
3441 "default precision statements do not apply to "
3442 "arrays");
3443 return NULL;
3445 if (this->type_specifier != ast_float
3446 && this->type_specifier != ast_int) {
3447 _mesa_glsl_error(&loc, state,
3448 "default precision statements apply only to types "
3449 "float and int");
3450 return NULL;
3453 /* FINISHME: Translate precision statements into IR. */
3454 return NULL;
3457 if (this->structure != NULL)
3458 return this->structure->hir(instructions, state);
3460 return NULL;
3464 ir_rvalue *
3465 ast_struct_specifier::hir(exec_list *instructions,
3466 struct _mesa_glsl_parse_state *state)
3468 unsigned decl_count = 0;
3470 /* Make an initial pass over the list of structure fields to determine how
3471 * many there are. Each element in this list is an ast_declarator_list.
3472 * This means that we actually need to count the number of elements in the
3473 * 'declarations' list in each of the elements.
3475 foreach_list_typed (ast_declarator_list, decl_list, link,
3476 &this->declarations) {
3477 foreach_list_const (decl_ptr, & decl_list->declarations) {
3478 decl_count++;
3482 /* Allocate storage for the structure fields and process the field
3483 * declarations. As the declarations are processed, try to also convert
3484 * the types to HIR. This ensures that structure definitions embedded in
3485 * other structure definitions are processed.
3487 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
3488 decl_count);
3490 unsigned i = 0;
3491 foreach_list_typed (ast_declarator_list, decl_list, link,
3492 &this->declarations) {
3493 const char *type_name;
3495 decl_list->type->specifier->hir(instructions, state);
3497 /* Section 10.9 of the GLSL ES 1.00 specification states that
3498 * embedded structure definitions have been removed from the language.
3500 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
3501 YYLTYPE loc = this->get_location();
3502 _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
3503 "not allowed in GLSL ES 1.00.");
3506 const glsl_type *decl_type =
3507 decl_list->type->specifier->glsl_type(& type_name, state);
3509 foreach_list_typed (ast_declaration, decl, link,
3510 &decl_list->declarations) {
3511 const struct glsl_type *field_type = decl_type;
3512 if (decl->is_array) {
3513 YYLTYPE loc = decl->get_location();
3514 field_type = process_array_type(&loc, decl_type, decl->array_size,
3515 state);
3517 fields[i].type = (field_type != NULL)
3518 ? field_type : glsl_type::error_type;
3519 fields[i].name = decl->identifier;
3520 i++;
3524 assert(i == decl_count);
3526 const glsl_type *t =
3527 glsl_type::get_record_instance(fields, decl_count, this->name);
3529 YYLTYPE loc = this->get_location();
3530 if (!state->symbols->add_type(name, t)) {
3531 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
3532 } else {
3533 const glsl_type **s = reralloc(state, state->user_structures,
3534 const glsl_type *,
3535 state->num_user_structures + 1);
3536 if (s != NULL) {
3537 s[state->num_user_structures] = t;
3538 state->user_structures = s;
3539 state->num_user_structures++;
3543 /* Structure type definitions do not have r-values.
3545 return NULL;