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