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