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