7f30a7088551883b7be9aa1295ac50b00704aaa7
[mesa.git] / src / compiler / 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 "compiler/glsl_types.h"
56 #include "util/hash_table.h"
57 #include "main/mtypes.h"
58 #include "main/macros.h"
59 #include "main/shaderobj.h"
60 #include "ir.h"
61 #include "ir_builder.h"
62 #include "builtin_functions.h"
63
64 using namespace ir_builder;
65
66 static void
67 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
68 exec_list *instructions);
69 static void
70 verify_subroutine_associated_funcs(struct _mesa_glsl_parse_state *state);
71
72 static void
73 remove_per_vertex_blocks(exec_list *instructions,
74 _mesa_glsl_parse_state *state, ir_variable_mode mode);
75
76 /**
77 * Visitor class that finds the first instance of any write-only variable that
78 * is ever read, if any
79 */
80 class read_from_write_only_variable_visitor : public ir_hierarchical_visitor
81 {
82 public:
83 read_from_write_only_variable_visitor() : found(NULL)
84 {
85 }
86
87 virtual ir_visitor_status visit(ir_dereference_variable *ir)
88 {
89 if (this->in_assignee)
90 return visit_continue;
91
92 ir_variable *var = ir->variable_referenced();
93 /* We can have memory_write_only set on both images and buffer variables,
94 * but in the former there is a distinction between reads from
95 * the variable itself (write_only) and from the memory they point to
96 * (memory_write_only), while in the case of buffer variables there is
97 * no such distinction, that is why this check here is limited to
98 * buffer variables alone.
99 */
100 if (!var || var->data.mode != ir_var_shader_storage)
101 return visit_continue;
102
103 if (var->data.memory_write_only) {
104 found = var;
105 return visit_stop;
106 }
107
108 return visit_continue;
109 }
110
111 ir_variable *get_variable() {
112 return found;
113 }
114
115 virtual ir_visitor_status visit_enter(ir_expression *ir)
116 {
117 /* .length() doesn't actually read anything */
118 if (ir->operation == ir_unop_ssbo_unsized_array_length)
119 return visit_continue_with_parent;
120
121 return visit_continue;
122 }
123
124 private:
125 ir_variable *found;
126 };
127
128 void
129 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
130 {
131 _mesa_glsl_initialize_variables(instructions, state);
132
133 state->symbols->separate_function_namespace = state->language_version == 110;
134
135 state->current_function = NULL;
136
137 state->toplevel_ir = instructions;
138
139 state->gs_input_prim_type_specified = false;
140 state->tcs_output_vertices_specified = false;
141 state->cs_input_local_size_specified = false;
142
143 /* Section 4.2 of the GLSL 1.20 specification states:
144 * "The built-in functions are scoped in a scope outside the global scope
145 * users declare global variables in. That is, a shader's global scope,
146 * available for user-defined functions and global variables, is nested
147 * inside the scope containing the built-in functions."
148 *
149 * Since built-in functions like ftransform() access built-in variables,
150 * it follows that those must be in the outer scope as well.
151 *
152 * We push scope here to create this nesting effect...but don't pop.
153 * This way, a shader's globals are still in the symbol table for use
154 * by the linker.
155 */
156 state->symbols->push_scope();
157
158 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
159 ast->hir(instructions, state);
160
161 verify_subroutine_associated_funcs(state);
162 detect_recursion_unlinked(state, instructions);
163 detect_conflicting_assignments(state, instructions);
164
165 state->toplevel_ir = NULL;
166
167 /* Move all of the variable declarations to the front of the IR list, and
168 * reverse the order. This has the (intended!) side effect that vertex
169 * shader inputs and fragment shader outputs will appear in the IR in the
170 * same order that they appeared in the shader code. This results in the
171 * locations being assigned in the declared order. Many (arguably buggy)
172 * applications depend on this behavior, and it matches what nearly all
173 * other drivers do.
174 */
175 foreach_in_list_safe(ir_instruction, node, instructions) {
176 ir_variable *const var = node->as_variable();
177
178 if (var == NULL)
179 continue;
180
181 var->remove();
182 instructions->push_head(var);
183 }
184
185 /* Figure out if gl_FragCoord is actually used in fragment shader */
186 ir_variable *const var = state->symbols->get_variable("gl_FragCoord");
187 if (var != NULL)
188 state->fs_uses_gl_fragcoord = var->data.used;
189
190 /* From section 7.1 (Built-In Language Variables) of the GLSL 4.10 spec:
191 *
192 * If multiple shaders using members of a built-in block belonging to
193 * the same interface are linked together in the same program, they
194 * must all redeclare the built-in block in the same way, as described
195 * in section 4.3.7 "Interface Blocks" for interface block matching, or
196 * a link error will result.
197 *
198 * The phrase "using members of a built-in block" implies that if two
199 * shaders are linked together and one of them *does not use* any members
200 * of the built-in block, then that shader does not need to have a matching
201 * redeclaration of the built-in block.
202 *
203 * This appears to be a clarification to the behaviour established for
204 * gl_PerVertex by GLSL 1.50, therefore implement it regardless of GLSL
205 * version.
206 *
207 * The definition of "interface" in section 4.3.7 that applies here is as
208 * follows:
209 *
210 * The boundary between adjacent programmable pipeline stages: This
211 * spans all the outputs in all compilation units of the first stage
212 * and all the inputs in all compilation units of the second stage.
213 *
214 * Therefore this rule applies to both inter- and intra-stage linking.
215 *
216 * The easiest way to implement this is to check whether the shader uses
217 * gl_PerVertex right after ast-to-ir conversion, and if it doesn't, simply
218 * remove all the relevant variable declaration from the IR, so that the
219 * linker won't see them and complain about mismatches.
220 */
221 remove_per_vertex_blocks(instructions, state, ir_var_shader_in);
222 remove_per_vertex_blocks(instructions, state, ir_var_shader_out);
223
224 /* Check that we don't have reads from write-only variables */
225 read_from_write_only_variable_visitor v;
226 v.run(instructions);
227 ir_variable *error_var = v.get_variable();
228 if (error_var) {
229 /* It would be nice to have proper location information, but for that
230 * we would need to check this as we process each kind of AST node
231 */
232 YYLTYPE loc;
233 memset(&loc, 0, sizeof(loc));
234 _mesa_glsl_error(&loc, state, "Read from write-only variable `%s'",
235 error_var->name);
236 }
237 }
238
239
240 static ir_expression_operation
241 get_implicit_conversion_operation(const glsl_type *to, const glsl_type *from,
242 struct _mesa_glsl_parse_state *state)
243 {
244 switch (to->base_type) {
245 case GLSL_TYPE_FLOAT:
246 switch (from->base_type) {
247 case GLSL_TYPE_INT: return ir_unop_i2f;
248 case GLSL_TYPE_UINT: return ir_unop_u2f;
249 default: return (ir_expression_operation)0;
250 }
251
252 case GLSL_TYPE_UINT:
253 if (!state->has_implicit_uint_to_int_conversion())
254 return (ir_expression_operation)0;
255 switch (from->base_type) {
256 case GLSL_TYPE_INT: return ir_unop_i2u;
257 default: return (ir_expression_operation)0;
258 }
259
260 case GLSL_TYPE_DOUBLE:
261 if (!state->has_double())
262 return (ir_expression_operation)0;
263 switch (from->base_type) {
264 case GLSL_TYPE_INT: return ir_unop_i2d;
265 case GLSL_TYPE_UINT: return ir_unop_u2d;
266 case GLSL_TYPE_FLOAT: return ir_unop_f2d;
267 case GLSL_TYPE_INT64: return ir_unop_i642d;
268 case GLSL_TYPE_UINT64: return ir_unop_u642d;
269 default: return (ir_expression_operation)0;
270 }
271
272 case GLSL_TYPE_UINT64:
273 if (!state->has_int64())
274 return (ir_expression_operation)0;
275 switch (from->base_type) {
276 case GLSL_TYPE_INT: return ir_unop_i2u64;
277 case GLSL_TYPE_UINT: return ir_unop_u2u64;
278 case GLSL_TYPE_INT64: return ir_unop_i642u64;
279 default: return (ir_expression_operation)0;
280 }
281
282 case GLSL_TYPE_INT64:
283 if (!state->has_int64())
284 return (ir_expression_operation)0;
285 switch (from->base_type) {
286 case GLSL_TYPE_INT: return ir_unop_i2i64;
287 default: return (ir_expression_operation)0;
288 }
289
290 default: return (ir_expression_operation)0;
291 }
292 }
293
294
295 /**
296 * If a conversion is available, convert one operand to a different type
297 *
298 * The \c from \c ir_rvalue is converted "in place".
299 *
300 * \param to Type that the operand it to be converted to
301 * \param from Operand that is being converted
302 * \param state GLSL compiler state
303 *
304 * \return
305 * If a conversion is possible (or unnecessary), \c true is returned.
306 * Otherwise \c false is returned.
307 */
308 static bool
309 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
310 struct _mesa_glsl_parse_state *state)
311 {
312 void *ctx = state;
313 if (to->base_type == from->type->base_type)
314 return true;
315
316 /* Prior to GLSL 1.20, there are no implicit conversions */
317 if (!state->has_implicit_conversions())
318 return false;
319
320 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
321 *
322 * "There are no implicit array or structure conversions. For
323 * example, an array of int cannot be implicitly converted to an
324 * array of float.
325 */
326 if (!to->is_numeric() || !from->type->is_numeric())
327 return false;
328
329 /* We don't actually want the specific type `to`, we want a type
330 * with the same base type as `to`, but the same vector width as
331 * `from`.
332 */
333 to = glsl_type::get_instance(to->base_type, from->type->vector_elements,
334 from->type->matrix_columns);
335
336 ir_expression_operation op = get_implicit_conversion_operation(to, from->type, state);
337 if (op) {
338 from = new(ctx) ir_expression(op, to, from, NULL);
339 return true;
340 } else {
341 return false;
342 }
343 }
344
345
346 static const struct glsl_type *
347 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
348 bool multiply,
349 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
350 {
351 const glsl_type *type_a = value_a->type;
352 const glsl_type *type_b = value_b->type;
353
354 /* From GLSL 1.50 spec, page 56:
355 *
356 * "The arithmetic binary operators add (+), subtract (-),
357 * multiply (*), and divide (/) operate on integer and
358 * floating-point scalars, vectors, and matrices."
359 */
360 if (!type_a->is_numeric() || !type_b->is_numeric()) {
361 _mesa_glsl_error(loc, state,
362 "operands to arithmetic operators must be numeric");
363 return glsl_type::error_type;
364 }
365
366
367 /* "If one operand is floating-point based and the other is
368 * not, then the conversions from Section 4.1.10 "Implicit
369 * Conversions" are applied to the non-floating-point-based operand."
370 */
371 if (!apply_implicit_conversion(type_a, value_b, state)
372 && !apply_implicit_conversion(type_b, value_a, state)) {
373 _mesa_glsl_error(loc, state,
374 "could not implicitly convert operands to "
375 "arithmetic operator");
376 return glsl_type::error_type;
377 }
378 type_a = value_a->type;
379 type_b = value_b->type;
380
381 /* "If the operands are integer types, they must both be signed or
382 * both be unsigned."
383 *
384 * From this rule and the preceeding conversion it can be inferred that
385 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
386 * The is_numeric check above already filtered out the case where either
387 * type is not one of these, so now the base types need only be tested for
388 * equality.
389 */
390 if (type_a->base_type != type_b->base_type) {
391 _mesa_glsl_error(loc, state,
392 "base type mismatch for arithmetic operator");
393 return glsl_type::error_type;
394 }
395
396 /* "All arithmetic binary operators result in the same fundamental type
397 * (signed integer, unsigned integer, or floating-point) as the
398 * operands they operate on, after operand type conversion. After
399 * conversion, the following cases are valid
400 *
401 * * The two operands are scalars. In this case the operation is
402 * applied, resulting in a scalar."
403 */
404 if (type_a->is_scalar() && type_b->is_scalar())
405 return type_a;
406
407 /* "* One operand is a scalar, and the other is a vector or matrix.
408 * In this case, the scalar operation is applied independently to each
409 * component of the vector or matrix, resulting in the same size
410 * vector or matrix."
411 */
412 if (type_a->is_scalar()) {
413 if (!type_b->is_scalar())
414 return type_b;
415 } else if (type_b->is_scalar()) {
416 return type_a;
417 }
418
419 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
420 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
421 * handled.
422 */
423 assert(!type_a->is_scalar());
424 assert(!type_b->is_scalar());
425
426 /* "* The two operands are vectors of the same size. In this case, the
427 * operation is done component-wise resulting in the same size
428 * vector."
429 */
430 if (type_a->is_vector() && type_b->is_vector()) {
431 if (type_a == type_b) {
432 return type_a;
433 } else {
434 _mesa_glsl_error(loc, state,
435 "vector size mismatch for arithmetic operator");
436 return glsl_type::error_type;
437 }
438 }
439
440 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
441 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
442 * <vector, vector> have been handled. At least one of the operands must
443 * be matrix. Further, since there are no integer matrix types, the base
444 * type of both operands must be float.
445 */
446 assert(type_a->is_matrix() || type_b->is_matrix());
447 assert(type_a->is_float() || type_a->is_double());
448 assert(type_b->is_float() || type_b->is_double());
449
450 /* "* The operator is add (+), subtract (-), or divide (/), and the
451 * operands are matrices with the same number of rows and the same
452 * number of columns. In this case, the operation is done component-
453 * wise resulting in the same size matrix."
454 * * The operator is multiply (*), where both operands are matrices or
455 * one operand is a vector and the other a matrix. A right vector
456 * operand is treated as a column vector and a left vector operand as a
457 * row vector. In all these cases, it is required that the number of
458 * columns of the left operand is equal to the number of rows of the
459 * right operand. Then, the multiply (*) operation does a linear
460 * algebraic multiply, yielding an object that has the same number of
461 * rows as the left operand and the same number of columns as the right
462 * operand. Section 5.10 "Vector and Matrix Operations" explains in
463 * more detail how vectors and matrices are operated on."
464 */
465 if (! multiply) {
466 if (type_a == type_b)
467 return type_a;
468 } else {
469 const glsl_type *type = glsl_type::get_mul_type(type_a, type_b);
470
471 if (type == glsl_type::error_type) {
472 _mesa_glsl_error(loc, state,
473 "size mismatch for matrix multiplication");
474 }
475
476 return type;
477 }
478
479
480 /* "All other cases are illegal."
481 */
482 _mesa_glsl_error(loc, state, "type mismatch");
483 return glsl_type::error_type;
484 }
485
486
487 static const struct glsl_type *
488 unary_arithmetic_result_type(const struct glsl_type *type,
489 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
490 {
491 /* From GLSL 1.50 spec, page 57:
492 *
493 * "The arithmetic unary operators negate (-), post- and pre-increment
494 * and decrement (-- and ++) operate on integer or floating-point
495 * values (including vectors and matrices). All unary operators work
496 * component-wise on their operands. These result with the same type
497 * they operated on."
498 */
499 if (!type->is_numeric()) {
500 _mesa_glsl_error(loc, state,
501 "operands to arithmetic operators must be numeric");
502 return glsl_type::error_type;
503 }
504
505 return type;
506 }
507
508 /**
509 * \brief Return the result type of a bit-logic operation.
510 *
511 * If the given types to the bit-logic operator are invalid, return
512 * glsl_type::error_type.
513 *
514 * \param value_a LHS of bit-logic op
515 * \param value_b RHS of bit-logic op
516 */
517 static const struct glsl_type *
518 bit_logic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
519 ast_operators op,
520 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
521 {
522 const glsl_type *type_a = value_a->type;
523 const glsl_type *type_b = value_b->type;
524
525 if (!state->check_bitwise_operations_allowed(loc)) {
526 return glsl_type::error_type;
527 }
528
529 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
530 *
531 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
532 * (|). The operands must be of type signed or unsigned integers or
533 * integer vectors."
534 */
535 if (!type_a->is_integer_32_64()) {
536 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
537 ast_expression::operator_string(op));
538 return glsl_type::error_type;
539 }
540 if (!type_b->is_integer_32_64()) {
541 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
542 ast_expression::operator_string(op));
543 return glsl_type::error_type;
544 }
545
546 /* Prior to GLSL 4.0 / GL_ARB_gpu_shader5, implicit conversions didn't
547 * make sense for bitwise operations, as they don't operate on floats.
548 *
549 * GLSL 4.0 added implicit int -> uint conversions, which are relevant
550 * here. It wasn't clear whether or not we should apply them to bitwise
551 * operations. However, Khronos has decided that they should in future
552 * language revisions. Applications also rely on this behavior. We opt
553 * to apply them in general, but issue a portability warning.
554 *
555 * See https://www.khronos.org/bugzilla/show_bug.cgi?id=1405
556 */
557 if (type_a->base_type != type_b->base_type) {
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 "`%s` operator",
563 ast_expression::operator_string(op));
564 return glsl_type::error_type;
565 } else {
566 _mesa_glsl_warning(loc, state,
567 "some implementations may not support implicit "
568 "int -> uint conversions for `%s' operators; "
569 "consider casting explicitly for portability",
570 ast_expression::operator_string(op));
571 }
572 type_a = value_a->type;
573 type_b = value_b->type;
574 }
575
576 /* "The fundamental types of the operands (signed or unsigned) must
577 * match,"
578 */
579 if (type_a->base_type != type_b->base_type) {
580 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
581 "base type", ast_expression::operator_string(op));
582 return glsl_type::error_type;
583 }
584
585 /* "The operands cannot be vectors of differing size." */
586 if (type_a->is_vector() &&
587 type_b->is_vector() &&
588 type_a->vector_elements != type_b->vector_elements) {
589 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
590 "different sizes", ast_expression::operator_string(op));
591 return glsl_type::error_type;
592 }
593
594 /* "If one operand is a scalar and the other a vector, the scalar is
595 * applied component-wise to the vector, resulting in the same type as
596 * the vector. The fundamental types of the operands [...] will be the
597 * resulting fundamental type."
598 */
599 if (type_a->is_scalar())
600 return type_b;
601 else
602 return type_a;
603 }
604
605 static const struct glsl_type *
606 modulus_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
607 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
608 {
609 const glsl_type *type_a = value_a->type;
610 const glsl_type *type_b = value_b->type;
611
612 if (!state->check_version(130, 300, loc, "operator '%%' is reserved")) {
613 return glsl_type::error_type;
614 }
615
616 /* Section 5.9 (Expressions) of the GLSL 4.00 specification says:
617 *
618 * "The operator modulus (%) operates on signed or unsigned integers or
619 * integer vectors."
620 */
621 if (!type_a->is_integer_32_64()) {
622 _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer");
623 return glsl_type::error_type;
624 }
625 if (!type_b->is_integer_32_64()) {
626 _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer");
627 return glsl_type::error_type;
628 }
629
630 /* "If the fundamental types in the operands do not match, then the
631 * conversions from section 4.1.10 "Implicit Conversions" are applied
632 * to create matching types."
633 *
634 * Note that GLSL 4.00 (and GL_ARB_gpu_shader5) introduced implicit
635 * int -> uint conversion rules. Prior to that, there were no implicit
636 * conversions. So it's harmless to apply them universally - no implicit
637 * conversions will exist. If the types don't match, we'll receive false,
638 * and raise an error, satisfying the GLSL 1.50 spec, page 56:
639 *
640 * "The operand types must both be signed or unsigned."
641 */
642 if (!apply_implicit_conversion(type_a, value_b, state) &&
643 !apply_implicit_conversion(type_b, value_a, state)) {
644 _mesa_glsl_error(loc, state,
645 "could not implicitly convert operands to "
646 "modulus (%%) operator");
647 return glsl_type::error_type;
648 }
649 type_a = value_a->type;
650 type_b = value_b->type;
651
652 /* "The operands cannot be vectors of differing size. If one operand is
653 * a scalar and the other vector, then the scalar is applied component-
654 * wise to the vector, resulting in the same type as the vector. If both
655 * are vectors of the same size, the result is computed component-wise."
656 */
657 if (type_a->is_vector()) {
658 if (!type_b->is_vector()
659 || (type_a->vector_elements == type_b->vector_elements))
660 return type_a;
661 } else
662 return type_b;
663
664 /* "The operator modulus (%) is not defined for any other data types
665 * (non-integer types)."
666 */
667 _mesa_glsl_error(loc, state, "type mismatch");
668 return glsl_type::error_type;
669 }
670
671
672 static const struct glsl_type *
673 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
674 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
675 {
676 const glsl_type *type_a = value_a->type;
677 const glsl_type *type_b = value_b->type;
678
679 /* From GLSL 1.50 spec, page 56:
680 * "The relational operators greater than (>), less than (<), greater
681 * than or equal (>=), and less than or equal (<=) operate only on
682 * scalar integer and scalar floating-point expressions."
683 */
684 if (!type_a->is_numeric()
685 || !type_b->is_numeric()
686 || !type_a->is_scalar()
687 || !type_b->is_scalar()) {
688 _mesa_glsl_error(loc, state,
689 "operands to relational operators must be scalar and "
690 "numeric");
691 return glsl_type::error_type;
692 }
693
694 /* "Either the operands' types must match, or the conversions from
695 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
696 * operand, after which the types must match."
697 */
698 if (!apply_implicit_conversion(type_a, value_b, state)
699 && !apply_implicit_conversion(type_b, value_a, state)) {
700 _mesa_glsl_error(loc, state,
701 "could not implicitly convert operands to "
702 "relational operator");
703 return glsl_type::error_type;
704 }
705 type_a = value_a->type;
706 type_b = value_b->type;
707
708 if (type_a->base_type != type_b->base_type) {
709 _mesa_glsl_error(loc, state, "base type mismatch");
710 return glsl_type::error_type;
711 }
712
713 /* "The result is scalar Boolean."
714 */
715 return glsl_type::bool_type;
716 }
717
718 /**
719 * \brief Return the result type of a bit-shift operation.
720 *
721 * If the given types to the bit-shift operator are invalid, return
722 * glsl_type::error_type.
723 *
724 * \param type_a Type of LHS of bit-shift op
725 * \param type_b Type of RHS of bit-shift op
726 */
727 static const struct glsl_type *
728 shift_result_type(const struct glsl_type *type_a,
729 const struct glsl_type *type_b,
730 ast_operators op,
731 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
732 {
733 if (!state->check_bitwise_operations_allowed(loc)) {
734 return glsl_type::error_type;
735 }
736
737 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
738 *
739 * "The shift operators (<<) and (>>). For both operators, the operands
740 * must be signed or unsigned integers or integer vectors. One operand
741 * can be signed while the other is unsigned."
742 */
743 if (!type_a->is_integer_32_64()) {
744 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
745 "integer vector", ast_expression::operator_string(op));
746 return glsl_type::error_type;
747
748 }
749 if (!type_b->is_integer()) {
750 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
751 "integer vector", ast_expression::operator_string(op));
752 return glsl_type::error_type;
753 }
754
755 /* "If the first operand is a scalar, the second operand has to be
756 * a scalar as well."
757 */
758 if (type_a->is_scalar() && !type_b->is_scalar()) {
759 _mesa_glsl_error(loc, state, "if the first operand of %s is scalar, the "
760 "second must be scalar as well",
761 ast_expression::operator_string(op));
762 return glsl_type::error_type;
763 }
764
765 /* If both operands are vectors, check that they have same number of
766 * elements.
767 */
768 if (type_a->is_vector() &&
769 type_b->is_vector() &&
770 type_a->vector_elements != type_b->vector_elements) {
771 _mesa_glsl_error(loc, state, "vector operands to operator %s must "
772 "have same number of elements",
773 ast_expression::operator_string(op));
774 return glsl_type::error_type;
775 }
776
777 /* "In all cases, the resulting type will be the same type as the left
778 * operand."
779 */
780 return type_a;
781 }
782
783 /**
784 * Returns the innermost array index expression in an rvalue tree.
785 * This is the largest indexing level -- if an array of blocks, then
786 * it is the block index rather than an indexing expression for an
787 * array-typed member of an array of blocks.
788 */
789 static ir_rvalue *
790 find_innermost_array_index(ir_rvalue *rv)
791 {
792 ir_dereference_array *last = NULL;
793 while (rv) {
794 if (rv->as_dereference_array()) {
795 last = rv->as_dereference_array();
796 rv = last->array;
797 } else if (rv->as_dereference_record())
798 rv = rv->as_dereference_record()->record;
799 else if (rv->as_swizzle())
800 rv = rv->as_swizzle()->val;
801 else
802 rv = NULL;
803 }
804
805 if (last)
806 return last->array_index;
807
808 return NULL;
809 }
810
811 /**
812 * Validates that a value can be assigned to a location with a specified type
813 *
814 * Validates that \c rhs can be assigned to some location. If the types are
815 * not an exact match but an automatic conversion is possible, \c rhs will be
816 * converted.
817 *
818 * \return
819 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
820 * Otherwise the actual RHS to be assigned will be returned. This may be
821 * \c rhs, or it may be \c rhs after some type conversion.
822 *
823 * \note
824 * In addition to being used for assignments, this function is used to
825 * type-check return values.
826 */
827 static ir_rvalue *
828 validate_assignment(struct _mesa_glsl_parse_state *state,
829 YYLTYPE loc, ir_rvalue *lhs,
830 ir_rvalue *rhs, bool is_initializer)
831 {
832 /* If there is already some error in the RHS, just return it. Anything
833 * else will lead to an avalanche of error message back to the user.
834 */
835 if (rhs->type->is_error())
836 return rhs;
837
838 /* In the Tessellation Control Shader:
839 * If a per-vertex output variable is used as an l-value, it is an error
840 * if the expression indicating the vertex number is not the identifier
841 * `gl_InvocationID`.
842 */
843 if (state->stage == MESA_SHADER_TESS_CTRL && !lhs->type->is_error()) {
844 ir_variable *var = lhs->variable_referenced();
845 if (var && var->data.mode == ir_var_shader_out && !var->data.patch) {
846 ir_rvalue *index = find_innermost_array_index(lhs);
847 ir_variable *index_var = index ? index->variable_referenced() : NULL;
848 if (!index_var || strcmp(index_var->name, "gl_InvocationID") != 0) {
849 _mesa_glsl_error(&loc, state,
850 "Tessellation control shader outputs can only "
851 "be indexed by gl_InvocationID");
852 return NULL;
853 }
854 }
855 }
856
857 /* If the types are identical, the assignment can trivially proceed.
858 */
859 if (rhs->type == lhs->type)
860 return rhs;
861
862 /* If the array element types are the same and the LHS is unsized,
863 * the assignment is okay for initializers embedded in variable
864 * declarations.
865 *
866 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
867 * is handled by ir_dereference::is_lvalue.
868 */
869 const glsl_type *lhs_t = lhs->type;
870 const glsl_type *rhs_t = rhs->type;
871 bool unsized_array = false;
872 while(lhs_t->is_array()) {
873 if (rhs_t == lhs_t)
874 break; /* the rest of the inner arrays match so break out early */
875 if (!rhs_t->is_array()) {
876 unsized_array = false;
877 break; /* number of dimensions mismatch */
878 }
879 if (lhs_t->length == rhs_t->length) {
880 lhs_t = lhs_t->fields.array;
881 rhs_t = rhs_t->fields.array;
882 continue;
883 } else if (lhs_t->is_unsized_array()) {
884 unsized_array = true;
885 } else {
886 unsized_array = false;
887 break; /* sized array mismatch */
888 }
889 lhs_t = lhs_t->fields.array;
890 rhs_t = rhs_t->fields.array;
891 }
892 if (unsized_array) {
893 if (is_initializer) {
894 return rhs;
895 } else {
896 _mesa_glsl_error(&loc, state,
897 "implicitly sized arrays cannot be assigned");
898 return NULL;
899 }
900 }
901
902 /* Check for implicit conversion in GLSL 1.20 */
903 if (apply_implicit_conversion(lhs->type, rhs, state)) {
904 if (rhs->type == lhs->type)
905 return rhs;
906 }
907
908 _mesa_glsl_error(&loc, state,
909 "%s of type %s cannot be assigned to "
910 "variable of type %s",
911 is_initializer ? "initializer" : "value",
912 rhs->type->name, lhs->type->name);
913
914 return NULL;
915 }
916
917 static void
918 mark_whole_array_access(ir_rvalue *access)
919 {
920 ir_dereference_variable *deref = access->as_dereference_variable();
921
922 if (deref && deref->var) {
923 deref->var->data.max_array_access = deref->type->length - 1;
924 }
925 }
926
927 static bool
928 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
929 const char *non_lvalue_description,
930 ir_rvalue *lhs, ir_rvalue *rhs,
931 ir_rvalue **out_rvalue, bool needs_rvalue,
932 bool is_initializer,
933 YYLTYPE lhs_loc)
934 {
935 void *ctx = state;
936 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
937
938 ir_variable *lhs_var = lhs->variable_referenced();
939 if (lhs_var)
940 lhs_var->data.assigned = true;
941
942 if (!error_emitted) {
943 if (non_lvalue_description != NULL) {
944 _mesa_glsl_error(&lhs_loc, state,
945 "assignment to %s",
946 non_lvalue_description);
947 error_emitted = true;
948 } else if (lhs_var != NULL && (lhs_var->data.read_only ||
949 (lhs_var->data.mode == ir_var_shader_storage &&
950 lhs_var->data.memory_read_only))) {
951 /* We can have memory_read_only set on both images and buffer variables,
952 * but in the former there is a distinction between assignments to
953 * the variable itself (read_only) and to the memory they point to
954 * (memory_read_only), while in the case of buffer variables there is
955 * no such distinction, that is why this check here is limited to
956 * buffer variables alone.
957 */
958 _mesa_glsl_error(&lhs_loc, state,
959 "assignment to read-only variable '%s'",
960 lhs_var->name);
961 error_emitted = true;
962 } else if (lhs->type->is_array() &&
963 !state->check_version(120, 300, &lhs_loc,
964 "whole array assignment forbidden")) {
965 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
966 *
967 * "Other binary or unary expressions, non-dereferenced
968 * arrays, function names, swizzles with repeated fields,
969 * and constants cannot be l-values."
970 *
971 * The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.
972 */
973 error_emitted = true;
974 } else if (!lhs->is_lvalue(state)) {
975 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
976 error_emitted = true;
977 }
978 }
979
980 ir_rvalue *new_rhs =
981 validate_assignment(state, lhs_loc, lhs, rhs, is_initializer);
982 if (new_rhs != NULL) {
983 rhs = new_rhs;
984
985 /* If the LHS array was not declared with a size, it takes it size from
986 * the RHS. If the LHS is an l-value and a whole array, it must be a
987 * dereference of a variable. Any other case would require that the LHS
988 * is either not an l-value or not a whole array.
989 */
990 if (lhs->type->is_unsized_array()) {
991 ir_dereference *const d = lhs->as_dereference();
992
993 assert(d != NULL);
994
995 ir_variable *const var = d->variable_referenced();
996
997 assert(var != NULL);
998
999 if (var->data.max_array_access >= rhs->type->array_size()) {
1000 /* FINISHME: This should actually log the location of the RHS. */
1001 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
1002 "previous access",
1003 var->data.max_array_access);
1004 }
1005
1006 var->type = glsl_type::get_array_instance(lhs->type->fields.array,
1007 rhs->type->array_size());
1008 d->type = var->type;
1009 }
1010 if (lhs->type->is_array()) {
1011 mark_whole_array_access(rhs);
1012 mark_whole_array_access(lhs);
1013 }
1014 } else {
1015 error_emitted = true;
1016 }
1017
1018 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
1019 * but not post_inc) need the converted assigned value as an rvalue
1020 * to handle things like:
1021 *
1022 * i = j += 1;
1023 */
1024 if (needs_rvalue) {
1025 ir_rvalue *rvalue;
1026 if (!error_emitted) {
1027 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
1028 ir_var_temporary);
1029 instructions->push_tail(var);
1030 instructions->push_tail(assign(var, rhs));
1031
1032 ir_dereference_variable *deref_var =
1033 new(ctx) ir_dereference_variable(var);
1034 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));
1035 rvalue = new(ctx) ir_dereference_variable(var);
1036 } else {
1037 rvalue = ir_rvalue::error_value(ctx);
1038 }
1039 *out_rvalue = rvalue;
1040 } else {
1041 if (!error_emitted)
1042 instructions->push_tail(new(ctx) ir_assignment(lhs, rhs));
1043 *out_rvalue = NULL;
1044 }
1045
1046 return error_emitted;
1047 }
1048
1049 static ir_rvalue *
1050 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
1051 {
1052 void *ctx = ralloc_parent(lvalue);
1053 ir_variable *var;
1054
1055 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
1056 ir_var_temporary);
1057 instructions->push_tail(var);
1058
1059 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
1060 lvalue));
1061
1062 return new(ctx) ir_dereference_variable(var);
1063 }
1064
1065
1066 ir_rvalue *
1067 ast_node::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
1068 {
1069 (void) instructions;
1070 (void) state;
1071
1072 return NULL;
1073 }
1074
1075 bool
1076 ast_node::has_sequence_subexpression() const
1077 {
1078 return false;
1079 }
1080
1081 void
1082 ast_node::set_is_lhs(bool /* new_value */)
1083 {
1084 }
1085
1086 void
1087 ast_function_expression::hir_no_rvalue(exec_list *instructions,
1088 struct _mesa_glsl_parse_state *state)
1089 {
1090 (void)hir(instructions, state);
1091 }
1092
1093 void
1094 ast_aggregate_initializer::hir_no_rvalue(exec_list *instructions,
1095 struct _mesa_glsl_parse_state *state)
1096 {
1097 (void)hir(instructions, state);
1098 }
1099
1100 static ir_rvalue *
1101 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
1102 {
1103 int join_op;
1104 ir_rvalue *cmp = NULL;
1105
1106 if (operation == ir_binop_all_equal)
1107 join_op = ir_binop_logic_and;
1108 else
1109 join_op = ir_binop_logic_or;
1110
1111 switch (op0->type->base_type) {
1112 case GLSL_TYPE_FLOAT:
1113 case GLSL_TYPE_FLOAT16:
1114 case GLSL_TYPE_UINT:
1115 case GLSL_TYPE_INT:
1116 case GLSL_TYPE_BOOL:
1117 case GLSL_TYPE_DOUBLE:
1118 case GLSL_TYPE_UINT64:
1119 case GLSL_TYPE_INT64:
1120 case GLSL_TYPE_UINT16:
1121 case GLSL_TYPE_INT16:
1122 case GLSL_TYPE_UINT8:
1123 case GLSL_TYPE_INT8:
1124 return new(mem_ctx) ir_expression(operation, op0, op1);
1125
1126 case GLSL_TYPE_ARRAY: {
1127 for (unsigned int i = 0; i < op0->type->length; i++) {
1128 ir_rvalue *e0, *e1, *result;
1129
1130 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
1131 new(mem_ctx) ir_constant(i));
1132 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
1133 new(mem_ctx) ir_constant(i));
1134 result = do_comparison(mem_ctx, operation, e0, e1);
1135
1136 if (cmp) {
1137 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
1138 } else {
1139 cmp = result;
1140 }
1141 }
1142
1143 mark_whole_array_access(op0);
1144 mark_whole_array_access(op1);
1145 break;
1146 }
1147
1148 case GLSL_TYPE_STRUCT: {
1149 for (unsigned int i = 0; i < op0->type->length; i++) {
1150 ir_rvalue *e0, *e1, *result;
1151 const char *field_name = op0->type->fields.structure[i].name;
1152
1153 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
1154 field_name);
1155 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
1156 field_name);
1157 result = do_comparison(mem_ctx, operation, e0, e1);
1158
1159 if (cmp) {
1160 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
1161 } else {
1162 cmp = result;
1163 }
1164 }
1165 break;
1166 }
1167
1168 case GLSL_TYPE_ERROR:
1169 case GLSL_TYPE_VOID:
1170 case GLSL_TYPE_SAMPLER:
1171 case GLSL_TYPE_IMAGE:
1172 case GLSL_TYPE_INTERFACE:
1173 case GLSL_TYPE_ATOMIC_UINT:
1174 case GLSL_TYPE_SUBROUTINE:
1175 case GLSL_TYPE_FUNCTION:
1176 /* I assume a comparison of a struct containing a sampler just
1177 * ignores the sampler present in the type.
1178 */
1179 break;
1180 }
1181
1182 if (cmp == NULL)
1183 cmp = new(mem_ctx) ir_constant(true);
1184
1185 return cmp;
1186 }
1187
1188 /* For logical operations, we want to ensure that the operands are
1189 * scalar booleans. If it isn't, emit an error and return a constant
1190 * boolean to avoid triggering cascading error messages.
1191 */
1192 static ir_rvalue *
1193 get_scalar_boolean_operand(exec_list *instructions,
1194 struct _mesa_glsl_parse_state *state,
1195 ast_expression *parent_expr,
1196 int operand,
1197 const char *operand_name,
1198 bool *error_emitted)
1199 {
1200 ast_expression *expr = parent_expr->subexpressions[operand];
1201 void *ctx = state;
1202 ir_rvalue *val = expr->hir(instructions, state);
1203
1204 if (val->type->is_boolean() && val->type->is_scalar())
1205 return val;
1206
1207 if (!*error_emitted) {
1208 YYLTYPE loc = expr->get_location();
1209 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
1210 operand_name,
1211 parent_expr->operator_string(parent_expr->oper));
1212 *error_emitted = true;
1213 }
1214
1215 return new(ctx) ir_constant(true);
1216 }
1217
1218 /**
1219 * If name refers to a builtin array whose maximum allowed size is less than
1220 * size, report an error and return true. Otherwise return false.
1221 */
1222 void
1223 check_builtin_array_max_size(const char *name, unsigned size,
1224 YYLTYPE loc, struct _mesa_glsl_parse_state *state)
1225 {
1226 if ((strcmp("gl_TexCoord", name) == 0)
1227 && (size > state->Const.MaxTextureCoords)) {
1228 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
1229 *
1230 * "The size [of gl_TexCoord] can be at most
1231 * gl_MaxTextureCoords."
1232 */
1233 _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
1234 "be larger than gl_MaxTextureCoords (%u)",
1235 state->Const.MaxTextureCoords);
1236 } else if (strcmp("gl_ClipDistance", name) == 0) {
1237 state->clip_dist_size = size;
1238 if (size + state->cull_dist_size > state->Const.MaxClipPlanes) {
1239 /* From section 7.1 (Vertex Shader Special Variables) of the
1240 * GLSL 1.30 spec:
1241 *
1242 * "The gl_ClipDistance array is predeclared as unsized and
1243 * must be sized by the shader either redeclaring it with a
1244 * size or indexing it only with integral constant
1245 * expressions. ... The size can be at most
1246 * gl_MaxClipDistances."
1247 */
1248 _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
1249 "be larger than gl_MaxClipDistances (%u)",
1250 state->Const.MaxClipPlanes);
1251 }
1252 } else if (strcmp("gl_CullDistance", name) == 0) {
1253 state->cull_dist_size = size;
1254 if (size + state->clip_dist_size > state->Const.MaxClipPlanes) {
1255 /* From the ARB_cull_distance spec:
1256 *
1257 * "The gl_CullDistance array is predeclared as unsized and
1258 * must be sized by the shader either redeclaring it with
1259 * a size or indexing it only with integral constant
1260 * expressions. The size determines the number and set of
1261 * enabled cull distances and can be at most
1262 * gl_MaxCullDistances."
1263 */
1264 _mesa_glsl_error(&loc, state, "`gl_CullDistance' array size cannot "
1265 "be larger than gl_MaxCullDistances (%u)",
1266 state->Const.MaxClipPlanes);
1267 }
1268 }
1269 }
1270
1271 /**
1272 * Create the constant 1, of a which is appropriate for incrementing and
1273 * decrementing values of the given GLSL type. For example, if type is vec4,
1274 * this creates a constant value of 1.0 having type float.
1275 *
1276 * If the given type is invalid for increment and decrement operators, return
1277 * a floating point 1--the error will be detected later.
1278 */
1279 static ir_rvalue *
1280 constant_one_for_inc_dec(void *ctx, const glsl_type *type)
1281 {
1282 switch (type->base_type) {
1283 case GLSL_TYPE_UINT:
1284 return new(ctx) ir_constant((unsigned) 1);
1285 case GLSL_TYPE_INT:
1286 return new(ctx) ir_constant(1);
1287 case GLSL_TYPE_UINT64:
1288 return new(ctx) ir_constant((uint64_t) 1);
1289 case GLSL_TYPE_INT64:
1290 return new(ctx) ir_constant((int64_t) 1);
1291 default:
1292 case GLSL_TYPE_FLOAT:
1293 return new(ctx) ir_constant(1.0f);
1294 }
1295 }
1296
1297 ir_rvalue *
1298 ast_expression::hir(exec_list *instructions,
1299 struct _mesa_glsl_parse_state *state)
1300 {
1301 return do_hir(instructions, state, true);
1302 }
1303
1304 void
1305 ast_expression::hir_no_rvalue(exec_list *instructions,
1306 struct _mesa_glsl_parse_state *state)
1307 {
1308 do_hir(instructions, state, false);
1309 }
1310
1311 void
1312 ast_expression::set_is_lhs(bool new_value)
1313 {
1314 /* is_lhs is tracked only to print "variable used uninitialized" warnings,
1315 * if we lack an identifier we can just skip it.
1316 */
1317 if (this->primary_expression.identifier == NULL)
1318 return;
1319
1320 this->is_lhs = new_value;
1321
1322 /* We need to go through the subexpressions tree to cover cases like
1323 * ast_field_selection
1324 */
1325 if (this->subexpressions[0] != NULL)
1326 this->subexpressions[0]->set_is_lhs(new_value);
1327 }
1328
1329 ir_rvalue *
1330 ast_expression::do_hir(exec_list *instructions,
1331 struct _mesa_glsl_parse_state *state,
1332 bool needs_rvalue)
1333 {
1334 void *ctx = state;
1335 static const int operations[AST_NUM_OPERATORS] = {
1336 -1, /* ast_assign doesn't convert to ir_expression. */
1337 -1, /* ast_plus doesn't convert to ir_expression. */
1338 ir_unop_neg,
1339 ir_binop_add,
1340 ir_binop_sub,
1341 ir_binop_mul,
1342 ir_binop_div,
1343 ir_binop_mod,
1344 ir_binop_lshift,
1345 ir_binop_rshift,
1346 ir_binop_less,
1347 ir_binop_less, /* This is correct. See the ast_greater case below. */
1348 ir_binop_gequal, /* This is correct. See the ast_lequal case below. */
1349 ir_binop_gequal,
1350 ir_binop_all_equal,
1351 ir_binop_any_nequal,
1352 ir_binop_bit_and,
1353 ir_binop_bit_xor,
1354 ir_binop_bit_or,
1355 ir_unop_bit_not,
1356 ir_binop_logic_and,
1357 ir_binop_logic_xor,
1358 ir_binop_logic_or,
1359 ir_unop_logic_not,
1360
1361 /* Note: The following block of expression types actually convert
1362 * to multiple IR instructions.
1363 */
1364 ir_binop_mul, /* ast_mul_assign */
1365 ir_binop_div, /* ast_div_assign */
1366 ir_binop_mod, /* ast_mod_assign */
1367 ir_binop_add, /* ast_add_assign */
1368 ir_binop_sub, /* ast_sub_assign */
1369 ir_binop_lshift, /* ast_ls_assign */
1370 ir_binop_rshift, /* ast_rs_assign */
1371 ir_binop_bit_and, /* ast_and_assign */
1372 ir_binop_bit_xor, /* ast_xor_assign */
1373 ir_binop_bit_or, /* ast_or_assign */
1374
1375 -1, /* ast_conditional doesn't convert to ir_expression. */
1376 ir_binop_add, /* ast_pre_inc. */
1377 ir_binop_sub, /* ast_pre_dec. */
1378 ir_binop_add, /* ast_post_inc. */
1379 ir_binop_sub, /* ast_post_dec. */
1380 -1, /* ast_field_selection doesn't conv to ir_expression. */
1381 -1, /* ast_array_index doesn't convert to ir_expression. */
1382 -1, /* ast_function_call doesn't conv to ir_expression. */
1383 -1, /* ast_identifier doesn't convert to ir_expression. */
1384 -1, /* ast_int_constant doesn't convert to ir_expression. */
1385 -1, /* ast_uint_constant doesn't conv to ir_expression. */
1386 -1, /* ast_float_constant doesn't conv to ir_expression. */
1387 -1, /* ast_bool_constant doesn't conv to ir_expression. */
1388 -1, /* ast_sequence doesn't convert to ir_expression. */
1389 -1, /* ast_aggregate shouldn't ever even get here. */
1390 };
1391 ir_rvalue *result = NULL;
1392 ir_rvalue *op[3];
1393 const struct glsl_type *type, *orig_type;
1394 bool error_emitted = false;
1395 YYLTYPE loc;
1396
1397 loc = this->get_location();
1398
1399 switch (this->oper) {
1400 case ast_aggregate:
1401 unreachable("ast_aggregate: Should never get here.");
1402
1403 case ast_assign: {
1404 this->subexpressions[0]->set_is_lhs(true);
1405 op[0] = this->subexpressions[0]->hir(instructions, state);
1406 op[1] = this->subexpressions[1]->hir(instructions, state);
1407
1408 error_emitted =
1409 do_assignment(instructions, state,
1410 this->subexpressions[0]->non_lvalue_description,
1411 op[0], op[1], &result, needs_rvalue, false,
1412 this->subexpressions[0]->get_location());
1413 break;
1414 }
1415
1416 case ast_plus:
1417 op[0] = this->subexpressions[0]->hir(instructions, state);
1418
1419 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1420
1421 error_emitted = type->is_error();
1422
1423 result = op[0];
1424 break;
1425
1426 case ast_neg:
1427 op[0] = this->subexpressions[0]->hir(instructions, state);
1428
1429 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1430
1431 error_emitted = type->is_error();
1432
1433 result = new(ctx) ir_expression(operations[this->oper], type,
1434 op[0], NULL);
1435 break;
1436
1437 case ast_add:
1438 case ast_sub:
1439 case ast_mul:
1440 case ast_div:
1441 op[0] = this->subexpressions[0]->hir(instructions, state);
1442 op[1] = this->subexpressions[1]->hir(instructions, state);
1443
1444 type = arithmetic_result_type(op[0], op[1],
1445 (this->oper == ast_mul),
1446 state, & loc);
1447 error_emitted = type->is_error();
1448
1449 result = new(ctx) ir_expression(operations[this->oper], type,
1450 op[0], op[1]);
1451 break;
1452
1453 case ast_mod:
1454 op[0] = this->subexpressions[0]->hir(instructions, state);
1455 op[1] = this->subexpressions[1]->hir(instructions, state);
1456
1457 type = modulus_result_type(op[0], op[1], state, &loc);
1458
1459 assert(operations[this->oper] == ir_binop_mod);
1460
1461 result = new(ctx) ir_expression(operations[this->oper], type,
1462 op[0], op[1]);
1463 error_emitted = type->is_error();
1464 break;
1465
1466 case ast_lshift:
1467 case ast_rshift:
1468 if (!state->check_bitwise_operations_allowed(&loc)) {
1469 error_emitted = true;
1470 }
1471
1472 op[0] = this->subexpressions[0]->hir(instructions, state);
1473 op[1] = this->subexpressions[1]->hir(instructions, state);
1474 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1475 &loc);
1476 result = new(ctx) ir_expression(operations[this->oper], type,
1477 op[0], op[1]);
1478 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1479 break;
1480
1481 case ast_less:
1482 case ast_greater:
1483 case ast_lequal:
1484 case ast_gequal:
1485 op[0] = this->subexpressions[0]->hir(instructions, state);
1486 op[1] = this->subexpressions[1]->hir(instructions, state);
1487
1488 type = relational_result_type(op[0], op[1], state, & loc);
1489
1490 /* The relational operators must either generate an error or result
1491 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1492 */
1493 assert(type->is_error()
1494 || (type->is_boolean() && type->is_scalar()));
1495
1496 /* Like NIR, GLSL IR does not have opcodes for > or <=. Instead, swap
1497 * the arguments and use < or >=.
1498 */
1499 if (this->oper == ast_greater || this->oper == ast_lequal) {
1500 ir_rvalue *const tmp = op[0];
1501 op[0] = op[1];
1502 op[1] = tmp;
1503 }
1504
1505 result = new(ctx) ir_expression(operations[this->oper], type,
1506 op[0], op[1]);
1507 error_emitted = type->is_error();
1508 break;
1509
1510 case ast_nequal:
1511 case ast_equal:
1512 op[0] = this->subexpressions[0]->hir(instructions, state);
1513 op[1] = this->subexpressions[1]->hir(instructions, state);
1514
1515 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1516 *
1517 * "The equality operators equal (==), and not equal (!=)
1518 * operate on all types. They result in a scalar Boolean. If
1519 * the operand types do not match, then there must be a
1520 * conversion from Section 4.1.10 "Implicit Conversions"
1521 * applied to one operand that can make them match, in which
1522 * case this conversion is done."
1523 */
1524
1525 if (op[0]->type == glsl_type::void_type || op[1]->type == glsl_type::void_type) {
1526 _mesa_glsl_error(& loc, state, "`%s': wrong operand types: "
1527 "no operation `%1$s' exists that takes a left-hand "
1528 "operand of type 'void' or a right operand of type "
1529 "'void'", (this->oper == ast_equal) ? "==" : "!=");
1530 error_emitted = true;
1531 } else if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1532 && !apply_implicit_conversion(op[1]->type, op[0], state))
1533 || (op[0]->type != op[1]->type)) {
1534 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1535 "type", (this->oper == ast_equal) ? "==" : "!=");
1536 error_emitted = true;
1537 } else if ((op[0]->type->is_array() || op[1]->type->is_array()) &&
1538 !state->check_version(120, 300, &loc,
1539 "array comparisons forbidden")) {
1540 error_emitted = true;
1541 } else if ((op[0]->type->contains_subroutine() ||
1542 op[1]->type->contains_subroutine())) {
1543 _mesa_glsl_error(&loc, state, "subroutine comparisons forbidden");
1544 error_emitted = true;
1545 } else if ((op[0]->type->contains_opaque() ||
1546 op[1]->type->contains_opaque())) {
1547 _mesa_glsl_error(&loc, state, "opaque type comparisons forbidden");
1548 error_emitted = true;
1549 }
1550
1551 if (error_emitted) {
1552 result = new(ctx) ir_constant(false);
1553 } else {
1554 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1555 assert(result->type == glsl_type::bool_type);
1556 }
1557 break;
1558
1559 case ast_bit_and:
1560 case ast_bit_xor:
1561 case ast_bit_or:
1562 op[0] = this->subexpressions[0]->hir(instructions, state);
1563 op[1] = this->subexpressions[1]->hir(instructions, state);
1564 type = bit_logic_result_type(op[0], op[1], this->oper, state, &loc);
1565 result = new(ctx) ir_expression(operations[this->oper], type,
1566 op[0], op[1]);
1567 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1568 break;
1569
1570 case ast_bit_not:
1571 op[0] = this->subexpressions[0]->hir(instructions, state);
1572
1573 if (!state->check_bitwise_operations_allowed(&loc)) {
1574 error_emitted = true;
1575 }
1576
1577 if (!op[0]->type->is_integer_32_64()) {
1578 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1579 error_emitted = true;
1580 }
1581
1582 type = error_emitted ? glsl_type::error_type : op[0]->type;
1583 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1584 break;
1585
1586 case ast_logic_and: {
1587 exec_list rhs_instructions;
1588 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1589 "LHS", &error_emitted);
1590 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1591 "RHS", &error_emitted);
1592
1593 if (rhs_instructions.is_empty()) {
1594 result = new(ctx) ir_expression(ir_binop_logic_and, op[0], op[1]);
1595 } else {
1596 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1597 "and_tmp",
1598 ir_var_temporary);
1599 instructions->push_tail(tmp);
1600
1601 ir_if *const stmt = new(ctx) ir_if(op[0]);
1602 instructions->push_tail(stmt);
1603
1604 stmt->then_instructions.append_list(&rhs_instructions);
1605 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1606 ir_assignment *const then_assign =
1607 new(ctx) ir_assignment(then_deref, op[1]);
1608 stmt->then_instructions.push_tail(then_assign);
1609
1610 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1611 ir_assignment *const else_assign =
1612 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false));
1613 stmt->else_instructions.push_tail(else_assign);
1614
1615 result = new(ctx) ir_dereference_variable(tmp);
1616 }
1617 break;
1618 }
1619
1620 case ast_logic_or: {
1621 exec_list rhs_instructions;
1622 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1623 "LHS", &error_emitted);
1624 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1625 "RHS", &error_emitted);
1626
1627 if (rhs_instructions.is_empty()) {
1628 result = new(ctx) ir_expression(ir_binop_logic_or, op[0], op[1]);
1629 } else {
1630 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1631 "or_tmp",
1632 ir_var_temporary);
1633 instructions->push_tail(tmp);
1634
1635 ir_if *const stmt = new(ctx) ir_if(op[0]);
1636 instructions->push_tail(stmt);
1637
1638 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1639 ir_assignment *const then_assign =
1640 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true));
1641 stmt->then_instructions.push_tail(then_assign);
1642
1643 stmt->else_instructions.append_list(&rhs_instructions);
1644 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1645 ir_assignment *const else_assign =
1646 new(ctx) ir_assignment(else_deref, op[1]);
1647 stmt->else_instructions.push_tail(else_assign);
1648
1649 result = new(ctx) ir_dereference_variable(tmp);
1650 }
1651 break;
1652 }
1653
1654 case ast_logic_xor:
1655 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1656 *
1657 * "The logical binary operators and (&&), or ( | | ), and
1658 * exclusive or (^^). They operate only on two Boolean
1659 * expressions and result in a Boolean expression."
1660 */
1661 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1662 &error_emitted);
1663 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1664 &error_emitted);
1665
1666 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1667 op[0], op[1]);
1668 break;
1669
1670 case ast_logic_not:
1671 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1672 "operand", &error_emitted);
1673
1674 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1675 op[0], NULL);
1676 break;
1677
1678 case ast_mul_assign:
1679 case ast_div_assign:
1680 case ast_add_assign:
1681 case ast_sub_assign: {
1682 this->subexpressions[0]->set_is_lhs(true);
1683 op[0] = this->subexpressions[0]->hir(instructions, state);
1684 op[1] = this->subexpressions[1]->hir(instructions, state);
1685
1686 orig_type = op[0]->type;
1687
1688 /* Break out if operand types were not parsed successfully. */
1689 if ((op[0]->type == glsl_type::error_type ||
1690 op[1]->type == glsl_type::error_type))
1691 break;
1692
1693 type = arithmetic_result_type(op[0], op[1],
1694 (this->oper == ast_mul_assign),
1695 state, & loc);
1696
1697 if (type != orig_type) {
1698 _mesa_glsl_error(& loc, state,
1699 "could not implicitly convert "
1700 "%s to %s", type->name, orig_type->name);
1701 type = glsl_type::error_type;
1702 }
1703
1704 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1705 op[0], op[1]);
1706
1707 error_emitted =
1708 do_assignment(instructions, state,
1709 this->subexpressions[0]->non_lvalue_description,
1710 op[0]->clone(ctx, NULL), temp_rhs,
1711 &result, needs_rvalue, false,
1712 this->subexpressions[0]->get_location());
1713
1714 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1715 * explicitly test for this because none of the binary expression
1716 * operators allow array operands either.
1717 */
1718
1719 break;
1720 }
1721
1722 case ast_mod_assign: {
1723 this->subexpressions[0]->set_is_lhs(true);
1724 op[0] = this->subexpressions[0]->hir(instructions, state);
1725 op[1] = this->subexpressions[1]->hir(instructions, state);
1726
1727 orig_type = op[0]->type;
1728 type = modulus_result_type(op[0], op[1], state, &loc);
1729
1730 if (type != orig_type) {
1731 _mesa_glsl_error(& loc, state,
1732 "could not implicitly convert "
1733 "%s to %s", type->name, orig_type->name);
1734 type = glsl_type::error_type;
1735 }
1736
1737 assert(operations[this->oper] == ir_binop_mod);
1738
1739 ir_rvalue *temp_rhs;
1740 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1741 op[0], op[1]);
1742
1743 error_emitted =
1744 do_assignment(instructions, state,
1745 this->subexpressions[0]->non_lvalue_description,
1746 op[0]->clone(ctx, NULL), temp_rhs,
1747 &result, needs_rvalue, false,
1748 this->subexpressions[0]->get_location());
1749 break;
1750 }
1751
1752 case ast_ls_assign:
1753 case ast_rs_assign: {
1754 this->subexpressions[0]->set_is_lhs(true);
1755 op[0] = this->subexpressions[0]->hir(instructions, state);
1756 op[1] = this->subexpressions[1]->hir(instructions, state);
1757 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1758 &loc);
1759 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1760 type, op[0], op[1]);
1761 error_emitted =
1762 do_assignment(instructions, state,
1763 this->subexpressions[0]->non_lvalue_description,
1764 op[0]->clone(ctx, NULL), temp_rhs,
1765 &result, needs_rvalue, false,
1766 this->subexpressions[0]->get_location());
1767 break;
1768 }
1769
1770 case ast_and_assign:
1771 case ast_xor_assign:
1772 case ast_or_assign: {
1773 this->subexpressions[0]->set_is_lhs(true);
1774 op[0] = this->subexpressions[0]->hir(instructions, state);
1775 op[1] = this->subexpressions[1]->hir(instructions, state);
1776
1777 orig_type = op[0]->type;
1778 type = bit_logic_result_type(op[0], op[1], this->oper, state, &loc);
1779
1780 if (type != orig_type) {
1781 _mesa_glsl_error(& loc, state,
1782 "could not implicitly convert "
1783 "%s to %s", type->name, orig_type->name);
1784 type = glsl_type::error_type;
1785 }
1786
1787 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1788 type, op[0], op[1]);
1789 error_emitted =
1790 do_assignment(instructions, state,
1791 this->subexpressions[0]->non_lvalue_description,
1792 op[0]->clone(ctx, NULL), temp_rhs,
1793 &result, needs_rvalue, false,
1794 this->subexpressions[0]->get_location());
1795 break;
1796 }
1797
1798 case ast_conditional: {
1799 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1800 *
1801 * "The ternary selection operator (?:). It operates on three
1802 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1803 * first expression, which must result in a scalar Boolean."
1804 */
1805 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1806 "condition", &error_emitted);
1807
1808 /* The :? operator is implemented by generating an anonymous temporary
1809 * followed by an if-statement. The last instruction in each branch of
1810 * the if-statement assigns a value to the anonymous temporary. This
1811 * temporary is the r-value of the expression.
1812 */
1813 exec_list then_instructions;
1814 exec_list else_instructions;
1815
1816 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1817 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1818
1819 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1820 *
1821 * "The second and third expressions can be any type, as
1822 * long their types match, or there is a conversion in
1823 * Section 4.1.10 "Implicit Conversions" that can be applied
1824 * to one of the expressions to make their types match. This
1825 * resulting matching type is the type of the entire
1826 * expression."
1827 */
1828 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1829 && !apply_implicit_conversion(op[2]->type, op[1], state))
1830 || (op[1]->type != op[2]->type)) {
1831 YYLTYPE loc = this->subexpressions[1]->get_location();
1832
1833 _mesa_glsl_error(& loc, state, "second and third operands of ?: "
1834 "operator must have matching types");
1835 error_emitted = true;
1836 type = glsl_type::error_type;
1837 } else {
1838 type = op[1]->type;
1839 }
1840
1841 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1842 *
1843 * "The second and third expressions must be the same type, but can
1844 * be of any type other than an array."
1845 */
1846 if (type->is_array() &&
1847 !state->check_version(120, 300, &loc,
1848 "second and third operands of ?: operator "
1849 "cannot be arrays")) {
1850 error_emitted = true;
1851 }
1852
1853 /* From section 4.1.7 of the GLSL 4.50 spec (Opaque Types):
1854 *
1855 * "Except for array indexing, structure member selection, and
1856 * parentheses, opaque variables are not allowed to be operands in
1857 * expressions; such use results in a compile-time error."
1858 */
1859 if (type->contains_opaque()) {
1860 if (!(state->has_bindless() && (type->is_image() || type->is_sampler()))) {
1861 _mesa_glsl_error(&loc, state, "variables of type %s cannot be "
1862 "operands of the ?: operator", type->name);
1863 error_emitted = true;
1864 }
1865 }
1866
1867 ir_constant *cond_val = op[0]->constant_expression_value(ctx);
1868
1869 if (then_instructions.is_empty()
1870 && else_instructions.is_empty()
1871 && cond_val != NULL) {
1872 result = cond_val->value.b[0] ? op[1] : op[2];
1873 } else {
1874 /* The copy to conditional_tmp reads the whole array. */
1875 if (type->is_array()) {
1876 mark_whole_array_access(op[1]);
1877 mark_whole_array_access(op[2]);
1878 }
1879
1880 ir_variable *const tmp =
1881 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1882 instructions->push_tail(tmp);
1883
1884 ir_if *const stmt = new(ctx) ir_if(op[0]);
1885 instructions->push_tail(stmt);
1886
1887 then_instructions.move_nodes_to(& stmt->then_instructions);
1888 ir_dereference *const then_deref =
1889 new(ctx) ir_dereference_variable(tmp);
1890 ir_assignment *const then_assign =
1891 new(ctx) ir_assignment(then_deref, op[1]);
1892 stmt->then_instructions.push_tail(then_assign);
1893
1894 else_instructions.move_nodes_to(& stmt->else_instructions);
1895 ir_dereference *const else_deref =
1896 new(ctx) ir_dereference_variable(tmp);
1897 ir_assignment *const else_assign =
1898 new(ctx) ir_assignment(else_deref, op[2]);
1899 stmt->else_instructions.push_tail(else_assign);
1900
1901 result = new(ctx) ir_dereference_variable(tmp);
1902 }
1903 break;
1904 }
1905
1906 case ast_pre_inc:
1907 case ast_pre_dec: {
1908 this->non_lvalue_description = (this->oper == ast_pre_inc)
1909 ? "pre-increment operation" : "pre-decrement operation";
1910
1911 op[0] = this->subexpressions[0]->hir(instructions, state);
1912 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1913
1914 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1915
1916 ir_rvalue *temp_rhs;
1917 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1918 op[0], op[1]);
1919
1920 error_emitted =
1921 do_assignment(instructions, state,
1922 this->subexpressions[0]->non_lvalue_description,
1923 op[0]->clone(ctx, NULL), temp_rhs,
1924 &result, needs_rvalue, false,
1925 this->subexpressions[0]->get_location());
1926 break;
1927 }
1928
1929 case ast_post_inc:
1930 case ast_post_dec: {
1931 this->non_lvalue_description = (this->oper == ast_post_inc)
1932 ? "post-increment operation" : "post-decrement operation";
1933 op[0] = this->subexpressions[0]->hir(instructions, state);
1934 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1935
1936 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1937
1938 if (error_emitted) {
1939 result = ir_rvalue::error_value(ctx);
1940 break;
1941 }
1942
1943 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1944
1945 ir_rvalue *temp_rhs;
1946 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1947 op[0], op[1]);
1948
1949 /* Get a temporary of a copy of the lvalue before it's modified.
1950 * This may get thrown away later.
1951 */
1952 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1953
1954 ir_rvalue *junk_rvalue;
1955 error_emitted =
1956 do_assignment(instructions, state,
1957 this->subexpressions[0]->non_lvalue_description,
1958 op[0]->clone(ctx, NULL), temp_rhs,
1959 &junk_rvalue, false, false,
1960 this->subexpressions[0]->get_location());
1961
1962 break;
1963 }
1964
1965 case ast_field_selection:
1966 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1967 break;
1968
1969 case ast_array_index: {
1970 YYLTYPE index_loc = subexpressions[1]->get_location();
1971
1972 /* Getting if an array is being used uninitialized is beyond what we get
1973 * from ir_value.data.assigned. Setting is_lhs as true would force to
1974 * not raise a uninitialized warning when using an array
1975 */
1976 subexpressions[0]->set_is_lhs(true);
1977 op[0] = subexpressions[0]->hir(instructions, state);
1978 op[1] = subexpressions[1]->hir(instructions, state);
1979
1980 result = _mesa_ast_array_index_to_hir(ctx, state, op[0], op[1],
1981 loc, index_loc);
1982
1983 if (result->type->is_error())
1984 error_emitted = true;
1985
1986 break;
1987 }
1988
1989 case ast_unsized_array_dim:
1990 unreachable("ast_unsized_array_dim: Should never get here.");
1991
1992 case ast_function_call:
1993 /* Should *NEVER* get here. ast_function_call should always be handled
1994 * by ast_function_expression::hir.
1995 */
1996 unreachable("ast_function_call: handled elsewhere ");
1997
1998 case ast_identifier: {
1999 /* ast_identifier can appear several places in a full abstract syntax
2000 * tree. This particular use must be at location specified in the grammar
2001 * as 'variable_identifier'.
2002 */
2003 ir_variable *var =
2004 state->symbols->get_variable(this->primary_expression.identifier);
2005
2006 if (var == NULL) {
2007 /* the identifier might be a subroutine name */
2008 char *sub_name;
2009 sub_name = ralloc_asprintf(ctx, "%s_%s", _mesa_shader_stage_to_subroutine_prefix(state->stage), this->primary_expression.identifier);
2010 var = state->symbols->get_variable(sub_name);
2011 ralloc_free(sub_name);
2012 }
2013
2014 if (var != NULL) {
2015 var->data.used = true;
2016 result = new(ctx) ir_dereference_variable(var);
2017
2018 if ((var->data.mode == ir_var_auto || var->data.mode == ir_var_shader_out)
2019 && !this->is_lhs
2020 && result->variable_referenced()->data.assigned != true
2021 && !is_gl_identifier(var->name)) {
2022 _mesa_glsl_warning(&loc, state, "`%s' used uninitialized",
2023 this->primary_expression.identifier);
2024 }
2025
2026 /* From the EXT_shader_framebuffer_fetch spec:
2027 *
2028 * "Unless the GL_EXT_shader_framebuffer_fetch extension has been
2029 * enabled in addition, it's an error to use gl_LastFragData if it
2030 * hasn't been explicitly redeclared with layout(noncoherent)."
2031 */
2032 if (var->data.fb_fetch_output && var->data.memory_coherent &&
2033 !state->EXT_shader_framebuffer_fetch_enable) {
2034 _mesa_glsl_error(&loc, state,
2035 "invalid use of framebuffer fetch output not "
2036 "qualified with layout(noncoherent)");
2037 }
2038
2039 } else {
2040 _mesa_glsl_error(& loc, state, "`%s' undeclared",
2041 this->primary_expression.identifier);
2042
2043 result = ir_rvalue::error_value(ctx);
2044 error_emitted = true;
2045 }
2046 break;
2047 }
2048
2049 case ast_int_constant:
2050 result = new(ctx) ir_constant(this->primary_expression.int_constant);
2051 break;
2052
2053 case ast_uint_constant:
2054 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
2055 break;
2056
2057 case ast_float_constant:
2058 result = new(ctx) ir_constant(this->primary_expression.float_constant);
2059 break;
2060
2061 case ast_bool_constant:
2062 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
2063 break;
2064
2065 case ast_double_constant:
2066 result = new(ctx) ir_constant(this->primary_expression.double_constant);
2067 break;
2068
2069 case ast_uint64_constant:
2070 result = new(ctx) ir_constant(this->primary_expression.uint64_constant);
2071 break;
2072
2073 case ast_int64_constant:
2074 result = new(ctx) ir_constant(this->primary_expression.int64_constant);
2075 break;
2076
2077 case ast_sequence: {
2078 /* It should not be possible to generate a sequence in the AST without
2079 * any expressions in it.
2080 */
2081 assert(!this->expressions.is_empty());
2082
2083 /* The r-value of a sequence is the last expression in the sequence. If
2084 * the other expressions in the sequence do not have side-effects (and
2085 * therefore add instructions to the instruction list), they get dropped
2086 * on the floor.
2087 */
2088 exec_node *previous_tail = NULL;
2089 YYLTYPE previous_operand_loc = loc;
2090
2091 foreach_list_typed (ast_node, ast, link, &this->expressions) {
2092 /* If one of the operands of comma operator does not generate any
2093 * code, we want to emit a warning. At each pass through the loop
2094 * previous_tail will point to the last instruction in the stream
2095 * *before* processing the previous operand. Naturally,
2096 * instructions->get_tail_raw() will point to the last instruction in
2097 * the stream *after* processing the previous operand. If the two
2098 * pointers match, then the previous operand had no effect.
2099 *
2100 * The warning behavior here differs slightly from GCC. GCC will
2101 * only emit a warning if none of the left-hand operands have an
2102 * effect. However, it will emit a warning for each. I believe that
2103 * there are some cases in C (especially with GCC extensions) where
2104 * it is useful to have an intermediate step in a sequence have no
2105 * effect, but I don't think these cases exist in GLSL. Either way,
2106 * it would be a giant hassle to replicate that behavior.
2107 */
2108 if (previous_tail == instructions->get_tail_raw()) {
2109 _mesa_glsl_warning(&previous_operand_loc, state,
2110 "left-hand operand of comma expression has "
2111 "no effect");
2112 }
2113
2114 /* The tail is directly accessed instead of using the get_tail()
2115 * method for performance reasons. get_tail() has extra code to
2116 * return NULL when the list is empty. We don't care about that
2117 * here, so using get_tail_raw() is fine.
2118 */
2119 previous_tail = instructions->get_tail_raw();
2120 previous_operand_loc = ast->get_location();
2121
2122 result = ast->hir(instructions, state);
2123 }
2124
2125 /* Any errors should have already been emitted in the loop above.
2126 */
2127 error_emitted = true;
2128 break;
2129 }
2130 }
2131 type = NULL; /* use result->type, not type. */
2132 assert(result != NULL || !needs_rvalue);
2133
2134 if (result && result->type->is_error() && !error_emitted)
2135 _mesa_glsl_error(& loc, state, "type mismatch");
2136
2137 return result;
2138 }
2139
2140 bool
2141 ast_expression::has_sequence_subexpression() const
2142 {
2143 switch (this->oper) {
2144 case ast_plus:
2145 case ast_neg:
2146 case ast_bit_not:
2147 case ast_logic_not:
2148 case ast_pre_inc:
2149 case ast_pre_dec:
2150 case ast_post_inc:
2151 case ast_post_dec:
2152 return this->subexpressions[0]->has_sequence_subexpression();
2153
2154 case ast_assign:
2155 case ast_add:
2156 case ast_sub:
2157 case ast_mul:
2158 case ast_div:
2159 case ast_mod:
2160 case ast_lshift:
2161 case ast_rshift:
2162 case ast_less:
2163 case ast_greater:
2164 case ast_lequal:
2165 case ast_gequal:
2166 case ast_nequal:
2167 case ast_equal:
2168 case ast_bit_and:
2169 case ast_bit_xor:
2170 case ast_bit_or:
2171 case ast_logic_and:
2172 case ast_logic_or:
2173 case ast_logic_xor:
2174 case ast_array_index:
2175 case ast_mul_assign:
2176 case ast_div_assign:
2177 case ast_add_assign:
2178 case ast_sub_assign:
2179 case ast_mod_assign:
2180 case ast_ls_assign:
2181 case ast_rs_assign:
2182 case ast_and_assign:
2183 case ast_xor_assign:
2184 case ast_or_assign:
2185 return this->subexpressions[0]->has_sequence_subexpression() ||
2186 this->subexpressions[1]->has_sequence_subexpression();
2187
2188 case ast_conditional:
2189 return this->subexpressions[0]->has_sequence_subexpression() ||
2190 this->subexpressions[1]->has_sequence_subexpression() ||
2191 this->subexpressions[2]->has_sequence_subexpression();
2192
2193 case ast_sequence:
2194 return true;
2195
2196 case ast_field_selection:
2197 case ast_identifier:
2198 case ast_int_constant:
2199 case ast_uint_constant:
2200 case ast_float_constant:
2201 case ast_bool_constant:
2202 case ast_double_constant:
2203 case ast_int64_constant:
2204 case ast_uint64_constant:
2205 return false;
2206
2207 case ast_aggregate:
2208 return false;
2209
2210 case ast_function_call:
2211 unreachable("should be handled by ast_function_expression::hir");
2212
2213 case ast_unsized_array_dim:
2214 unreachable("ast_unsized_array_dim: Should never get here.");
2215 }
2216
2217 return false;
2218 }
2219
2220 ir_rvalue *
2221 ast_expression_statement::hir(exec_list *instructions,
2222 struct _mesa_glsl_parse_state *state)
2223 {
2224 /* It is possible to have expression statements that don't have an
2225 * expression. This is the solitary semicolon:
2226 *
2227 * for (i = 0; i < 5; i++)
2228 * ;
2229 *
2230 * In this case the expression will be NULL. Test for NULL and don't do
2231 * anything in that case.
2232 */
2233 if (expression != NULL)
2234 expression->hir_no_rvalue(instructions, state);
2235
2236 /* Statements do not have r-values.
2237 */
2238 return NULL;
2239 }
2240
2241
2242 ir_rvalue *
2243 ast_compound_statement::hir(exec_list *instructions,
2244 struct _mesa_glsl_parse_state *state)
2245 {
2246 if (new_scope)
2247 state->symbols->push_scope();
2248
2249 foreach_list_typed (ast_node, ast, link, &this->statements)
2250 ast->hir(instructions, state);
2251
2252 if (new_scope)
2253 state->symbols->pop_scope();
2254
2255 /* Compound statements do not have r-values.
2256 */
2257 return NULL;
2258 }
2259
2260 /**
2261 * Evaluate the given exec_node (which should be an ast_node representing
2262 * a single array dimension) and return its integer value.
2263 */
2264 static unsigned
2265 process_array_size(exec_node *node,
2266 struct _mesa_glsl_parse_state *state)
2267 {
2268 void *mem_ctx = state;
2269
2270 exec_list dummy_instructions;
2271
2272 ast_node *array_size = exec_node_data(ast_node, node, link);
2273
2274 /**
2275 * Dimensions other than the outermost dimension can by unsized if they
2276 * are immediately sized by a constructor or initializer.
2277 */
2278 if (((ast_expression*)array_size)->oper == ast_unsized_array_dim)
2279 return 0;
2280
2281 ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
2282 YYLTYPE loc = array_size->get_location();
2283
2284 if (ir == NULL) {
2285 _mesa_glsl_error(& loc, state,
2286 "array size could not be resolved");
2287 return 0;
2288 }
2289
2290 if (!ir->type->is_integer()) {
2291 _mesa_glsl_error(& loc, state,
2292 "array size must be integer type");
2293 return 0;
2294 }
2295
2296 if (!ir->type->is_scalar()) {
2297 _mesa_glsl_error(& loc, state,
2298 "array size must be scalar type");
2299 return 0;
2300 }
2301
2302 ir_constant *const size = ir->constant_expression_value(mem_ctx);
2303 if (size == NULL ||
2304 (state->is_version(120, 300) &&
2305 array_size->has_sequence_subexpression())) {
2306 _mesa_glsl_error(& loc, state, "array size must be a "
2307 "constant valued expression");
2308 return 0;
2309 }
2310
2311 if (size->value.i[0] <= 0) {
2312 _mesa_glsl_error(& loc, state, "array size must be > 0");
2313 return 0;
2314 }
2315
2316 assert(size->type == ir->type);
2317
2318 /* If the array size is const (and we've verified that
2319 * it is) then no instructions should have been emitted
2320 * when we converted it to HIR. If they were emitted,
2321 * then either the array size isn't const after all, or
2322 * we are emitting unnecessary instructions.
2323 */
2324 assert(dummy_instructions.is_empty());
2325
2326 return size->value.u[0];
2327 }
2328
2329 static const glsl_type *
2330 process_array_type(YYLTYPE *loc, const glsl_type *base,
2331 ast_array_specifier *array_specifier,
2332 struct _mesa_glsl_parse_state *state)
2333 {
2334 const glsl_type *array_type = base;
2335
2336 if (array_specifier != NULL) {
2337 if (base->is_array()) {
2338
2339 /* From page 19 (page 25) of the GLSL 1.20 spec:
2340 *
2341 * "Only one-dimensional arrays may be declared."
2342 */
2343 if (!state->check_arrays_of_arrays_allowed(loc)) {
2344 return glsl_type::error_type;
2345 }
2346 }
2347
2348 for (exec_node *node = array_specifier->array_dimensions.get_tail_raw();
2349 !node->is_head_sentinel(); node = node->prev) {
2350 unsigned array_size = process_array_size(node, state);
2351 array_type = glsl_type::get_array_instance(array_type, array_size);
2352 }
2353 }
2354
2355 return array_type;
2356 }
2357
2358 static bool
2359 precision_qualifier_allowed(const glsl_type *type)
2360 {
2361 /* Precision qualifiers apply to floating point, integer and opaque
2362 * types.
2363 *
2364 * Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:
2365 * "Any floating point or any integer declaration can have the type
2366 * preceded by one of these precision qualifiers [...] Literal
2367 * constants do not have precision qualifiers. Neither do Boolean
2368 * variables.
2369 *
2370 * Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.30
2371 * spec also says:
2372 *
2373 * "Precision qualifiers are added for code portability with OpenGL
2374 * ES, not for functionality. They have the same syntax as in OpenGL
2375 * ES."
2376 *
2377 * Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:
2378 *
2379 * "uniform lowp sampler2D sampler;
2380 * highp vec2 coord;
2381 * ...
2382 * lowp vec4 col = texture2D (sampler, coord);
2383 * // texture2D returns lowp"
2384 *
2385 * From this, we infer that GLSL 1.30 (and later) should allow precision
2386 * qualifiers on sampler types just like float and integer types.
2387 */
2388 const glsl_type *const t = type->without_array();
2389
2390 return (t->is_float() || t->is_integer() || t->contains_opaque()) &&
2391 !t->is_record();
2392 }
2393
2394 const glsl_type *
2395 ast_type_specifier::glsl_type(const char **name,
2396 struct _mesa_glsl_parse_state *state) const
2397 {
2398 const struct glsl_type *type;
2399
2400 if (this->type != NULL)
2401 type = this->type;
2402 else if (structure)
2403 type = structure->type;
2404 else
2405 type = state->symbols->get_type(this->type_name);
2406 *name = this->type_name;
2407
2408 YYLTYPE loc = this->get_location();
2409 type = process_array_type(&loc, type, this->array_specifier, state);
2410
2411 return type;
2412 }
2413
2414 /**
2415 * From the OpenGL ES 3.0 spec, 4.5.4 Default Precision Qualifiers:
2416 *
2417 * "The precision statement
2418 *
2419 * precision precision-qualifier type;
2420 *
2421 * can be used to establish a default precision qualifier. The type field can
2422 * be either int or float or any of the sampler types, (...) If type is float,
2423 * the directive applies to non-precision-qualified floating point type
2424 * (scalar, vector, and matrix) declarations. If type is int, the directive
2425 * applies to all non-precision-qualified integer type (scalar, vector, signed,
2426 * and unsigned) declarations."
2427 *
2428 * We use the symbol table to keep the values of the default precisions for
2429 * each 'type' in each scope and we use the 'type' string from the precision
2430 * statement as key in the symbol table. When we want to retrieve the default
2431 * precision associated with a given glsl_type we need to know the type string
2432 * associated with it. This is what this function returns.
2433 */
2434 static const char *
2435 get_type_name_for_precision_qualifier(const glsl_type *type)
2436 {
2437 switch (type->base_type) {
2438 case GLSL_TYPE_FLOAT:
2439 return "float";
2440 case GLSL_TYPE_UINT:
2441 case GLSL_TYPE_INT:
2442 return "int";
2443 case GLSL_TYPE_ATOMIC_UINT:
2444 return "atomic_uint";
2445 case GLSL_TYPE_IMAGE:
2446 /* fallthrough */
2447 case GLSL_TYPE_SAMPLER: {
2448 const unsigned type_idx =
2449 type->sampler_array + 2 * type->sampler_shadow;
2450 const unsigned offset = type->is_sampler() ? 0 : 4;
2451 assert(type_idx < 4);
2452 switch (type->sampled_type) {
2453 case GLSL_TYPE_FLOAT:
2454 switch (type->sampler_dimensionality) {
2455 case GLSL_SAMPLER_DIM_1D: {
2456 assert(type->is_sampler());
2457 static const char *const names[4] = {
2458 "sampler1D", "sampler1DArray",
2459 "sampler1DShadow", "sampler1DArrayShadow"
2460 };
2461 return names[type_idx];
2462 }
2463 case GLSL_SAMPLER_DIM_2D: {
2464 static const char *const names[8] = {
2465 "sampler2D", "sampler2DArray",
2466 "sampler2DShadow", "sampler2DArrayShadow",
2467 "image2D", "image2DArray", NULL, NULL
2468 };
2469 return names[offset + type_idx];
2470 }
2471 case GLSL_SAMPLER_DIM_3D: {
2472 static const char *const names[8] = {
2473 "sampler3D", NULL, NULL, NULL,
2474 "image3D", NULL, NULL, NULL
2475 };
2476 return names[offset + type_idx];
2477 }
2478 case GLSL_SAMPLER_DIM_CUBE: {
2479 static const char *const names[8] = {
2480 "samplerCube", "samplerCubeArray",
2481 "samplerCubeShadow", "samplerCubeArrayShadow",
2482 "imageCube", NULL, NULL, NULL
2483 };
2484 return names[offset + type_idx];
2485 }
2486 case GLSL_SAMPLER_DIM_MS: {
2487 assert(type->is_sampler());
2488 static const char *const names[4] = {
2489 "sampler2DMS", "sampler2DMSArray", NULL, NULL
2490 };
2491 return names[type_idx];
2492 }
2493 case GLSL_SAMPLER_DIM_RECT: {
2494 assert(type->is_sampler());
2495 static const char *const names[4] = {
2496 "samplerRect", NULL, "samplerRectShadow", NULL
2497 };
2498 return names[type_idx];
2499 }
2500 case GLSL_SAMPLER_DIM_BUF: {
2501 static const char *const names[8] = {
2502 "samplerBuffer", NULL, NULL, NULL,
2503 "imageBuffer", NULL, NULL, NULL
2504 };
2505 return names[offset + type_idx];
2506 }
2507 case GLSL_SAMPLER_DIM_EXTERNAL: {
2508 assert(type->is_sampler());
2509 static const char *const names[4] = {
2510 "samplerExternalOES", NULL, NULL, NULL
2511 };
2512 return names[type_idx];
2513 }
2514 default:
2515 unreachable("Unsupported sampler/image dimensionality");
2516 } /* sampler/image float dimensionality */
2517 break;
2518 case GLSL_TYPE_INT:
2519 switch (type->sampler_dimensionality) {
2520 case GLSL_SAMPLER_DIM_1D: {
2521 assert(type->is_sampler());
2522 static const char *const names[4] = {
2523 "isampler1D", "isampler1DArray", NULL, NULL
2524 };
2525 return names[type_idx];
2526 }
2527 case GLSL_SAMPLER_DIM_2D: {
2528 static const char *const names[8] = {
2529 "isampler2D", "isampler2DArray", NULL, NULL,
2530 "iimage2D", "iimage2DArray", NULL, NULL
2531 };
2532 return names[offset + type_idx];
2533 }
2534 case GLSL_SAMPLER_DIM_3D: {
2535 static const char *const names[8] = {
2536 "isampler3D", NULL, NULL, NULL,
2537 "iimage3D", NULL, NULL, NULL
2538 };
2539 return names[offset + type_idx];
2540 }
2541 case GLSL_SAMPLER_DIM_CUBE: {
2542 static const char *const names[8] = {
2543 "isamplerCube", "isamplerCubeArray", NULL, NULL,
2544 "iimageCube", NULL, NULL, NULL
2545 };
2546 return names[offset + type_idx];
2547 }
2548 case GLSL_SAMPLER_DIM_MS: {
2549 assert(type->is_sampler());
2550 static const char *const names[4] = {
2551 "isampler2DMS", "isampler2DMSArray", NULL, NULL
2552 };
2553 return names[type_idx];
2554 }
2555 case GLSL_SAMPLER_DIM_RECT: {
2556 assert(type->is_sampler());
2557 static const char *const names[4] = {
2558 "isamplerRect", NULL, "isamplerRectShadow", NULL
2559 };
2560 return names[type_idx];
2561 }
2562 case GLSL_SAMPLER_DIM_BUF: {
2563 static const char *const names[8] = {
2564 "isamplerBuffer", NULL, NULL, NULL,
2565 "iimageBuffer", NULL, NULL, NULL
2566 };
2567 return names[offset + type_idx];
2568 }
2569 default:
2570 unreachable("Unsupported isampler/iimage dimensionality");
2571 } /* sampler/image int dimensionality */
2572 break;
2573 case GLSL_TYPE_UINT:
2574 switch (type->sampler_dimensionality) {
2575 case GLSL_SAMPLER_DIM_1D: {
2576 assert(type->is_sampler());
2577 static const char *const names[4] = {
2578 "usampler1D", "usampler1DArray", NULL, NULL
2579 };
2580 return names[type_idx];
2581 }
2582 case GLSL_SAMPLER_DIM_2D: {
2583 static const char *const names[8] = {
2584 "usampler2D", "usampler2DArray", NULL, NULL,
2585 "uimage2D", "uimage2DArray", NULL, NULL
2586 };
2587 return names[offset + type_idx];
2588 }
2589 case GLSL_SAMPLER_DIM_3D: {
2590 static const char *const names[8] = {
2591 "usampler3D", NULL, NULL, NULL,
2592 "uimage3D", NULL, NULL, NULL
2593 };
2594 return names[offset + type_idx];
2595 }
2596 case GLSL_SAMPLER_DIM_CUBE: {
2597 static const char *const names[8] = {
2598 "usamplerCube", "usamplerCubeArray", NULL, NULL,
2599 "uimageCube", NULL, NULL, NULL
2600 };
2601 return names[offset + type_idx];
2602 }
2603 case GLSL_SAMPLER_DIM_MS: {
2604 assert(type->is_sampler());
2605 static const char *const names[4] = {
2606 "usampler2DMS", "usampler2DMSArray", NULL, NULL
2607 };
2608 return names[type_idx];
2609 }
2610 case GLSL_SAMPLER_DIM_RECT: {
2611 assert(type->is_sampler());
2612 static const char *const names[4] = {
2613 "usamplerRect", NULL, "usamplerRectShadow", NULL
2614 };
2615 return names[type_idx];
2616 }
2617 case GLSL_SAMPLER_DIM_BUF: {
2618 static const char *const names[8] = {
2619 "usamplerBuffer", NULL, NULL, NULL,
2620 "uimageBuffer", NULL, NULL, NULL
2621 };
2622 return names[offset + type_idx];
2623 }
2624 default:
2625 unreachable("Unsupported usampler/uimage dimensionality");
2626 } /* sampler/image uint dimensionality */
2627 break;
2628 default:
2629 unreachable("Unsupported sampler/image type");
2630 } /* sampler/image type */
2631 break;
2632 } /* GLSL_TYPE_SAMPLER/GLSL_TYPE_IMAGE */
2633 break;
2634 default:
2635 unreachable("Unsupported type");
2636 } /* base type */
2637 }
2638
2639 static unsigned
2640 select_gles_precision(unsigned qual_precision,
2641 const glsl_type *type,
2642 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
2643 {
2644 /* Precision qualifiers do not have any meaning in Desktop GLSL.
2645 * In GLES we take the precision from the type qualifier if present,
2646 * otherwise, if the type of the variable allows precision qualifiers at
2647 * all, we look for the default precision qualifier for that type in the
2648 * current scope.
2649 */
2650 assert(state->es_shader);
2651
2652 unsigned precision = GLSL_PRECISION_NONE;
2653 if (qual_precision) {
2654 precision = qual_precision;
2655 } else if (precision_qualifier_allowed(type)) {
2656 const char *type_name =
2657 get_type_name_for_precision_qualifier(type->without_array());
2658 assert(type_name != NULL);
2659
2660 precision =
2661 state->symbols->get_default_precision_qualifier(type_name);
2662 if (precision == ast_precision_none) {
2663 _mesa_glsl_error(loc, state,
2664 "No precision specified in this scope for type `%s'",
2665 type->name);
2666 }
2667 }
2668
2669
2670 /* Section 4.1.7.3 (Atomic Counters) of the GLSL ES 3.10 spec says:
2671 *
2672 * "The default precision of all atomic types is highp. It is an error to
2673 * declare an atomic type with a different precision or to specify the
2674 * default precision for an atomic type to be lowp or mediump."
2675 */
2676 if (type->is_atomic_uint() && precision != ast_precision_high) {
2677 _mesa_glsl_error(loc, state,
2678 "atomic_uint can only have highp precision qualifier");
2679 }
2680
2681 return precision;
2682 }
2683
2684 const glsl_type *
2685 ast_fully_specified_type::glsl_type(const char **name,
2686 struct _mesa_glsl_parse_state *state) const
2687 {
2688 return this->specifier->glsl_type(name, state);
2689 }
2690
2691 /**
2692 * Determine whether a toplevel variable declaration declares a varying. This
2693 * function operates by examining the variable's mode and the shader target,
2694 * so it correctly identifies linkage variables regardless of whether they are
2695 * declared using the deprecated "varying" syntax or the new "in/out" syntax.
2696 *
2697 * Passing a non-toplevel variable declaration (e.g. a function parameter) to
2698 * this function will produce undefined results.
2699 */
2700 static bool
2701 is_varying_var(ir_variable *var, gl_shader_stage target)
2702 {
2703 switch (target) {
2704 case MESA_SHADER_VERTEX:
2705 return var->data.mode == ir_var_shader_out;
2706 case MESA_SHADER_FRAGMENT:
2707 return var->data.mode == ir_var_shader_in;
2708 default:
2709 return var->data.mode == ir_var_shader_out || var->data.mode == ir_var_shader_in;
2710 }
2711 }
2712
2713 static bool
2714 is_allowed_invariant(ir_variable *var, struct _mesa_glsl_parse_state *state)
2715 {
2716 if (is_varying_var(var, state->stage))
2717 return true;
2718
2719 /* From Section 4.6.1 ("The Invariant Qualifier") GLSL 1.20 spec:
2720 * "Only variables output from a vertex shader can be candidates
2721 * for invariance".
2722 */
2723 if (!state->is_version(130, 0))
2724 return false;
2725
2726 /*
2727 * Later specs remove this language - so allowed invariant
2728 * on fragment shader outputs as well.
2729 */
2730 if (state->stage == MESA_SHADER_FRAGMENT &&
2731 var->data.mode == ir_var_shader_out)
2732 return true;
2733 return false;
2734 }
2735
2736 /**
2737 * Matrix layout qualifiers are only allowed on certain types
2738 */
2739 static void
2740 validate_matrix_layout_for_type(struct _mesa_glsl_parse_state *state,
2741 YYLTYPE *loc,
2742 const glsl_type *type,
2743 ir_variable *var)
2744 {
2745 if (var && !var->is_in_buffer_block()) {
2746 /* Layout qualifiers may only apply to interface blocks and fields in
2747 * them.
2748 */
2749 _mesa_glsl_error(loc, state,
2750 "uniform block layout qualifiers row_major and "
2751 "column_major may not be applied to variables "
2752 "outside of uniform blocks");
2753 } else if (!type->without_array()->is_matrix()) {
2754 /* The OpenGL ES 3.0 conformance tests did not originally allow
2755 * matrix layout qualifiers on non-matrices. However, the OpenGL
2756 * 4.4 and OpenGL ES 3.0 (revision TBD) specifications were
2757 * amended to specifically allow these layouts on all types. Emit
2758 * a warning so that people know their code may not be portable.
2759 */
2760 _mesa_glsl_warning(loc, state,
2761 "uniform block layout qualifiers row_major and "
2762 "column_major applied to non-matrix types may "
2763 "be rejected by older compilers");
2764 }
2765 }
2766
2767 static bool
2768 validate_xfb_buffer_qualifier(YYLTYPE *loc,
2769 struct _mesa_glsl_parse_state *state,
2770 unsigned xfb_buffer) {
2771 if (xfb_buffer >= state->Const.MaxTransformFeedbackBuffers) {
2772 _mesa_glsl_error(loc, state,
2773 "invalid xfb_buffer specified %d is larger than "
2774 "MAX_TRANSFORM_FEEDBACK_BUFFERS - 1 (%d).",
2775 xfb_buffer,
2776 state->Const.MaxTransformFeedbackBuffers - 1);
2777 return false;
2778 }
2779
2780 return true;
2781 }
2782
2783 /* From the ARB_enhanced_layouts spec:
2784 *
2785 * "Variables and block members qualified with *xfb_offset* can be
2786 * scalars, vectors, matrices, structures, and (sized) arrays of these.
2787 * The offset must be a multiple of the size of the first component of
2788 * the first qualified variable or block member, or a compile-time error
2789 * results. Further, if applied to an aggregate containing a double,
2790 * the offset must also be a multiple of 8, and the space taken in the
2791 * buffer will be a multiple of 8.
2792 */
2793 static bool
2794 validate_xfb_offset_qualifier(YYLTYPE *loc,
2795 struct _mesa_glsl_parse_state *state,
2796 int xfb_offset, const glsl_type *type,
2797 unsigned component_size) {
2798 const glsl_type *t_without_array = type->without_array();
2799
2800 if (xfb_offset != -1 && type->is_unsized_array()) {
2801 _mesa_glsl_error(loc, state,
2802 "xfb_offset can't be used with unsized arrays.");
2803 return false;
2804 }
2805
2806 /* Make sure nested structs don't contain unsized arrays, and validate
2807 * any xfb_offsets on interface members.
2808 */
2809 if (t_without_array->is_record() || t_without_array->is_interface())
2810 for (unsigned int i = 0; i < t_without_array->length; i++) {
2811 const glsl_type *member_t = t_without_array->fields.structure[i].type;
2812
2813 /* When the interface block doesn't have an xfb_offset qualifier then
2814 * we apply the component size rules at the member level.
2815 */
2816 if (xfb_offset == -1)
2817 component_size = member_t->contains_double() ? 8 : 4;
2818
2819 int xfb_offset = t_without_array->fields.structure[i].offset;
2820 validate_xfb_offset_qualifier(loc, state, xfb_offset, member_t,
2821 component_size);
2822 }
2823
2824 /* Nested structs or interface block without offset may not have had an
2825 * offset applied yet so return.
2826 */
2827 if (xfb_offset == -1) {
2828 return true;
2829 }
2830
2831 if (xfb_offset % component_size) {
2832 _mesa_glsl_error(loc, state,
2833 "invalid qualifier xfb_offset=%d must be a multiple "
2834 "of the first component size of the first qualified "
2835 "variable or block member. Or double if an aggregate "
2836 "that contains a double (%d).",
2837 xfb_offset, component_size);
2838 return false;
2839 }
2840
2841 return true;
2842 }
2843
2844 static bool
2845 validate_stream_qualifier(YYLTYPE *loc, struct _mesa_glsl_parse_state *state,
2846 unsigned stream)
2847 {
2848 if (stream >= state->ctx->Const.MaxVertexStreams) {
2849 _mesa_glsl_error(loc, state,
2850 "invalid stream specified %d is larger than "
2851 "MAX_VERTEX_STREAMS - 1 (%d).",
2852 stream, state->ctx->Const.MaxVertexStreams - 1);
2853 return false;
2854 }
2855
2856 return true;
2857 }
2858
2859 static void
2860 apply_explicit_binding(struct _mesa_glsl_parse_state *state,
2861 YYLTYPE *loc,
2862 ir_variable *var,
2863 const glsl_type *type,
2864 const ast_type_qualifier *qual)
2865 {
2866 if (!qual->flags.q.uniform && !qual->flags.q.buffer) {
2867 _mesa_glsl_error(loc, state,
2868 "the \"binding\" qualifier only applies to uniforms and "
2869 "shader storage buffer objects");
2870 return;
2871 }
2872
2873 unsigned qual_binding;
2874 if (!process_qualifier_constant(state, loc, "binding", qual->binding,
2875 &qual_binding)) {
2876 return;
2877 }
2878
2879 const struct gl_context *const ctx = state->ctx;
2880 unsigned elements = type->is_array() ? type->arrays_of_arrays_size() : 1;
2881 unsigned max_index = qual_binding + elements - 1;
2882 const glsl_type *base_type = type->without_array();
2883
2884 if (base_type->is_interface()) {
2885 /* UBOs. From page 60 of the GLSL 4.20 specification:
2886 * "If the binding point for any uniform block instance is less than zero,
2887 * or greater than or equal to the implementation-dependent maximum
2888 * number of uniform buffer bindings, a compilation error will occur.
2889 * When the binding identifier is used with a uniform block instanced as
2890 * an array of size N, all elements of the array from binding through
2891 * binding + N – 1 must be within this range."
2892 *
2893 * The implementation-dependent maximum is GL_MAX_UNIFORM_BUFFER_BINDINGS.
2894 */
2895 if (qual->flags.q.uniform &&
2896 max_index >= ctx->Const.MaxUniformBufferBindings) {
2897 _mesa_glsl_error(loc, state, "layout(binding = %u) for %d UBOs exceeds "
2898 "the maximum number of UBO binding points (%d)",
2899 qual_binding, elements,
2900 ctx->Const.MaxUniformBufferBindings);
2901 return;
2902 }
2903
2904 /* SSBOs. From page 67 of the GLSL 4.30 specification:
2905 * "If the binding point for any uniform or shader storage block instance
2906 * is less than zero, or greater than or equal to the
2907 * implementation-dependent maximum number of uniform buffer bindings, a
2908 * compile-time error will occur. When the binding identifier is used
2909 * with a uniform or shader storage block instanced as an array of size
2910 * N, all elements of the array from binding through binding + N – 1 must
2911 * be within this range."
2912 */
2913 if (qual->flags.q.buffer &&
2914 max_index >= ctx->Const.MaxShaderStorageBufferBindings) {
2915 _mesa_glsl_error(loc, state, "layout(binding = %u) for %d SSBOs exceeds "
2916 "the maximum number of SSBO binding points (%d)",
2917 qual_binding, elements,
2918 ctx->Const.MaxShaderStorageBufferBindings);
2919 return;
2920 }
2921 } else if (base_type->is_sampler()) {
2922 /* Samplers. From page 63 of the GLSL 4.20 specification:
2923 * "If the binding is less than zero, or greater than or equal to the
2924 * implementation-dependent maximum supported number of units, a
2925 * compilation error will occur. When the binding identifier is used
2926 * with an array of size N, all elements of the array from binding
2927 * through binding + N - 1 must be within this range."
2928 */
2929 unsigned limit = ctx->Const.MaxCombinedTextureImageUnits;
2930
2931 if (max_index >= limit) {
2932 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d samplers "
2933 "exceeds the maximum number of texture image units "
2934 "(%u)", qual_binding, elements, limit);
2935
2936 return;
2937 }
2938 } else if (base_type->contains_atomic()) {
2939 assert(ctx->Const.MaxAtomicBufferBindings <= MAX_COMBINED_ATOMIC_BUFFERS);
2940 if (qual_binding >= ctx->Const.MaxAtomicBufferBindings) {
2941 _mesa_glsl_error(loc, state, "layout(binding = %d) exceeds the "
2942 "maximum number of atomic counter buffer bindings "
2943 "(%u)", qual_binding,
2944 ctx->Const.MaxAtomicBufferBindings);
2945
2946 return;
2947 }
2948 } else if ((state->is_version(420, 310) ||
2949 state->ARB_shading_language_420pack_enable) &&
2950 base_type->is_image()) {
2951 assert(ctx->Const.MaxImageUnits <= MAX_IMAGE_UNITS);
2952 if (max_index >= ctx->Const.MaxImageUnits) {
2953 _mesa_glsl_error(loc, state, "Image binding %d exceeds the "
2954 "maximum number of image units (%d)", max_index,
2955 ctx->Const.MaxImageUnits);
2956 return;
2957 }
2958
2959 } else {
2960 _mesa_glsl_error(loc, state,
2961 "the \"binding\" qualifier only applies to uniform "
2962 "blocks, storage blocks, opaque variables, or arrays "
2963 "thereof");
2964 return;
2965 }
2966
2967 var->data.explicit_binding = true;
2968 var->data.binding = qual_binding;
2969
2970 return;
2971 }
2972
2973 static void
2974 validate_fragment_flat_interpolation_input(struct _mesa_glsl_parse_state *state,
2975 YYLTYPE *loc,
2976 const glsl_interp_mode interpolation,
2977 const struct glsl_type *var_type,
2978 ir_variable_mode mode)
2979 {
2980 if (state->stage != MESA_SHADER_FRAGMENT ||
2981 interpolation == INTERP_MODE_FLAT ||
2982 mode != ir_var_shader_in)
2983 return;
2984
2985 /* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,
2986 * so must integer vertex outputs.
2987 *
2988 * From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:
2989 * "Fragment shader inputs that are signed or unsigned integers or
2990 * integer vectors must be qualified with the interpolation qualifier
2991 * flat."
2992 *
2993 * From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:
2994 * "Fragment shader inputs that are, or contain, signed or unsigned
2995 * integers or integer vectors must be qualified with the
2996 * interpolation qualifier flat."
2997 *
2998 * From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:
2999 * "Vertex shader outputs that are, or contain, signed or unsigned
3000 * integers or integer vectors must be qualified with the
3001 * interpolation qualifier flat."
3002 *
3003 * Note that prior to GLSL 1.50, this requirement applied to vertex
3004 * outputs rather than fragment inputs. That creates problems in the
3005 * presence of geometry shaders, so we adopt the GLSL 1.50 rule for all
3006 * desktop GL shaders. For GLSL ES shaders, we follow the spec and
3007 * apply the restriction to both vertex outputs and fragment inputs.
3008 *
3009 * Note also that the desktop GLSL specs are missing the text "or
3010 * contain"; this is presumably an oversight, since there is no
3011 * reasonable way to interpolate a fragment shader input that contains
3012 * an integer. See Khronos bug #15671.
3013 */
3014 if (state->is_version(130, 300)
3015 && var_type->contains_integer()) {
3016 _mesa_glsl_error(loc, state, "if a fragment input is (or contains) "
3017 "an integer, then it must be qualified with 'flat'");
3018 }
3019
3020 /* Double fragment inputs must be qualified with 'flat'.
3021 *
3022 * From the "Overview" of the ARB_gpu_shader_fp64 extension spec:
3023 * "This extension does not support interpolation of double-precision
3024 * values; doubles used as fragment shader inputs must be qualified as
3025 * "flat"."
3026 *
3027 * From section 4.3.4 ("Inputs") of the GLSL 4.00 spec:
3028 * "Fragment shader inputs that are signed or unsigned integers, integer
3029 * vectors, or any double-precision floating-point type must be
3030 * qualified with the interpolation qualifier flat."
3031 *
3032 * Note that the GLSL specs are missing the text "or contain"; this is
3033 * presumably an oversight. See Khronos bug #15671.
3034 *
3035 * The 'double' type does not exist in GLSL ES so far.
3036 */
3037 if (state->has_double()
3038 && var_type->contains_double()) {
3039 _mesa_glsl_error(loc, state, "if a fragment input is (or contains) "
3040 "a double, then it must be qualified with 'flat'");
3041 }
3042
3043 /* Bindless sampler/image fragment inputs must be qualified with 'flat'.
3044 *
3045 * From section 4.3.4 of the ARB_bindless_texture spec:
3046 *
3047 * "(modify last paragraph, p. 35, allowing samplers and images as
3048 * fragment shader inputs) ... Fragment inputs can only be signed and
3049 * unsigned integers and integer vectors, floating point scalars,
3050 * floating-point vectors, matrices, sampler and image types, or arrays
3051 * or structures of these. Fragment shader inputs that are signed or
3052 * unsigned integers, integer vectors, or any double-precision floating-
3053 * point type, or any sampler or image type must be qualified with the
3054 * interpolation qualifier "flat"."
3055 */
3056 if (state->has_bindless()
3057 && (var_type->contains_sampler() || var_type->contains_image())) {
3058 _mesa_glsl_error(loc, state, "if a fragment input is (or contains) "
3059 "a bindless sampler (or image), then it must be "
3060 "qualified with 'flat'");
3061 }
3062 }
3063
3064 static void
3065 validate_interpolation_qualifier(struct _mesa_glsl_parse_state *state,
3066 YYLTYPE *loc,
3067 const glsl_interp_mode interpolation,
3068 const struct ast_type_qualifier *qual,
3069 const struct glsl_type *var_type,
3070 ir_variable_mode mode)
3071 {
3072 /* Interpolation qualifiers can only apply to shader inputs or outputs, but
3073 * not to vertex shader inputs nor fragment shader outputs.
3074 *
3075 * From section 4.3 ("Storage Qualifiers") of the GLSL 1.30 spec:
3076 * "Outputs from a vertex shader (out) and inputs to a fragment
3077 * shader (in) can be further qualified with one or more of these
3078 * interpolation qualifiers"
3079 * ...
3080 * "These interpolation qualifiers may only precede the qualifiers in,
3081 * centroid in, out, or centroid out in a declaration. They do not apply
3082 * to the deprecated storage qualifiers varying or centroid
3083 * varying. They also do not apply to inputs into a vertex shader or
3084 * outputs from a fragment shader."
3085 *
3086 * From section 4.3 ("Storage Qualifiers") of the GLSL ES 3.00 spec:
3087 * "Outputs from a shader (out) and inputs to a shader (in) can be
3088 * further qualified with one of these interpolation qualifiers."
3089 * ...
3090 * "These interpolation qualifiers may only precede the qualifiers
3091 * in, centroid in, out, or centroid out in a declaration. They do
3092 * not apply to inputs into a vertex shader or outputs from a
3093 * fragment shader."
3094 */
3095 if (state->is_version(130, 300)
3096 && interpolation != INTERP_MODE_NONE) {
3097 const char *i = interpolation_string(interpolation);
3098 if (mode != ir_var_shader_in && mode != ir_var_shader_out)
3099 _mesa_glsl_error(loc, state,
3100 "interpolation qualifier `%s' can only be applied to "
3101 "shader inputs or outputs.", i);
3102
3103 switch (state->stage) {
3104 case MESA_SHADER_VERTEX:
3105 if (mode == ir_var_shader_in) {
3106 _mesa_glsl_error(loc, state,
3107 "interpolation qualifier '%s' cannot be applied to "
3108 "vertex shader inputs", i);
3109 }
3110 break;
3111 case MESA_SHADER_FRAGMENT:
3112 if (mode == ir_var_shader_out) {
3113 _mesa_glsl_error(loc, state,
3114 "interpolation qualifier '%s' cannot be applied to "
3115 "fragment shader outputs", i);
3116 }
3117 break;
3118 default:
3119 break;
3120 }
3121 }
3122
3123 /* Interpolation qualifiers cannot be applied to 'centroid' and
3124 * 'centroid varying'.
3125 *
3126 * From section 4.3 ("Storage Qualifiers") of the GLSL 1.30 spec:
3127 * "interpolation qualifiers may only precede the qualifiers in,
3128 * centroid in, out, or centroid out in a declaration. They do not apply
3129 * to the deprecated storage qualifiers varying or centroid varying."
3130 *
3131 * These deprecated storage qualifiers do not exist in GLSL ES 3.00.
3132 */
3133 if (state->is_version(130, 0)
3134 && interpolation != INTERP_MODE_NONE
3135 && qual->flags.q.varying) {
3136
3137 const char *i = interpolation_string(interpolation);
3138 const char *s;
3139 if (qual->flags.q.centroid)
3140 s = "centroid varying";
3141 else
3142 s = "varying";
3143
3144 _mesa_glsl_error(loc, state,
3145 "qualifier '%s' cannot be applied to the "
3146 "deprecated storage qualifier '%s'", i, s);
3147 }
3148
3149 validate_fragment_flat_interpolation_input(state, loc, interpolation,
3150 var_type, mode);
3151 }
3152
3153 static glsl_interp_mode
3154 interpret_interpolation_qualifier(const struct ast_type_qualifier *qual,
3155 const struct glsl_type *var_type,
3156 ir_variable_mode mode,
3157 struct _mesa_glsl_parse_state *state,
3158 YYLTYPE *loc)
3159 {
3160 glsl_interp_mode interpolation;
3161 if (qual->flags.q.flat)
3162 interpolation = INTERP_MODE_FLAT;
3163 else if (qual->flags.q.noperspective)
3164 interpolation = INTERP_MODE_NOPERSPECTIVE;
3165 else if (qual->flags.q.smooth)
3166 interpolation = INTERP_MODE_SMOOTH;
3167 else
3168 interpolation = INTERP_MODE_NONE;
3169
3170 validate_interpolation_qualifier(state, loc,
3171 interpolation,
3172 qual, var_type, mode);
3173
3174 return interpolation;
3175 }
3176
3177
3178 static void
3179 apply_explicit_location(const struct ast_type_qualifier *qual,
3180 ir_variable *var,
3181 struct _mesa_glsl_parse_state *state,
3182 YYLTYPE *loc)
3183 {
3184 bool fail = false;
3185
3186 unsigned qual_location;
3187 if (!process_qualifier_constant(state, loc, "location", qual->location,
3188 &qual_location)) {
3189 return;
3190 }
3191
3192 /* Checks for GL_ARB_explicit_uniform_location. */
3193 if (qual->flags.q.uniform) {
3194 if (!state->check_explicit_uniform_location_allowed(loc, var))
3195 return;
3196
3197 const struct gl_context *const ctx = state->ctx;
3198 unsigned max_loc = qual_location + var->type->uniform_locations() - 1;
3199
3200 if (max_loc >= ctx->Const.MaxUserAssignableUniformLocations) {
3201 _mesa_glsl_error(loc, state, "location(s) consumed by uniform %s "
3202 ">= MAX_UNIFORM_LOCATIONS (%u)", var->name,
3203 ctx->Const.MaxUserAssignableUniformLocations);
3204 return;
3205 }
3206
3207 var->data.explicit_location = true;
3208 var->data.location = qual_location;
3209 return;
3210 }
3211
3212 /* Between GL_ARB_explicit_attrib_location an
3213 * GL_ARB_separate_shader_objects, the inputs and outputs of any shader
3214 * stage can be assigned explicit locations. The checking here associates
3215 * the correct extension with the correct stage's input / output:
3216 *
3217 * input output
3218 * ----- ------
3219 * vertex explicit_loc sso
3220 * tess control sso sso
3221 * tess eval sso sso
3222 * geometry sso sso
3223 * fragment sso explicit_loc
3224 */
3225 switch (state->stage) {
3226 case MESA_SHADER_VERTEX:
3227 if (var->data.mode == ir_var_shader_in) {
3228 if (!state->check_explicit_attrib_location_allowed(loc, var))
3229 return;
3230
3231 break;
3232 }
3233
3234 if (var->data.mode == ir_var_shader_out) {
3235 if (!state->check_separate_shader_objects_allowed(loc, var))
3236 return;
3237
3238 break;
3239 }
3240
3241 fail = true;
3242 break;
3243
3244 case MESA_SHADER_TESS_CTRL:
3245 case MESA_SHADER_TESS_EVAL:
3246 case MESA_SHADER_GEOMETRY:
3247 if (var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) {
3248 if (!state->check_separate_shader_objects_allowed(loc, var))
3249 return;
3250
3251 break;
3252 }
3253
3254 fail = true;
3255 break;
3256
3257 case MESA_SHADER_FRAGMENT:
3258 if (var->data.mode == ir_var_shader_in) {
3259 if (!state->check_separate_shader_objects_allowed(loc, var))
3260 return;
3261
3262 break;
3263 }
3264
3265 if (var->data.mode == ir_var_shader_out) {
3266 if (!state->check_explicit_attrib_location_allowed(loc, var))
3267 return;
3268
3269 break;
3270 }
3271
3272 fail = true;
3273 break;
3274
3275 case MESA_SHADER_COMPUTE:
3276 _mesa_glsl_error(loc, state,
3277 "compute shader variables cannot be given "
3278 "explicit locations");
3279 return;
3280 default:
3281 fail = true;
3282 break;
3283 };
3284
3285 if (fail) {
3286 _mesa_glsl_error(loc, state,
3287 "%s cannot be given an explicit location in %s shader",
3288 mode_string(var),
3289 _mesa_shader_stage_to_string(state->stage));
3290 } else {
3291 var->data.explicit_location = true;
3292
3293 switch (state->stage) {
3294 case MESA_SHADER_VERTEX:
3295 var->data.location = (var->data.mode == ir_var_shader_in)
3296 ? (qual_location + VERT_ATTRIB_GENERIC0)
3297 : (qual_location + VARYING_SLOT_VAR0);
3298 break;
3299
3300 case MESA_SHADER_TESS_CTRL:
3301 case MESA_SHADER_TESS_EVAL:
3302 case MESA_SHADER_GEOMETRY:
3303 if (var->data.patch)
3304 var->data.location = qual_location + VARYING_SLOT_PATCH0;
3305 else
3306 var->data.location = qual_location + VARYING_SLOT_VAR0;
3307 break;
3308
3309 case MESA_SHADER_FRAGMENT:
3310 var->data.location = (var->data.mode == ir_var_shader_out)
3311 ? (qual_location + FRAG_RESULT_DATA0)
3312 : (qual_location + VARYING_SLOT_VAR0);
3313 break;
3314 default:
3315 assert(!"Unexpected shader type");
3316 break;
3317 }
3318
3319 /* Check if index was set for the uniform instead of the function */
3320 if (qual->flags.q.explicit_index && qual->is_subroutine_decl()) {
3321 _mesa_glsl_error(loc, state, "an index qualifier can only be "
3322 "used with subroutine functions");
3323 return;
3324 }
3325
3326 unsigned qual_index;
3327 if (qual->flags.q.explicit_index &&
3328 process_qualifier_constant(state, loc, "index", qual->index,
3329 &qual_index)) {
3330 /* From the GLSL 4.30 specification, section 4.4.2 (Output
3331 * Layout Qualifiers):
3332 *
3333 * "It is also a compile-time error if a fragment shader
3334 * sets a layout index to less than 0 or greater than 1."
3335 *
3336 * Older specifications don't mandate a behavior; we take
3337 * this as a clarification and always generate the error.
3338 */
3339 if (qual_index > 1) {
3340 _mesa_glsl_error(loc, state,
3341 "explicit index may only be 0 or 1");
3342 } else {
3343 var->data.explicit_index = true;
3344 var->data.index = qual_index;
3345 }
3346 }
3347 }
3348 }
3349
3350 static bool
3351 validate_storage_for_sampler_image_types(ir_variable *var,
3352 struct _mesa_glsl_parse_state *state,
3353 YYLTYPE *loc)
3354 {
3355 /* From section 4.1.7 of the GLSL 4.40 spec:
3356 *
3357 * "[Opaque types] can only be declared as function
3358 * parameters or uniform-qualified variables."
3359 *
3360 * From section 4.1.7 of the ARB_bindless_texture spec:
3361 *
3362 * "Samplers may be declared as shader inputs and outputs, as uniform
3363 * variables, as temporary variables, and as function parameters."
3364 *
3365 * From section 4.1.X of the ARB_bindless_texture spec:
3366 *
3367 * "Images may be declared as shader inputs and outputs, as uniform
3368 * variables, as temporary variables, and as function parameters."
3369 */
3370 if (state->has_bindless()) {
3371 if (var->data.mode != ir_var_auto &&
3372 var->data.mode != ir_var_uniform &&
3373 var->data.mode != ir_var_shader_in &&
3374 var->data.mode != ir_var_shader_out &&
3375 var->data.mode != ir_var_function_in &&
3376 var->data.mode != ir_var_function_out &&
3377 var->data.mode != ir_var_function_inout) {
3378 _mesa_glsl_error(loc, state, "bindless image/sampler variables may "
3379 "only be declared as shader inputs and outputs, as "
3380 "uniform variables, as temporary variables and as "
3381 "function parameters");
3382 return false;
3383 }
3384 } else {
3385 if (var->data.mode != ir_var_uniform &&
3386 var->data.mode != ir_var_function_in) {
3387 _mesa_glsl_error(loc, state, "image/sampler variables may only be "
3388 "declared as function parameters or "
3389 "uniform-qualified global variables");
3390 return false;
3391 }
3392 }
3393 return true;
3394 }
3395
3396 static bool
3397 validate_memory_qualifier_for_type(struct _mesa_glsl_parse_state *state,
3398 YYLTYPE *loc,
3399 const struct ast_type_qualifier *qual,
3400 const glsl_type *type)
3401 {
3402 /* From Section 4.10 (Memory Qualifiers) of the GLSL 4.50 spec:
3403 *
3404 * "Memory qualifiers are only supported in the declarations of image
3405 * variables, buffer variables, and shader storage blocks; it is an error
3406 * to use such qualifiers in any other declarations.
3407 */
3408 if (!type->is_image() && !qual->flags.q.buffer) {
3409 if (qual->flags.q.read_only ||
3410 qual->flags.q.write_only ||
3411 qual->flags.q.coherent ||
3412 qual->flags.q._volatile ||
3413 qual->flags.q.restrict_flag) {
3414 _mesa_glsl_error(loc, state, "memory qualifiers may only be applied "
3415 "in the declarations of image variables, buffer "
3416 "variables, and shader storage blocks");
3417 return false;
3418 }
3419 }
3420 return true;
3421 }
3422
3423 static bool
3424 validate_image_format_qualifier_for_type(struct _mesa_glsl_parse_state *state,
3425 YYLTYPE *loc,
3426 const struct ast_type_qualifier *qual,
3427 const glsl_type *type)
3428 {
3429 /* From section 4.4.6.2 (Format Layout Qualifiers) of the GLSL 4.50 spec:
3430 *
3431 * "Format layout qualifiers can be used on image variable declarations
3432 * (those declared with a basic type having “image ” in its keyword)."
3433 */
3434 if (!type->is_image() && qual->flags.q.explicit_image_format) {
3435 _mesa_glsl_error(loc, state, "format layout qualifiers may only be "
3436 "applied to images");
3437 return false;
3438 }
3439 return true;
3440 }
3441
3442 static void
3443 apply_image_qualifier_to_variable(const struct ast_type_qualifier *qual,
3444 ir_variable *var,
3445 struct _mesa_glsl_parse_state *state,
3446 YYLTYPE *loc)
3447 {
3448 const glsl_type *base_type = var->type->without_array();
3449
3450 if (!validate_image_format_qualifier_for_type(state, loc, qual, base_type) ||
3451 !validate_memory_qualifier_for_type(state, loc, qual, base_type))
3452 return;
3453
3454 if (!base_type->is_image())
3455 return;
3456
3457 if (!validate_storage_for_sampler_image_types(var, state, loc))
3458 return;
3459
3460 var->data.memory_read_only |= qual->flags.q.read_only;
3461 var->data.memory_write_only |= qual->flags.q.write_only;
3462 var->data.memory_coherent |= qual->flags.q.coherent;
3463 var->data.memory_volatile |= qual->flags.q._volatile;
3464 var->data.memory_restrict |= qual->flags.q.restrict_flag;
3465
3466 if (qual->flags.q.explicit_image_format) {
3467 if (var->data.mode == ir_var_function_in) {
3468 _mesa_glsl_error(loc, state, "format qualifiers cannot be used on "
3469 "image function parameters");
3470 }
3471
3472 if (qual->image_base_type != base_type->sampled_type) {
3473 _mesa_glsl_error(loc, state, "format qualifier doesn't match the base "
3474 "data type of the image");
3475 }
3476
3477 var->data.image_format = qual->image_format;
3478 } else {
3479 if (var->data.mode == ir_var_uniform) {
3480 if (state->es_shader) {
3481 _mesa_glsl_error(loc, state, "all image uniforms must have a "
3482 "format layout qualifier");
3483 } else if (!qual->flags.q.write_only) {
3484 _mesa_glsl_error(loc, state, "image uniforms not qualified with "
3485 "`writeonly' must have a format layout qualifier");
3486 }
3487 }
3488 var->data.image_format = GL_NONE;
3489 }
3490
3491 /* From page 70 of the GLSL ES 3.1 specification:
3492 *
3493 * "Except for image variables qualified with the format qualifiers r32f,
3494 * r32i, and r32ui, image variables must specify either memory qualifier
3495 * readonly or the memory qualifier writeonly."
3496 */
3497 if (state->es_shader &&
3498 var->data.image_format != GL_R32F &&
3499 var->data.image_format != GL_R32I &&
3500 var->data.image_format != GL_R32UI &&
3501 !var->data.memory_read_only &&
3502 !var->data.memory_write_only) {
3503 _mesa_glsl_error(loc, state, "image variables of format other than r32f, "
3504 "r32i or r32ui must be qualified `readonly' or "
3505 "`writeonly'");
3506 }
3507 }
3508
3509 static inline const char*
3510 get_layout_qualifier_string(bool origin_upper_left, bool pixel_center_integer)
3511 {
3512 if (origin_upper_left && pixel_center_integer)
3513 return "origin_upper_left, pixel_center_integer";
3514 else if (origin_upper_left)
3515 return "origin_upper_left";
3516 else if (pixel_center_integer)
3517 return "pixel_center_integer";
3518 else
3519 return " ";
3520 }
3521
3522 static inline bool
3523 is_conflicting_fragcoord_redeclaration(struct _mesa_glsl_parse_state *state,
3524 const struct ast_type_qualifier *qual)
3525 {
3526 /* If gl_FragCoord was previously declared, and the qualifiers were
3527 * different in any way, return true.
3528 */
3529 if (state->fs_redeclares_gl_fragcoord) {
3530 return (state->fs_pixel_center_integer != qual->flags.q.pixel_center_integer
3531 || state->fs_origin_upper_left != qual->flags.q.origin_upper_left);
3532 }
3533
3534 return false;
3535 }
3536
3537 static inline void
3538 validate_array_dimensions(const glsl_type *t,
3539 struct _mesa_glsl_parse_state *state,
3540 YYLTYPE *loc) {
3541 if (t->is_array()) {
3542 t = t->fields.array;
3543 while (t->is_array()) {
3544 if (t->is_unsized_array()) {
3545 _mesa_glsl_error(loc, state,
3546 "only the outermost array dimension can "
3547 "be unsized",
3548 t->name);
3549 break;
3550 }
3551 t = t->fields.array;
3552 }
3553 }
3554 }
3555
3556 static void
3557 apply_bindless_qualifier_to_variable(const struct ast_type_qualifier *qual,
3558 ir_variable *var,
3559 struct _mesa_glsl_parse_state *state,
3560 YYLTYPE *loc)
3561 {
3562 bool has_local_qualifiers = qual->flags.q.bindless_sampler ||
3563 qual->flags.q.bindless_image ||
3564 qual->flags.q.bound_sampler ||
3565 qual->flags.q.bound_image;
3566
3567 /* The ARB_bindless_texture spec says:
3568 *
3569 * "Modify Section 4.4.6 Opaque-Uniform Layout Qualifiers of the GLSL 4.30
3570 * spec"
3571 *
3572 * "If these layout qualifiers are applied to other types of default block
3573 * uniforms, or variables with non-uniform storage, a compile-time error
3574 * will be generated."
3575 */
3576 if (has_local_qualifiers && !qual->flags.q.uniform) {
3577 _mesa_glsl_error(loc, state, "ARB_bindless_texture layout qualifiers "
3578 "can only be applied to default block uniforms or "
3579 "variables with uniform storage");
3580 return;
3581 }
3582
3583 /* The ARB_bindless_texture spec doesn't state anything in this situation,
3584 * but it makes sense to only allow bindless_sampler/bound_sampler for
3585 * sampler types, and respectively bindless_image/bound_image for image
3586 * types.
3587 */
3588 if ((qual->flags.q.bindless_sampler || qual->flags.q.bound_sampler) &&
3589 !var->type->contains_sampler()) {
3590 _mesa_glsl_error(loc, state, "bindless_sampler or bound_sampler can only "
3591 "be applied to sampler types");
3592 return;
3593 }
3594
3595 if ((qual->flags.q.bindless_image || qual->flags.q.bound_image) &&
3596 !var->type->contains_image()) {
3597 _mesa_glsl_error(loc, state, "bindless_image or bound_image can only be "
3598 "applied to image types");
3599 return;
3600 }
3601
3602 /* The bindless_sampler/bindless_image (and respectively
3603 * bound_sampler/bound_image) layout qualifiers can be set at global and at
3604 * local scope.
3605 */
3606 if (var->type->contains_sampler() || var->type->contains_image()) {
3607 var->data.bindless = qual->flags.q.bindless_sampler ||
3608 qual->flags.q.bindless_image ||
3609 state->bindless_sampler_specified ||
3610 state->bindless_image_specified;
3611
3612 var->data.bound = qual->flags.q.bound_sampler ||
3613 qual->flags.q.bound_image ||
3614 state->bound_sampler_specified ||
3615 state->bound_image_specified;
3616 }
3617 }
3618
3619 static void
3620 apply_layout_qualifier_to_variable(const struct ast_type_qualifier *qual,
3621 ir_variable *var,
3622 struct _mesa_glsl_parse_state *state,
3623 YYLTYPE *loc)
3624 {
3625 if (var->name != NULL && strcmp(var->name, "gl_FragCoord") == 0) {
3626
3627 /* Section 4.3.8.1, page 39 of GLSL 1.50 spec says:
3628 *
3629 * "Within any shader, the first redeclarations of gl_FragCoord
3630 * must appear before any use of gl_FragCoord."
3631 *
3632 * Generate a compiler error if above condition is not met by the
3633 * fragment shader.
3634 */
3635 ir_variable *earlier = state->symbols->get_variable("gl_FragCoord");
3636 if (earlier != NULL &&
3637 earlier->data.used &&
3638 !state->fs_redeclares_gl_fragcoord) {
3639 _mesa_glsl_error(loc, state,
3640 "gl_FragCoord used before its first redeclaration "
3641 "in fragment shader");
3642 }
3643
3644 /* Make sure all gl_FragCoord redeclarations specify the same layout
3645 * qualifiers.
3646 */
3647 if (is_conflicting_fragcoord_redeclaration(state, qual)) {
3648 const char *const qual_string =
3649 get_layout_qualifier_string(qual->flags.q.origin_upper_left,
3650 qual->flags.q.pixel_center_integer);
3651
3652 const char *const state_string =
3653 get_layout_qualifier_string(state->fs_origin_upper_left,
3654 state->fs_pixel_center_integer);
3655
3656 _mesa_glsl_error(loc, state,
3657 "gl_FragCoord redeclared with different layout "
3658 "qualifiers (%s) and (%s) ",
3659 state_string,
3660 qual_string);
3661 }
3662 state->fs_origin_upper_left = qual->flags.q.origin_upper_left;
3663 state->fs_pixel_center_integer = qual->flags.q.pixel_center_integer;
3664 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers =
3665 !qual->flags.q.origin_upper_left && !qual->flags.q.pixel_center_integer;
3666 state->fs_redeclares_gl_fragcoord =
3667 state->fs_origin_upper_left ||
3668 state->fs_pixel_center_integer ||
3669 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers;
3670 }
3671
3672 var->data.pixel_center_integer = qual->flags.q.pixel_center_integer;
3673 var->data.origin_upper_left = qual->flags.q.origin_upper_left;
3674 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
3675 && (strcmp(var->name, "gl_FragCoord") != 0)) {
3676 const char *const qual_string = (qual->flags.q.origin_upper_left)
3677 ? "origin_upper_left" : "pixel_center_integer";
3678
3679 _mesa_glsl_error(loc, state,
3680 "layout qualifier `%s' can only be applied to "
3681 "fragment shader input `gl_FragCoord'",
3682 qual_string);
3683 }
3684
3685 if (qual->flags.q.explicit_location) {
3686 apply_explicit_location(qual, var, state, loc);
3687
3688 if (qual->flags.q.explicit_component) {
3689 unsigned qual_component;
3690 if (process_qualifier_constant(state, loc, "component",
3691 qual->component, &qual_component)) {
3692 const glsl_type *type = var->type->without_array();
3693 unsigned components = type->component_slots();
3694
3695 if (type->is_matrix() || type->is_record()) {
3696 _mesa_glsl_error(loc, state, "component layout qualifier "
3697 "cannot be applied to a matrix, a structure, "
3698 "a block, or an array containing any of "
3699 "these.");
3700 } else if (qual_component != 0 &&
3701 (qual_component + components - 1) > 3) {
3702 _mesa_glsl_error(loc, state, "component overflow (%u > 3)",
3703 (qual_component + components - 1));
3704 } else if (qual_component == 1 && type->is_64bit()) {
3705 /* We don't bother checking for 3 as it should be caught by the
3706 * overflow check above.
3707 */
3708 _mesa_glsl_error(loc, state, "doubles cannot begin at "
3709 "component 1 or 3");
3710 } else {
3711 var->data.explicit_component = true;
3712 var->data.location_frac = qual_component;
3713 }
3714 }
3715 }
3716 } else if (qual->flags.q.explicit_index) {
3717 if (!qual->subroutine_list)
3718 _mesa_glsl_error(loc, state,
3719 "explicit index requires explicit location");
3720 } else if (qual->flags.q.explicit_component) {
3721 _mesa_glsl_error(loc, state,
3722 "explicit component requires explicit location");
3723 }
3724
3725 if (qual->flags.q.explicit_binding) {
3726 apply_explicit_binding(state, loc, var, var->type, qual);
3727 }
3728
3729 if (state->stage == MESA_SHADER_GEOMETRY &&
3730 qual->flags.q.out && qual->flags.q.stream) {
3731 unsigned qual_stream;
3732 if (process_qualifier_constant(state, loc, "stream", qual->stream,
3733 &qual_stream) &&
3734 validate_stream_qualifier(loc, state, qual_stream)) {
3735 var->data.stream = qual_stream;
3736 }
3737 }
3738
3739 if (qual->flags.q.out && qual->flags.q.xfb_buffer) {
3740 unsigned qual_xfb_buffer;
3741 if (process_qualifier_constant(state, loc, "xfb_buffer",
3742 qual->xfb_buffer, &qual_xfb_buffer) &&
3743 validate_xfb_buffer_qualifier(loc, state, qual_xfb_buffer)) {
3744 var->data.xfb_buffer = qual_xfb_buffer;
3745 if (qual->flags.q.explicit_xfb_buffer)
3746 var->data.explicit_xfb_buffer = true;
3747 }
3748 }
3749
3750 if (qual->flags.q.explicit_xfb_offset) {
3751 unsigned qual_xfb_offset;
3752 unsigned component_size = var->type->contains_double() ? 8 : 4;
3753
3754 if (process_qualifier_constant(state, loc, "xfb_offset",
3755 qual->offset, &qual_xfb_offset) &&
3756 validate_xfb_offset_qualifier(loc, state, (int) qual_xfb_offset,
3757 var->type, component_size)) {
3758 var->data.offset = qual_xfb_offset;
3759 var->data.explicit_xfb_offset = true;
3760 }
3761 }
3762
3763 if (qual->flags.q.explicit_xfb_stride) {
3764 unsigned qual_xfb_stride;
3765 if (process_qualifier_constant(state, loc, "xfb_stride",
3766 qual->xfb_stride, &qual_xfb_stride)) {
3767 var->data.xfb_stride = qual_xfb_stride;
3768 var->data.explicit_xfb_stride = true;
3769 }
3770 }
3771
3772 if (var->type->contains_atomic()) {
3773 if (var->data.mode == ir_var_uniform) {
3774 if (var->data.explicit_binding) {
3775 unsigned *offset =
3776 &state->atomic_counter_offsets[var->data.binding];
3777
3778 if (*offset % ATOMIC_COUNTER_SIZE)
3779 _mesa_glsl_error(loc, state,
3780 "misaligned atomic counter offset");
3781
3782 var->data.offset = *offset;
3783 *offset += var->type->atomic_size();
3784
3785 } else {
3786 _mesa_glsl_error(loc, state,
3787 "atomic counters require explicit binding point");
3788 }
3789 } else if (var->data.mode != ir_var_function_in) {
3790 _mesa_glsl_error(loc, state, "atomic counters may only be declared as "
3791 "function parameters or uniform-qualified "
3792 "global variables");
3793 }
3794 }
3795
3796 if (var->type->contains_sampler() &&
3797 !validate_storage_for_sampler_image_types(var, state, loc))
3798 return;
3799
3800 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
3801 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
3802 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
3803 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
3804 * These extensions and all following extensions that add the 'layout'
3805 * keyword have been modified to require the use of 'in' or 'out'.
3806 *
3807 * The following extension do not allow the deprecated keywords:
3808 *
3809 * GL_AMD_conservative_depth
3810 * GL_ARB_conservative_depth
3811 * GL_ARB_gpu_shader5
3812 * GL_ARB_separate_shader_objects
3813 * GL_ARB_tessellation_shader
3814 * GL_ARB_transform_feedback3
3815 * GL_ARB_uniform_buffer_object
3816 *
3817 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
3818 * allow layout with the deprecated keywords.
3819 */
3820 const bool relaxed_layout_qualifier_checking =
3821 state->ARB_fragment_coord_conventions_enable;
3822
3823 const bool uses_deprecated_qualifier = qual->flags.q.attribute
3824 || qual->flags.q.varying;
3825 if (qual->has_layout() && uses_deprecated_qualifier) {
3826 if (relaxed_layout_qualifier_checking) {
3827 _mesa_glsl_warning(loc, state,
3828 "`layout' qualifier may not be used with "
3829 "`attribute' or `varying'");
3830 } else {
3831 _mesa_glsl_error(loc, state,
3832 "`layout' qualifier may not be used with "
3833 "`attribute' or `varying'");
3834 }
3835 }
3836
3837 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
3838 * AMD_conservative_depth.
3839 */
3840 if (qual->flags.q.depth_type
3841 && !state->is_version(420, 0)
3842 && !state->AMD_conservative_depth_enable
3843 && !state->ARB_conservative_depth_enable) {
3844 _mesa_glsl_error(loc, state,
3845 "extension GL_AMD_conservative_depth or "
3846 "GL_ARB_conservative_depth must be enabled "
3847 "to use depth layout qualifiers");
3848 } else if (qual->flags.q.depth_type
3849 && strcmp(var->name, "gl_FragDepth") != 0) {
3850 _mesa_glsl_error(loc, state,
3851 "depth layout qualifiers can be applied only to "
3852 "gl_FragDepth");
3853 }
3854
3855 switch (qual->depth_type) {
3856 case ast_depth_any:
3857 var->data.depth_layout = ir_depth_layout_any;
3858 break;
3859 case ast_depth_greater:
3860 var->data.depth_layout = ir_depth_layout_greater;
3861 break;
3862 case ast_depth_less:
3863 var->data.depth_layout = ir_depth_layout_less;
3864 break;
3865 case ast_depth_unchanged:
3866 var->data.depth_layout = ir_depth_layout_unchanged;
3867 break;
3868 default:
3869 var->data.depth_layout = ir_depth_layout_none;
3870 break;
3871 }
3872
3873 if (qual->flags.q.std140 ||
3874 qual->flags.q.std430 ||
3875 qual->flags.q.packed ||
3876 qual->flags.q.shared) {
3877 _mesa_glsl_error(loc, state,
3878 "uniform and shader storage block layout qualifiers "
3879 "std140, std430, packed, and shared can only be "
3880 "applied to uniform or shader storage blocks, not "
3881 "members");
3882 }
3883
3884 if (qual->flags.q.row_major || qual->flags.q.column_major) {
3885 validate_matrix_layout_for_type(state, loc, var->type, var);
3886 }
3887
3888 /* From section 4.4.1.3 of the GLSL 4.50 specification (Fragment Shader
3889 * Inputs):
3890 *
3891 * "Fragment shaders also allow the following layout qualifier on in only
3892 * (not with variable declarations)
3893 * layout-qualifier-id
3894 * early_fragment_tests
3895 * [...]"
3896 */
3897 if (qual->flags.q.early_fragment_tests) {
3898 _mesa_glsl_error(loc, state, "early_fragment_tests layout qualifier only "
3899 "valid in fragment shader input layout declaration.");
3900 }
3901
3902 if (qual->flags.q.inner_coverage) {
3903 _mesa_glsl_error(loc, state, "inner_coverage layout qualifier only "
3904 "valid in fragment shader input layout declaration.");
3905 }
3906
3907 if (qual->flags.q.post_depth_coverage) {
3908 _mesa_glsl_error(loc, state, "post_depth_coverage layout qualifier only "
3909 "valid in fragment shader input layout declaration.");
3910 }
3911
3912 if (state->has_bindless())
3913 apply_bindless_qualifier_to_variable(qual, var, state, loc);
3914
3915 if (qual->flags.q.pixel_interlock_ordered ||
3916 qual->flags.q.pixel_interlock_unordered ||
3917 qual->flags.q.sample_interlock_ordered ||
3918 qual->flags.q.sample_interlock_unordered) {
3919 _mesa_glsl_error(loc, state, "interlock layout qualifiers: "
3920 "pixel_interlock_ordered, pixel_interlock_unordered, "
3921 "sample_interlock_ordered and sample_interlock_unordered, "
3922 "only valid in fragment shader input layout declaration.");
3923 }
3924 }
3925
3926 static void
3927 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
3928 ir_variable *var,
3929 struct _mesa_glsl_parse_state *state,
3930 YYLTYPE *loc,
3931 bool is_parameter)
3932 {
3933 STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));
3934
3935 if (qual->flags.q.invariant) {
3936 if (var->data.used) {
3937 _mesa_glsl_error(loc, state,
3938 "variable `%s' may not be redeclared "
3939 "`invariant' after being used",
3940 var->name);
3941 } else {
3942 var->data.invariant = 1;
3943 }
3944 }
3945
3946 if (qual->flags.q.precise) {
3947 if (var->data.used) {
3948 _mesa_glsl_error(loc, state,
3949 "variable `%s' may not be redeclared "
3950 "`precise' after being used",
3951 var->name);
3952 } else {
3953 var->data.precise = 1;
3954 }
3955 }
3956
3957 if (qual->is_subroutine_decl() && !qual->flags.q.uniform) {
3958 _mesa_glsl_error(loc, state,
3959 "`subroutine' may only be applied to uniforms, "
3960 "subroutine type declarations, or function definitions");
3961 }
3962
3963 if (qual->flags.q.constant || qual->flags.q.attribute
3964 || qual->flags.q.uniform
3965 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
3966 var->data.read_only = 1;
3967
3968 if (qual->flags.q.centroid)
3969 var->data.centroid = 1;
3970
3971 if (qual->flags.q.sample)
3972 var->data.sample = 1;
3973
3974 /* Precision qualifiers do not hold any meaning in Desktop GLSL */
3975 if (state->es_shader) {
3976 var->data.precision =
3977 select_gles_precision(qual->precision, var->type, state, loc);
3978 }
3979
3980 if (qual->flags.q.patch)
3981 var->data.patch = 1;
3982
3983 if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {
3984 var->type = glsl_type::error_type;
3985 _mesa_glsl_error(loc, state,
3986 "`attribute' variables may not be declared in the "
3987 "%s shader",
3988 _mesa_shader_stage_to_string(state->stage));
3989 }
3990
3991 /* Disallow layout qualifiers which may only appear on layout declarations. */
3992 if (qual->flags.q.prim_type) {
3993 _mesa_glsl_error(loc, state,
3994 "Primitive type may only be specified on GS input or output "
3995 "layout declaration, not on variables.");
3996 }
3997
3998 /* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:
3999 *
4000 * "However, the const qualifier cannot be used with out or inout."
4001 *
4002 * The same section of the GLSL 4.40 spec further clarifies this saying:
4003 *
4004 * "The const qualifier cannot be used with out or inout, or a
4005 * compile-time error results."
4006 */
4007 if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {
4008 _mesa_glsl_error(loc, state,
4009 "`const' may not be applied to `out' or `inout' "
4010 "function parameters");
4011 }
4012
4013 /* If there is no qualifier that changes the mode of the variable, leave
4014 * the setting alone.
4015 */
4016 assert(var->data.mode != ir_var_temporary);
4017 if (qual->flags.q.in && qual->flags.q.out)
4018 var->data.mode = is_parameter ? ir_var_function_inout : ir_var_shader_out;
4019 else if (qual->flags.q.in)
4020 var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;
4021 else if (qual->flags.q.attribute
4022 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
4023 var->data.mode = ir_var_shader_in;
4024 else if (qual->flags.q.out)
4025 var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;
4026 else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))
4027 var->data.mode = ir_var_shader_out;
4028 else if (qual->flags.q.uniform)
4029 var->data.mode = ir_var_uniform;
4030 else if (qual->flags.q.buffer)
4031 var->data.mode = ir_var_shader_storage;
4032 else if (qual->flags.q.shared_storage)
4033 var->data.mode = ir_var_shader_shared;
4034
4035 if (!is_parameter && state->has_framebuffer_fetch() &&
4036 state->stage == MESA_SHADER_FRAGMENT) {
4037 if (state->is_version(130, 300))
4038 var->data.fb_fetch_output = qual->flags.q.in && qual->flags.q.out;
4039 else
4040 var->data.fb_fetch_output = (strcmp(var->name, "gl_LastFragData") == 0);
4041 }
4042
4043 if (var->data.fb_fetch_output) {
4044 var->data.assigned = true;
4045 var->data.memory_coherent = !qual->flags.q.non_coherent;
4046
4047 /* From the EXT_shader_framebuffer_fetch spec:
4048 *
4049 * "It is an error to declare an inout fragment output not qualified
4050 * with layout(noncoherent) if the GL_EXT_shader_framebuffer_fetch
4051 * extension hasn't been enabled."
4052 */
4053 if (var->data.memory_coherent &&
4054 !state->EXT_shader_framebuffer_fetch_enable)
4055 _mesa_glsl_error(loc, state,
4056 "invalid declaration of framebuffer fetch output not "
4057 "qualified with layout(noncoherent)");
4058
4059 } else {
4060 /* From the EXT_shader_framebuffer_fetch spec:
4061 *
4062 * "Fragment outputs declared inout may specify the following layout
4063 * qualifier: [...] noncoherent"
4064 */
4065 if (qual->flags.q.non_coherent)
4066 _mesa_glsl_error(loc, state,
4067 "invalid layout(noncoherent) qualifier not part of "
4068 "framebuffer fetch output declaration");
4069 }
4070
4071 if (!is_parameter && is_varying_var(var, state->stage)) {
4072 /* User-defined ins/outs are not permitted in compute shaders. */
4073 if (state->stage == MESA_SHADER_COMPUTE) {
4074 _mesa_glsl_error(loc, state,
4075 "user-defined input and output variables are not "
4076 "permitted in compute shaders");
4077 }
4078
4079 /* This variable is being used to link data between shader stages (in
4080 * pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type
4081 * that is allowed for such purposes.
4082 *
4083 * From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
4084 *
4085 * "The varying qualifier can be used only with the data types
4086 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
4087 * these."
4088 *
4089 * This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From
4090 * page 31 (page 37 of the PDF) of the GLSL 1.30 spec:
4091 *
4092 * "Fragment inputs can only be signed and unsigned integers and
4093 * integer vectors, float, floating-point vectors, matrices, or
4094 * arrays of these. Structures cannot be input.
4095 *
4096 * Similar text exists in the section on vertex shader outputs.
4097 *
4098 * Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES
4099 * 3.00 spec allows structs as well. Varying structs are also allowed
4100 * in GLSL 1.50.
4101 *
4102 * From section 4.3.4 of the ARB_bindless_texture spec:
4103 *
4104 * "(modify third paragraph of the section to allow sampler and image
4105 * types) ... Vertex shader inputs can only be float,
4106 * single-precision floating-point scalars, single-precision
4107 * floating-point vectors, matrices, signed and unsigned integers
4108 * and integer vectors, sampler and image types."
4109 *
4110 * From section 4.3.6 of the ARB_bindless_texture spec:
4111 *
4112 * "Output variables can only be floating-point scalars,
4113 * floating-point vectors, matrices, signed or unsigned integers or
4114 * integer vectors, sampler or image types, or arrays or structures
4115 * of any these."
4116 */
4117 switch (var->type->without_array()->base_type) {
4118 case GLSL_TYPE_FLOAT:
4119 /* Ok in all GLSL versions */
4120 break;
4121 case GLSL_TYPE_UINT:
4122 case GLSL_TYPE_INT:
4123 if (state->is_version(130, 300))
4124 break;
4125 _mesa_glsl_error(loc, state,
4126 "varying variables must be of base type float in %s",
4127 state->get_version_string());
4128 break;
4129 case GLSL_TYPE_STRUCT:
4130 if (state->is_version(150, 300))
4131 break;
4132 _mesa_glsl_error(loc, state,
4133 "varying variables may not be of type struct");
4134 break;
4135 case GLSL_TYPE_DOUBLE:
4136 case GLSL_TYPE_UINT64:
4137 case GLSL_TYPE_INT64:
4138 break;
4139 case GLSL_TYPE_SAMPLER:
4140 case GLSL_TYPE_IMAGE:
4141 if (state->has_bindless())
4142 break;
4143 /* fallthrough */
4144 default:
4145 _mesa_glsl_error(loc, state, "illegal type for a varying variable");
4146 break;
4147 }
4148 }
4149
4150 if (state->all_invariant && var->data.mode == ir_var_shader_out)
4151 var->data.invariant = true;
4152
4153 var->data.interpolation =
4154 interpret_interpolation_qualifier(qual, var->type,
4155 (ir_variable_mode) var->data.mode,
4156 state, loc);
4157
4158 /* Does the declaration use the deprecated 'attribute' or 'varying'
4159 * keywords?
4160 */
4161 const bool uses_deprecated_qualifier = qual->flags.q.attribute
4162 || qual->flags.q.varying;
4163
4164
4165 /* Validate auxiliary storage qualifiers */
4166
4167 /* From section 4.3.4 of the GLSL 1.30 spec:
4168 * "It is an error to use centroid in in a vertex shader."
4169 *
4170 * From section 4.3.4 of the GLSL ES 3.00 spec:
4171 * "It is an error to use centroid in or interpolation qualifiers in
4172 * a vertex shader input."
4173 */
4174
4175 /* Section 4.3.6 of the GLSL 1.30 specification states:
4176 * "It is an error to use centroid out in a fragment shader."
4177 *
4178 * The GL_ARB_shading_language_420pack extension specification states:
4179 * "It is an error to use auxiliary storage qualifiers or interpolation
4180 * qualifiers on an output in a fragment shader."
4181 */
4182 if (qual->flags.q.sample && (!is_varying_var(var, state->stage) || uses_deprecated_qualifier)) {
4183 _mesa_glsl_error(loc, state,
4184 "sample qualifier may only be used on `in` or `out` "
4185 "variables between shader stages");
4186 }
4187 if (qual->flags.q.centroid && !is_varying_var(var, state->stage)) {
4188 _mesa_glsl_error(loc, state,
4189 "centroid qualifier may only be used with `in', "
4190 "`out' or `varying' variables between shader stages");
4191 }
4192
4193 if (qual->flags.q.shared_storage && state->stage != MESA_SHADER_COMPUTE) {
4194 _mesa_glsl_error(loc, state,
4195 "the shared storage qualifiers can only be used with "
4196 "compute shaders");
4197 }
4198
4199 apply_image_qualifier_to_variable(qual, var, state, loc);
4200 }
4201
4202 /**
4203 * Get the variable that is being redeclared by this declaration or if it
4204 * does not exist, the current declared variable.
4205 *
4206 * Semantic checks to verify the validity of the redeclaration are also
4207 * performed. If semantic checks fail, compilation error will be emitted via
4208 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
4209 *
4210 * \returns
4211 * A pointer to an existing variable in the current scope if the declaration
4212 * is a redeclaration, current variable otherwise. \c is_declared boolean
4213 * will return \c true if the declaration is a redeclaration, \c false
4214 * otherwise.
4215 */
4216 static ir_variable *
4217 get_variable_being_redeclared(ir_variable **var_ptr, YYLTYPE loc,
4218 struct _mesa_glsl_parse_state *state,
4219 bool allow_all_redeclarations,
4220 bool *is_redeclaration)
4221 {
4222 ir_variable *var = *var_ptr;
4223
4224 /* Check if this declaration is actually a re-declaration, either to
4225 * resize an array or add qualifiers to an existing variable.
4226 *
4227 * This is allowed for variables in the current scope, or when at
4228 * global scope (for built-ins in the implicit outer scope).
4229 */
4230 ir_variable *earlier = state->symbols->get_variable(var->name);
4231 if (earlier == NULL ||
4232 (state->current_function != NULL &&
4233 !state->symbols->name_declared_this_scope(var->name))) {
4234 *is_redeclaration = false;
4235 return var;
4236 }
4237
4238 *is_redeclaration = true;
4239
4240 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
4241 *
4242 * "It is legal to declare an array without a size and then
4243 * later re-declare the same name as an array of the same
4244 * type and specify a size."
4245 */
4246 if (earlier->type->is_unsized_array() && var->type->is_array()
4247 && (var->type->fields.array == earlier->type->fields.array)) {
4248 /* FINISHME: This doesn't match the qualifiers on the two
4249 * FINISHME: declarations. It's not 100% clear whether this is
4250 * FINISHME: required or not.
4251 */
4252
4253 const int size = var->type->array_size();
4254 check_builtin_array_max_size(var->name, size, loc, state);
4255 if ((size > 0) && (size <= earlier->data.max_array_access)) {
4256 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
4257 "previous access",
4258 earlier->data.max_array_access);
4259 }
4260
4261 earlier->type = var->type;
4262 delete var;
4263 var = NULL;
4264 *var_ptr = NULL;
4265 } else if ((state->ARB_fragment_coord_conventions_enable ||
4266 state->is_version(150, 0))
4267 && strcmp(var->name, "gl_FragCoord") == 0
4268 && earlier->type == var->type
4269 && var->data.mode == ir_var_shader_in) {
4270 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
4271 * qualifiers.
4272 */
4273 earlier->data.origin_upper_left = var->data.origin_upper_left;
4274 earlier->data.pixel_center_integer = var->data.pixel_center_integer;
4275
4276 /* According to section 4.3.7 of the GLSL 1.30 spec,
4277 * the following built-in varaibles can be redeclared with an
4278 * interpolation qualifier:
4279 * * gl_FrontColor
4280 * * gl_BackColor
4281 * * gl_FrontSecondaryColor
4282 * * gl_BackSecondaryColor
4283 * * gl_Color
4284 * * gl_SecondaryColor
4285 */
4286 } else if (state->is_version(130, 0)
4287 && (strcmp(var->name, "gl_FrontColor") == 0
4288 || strcmp(var->name, "gl_BackColor") == 0
4289 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
4290 || strcmp(var->name, "gl_BackSecondaryColor") == 0
4291 || strcmp(var->name, "gl_Color") == 0
4292 || strcmp(var->name, "gl_SecondaryColor") == 0)
4293 && earlier->type == var->type
4294 && earlier->data.mode == var->data.mode) {
4295 earlier->data.interpolation = var->data.interpolation;
4296
4297 /* Layout qualifiers for gl_FragDepth. */
4298 } else if ((state->is_version(420, 0) ||
4299 state->AMD_conservative_depth_enable ||
4300 state->ARB_conservative_depth_enable)
4301 && strcmp(var->name, "gl_FragDepth") == 0
4302 && earlier->type == var->type
4303 && earlier->data.mode == var->data.mode) {
4304
4305 /** From the AMD_conservative_depth spec:
4306 * Within any shader, the first redeclarations of gl_FragDepth
4307 * must appear before any use of gl_FragDepth.
4308 */
4309 if (earlier->data.used) {
4310 _mesa_glsl_error(&loc, state,
4311 "the first redeclaration of gl_FragDepth "
4312 "must appear before any use of gl_FragDepth");
4313 }
4314
4315 /* Prevent inconsistent redeclaration of depth layout qualifier. */
4316 if (earlier->data.depth_layout != ir_depth_layout_none
4317 && earlier->data.depth_layout != var->data.depth_layout) {
4318 _mesa_glsl_error(&loc, state,
4319 "gl_FragDepth: depth layout is declared here "
4320 "as '%s, but it was previously declared as "
4321 "'%s'",
4322 depth_layout_string(var->data.depth_layout),
4323 depth_layout_string(earlier->data.depth_layout));
4324 }
4325
4326 earlier->data.depth_layout = var->data.depth_layout;
4327
4328 } else if (state->has_framebuffer_fetch() &&
4329 strcmp(var->name, "gl_LastFragData") == 0 &&
4330 var->type == earlier->type &&
4331 var->data.mode == ir_var_auto) {
4332 /* According to the EXT_shader_framebuffer_fetch spec:
4333 *
4334 * "By default, gl_LastFragData is declared with the mediump precision
4335 * qualifier. This can be changed by redeclaring the corresponding
4336 * variables with the desired precision qualifier."
4337 *
4338 * "Fragment shaders may specify the following layout qualifier only for
4339 * redeclaring the built-in gl_LastFragData array [...]: noncoherent"
4340 */
4341 earlier->data.precision = var->data.precision;
4342 earlier->data.memory_coherent = var->data.memory_coherent;
4343
4344 } else if (earlier->data.how_declared == ir_var_declared_implicitly &&
4345 state->allow_builtin_variable_redeclaration) {
4346 /* Allow verbatim redeclarations of built-in variables. Not explicitly
4347 * valid, but some applications do it.
4348 */
4349 if (earlier->data.mode != var->data.mode &&
4350 !(earlier->data.mode == ir_var_system_value &&
4351 var->data.mode == ir_var_shader_in)) {
4352 _mesa_glsl_error(&loc, state,
4353 "redeclaration of `%s' with incorrect qualifiers",
4354 var->name);
4355 } else if (earlier->type != var->type) {
4356 _mesa_glsl_error(&loc, state,
4357 "redeclaration of `%s' has incorrect type",
4358 var->name);
4359 }
4360 } else if (allow_all_redeclarations) {
4361 if (earlier->data.mode != var->data.mode) {
4362 _mesa_glsl_error(&loc, state,
4363 "redeclaration of `%s' with incorrect qualifiers",
4364 var->name);
4365 } else if (earlier->type != var->type) {
4366 _mesa_glsl_error(&loc, state,
4367 "redeclaration of `%s' has incorrect type",
4368 var->name);
4369 }
4370 } else {
4371 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
4372 }
4373
4374 return earlier;
4375 }
4376
4377 /**
4378 * Generate the IR for an initializer in a variable declaration
4379 */
4380 static ir_rvalue *
4381 process_initializer(ir_variable *var, ast_declaration *decl,
4382 ast_fully_specified_type *type,
4383 exec_list *initializer_instructions,
4384 struct _mesa_glsl_parse_state *state)
4385 {
4386 void *mem_ctx = state;
4387 ir_rvalue *result = NULL;
4388
4389 YYLTYPE initializer_loc = decl->initializer->get_location();
4390
4391 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
4392 *
4393 * "All uniform variables are read-only and are initialized either
4394 * directly by an application via API commands, or indirectly by
4395 * OpenGL."
4396 */
4397 if (var->data.mode == ir_var_uniform) {
4398 state->check_version(120, 0, &initializer_loc,
4399 "cannot initialize uniform %s",
4400 var->name);
4401 }
4402
4403 /* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:
4404 *
4405 * "Buffer variables cannot have initializers."
4406 */
4407 if (var->data.mode == ir_var_shader_storage) {
4408 _mesa_glsl_error(&initializer_loc, state,
4409 "cannot initialize buffer variable %s",
4410 var->name);
4411 }
4412
4413 /* From section 4.1.7 of the GLSL 4.40 spec:
4414 *
4415 * "Opaque variables [...] are initialized only through the
4416 * OpenGL API; they cannot be declared with an initializer in a
4417 * shader."
4418 *
4419 * From section 4.1.7 of the ARB_bindless_texture spec:
4420 *
4421 * "Samplers may be declared as shader inputs and outputs, as uniform
4422 * variables, as temporary variables, and as function parameters."
4423 *
4424 * From section 4.1.X of the ARB_bindless_texture spec:
4425 *
4426 * "Images may be declared as shader inputs and outputs, as uniform
4427 * variables, as temporary variables, and as function parameters."
4428 */
4429 if (var->type->contains_atomic() ||
4430 (!state->has_bindless() && var->type->contains_opaque())) {
4431 _mesa_glsl_error(&initializer_loc, state,
4432 "cannot initialize %s variable %s",
4433 var->name, state->has_bindless() ? "atomic" : "opaque");
4434 }
4435
4436 if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {
4437 _mesa_glsl_error(&initializer_loc, state,
4438 "cannot initialize %s shader input / %s %s",
4439 _mesa_shader_stage_to_string(state->stage),
4440 (state->stage == MESA_SHADER_VERTEX)
4441 ? "attribute" : "varying",
4442 var->name);
4443 }
4444
4445 if (var->data.mode == ir_var_shader_out && state->current_function == NULL) {
4446 _mesa_glsl_error(&initializer_loc, state,
4447 "cannot initialize %s shader output %s",
4448 _mesa_shader_stage_to_string(state->stage),
4449 var->name);
4450 }
4451
4452 /* If the initializer is an ast_aggregate_initializer, recursively store
4453 * type information from the LHS into it, so that its hir() function can do
4454 * type checking.
4455 */
4456 if (decl->initializer->oper == ast_aggregate)
4457 _mesa_ast_set_aggregate_type(var->type, decl->initializer);
4458
4459 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
4460 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions, state);
4461
4462 /* Calculate the constant value if this is a const or uniform
4463 * declaration.
4464 *
4465 * Section 4.3 (Storage Qualifiers) of the GLSL ES 1.00.17 spec says:
4466 *
4467 * "Declarations of globals without a storage qualifier, or with
4468 * just the const qualifier, may include initializers, in which case
4469 * they will be initialized before the first line of main() is
4470 * executed. Such initializers must be a constant expression."
4471 *
4472 * The same section of the GLSL ES 3.00.4 spec has similar language.
4473 */
4474 if (type->qualifier.flags.q.constant
4475 || type->qualifier.flags.q.uniform
4476 || (state->es_shader && state->current_function == NULL)) {
4477 ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,
4478 lhs, rhs, true);
4479 if (new_rhs != NULL) {
4480 rhs = new_rhs;
4481
4482 /* Section 4.3.3 (Constant Expressions) of the GLSL ES 3.00.4 spec
4483 * says:
4484 *
4485 * "A constant expression is one of
4486 *
4487 * ...
4488 *
4489 * - an expression formed by an operator on operands that are
4490 * all constant expressions, including getting an element of
4491 * a constant array, or a field of a constant structure, or
4492 * components of a constant vector. However, the sequence
4493 * operator ( , ) and the assignment operators ( =, +=, ...)
4494 * are not included in the operators that can create a
4495 * constant expression."
4496 *
4497 * Section 12.43 (Sequence operator and constant expressions) says:
4498 *
4499 * "Should the following construct be allowed?
4500 *
4501 * float a[2,3];
4502 *
4503 * The expression within the brackets uses the sequence operator
4504 * (',') and returns the integer 3 so the construct is declaring
4505 * a single-dimensional array of size 3. In some languages, the
4506 * construct declares a two-dimensional array. It would be
4507 * preferable to make this construct illegal to avoid confusion.
4508 *
4509 * One possibility is to change the definition of the sequence
4510 * operator so that it does not return a constant-expression and
4511 * hence cannot be used to declare an array size.
4512 *
4513 * RESOLUTION: The result of a sequence operator is not a
4514 * constant-expression."
4515 *
4516 * Section 4.3.3 (Constant Expressions) of the GLSL 4.30.9 spec
4517 * contains language almost identical to the section 4.3.3 in the
4518 * GLSL ES 3.00.4 spec. This is a new limitation for these GLSL
4519 * versions.
4520 */
4521 ir_constant *constant_value =
4522 rhs->constant_expression_value(mem_ctx);
4523
4524 if (!constant_value ||
4525 (state->is_version(430, 300) &&
4526 decl->initializer->has_sequence_subexpression())) {
4527 const char *const variable_mode =
4528 (type->qualifier.flags.q.constant)
4529 ? "const"
4530 : ((type->qualifier.flags.q.uniform) ? "uniform" : "global");
4531
4532 /* If ARB_shading_language_420pack is enabled, initializers of
4533 * const-qualified local variables do not have to be constant
4534 * expressions. Const-qualified global variables must still be
4535 * initialized with constant expressions.
4536 */
4537 if (!state->has_420pack()
4538 || state->current_function == NULL) {
4539 _mesa_glsl_error(& initializer_loc, state,
4540 "initializer of %s variable `%s' must be a "
4541 "constant expression",
4542 variable_mode,
4543 decl->identifier);
4544 if (var->type->is_numeric()) {
4545 /* Reduce cascading errors. */
4546 var->constant_value = type->qualifier.flags.q.constant
4547 ? ir_constant::zero(state, var->type) : NULL;
4548 }
4549 }
4550 } else {
4551 rhs = constant_value;
4552 var->constant_value = type->qualifier.flags.q.constant
4553 ? constant_value : NULL;
4554 }
4555 } else {
4556 if (var->type->is_numeric()) {
4557 /* Reduce cascading errors. */
4558 rhs = var->constant_value = type->qualifier.flags.q.constant
4559 ? ir_constant::zero(state, var->type) : NULL;
4560 }
4561 }
4562 }
4563
4564 if (rhs && !rhs->type->is_error()) {
4565 bool temp = var->data.read_only;
4566 if (type->qualifier.flags.q.constant)
4567 var->data.read_only = false;
4568
4569 /* Never emit code to initialize a uniform.
4570 */
4571 const glsl_type *initializer_type;
4572 bool error_emitted = false;
4573 if (!type->qualifier.flags.q.uniform) {
4574 error_emitted =
4575 do_assignment(initializer_instructions, state,
4576 NULL, lhs, rhs,
4577 &result, true, true,
4578 type->get_location());
4579 initializer_type = result->type;
4580 } else
4581 initializer_type = rhs->type;
4582
4583 if (!error_emitted) {
4584 var->constant_initializer = rhs->constant_expression_value(mem_ctx);
4585 var->data.has_initializer = true;
4586
4587 /* If the declared variable is an unsized array, it must inherrit
4588 * its full type from the initializer. A declaration such as
4589 *
4590 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
4591 *
4592 * becomes
4593 *
4594 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
4595 *
4596 * The assignment generated in the if-statement (below) will also
4597 * automatically handle this case for non-uniforms.
4598 *
4599 * If the declared variable is not an array, the types must
4600 * already match exactly. As a result, the type assignment
4601 * here can be done unconditionally. For non-uniforms the call
4602 * to do_assignment can change the type of the initializer (via
4603 * the implicit conversion rules). For uniforms the initializer
4604 * must be a constant expression, and the type of that expression
4605 * was validated above.
4606 */
4607 var->type = initializer_type;
4608 }
4609
4610 var->data.read_only = temp;
4611 }
4612
4613 return result;
4614 }
4615
4616 static void
4617 validate_layout_qualifier_vertex_count(struct _mesa_glsl_parse_state *state,
4618 YYLTYPE loc, ir_variable *var,
4619 unsigned num_vertices,
4620 unsigned *size,
4621 const char *var_category)
4622 {
4623 if (var->type->is_unsized_array()) {
4624 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:
4625 *
4626 * All geometry shader input unsized array declarations will be
4627 * sized by an earlier input layout qualifier, when present, as per
4628 * the following table.
4629 *
4630 * Followed by a table mapping each allowed input layout qualifier to
4631 * the corresponding input length.
4632 *
4633 * Similarly for tessellation control shader outputs.
4634 */
4635 if (num_vertices != 0)
4636 var->type = glsl_type::get_array_instance(var->type->fields.array,
4637 num_vertices);
4638 } else {
4639 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec
4640 * includes the following examples of compile-time errors:
4641 *
4642 * // code sequence within one shader...
4643 * in vec4 Color1[]; // size unknown
4644 * ...Color1.length()...// illegal, length() unknown
4645 * in vec4 Color2[2]; // size is 2
4646 * ...Color1.length()...// illegal, Color1 still has no size
4647 * in vec4 Color3[3]; // illegal, input sizes are inconsistent
4648 * layout(lines) in; // legal, input size is 2, matching
4649 * in vec4 Color4[3]; // illegal, contradicts layout
4650 * ...
4651 *
4652 * To detect the case illustrated by Color3, we verify that the size of
4653 * an explicitly-sized array matches the size of any previously declared
4654 * explicitly-sized array. To detect the case illustrated by Color4, we
4655 * verify that the size of an explicitly-sized array is consistent with
4656 * any previously declared input layout.
4657 */
4658 if (num_vertices != 0 && var->type->length != num_vertices) {
4659 _mesa_glsl_error(&loc, state,
4660 "%s size contradicts previously declared layout "
4661 "(size is %u, but layout requires a size of %u)",
4662 var_category, var->type->length, num_vertices);
4663 } else if (*size != 0 && var->type->length != *size) {
4664 _mesa_glsl_error(&loc, state,
4665 "%s sizes are inconsistent (size is %u, but a "
4666 "previous declaration has size %u)",
4667 var_category, var->type->length, *size);
4668 } else {
4669 *size = var->type->length;
4670 }
4671 }
4672 }
4673
4674 static void
4675 handle_tess_ctrl_shader_output_decl(struct _mesa_glsl_parse_state *state,
4676 YYLTYPE loc, ir_variable *var)
4677 {
4678 unsigned num_vertices = 0;
4679
4680 if (state->tcs_output_vertices_specified) {
4681 if (!state->out_qualifier->vertices->
4682 process_qualifier_constant(state, "vertices",
4683 &num_vertices, false)) {
4684 return;
4685 }
4686
4687 if (num_vertices > state->Const.MaxPatchVertices) {
4688 _mesa_glsl_error(&loc, state, "vertices (%d) exceeds "
4689 "GL_MAX_PATCH_VERTICES", num_vertices);
4690 return;
4691 }
4692 }
4693
4694 if (!var->type->is_array() && !var->data.patch) {
4695 _mesa_glsl_error(&loc, state,
4696 "tessellation control shader outputs must be arrays");
4697
4698 /* To avoid cascading failures, short circuit the checks below. */
4699 return;
4700 }
4701
4702 if (var->data.patch)
4703 return;
4704
4705 validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,
4706 &state->tcs_output_size,
4707 "tessellation control shader output");
4708 }
4709
4710 /**
4711 * Do additional processing necessary for tessellation control/evaluation shader
4712 * input declarations. This covers both interface block arrays and bare input
4713 * variables.
4714 */
4715 static void
4716 handle_tess_shader_input_decl(struct _mesa_glsl_parse_state *state,
4717 YYLTYPE loc, ir_variable *var)
4718 {
4719 if (!var->type->is_array() && !var->data.patch) {
4720 _mesa_glsl_error(&loc, state,
4721 "per-vertex tessellation shader inputs must be arrays");
4722 /* Avoid cascading failures. */
4723 return;
4724 }
4725
4726 if (var->data.patch)
4727 return;
4728
4729 /* The ARB_tessellation_shader spec says:
4730 *
4731 * "Declaring an array size is optional. If no size is specified, it
4732 * will be taken from the implementation-dependent maximum patch size
4733 * (gl_MaxPatchVertices). If a size is specified, it must match the
4734 * maximum patch size; otherwise, a compile or link error will occur."
4735 *
4736 * This text appears twice, once for TCS inputs, and again for TES inputs.
4737 */
4738 if (var->type->is_unsized_array()) {
4739 var->type = glsl_type::get_array_instance(var->type->fields.array,
4740 state->Const.MaxPatchVertices);
4741 } else if (var->type->length != state->Const.MaxPatchVertices) {
4742 _mesa_glsl_error(&loc, state,
4743 "per-vertex tessellation shader input arrays must be "
4744 "sized to gl_MaxPatchVertices (%d).",
4745 state->Const.MaxPatchVertices);
4746 }
4747 }
4748
4749
4750 /**
4751 * Do additional processing necessary for geometry shader input declarations
4752 * (this covers both interface blocks arrays and bare input variables).
4753 */
4754 static void
4755 handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,
4756 YYLTYPE loc, ir_variable *var)
4757 {
4758 unsigned num_vertices = 0;
4759
4760 if (state->gs_input_prim_type_specified) {
4761 num_vertices = vertices_per_prim(state->in_qualifier->prim_type);
4762 }
4763
4764 /* Geometry shader input variables must be arrays. Caller should have
4765 * reported an error for this.
4766 */
4767 if (!var->type->is_array()) {
4768 assert(state->error);
4769
4770 /* To avoid cascading failures, short circuit the checks below. */
4771 return;
4772 }
4773
4774 validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,
4775 &state->gs_input_size,
4776 "geometry shader input");
4777 }
4778
4779 static void
4780 validate_identifier(const char *identifier, YYLTYPE loc,
4781 struct _mesa_glsl_parse_state *state)
4782 {
4783 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
4784 *
4785 * "Identifiers starting with "gl_" are reserved for use by
4786 * OpenGL, and may not be declared in a shader as either a
4787 * variable or a function."
4788 */
4789 if (is_gl_identifier(identifier)) {
4790 _mesa_glsl_error(&loc, state,
4791 "identifier `%s' uses reserved `gl_' prefix",
4792 identifier);
4793 } else if (strstr(identifier, "__")) {
4794 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
4795 * spec:
4796 *
4797 * "In addition, all identifiers containing two
4798 * consecutive underscores (__) are reserved as
4799 * possible future keywords."
4800 *
4801 * The intention is that names containing __ are reserved for internal
4802 * use by the implementation, and names prefixed with GL_ are reserved
4803 * for use by Khronos. Names simply containing __ are dangerous to use,
4804 * but should be allowed.
4805 *
4806 * A future version of the GLSL specification will clarify this.
4807 */
4808 _mesa_glsl_warning(&loc, state,
4809 "identifier `%s' uses reserved `__' string",
4810 identifier);
4811 }
4812 }
4813
4814 ir_rvalue *
4815 ast_declarator_list::hir(exec_list *instructions,
4816 struct _mesa_glsl_parse_state *state)
4817 {
4818 void *ctx = state;
4819 const struct glsl_type *decl_type;
4820 const char *type_name = NULL;
4821 ir_rvalue *result = NULL;
4822 YYLTYPE loc = this->get_location();
4823
4824 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
4825 *
4826 * "To ensure that a particular output variable is invariant, it is
4827 * necessary to use the invariant qualifier. It can either be used to
4828 * qualify a previously declared variable as being invariant
4829 *
4830 * invariant gl_Position; // make existing gl_Position be invariant"
4831 *
4832 * In these cases the parser will set the 'invariant' flag in the declarator
4833 * list, and the type will be NULL.
4834 */
4835 if (this->invariant) {
4836 assert(this->type == NULL);
4837
4838 if (state->current_function != NULL) {
4839 _mesa_glsl_error(& loc, state,
4840 "all uses of `invariant' keyword must be at global "
4841 "scope");
4842 }
4843
4844 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
4845 assert(decl->array_specifier == NULL);
4846 assert(decl->initializer == NULL);
4847
4848 ir_variable *const earlier =
4849 state->symbols->get_variable(decl->identifier);
4850 if (earlier == NULL) {
4851 _mesa_glsl_error(& loc, state,
4852 "undeclared variable `%s' cannot be marked "
4853 "invariant", decl->identifier);
4854 } else if (!is_allowed_invariant(earlier, state)) {
4855 _mesa_glsl_error(&loc, state,
4856 "`%s' cannot be marked invariant; interfaces between "
4857 "shader stages only.", decl->identifier);
4858 } else if (earlier->data.used) {
4859 _mesa_glsl_error(& loc, state,
4860 "variable `%s' may not be redeclared "
4861 "`invariant' after being used",
4862 earlier->name);
4863 } else {
4864 earlier->data.invariant = true;
4865 }
4866 }
4867
4868 /* Invariant redeclarations do not have r-values.
4869 */
4870 return NULL;
4871 }
4872
4873 if (this->precise) {
4874 assert(this->type == NULL);
4875
4876 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
4877 assert(decl->array_specifier == NULL);
4878 assert(decl->initializer == NULL);
4879
4880 ir_variable *const earlier =
4881 state->symbols->get_variable(decl->identifier);
4882 if (earlier == NULL) {
4883 _mesa_glsl_error(& loc, state,
4884 "undeclared variable `%s' cannot be marked "
4885 "precise", decl->identifier);
4886 } else if (state->current_function != NULL &&
4887 !state->symbols->name_declared_this_scope(decl->identifier)) {
4888 /* Note: we have to check if we're in a function, since
4889 * builtins are treated as having come from another scope.
4890 */
4891 _mesa_glsl_error(& loc, state,
4892 "variable `%s' from an outer scope may not be "
4893 "redeclared `precise' in this scope",
4894 earlier->name);
4895 } else if (earlier->data.used) {
4896 _mesa_glsl_error(& loc, state,
4897 "variable `%s' may not be redeclared "
4898 "`precise' after being used",
4899 earlier->name);
4900 } else {
4901 earlier->data.precise = true;
4902 }
4903 }
4904
4905 /* Precise redeclarations do not have r-values either. */
4906 return NULL;
4907 }
4908
4909 assert(this->type != NULL);
4910 assert(!this->invariant);
4911 assert(!this->precise);
4912
4913 /* The type specifier may contain a structure definition. Process that
4914 * before any of the variable declarations.
4915 */
4916 (void) this->type->specifier->hir(instructions, state);
4917
4918 decl_type = this->type->glsl_type(& type_name, state);
4919
4920 /* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:
4921 * "Buffer variables may only be declared inside interface blocks
4922 * (section 4.3.9 “Interface Blocks”), which are then referred to as
4923 * shader storage blocks. It is a compile-time error to declare buffer
4924 * variables at global scope (outside a block)."
4925 */
4926 if (type->qualifier.flags.q.buffer && !decl_type->is_interface()) {
4927 _mesa_glsl_error(&loc, state,
4928 "buffer variables cannot be declared outside "
4929 "interface blocks");
4930 }
4931
4932 /* An offset-qualified atomic counter declaration sets the default
4933 * offset for the next declaration within the same atomic counter
4934 * buffer.
4935 */
4936 if (decl_type && decl_type->contains_atomic()) {
4937 if (type->qualifier.flags.q.explicit_binding &&
4938 type->qualifier.flags.q.explicit_offset) {
4939 unsigned qual_binding;
4940 unsigned qual_offset;
4941 if (process_qualifier_constant(state, &loc, "binding",
4942 type->qualifier.binding,
4943 &qual_binding)
4944 && process_qualifier_constant(state, &loc, "offset",
4945 type->qualifier.offset,
4946 &qual_offset)) {
4947 state->atomic_counter_offsets[qual_binding] = qual_offset;
4948 }
4949 }
4950
4951 ast_type_qualifier allowed_atomic_qual_mask;
4952 allowed_atomic_qual_mask.flags.i = 0;
4953 allowed_atomic_qual_mask.flags.q.explicit_binding = 1;
4954 allowed_atomic_qual_mask.flags.q.explicit_offset = 1;
4955 allowed_atomic_qual_mask.flags.q.uniform = 1;
4956
4957 type->qualifier.validate_flags(&loc, state, allowed_atomic_qual_mask,
4958 "invalid layout qualifier for",
4959 "atomic_uint");
4960 }
4961
4962 if (this->declarations.is_empty()) {
4963 /* If there is no structure involved in the program text, there are two
4964 * possible scenarios:
4965 *
4966 * - The program text contained something like 'vec4;'. This is an
4967 * empty declaration. It is valid but weird. Emit a warning.
4968 *
4969 * - The program text contained something like 'S;' and 'S' is not the
4970 * name of a known structure type. This is both invalid and weird.
4971 * Emit an error.
4972 *
4973 * - The program text contained something like 'mediump float;'
4974 * when the programmer probably meant 'precision mediump
4975 * float;' Emit a warning with a description of what they
4976 * probably meant to do.
4977 *
4978 * Note that if decl_type is NULL and there is a structure involved,
4979 * there must have been some sort of error with the structure. In this
4980 * case we assume that an error was already generated on this line of
4981 * code for the structure. There is no need to generate an additional,
4982 * confusing error.
4983 */
4984 assert(this->type->specifier->structure == NULL || decl_type != NULL
4985 || state->error);
4986
4987 if (decl_type == NULL) {
4988 _mesa_glsl_error(&loc, state,
4989 "invalid type `%s' in empty declaration",
4990 type_name);
4991 } else {
4992 if (decl_type->is_array()) {
4993 /* From Section 13.22 (Array Declarations) of the GLSL ES 3.2
4994 * spec:
4995 *
4996 * "... any declaration that leaves the size undefined is
4997 * disallowed as this would add complexity and there are no
4998 * use-cases."
4999 */
5000 if (state->es_shader && decl_type->is_unsized_array()) {
5001 _mesa_glsl_error(&loc, state, "array size must be explicitly "
5002 "or implicitly defined");
5003 }
5004
5005 /* From Section 4.12 (Empty Declarations) of the GLSL 4.5 spec:
5006 *
5007 * "The combinations of types and qualifiers that cause
5008 * compile-time or link-time errors are the same whether or not
5009 * the declaration is empty."
5010 */
5011 validate_array_dimensions(decl_type, state, &loc);
5012 }
5013
5014 if (decl_type->is_atomic_uint()) {
5015 /* Empty atomic counter declarations are allowed and useful
5016 * to set the default offset qualifier.
5017 */
5018 return NULL;
5019 } else if (this->type->qualifier.precision != ast_precision_none) {
5020 if (this->type->specifier->structure != NULL) {
5021 _mesa_glsl_error(&loc, state,
5022 "precision qualifiers can't be applied "
5023 "to structures");
5024 } else {
5025 static const char *const precision_names[] = {
5026 "highp",
5027 "highp",
5028 "mediump",
5029 "lowp"
5030 };
5031
5032 _mesa_glsl_warning(&loc, state,
5033 "empty declaration with precision "
5034 "qualifier, to set the default precision, "
5035 "use `precision %s %s;'",
5036 precision_names[this->type->
5037 qualifier.precision],
5038 type_name);
5039 }
5040 } else if (this->type->specifier->structure == NULL) {
5041 _mesa_glsl_warning(&loc, state, "empty declaration");
5042 }
5043 }
5044 }
5045
5046 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
5047 const struct glsl_type *var_type;
5048 ir_variable *var;
5049 const char *identifier = decl->identifier;
5050 /* FINISHME: Emit a warning if a variable declaration shadows a
5051 * FINISHME: declaration at a higher scope.
5052 */
5053
5054 if ((decl_type == NULL) || decl_type->is_void()) {
5055 if (type_name != NULL) {
5056 _mesa_glsl_error(& loc, state,
5057 "invalid type `%s' in declaration of `%s'",
5058 type_name, decl->identifier);
5059 } else {
5060 _mesa_glsl_error(& loc, state,
5061 "invalid type in declaration of `%s'",
5062 decl->identifier);
5063 }
5064 continue;
5065 }
5066
5067 if (this->type->qualifier.is_subroutine_decl()) {
5068 const glsl_type *t;
5069 const char *name;
5070
5071 t = state->symbols->get_type(this->type->specifier->type_name);
5072 if (!t)
5073 _mesa_glsl_error(& loc, state,
5074 "invalid type in declaration of `%s'",
5075 decl->identifier);
5076 name = ralloc_asprintf(ctx, "%s_%s", _mesa_shader_stage_to_subroutine_prefix(state->stage), decl->identifier);
5077
5078 identifier = name;
5079
5080 }
5081 var_type = process_array_type(&loc, decl_type, decl->array_specifier,
5082 state);
5083
5084 var = new(ctx) ir_variable(var_type, identifier, ir_var_auto);
5085
5086 /* The 'varying in' and 'varying out' qualifiers can only be used with
5087 * ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support
5088 * yet.
5089 */
5090 if (this->type->qualifier.flags.q.varying) {
5091 if (this->type->qualifier.flags.q.in) {
5092 _mesa_glsl_error(& loc, state,
5093 "`varying in' qualifier in declaration of "
5094 "`%s' only valid for geometry shaders using "
5095 "ARB_geometry_shader4 or EXT_geometry_shader4",
5096 decl->identifier);
5097 } else if (this->type->qualifier.flags.q.out) {
5098 _mesa_glsl_error(& loc, state,
5099 "`varying out' qualifier in declaration of "
5100 "`%s' only valid for geometry shaders using "
5101 "ARB_geometry_shader4 or EXT_geometry_shader4",
5102 decl->identifier);
5103 }
5104 }
5105
5106 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
5107 *
5108 * "Global variables can only use the qualifiers const,
5109 * attribute, uniform, or varying. Only one may be
5110 * specified.
5111 *
5112 * Local variables can only use the qualifier const."
5113 *
5114 * This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by
5115 * any extension that adds the 'layout' keyword.
5116 */
5117 if (!state->is_version(130, 300)
5118 && !state->has_explicit_attrib_location()
5119 && !state->has_separate_shader_objects()
5120 && !state->ARB_fragment_coord_conventions_enable) {
5121 if (this->type->qualifier.flags.q.out) {
5122 _mesa_glsl_error(& loc, state,
5123 "`out' qualifier in declaration of `%s' "
5124 "only valid for function parameters in %s",
5125 decl->identifier, state->get_version_string());
5126 }
5127 if (this->type->qualifier.flags.q.in) {
5128 _mesa_glsl_error(& loc, state,
5129 "`in' qualifier in declaration of `%s' "
5130 "only valid for function parameters in %s",
5131 decl->identifier, state->get_version_string());
5132 }
5133 /* FINISHME: Test for other invalid qualifiers. */
5134 }
5135
5136 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
5137 & loc, false);
5138 apply_layout_qualifier_to_variable(&this->type->qualifier, var, state,
5139 &loc);
5140
5141 if ((var->data.mode == ir_var_auto || var->data.mode == ir_var_temporary)
5142 && (var->type->is_numeric() || var->type->is_boolean())
5143 && state->zero_init) {
5144 const ir_constant_data data = { { 0 } };
5145 var->data.has_initializer = true;
5146 var->constant_initializer = new(var) ir_constant(var->type, &data);
5147 }
5148
5149 if (this->type->qualifier.flags.q.invariant) {
5150 if (!is_allowed_invariant(var, state)) {
5151 _mesa_glsl_error(&loc, state,
5152 "`%s' cannot be marked invariant; interfaces between "
5153 "shader stages only", var->name);
5154 }
5155 }
5156
5157 if (state->current_function != NULL) {
5158 const char *mode = NULL;
5159 const char *extra = "";
5160
5161 /* There is no need to check for 'inout' here because the parser will
5162 * only allow that in function parameter lists.
5163 */
5164 if (this->type->qualifier.flags.q.attribute) {
5165 mode = "attribute";
5166 } else if (this->type->qualifier.is_subroutine_decl()) {
5167 mode = "subroutine uniform";
5168 } else if (this->type->qualifier.flags.q.uniform) {
5169 mode = "uniform";
5170 } else if (this->type->qualifier.flags.q.varying) {
5171 mode = "varying";
5172 } else if (this->type->qualifier.flags.q.in) {
5173 mode = "in";
5174 extra = " or in function parameter list";
5175 } else if (this->type->qualifier.flags.q.out) {
5176 mode = "out";
5177 extra = " or in function parameter list";
5178 }
5179
5180 if (mode) {
5181 _mesa_glsl_error(& loc, state,
5182 "%s variable `%s' must be declared at "
5183 "global scope%s",
5184 mode, var->name, extra);
5185 }
5186 } else if (var->data.mode == ir_var_shader_in) {
5187 var->data.read_only = true;
5188
5189 if (state->stage == MESA_SHADER_VERTEX) {
5190 bool error_emitted = false;
5191
5192 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
5193 *
5194 * "Vertex shader inputs can only be float, floating-point
5195 * vectors, matrices, signed and unsigned integers and integer
5196 * vectors. Vertex shader inputs can also form arrays of these
5197 * types, but not structures."
5198 *
5199 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
5200 *
5201 * "Vertex shader inputs can only be float, floating-point
5202 * vectors, matrices, signed and unsigned integers and integer
5203 * vectors. They cannot be arrays or structures."
5204 *
5205 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
5206 *
5207 * "The attribute qualifier can be used only with float,
5208 * floating-point vectors, and matrices. Attribute variables
5209 * cannot be declared as arrays or structures."
5210 *
5211 * From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:
5212 *
5213 * "Vertex shader inputs can only be float, floating-point
5214 * vectors, matrices, signed and unsigned integers and integer
5215 * vectors. Vertex shader inputs cannot be arrays or
5216 * structures."
5217 *
5218 * From section 4.3.4 of the ARB_bindless_texture spec:
5219 *
5220 * "(modify third paragraph of the section to allow sampler and
5221 * image types) ... Vertex shader inputs can only be float,
5222 * single-precision floating-point scalars, single-precision
5223 * floating-point vectors, matrices, signed and unsigned
5224 * integers and integer vectors, sampler and image types."
5225 */
5226 const glsl_type *check_type = var->type->without_array();
5227
5228 switch (check_type->base_type) {
5229 case GLSL_TYPE_FLOAT:
5230 break;
5231 case GLSL_TYPE_UINT64:
5232 case GLSL_TYPE_INT64:
5233 break;
5234 case GLSL_TYPE_UINT:
5235 case GLSL_TYPE_INT:
5236 if (state->is_version(120, 300))
5237 break;
5238 case GLSL_TYPE_DOUBLE:
5239 if (check_type->is_double() && (state->is_version(410, 0) || state->ARB_vertex_attrib_64bit_enable))
5240 break;
5241 case GLSL_TYPE_SAMPLER:
5242 if (check_type->is_sampler() && state->has_bindless())
5243 break;
5244 case GLSL_TYPE_IMAGE:
5245 if (check_type->is_image() && state->has_bindless())
5246 break;
5247 /* FALLTHROUGH */
5248 default:
5249 _mesa_glsl_error(& loc, state,
5250 "vertex shader input / attribute cannot have "
5251 "type %s`%s'",
5252 var->type->is_array() ? "array of " : "",
5253 check_type->name);
5254 error_emitted = true;
5255 }
5256
5257 if (!error_emitted && var->type->is_array() &&
5258 !state->check_version(150, 0, &loc,
5259 "vertex shader input / attribute "
5260 "cannot have array type")) {
5261 error_emitted = true;
5262 }
5263 } else if (state->stage == MESA_SHADER_GEOMETRY) {
5264 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
5265 *
5266 * Geometry shader input variables get the per-vertex values
5267 * written out by vertex shader output variables of the same
5268 * names. Since a geometry shader operates on a set of
5269 * vertices, each input varying variable (or input block, see
5270 * interface blocks below) needs to be declared as an array.
5271 */
5272 if (!var->type->is_array()) {
5273 _mesa_glsl_error(&loc, state,
5274 "geometry shader inputs must be arrays");
5275 }
5276
5277 handle_geometry_shader_input_decl(state, loc, var);
5278 } else if (state->stage == MESA_SHADER_FRAGMENT) {
5279 /* From section 4.3.4 (Input Variables) of the GLSL ES 3.10 spec:
5280 *
5281 * It is a compile-time error to declare a fragment shader
5282 * input with, or that contains, any of the following types:
5283 *
5284 * * A boolean type
5285 * * An opaque type
5286 * * An array of arrays
5287 * * An array of structures
5288 * * A structure containing an array
5289 * * A structure containing a structure
5290 */
5291 if (state->es_shader) {
5292 const glsl_type *check_type = var->type->without_array();
5293 if (check_type->is_boolean() ||
5294 check_type->contains_opaque()) {
5295 _mesa_glsl_error(&loc, state,
5296 "fragment shader input cannot have type %s",
5297 check_type->name);
5298 }
5299 if (var->type->is_array() &&
5300 var->type->fields.array->is_array()) {
5301 _mesa_glsl_error(&loc, state,
5302 "%s shader output "
5303 "cannot have an array of arrays",
5304 _mesa_shader_stage_to_string(state->stage));
5305 }
5306 if (var->type->is_array() &&
5307 var->type->fields.array->is_record()) {
5308 _mesa_glsl_error(&loc, state,
5309 "fragment shader input "
5310 "cannot have an array of structs");
5311 }
5312 if (var->type->is_record()) {
5313 for (unsigned i = 0; i < var->type->length; i++) {
5314 if (var->type->fields.structure[i].type->is_array() ||
5315 var->type->fields.structure[i].type->is_record())
5316 _mesa_glsl_error(&loc, state,
5317 "fragment shader input cannot have "
5318 "a struct that contains an "
5319 "array or struct");
5320 }
5321 }
5322 }
5323 } else if (state->stage == MESA_SHADER_TESS_CTRL ||
5324 state->stage == MESA_SHADER_TESS_EVAL) {
5325 handle_tess_shader_input_decl(state, loc, var);
5326 }
5327 } else if (var->data.mode == ir_var_shader_out) {
5328 const glsl_type *check_type = var->type->without_array();
5329
5330 /* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:
5331 *
5332 * It is a compile-time error to declare a fragment shader output
5333 * that contains any of the following:
5334 *
5335 * * A Boolean type (bool, bvec2 ...)
5336 * * A double-precision scalar or vector (double, dvec2 ...)
5337 * * An opaque type
5338 * * Any matrix type
5339 * * A structure
5340 */
5341 if (state->stage == MESA_SHADER_FRAGMENT) {
5342 if (check_type->is_record() || check_type->is_matrix())
5343 _mesa_glsl_error(&loc, state,
5344 "fragment shader output "
5345 "cannot have struct or matrix type");
5346 switch (check_type->base_type) {
5347 case GLSL_TYPE_UINT:
5348 case GLSL_TYPE_INT:
5349 case GLSL_TYPE_FLOAT:
5350 break;
5351 default:
5352 _mesa_glsl_error(&loc, state,
5353 "fragment shader output cannot have "
5354 "type %s", check_type->name);
5355 }
5356 }
5357
5358 /* From section 4.3.6 (Output Variables) of the GLSL ES 3.10 spec:
5359 *
5360 * It is a compile-time error to declare a vertex shader output
5361 * with, or that contains, any of the following types:
5362 *
5363 * * A boolean type
5364 * * An opaque type
5365 * * An array of arrays
5366 * * An array of structures
5367 * * A structure containing an array
5368 * * A structure containing a structure
5369 *
5370 * It is a compile-time error to declare a fragment shader output
5371 * with, or that contains, any of the following types:
5372 *
5373 * * A boolean type
5374 * * An opaque type
5375 * * A matrix
5376 * * A structure
5377 * * An array of array
5378 *
5379 * ES 3.20 updates this to apply to tessellation and geometry shaders
5380 * as well. Because there are per-vertex arrays in the new stages,
5381 * it strikes the "array of..." rules and replaces them with these:
5382 *
5383 * * For per-vertex-arrayed variables (applies to tessellation
5384 * control, tessellation evaluation and geometry shaders):
5385 *
5386 * * Per-vertex-arrayed arrays of arrays
5387 * * Per-vertex-arrayed arrays of structures
5388 *
5389 * * For non-per-vertex-arrayed variables:
5390 *
5391 * * An array of arrays
5392 * * An array of structures
5393 *
5394 * which basically says to unwrap the per-vertex aspect and apply
5395 * the old rules.
5396 */
5397 if (state->es_shader) {
5398 if (var->type->is_array() &&
5399 var->type->fields.array->is_array()) {
5400 _mesa_glsl_error(&loc, state,
5401 "%s shader output "
5402 "cannot have an array of arrays",
5403 _mesa_shader_stage_to_string(state->stage));
5404 }
5405 if (state->stage <= MESA_SHADER_GEOMETRY) {
5406 const glsl_type *type = var->type;
5407
5408 if (state->stage == MESA_SHADER_TESS_CTRL &&
5409 !var->data.patch && var->type->is_array()) {
5410 type = var->type->fields.array;
5411 }
5412
5413 if (type->is_array() && type->fields.array->is_record()) {
5414 _mesa_glsl_error(&loc, state,
5415 "%s shader output cannot have "
5416 "an array of structs",
5417 _mesa_shader_stage_to_string(state->stage));
5418 }
5419 if (type->is_record()) {
5420 for (unsigned i = 0; i < type->length; i++) {
5421 if (type->fields.structure[i].type->is_array() ||
5422 type->fields.structure[i].type->is_record())
5423 _mesa_glsl_error(&loc, state,
5424 "%s shader output cannot have a "
5425 "struct that contains an "
5426 "array or struct",
5427 _mesa_shader_stage_to_string(state->stage));
5428 }
5429 }
5430 }
5431 }
5432
5433 if (state->stage == MESA_SHADER_TESS_CTRL) {
5434 handle_tess_ctrl_shader_output_decl(state, loc, var);
5435 }
5436 } else if (var->type->contains_subroutine()) {
5437 /* declare subroutine uniforms as hidden */
5438 var->data.how_declared = ir_var_hidden;
5439 }
5440
5441 /* From section 4.3.4 of the GLSL 4.00 spec:
5442 * "Input variables may not be declared using the patch in qualifier
5443 * in tessellation control or geometry shaders."
5444 *
5445 * From section 4.3.6 of the GLSL 4.00 spec:
5446 * "It is an error to use patch out in a vertex, tessellation
5447 * evaluation, or geometry shader."
5448 *
5449 * This doesn't explicitly forbid using them in a fragment shader, but
5450 * that's probably just an oversight.
5451 */
5452 if (state->stage != MESA_SHADER_TESS_EVAL
5453 && this->type->qualifier.flags.q.patch
5454 && this->type->qualifier.flags.q.in) {
5455
5456 _mesa_glsl_error(&loc, state, "'patch in' can only be used in a "
5457 "tessellation evaluation shader");
5458 }
5459
5460 if (state->stage != MESA_SHADER_TESS_CTRL
5461 && this->type->qualifier.flags.q.patch
5462 && this->type->qualifier.flags.q.out) {
5463
5464 _mesa_glsl_error(&loc, state, "'patch out' can only be used in a "
5465 "tessellation control shader");
5466 }
5467
5468 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
5469 */
5470 if (this->type->qualifier.precision != ast_precision_none) {
5471 state->check_precision_qualifiers_allowed(&loc);
5472 }
5473
5474 if (this->type->qualifier.precision != ast_precision_none &&
5475 !precision_qualifier_allowed(var->type)) {
5476 _mesa_glsl_error(&loc, state,
5477 "precision qualifiers apply only to floating point"
5478 ", integer and opaque types");
5479 }
5480
5481 /* From section 4.1.7 of the GLSL 4.40 spec:
5482 *
5483 * "[Opaque types] can only be declared as function
5484 * parameters or uniform-qualified variables."
5485 *
5486 * From section 4.1.7 of the ARB_bindless_texture spec:
5487 *
5488 * "Samplers may be declared as shader inputs and outputs, as uniform
5489 * variables, as temporary variables, and as function parameters."
5490 *
5491 * From section 4.1.X of the ARB_bindless_texture spec:
5492 *
5493 * "Images may be declared as shader inputs and outputs, as uniform
5494 * variables, as temporary variables, and as function parameters."
5495 */
5496 if (!this->type->qualifier.flags.q.uniform &&
5497 (var_type->contains_atomic() ||
5498 (!state->has_bindless() && var_type->contains_opaque()))) {
5499 _mesa_glsl_error(&loc, state,
5500 "%s variables must be declared uniform",
5501 state->has_bindless() ? "atomic" : "opaque");
5502 }
5503
5504 /* Process the initializer and add its instructions to a temporary
5505 * list. This list will be added to the instruction stream (below) after
5506 * the declaration is added. This is done because in some cases (such as
5507 * redeclarations) the declaration may not actually be added to the
5508 * instruction stream.
5509 */
5510 exec_list initializer_instructions;
5511
5512 /* Examine var name here since var may get deleted in the next call */
5513 bool var_is_gl_id = is_gl_identifier(var->name);
5514
5515 bool is_redeclaration;
5516 var = get_variable_being_redeclared(&var, decl->get_location(), state,
5517 false /* allow_all_redeclarations */,
5518 &is_redeclaration);
5519 if (is_redeclaration) {
5520 if (var_is_gl_id &&
5521 var->data.how_declared == ir_var_declared_in_block) {
5522 _mesa_glsl_error(&loc, state,
5523 "`%s' has already been redeclared using "
5524 "gl_PerVertex", var->name);
5525 }
5526 var->data.how_declared = ir_var_declared_normally;
5527 }
5528
5529 if (decl->initializer != NULL) {
5530 result = process_initializer(var,
5531 decl, this->type,
5532 &initializer_instructions, state);
5533 } else {
5534 validate_array_dimensions(var_type, state, &loc);
5535 }
5536
5537 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
5538 *
5539 * "It is an error to write to a const variable outside of
5540 * its declaration, so they must be initialized when
5541 * declared."
5542 */
5543 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
5544 _mesa_glsl_error(& loc, state,
5545 "const declaration of `%s' must be initialized",
5546 decl->identifier);
5547 }
5548
5549 if (state->es_shader) {
5550 const glsl_type *const t = var->type;
5551
5552 /* Skip the unsized array check for TCS/TES/GS inputs & TCS outputs.
5553 *
5554 * The GL_OES_tessellation_shader spec says about inputs:
5555 *
5556 * "Declaring an array size is optional. If no size is specified,
5557 * it will be taken from the implementation-dependent maximum
5558 * patch size (gl_MaxPatchVertices)."
5559 *
5560 * and about TCS outputs:
5561 *
5562 * "If no size is specified, it will be taken from output patch
5563 * size declared in the shader."
5564 *
5565 * The GL_OES_geometry_shader spec says:
5566 *
5567 * "All geometry shader input unsized array declarations will be
5568 * sized by an earlier input primitive layout qualifier, when
5569 * present, as per the following table."
5570 */
5571 const bool implicitly_sized =
5572 (var->data.mode == ir_var_shader_in &&
5573 state->stage >= MESA_SHADER_TESS_CTRL &&
5574 state->stage <= MESA_SHADER_GEOMETRY) ||
5575 (var->data.mode == ir_var_shader_out &&
5576 state->stage == MESA_SHADER_TESS_CTRL);
5577
5578 if (t->is_unsized_array() && !implicitly_sized)
5579 /* Section 10.17 of the GLSL ES 1.00 specification states that
5580 * unsized array declarations have been removed from the language.
5581 * Arrays that are sized using an initializer are still explicitly
5582 * sized. However, GLSL ES 1.00 does not allow array
5583 * initializers. That is only allowed in GLSL ES 3.00.
5584 *
5585 * Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:
5586 *
5587 * "An array type can also be formed without specifying a size
5588 * if the definition includes an initializer:
5589 *
5590 * float x[] = float[2] (1.0, 2.0); // declares an array of size 2
5591 * float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 3
5592 *
5593 * float a[5];
5594 * float b[] = a;"
5595 */
5596 _mesa_glsl_error(& loc, state,
5597 "unsized array declarations are not allowed in "
5598 "GLSL ES");
5599 }
5600
5601 /* Section 4.4.6.1 Atomic Counter Layout Qualifiers of the GLSL 4.60 spec:
5602 *
5603 * "It is a compile-time error to declare an unsized array of
5604 * atomic_uint"
5605 */
5606 if (var->type->is_unsized_array() &&
5607 var->type->without_array()->base_type == GLSL_TYPE_ATOMIC_UINT) {
5608 _mesa_glsl_error(& loc, state,
5609 "Unsized array of atomic_uint is not allowed");
5610 }
5611
5612 /* If the declaration is not a redeclaration, there are a few additional
5613 * semantic checks that must be applied. In addition, variable that was
5614 * created for the declaration should be added to the IR stream.
5615 */
5616 if (!is_redeclaration) {
5617 validate_identifier(decl->identifier, loc, state);
5618
5619 /* Add the variable to the symbol table. Note that the initializer's
5620 * IR was already processed earlier (though it hasn't been emitted
5621 * yet), without the variable in scope.
5622 *
5623 * This differs from most C-like languages, but it follows the GLSL
5624 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
5625 * spec:
5626 *
5627 * "Within a declaration, the scope of a name starts immediately
5628 * after the initializer if present or immediately after the name
5629 * being declared if not."
5630 */
5631 if (!state->symbols->add_variable(var)) {
5632 YYLTYPE loc = this->get_location();
5633 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
5634 "current scope", decl->identifier);
5635 continue;
5636 }
5637
5638 /* Push the variable declaration to the top. It means that all the
5639 * variable declarations will appear in a funny last-to-first order,
5640 * but otherwise we run into trouble if a function is prototyped, a
5641 * global var is decled, then the function is defined with usage of
5642 * the global var. See glslparsertest's CorrectModule.frag.
5643 */
5644 instructions->push_head(var);
5645 }
5646
5647 instructions->append_list(&initializer_instructions);
5648 }
5649
5650
5651 /* Generally, variable declarations do not have r-values. However,
5652 * one is used for the declaration in
5653 *
5654 * while (bool b = some_condition()) {
5655 * ...
5656 * }
5657 *
5658 * so we return the rvalue from the last seen declaration here.
5659 */
5660 return result;
5661 }
5662
5663
5664 ir_rvalue *
5665 ast_parameter_declarator::hir(exec_list *instructions,
5666 struct _mesa_glsl_parse_state *state)
5667 {
5668 void *ctx = state;
5669 const struct glsl_type *type;
5670 const char *name = NULL;
5671 YYLTYPE loc = this->get_location();
5672
5673 type = this->type->glsl_type(& name, state);
5674
5675 if (type == NULL) {
5676 if (name != NULL) {
5677 _mesa_glsl_error(& loc, state,
5678 "invalid type `%s' in declaration of `%s'",
5679 name, this->identifier);
5680 } else {
5681 _mesa_glsl_error(& loc, state,
5682 "invalid type in declaration of `%s'",
5683 this->identifier);
5684 }
5685
5686 type = glsl_type::error_type;
5687 }
5688
5689 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
5690 *
5691 * "Functions that accept no input arguments need not use void in the
5692 * argument list because prototypes (or definitions) are required and
5693 * therefore there is no ambiguity when an empty argument list "( )" is
5694 * declared. The idiom "(void)" as a parameter list is provided for
5695 * convenience."
5696 *
5697 * Placing this check here prevents a void parameter being set up
5698 * for a function, which avoids tripping up checks for main taking
5699 * parameters and lookups of an unnamed symbol.
5700 */
5701 if (type->is_void()) {
5702 if (this->identifier != NULL)
5703 _mesa_glsl_error(& loc, state,
5704 "named parameter cannot have type `void'");
5705
5706 is_void = true;
5707 return NULL;
5708 }
5709
5710 if (formal_parameter && (this->identifier == NULL)) {
5711 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
5712 return NULL;
5713 }
5714
5715 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
5716 * call already handled the "vec4[..] foo" case.
5717 */
5718 type = process_array_type(&loc, type, this->array_specifier, state);
5719
5720 if (!type->is_error() && type->is_unsized_array()) {
5721 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
5722 "a declared size");
5723 type = glsl_type::error_type;
5724 }
5725
5726 is_void = false;
5727 ir_variable *var = new(ctx)
5728 ir_variable(type, this->identifier, ir_var_function_in);
5729
5730 /* Apply any specified qualifiers to the parameter declaration. Note that
5731 * for function parameters the default mode is 'in'.
5732 */
5733 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,
5734 true);
5735
5736 /* From section 4.1.7 of the GLSL 4.40 spec:
5737 *
5738 * "Opaque variables cannot be treated as l-values; hence cannot
5739 * be used as out or inout function parameters, nor can they be
5740 * assigned into."
5741 *
5742 * From section 4.1.7 of the ARB_bindless_texture spec:
5743 *
5744 * "Samplers can be used as l-values, so can be assigned into and used
5745 * as "out" and "inout" function parameters."
5746 *
5747 * From section 4.1.X of the ARB_bindless_texture spec:
5748 *
5749 * "Images can be used as l-values, so can be assigned into and used as
5750 * "out" and "inout" function parameters."
5751 */
5752 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
5753 && (type->contains_atomic() ||
5754 (!state->has_bindless() && type->contains_opaque()))) {
5755 _mesa_glsl_error(&loc, state, "out and inout parameters cannot "
5756 "contain %s variables",
5757 state->has_bindless() ? "atomic" : "opaque");
5758 type = glsl_type::error_type;
5759 }
5760
5761 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
5762 *
5763 * "When calling a function, expressions that do not evaluate to
5764 * l-values cannot be passed to parameters declared as out or inout."
5765 *
5766 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
5767 *
5768 * "Other binary or unary expressions, non-dereferenced arrays,
5769 * function names, swizzles with repeated fields, and constants
5770 * cannot be l-values."
5771 *
5772 * So for GLSL 1.10, passing an array as an out or inout parameter is not
5773 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
5774 */
5775 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
5776 && type->is_array()
5777 && !state->check_version(120, 100, &loc,
5778 "arrays cannot be out or inout parameters")) {
5779 type = glsl_type::error_type;
5780 }
5781
5782 instructions->push_tail(var);
5783
5784 /* Parameter declarations do not have r-values.
5785 */
5786 return NULL;
5787 }
5788
5789
5790 void
5791 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
5792 bool formal,
5793 exec_list *ir_parameters,
5794 _mesa_glsl_parse_state *state)
5795 {
5796 ast_parameter_declarator *void_param = NULL;
5797 unsigned count = 0;
5798
5799 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
5800 param->formal_parameter = formal;
5801 param->hir(ir_parameters, state);
5802
5803 if (param->is_void)
5804 void_param = param;
5805
5806 count++;
5807 }
5808
5809 if ((void_param != NULL) && (count > 1)) {
5810 YYLTYPE loc = void_param->get_location();
5811
5812 _mesa_glsl_error(& loc, state,
5813 "`void' parameter must be only parameter");
5814 }
5815 }
5816
5817
5818 void
5819 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
5820 {
5821 /* IR invariants disallow function declarations or definitions
5822 * nested within other function definitions. But there is no
5823 * requirement about the relative order of function declarations
5824 * and definitions with respect to one another. So simply insert
5825 * the new ir_function block at the end of the toplevel instruction
5826 * list.
5827 */
5828 state->toplevel_ir->push_tail(f);
5829 }
5830
5831
5832 ir_rvalue *
5833 ast_function::hir(exec_list *instructions,
5834 struct _mesa_glsl_parse_state *state)
5835 {
5836 void *ctx = state;
5837 ir_function *f = NULL;
5838 ir_function_signature *sig = NULL;
5839 exec_list hir_parameters;
5840 YYLTYPE loc = this->get_location();
5841
5842 const char *const name = identifier;
5843
5844 /* New functions are always added to the top-level IR instruction stream,
5845 * so this instruction list pointer is ignored. See also emit_function
5846 * (called below).
5847 */
5848 (void) instructions;
5849
5850 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
5851 *
5852 * "Function declarations (prototypes) cannot occur inside of functions;
5853 * they must be at global scope, or for the built-in functions, outside
5854 * the global scope."
5855 *
5856 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
5857 *
5858 * "User defined functions may only be defined within the global scope."
5859 *
5860 * Note that this language does not appear in GLSL 1.10.
5861 */
5862 if ((state->current_function != NULL) &&
5863 state->is_version(120, 100)) {
5864 YYLTYPE loc = this->get_location();
5865 _mesa_glsl_error(&loc, state,
5866 "declaration of function `%s' not allowed within "
5867 "function body", name);
5868 }
5869
5870 validate_identifier(name, this->get_location(), state);
5871
5872 /* Convert the list of function parameters to HIR now so that they can be
5873 * used below to compare this function's signature with previously seen
5874 * signatures for functions with the same name.
5875 */
5876 ast_parameter_declarator::parameters_to_hir(& this->parameters,
5877 is_definition,
5878 & hir_parameters, state);
5879
5880 const char *return_type_name;
5881 const glsl_type *return_type =
5882 this->return_type->glsl_type(& return_type_name, state);
5883
5884 if (!return_type) {
5885 YYLTYPE loc = this->get_location();
5886 _mesa_glsl_error(&loc, state,
5887 "function `%s' has undeclared return type `%s'",
5888 name, return_type_name);
5889 return_type = glsl_type::error_type;
5890 }
5891
5892 /* ARB_shader_subroutine states:
5893 * "Subroutine declarations cannot be prototyped. It is an error to prepend
5894 * subroutine(...) to a function declaration."
5895 */
5896 if (this->return_type->qualifier.subroutine_list && !is_definition) {
5897 YYLTYPE loc = this->get_location();
5898 _mesa_glsl_error(&loc, state,
5899 "function declaration `%s' cannot have subroutine prepended",
5900 name);
5901 }
5902
5903 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
5904 * "No qualifier is allowed on the return type of a function."
5905 */
5906 if (this->return_type->has_qualifiers(state)) {
5907 YYLTYPE loc = this->get_location();
5908 _mesa_glsl_error(& loc, state,
5909 "function `%s' return type has qualifiers", name);
5910 }
5911
5912 /* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:
5913 *
5914 * "Arrays are allowed as arguments and as the return type. In both
5915 * cases, the array must be explicitly sized."
5916 */
5917 if (return_type->is_unsized_array()) {
5918 YYLTYPE loc = this->get_location();
5919 _mesa_glsl_error(& loc, state,
5920 "function `%s' return type array must be explicitly "
5921 "sized", name);
5922 }
5923
5924 /* From Section 6.1 (Function Definitions) of the GLSL 1.00 spec:
5925 *
5926 * "Arrays are allowed as arguments, but not as the return type. [...]
5927 * The return type can also be a structure if the structure does not
5928 * contain an array."
5929 */
5930 if (state->language_version == 100 && return_type->contains_array()) {
5931 YYLTYPE loc = this->get_location();
5932 _mesa_glsl_error(& loc, state,
5933 "function `%s' return type contains an array", name);
5934 }
5935
5936 /* From section 4.1.7 of the GLSL 4.40 spec:
5937 *
5938 * "[Opaque types] can only be declared as function parameters
5939 * or uniform-qualified variables."
5940 *
5941 * The ARB_bindless_texture spec doesn't clearly state this, but as it says
5942 * "Replace Section 4.1.7 (Samplers), p. 25" and, "Replace Section 4.1.X,
5943 * (Images)", this should be allowed.
5944 */
5945 if (return_type->contains_atomic() ||
5946 (!state->has_bindless() && return_type->contains_opaque())) {
5947 YYLTYPE loc = this->get_location();
5948 _mesa_glsl_error(&loc, state,
5949 "function `%s' return type can't contain an %s type",
5950 name, state->has_bindless() ? "atomic" : "opaque");
5951 }
5952
5953 /**/
5954 if (return_type->is_subroutine()) {
5955 YYLTYPE loc = this->get_location();
5956 _mesa_glsl_error(&loc, state,
5957 "function `%s' return type can't be a subroutine type",
5958 name);
5959 }
5960
5961
5962 /* Create an ir_function if one doesn't already exist. */
5963 f = state->symbols->get_function(name);
5964 if (f == NULL) {
5965 f = new(ctx) ir_function(name);
5966 if (!this->return_type->qualifier.is_subroutine_decl()) {
5967 if (!state->symbols->add_function(f)) {
5968 /* This function name shadows a non-function use of the same name. */
5969 YYLTYPE loc = this->get_location();
5970 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
5971 "non-function", name);
5972 return NULL;
5973 }
5974 }
5975 emit_function(state, f);
5976 }
5977
5978 /* From GLSL ES 3.0 spec, chapter 6.1 "Function Definitions", page 71:
5979 *
5980 * "A shader cannot redefine or overload built-in functions."
5981 *
5982 * While in GLSL ES 1.0 specification, chapter 8 "Built-in Functions":
5983 *
5984 * "User code can overload the built-in functions but cannot redefine
5985 * them."
5986 */
5987 if (state->es_shader) {
5988 /* Local shader has no exact candidates; check the built-ins. */
5989 _mesa_glsl_initialize_builtin_functions();
5990 if (state->language_version >= 300 &&
5991 _mesa_glsl_has_builtin_function(state, name)) {
5992 YYLTYPE loc = this->get_location();
5993 _mesa_glsl_error(& loc, state,
5994 "A shader cannot redefine or overload built-in "
5995 "function `%s' in GLSL ES 3.00", name);
5996 return NULL;
5997 }
5998
5999 if (state->language_version == 100) {
6000 ir_function_signature *sig =
6001 _mesa_glsl_find_builtin_function(state, name, &hir_parameters);
6002 if (sig && sig->is_builtin()) {
6003 _mesa_glsl_error(& loc, state,
6004 "A shader cannot redefine built-in "
6005 "function `%s' in GLSL ES 1.00", name);
6006 }
6007 }
6008 }
6009
6010 /* Verify that this function's signature either doesn't match a previously
6011 * seen signature for a function with the same name, or, if a match is found,
6012 * that the previously seen signature does not have an associated definition.
6013 */
6014 if (state->es_shader || f->has_user_signature()) {
6015 sig = f->exact_matching_signature(state, &hir_parameters);
6016 if (sig != NULL) {
6017 const char *badvar = sig->qualifiers_match(&hir_parameters);
6018 if (badvar != NULL) {
6019 YYLTYPE loc = this->get_location();
6020
6021 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
6022 "qualifiers don't match prototype", name, badvar);
6023 }
6024
6025 if (sig->return_type != return_type) {
6026 YYLTYPE loc = this->get_location();
6027
6028 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
6029 "match prototype", name);
6030 }
6031
6032 if (sig->is_defined) {
6033 if (is_definition) {
6034 YYLTYPE loc = this->get_location();
6035 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
6036 } else {
6037 /* We just encountered a prototype that exactly matches a
6038 * function that's already been defined. This is redundant,
6039 * and we should ignore it.
6040 */
6041 return NULL;
6042 }
6043 } else if (state->language_version == 100 && !is_definition) {
6044 /* From the GLSL 1.00 spec, section 4.2.7:
6045 *
6046 * "A particular variable, structure or function declaration
6047 * may occur at most once within a scope with the exception
6048 * that a single function prototype plus the corresponding
6049 * function definition are allowed."
6050 */
6051 YYLTYPE loc = this->get_location();
6052 _mesa_glsl_error(&loc, state, "function `%s' redeclared", name);
6053 }
6054 }
6055 }
6056
6057 /* Verify the return type of main() */
6058 if (strcmp(name, "main") == 0) {
6059 if (! return_type->is_void()) {
6060 YYLTYPE loc = this->get_location();
6061
6062 _mesa_glsl_error(& loc, state, "main() must return void");
6063 }
6064
6065 if (!hir_parameters.is_empty()) {
6066 YYLTYPE loc = this->get_location();
6067
6068 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
6069 }
6070 }
6071
6072 /* Finish storing the information about this new function in its signature.
6073 */
6074 if (sig == NULL) {
6075 sig = new(ctx) ir_function_signature(return_type);
6076 f->add_signature(sig);
6077 }
6078
6079 sig->replace_parameters(&hir_parameters);
6080 signature = sig;
6081
6082 if (this->return_type->qualifier.subroutine_list) {
6083 int idx;
6084
6085 if (this->return_type->qualifier.flags.q.explicit_index) {
6086 unsigned qual_index;
6087 if (process_qualifier_constant(state, &loc, "index",
6088 this->return_type->qualifier.index,
6089 &qual_index)) {
6090 if (!state->has_explicit_uniform_location()) {
6091 _mesa_glsl_error(&loc, state, "subroutine index requires "
6092 "GL_ARB_explicit_uniform_location or "
6093 "GLSL 4.30");
6094 } else if (qual_index >= MAX_SUBROUTINES) {
6095 _mesa_glsl_error(&loc, state,
6096 "invalid subroutine index (%d) index must "
6097 "be a number between 0 and "
6098 "GL_MAX_SUBROUTINES - 1 (%d)", qual_index,
6099 MAX_SUBROUTINES - 1);
6100 } else {
6101 f->subroutine_index = qual_index;
6102 }
6103 }
6104 }
6105
6106 f->num_subroutine_types = this->return_type->qualifier.subroutine_list->declarations.length();
6107 f->subroutine_types = ralloc_array(state, const struct glsl_type *,
6108 f->num_subroutine_types);
6109 idx = 0;
6110 foreach_list_typed(ast_declaration, decl, link, &this->return_type->qualifier.subroutine_list->declarations) {
6111 const struct glsl_type *type;
6112 /* the subroutine type must be already declared */
6113 type = state->symbols->get_type(decl->identifier);
6114 if (!type) {
6115 _mesa_glsl_error(& loc, state, "unknown type '%s' in subroutine function definition", decl->identifier);
6116 }
6117
6118 for (int i = 0; i < state->num_subroutine_types; i++) {
6119 ir_function *fn = state->subroutine_types[i];
6120 ir_function_signature *tsig = NULL;
6121
6122 if (strcmp(fn->name, decl->identifier))
6123 continue;
6124
6125 tsig = fn->matching_signature(state, &sig->parameters,
6126 false);
6127 if (!tsig) {
6128 _mesa_glsl_error(& loc, state, "subroutine type mismatch '%s' - signatures do not match\n", decl->identifier);
6129 } else {
6130 if (tsig->return_type != sig->return_type) {
6131 _mesa_glsl_error(& loc, state, "subroutine type mismatch '%s' - return types do not match\n", decl->identifier);
6132 }
6133 }
6134 }
6135 f->subroutine_types[idx++] = type;
6136 }
6137 state->subroutines = (ir_function **)reralloc(state, state->subroutines,
6138 ir_function *,
6139 state->num_subroutines + 1);
6140 state->subroutines[state->num_subroutines] = f;
6141 state->num_subroutines++;
6142
6143 }
6144
6145 if (this->return_type->qualifier.is_subroutine_decl()) {
6146 if (!state->symbols->add_type(this->identifier, glsl_type::get_subroutine_instance(this->identifier))) {
6147 _mesa_glsl_error(& loc, state, "type '%s' previously defined", this->identifier);
6148 return NULL;
6149 }
6150 state->subroutine_types = (ir_function **)reralloc(state, state->subroutine_types,
6151 ir_function *,
6152 state->num_subroutine_types + 1);
6153 state->subroutine_types[state->num_subroutine_types] = f;
6154 state->num_subroutine_types++;
6155
6156 f->is_subroutine = true;
6157 }
6158
6159 /* Function declarations (prototypes) do not have r-values.
6160 */
6161 return NULL;
6162 }
6163
6164
6165 ir_rvalue *
6166 ast_function_definition::hir(exec_list *instructions,
6167 struct _mesa_glsl_parse_state *state)
6168 {
6169 prototype->is_definition = true;
6170 prototype->hir(instructions, state);
6171
6172 ir_function_signature *signature = prototype->signature;
6173 if (signature == NULL)
6174 return NULL;
6175
6176 assert(state->current_function == NULL);
6177 state->current_function = signature;
6178 state->found_return = false;
6179
6180 /* Duplicate parameters declared in the prototype as concrete variables.
6181 * Add these to the symbol table.
6182 */
6183 state->symbols->push_scope();
6184 foreach_in_list(ir_variable, var, &signature->parameters) {
6185 assert(var->as_variable() != NULL);
6186
6187 /* The only way a parameter would "exist" is if two parameters have
6188 * the same name.
6189 */
6190 if (state->symbols->name_declared_this_scope(var->name)) {
6191 YYLTYPE loc = this->get_location();
6192
6193 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
6194 } else {
6195 state->symbols->add_variable(var);
6196 }
6197 }
6198
6199 /* Convert the body of the function to HIR. */
6200 this->body->hir(&signature->body, state);
6201 signature->is_defined = true;
6202
6203 state->symbols->pop_scope();
6204
6205 assert(state->current_function == signature);
6206 state->current_function = NULL;
6207
6208 if (!signature->return_type->is_void() && !state->found_return) {
6209 YYLTYPE loc = this->get_location();
6210 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
6211 "%s, but no return statement",
6212 signature->function_name(),
6213 signature->return_type->name);
6214 }
6215
6216 /* Function definitions do not have r-values.
6217 */
6218 return NULL;
6219 }
6220
6221
6222 ir_rvalue *
6223 ast_jump_statement::hir(exec_list *instructions,
6224 struct _mesa_glsl_parse_state *state)
6225 {
6226 void *ctx = state;
6227
6228 switch (mode) {
6229 case ast_return: {
6230 ir_return *inst;
6231 assert(state->current_function);
6232
6233 if (opt_return_value) {
6234 ir_rvalue *ret = opt_return_value->hir(instructions, state);
6235
6236 /* The value of the return type can be NULL if the shader says
6237 * 'return foo();' and foo() is a function that returns void.
6238 *
6239 * NOTE: The GLSL spec doesn't say that this is an error. The type
6240 * of the return value is void. If the return type of the function is
6241 * also void, then this should compile without error. Seriously.
6242 */
6243 const glsl_type *const ret_type =
6244 (ret == NULL) ? glsl_type::void_type : ret->type;
6245
6246 /* Implicit conversions are not allowed for return values prior to
6247 * ARB_shading_language_420pack.
6248 */
6249 if (state->current_function->return_type != ret_type) {
6250 YYLTYPE loc = this->get_location();
6251
6252 if (state->has_420pack()) {
6253 if (!apply_implicit_conversion(state->current_function->return_type,
6254 ret, state)) {
6255 _mesa_glsl_error(& loc, state,
6256 "could not implicitly convert return value "
6257 "to %s, in function `%s'",
6258 state->current_function->return_type->name,
6259 state->current_function->function_name());
6260 }
6261 } else {
6262 _mesa_glsl_error(& loc, state,
6263 "`return' with wrong type %s, in function `%s' "
6264 "returning %s",
6265 ret_type->name,
6266 state->current_function->function_name(),
6267 state->current_function->return_type->name);
6268 }
6269 } else if (state->current_function->return_type->base_type ==
6270 GLSL_TYPE_VOID) {
6271 YYLTYPE loc = this->get_location();
6272
6273 /* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.20
6274 * specs add a clarification:
6275 *
6276 * "A void function can only use return without a return argument, even if
6277 * the return argument has void type. Return statements only accept values:
6278 *
6279 * void func1() { }
6280 * void func2() { return func1(); } // illegal return statement"
6281 */
6282 _mesa_glsl_error(& loc, state,
6283 "void functions can only use `return' without a "
6284 "return argument");
6285 }
6286
6287 inst = new(ctx) ir_return(ret);
6288 } else {
6289 if (state->current_function->return_type->base_type !=
6290 GLSL_TYPE_VOID) {
6291 YYLTYPE loc = this->get_location();
6292
6293 _mesa_glsl_error(& loc, state,
6294 "`return' with no value, in function %s returning "
6295 "non-void",
6296 state->current_function->function_name());
6297 }
6298 inst = new(ctx) ir_return;
6299 }
6300
6301 state->found_return = true;
6302 instructions->push_tail(inst);
6303 break;
6304 }
6305
6306 case ast_discard:
6307 if (state->stage != MESA_SHADER_FRAGMENT) {
6308 YYLTYPE loc = this->get_location();
6309
6310 _mesa_glsl_error(& loc, state,
6311 "`discard' may only appear in a fragment shader");
6312 }
6313 instructions->push_tail(new(ctx) ir_discard);
6314 break;
6315
6316 case ast_break:
6317 case ast_continue:
6318 if (mode == ast_continue &&
6319 state->loop_nesting_ast == NULL) {
6320 YYLTYPE loc = this->get_location();
6321
6322 _mesa_glsl_error(& loc, state, "continue may only appear in a loop");
6323 } else if (mode == ast_break &&
6324 state->loop_nesting_ast == NULL &&
6325 state->switch_state.switch_nesting_ast == NULL) {
6326 YYLTYPE loc = this->get_location();
6327
6328 _mesa_glsl_error(& loc, state,
6329 "break may only appear in a loop or a switch");
6330 } else {
6331 /* For a loop, inline the for loop expression again, since we don't
6332 * know where near the end of the loop body the normal copy of it is
6333 * going to be placed. Same goes for the condition for a do-while
6334 * loop.
6335 */
6336 if (state->loop_nesting_ast != NULL &&
6337 mode == ast_continue && !state->switch_state.is_switch_innermost) {
6338 if (state->loop_nesting_ast->rest_expression) {
6339 state->loop_nesting_ast->rest_expression->hir(instructions,
6340 state);
6341 }
6342 if (state->loop_nesting_ast->mode ==
6343 ast_iteration_statement::ast_do_while) {
6344 state->loop_nesting_ast->condition_to_hir(instructions, state);
6345 }
6346 }
6347
6348 if (state->switch_state.is_switch_innermost &&
6349 mode == ast_continue) {
6350 /* Set 'continue_inside' to true. */
6351 ir_rvalue *const true_val = new (ctx) ir_constant(true);
6352 ir_dereference_variable *deref_continue_inside_var =
6353 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
6354 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
6355 true_val));
6356
6357 /* Break out from the switch, continue for the loop will
6358 * be called right after switch. */
6359 ir_loop_jump *const jump =
6360 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
6361 instructions->push_tail(jump);
6362
6363 } else if (state->switch_state.is_switch_innermost &&
6364 mode == ast_break) {
6365 /* Force break out of switch by inserting a break. */
6366 ir_loop_jump *const jump =
6367 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
6368 instructions->push_tail(jump);
6369 } else {
6370 ir_loop_jump *const jump =
6371 new(ctx) ir_loop_jump((mode == ast_break)
6372 ? ir_loop_jump::jump_break
6373 : ir_loop_jump::jump_continue);
6374 instructions->push_tail(jump);
6375 }
6376 }
6377
6378 break;
6379 }
6380
6381 /* Jump instructions do not have r-values.
6382 */
6383 return NULL;
6384 }
6385
6386
6387 ir_rvalue *
6388 ast_selection_statement::hir(exec_list *instructions,
6389 struct _mesa_glsl_parse_state *state)
6390 {
6391 void *ctx = state;
6392
6393 ir_rvalue *const condition = this->condition->hir(instructions, state);
6394
6395 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
6396 *
6397 * "Any expression whose type evaluates to a Boolean can be used as the
6398 * conditional expression bool-expression. Vector types are not accepted
6399 * as the expression to if."
6400 *
6401 * The checks are separated so that higher quality diagnostics can be
6402 * generated for cases where both rules are violated.
6403 */
6404 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
6405 YYLTYPE loc = this->condition->get_location();
6406
6407 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
6408 "boolean");
6409 }
6410
6411 ir_if *const stmt = new(ctx) ir_if(condition);
6412
6413 if (then_statement != NULL) {
6414 state->symbols->push_scope();
6415 then_statement->hir(& stmt->then_instructions, state);
6416 state->symbols->pop_scope();
6417 }
6418
6419 if (else_statement != NULL) {
6420 state->symbols->push_scope();
6421 else_statement->hir(& stmt->else_instructions, state);
6422 state->symbols->pop_scope();
6423 }
6424
6425 instructions->push_tail(stmt);
6426
6427 /* if-statements do not have r-values.
6428 */
6429 return NULL;
6430 }
6431
6432
6433 struct case_label {
6434 /** Value of the case label. */
6435 unsigned value;
6436
6437 /** Does this label occur after the default? */
6438 bool after_default;
6439
6440 /**
6441 * AST for the case label.
6442 *
6443 * This is only used to generate error messages for duplicate labels.
6444 */
6445 ast_expression *ast;
6446 };
6447
6448 /* Used for detection of duplicate case values, compare
6449 * given contents directly.
6450 */
6451 static bool
6452 compare_case_value(const void *a, const void *b)
6453 {
6454 return ((struct case_label *) a)->value == ((struct case_label *) b)->value;
6455 }
6456
6457
6458 /* Used for detection of duplicate case values, just
6459 * returns key contents as is.
6460 */
6461 static unsigned
6462 key_contents(const void *key)
6463 {
6464 return ((struct case_label *) key)->value;
6465 }
6466
6467
6468 ir_rvalue *
6469 ast_switch_statement::hir(exec_list *instructions,
6470 struct _mesa_glsl_parse_state *state)
6471 {
6472 void *ctx = state;
6473
6474 ir_rvalue *const test_expression =
6475 this->test_expression->hir(instructions, state);
6476
6477 /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
6478 *
6479 * "The type of init-expression in a switch statement must be a
6480 * scalar integer."
6481 */
6482 if (!test_expression->type->is_scalar() ||
6483 !test_expression->type->is_integer()) {
6484 YYLTYPE loc = this->test_expression->get_location();
6485
6486 _mesa_glsl_error(& loc,
6487 state,
6488 "switch-statement expression must be scalar "
6489 "integer");
6490 return NULL;
6491 }
6492
6493 /* Track the switch-statement nesting in a stack-like manner.
6494 */
6495 struct glsl_switch_state saved = state->switch_state;
6496
6497 state->switch_state.is_switch_innermost = true;
6498 state->switch_state.switch_nesting_ast = this;
6499 state->switch_state.labels_ht =
6500 _mesa_hash_table_create(NULL, key_contents,
6501 compare_case_value);
6502 state->switch_state.previous_default = NULL;
6503
6504 /* Initalize is_fallthru state to false.
6505 */
6506 ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
6507 state->switch_state.is_fallthru_var =
6508 new(ctx) ir_variable(glsl_type::bool_type,
6509 "switch_is_fallthru_tmp",
6510 ir_var_temporary);
6511 instructions->push_tail(state->switch_state.is_fallthru_var);
6512
6513 ir_dereference_variable *deref_is_fallthru_var =
6514 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
6515 instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
6516 is_fallthru_val));
6517
6518 /* Initialize continue_inside state to false.
6519 */
6520 state->switch_state.continue_inside =
6521 new(ctx) ir_variable(glsl_type::bool_type,
6522 "continue_inside_tmp",
6523 ir_var_temporary);
6524 instructions->push_tail(state->switch_state.continue_inside);
6525
6526 ir_rvalue *const false_val = new (ctx) ir_constant(false);
6527 ir_dereference_variable *deref_continue_inside_var =
6528 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
6529 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
6530 false_val));
6531
6532 state->switch_state.run_default =
6533 new(ctx) ir_variable(glsl_type::bool_type,
6534 "run_default_tmp",
6535 ir_var_temporary);
6536 instructions->push_tail(state->switch_state.run_default);
6537
6538 /* Loop around the switch is used for flow control. */
6539 ir_loop * loop = new(ctx) ir_loop();
6540 instructions->push_tail(loop);
6541
6542 /* Cache test expression.
6543 */
6544 test_to_hir(&loop->body_instructions, state);
6545
6546 /* Emit code for body of switch stmt.
6547 */
6548 body->hir(&loop->body_instructions, state);
6549
6550 /* Insert a break at the end to exit loop. */
6551 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
6552 loop->body_instructions.push_tail(jump);
6553
6554 /* If we are inside loop, check if continue got called inside switch. */
6555 if (state->loop_nesting_ast != NULL) {
6556 ir_dereference_variable *deref_continue_inside =
6557 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
6558 ir_if *irif = new(ctx) ir_if(deref_continue_inside);
6559 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_continue);
6560
6561 if (state->loop_nesting_ast != NULL) {
6562 if (state->loop_nesting_ast->rest_expression) {
6563 state->loop_nesting_ast->rest_expression->hir(&irif->then_instructions,
6564 state);
6565 }
6566 if (state->loop_nesting_ast->mode ==
6567 ast_iteration_statement::ast_do_while) {
6568 state->loop_nesting_ast->condition_to_hir(&irif->then_instructions, state);
6569 }
6570 }
6571 irif->then_instructions.push_tail(jump);
6572 instructions->push_tail(irif);
6573 }
6574
6575 _mesa_hash_table_destroy(state->switch_state.labels_ht, NULL);
6576
6577 state->switch_state = saved;
6578
6579 /* Switch statements do not have r-values. */
6580 return NULL;
6581 }
6582
6583
6584 void
6585 ast_switch_statement::test_to_hir(exec_list *instructions,
6586 struct _mesa_glsl_parse_state *state)
6587 {
6588 void *ctx = state;
6589
6590 /* set to true to avoid a duplicate "use of uninitialized variable" warning
6591 * on the switch test case. The first one would be already raised when
6592 * getting the test_expression at ast_switch_statement::hir
6593 */
6594 test_expression->set_is_lhs(true);
6595 /* Cache value of test expression. */
6596 ir_rvalue *const test_val = test_expression->hir(instructions, state);
6597
6598 state->switch_state.test_var = new(ctx) ir_variable(test_val->type,
6599 "switch_test_tmp",
6600 ir_var_temporary);
6601 ir_dereference_variable *deref_test_var =
6602 new(ctx) ir_dereference_variable(state->switch_state.test_var);
6603
6604 instructions->push_tail(state->switch_state.test_var);
6605 instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));
6606 }
6607
6608
6609 ir_rvalue *
6610 ast_switch_body::hir(exec_list *instructions,
6611 struct _mesa_glsl_parse_state *state)
6612 {
6613 if (stmts != NULL)
6614 stmts->hir(instructions, state);
6615
6616 /* Switch bodies do not have r-values. */
6617 return NULL;
6618 }
6619
6620 ir_rvalue *
6621 ast_case_statement_list::hir(exec_list *instructions,
6622 struct _mesa_glsl_parse_state *state)
6623 {
6624 exec_list default_case, after_default, tmp;
6625
6626 foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases) {
6627 case_stmt->hir(&tmp, state);
6628
6629 /* Default case. */
6630 if (state->switch_state.previous_default && default_case.is_empty()) {
6631 default_case.append_list(&tmp);
6632 continue;
6633 }
6634
6635 /* If default case found, append 'after_default' list. */
6636 if (!default_case.is_empty())
6637 after_default.append_list(&tmp);
6638 else
6639 instructions->append_list(&tmp);
6640 }
6641
6642 /* Handle the default case. This is done here because default might not be
6643 * the last case. We need to add checks against following cases first to see
6644 * if default should be chosen or not.
6645 */
6646 if (!default_case.is_empty()) {
6647 ir_factory body(instructions, state);
6648
6649 ir_expression *cmp = NULL;
6650
6651 hash_table_foreach(state->switch_state.labels_ht, entry) {
6652 const struct case_label *const l = (struct case_label *) entry->data;
6653
6654 /* If the switch init-value is the value of one of the labels that
6655 * occurs after the default case, disable execution of the default
6656 * case.
6657 */
6658 if (l->after_default) {
6659 ir_constant *const cnst =
6660 state->switch_state.test_var->type->base_type == GLSL_TYPE_UINT
6661 ? body.constant(unsigned(l->value))
6662 : body.constant(int(l->value));
6663
6664 cmp = cmp == NULL
6665 ? equal(cnst, state->switch_state.test_var)
6666 : logic_or(cmp, equal(cnst, state->switch_state.test_var));
6667 }
6668 }
6669
6670 if (cmp != NULL)
6671 body.emit(assign(state->switch_state.run_default, logic_not(cmp)));
6672 else
6673 body.emit(assign(state->switch_state.run_default, body.constant(true)));
6674
6675 /* Append default case and all cases after it. */
6676 instructions->append_list(&default_case);
6677 instructions->append_list(&after_default);
6678 }
6679
6680 /* Case statements do not have r-values. */
6681 return NULL;
6682 }
6683
6684 ir_rvalue *
6685 ast_case_statement::hir(exec_list *instructions,
6686 struct _mesa_glsl_parse_state *state)
6687 {
6688 labels->hir(instructions, state);
6689
6690 /* Guard case statements depending on fallthru state. */
6691 ir_dereference_variable *const deref_fallthru_guard =
6692 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
6693 ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
6694
6695 foreach_list_typed (ast_node, stmt, link, & this->stmts)
6696 stmt->hir(& test_fallthru->then_instructions, state);
6697
6698 instructions->push_tail(test_fallthru);
6699
6700 /* Case statements do not have r-values. */
6701 return NULL;
6702 }
6703
6704
6705 ir_rvalue *
6706 ast_case_label_list::hir(exec_list *instructions,
6707 struct _mesa_glsl_parse_state *state)
6708 {
6709 foreach_list_typed (ast_case_label, label, link, & this->labels)
6710 label->hir(instructions, state);
6711
6712 /* Case labels do not have r-values. */
6713 return NULL;
6714 }
6715
6716 ir_rvalue *
6717 ast_case_label::hir(exec_list *instructions,
6718 struct _mesa_glsl_parse_state *state)
6719 {
6720 ir_factory body(instructions, state);
6721
6722 ir_variable *const fallthru_var = state->switch_state.is_fallthru_var;
6723
6724 /* If not default case, ... */
6725 if (this->test_value != NULL) {
6726 /* Conditionally set fallthru state based on
6727 * comparison of cached test expression value to case label.
6728 */
6729 ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
6730 ir_constant *label_const =
6731 label_rval->constant_expression_value(body.mem_ctx);
6732
6733 if (!label_const) {
6734 YYLTYPE loc = this->test_value->get_location();
6735
6736 _mesa_glsl_error(& loc, state,
6737 "switch statement case label must be a "
6738 "constant expression");
6739
6740 /* Stuff a dummy value in to allow processing to continue. */
6741 label_const = body.constant(0);
6742 } else {
6743 hash_entry *entry =
6744 _mesa_hash_table_search(state->switch_state.labels_ht,
6745 &label_const->value.u[0]);
6746
6747 if (entry) {
6748 const struct case_label *const l =
6749 (struct case_label *) entry->data;
6750 const ast_expression *const previous_label = l->ast;
6751 YYLTYPE loc = this->test_value->get_location();
6752
6753 _mesa_glsl_error(& loc, state, "duplicate case value");
6754
6755 loc = previous_label->get_location();
6756 _mesa_glsl_error(& loc, state, "this is the previous case label");
6757 } else {
6758 struct case_label *l = ralloc(state->switch_state.labels_ht,
6759 struct case_label);
6760
6761 l->value = label_const->value.u[0];
6762 l->after_default = state->switch_state.previous_default != NULL;
6763 l->ast = this->test_value;
6764
6765 _mesa_hash_table_insert(state->switch_state.labels_ht,
6766 &label_const->value.u[0],
6767 l);
6768 }
6769 }
6770
6771 /* Create an r-value version of the ir_constant label here (after we may
6772 * have created a fake one in error cases) that can be passed to
6773 * apply_implicit_conversion below.
6774 */
6775 ir_rvalue *label = label_const;
6776
6777 ir_rvalue *deref_test_var =
6778 new(body.mem_ctx) ir_dereference_variable(state->switch_state.test_var);
6779
6780 /*
6781 * From GLSL 4.40 specification section 6.2 ("Selection"):
6782 *
6783 * "The type of the init-expression value in a switch statement must
6784 * be a scalar int or uint. The type of the constant-expression value
6785 * in a case label also must be a scalar int or uint. When any pair
6786 * of these values is tested for "equal value" and the types do not
6787 * match, an implicit conversion will be done to convert the int to a
6788 * uint (see section 4.1.10 “Implicit Conversions”) before the compare
6789 * is done."
6790 */
6791 if (label->type != state->switch_state.test_var->type) {
6792 YYLTYPE loc = this->test_value->get_location();
6793
6794 const glsl_type *type_a = label->type;
6795 const glsl_type *type_b = state->switch_state.test_var->type;
6796
6797 /* Check if int->uint implicit conversion is supported. */
6798 bool integer_conversion_supported =
6799 glsl_type::int_type->can_implicitly_convert_to(glsl_type::uint_type,
6800 state);
6801
6802 if ((!type_a->is_integer() || !type_b->is_integer()) ||
6803 !integer_conversion_supported) {
6804 _mesa_glsl_error(&loc, state, "type mismatch with switch "
6805 "init-expression and case label (%s != %s)",
6806 type_a->name, type_b->name);
6807 } else {
6808 /* Conversion of the case label. */
6809 if (type_a->base_type == GLSL_TYPE_INT) {
6810 if (!apply_implicit_conversion(glsl_type::uint_type,
6811 label, state))
6812 _mesa_glsl_error(&loc, state, "implicit type conversion error");
6813 } else {
6814 /* Conversion of the init-expression value. */
6815 if (!apply_implicit_conversion(glsl_type::uint_type,
6816 deref_test_var, state))
6817 _mesa_glsl_error(&loc, state, "implicit type conversion error");
6818 }
6819 }
6820
6821 /* If the implicit conversion was allowed, the types will already be
6822 * the same. If the implicit conversion wasn't allowed, smash the
6823 * type of the label anyway. This will prevent the expression
6824 * constructor (below) from failing an assertion.
6825 */
6826 label->type = deref_test_var->type;
6827 }
6828
6829 body.emit(assign(fallthru_var,
6830 logic_or(fallthru_var, equal(label, deref_test_var))));
6831 } else { /* default case */
6832 if (state->switch_state.previous_default) {
6833 YYLTYPE loc = this->get_location();
6834 _mesa_glsl_error(& loc, state,
6835 "multiple default labels in one switch");
6836
6837 loc = state->switch_state.previous_default->get_location();
6838 _mesa_glsl_error(& loc, state, "this is the first default label");
6839 }
6840 state->switch_state.previous_default = this;
6841
6842 /* Set fallthru condition on 'run_default' bool. */
6843 body.emit(assign(fallthru_var,
6844 logic_or(fallthru_var,
6845 state->switch_state.run_default)));
6846 }
6847
6848 /* Case statements do not have r-values. */
6849 return NULL;
6850 }
6851
6852 void
6853 ast_iteration_statement::condition_to_hir(exec_list *instructions,
6854 struct _mesa_glsl_parse_state *state)
6855 {
6856 void *ctx = state;
6857
6858 if (condition != NULL) {
6859 ir_rvalue *const cond =
6860 condition->hir(instructions, state);
6861
6862 if ((cond == NULL)
6863 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
6864 YYLTYPE loc = condition->get_location();
6865
6866 _mesa_glsl_error(& loc, state,
6867 "loop condition must be scalar boolean");
6868 } else {
6869 /* As the first code in the loop body, generate a block that looks
6870 * like 'if (!condition) break;' as the loop termination condition.
6871 */
6872 ir_rvalue *const not_cond =
6873 new(ctx) ir_expression(ir_unop_logic_not, cond);
6874
6875 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
6876
6877 ir_jump *const break_stmt =
6878 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
6879
6880 if_stmt->then_instructions.push_tail(break_stmt);
6881 instructions->push_tail(if_stmt);
6882 }
6883 }
6884 }
6885
6886
6887 ir_rvalue *
6888 ast_iteration_statement::hir(exec_list *instructions,
6889 struct _mesa_glsl_parse_state *state)
6890 {
6891 void *ctx = state;
6892
6893 /* For-loops and while-loops start a new scope, but do-while loops do not.
6894 */
6895 if (mode != ast_do_while)
6896 state->symbols->push_scope();
6897
6898 if (init_statement != NULL)
6899 init_statement->hir(instructions, state);
6900
6901 ir_loop *const stmt = new(ctx) ir_loop();
6902 instructions->push_tail(stmt);
6903
6904 /* Track the current loop nesting. */
6905 ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
6906
6907 state->loop_nesting_ast = this;
6908
6909 /* Likewise, indicate that following code is closest to a loop,
6910 * NOT closest to a switch.
6911 */
6912 bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
6913 state->switch_state.is_switch_innermost = false;
6914
6915 if (mode != ast_do_while)
6916 condition_to_hir(&stmt->body_instructions, state);
6917
6918 if (body != NULL)
6919 body->hir(& stmt->body_instructions, state);
6920
6921 if (rest_expression != NULL)
6922 rest_expression->hir(& stmt->body_instructions, state);
6923
6924 if (mode == ast_do_while)
6925 condition_to_hir(&stmt->body_instructions, state);
6926
6927 if (mode != ast_do_while)
6928 state->symbols->pop_scope();
6929
6930 /* Restore previous nesting before returning. */
6931 state->loop_nesting_ast = nesting_ast;
6932 state->switch_state.is_switch_innermost = saved_is_switch_innermost;
6933
6934 /* Loops do not have r-values.
6935 */
6936 return NULL;
6937 }
6938
6939
6940 /**
6941 * Determine if the given type is valid for establishing a default precision
6942 * qualifier.
6943 *
6944 * From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):
6945 *
6946 * "The precision statement
6947 *
6948 * precision precision-qualifier type;
6949 *
6950 * can be used to establish a default precision qualifier. The type field
6951 * can be either int or float or any of the sampler types, and the
6952 * precision-qualifier can be lowp, mediump, or highp."
6953 *
6954 * GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision
6955 * qualifiers on sampler types, but this seems like an oversight (since the
6956 * intention of including these in GLSL 1.30 is to allow compatibility with ES
6957 * shaders). So we allow int, float, and all sampler types regardless of GLSL
6958 * version.
6959 */
6960 static bool
6961 is_valid_default_precision_type(const struct glsl_type *const type)
6962 {
6963 if (type == NULL)
6964 return false;
6965
6966 switch (type->base_type) {
6967 case GLSL_TYPE_INT:
6968 case GLSL_TYPE_FLOAT:
6969 /* "int" and "float" are valid, but vectors and matrices are not. */
6970 return type->vector_elements == 1 && type->matrix_columns == 1;
6971 case GLSL_TYPE_SAMPLER:
6972 case GLSL_TYPE_IMAGE:
6973 case GLSL_TYPE_ATOMIC_UINT:
6974 return true;
6975 default:
6976 return false;
6977 }
6978 }
6979
6980
6981 ir_rvalue *
6982 ast_type_specifier::hir(exec_list *instructions,
6983 struct _mesa_glsl_parse_state *state)
6984 {
6985 if (this->default_precision == ast_precision_none && this->structure == NULL)
6986 return NULL;
6987
6988 YYLTYPE loc = this->get_location();
6989
6990 /* If this is a precision statement, check that the type to which it is
6991 * applied is either float or int.
6992 *
6993 * From section 4.5.3 of the GLSL 1.30 spec:
6994 * "The precision statement
6995 * precision precision-qualifier type;
6996 * can be used to establish a default precision qualifier. The type
6997 * field can be either int or float [...]. Any other types or
6998 * qualifiers will result in an error.
6999 */
7000 if (this->default_precision != ast_precision_none) {
7001 if (!state->check_precision_qualifiers_allowed(&loc))
7002 return NULL;
7003
7004 if (this->structure != NULL) {
7005 _mesa_glsl_error(&loc, state,
7006 "precision qualifiers do not apply to structures");
7007 return NULL;
7008 }
7009
7010 if (this->array_specifier != NULL) {
7011 _mesa_glsl_error(&loc, state,
7012 "default precision statements do not apply to "
7013 "arrays");
7014 return NULL;
7015 }
7016
7017 const struct glsl_type *const type =
7018 state->symbols->get_type(this->type_name);
7019 if (!is_valid_default_precision_type(type)) {
7020 _mesa_glsl_error(&loc, state,
7021 "default precision statements apply only to "
7022 "float, int, and opaque types");
7023 return NULL;
7024 }
7025
7026 if (state->es_shader) {
7027 /* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.00
7028 * spec says:
7029 *
7030 * "Non-precision qualified declarations will use the precision
7031 * qualifier specified in the most recent precision statement
7032 * that is still in scope. The precision statement has the same
7033 * scoping rules as variable declarations. If it is declared
7034 * inside a compound statement, its effect stops at the end of
7035 * the innermost statement it was declared in. Precision
7036 * statements in nested scopes override precision statements in
7037 * outer scopes. Multiple precision statements for the same basic
7038 * type can appear inside the same scope, with later statements
7039 * overriding earlier statements within that scope."
7040 *
7041 * Default precision specifications follow the same scope rules as
7042 * variables. So, we can track the state of the default precision
7043 * qualifiers in the symbol table, and the rules will just work. This
7044 * is a slight abuse of the symbol table, but it has the semantics
7045 * that we want.
7046 */
7047 state->symbols->add_default_precision_qualifier(this->type_name,
7048 this->default_precision);
7049 }
7050
7051 /* FINISHME: Translate precision statements into IR. */
7052 return NULL;
7053 }
7054
7055 /* _mesa_ast_set_aggregate_type() sets the <structure> field so that
7056 * process_record_constructor() can do type-checking on C-style initializer
7057 * expressions of structs, but ast_struct_specifier should only be translated
7058 * to HIR if it is declaring the type of a structure.
7059 *
7060 * The ->is_declaration field is false for initializers of variables
7061 * declared separately from the struct's type definition.
7062 *
7063 * struct S { ... }; (is_declaration = true)
7064 * struct T { ... } t = { ... }; (is_declaration = true)
7065 * S s = { ... }; (is_declaration = false)
7066 */
7067 if (this->structure != NULL && this->structure->is_declaration)
7068 return this->structure->hir(instructions, state);
7069
7070 return NULL;
7071 }
7072
7073
7074 /**
7075 * Process a structure or interface block tree into an array of structure fields
7076 *
7077 * After parsing, where there are some syntax differnces, structures and
7078 * interface blocks are almost identical. They are similar enough that the
7079 * AST for each can be processed the same way into a set of
7080 * \c glsl_struct_field to describe the members.
7081 *
7082 * If we're processing an interface block, var_mode should be the type of the
7083 * interface block (ir_var_shader_in, ir_var_shader_out, ir_var_uniform or
7084 * ir_var_shader_storage). If we're processing a structure, var_mode should be
7085 * ir_var_auto.
7086 *
7087 * \return
7088 * The number of fields processed. A pointer to the array structure fields is
7089 * stored in \c *fields_ret.
7090 */
7091 static unsigned
7092 ast_process_struct_or_iface_block_members(exec_list *instructions,
7093 struct _mesa_glsl_parse_state *state,
7094 exec_list *declarations,
7095 glsl_struct_field **fields_ret,
7096 bool is_interface,
7097 enum glsl_matrix_layout matrix_layout,
7098 bool allow_reserved_names,
7099 ir_variable_mode var_mode,
7100 ast_type_qualifier *layout,
7101 unsigned block_stream,
7102 unsigned block_xfb_buffer,
7103 unsigned block_xfb_offset,
7104 unsigned expl_location,
7105 unsigned expl_align)
7106 {
7107 unsigned decl_count = 0;
7108 unsigned next_offset = 0;
7109
7110 /* Make an initial pass over the list of fields to determine how
7111 * many there are. Each element in this list is an ast_declarator_list.
7112 * This means that we actually need to count the number of elements in the
7113 * 'declarations' list in each of the elements.
7114 */
7115 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
7116 decl_count += decl_list->declarations.length();
7117 }
7118
7119 /* Allocate storage for the fields and process the field
7120 * declarations. As the declarations are processed, try to also convert
7121 * the types to HIR. This ensures that structure definitions embedded in
7122 * other structure definitions or in interface blocks are processed.
7123 */
7124 glsl_struct_field *const fields = rzalloc_array(state, glsl_struct_field,
7125 decl_count);
7126
7127 bool first_member = true;
7128 bool first_member_has_explicit_location = false;
7129
7130 unsigned i = 0;
7131 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
7132 const char *type_name;
7133 YYLTYPE loc = decl_list->get_location();
7134
7135 decl_list->type->specifier->hir(instructions, state);
7136
7137 /* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:
7138 *
7139 * "Anonymous structures are not supported; so embedded structures
7140 * must have a declarator. A name given to an embedded struct is
7141 * scoped at the same level as the struct it is embedded in."
7142 *
7143 * The same section of the GLSL 1.20 spec says:
7144 *
7145 * "Anonymous structures are not supported. Embedded structures are
7146 * not supported."
7147 *
7148 * The GLSL ES 1.00 and 3.00 specs have similar langauge. So, we allow
7149 * embedded structures in 1.10 only.
7150 */
7151 if (state->language_version != 110 &&
7152 decl_list->type->specifier->structure != NULL)
7153 _mesa_glsl_error(&loc, state,
7154 "embedded structure declarations are not allowed");
7155
7156 const glsl_type *decl_type =
7157 decl_list->type->glsl_type(& type_name, state);
7158
7159 const struct ast_type_qualifier *const qual =
7160 &decl_list->type->qualifier;
7161
7162 /* From section 4.3.9 of the GLSL 4.40 spec:
7163 *
7164 * "[In interface blocks] opaque types are not allowed."
7165 *
7166 * It should be impossible for decl_type to be NULL here. Cases that
7167 * might naturally lead to decl_type being NULL, especially for the
7168 * is_interface case, will have resulted in compilation having
7169 * already halted due to a syntax error.
7170 */
7171 assert(decl_type);
7172
7173 if (is_interface) {
7174 /* From section 4.3.7 of the ARB_bindless_texture spec:
7175 *
7176 * "(remove the following bullet from the last list on p. 39,
7177 * thereby permitting sampler types in interface blocks; image
7178 * types are also permitted in blocks by this extension)"
7179 *
7180 * * sampler types are not allowed
7181 */
7182 if (decl_type->contains_atomic() ||
7183 (!state->has_bindless() && decl_type->contains_opaque())) {
7184 _mesa_glsl_error(&loc, state, "uniform/buffer in non-default "
7185 "interface block contains %s variable",
7186 state->has_bindless() ? "atomic" : "opaque");
7187 }
7188 } else {
7189 if (decl_type->contains_atomic()) {
7190 /* From section 4.1.7.3 of the GLSL 4.40 spec:
7191 *
7192 * "Members of structures cannot be declared as atomic counter
7193 * types."
7194 */
7195 _mesa_glsl_error(&loc, state, "atomic counter in structure");
7196 }
7197
7198 if (!state->has_bindless() && decl_type->contains_image()) {
7199 /* FINISHME: Same problem as with atomic counters.
7200 * FINISHME: Request clarification from Khronos and add
7201 * FINISHME: spec quotation here.
7202 */
7203 _mesa_glsl_error(&loc, state, "image in structure");
7204 }
7205 }
7206
7207 if (qual->flags.q.explicit_binding) {
7208 _mesa_glsl_error(&loc, state,
7209 "binding layout qualifier cannot be applied "
7210 "to struct or interface block members");
7211 }
7212
7213 if (is_interface) {
7214 if (!first_member) {
7215 if (!layout->flags.q.explicit_location &&
7216 ((first_member_has_explicit_location &&
7217 !qual->flags.q.explicit_location) ||
7218 (!first_member_has_explicit_location &&
7219 qual->flags.q.explicit_location))) {
7220 _mesa_glsl_error(&loc, state,
7221 "when block-level location layout qualifier "
7222 "is not supplied either all members must "
7223 "have a location layout qualifier or all "
7224 "members must not have a location layout "
7225 "qualifier");
7226 }
7227 } else {
7228 first_member = false;
7229 first_member_has_explicit_location =
7230 qual->flags.q.explicit_location;
7231 }
7232 }
7233
7234 if (qual->flags.q.std140 ||
7235 qual->flags.q.std430 ||
7236 qual->flags.q.packed ||
7237 qual->flags.q.shared) {
7238 _mesa_glsl_error(&loc, state,
7239 "uniform/shader storage block layout qualifiers "
7240 "std140, std430, packed, and shared can only be "
7241 "applied to uniform/shader storage blocks, not "
7242 "members");
7243 }
7244
7245 if (qual->flags.q.constant) {
7246 _mesa_glsl_error(&loc, state,
7247 "const storage qualifier cannot be applied "
7248 "to struct or interface block members");
7249 }
7250
7251 validate_memory_qualifier_for_type(state, &loc, qual, decl_type);
7252 validate_image_format_qualifier_for_type(state, &loc, qual, decl_type);
7253
7254 /* From Section 4.4.2.3 (Geometry Outputs) of the GLSL 4.50 spec:
7255 *
7256 * "A block member may be declared with a stream identifier, but
7257 * the specified stream must match the stream associated with the
7258 * containing block."
7259 */
7260 if (qual->flags.q.explicit_stream) {
7261 unsigned qual_stream;
7262 if (process_qualifier_constant(state, &loc, "stream",
7263 qual->stream, &qual_stream) &&
7264 qual_stream != block_stream) {
7265 _mesa_glsl_error(&loc, state, "stream layout qualifier on "
7266 "interface block member does not match "
7267 "the interface block (%u vs %u)", qual_stream,
7268 block_stream);
7269 }
7270 }
7271
7272 int xfb_buffer;
7273 unsigned explicit_xfb_buffer = 0;
7274 if (qual->flags.q.explicit_xfb_buffer) {
7275 unsigned qual_xfb_buffer;
7276 if (process_qualifier_constant(state, &loc, "xfb_buffer",
7277 qual->xfb_buffer, &qual_xfb_buffer)) {
7278 explicit_xfb_buffer = 1;
7279 if (qual_xfb_buffer != block_xfb_buffer)
7280 _mesa_glsl_error(&loc, state, "xfb_buffer layout qualifier on "
7281 "interface block member does not match "
7282 "the interface block (%u vs %u)",
7283 qual_xfb_buffer, block_xfb_buffer);
7284 }
7285 xfb_buffer = (int) qual_xfb_buffer;
7286 } else {
7287 if (layout)
7288 explicit_xfb_buffer = layout->flags.q.explicit_xfb_buffer;
7289 xfb_buffer = (int) block_xfb_buffer;
7290 }
7291
7292 int xfb_stride = -1;
7293 if (qual->flags.q.explicit_xfb_stride) {
7294 unsigned qual_xfb_stride;
7295 if (process_qualifier_constant(state, &loc, "xfb_stride",
7296 qual->xfb_stride, &qual_xfb_stride)) {
7297 xfb_stride = (int) qual_xfb_stride;
7298 }
7299 }
7300
7301 if (qual->flags.q.uniform && qual->has_interpolation()) {
7302 _mesa_glsl_error(&loc, state,
7303 "interpolation qualifiers cannot be used "
7304 "with uniform interface blocks");
7305 }
7306
7307 if ((qual->flags.q.uniform || !is_interface) &&
7308 qual->has_auxiliary_storage()) {
7309 _mesa_glsl_error(&loc, state,
7310 "auxiliary storage qualifiers cannot be used "
7311 "in uniform blocks or structures.");
7312 }
7313
7314 if (qual->flags.q.row_major || qual->flags.q.column_major) {
7315 if (!qual->flags.q.uniform && !qual->flags.q.buffer) {
7316 _mesa_glsl_error(&loc, state,
7317 "row_major and column_major can only be "
7318 "applied to interface blocks");
7319 } else
7320 validate_matrix_layout_for_type(state, &loc, decl_type, NULL);
7321 }
7322
7323 foreach_list_typed (ast_declaration, decl, link,
7324 &decl_list->declarations) {
7325 YYLTYPE loc = decl->get_location();
7326
7327 if (!allow_reserved_names)
7328 validate_identifier(decl->identifier, loc, state);
7329
7330 const struct glsl_type *field_type =
7331 process_array_type(&loc, decl_type, decl->array_specifier, state);
7332 validate_array_dimensions(field_type, state, &loc);
7333 fields[i].type = field_type;
7334 fields[i].name = decl->identifier;
7335 fields[i].interpolation =
7336 interpret_interpolation_qualifier(qual, field_type,
7337 var_mode, state, &loc);
7338 fields[i].centroid = qual->flags.q.centroid ? 1 : 0;
7339 fields[i].sample = qual->flags.q.sample ? 1 : 0;
7340 fields[i].patch = qual->flags.q.patch ? 1 : 0;
7341 fields[i].precision = qual->precision;
7342 fields[i].offset = -1;
7343 fields[i].explicit_xfb_buffer = explicit_xfb_buffer;
7344 fields[i].xfb_buffer = xfb_buffer;
7345 fields[i].xfb_stride = xfb_stride;
7346
7347 if (qual->flags.q.explicit_location) {
7348 unsigned qual_location;
7349 if (process_qualifier_constant(state, &loc, "location",
7350 qual->location, &qual_location)) {
7351 fields[i].location = qual_location +
7352 (fields[i].patch ? VARYING_SLOT_PATCH0 : VARYING_SLOT_VAR0);
7353 expl_location = fields[i].location +
7354 fields[i].type->count_attribute_slots(false);
7355 }
7356 } else {
7357 if (layout && layout->flags.q.explicit_location) {
7358 fields[i].location = expl_location;
7359 expl_location += fields[i].type->count_attribute_slots(false);
7360 } else {
7361 fields[i].location = -1;
7362 }
7363 }
7364
7365 /* Offset can only be used with std430 and std140 layouts an initial
7366 * value of 0 is used for error detection.
7367 */
7368 unsigned align = 0;
7369 unsigned size = 0;
7370 if (layout) {
7371 bool row_major;
7372 if (qual->flags.q.row_major ||
7373 matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR) {
7374 row_major = true;
7375 } else {
7376 row_major = false;
7377 }
7378
7379 if(layout->flags.q.std140) {
7380 align = field_type->std140_base_alignment(row_major);
7381 size = field_type->std140_size(row_major);
7382 } else if (layout->flags.q.std430) {
7383 align = field_type->std430_base_alignment(row_major);
7384 size = field_type->std430_size(row_major);
7385 }
7386 }
7387
7388 if (qual->flags.q.explicit_offset) {
7389 unsigned qual_offset;
7390 if (process_qualifier_constant(state, &loc, "offset",
7391 qual->offset, &qual_offset)) {
7392 if (align != 0 && size != 0) {
7393 if (next_offset > qual_offset)
7394 _mesa_glsl_error(&loc, state, "layout qualifier "
7395 "offset overlaps previous member");
7396
7397 if (qual_offset % align) {
7398 _mesa_glsl_error(&loc, state, "layout qualifier offset "
7399 "must be a multiple of the base "
7400 "alignment of %s", field_type->name);
7401 }
7402 fields[i].offset = qual_offset;
7403 next_offset = glsl_align(qual_offset + size, align);
7404 } else {
7405 _mesa_glsl_error(&loc, state, "offset can only be used "
7406 "with std430 and std140 layouts");
7407 }
7408 }
7409 }
7410
7411 if (qual->flags.q.explicit_align || expl_align != 0) {
7412 unsigned offset = fields[i].offset != -1 ? fields[i].offset :
7413 next_offset;
7414 if (align == 0 || size == 0) {
7415 _mesa_glsl_error(&loc, state, "align can only be used with "
7416 "std430 and std140 layouts");
7417 } else if (qual->flags.q.explicit_align) {
7418 unsigned member_align;
7419 if (process_qualifier_constant(state, &loc, "align",
7420 qual->align, &member_align)) {
7421 if (member_align == 0 ||
7422 member_align & (member_align - 1)) {
7423 _mesa_glsl_error(&loc, state, "align layout qualifier "
7424 "in not a power of 2");
7425 } else {
7426 fields[i].offset = glsl_align(offset, member_align);
7427 next_offset = glsl_align(fields[i].offset + size, align);
7428 }
7429 }
7430 } else {
7431 fields[i].offset = glsl_align(offset, expl_align);
7432 next_offset = glsl_align(fields[i].offset + size, align);
7433 }
7434 } else if (!qual->flags.q.explicit_offset) {
7435 if (align != 0 && size != 0)
7436 next_offset = glsl_align(next_offset + size, align);
7437 }
7438
7439 /* From the ARB_enhanced_layouts spec:
7440 *
7441 * "The given offset applies to the first component of the first
7442 * member of the qualified entity. Then, within the qualified
7443 * entity, subsequent components are each assigned, in order, to
7444 * the next available offset aligned to a multiple of that
7445 * component's size. Aggregate types are flattened down to the
7446 * component level to get this sequence of components."
7447 */
7448 if (qual->flags.q.explicit_xfb_offset) {
7449 unsigned xfb_offset;
7450 if (process_qualifier_constant(state, &loc, "xfb_offset",
7451 qual->offset, &xfb_offset)) {
7452 fields[i].offset = xfb_offset;
7453 block_xfb_offset = fields[i].offset +
7454 4 * field_type->component_slots();
7455 }
7456 } else {
7457 if (layout && layout->flags.q.explicit_xfb_offset) {
7458 unsigned align = field_type->is_64bit() ? 8 : 4;
7459 fields[i].offset = glsl_align(block_xfb_offset, align);
7460 block_xfb_offset += 4 * field_type->component_slots();
7461 }
7462 }
7463
7464 /* Propogate row- / column-major information down the fields of the
7465 * structure or interface block. Structures need this data because
7466 * the structure may contain a structure that contains ... a matrix
7467 * that need the proper layout.
7468 */
7469 if (is_interface && layout &&
7470 (layout->flags.q.uniform || layout->flags.q.buffer) &&
7471 (field_type->without_array()->is_matrix()
7472 || field_type->without_array()->is_record())) {
7473 /* If no layout is specified for the field, inherit the layout
7474 * from the block.
7475 */
7476 fields[i].matrix_layout = matrix_layout;
7477
7478 if (qual->flags.q.row_major)
7479 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
7480 else if (qual->flags.q.column_major)
7481 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
7482
7483 /* If we're processing an uniform or buffer block, the matrix
7484 * layout must be decided by this point.
7485 */
7486 assert(fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR
7487 || fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR);
7488 }
7489
7490 /* Memory qualifiers are allowed on buffer and image variables, while
7491 * the format qualifier is only accepted for images.
7492 */
7493 if (var_mode == ir_var_shader_storage ||
7494 field_type->without_array()->is_image()) {
7495 /* For readonly and writeonly qualifiers the field definition,
7496 * if set, overwrites the layout qualifier.
7497 */
7498 if (qual->flags.q.read_only || qual->flags.q.write_only) {
7499 fields[i].memory_read_only = qual->flags.q.read_only;
7500 fields[i].memory_write_only = qual->flags.q.write_only;
7501 } else {
7502 fields[i].memory_read_only =
7503 layout ? layout->flags.q.read_only : 0;
7504 fields[i].memory_write_only =
7505 layout ? layout->flags.q.write_only : 0;
7506 }
7507
7508 /* For other qualifiers, we set the flag if either the layout
7509 * qualifier or the field qualifier are set
7510 */
7511 fields[i].memory_coherent = qual->flags.q.coherent ||
7512 (layout && layout->flags.q.coherent);
7513 fields[i].memory_volatile = qual->flags.q._volatile ||
7514 (layout && layout->flags.q._volatile);
7515 fields[i].memory_restrict = qual->flags.q.restrict_flag ||
7516 (layout && layout->flags.q.restrict_flag);
7517
7518 if (field_type->without_array()->is_image()) {
7519 if (qual->flags.q.explicit_image_format) {
7520 if (qual->image_base_type !=
7521 field_type->without_array()->sampled_type) {
7522 _mesa_glsl_error(&loc, state, "format qualifier doesn't "
7523 "match the base data type of the image");
7524 }
7525
7526 fields[i].image_format = qual->image_format;
7527 } else {
7528 if (!qual->flags.q.write_only) {
7529 _mesa_glsl_error(&loc, state, "image not qualified with "
7530 "`writeonly' must have a format layout "
7531 "qualifier");
7532 }
7533
7534 fields[i].image_format = GL_NONE;
7535 }
7536 }
7537 }
7538
7539 i++;
7540 }
7541 }
7542
7543 assert(i == decl_count);
7544
7545 *fields_ret = fields;
7546 return decl_count;
7547 }
7548
7549
7550 ir_rvalue *
7551 ast_struct_specifier::hir(exec_list *instructions,
7552 struct _mesa_glsl_parse_state *state)
7553 {
7554 YYLTYPE loc = this->get_location();
7555
7556 unsigned expl_location = 0;
7557 if (layout && layout->flags.q.explicit_location) {
7558 if (!process_qualifier_constant(state, &loc, "location",
7559 layout->location, &expl_location)) {
7560 return NULL;
7561 } else {
7562 expl_location = VARYING_SLOT_VAR0 + expl_location;
7563 }
7564 }
7565
7566 glsl_struct_field *fields;
7567 unsigned decl_count =
7568 ast_process_struct_or_iface_block_members(instructions,
7569 state,
7570 &this->declarations,
7571 &fields,
7572 false,
7573 GLSL_MATRIX_LAYOUT_INHERITED,
7574 false /* allow_reserved_names */,
7575 ir_var_auto,
7576 layout,
7577 0, /* for interface only */
7578 0, /* for interface only */
7579 0, /* for interface only */
7580 expl_location,
7581 0 /* for interface only */);
7582
7583 validate_identifier(this->name, loc, state);
7584
7585 type = glsl_type::get_record_instance(fields, decl_count, this->name);
7586
7587 if (!type->is_anonymous() && !state->symbols->add_type(name, type)) {
7588 const glsl_type *match = state->symbols->get_type(name);
7589 /* allow struct matching for desktop GL - older UE4 does this */
7590 if (match != NULL && state->is_version(130, 0) && match->record_compare(type, false))
7591 _mesa_glsl_warning(& loc, state, "struct `%s' previously defined", name);
7592 else
7593 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
7594 } else {
7595 const glsl_type **s = reralloc(state, state->user_structures,
7596 const glsl_type *,
7597 state->num_user_structures + 1);
7598 if (s != NULL) {
7599 s[state->num_user_structures] = type;
7600 state->user_structures = s;
7601 state->num_user_structures++;
7602 }
7603 }
7604
7605 /* Structure type definitions do not have r-values.
7606 */
7607 return NULL;
7608 }
7609
7610
7611 /**
7612 * Visitor class which detects whether a given interface block has been used.
7613 */
7614 class interface_block_usage_visitor : public ir_hierarchical_visitor
7615 {
7616 public:
7617 interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)
7618 : mode(mode), block(block), found(false)
7619 {
7620 }
7621
7622 virtual ir_visitor_status visit(ir_dereference_variable *ir)
7623 {
7624 if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {
7625 found = true;
7626 return visit_stop;
7627 }
7628 return visit_continue;
7629 }
7630
7631 bool usage_found() const
7632 {
7633 return this->found;
7634 }
7635
7636 private:
7637 ir_variable_mode mode;
7638 const glsl_type *block;
7639 bool found;
7640 };
7641
7642 static bool
7643 is_unsized_array_last_element(ir_variable *v)
7644 {
7645 const glsl_type *interface_type = v->get_interface_type();
7646 int length = interface_type->length;
7647
7648 assert(v->type->is_unsized_array());
7649
7650 /* Check if it is the last element of the interface */
7651 if (strcmp(interface_type->fields.structure[length-1].name, v->name) == 0)
7652 return true;
7653 return false;
7654 }
7655
7656 static void
7657 apply_memory_qualifiers(ir_variable *var, glsl_struct_field field)
7658 {
7659 var->data.memory_read_only = field.memory_read_only;
7660 var->data.memory_write_only = field.memory_write_only;
7661 var->data.memory_coherent = field.memory_coherent;
7662 var->data.memory_volatile = field.memory_volatile;
7663 var->data.memory_restrict = field.memory_restrict;
7664 }
7665
7666 ir_rvalue *
7667 ast_interface_block::hir(exec_list *instructions,
7668 struct _mesa_glsl_parse_state *state)
7669 {
7670 YYLTYPE loc = this->get_location();
7671
7672 /* Interface blocks must be declared at global scope */
7673 if (state->current_function != NULL) {
7674 _mesa_glsl_error(&loc, state,
7675 "Interface block `%s' must be declared "
7676 "at global scope",
7677 this->block_name);
7678 }
7679
7680 /* Validate qualifiers:
7681 *
7682 * - Layout Qualifiers as per the table in Section 4.4
7683 * ("Layout Qualifiers") of the GLSL 4.50 spec.
7684 *
7685 * - Memory Qualifiers as per Section 4.10 ("Memory Qualifiers") of the
7686 * GLSL 4.50 spec:
7687 *
7688 * "Additionally, memory qualifiers may also be used in the declaration
7689 * of shader storage blocks"
7690 *
7691 * Note the table in Section 4.4 says std430 is allowed on both uniform and
7692 * buffer blocks however Section 4.4.5 (Uniform and Shader Storage Block
7693 * Layout Qualifiers) of the GLSL 4.50 spec says:
7694 *
7695 * "The std430 qualifier is supported only for shader storage blocks;
7696 * using std430 on a uniform block will result in a compile-time error."
7697 */
7698 ast_type_qualifier allowed_blk_qualifiers;
7699 allowed_blk_qualifiers.flags.i = 0;
7700 if (this->layout.flags.q.buffer || this->layout.flags.q.uniform) {
7701 allowed_blk_qualifiers.flags.q.shared = 1;
7702 allowed_blk_qualifiers.flags.q.packed = 1;
7703 allowed_blk_qualifiers.flags.q.std140 = 1;
7704 allowed_blk_qualifiers.flags.q.row_major = 1;
7705 allowed_blk_qualifiers.flags.q.column_major = 1;
7706 allowed_blk_qualifiers.flags.q.explicit_align = 1;
7707 allowed_blk_qualifiers.flags.q.explicit_binding = 1;
7708 if (this->layout.flags.q.buffer) {
7709 allowed_blk_qualifiers.flags.q.buffer = 1;
7710 allowed_blk_qualifiers.flags.q.std430 = 1;
7711 allowed_blk_qualifiers.flags.q.coherent = 1;
7712 allowed_blk_qualifiers.flags.q._volatile = 1;
7713 allowed_blk_qualifiers.flags.q.restrict_flag = 1;
7714 allowed_blk_qualifiers.flags.q.read_only = 1;
7715 allowed_blk_qualifiers.flags.q.write_only = 1;
7716 } else {
7717 allowed_blk_qualifiers.flags.q.uniform = 1;
7718 }
7719 } else {
7720 /* Interface block */
7721 assert(this->layout.flags.q.in || this->layout.flags.q.out);
7722
7723 allowed_blk_qualifiers.flags.q.explicit_location = 1;
7724 if (this->layout.flags.q.out) {
7725 allowed_blk_qualifiers.flags.q.out = 1;
7726 if (state->stage == MESA_SHADER_GEOMETRY ||
7727 state->stage == MESA_SHADER_TESS_CTRL ||
7728 state->stage == MESA_SHADER_TESS_EVAL ||
7729 state->stage == MESA_SHADER_VERTEX ) {
7730 allowed_blk_qualifiers.flags.q.explicit_xfb_offset = 1;
7731 allowed_blk_qualifiers.flags.q.explicit_xfb_buffer = 1;
7732 allowed_blk_qualifiers.flags.q.xfb_buffer = 1;
7733 allowed_blk_qualifiers.flags.q.explicit_xfb_stride = 1;
7734 allowed_blk_qualifiers.flags.q.xfb_stride = 1;
7735 if (state->stage == MESA_SHADER_GEOMETRY) {
7736 allowed_blk_qualifiers.flags.q.stream = 1;
7737 allowed_blk_qualifiers.flags.q.explicit_stream = 1;
7738 }
7739 if (state->stage == MESA_SHADER_TESS_CTRL) {
7740 allowed_blk_qualifiers.flags.q.patch = 1;
7741 }
7742 }
7743 } else {
7744 allowed_blk_qualifiers.flags.q.in = 1;
7745 if (state->stage == MESA_SHADER_TESS_EVAL) {
7746 allowed_blk_qualifiers.flags.q.patch = 1;
7747 }
7748 }
7749 }
7750
7751 this->layout.validate_flags(&loc, state, allowed_blk_qualifiers,
7752 "invalid qualifier for block",
7753 this->block_name);
7754
7755 enum glsl_interface_packing packing;
7756 if (this->layout.flags.q.std140) {
7757 packing = GLSL_INTERFACE_PACKING_STD140;
7758 } else if (this->layout.flags.q.packed) {
7759 packing = GLSL_INTERFACE_PACKING_PACKED;
7760 } else if (this->layout.flags.q.std430) {
7761 packing = GLSL_INTERFACE_PACKING_STD430;
7762 } else {
7763 /* The default layout is shared.
7764 */
7765 packing = GLSL_INTERFACE_PACKING_SHARED;
7766 }
7767
7768 ir_variable_mode var_mode;
7769 const char *iface_type_name;
7770 if (this->layout.flags.q.in) {
7771 var_mode = ir_var_shader_in;
7772 iface_type_name = "in";
7773 } else if (this->layout.flags.q.out) {
7774 var_mode = ir_var_shader_out;
7775 iface_type_name = "out";
7776 } else if (this->layout.flags.q.uniform) {
7777 var_mode = ir_var_uniform;
7778 iface_type_name = "uniform";
7779 } else if (this->layout.flags.q.buffer) {
7780 var_mode = ir_var_shader_storage;
7781 iface_type_name = "buffer";
7782 } else {
7783 var_mode = ir_var_auto;
7784 iface_type_name = "UNKNOWN";
7785 assert(!"interface block layout qualifier not found!");
7786 }
7787
7788 enum glsl_matrix_layout matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;
7789 if (this->layout.flags.q.row_major)
7790 matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
7791 else if (this->layout.flags.q.column_major)
7792 matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
7793
7794 bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;
7795 exec_list declared_variables;
7796 glsl_struct_field *fields;
7797
7798 /* For blocks that accept memory qualifiers (i.e. shader storage), verify
7799 * that we don't have incompatible qualifiers
7800 */
7801 if (this->layout.flags.q.read_only && this->layout.flags.q.write_only) {
7802 _mesa_glsl_error(&loc, state,
7803 "Interface block sets both readonly and writeonly");
7804 }
7805
7806 unsigned qual_stream;
7807 if (!process_qualifier_constant(state, &loc, "stream", this->layout.stream,
7808 &qual_stream) ||
7809 !validate_stream_qualifier(&loc, state, qual_stream)) {
7810 /* If the stream qualifier is invalid it doesn't make sense to continue
7811 * on and try to compare stream layouts on member variables against it
7812 * so just return early.
7813 */
7814 return NULL;
7815 }
7816
7817 unsigned qual_xfb_buffer;
7818 if (!process_qualifier_constant(state, &loc, "xfb_buffer",
7819 layout.xfb_buffer, &qual_xfb_buffer) ||
7820 !validate_xfb_buffer_qualifier(&loc, state, qual_xfb_buffer)) {
7821 return NULL;
7822 }
7823
7824 unsigned qual_xfb_offset;
7825 if (layout.flags.q.explicit_xfb_offset) {
7826 if (!process_qualifier_constant(state, &loc, "xfb_offset",
7827 layout.offset, &qual_xfb_offset)) {
7828 return NULL;
7829 }
7830 }
7831
7832 unsigned qual_xfb_stride;
7833 if (layout.flags.q.explicit_xfb_stride) {
7834 if (!process_qualifier_constant(state, &loc, "xfb_stride",
7835 layout.xfb_stride, &qual_xfb_stride)) {
7836 return NULL;
7837 }
7838 }
7839
7840 unsigned expl_location = 0;
7841 if (layout.flags.q.explicit_location) {
7842 if (!process_qualifier_constant(state, &loc, "location",
7843 layout.location, &expl_location)) {
7844 return NULL;
7845 } else {
7846 expl_location += this->layout.flags.q.patch ? VARYING_SLOT_PATCH0
7847 : VARYING_SLOT_VAR0;
7848 }
7849 }
7850
7851 unsigned expl_align = 0;
7852 if (layout.flags.q.explicit_align) {
7853 if (!process_qualifier_constant(state, &loc, "align",
7854 layout.align, &expl_align)) {
7855 return NULL;
7856 } else {
7857 if (expl_align == 0 || expl_align & (expl_align - 1)) {
7858 _mesa_glsl_error(&loc, state, "align layout qualifier is not a "
7859 "power of 2.");
7860 return NULL;
7861 }
7862 }
7863 }
7864
7865 unsigned int num_variables =
7866 ast_process_struct_or_iface_block_members(&declared_variables,
7867 state,
7868 &this->declarations,
7869 &fields,
7870 true,
7871 matrix_layout,
7872 redeclaring_per_vertex,
7873 var_mode,
7874 &this->layout,
7875 qual_stream,
7876 qual_xfb_buffer,
7877 qual_xfb_offset,
7878 expl_location,
7879 expl_align);
7880
7881 if (!redeclaring_per_vertex) {
7882 validate_identifier(this->block_name, loc, state);
7883
7884 /* From section 4.3.9 ("Interface Blocks") of the GLSL 4.50 spec:
7885 *
7886 * "Block names have no other use within a shader beyond interface
7887 * matching; it is a compile-time error to use a block name at global
7888 * scope for anything other than as a block name."
7889 */
7890 ir_variable *var = state->symbols->get_variable(this->block_name);
7891 if (var && !var->type->is_interface()) {
7892 _mesa_glsl_error(&loc, state, "Block name `%s' is "
7893 "already used in the scope.",
7894 this->block_name);
7895 }
7896 }
7897
7898 const glsl_type *earlier_per_vertex = NULL;
7899 if (redeclaring_per_vertex) {
7900 /* Find the previous declaration of gl_PerVertex. If we're redeclaring
7901 * the named interface block gl_in, we can find it by looking at the
7902 * previous declaration of gl_in. Otherwise we can find it by looking
7903 * at the previous decalartion of any of the built-in outputs,
7904 * e.g. gl_Position.
7905 *
7906 * Also check that the instance name and array-ness of the redeclaration
7907 * are correct.
7908 */
7909 switch (var_mode) {
7910 case ir_var_shader_in:
7911 if (ir_variable *earlier_gl_in =
7912 state->symbols->get_variable("gl_in")) {
7913 earlier_per_vertex = earlier_gl_in->get_interface_type();
7914 } else {
7915 _mesa_glsl_error(&loc, state,
7916 "redeclaration of gl_PerVertex input not allowed "
7917 "in the %s shader",
7918 _mesa_shader_stage_to_string(state->stage));
7919 }
7920 if (this->instance_name == NULL ||
7921 strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL ||
7922 !this->array_specifier->is_single_dimension()) {
7923 _mesa_glsl_error(&loc, state,
7924 "gl_PerVertex input must be redeclared as "
7925 "gl_in[]");
7926 }
7927 break;
7928 case ir_var_shader_out:
7929 if (ir_variable *earlier_gl_Position =
7930 state->symbols->get_variable("gl_Position")) {
7931 earlier_per_vertex = earlier_gl_Position->get_interface_type();
7932 } else if (ir_variable *earlier_gl_out =
7933 state->symbols->get_variable("gl_out")) {
7934 earlier_per_vertex = earlier_gl_out->get_interface_type();
7935 } else {
7936 _mesa_glsl_error(&loc, state,
7937 "redeclaration of gl_PerVertex output not "
7938 "allowed in the %s shader",
7939 _mesa_shader_stage_to_string(state->stage));
7940 }
7941 if (state->stage == MESA_SHADER_TESS_CTRL) {
7942 if (this->instance_name == NULL ||
7943 strcmp(this->instance_name, "gl_out") != 0 || this->array_specifier == NULL) {
7944 _mesa_glsl_error(&loc, state,
7945 "gl_PerVertex output must be redeclared as "
7946 "gl_out[]");
7947 }
7948 } else {
7949 if (this->instance_name != NULL) {
7950 _mesa_glsl_error(&loc, state,
7951 "gl_PerVertex output may not be redeclared with "
7952 "an instance name");
7953 }
7954 }
7955 break;
7956 default:
7957 _mesa_glsl_error(&loc, state,
7958 "gl_PerVertex must be declared as an input or an "
7959 "output");
7960 break;
7961 }
7962
7963 if (earlier_per_vertex == NULL) {
7964 /* An error has already been reported. Bail out to avoid null
7965 * dereferences later in this function.
7966 */
7967 return NULL;
7968 }
7969
7970 /* Copy locations from the old gl_PerVertex interface block. */
7971 for (unsigned i = 0; i < num_variables; i++) {
7972 int j = earlier_per_vertex->field_index(fields[i].name);
7973 if (j == -1) {
7974 _mesa_glsl_error(&loc, state,
7975 "redeclaration of gl_PerVertex must be a subset "
7976 "of the built-in members of gl_PerVertex");
7977 } else {
7978 fields[i].location =
7979 earlier_per_vertex->fields.structure[j].location;
7980 fields[i].offset =
7981 earlier_per_vertex->fields.structure[j].offset;
7982 fields[i].interpolation =
7983 earlier_per_vertex->fields.structure[j].interpolation;
7984 fields[i].centroid =
7985 earlier_per_vertex->fields.structure[j].centroid;
7986 fields[i].sample =
7987 earlier_per_vertex->fields.structure[j].sample;
7988 fields[i].patch =
7989 earlier_per_vertex->fields.structure[j].patch;
7990 fields[i].precision =
7991 earlier_per_vertex->fields.structure[j].precision;
7992 fields[i].explicit_xfb_buffer =
7993 earlier_per_vertex->fields.structure[j].explicit_xfb_buffer;
7994 fields[i].xfb_buffer =
7995 earlier_per_vertex->fields.structure[j].xfb_buffer;
7996 fields[i].xfb_stride =
7997 earlier_per_vertex->fields.structure[j].xfb_stride;
7998 }
7999 }
8000
8001 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10
8002 * spec:
8003 *
8004 * If a built-in interface block is redeclared, it must appear in
8005 * the shader before any use of any member included in the built-in
8006 * declaration, or a compilation error will result.
8007 *
8008 * This appears to be a clarification to the behaviour established for
8009 * gl_PerVertex by GLSL 1.50, therefore we implement this behaviour
8010 * regardless of GLSL version.
8011 */
8012 interface_block_usage_visitor v(var_mode, earlier_per_vertex);
8013 v.run(instructions);
8014 if (v.usage_found()) {
8015 _mesa_glsl_error(&loc, state,
8016 "redeclaration of a built-in interface block must "
8017 "appear before any use of any member of the "
8018 "interface block");
8019 }
8020 }
8021
8022 const glsl_type *block_type =
8023 glsl_type::get_interface_instance(fields,
8024 num_variables,
8025 packing,
8026 matrix_layout ==
8027 GLSL_MATRIX_LAYOUT_ROW_MAJOR,
8028 this->block_name);
8029
8030 unsigned component_size = block_type->contains_double() ? 8 : 4;
8031 int xfb_offset =
8032 layout.flags.q.explicit_xfb_offset ? (int) qual_xfb_offset : -1;
8033 validate_xfb_offset_qualifier(&loc, state, xfb_offset, block_type,
8034 component_size);
8035
8036 if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {
8037 YYLTYPE loc = this->get_location();
8038 _mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "
8039 "already taken in the current scope",
8040 this->block_name, iface_type_name);
8041 }
8042
8043 /* Since interface blocks cannot contain statements, it should be
8044 * impossible for the block to generate any instructions.
8045 */
8046 assert(declared_variables.is_empty());
8047
8048 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
8049 *
8050 * Geometry shader input variables get the per-vertex values written
8051 * out by vertex shader output variables of the same names. Since a
8052 * geometry shader operates on a set of vertices, each input varying
8053 * variable (or input block, see interface blocks below) needs to be
8054 * declared as an array.
8055 */
8056 if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&
8057 var_mode == ir_var_shader_in) {
8058 _mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");
8059 } else if ((state->stage == MESA_SHADER_TESS_CTRL ||
8060 state->stage == MESA_SHADER_TESS_EVAL) &&
8061 !this->layout.flags.q.patch &&
8062 this->array_specifier == NULL &&
8063 var_mode == ir_var_shader_in) {
8064 _mesa_glsl_error(&loc, state, "per-vertex tessellation shader inputs must be arrays");
8065 } else if (state->stage == MESA_SHADER_TESS_CTRL &&
8066 !this->layout.flags.q.patch &&
8067 this->array_specifier == NULL &&
8068 var_mode == ir_var_shader_out) {
8069 _mesa_glsl_error(&loc, state, "tessellation control shader outputs must be arrays");
8070 }
8071
8072
8073 /* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec
8074 * says:
8075 *
8076 * "If an instance name (instance-name) is used, then it puts all the
8077 * members inside a scope within its own name space, accessed with the
8078 * field selector ( . ) operator (analogously to structures)."
8079 */
8080 if (this->instance_name) {
8081 if (redeclaring_per_vertex) {
8082 /* When a built-in in an unnamed interface block is redeclared,
8083 * get_variable_being_redeclared() calls
8084 * check_builtin_array_max_size() to make sure that built-in array
8085 * variables aren't redeclared to illegal sizes. But we're looking
8086 * at a redeclaration of a named built-in interface block. So we
8087 * have to manually call check_builtin_array_max_size() for all parts
8088 * of the interface that are arrays.
8089 */
8090 for (unsigned i = 0; i < num_variables; i++) {
8091 if (fields[i].type->is_array()) {
8092 const unsigned size = fields[i].type->array_size();
8093 check_builtin_array_max_size(fields[i].name, size, loc, state);
8094 }
8095 }
8096 } else {
8097 validate_identifier(this->instance_name, loc, state);
8098 }
8099
8100 ir_variable *var;
8101
8102 if (this->array_specifier != NULL) {
8103 const glsl_type *block_array_type =
8104 process_array_type(&loc, block_type, this->array_specifier, state);
8105
8106 /* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:
8107 *
8108 * For uniform blocks declared an array, each individual array
8109 * element corresponds to a separate buffer object backing one
8110 * instance of the block. As the array size indicates the number
8111 * of buffer objects needed, uniform block array declarations
8112 * must specify an array size.
8113 *
8114 * And a few paragraphs later:
8115 *
8116 * Geometry shader input blocks must be declared as arrays and
8117 * follow the array declaration and linking rules for all
8118 * geometry shader inputs. All other input and output block
8119 * arrays must specify an array size.
8120 *
8121 * The same applies to tessellation shaders.
8122 *
8123 * The upshot of this is that the only circumstance where an
8124 * interface array size *doesn't* need to be specified is on a
8125 * geometry shader input, tessellation control shader input,
8126 * tessellation control shader output, and tessellation evaluation
8127 * shader input.
8128 */
8129 if (block_array_type->is_unsized_array()) {
8130 bool allow_inputs = state->stage == MESA_SHADER_GEOMETRY ||
8131 state->stage == MESA_SHADER_TESS_CTRL ||
8132 state->stage == MESA_SHADER_TESS_EVAL;
8133 bool allow_outputs = state->stage == MESA_SHADER_TESS_CTRL;
8134
8135 if (this->layout.flags.q.in) {
8136 if (!allow_inputs)
8137 _mesa_glsl_error(&loc, state,
8138 "unsized input block arrays not allowed in "
8139 "%s shader",
8140 _mesa_shader_stage_to_string(state->stage));
8141 } else if (this->layout.flags.q.out) {
8142 if (!allow_outputs)
8143 _mesa_glsl_error(&loc, state,
8144 "unsized output block arrays not allowed in "
8145 "%s shader",
8146 _mesa_shader_stage_to_string(state->stage));
8147 } else {
8148 /* by elimination, this is a uniform block array */
8149 _mesa_glsl_error(&loc, state,
8150 "unsized uniform block arrays not allowed in "
8151 "%s shader",
8152 _mesa_shader_stage_to_string(state->stage));
8153 }
8154 }
8155
8156 /* From section 4.3.9 (Interface Blocks) of the GLSL ES 3.10 spec:
8157 *
8158 * * Arrays of arrays of blocks are not allowed
8159 */
8160 if (state->es_shader && block_array_type->is_array() &&
8161 block_array_type->fields.array->is_array()) {
8162 _mesa_glsl_error(&loc, state,
8163 "arrays of arrays interface blocks are "
8164 "not allowed");
8165 }
8166
8167 var = new(state) ir_variable(block_array_type,
8168 this->instance_name,
8169 var_mode);
8170 } else {
8171 var = new(state) ir_variable(block_type,
8172 this->instance_name,
8173 var_mode);
8174 }
8175
8176 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
8177 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
8178
8179 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
8180 var->data.read_only = true;
8181
8182 var->data.patch = this->layout.flags.q.patch;
8183
8184 if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)
8185 handle_geometry_shader_input_decl(state, loc, var);
8186 else if ((state->stage == MESA_SHADER_TESS_CTRL ||
8187 state->stage == MESA_SHADER_TESS_EVAL) && var_mode == ir_var_shader_in)
8188 handle_tess_shader_input_decl(state, loc, var);
8189 else if (state->stage == MESA_SHADER_TESS_CTRL && var_mode == ir_var_shader_out)
8190 handle_tess_ctrl_shader_output_decl(state, loc, var);
8191
8192 for (unsigned i = 0; i < num_variables; i++) {
8193 if (var->data.mode == ir_var_shader_storage)
8194 apply_memory_qualifiers(var, fields[i]);
8195 }
8196
8197 if (ir_variable *earlier =
8198 state->symbols->get_variable(this->instance_name)) {
8199 if (!redeclaring_per_vertex) {
8200 _mesa_glsl_error(&loc, state, "`%s' redeclared",
8201 this->instance_name);
8202 }
8203 earlier->data.how_declared = ir_var_declared_normally;
8204 earlier->type = var->type;
8205 earlier->reinit_interface_type(block_type);
8206 delete var;
8207 } else {
8208 if (this->layout.flags.q.explicit_binding) {
8209 apply_explicit_binding(state, &loc, var, var->type,
8210 &this->layout);
8211 }
8212
8213 var->data.stream = qual_stream;
8214 if (layout.flags.q.explicit_location) {
8215 var->data.location = expl_location;
8216 var->data.explicit_location = true;
8217 }
8218
8219 state->symbols->add_variable(var);
8220 instructions->push_tail(var);
8221 }
8222 } else {
8223 /* In order to have an array size, the block must also be declared with
8224 * an instance name.
8225 */
8226 assert(this->array_specifier == NULL);
8227
8228 for (unsigned i = 0; i < num_variables; i++) {
8229 ir_variable *var =
8230 new(state) ir_variable(fields[i].type,
8231 ralloc_strdup(state, fields[i].name),
8232 var_mode);
8233 var->data.interpolation = fields[i].interpolation;
8234 var->data.centroid = fields[i].centroid;
8235 var->data.sample = fields[i].sample;
8236 var->data.patch = fields[i].patch;
8237 var->data.stream = qual_stream;
8238 var->data.location = fields[i].location;
8239
8240 if (fields[i].location != -1)
8241 var->data.explicit_location = true;
8242
8243 var->data.explicit_xfb_buffer = fields[i].explicit_xfb_buffer;
8244 var->data.xfb_buffer = fields[i].xfb_buffer;
8245
8246 if (fields[i].offset != -1)
8247 var->data.explicit_xfb_offset = true;
8248 var->data.offset = fields[i].offset;
8249
8250 var->init_interface_type(block_type);
8251
8252 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
8253 var->data.read_only = true;
8254
8255 /* Precision qualifiers do not have any meaning in Desktop GLSL */
8256 if (state->es_shader) {
8257 var->data.precision =
8258 select_gles_precision(fields[i].precision, fields[i].type,
8259 state, &loc);
8260 }
8261
8262 if (fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED) {
8263 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
8264 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
8265 } else {
8266 var->data.matrix_layout = fields[i].matrix_layout;
8267 }
8268
8269 if (var->data.mode == ir_var_shader_storage)
8270 apply_memory_qualifiers(var, fields[i]);
8271
8272 /* Examine var name here since var may get deleted in the next call */
8273 bool var_is_gl_id = is_gl_identifier(var->name);
8274
8275 if (redeclaring_per_vertex) {
8276 bool is_redeclaration;
8277 var =
8278 get_variable_being_redeclared(&var, loc, state,
8279 true /* allow_all_redeclarations */,
8280 &is_redeclaration);
8281 if (!var_is_gl_id || !is_redeclaration) {
8282 _mesa_glsl_error(&loc, state,
8283 "redeclaration of gl_PerVertex can only "
8284 "include built-in variables");
8285 } else if (var->data.how_declared == ir_var_declared_normally) {
8286 _mesa_glsl_error(&loc, state,
8287 "`%s' has already been redeclared",
8288 var->name);
8289 } else {
8290 var->data.how_declared = ir_var_declared_in_block;
8291 var->reinit_interface_type(block_type);
8292 }
8293 continue;
8294 }
8295
8296 if (state->symbols->get_variable(var->name) != NULL)
8297 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
8298
8299 /* Propagate the "binding" keyword into this UBO/SSBO's fields.
8300 * The UBO declaration itself doesn't get an ir_variable unless it
8301 * has an instance name. This is ugly.
8302 */
8303 if (this->layout.flags.q.explicit_binding) {
8304 apply_explicit_binding(state, &loc, var,
8305 var->get_interface_type(), &this->layout);
8306 }
8307
8308 if (var->type->is_unsized_array()) {
8309 if (var->is_in_shader_storage_block() &&
8310 is_unsized_array_last_element(var)) {
8311 var->data.from_ssbo_unsized_array = true;
8312 } else {
8313 /* From GLSL ES 3.10 spec, section 4.1.9 "Arrays":
8314 *
8315 * "If an array is declared as the last member of a shader storage
8316 * block and the size is not specified at compile-time, it is
8317 * sized at run-time. In all other cases, arrays are sized only
8318 * at compile-time."
8319 *
8320 * In desktop GLSL it is allowed to have unsized-arrays that are
8321 * not last, as long as we can determine that they are implicitly
8322 * sized.
8323 */
8324 if (state->es_shader) {
8325 _mesa_glsl_error(&loc, state, "unsized array `%s' "
8326 "definition: only last member of a shader "
8327 "storage block can be defined as unsized "
8328 "array", fields[i].name);
8329 }
8330 }
8331 }
8332
8333 state->symbols->add_variable(var);
8334 instructions->push_tail(var);
8335 }
8336
8337 if (redeclaring_per_vertex && block_type != earlier_per_vertex) {
8338 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:
8339 *
8340 * It is also a compilation error ... to redeclare a built-in
8341 * block and then use a member from that built-in block that was
8342 * not included in the redeclaration.
8343 *
8344 * This appears to be a clarification to the behaviour established
8345 * for gl_PerVertex by GLSL 1.50, therefore we implement this
8346 * behaviour regardless of GLSL version.
8347 *
8348 * To prevent the shader from using a member that was not included in
8349 * the redeclaration, we disable any ir_variables that are still
8350 * associated with the old declaration of gl_PerVertex (since we've
8351 * already updated all of the variables contained in the new
8352 * gl_PerVertex to point to it).
8353 *
8354 * As a side effect this will prevent
8355 * validate_intrastage_interface_blocks() from getting confused and
8356 * thinking there are conflicting definitions of gl_PerVertex in the
8357 * shader.
8358 */
8359 foreach_in_list_safe(ir_instruction, node, instructions) {
8360 ir_variable *const var = node->as_variable();
8361 if (var != NULL &&
8362 var->get_interface_type() == earlier_per_vertex &&
8363 var->data.mode == var_mode) {
8364 if (var->data.how_declared == ir_var_declared_normally) {
8365 _mesa_glsl_error(&loc, state,
8366 "redeclaration of gl_PerVertex cannot "
8367 "follow a redeclaration of `%s'",
8368 var->name);
8369 }
8370 state->symbols->disable_variable(var->name);
8371 var->remove();
8372 }
8373 }
8374 }
8375 }
8376
8377 return NULL;
8378 }
8379
8380
8381 ir_rvalue *
8382 ast_tcs_output_layout::hir(exec_list *instructions,
8383 struct _mesa_glsl_parse_state *state)
8384 {
8385 YYLTYPE loc = this->get_location();
8386
8387 unsigned num_vertices;
8388 if (!state->out_qualifier->vertices->
8389 process_qualifier_constant(state, "vertices", &num_vertices,
8390 false)) {
8391 /* return here to stop cascading incorrect error messages */
8392 return NULL;
8393 }
8394
8395 /* If any shader outputs occurred before this declaration and specified an
8396 * array size, make sure the size they specified is consistent with the
8397 * primitive type.
8398 */
8399 if (state->tcs_output_size != 0 && state->tcs_output_size != num_vertices) {
8400 _mesa_glsl_error(&loc, state,
8401 "this tessellation control shader output layout "
8402 "specifies %u vertices, but a previous output "
8403 "is declared with size %u",
8404 num_vertices, state->tcs_output_size);
8405 return NULL;
8406 }
8407
8408 state->tcs_output_vertices_specified = true;
8409
8410 /* If any shader outputs occurred before this declaration and did not
8411 * specify an array size, their size is determined now.
8412 */
8413 foreach_in_list (ir_instruction, node, instructions) {
8414 ir_variable *var = node->as_variable();
8415 if (var == NULL || var->data.mode != ir_var_shader_out)
8416 continue;
8417
8418 /* Note: Not all tessellation control shader output are arrays. */
8419 if (!var->type->is_unsized_array() || var->data.patch)
8420 continue;
8421
8422 if (var->data.max_array_access >= (int)num_vertices) {
8423 _mesa_glsl_error(&loc, state,
8424 "this tessellation control shader output layout "
8425 "specifies %u vertices, but an access to element "
8426 "%u of output `%s' already exists", num_vertices,
8427 var->data.max_array_access, var->name);
8428 } else {
8429 var->type = glsl_type::get_array_instance(var->type->fields.array,
8430 num_vertices);
8431 }
8432 }
8433
8434 return NULL;
8435 }
8436
8437
8438 ir_rvalue *
8439 ast_gs_input_layout::hir(exec_list *instructions,
8440 struct _mesa_glsl_parse_state *state)
8441 {
8442 YYLTYPE loc = this->get_location();
8443
8444 /* Should have been prevented by the parser. */
8445 assert(!state->gs_input_prim_type_specified
8446 || state->in_qualifier->prim_type == this->prim_type);
8447
8448 /* If any shader inputs occurred before this declaration and specified an
8449 * array size, make sure the size they specified is consistent with the
8450 * primitive type.
8451 */
8452 unsigned num_vertices = vertices_per_prim(this->prim_type);
8453 if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {
8454 _mesa_glsl_error(&loc, state,
8455 "this geometry shader input layout implies %u vertices"
8456 " per primitive, but a previous input is declared"
8457 " with size %u", num_vertices, state->gs_input_size);
8458 return NULL;
8459 }
8460
8461 state->gs_input_prim_type_specified = true;
8462
8463 /* If any shader inputs occurred before this declaration and did not
8464 * specify an array size, their size is determined now.
8465 */
8466 foreach_in_list(ir_instruction, node, instructions) {
8467 ir_variable *var = node->as_variable();
8468 if (var == NULL || var->data.mode != ir_var_shader_in)
8469 continue;
8470
8471 /* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an
8472 * array; skip it.
8473 */
8474
8475 if (var->type->is_unsized_array()) {
8476 if (var->data.max_array_access >= (int)num_vertices) {
8477 _mesa_glsl_error(&loc, state,
8478 "this geometry shader input layout implies %u"
8479 " vertices, but an access to element %u of input"
8480 " `%s' already exists", num_vertices,
8481 var->data.max_array_access, var->name);
8482 } else {
8483 var->type = glsl_type::get_array_instance(var->type->fields.array,
8484 num_vertices);
8485 }
8486 }
8487 }
8488
8489 return NULL;
8490 }
8491
8492
8493 ir_rvalue *
8494 ast_cs_input_layout::hir(exec_list *instructions,
8495 struct _mesa_glsl_parse_state *state)
8496 {
8497 YYLTYPE loc = this->get_location();
8498
8499 /* From the ARB_compute_shader specification:
8500 *
8501 * If the local size of the shader in any dimension is greater
8502 * than the maximum size supported by the implementation for that
8503 * dimension, a compile-time error results.
8504 *
8505 * It is not clear from the spec how the error should be reported if
8506 * the total size of the work group exceeds
8507 * MAX_COMPUTE_WORK_GROUP_INVOCATIONS, but it seems reasonable to
8508 * report it at compile time as well.
8509 */
8510 GLuint64 total_invocations = 1;
8511 unsigned qual_local_size[3];
8512 for (int i = 0; i < 3; i++) {
8513
8514 char *local_size_str = ralloc_asprintf(NULL, "invalid local_size_%c",
8515 'x' + i);
8516 /* Infer a local_size of 1 for unspecified dimensions */
8517 if (this->local_size[i] == NULL) {
8518 qual_local_size[i] = 1;
8519 } else if (!this->local_size[i]->
8520 process_qualifier_constant(state, local_size_str,
8521 &qual_local_size[i], false)) {
8522 ralloc_free(local_size_str);
8523 return NULL;
8524 }
8525 ralloc_free(local_size_str);
8526
8527 if (qual_local_size[i] > state->ctx->Const.MaxComputeWorkGroupSize[i]) {
8528 _mesa_glsl_error(&loc, state,
8529 "local_size_%c exceeds MAX_COMPUTE_WORK_GROUP_SIZE"
8530 " (%d)", 'x' + i,
8531 state->ctx->Const.MaxComputeWorkGroupSize[i]);
8532 break;
8533 }
8534 total_invocations *= qual_local_size[i];
8535 if (total_invocations >
8536 state->ctx->Const.MaxComputeWorkGroupInvocations) {
8537 _mesa_glsl_error(&loc, state,
8538 "product of local_sizes exceeds "
8539 "MAX_COMPUTE_WORK_GROUP_INVOCATIONS (%d)",
8540 state->ctx->Const.MaxComputeWorkGroupInvocations);
8541 break;
8542 }
8543 }
8544
8545 /* If any compute input layout declaration preceded this one, make sure it
8546 * was consistent with this one.
8547 */
8548 if (state->cs_input_local_size_specified) {
8549 for (int i = 0; i < 3; i++) {
8550 if (state->cs_input_local_size[i] != qual_local_size[i]) {
8551 _mesa_glsl_error(&loc, state,
8552 "compute shader input layout does not match"
8553 " previous declaration");
8554 return NULL;
8555 }
8556 }
8557 }
8558
8559 /* The ARB_compute_variable_group_size spec says:
8560 *
8561 * If a compute shader including a *local_size_variable* qualifier also
8562 * declares a fixed local group size using the *local_size_x*,
8563 * *local_size_y*, or *local_size_z* qualifiers, a compile-time error
8564 * results
8565 */
8566 if (state->cs_input_local_size_variable_specified) {
8567 _mesa_glsl_error(&loc, state,
8568 "compute shader can't include both a variable and a "
8569 "fixed local group size");
8570 return NULL;
8571 }
8572
8573 state->cs_input_local_size_specified = true;
8574 for (int i = 0; i < 3; i++)
8575 state->cs_input_local_size[i] = qual_local_size[i];
8576
8577 /* We may now declare the built-in constant gl_WorkGroupSize (see
8578 * builtin_variable_generator::generate_constants() for why we didn't
8579 * declare it earlier).
8580 */
8581 ir_variable *var = new(state->symbols)
8582 ir_variable(glsl_type::uvec3_type, "gl_WorkGroupSize", ir_var_auto);
8583 var->data.how_declared = ir_var_declared_implicitly;
8584 var->data.read_only = true;
8585 instructions->push_tail(var);
8586 state->symbols->add_variable(var);
8587 ir_constant_data data;
8588 memset(&data, 0, sizeof(data));
8589 for (int i = 0; i < 3; i++)
8590 data.u[i] = qual_local_size[i];
8591 var->constant_value = new(var) ir_constant(glsl_type::uvec3_type, &data);
8592 var->constant_initializer =
8593 new(var) ir_constant(glsl_type::uvec3_type, &data);
8594 var->data.has_initializer = true;
8595
8596 return NULL;
8597 }
8598
8599
8600 static void
8601 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
8602 exec_list *instructions)
8603 {
8604 bool gl_FragColor_assigned = false;
8605 bool gl_FragData_assigned = false;
8606 bool gl_FragSecondaryColor_assigned = false;
8607 bool gl_FragSecondaryData_assigned = false;
8608 bool user_defined_fs_output_assigned = false;
8609 ir_variable *user_defined_fs_output = NULL;
8610
8611 /* It would be nice to have proper location information. */
8612 YYLTYPE loc;
8613 memset(&loc, 0, sizeof(loc));
8614
8615 foreach_in_list(ir_instruction, node, instructions) {
8616 ir_variable *var = node->as_variable();
8617
8618 if (!var || !var->data.assigned)
8619 continue;
8620
8621 if (strcmp(var->name, "gl_FragColor") == 0)
8622 gl_FragColor_assigned = true;
8623 else if (strcmp(var->name, "gl_FragData") == 0)
8624 gl_FragData_assigned = true;
8625 else if (strcmp(var->name, "gl_SecondaryFragColorEXT") == 0)
8626 gl_FragSecondaryColor_assigned = true;
8627 else if (strcmp(var->name, "gl_SecondaryFragDataEXT") == 0)
8628 gl_FragSecondaryData_assigned = true;
8629 else if (!is_gl_identifier(var->name)) {
8630 if (state->stage == MESA_SHADER_FRAGMENT &&
8631 var->data.mode == ir_var_shader_out) {
8632 user_defined_fs_output_assigned = true;
8633 user_defined_fs_output = var;
8634 }
8635 }
8636 }
8637
8638 /* From the GLSL 1.30 spec:
8639 *
8640 * "If a shader statically assigns a value to gl_FragColor, it
8641 * may not assign a value to any element of gl_FragData. If a
8642 * shader statically writes a value to any element of
8643 * gl_FragData, it may not assign a value to
8644 * gl_FragColor. That is, a shader may assign values to either
8645 * gl_FragColor or gl_FragData, but not both. Multiple shaders
8646 * linked together must also consistently write just one of
8647 * these variables. Similarly, if user declared output
8648 * variables are in use (statically assigned to), then the
8649 * built-in variables gl_FragColor and gl_FragData may not be
8650 * assigned to. These incorrect usages all generate compile
8651 * time errors."
8652 */
8653 if (gl_FragColor_assigned && gl_FragData_assigned) {
8654 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8655 "`gl_FragColor' and `gl_FragData'");
8656 } else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {
8657 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8658 "`gl_FragColor' and `%s'",
8659 user_defined_fs_output->name);
8660 } else if (gl_FragSecondaryColor_assigned && gl_FragSecondaryData_assigned) {
8661 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8662 "`gl_FragSecondaryColorEXT' and"
8663 " `gl_FragSecondaryDataEXT'");
8664 } else if (gl_FragColor_assigned && gl_FragSecondaryData_assigned) {
8665 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8666 "`gl_FragColor' and"
8667 " `gl_FragSecondaryDataEXT'");
8668 } else if (gl_FragData_assigned && gl_FragSecondaryColor_assigned) {
8669 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8670 "`gl_FragData' and"
8671 " `gl_FragSecondaryColorEXT'");
8672 } else if (gl_FragData_assigned && user_defined_fs_output_assigned) {
8673 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
8674 "`gl_FragData' and `%s'",
8675 user_defined_fs_output->name);
8676 }
8677
8678 if ((gl_FragSecondaryColor_assigned || gl_FragSecondaryData_assigned) &&
8679 !state->EXT_blend_func_extended_enable) {
8680 _mesa_glsl_error(&loc, state,
8681 "Dual source blending requires EXT_blend_func_extended");
8682 }
8683 }
8684
8685 static void
8686 verify_subroutine_associated_funcs(struct _mesa_glsl_parse_state *state)
8687 {
8688 YYLTYPE loc;
8689 memset(&loc, 0, sizeof(loc));
8690
8691 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
8692 *
8693 * "A program will fail to compile or link if any shader
8694 * or stage contains two or more functions with the same
8695 * name if the name is associated with a subroutine type."
8696 */
8697
8698 for (int i = 0; i < state->num_subroutines; i++) {
8699 unsigned definitions = 0;
8700 ir_function *fn = state->subroutines[i];
8701 /* Calculate number of function definitions with the same name */
8702 foreach_in_list(ir_function_signature, sig, &fn->signatures) {
8703 if (sig->is_defined) {
8704 if (++definitions > 1) {
8705 _mesa_glsl_error(&loc, state,
8706 "%s shader contains two or more function "
8707 "definitions with name `%s', which is "
8708 "associated with a subroutine type.\n",
8709 _mesa_shader_stage_to_string(state->stage),
8710 fn->name);
8711 return;
8712 }
8713 }
8714 }
8715 }
8716 }
8717
8718 static void
8719 remove_per_vertex_blocks(exec_list *instructions,
8720 _mesa_glsl_parse_state *state, ir_variable_mode mode)
8721 {
8722 /* Find the gl_PerVertex interface block of the appropriate (in/out) mode,
8723 * if it exists in this shader type.
8724 */
8725 const glsl_type *per_vertex = NULL;
8726 switch (mode) {
8727 case ir_var_shader_in:
8728 if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))
8729 per_vertex = gl_in->get_interface_type();
8730 break;
8731 case ir_var_shader_out:
8732 if (ir_variable *gl_Position =
8733 state->symbols->get_variable("gl_Position")) {
8734 per_vertex = gl_Position->get_interface_type();
8735 }
8736 break;
8737 default:
8738 assert(!"Unexpected mode");
8739 break;
8740 }
8741
8742 /* If we didn't find a built-in gl_PerVertex interface block, then we don't
8743 * need to do anything.
8744 */
8745 if (per_vertex == NULL)
8746 return;
8747
8748 /* If the interface block is used by the shader, then we don't need to do
8749 * anything.
8750 */
8751 interface_block_usage_visitor v(mode, per_vertex);
8752 v.run(instructions);
8753 if (v.usage_found())
8754 return;
8755
8756 /* Remove any ir_variable declarations that refer to the interface block
8757 * we're removing.
8758 */
8759 foreach_in_list_safe(ir_instruction, node, instructions) {
8760 ir_variable *const var = node->as_variable();
8761 if (var != NULL && var->get_interface_type() == per_vertex &&
8762 var->data.mode == mode) {
8763 state->symbols->disable_variable(var->name);
8764 var->remove();
8765 }
8766 }
8767 }