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