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