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