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