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