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