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