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