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