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