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