glsl: Move the definition of precision_qualifier_allowed
[mesa.git] / src / 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 "glsl_types.h"
56 #include "program/hash_table.h"
57 #include "main/shaderobj.h"
58 #include "ir.h"
59 #include "ir_builder.h"
60
61 using namespace ir_builder;
62
63 static void
64 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
65 exec_list *instructions);
66 static void
67 remove_per_vertex_blocks(exec_list *instructions,
68 _mesa_glsl_parse_state *state, ir_variable_mode mode);
69
70 /**
71 * Visitor class that finds the first instance of any write-only variable that
72 * is ever read, if any
73 */
74 class read_from_write_only_variable_visitor : public ir_hierarchical_visitor
75 {
76 public:
77 read_from_write_only_variable_visitor() : found(NULL)
78 {
79 }
80
81 virtual ir_visitor_status visit(ir_dereference_variable *ir)
82 {
83 if (this->in_assignee)
84 return visit_continue;
85
86 ir_variable *var = ir->variable_referenced();
87 /* We can have image_write_only set on both images and buffer variables,
88 * but in the former there is a distinction between reads from
89 * the variable itself (write_only) and from the memory they point to
90 * (image_write_only), while in the case of buffer variables there is
91 * no such distinction, that is why this check here is limited to
92 * buffer variables alone.
93 */
94 if (!var || var->data.mode != ir_var_shader_storage)
95 return visit_continue;
96
97 if (var->data.image_write_only) {
98 found = var;
99 return visit_stop;
100 }
101
102 return visit_continue;
103 }
104
105 ir_variable *get_variable() {
106 return found;
107 }
108
109 private:
110 ir_variable *found;
111 };
112
113 void
114 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
115 {
116 _mesa_glsl_initialize_variables(instructions, state);
117
118 state->symbols->separate_function_namespace = state->language_version == 110;
119
120 state->current_function = NULL;
121
122 state->toplevel_ir = instructions;
123
124 state->gs_input_prim_type_specified = false;
125 state->tcs_output_vertices_specified = false;
126 state->cs_input_local_size_specified = false;
127
128 /* Section 4.2 of the GLSL 1.20 specification states:
129 * "The built-in functions are scoped in a scope outside the global scope
130 * users declare global variables in. That is, a shader's global scope,
131 * available for user-defined functions and global variables, is nested
132 * inside the scope containing the built-in functions."
133 *
134 * Since built-in functions like ftransform() access built-in variables,
135 * it follows that those must be in the outer scope as well.
136 *
137 * We push scope here to create this nesting effect...but don't pop.
138 * This way, a shader's globals are still in the symbol table for use
139 * by the linker.
140 */
141 state->symbols->push_scope();
142
143 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
144 ast->hir(instructions, state);
145
146 detect_recursion_unlinked(state, instructions);
147 detect_conflicting_assignments(state, instructions);
148
149 state->toplevel_ir = NULL;
150
151 /* Move all of the variable declarations to the front of the IR list, and
152 * reverse the order. This has the (intended!) side effect that vertex
153 * shader inputs and fragment shader outputs will appear in the IR in the
154 * same order that they appeared in the shader code. This results in the
155 * locations being assigned in the declared order. Many (arguably buggy)
156 * applications depend on this behavior, and it matches what nearly all
157 * other drivers do.
158 */
159 foreach_in_list_safe(ir_instruction, node, instructions) {
160 ir_variable *const var = node->as_variable();
161
162 if (var == NULL)
163 continue;
164
165 var->remove();
166 instructions->push_head(var);
167 }
168
169 /* Figure out if gl_FragCoord is actually used in fragment shader */
170 ir_variable *const var = state->symbols->get_variable("gl_FragCoord");
171 if (var != NULL)
172 state->fs_uses_gl_fragcoord = var->data.used;
173
174 /* From section 7.1 (Built-In Language Variables) of the GLSL 4.10 spec:
175 *
176 * If multiple shaders using members of a built-in block belonging to
177 * the same interface are linked together in the same program, they
178 * must all redeclare the built-in block in the same way, as described
179 * in section 4.3.7 "Interface Blocks" for interface block matching, or
180 * a link error will result.
181 *
182 * The phrase "using members of a built-in block" implies that if two
183 * shaders are linked together and one of them *does not use* any members
184 * of the built-in block, then that shader does not need to have a matching
185 * redeclaration of the built-in block.
186 *
187 * This appears to be a clarification to the behaviour established for
188 * gl_PerVertex by GLSL 1.50, therefore implement it regardless of GLSL
189 * version.
190 *
191 * The definition of "interface" in section 4.3.7 that applies here is as
192 * follows:
193 *
194 * The boundary between adjacent programmable pipeline stages: This
195 * spans all the outputs in all compilation units of the first stage
196 * and all the inputs in all compilation units of the second stage.
197 *
198 * Therefore this rule applies to both inter- and intra-stage linking.
199 *
200 * The easiest way to implement this is to check whether the shader uses
201 * gl_PerVertex right after ast-to-ir conversion, and if it doesn't, simply
202 * remove all the relevant variable declaration from the IR, so that the
203 * linker won't see them and complain about mismatches.
204 */
205 remove_per_vertex_blocks(instructions, state, ir_var_shader_in);
206 remove_per_vertex_blocks(instructions, state, ir_var_shader_out);
207
208 /* Check that we don't have reads from write-only variables */
209 read_from_write_only_variable_visitor v;
210 v.run(instructions);
211 ir_variable *error_var = v.get_variable();
212 if (error_var) {
213 /* It would be nice to have proper location information, but for that
214 * we would need to check this as we process each kind of AST node
215 */
216 YYLTYPE loc;
217 memset(&loc, 0, sizeof(loc));
218 _mesa_glsl_error(&loc, state, "Read from write-only variable `%s'",
219 error_var->name);
220 }
221 }
222
223
224 static ir_expression_operation
225 get_conversion_operation(const glsl_type *to, const glsl_type *from,
226 struct _mesa_glsl_parse_state *state)
227 {
228 switch (to->base_type) {
229 case GLSL_TYPE_FLOAT:
230 switch (from->base_type) {
231 case GLSL_TYPE_INT: return ir_unop_i2f;
232 case GLSL_TYPE_UINT: return ir_unop_u2f;
233 case GLSL_TYPE_DOUBLE: return ir_unop_d2f;
234 default: return (ir_expression_operation)0;
235 }
236
237 case GLSL_TYPE_UINT:
238 if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable)
239 return (ir_expression_operation)0;
240 switch (from->base_type) {
241 case GLSL_TYPE_INT: return ir_unop_i2u;
242 default: return (ir_expression_operation)0;
243 }
244
245 case GLSL_TYPE_DOUBLE:
246 if (!state->has_double())
247 return (ir_expression_operation)0;
248 switch (from->base_type) {
249 case GLSL_TYPE_INT: return ir_unop_i2d;
250 case GLSL_TYPE_UINT: return ir_unop_u2d;
251 case GLSL_TYPE_FLOAT: return ir_unop_f2d;
252 default: return (ir_expression_operation)0;
253 }
254
255 default: return (ir_expression_operation)0;
256 }
257 }
258
259
260 /**
261 * If a conversion is available, convert one operand to a different type
262 *
263 * The \c from \c ir_rvalue is converted "in place".
264 *
265 * \param to Type that the operand it to be converted to
266 * \param from Operand that is being converted
267 * \param state GLSL compiler state
268 *
269 * \return
270 * If a conversion is possible (or unnecessary), \c true is returned.
271 * Otherwise \c false is returned.
272 */
273 bool
274 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
275 struct _mesa_glsl_parse_state *state)
276 {
277 void *ctx = state;
278 if (to->base_type == from->type->base_type)
279 return true;
280
281 /* Prior to GLSL 1.20, there are no implicit conversions */
282 if (!state->is_version(120, 0))
283 return false;
284
285 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
286 *
287 * "There are no implicit array or structure conversions. For
288 * example, an array of int cannot be implicitly converted to an
289 * array of float.
290 */
291 if (!to->is_numeric() || !from->type->is_numeric())
292 return false;
293
294 /* We don't actually want the specific type `to`, we want a type
295 * with the same base type as `to`, but the same vector width as
296 * `from`.
297 */
298 to = glsl_type::get_instance(to->base_type, from->type->vector_elements,
299 from->type->matrix_columns);
300
301 ir_expression_operation op = get_conversion_operation(to, from->type, state);
302 if (op) {
303 from = new(ctx) ir_expression(op, to, from, NULL);
304 return true;
305 } else {
306 return false;
307 }
308 }
309
310
311 static const struct glsl_type *
312 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
313 bool multiply,
314 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
315 {
316 const glsl_type *type_a = value_a->type;
317 const glsl_type *type_b = value_b->type;
318
319 /* From GLSL 1.50 spec, page 56:
320 *
321 * "The arithmetic binary operators add (+), subtract (-),
322 * multiply (*), and divide (/) operate on integer and
323 * floating-point scalars, vectors, and matrices."
324 */
325 if (!type_a->is_numeric() || !type_b->is_numeric()) {
326 _mesa_glsl_error(loc, state,
327 "operands to arithmetic operators must be numeric");
328 return glsl_type::error_type;
329 }
330
331
332 /* "If one operand is floating-point based and the other is
333 * not, then the conversions from Section 4.1.10 "Implicit
334 * Conversions" are applied to the non-floating-point-based operand."
335 */
336 if (!apply_implicit_conversion(type_a, value_b, state)
337 && !apply_implicit_conversion(type_b, value_a, state)) {
338 _mesa_glsl_error(loc, state,
339 "could not implicitly convert operands to "
340 "arithmetic operator");
341 return glsl_type::error_type;
342 }
343 type_a = value_a->type;
344 type_b = value_b->type;
345
346 /* "If the operands are integer types, they must both be signed or
347 * both be unsigned."
348 *
349 * From this rule and the preceeding conversion it can be inferred that
350 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
351 * The is_numeric check above already filtered out the case where either
352 * type is not one of these, so now the base types need only be tested for
353 * equality.
354 */
355 if (type_a->base_type != type_b->base_type) {
356 _mesa_glsl_error(loc, state,
357 "base type mismatch for arithmetic operator");
358 return glsl_type::error_type;
359 }
360
361 /* "All arithmetic binary operators result in the same fundamental type
362 * (signed integer, unsigned integer, or floating-point) as the
363 * operands they operate on, after operand type conversion. After
364 * conversion, the following cases are valid
365 *
366 * * The two operands are scalars. In this case the operation is
367 * applied, resulting in a scalar."
368 */
369 if (type_a->is_scalar() && type_b->is_scalar())
370 return type_a;
371
372 /* "* One operand is a scalar, and the other is a vector or matrix.
373 * In this case, the scalar operation is applied independently to each
374 * component of the vector or matrix, resulting in the same size
375 * vector or matrix."
376 */
377 if (type_a->is_scalar()) {
378 if (!type_b->is_scalar())
379 return type_b;
380 } else if (type_b->is_scalar()) {
381 return type_a;
382 }
383
384 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
385 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
386 * handled.
387 */
388 assert(!type_a->is_scalar());
389 assert(!type_b->is_scalar());
390
391 /* "* The two operands are vectors of the same size. In this case, the
392 * operation is done component-wise resulting in the same size
393 * vector."
394 */
395 if (type_a->is_vector() && type_b->is_vector()) {
396 if (type_a == type_b) {
397 return type_a;
398 } else {
399 _mesa_glsl_error(loc, state,
400 "vector size mismatch for arithmetic operator");
401 return glsl_type::error_type;
402 }
403 }
404
405 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
406 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
407 * <vector, vector> have been handled. At least one of the operands must
408 * be matrix. Further, since there are no integer matrix types, the base
409 * type of both operands must be float.
410 */
411 assert(type_a->is_matrix() || type_b->is_matrix());
412 assert(type_a->base_type == GLSL_TYPE_FLOAT ||
413 type_a->base_type == GLSL_TYPE_DOUBLE);
414 assert(type_b->base_type == GLSL_TYPE_FLOAT ||
415 type_b->base_type == GLSL_TYPE_DOUBLE);
416
417 /* "* The operator is add (+), subtract (-), or divide (/), and the
418 * operands are matrices with the same number of rows and the same
419 * number of columns. In this case, the operation is done component-
420 * wise resulting in the same size matrix."
421 * * The operator is multiply (*), where both operands are matrices or
422 * one operand is a vector and the other a matrix. A right vector
423 * operand is treated as a column vector and a left vector operand as a
424 * row vector. In all these cases, it is required that the number of
425 * columns of the left operand is equal to the number of rows of the
426 * right operand. Then, the multiply (*) operation does a linear
427 * algebraic multiply, yielding an object that has the same number of
428 * rows as the left operand and the same number of columns as the right
429 * operand. Section 5.10 "Vector and Matrix Operations" explains in
430 * more detail how vectors and matrices are operated on."
431 */
432 if (! multiply) {
433 if (type_a == type_b)
434 return type_a;
435 } else {
436 const glsl_type *type = glsl_type::get_mul_type(type_a, type_b);
437
438 if (type == glsl_type::error_type) {
439 _mesa_glsl_error(loc, state,
440 "size mismatch for matrix multiplication");
441 }
442
443 return type;
444 }
445
446
447 /* "All other cases are illegal."
448 */
449 _mesa_glsl_error(loc, state, "type mismatch");
450 return glsl_type::error_type;
451 }
452
453
454 static const struct glsl_type *
455 unary_arithmetic_result_type(const struct glsl_type *type,
456 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
457 {
458 /* From GLSL 1.50 spec, page 57:
459 *
460 * "The arithmetic unary operators negate (-), post- and pre-increment
461 * and decrement (-- and ++) operate on integer or floating-point
462 * values (including vectors and matrices). All unary operators work
463 * component-wise on their operands. These result with the same type
464 * they operated on."
465 */
466 if (!type->is_numeric()) {
467 _mesa_glsl_error(loc, state,
468 "operands to arithmetic operators must be numeric");
469 return glsl_type::error_type;
470 }
471
472 return type;
473 }
474
475 /**
476 * \brief Return the result type of a bit-logic operation.
477 *
478 * If the given types to the bit-logic operator are invalid, return
479 * glsl_type::error_type.
480 *
481 * \param type_a Type of LHS of bit-logic op
482 * \param type_b Type of RHS of bit-logic op
483 */
484 static const struct glsl_type *
485 bit_logic_result_type(const struct glsl_type *type_a,
486 const struct glsl_type *type_b,
487 ast_operators op,
488 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
489 {
490 if (!state->check_bitwise_operations_allowed(loc)) {
491 return glsl_type::error_type;
492 }
493
494 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
495 *
496 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
497 * (|). The operands must be of type signed or unsigned integers or
498 * integer vectors."
499 */
500 if (!type_a->is_integer()) {
501 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
502 ast_expression::operator_string(op));
503 return glsl_type::error_type;
504 }
505 if (!type_b->is_integer()) {
506 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
507 ast_expression::operator_string(op));
508 return glsl_type::error_type;
509 }
510
511 /* "The fundamental types of the operands (signed or unsigned) must
512 * match,"
513 */
514 if (type_a->base_type != type_b->base_type) {
515 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
516 "base type", ast_expression::operator_string(op));
517 return glsl_type::error_type;
518 }
519
520 /* "The operands cannot be vectors of differing size." */
521 if (type_a->is_vector() &&
522 type_b->is_vector() &&
523 type_a->vector_elements != type_b->vector_elements) {
524 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
525 "different sizes", ast_expression::operator_string(op));
526 return glsl_type::error_type;
527 }
528
529 /* "If one operand is a scalar and the other a vector, the scalar is
530 * applied component-wise to the vector, resulting in the same type as
531 * the vector. The fundamental types of the operands [...] will be the
532 * resulting fundamental type."
533 */
534 if (type_a->is_scalar())
535 return type_b;
536 else
537 return type_a;
538 }
539
540 static const struct glsl_type *
541 modulus_result_type(const struct glsl_type *type_a,
542 const struct glsl_type *type_b,
543 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
544 {
545 if (!state->check_version(130, 300, loc, "operator '%%' is reserved")) {
546 return glsl_type::error_type;
547 }
548
549 /* From GLSL 1.50 spec, page 56:
550 * "The operator modulus (%) operates on signed or unsigned integers or
551 * integer vectors. The operand types must both be signed or both be
552 * unsigned."
553 */
554 if (!type_a->is_integer()) {
555 _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer");
556 return glsl_type::error_type;
557 }
558 if (!type_b->is_integer()) {
559 _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer");
560 return glsl_type::error_type;
561 }
562 if (type_a->base_type != type_b->base_type) {
563 _mesa_glsl_error(loc, state,
564 "operands of %% must have the same base type");
565 return glsl_type::error_type;
566 }
567
568 /* "The operands cannot be vectors of differing size. If one operand is
569 * a scalar and the other vector, then the scalar is applied component-
570 * wise to the vector, resulting in the same type as the vector. If both
571 * are vectors of the same size, the result is computed component-wise."
572 */
573 if (type_a->is_vector()) {
574 if (!type_b->is_vector()
575 || (type_a->vector_elements == type_b->vector_elements))
576 return type_a;
577 } else
578 return type_b;
579
580 /* "The operator modulus (%) is not defined for any other data types
581 * (non-integer types)."
582 */
583 _mesa_glsl_error(loc, state, "type mismatch");
584 return glsl_type::error_type;
585 }
586
587
588 static const struct glsl_type *
589 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
590 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
591 {
592 const glsl_type *type_a = value_a->type;
593 const glsl_type *type_b = value_b->type;
594
595 /* From GLSL 1.50 spec, page 56:
596 * "The relational operators greater than (>), less than (<), greater
597 * than or equal (>=), and less than or equal (<=) operate only on
598 * scalar integer and scalar floating-point expressions."
599 */
600 if (!type_a->is_numeric()
601 || !type_b->is_numeric()
602 || !type_a->is_scalar()
603 || !type_b->is_scalar()) {
604 _mesa_glsl_error(loc, state,
605 "operands to relational operators must be scalar and "
606 "numeric");
607 return glsl_type::error_type;
608 }
609
610 /* "Either the operands' types must match, or the conversions from
611 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
612 * operand, after which the types must match."
613 */
614 if (!apply_implicit_conversion(type_a, value_b, state)
615 && !apply_implicit_conversion(type_b, value_a, state)) {
616 _mesa_glsl_error(loc, state,
617 "could not implicitly convert operands to "
618 "relational operator");
619 return glsl_type::error_type;
620 }
621 type_a = value_a->type;
622 type_b = value_b->type;
623
624 if (type_a->base_type != type_b->base_type) {
625 _mesa_glsl_error(loc, state, "base type mismatch");
626 return glsl_type::error_type;
627 }
628
629 /* "The result is scalar Boolean."
630 */
631 return glsl_type::bool_type;
632 }
633
634 /**
635 * \brief Return the result type of a bit-shift operation.
636 *
637 * If the given types to the bit-shift operator are invalid, return
638 * glsl_type::error_type.
639 *
640 * \param type_a Type of LHS of bit-shift op
641 * \param type_b Type of RHS of bit-shift op
642 */
643 static const struct glsl_type *
644 shift_result_type(const struct glsl_type *type_a,
645 const struct glsl_type *type_b,
646 ast_operators op,
647 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
648 {
649 if (!state->check_bitwise_operations_allowed(loc)) {
650 return glsl_type::error_type;
651 }
652
653 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
654 *
655 * "The shift operators (<<) and (>>). For both operators, the operands
656 * must be signed or unsigned integers or integer vectors. One operand
657 * can be signed while the other is unsigned."
658 */
659 if (!type_a->is_integer()) {
660 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
661 "integer vector", ast_expression::operator_string(op));
662 return glsl_type::error_type;
663
664 }
665 if (!type_b->is_integer()) {
666 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
667 "integer vector", ast_expression::operator_string(op));
668 return glsl_type::error_type;
669 }
670
671 /* "If the first operand is a scalar, the second operand has to be
672 * a scalar as well."
673 */
674 if (type_a->is_scalar() && !type_b->is_scalar()) {
675 _mesa_glsl_error(loc, state, "if the first operand of %s is scalar, the "
676 "second must be scalar as well",
677 ast_expression::operator_string(op));
678 return glsl_type::error_type;
679 }
680
681 /* If both operands are vectors, check that they have same number of
682 * elements.
683 */
684 if (type_a->is_vector() &&
685 type_b->is_vector() &&
686 type_a->vector_elements != type_b->vector_elements) {
687 _mesa_glsl_error(loc, state, "vector operands to operator %s must "
688 "have same number of elements",
689 ast_expression::operator_string(op));
690 return glsl_type::error_type;
691 }
692
693 /* "In all cases, the resulting type will be the same type as the left
694 * operand."
695 */
696 return type_a;
697 }
698
699 /**
700 * Returns the innermost array index expression in an rvalue tree.
701 * This is the largest indexing level -- if an array of blocks, then
702 * it is the block index rather than an indexing expression for an
703 * array-typed member of an array of blocks.
704 */
705 static ir_rvalue *
706 find_innermost_array_index(ir_rvalue *rv)
707 {
708 ir_dereference_array *last = NULL;
709 while (rv) {
710 if (rv->as_dereference_array()) {
711 last = rv->as_dereference_array();
712 rv = last->array;
713 } else if (rv->as_dereference_record())
714 rv = rv->as_dereference_record()->record;
715 else if (rv->as_swizzle())
716 rv = rv->as_swizzle()->val;
717 else
718 rv = NULL;
719 }
720
721 if (last)
722 return last->array_index;
723
724 return NULL;
725 }
726
727 /**
728 * Validates that a value can be assigned to a location with a specified type
729 *
730 * Validates that \c rhs can be assigned to some location. If the types are
731 * not an exact match but an automatic conversion is possible, \c rhs will be
732 * converted.
733 *
734 * \return
735 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
736 * Otherwise the actual RHS to be assigned will be returned. This may be
737 * \c rhs, or it may be \c rhs after some type conversion.
738 *
739 * \note
740 * In addition to being used for assignments, this function is used to
741 * type-check return values.
742 */
743 static ir_rvalue *
744 validate_assignment(struct _mesa_glsl_parse_state *state,
745 YYLTYPE loc, ir_rvalue *lhs,
746 ir_rvalue *rhs, bool is_initializer)
747 {
748 /* If there is already some error in the RHS, just return it. Anything
749 * else will lead to an avalanche of error message back to the user.
750 */
751 if (rhs->type->is_error())
752 return rhs;
753
754 /* In the Tessellation Control Shader:
755 * If a per-vertex output variable is used as an l-value, it is an error
756 * if the expression indicating the vertex number is not the identifier
757 * `gl_InvocationID`.
758 */
759 if (state->stage == MESA_SHADER_TESS_CTRL) {
760 ir_variable *var = lhs->variable_referenced();
761 if (var->data.mode == ir_var_shader_out && !var->data.patch) {
762 ir_rvalue *index = find_innermost_array_index(lhs);
763 ir_variable *index_var = index ? index->variable_referenced() : NULL;
764 if (!index_var || strcmp(index_var->name, "gl_InvocationID") != 0) {
765 _mesa_glsl_error(&loc, state,
766 "Tessellation control shader outputs can only "
767 "be indexed by gl_InvocationID");
768 return NULL;
769 }
770 }
771 }
772
773 /* If the types are identical, the assignment can trivially proceed.
774 */
775 if (rhs->type == lhs->type)
776 return rhs;
777
778 /* If the array element types are the same and the LHS is unsized,
779 * the assignment is okay for initializers embedded in variable
780 * declarations.
781 *
782 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
783 * is handled by ir_dereference::is_lvalue.
784 */
785 const glsl_type *lhs_t = lhs->type;
786 const glsl_type *rhs_t = rhs->type;
787 bool unsized_array = false;
788 while(lhs_t->is_array()) {
789 if (rhs_t == lhs_t)
790 break; /* the rest of the inner arrays match so break out early */
791 if (!rhs_t->is_array()) {
792 unsized_array = false;
793 break; /* number of dimensions mismatch */
794 }
795 if (lhs_t->length == rhs_t->length) {
796 lhs_t = lhs_t->fields.array;
797 rhs_t = rhs_t->fields.array;
798 continue;
799 } else if (lhs_t->is_unsized_array()) {
800 unsized_array = true;
801 } else {
802 unsized_array = false;
803 break; /* sized array mismatch */
804 }
805 lhs_t = lhs_t->fields.array;
806 rhs_t = rhs_t->fields.array;
807 }
808 if (unsized_array) {
809 if (is_initializer) {
810 return rhs;
811 } else {
812 _mesa_glsl_error(&loc, state,
813 "implicitly sized arrays cannot be assigned");
814 return NULL;
815 }
816 }
817
818 /* Check for implicit conversion in GLSL 1.20 */
819 if (apply_implicit_conversion(lhs->type, rhs, state)) {
820 if (rhs->type == lhs->type)
821 return rhs;
822 }
823
824 _mesa_glsl_error(&loc, state,
825 "%s of type %s cannot be assigned to "
826 "variable of type %s",
827 is_initializer ? "initializer" : "value",
828 rhs->type->name, lhs->type->name);
829
830 return NULL;
831 }
832
833 static void
834 mark_whole_array_access(ir_rvalue *access)
835 {
836 ir_dereference_variable *deref = access->as_dereference_variable();
837
838 if (deref && deref->var) {
839 deref->var->data.max_array_access = deref->type->length - 1;
840 }
841 }
842
843 static bool
844 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
845 const char *non_lvalue_description,
846 ir_rvalue *lhs, ir_rvalue *rhs,
847 ir_rvalue **out_rvalue, bool needs_rvalue,
848 bool is_initializer,
849 YYLTYPE lhs_loc)
850 {
851 void *ctx = state;
852 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
853
854 ir_variable *lhs_var = lhs->variable_referenced();
855 if (lhs_var)
856 lhs_var->data.assigned = true;
857
858 if (!error_emitted) {
859 if (non_lvalue_description != NULL) {
860 _mesa_glsl_error(&lhs_loc, state,
861 "assignment to %s",
862 non_lvalue_description);
863 error_emitted = true;
864 } else if (lhs_var != NULL && (lhs_var->data.read_only ||
865 (lhs_var->data.mode == ir_var_shader_storage &&
866 lhs_var->data.image_read_only))) {
867 /* We can have image_read_only set on both images and buffer variables,
868 * but in the former there is a distinction between assignments to
869 * the variable itself (read_only) and to the memory they point to
870 * (image_read_only), while in the case of buffer variables there is
871 * no such distinction, that is why this check here is limited to
872 * buffer variables alone.
873 */
874 _mesa_glsl_error(&lhs_loc, state,
875 "assignment to read-only variable '%s'",
876 lhs_var->name);
877 error_emitted = true;
878 } else if (lhs->type->is_array() &&
879 !state->check_version(120, 300, &lhs_loc,
880 "whole array assignment forbidden")) {
881 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
882 *
883 * "Other binary or unary expressions, non-dereferenced
884 * arrays, function names, swizzles with repeated fields,
885 * and constants cannot be l-values."
886 *
887 * The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.
888 */
889 error_emitted = true;
890 } else if (!lhs->is_lvalue()) {
891 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
892 error_emitted = true;
893 }
894 }
895
896 ir_rvalue *new_rhs =
897 validate_assignment(state, lhs_loc, lhs, rhs, is_initializer);
898 if (new_rhs != NULL) {
899 rhs = new_rhs;
900
901 /* If the LHS array was not declared with a size, it takes it size from
902 * the RHS. If the LHS is an l-value and a whole array, it must be a
903 * dereference of a variable. Any other case would require that the LHS
904 * is either not an l-value or not a whole array.
905 */
906 if (lhs->type->is_unsized_array()) {
907 ir_dereference *const d = lhs->as_dereference();
908
909 assert(d != NULL);
910
911 ir_variable *const var = d->variable_referenced();
912
913 assert(var != NULL);
914
915 if (var->data.max_array_access >= unsigned(rhs->type->array_size())) {
916 /* FINISHME: This should actually log the location of the RHS. */
917 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
918 "previous access",
919 var->data.max_array_access);
920 }
921
922 var->type = glsl_type::get_array_instance(lhs->type->fields.array,
923 rhs->type->array_size());
924 d->type = var->type;
925 }
926 if (lhs->type->is_array()) {
927 mark_whole_array_access(rhs);
928 mark_whole_array_access(lhs);
929 }
930 }
931
932 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
933 * but not post_inc) need the converted assigned value as an rvalue
934 * to handle things like:
935 *
936 * i = j += 1;
937 */
938 if (needs_rvalue) {
939 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
940 ir_var_temporary);
941 instructions->push_tail(var);
942 instructions->push_tail(assign(var, rhs));
943
944 if (!error_emitted) {
945 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
946 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));
947 }
948 ir_rvalue *rvalue = new(ctx) ir_dereference_variable(var);
949
950 *out_rvalue = rvalue;
951 } else {
952 if (!error_emitted)
953 instructions->push_tail(new(ctx) ir_assignment(lhs, rhs));
954 *out_rvalue = NULL;
955 }
956
957 return error_emitted;
958 }
959
960 static ir_rvalue *
961 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
962 {
963 void *ctx = ralloc_parent(lvalue);
964 ir_variable *var;
965
966 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
967 ir_var_temporary);
968 instructions->push_tail(var);
969
970 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
971 lvalue));
972
973 return new(ctx) ir_dereference_variable(var);
974 }
975
976
977 ir_rvalue *
978 ast_node::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
979 {
980 (void) instructions;
981 (void) state;
982
983 return NULL;
984 }
985
986 bool
987 ast_node::has_sequence_subexpression() const
988 {
989 return false;
990 }
991
992 void
993 ast_function_expression::hir_no_rvalue(exec_list *instructions,
994 struct _mesa_glsl_parse_state *state)
995 {
996 (void)hir(instructions, state);
997 }
998
999 void
1000 ast_aggregate_initializer::hir_no_rvalue(exec_list *instructions,
1001 struct _mesa_glsl_parse_state *state)
1002 {
1003 (void)hir(instructions, state);
1004 }
1005
1006 static ir_rvalue *
1007 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
1008 {
1009 int join_op;
1010 ir_rvalue *cmp = NULL;
1011
1012 if (operation == ir_binop_all_equal)
1013 join_op = ir_binop_logic_and;
1014 else
1015 join_op = ir_binop_logic_or;
1016
1017 switch (op0->type->base_type) {
1018 case GLSL_TYPE_FLOAT:
1019 case GLSL_TYPE_UINT:
1020 case GLSL_TYPE_INT:
1021 case GLSL_TYPE_BOOL:
1022 case GLSL_TYPE_DOUBLE:
1023 return new(mem_ctx) ir_expression(operation, op0, op1);
1024
1025 case GLSL_TYPE_ARRAY: {
1026 for (unsigned int i = 0; i < op0->type->length; i++) {
1027 ir_rvalue *e0, *e1, *result;
1028
1029 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
1030 new(mem_ctx) ir_constant(i));
1031 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
1032 new(mem_ctx) ir_constant(i));
1033 result = do_comparison(mem_ctx, operation, e0, e1);
1034
1035 if (cmp) {
1036 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
1037 } else {
1038 cmp = result;
1039 }
1040 }
1041
1042 mark_whole_array_access(op0);
1043 mark_whole_array_access(op1);
1044 break;
1045 }
1046
1047 case GLSL_TYPE_STRUCT: {
1048 for (unsigned int i = 0; i < op0->type->length; i++) {
1049 ir_rvalue *e0, *e1, *result;
1050 const char *field_name = op0->type->fields.structure[i].name;
1051
1052 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
1053 field_name);
1054 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
1055 field_name);
1056 result = do_comparison(mem_ctx, operation, e0, e1);
1057
1058 if (cmp) {
1059 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
1060 } else {
1061 cmp = result;
1062 }
1063 }
1064 break;
1065 }
1066
1067 case GLSL_TYPE_ERROR:
1068 case GLSL_TYPE_VOID:
1069 case GLSL_TYPE_SAMPLER:
1070 case GLSL_TYPE_IMAGE:
1071 case GLSL_TYPE_INTERFACE:
1072 case GLSL_TYPE_ATOMIC_UINT:
1073 case GLSL_TYPE_SUBROUTINE:
1074 /* I assume a comparison of a struct containing a sampler just
1075 * ignores the sampler present in the type.
1076 */
1077 break;
1078 }
1079
1080 if (cmp == NULL)
1081 cmp = new(mem_ctx) ir_constant(true);
1082
1083 return cmp;
1084 }
1085
1086 /* For logical operations, we want to ensure that the operands are
1087 * scalar booleans. If it isn't, emit an error and return a constant
1088 * boolean to avoid triggering cascading error messages.
1089 */
1090 ir_rvalue *
1091 get_scalar_boolean_operand(exec_list *instructions,
1092 struct _mesa_glsl_parse_state *state,
1093 ast_expression *parent_expr,
1094 int operand,
1095 const char *operand_name,
1096 bool *error_emitted)
1097 {
1098 ast_expression *expr = parent_expr->subexpressions[operand];
1099 void *ctx = state;
1100 ir_rvalue *val = expr->hir(instructions, state);
1101
1102 if (val->type->is_boolean() && val->type->is_scalar())
1103 return val;
1104
1105 if (!*error_emitted) {
1106 YYLTYPE loc = expr->get_location();
1107 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
1108 operand_name,
1109 parent_expr->operator_string(parent_expr->oper));
1110 *error_emitted = true;
1111 }
1112
1113 return new(ctx) ir_constant(true);
1114 }
1115
1116 /**
1117 * If name refers to a builtin array whose maximum allowed size is less than
1118 * size, report an error and return true. Otherwise return false.
1119 */
1120 void
1121 check_builtin_array_max_size(const char *name, unsigned size,
1122 YYLTYPE loc, struct _mesa_glsl_parse_state *state)
1123 {
1124 if ((strcmp("gl_TexCoord", name) == 0)
1125 && (size > state->Const.MaxTextureCoords)) {
1126 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
1127 *
1128 * "The size [of gl_TexCoord] can be at most
1129 * gl_MaxTextureCoords."
1130 */
1131 _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
1132 "be larger than gl_MaxTextureCoords (%u)",
1133 state->Const.MaxTextureCoords);
1134 } else if (strcmp("gl_ClipDistance", name) == 0
1135 && size > state->Const.MaxClipPlanes) {
1136 /* From section 7.1 (Vertex Shader Special Variables) of the
1137 * GLSL 1.30 spec:
1138 *
1139 * "The gl_ClipDistance array is predeclared as unsized and
1140 * must be sized by the shader either redeclaring it with a
1141 * size or indexing it only with integral constant
1142 * expressions. ... The size can be at most
1143 * gl_MaxClipDistances."
1144 */
1145 _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
1146 "be larger than gl_MaxClipDistances (%u)",
1147 state->Const.MaxClipPlanes);
1148 }
1149 }
1150
1151 /**
1152 * Create the constant 1, of a which is appropriate for incrementing and
1153 * decrementing values of the given GLSL type. For example, if type is vec4,
1154 * this creates a constant value of 1.0 having type float.
1155 *
1156 * If the given type is invalid for increment and decrement operators, return
1157 * a floating point 1--the error will be detected later.
1158 */
1159 static ir_rvalue *
1160 constant_one_for_inc_dec(void *ctx, const glsl_type *type)
1161 {
1162 switch (type->base_type) {
1163 case GLSL_TYPE_UINT:
1164 return new(ctx) ir_constant((unsigned) 1);
1165 case GLSL_TYPE_INT:
1166 return new(ctx) ir_constant(1);
1167 default:
1168 case GLSL_TYPE_FLOAT:
1169 return new(ctx) ir_constant(1.0f);
1170 }
1171 }
1172
1173 ir_rvalue *
1174 ast_expression::hir(exec_list *instructions,
1175 struct _mesa_glsl_parse_state *state)
1176 {
1177 return do_hir(instructions, state, true);
1178 }
1179
1180 void
1181 ast_expression::hir_no_rvalue(exec_list *instructions,
1182 struct _mesa_glsl_parse_state *state)
1183 {
1184 do_hir(instructions, state, false);
1185 }
1186
1187 ir_rvalue *
1188 ast_expression::do_hir(exec_list *instructions,
1189 struct _mesa_glsl_parse_state *state,
1190 bool needs_rvalue)
1191 {
1192 void *ctx = state;
1193 static const int operations[AST_NUM_OPERATORS] = {
1194 -1, /* ast_assign doesn't convert to ir_expression. */
1195 -1, /* ast_plus doesn't convert to ir_expression. */
1196 ir_unop_neg,
1197 ir_binop_add,
1198 ir_binop_sub,
1199 ir_binop_mul,
1200 ir_binop_div,
1201 ir_binop_mod,
1202 ir_binop_lshift,
1203 ir_binop_rshift,
1204 ir_binop_less,
1205 ir_binop_greater,
1206 ir_binop_lequal,
1207 ir_binop_gequal,
1208 ir_binop_all_equal,
1209 ir_binop_any_nequal,
1210 ir_binop_bit_and,
1211 ir_binop_bit_xor,
1212 ir_binop_bit_or,
1213 ir_unop_bit_not,
1214 ir_binop_logic_and,
1215 ir_binop_logic_xor,
1216 ir_binop_logic_or,
1217 ir_unop_logic_not,
1218
1219 /* Note: The following block of expression types actually convert
1220 * to multiple IR instructions.
1221 */
1222 ir_binop_mul, /* ast_mul_assign */
1223 ir_binop_div, /* ast_div_assign */
1224 ir_binop_mod, /* ast_mod_assign */
1225 ir_binop_add, /* ast_add_assign */
1226 ir_binop_sub, /* ast_sub_assign */
1227 ir_binop_lshift, /* ast_ls_assign */
1228 ir_binop_rshift, /* ast_rs_assign */
1229 ir_binop_bit_and, /* ast_and_assign */
1230 ir_binop_bit_xor, /* ast_xor_assign */
1231 ir_binop_bit_or, /* ast_or_assign */
1232
1233 -1, /* ast_conditional doesn't convert to ir_expression. */
1234 ir_binop_add, /* ast_pre_inc. */
1235 ir_binop_sub, /* ast_pre_dec. */
1236 ir_binop_add, /* ast_post_inc. */
1237 ir_binop_sub, /* ast_post_dec. */
1238 -1, /* ast_field_selection doesn't conv to ir_expression. */
1239 -1, /* ast_array_index doesn't convert to ir_expression. */
1240 -1, /* ast_function_call doesn't conv to ir_expression. */
1241 -1, /* ast_identifier doesn't convert to ir_expression. */
1242 -1, /* ast_int_constant doesn't convert to ir_expression. */
1243 -1, /* ast_uint_constant doesn't conv to ir_expression. */
1244 -1, /* ast_float_constant doesn't conv to ir_expression. */
1245 -1, /* ast_bool_constant doesn't conv to ir_expression. */
1246 -1, /* ast_sequence doesn't convert to ir_expression. */
1247 };
1248 ir_rvalue *result = NULL;
1249 ir_rvalue *op[3];
1250 const struct glsl_type *type; /* a temporary variable for switch cases */
1251 bool error_emitted = false;
1252 YYLTYPE loc;
1253
1254 loc = this->get_location();
1255
1256 switch (this->oper) {
1257 case ast_aggregate:
1258 assert(!"ast_aggregate: Should never get here.");
1259 break;
1260
1261 case ast_assign: {
1262 op[0] = this->subexpressions[0]->hir(instructions, state);
1263 op[1] = this->subexpressions[1]->hir(instructions, state);
1264
1265 error_emitted =
1266 do_assignment(instructions, state,
1267 this->subexpressions[0]->non_lvalue_description,
1268 op[0], op[1], &result, needs_rvalue, false,
1269 this->subexpressions[0]->get_location());
1270 break;
1271 }
1272
1273 case ast_plus:
1274 op[0] = this->subexpressions[0]->hir(instructions, state);
1275
1276 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1277
1278 error_emitted = type->is_error();
1279
1280 result = op[0];
1281 break;
1282
1283 case ast_neg:
1284 op[0] = this->subexpressions[0]->hir(instructions, state);
1285
1286 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1287
1288 error_emitted = type->is_error();
1289
1290 result = new(ctx) ir_expression(operations[this->oper], type,
1291 op[0], NULL);
1292 break;
1293
1294 case ast_add:
1295 case ast_sub:
1296 case ast_mul:
1297 case ast_div:
1298 op[0] = this->subexpressions[0]->hir(instructions, state);
1299 op[1] = this->subexpressions[1]->hir(instructions, state);
1300
1301 type = arithmetic_result_type(op[0], op[1],
1302 (this->oper == ast_mul),
1303 state, & loc);
1304 error_emitted = type->is_error();
1305
1306 result = new(ctx) ir_expression(operations[this->oper], type,
1307 op[0], op[1]);
1308 break;
1309
1310 case ast_mod:
1311 op[0] = this->subexpressions[0]->hir(instructions, state);
1312 op[1] = this->subexpressions[1]->hir(instructions, state);
1313
1314 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1315
1316 assert(operations[this->oper] == ir_binop_mod);
1317
1318 result = new(ctx) ir_expression(operations[this->oper], type,
1319 op[0], op[1]);
1320 error_emitted = type->is_error();
1321 break;
1322
1323 case ast_lshift:
1324 case ast_rshift:
1325 if (!state->check_bitwise_operations_allowed(&loc)) {
1326 error_emitted = true;
1327 }
1328
1329 op[0] = this->subexpressions[0]->hir(instructions, state);
1330 op[1] = this->subexpressions[1]->hir(instructions, state);
1331 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1332 &loc);
1333 result = new(ctx) ir_expression(operations[this->oper], type,
1334 op[0], op[1]);
1335 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1336 break;
1337
1338 case ast_less:
1339 case ast_greater:
1340 case ast_lequal:
1341 case ast_gequal:
1342 op[0] = this->subexpressions[0]->hir(instructions, state);
1343 op[1] = this->subexpressions[1]->hir(instructions, state);
1344
1345 type = relational_result_type(op[0], op[1], state, & loc);
1346
1347 /* The relational operators must either generate an error or result
1348 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1349 */
1350 assert(type->is_error()
1351 || ((type->base_type == GLSL_TYPE_BOOL)
1352 && type->is_scalar()));
1353
1354 result = new(ctx) ir_expression(operations[this->oper], type,
1355 op[0], op[1]);
1356 error_emitted = type->is_error();
1357 break;
1358
1359 case ast_nequal:
1360 case ast_equal:
1361 op[0] = this->subexpressions[0]->hir(instructions, state);
1362 op[1] = this->subexpressions[1]->hir(instructions, state);
1363
1364 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1365 *
1366 * "The equality operators equal (==), and not equal (!=)
1367 * operate on all types. They result in a scalar Boolean. If
1368 * the operand types do not match, then there must be a
1369 * conversion from Section 4.1.10 "Implicit Conversions"
1370 * applied to one operand that can make them match, in which
1371 * case this conversion is done."
1372 */
1373
1374 if (op[0]->type == glsl_type::void_type || op[1]->type == glsl_type::void_type) {
1375 _mesa_glsl_error(& loc, state, "`%s': wrong operand types: "
1376 "no operation `%1$s' exists that takes a left-hand "
1377 "operand of type 'void' or a right operand of type "
1378 "'void'", (this->oper == ast_equal) ? "==" : "!=");
1379 error_emitted = true;
1380 } else if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1381 && !apply_implicit_conversion(op[1]->type, op[0], state))
1382 || (op[0]->type != op[1]->type)) {
1383 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1384 "type", (this->oper == ast_equal) ? "==" : "!=");
1385 error_emitted = true;
1386 } else if ((op[0]->type->is_array() || op[1]->type->is_array()) &&
1387 !state->check_version(120, 300, &loc,
1388 "array comparisons forbidden")) {
1389 error_emitted = true;
1390 } else if ((op[0]->type->contains_opaque() ||
1391 op[1]->type->contains_opaque())) {
1392 _mesa_glsl_error(&loc, state, "opaque type comparisons forbidden");
1393 error_emitted = true;
1394 }
1395
1396 if (error_emitted) {
1397 result = new(ctx) ir_constant(false);
1398 } else {
1399 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1400 assert(result->type == glsl_type::bool_type);
1401 }
1402 break;
1403
1404 case ast_bit_and:
1405 case ast_bit_xor:
1406 case ast_bit_or:
1407 op[0] = this->subexpressions[0]->hir(instructions, state);
1408 op[1] = this->subexpressions[1]->hir(instructions, state);
1409 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1410 state, &loc);
1411 result = new(ctx) ir_expression(operations[this->oper], type,
1412 op[0], op[1]);
1413 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1414 break;
1415
1416 case ast_bit_not:
1417 op[0] = this->subexpressions[0]->hir(instructions, state);
1418
1419 if (!state->check_bitwise_operations_allowed(&loc)) {
1420 error_emitted = true;
1421 }
1422
1423 if (!op[0]->type->is_integer()) {
1424 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1425 error_emitted = true;
1426 }
1427
1428 type = error_emitted ? glsl_type::error_type : op[0]->type;
1429 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1430 break;
1431
1432 case ast_logic_and: {
1433 exec_list rhs_instructions;
1434 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1435 "LHS", &error_emitted);
1436 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1437 "RHS", &error_emitted);
1438
1439 if (rhs_instructions.is_empty()) {
1440 result = new(ctx) ir_expression(ir_binop_logic_and, op[0], op[1]);
1441 type = result->type;
1442 } else {
1443 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1444 "and_tmp",
1445 ir_var_temporary);
1446 instructions->push_tail(tmp);
1447
1448 ir_if *const stmt = new(ctx) ir_if(op[0]);
1449 instructions->push_tail(stmt);
1450
1451 stmt->then_instructions.append_list(&rhs_instructions);
1452 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1453 ir_assignment *const then_assign =
1454 new(ctx) ir_assignment(then_deref, op[1]);
1455 stmt->then_instructions.push_tail(then_assign);
1456
1457 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1458 ir_assignment *const else_assign =
1459 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false));
1460 stmt->else_instructions.push_tail(else_assign);
1461
1462 result = new(ctx) ir_dereference_variable(tmp);
1463 type = tmp->type;
1464 }
1465 break;
1466 }
1467
1468 case ast_logic_or: {
1469 exec_list rhs_instructions;
1470 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1471 "LHS", &error_emitted);
1472 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1473 "RHS", &error_emitted);
1474
1475 if (rhs_instructions.is_empty()) {
1476 result = new(ctx) ir_expression(ir_binop_logic_or, op[0], op[1]);
1477 type = result->type;
1478 } else {
1479 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1480 "or_tmp",
1481 ir_var_temporary);
1482 instructions->push_tail(tmp);
1483
1484 ir_if *const stmt = new(ctx) ir_if(op[0]);
1485 instructions->push_tail(stmt);
1486
1487 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1488 ir_assignment *const then_assign =
1489 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true));
1490 stmt->then_instructions.push_tail(then_assign);
1491
1492 stmt->else_instructions.append_list(&rhs_instructions);
1493 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1494 ir_assignment *const else_assign =
1495 new(ctx) ir_assignment(else_deref, op[1]);
1496 stmt->else_instructions.push_tail(else_assign);
1497
1498 result = new(ctx) ir_dereference_variable(tmp);
1499 type = tmp->type;
1500 }
1501 break;
1502 }
1503
1504 case ast_logic_xor:
1505 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1506 *
1507 * "The logical binary operators and (&&), or ( | | ), and
1508 * exclusive or (^^). They operate only on two Boolean
1509 * expressions and result in a Boolean expression."
1510 */
1511 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1512 &error_emitted);
1513 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1514 &error_emitted);
1515
1516 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1517 op[0], op[1]);
1518 break;
1519
1520 case ast_logic_not:
1521 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1522 "operand", &error_emitted);
1523
1524 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1525 op[0], NULL);
1526 break;
1527
1528 case ast_mul_assign:
1529 case ast_div_assign:
1530 case ast_add_assign:
1531 case ast_sub_assign: {
1532 op[0] = this->subexpressions[0]->hir(instructions, state);
1533 op[1] = this->subexpressions[1]->hir(instructions, state);
1534
1535 type = arithmetic_result_type(op[0], op[1],
1536 (this->oper == ast_mul_assign),
1537 state, & loc);
1538
1539 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1540 op[0], op[1]);
1541
1542 error_emitted =
1543 do_assignment(instructions, state,
1544 this->subexpressions[0]->non_lvalue_description,
1545 op[0]->clone(ctx, NULL), temp_rhs,
1546 &result, needs_rvalue, false,
1547 this->subexpressions[0]->get_location());
1548
1549 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1550 * explicitly test for this because none of the binary expression
1551 * operators allow array operands either.
1552 */
1553
1554 break;
1555 }
1556
1557 case ast_mod_assign: {
1558 op[0] = this->subexpressions[0]->hir(instructions, state);
1559 op[1] = this->subexpressions[1]->hir(instructions, state);
1560
1561 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1562
1563 assert(operations[this->oper] == ir_binop_mod);
1564
1565 ir_rvalue *temp_rhs;
1566 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1567 op[0], op[1]);
1568
1569 error_emitted =
1570 do_assignment(instructions, state,
1571 this->subexpressions[0]->non_lvalue_description,
1572 op[0]->clone(ctx, NULL), temp_rhs,
1573 &result, needs_rvalue, false,
1574 this->subexpressions[0]->get_location());
1575 break;
1576 }
1577
1578 case ast_ls_assign:
1579 case ast_rs_assign: {
1580 op[0] = this->subexpressions[0]->hir(instructions, state);
1581 op[1] = this->subexpressions[1]->hir(instructions, state);
1582 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1583 &loc);
1584 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1585 type, op[0], op[1]);
1586 error_emitted =
1587 do_assignment(instructions, state,
1588 this->subexpressions[0]->non_lvalue_description,
1589 op[0]->clone(ctx, NULL), temp_rhs,
1590 &result, needs_rvalue, false,
1591 this->subexpressions[0]->get_location());
1592 break;
1593 }
1594
1595 case ast_and_assign:
1596 case ast_xor_assign:
1597 case ast_or_assign: {
1598 op[0] = this->subexpressions[0]->hir(instructions, state);
1599 op[1] = this->subexpressions[1]->hir(instructions, state);
1600 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1601 state, &loc);
1602 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1603 type, op[0], op[1]);
1604 error_emitted =
1605 do_assignment(instructions, state,
1606 this->subexpressions[0]->non_lvalue_description,
1607 op[0]->clone(ctx, NULL), temp_rhs,
1608 &result, needs_rvalue, false,
1609 this->subexpressions[0]->get_location());
1610 break;
1611 }
1612
1613 case ast_conditional: {
1614 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1615 *
1616 * "The ternary selection operator (?:). It operates on three
1617 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1618 * first expression, which must result in a scalar Boolean."
1619 */
1620 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1621 "condition", &error_emitted);
1622
1623 /* The :? operator is implemented by generating an anonymous temporary
1624 * followed by an if-statement. The last instruction in each branch of
1625 * the if-statement assigns a value to the anonymous temporary. This
1626 * temporary is the r-value of the expression.
1627 */
1628 exec_list then_instructions;
1629 exec_list else_instructions;
1630
1631 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1632 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1633
1634 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1635 *
1636 * "The second and third expressions can be any type, as
1637 * long their types match, or there is a conversion in
1638 * Section 4.1.10 "Implicit Conversions" that can be applied
1639 * to one of the expressions to make their types match. This
1640 * resulting matching type is the type of the entire
1641 * expression."
1642 */
1643 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1644 && !apply_implicit_conversion(op[2]->type, op[1], state))
1645 || (op[1]->type != op[2]->type)) {
1646 YYLTYPE loc = this->subexpressions[1]->get_location();
1647
1648 _mesa_glsl_error(& loc, state, "second and third operands of ?: "
1649 "operator must have matching types");
1650 error_emitted = true;
1651 type = glsl_type::error_type;
1652 } else {
1653 type = op[1]->type;
1654 }
1655
1656 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1657 *
1658 * "The second and third expressions must be the same type, but can
1659 * be of any type other than an array."
1660 */
1661 if (type->is_array() &&
1662 !state->check_version(120, 300, &loc,
1663 "second and third operands of ?: operator "
1664 "cannot be arrays")) {
1665 error_emitted = true;
1666 }
1667
1668 /* From section 4.1.7 of the GLSL 4.50 spec (Opaque Types):
1669 *
1670 * "Except for array indexing, structure member selection, and
1671 * parentheses, opaque variables are not allowed to be operands in
1672 * expressions; such use results in a compile-time error."
1673 */
1674 if (type->contains_opaque()) {
1675 _mesa_glsl_error(&loc, state, "opaque variables cannot be operands "
1676 "of the ?: operator");
1677 error_emitted = true;
1678 }
1679
1680 ir_constant *cond_val = op[0]->constant_expression_value();
1681
1682 if (then_instructions.is_empty()
1683 && else_instructions.is_empty()
1684 && cond_val != NULL) {
1685 result = cond_val->value.b[0] ? op[1] : op[2];
1686 } else {
1687 /* The copy to conditional_tmp reads the whole array. */
1688 if (type->is_array()) {
1689 mark_whole_array_access(op[1]);
1690 mark_whole_array_access(op[2]);
1691 }
1692
1693 ir_variable *const tmp =
1694 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1695 instructions->push_tail(tmp);
1696
1697 ir_if *const stmt = new(ctx) ir_if(op[0]);
1698 instructions->push_tail(stmt);
1699
1700 then_instructions.move_nodes_to(& stmt->then_instructions);
1701 ir_dereference *const then_deref =
1702 new(ctx) ir_dereference_variable(tmp);
1703 ir_assignment *const then_assign =
1704 new(ctx) ir_assignment(then_deref, op[1]);
1705 stmt->then_instructions.push_tail(then_assign);
1706
1707 else_instructions.move_nodes_to(& stmt->else_instructions);
1708 ir_dereference *const else_deref =
1709 new(ctx) ir_dereference_variable(tmp);
1710 ir_assignment *const else_assign =
1711 new(ctx) ir_assignment(else_deref, op[2]);
1712 stmt->else_instructions.push_tail(else_assign);
1713
1714 result = new(ctx) ir_dereference_variable(tmp);
1715 }
1716 break;
1717 }
1718
1719 case ast_pre_inc:
1720 case ast_pre_dec: {
1721 this->non_lvalue_description = (this->oper == ast_pre_inc)
1722 ? "pre-increment operation" : "pre-decrement operation";
1723
1724 op[0] = this->subexpressions[0]->hir(instructions, state);
1725 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1726
1727 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1728
1729 ir_rvalue *temp_rhs;
1730 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1731 op[0], op[1]);
1732
1733 error_emitted =
1734 do_assignment(instructions, state,
1735 this->subexpressions[0]->non_lvalue_description,
1736 op[0]->clone(ctx, NULL), temp_rhs,
1737 &result, needs_rvalue, false,
1738 this->subexpressions[0]->get_location());
1739 break;
1740 }
1741
1742 case ast_post_inc:
1743 case ast_post_dec: {
1744 this->non_lvalue_description = (this->oper == ast_post_inc)
1745 ? "post-increment operation" : "post-decrement operation";
1746 op[0] = this->subexpressions[0]->hir(instructions, state);
1747 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1748
1749 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1750
1751 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1752
1753 ir_rvalue *temp_rhs;
1754 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1755 op[0], op[1]);
1756
1757 /* Get a temporary of a copy of the lvalue before it's modified.
1758 * This may get thrown away later.
1759 */
1760 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1761
1762 ir_rvalue *junk_rvalue;
1763 error_emitted =
1764 do_assignment(instructions, state,
1765 this->subexpressions[0]->non_lvalue_description,
1766 op[0]->clone(ctx, NULL), temp_rhs,
1767 &junk_rvalue, false, false,
1768 this->subexpressions[0]->get_location());
1769
1770 break;
1771 }
1772
1773 case ast_field_selection:
1774 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1775 break;
1776
1777 case ast_array_index: {
1778 YYLTYPE index_loc = subexpressions[1]->get_location();
1779
1780 op[0] = subexpressions[0]->hir(instructions, state);
1781 op[1] = subexpressions[1]->hir(instructions, state);
1782
1783 result = _mesa_ast_array_index_to_hir(ctx, state, op[0], op[1],
1784 loc, index_loc);
1785
1786 if (result->type->is_error())
1787 error_emitted = true;
1788
1789 break;
1790 }
1791
1792 case ast_unsized_array_dim:
1793 assert(!"ast_unsized_array_dim: Should never get here.");
1794 break;
1795
1796 case ast_function_call:
1797 /* Should *NEVER* get here. ast_function_call should always be handled
1798 * by ast_function_expression::hir.
1799 */
1800 assert(0);
1801 break;
1802
1803 case ast_identifier: {
1804 /* ast_identifier can appear several places in a full abstract syntax
1805 * tree. This particular use must be at location specified in the grammar
1806 * as 'variable_identifier'.
1807 */
1808 ir_variable *var =
1809 state->symbols->get_variable(this->primary_expression.identifier);
1810
1811 if (var != NULL) {
1812 var->data.used = true;
1813 result = new(ctx) ir_dereference_variable(var);
1814 } else {
1815 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1816 this->primary_expression.identifier);
1817
1818 result = ir_rvalue::error_value(ctx);
1819 error_emitted = true;
1820 }
1821 break;
1822 }
1823
1824 case ast_int_constant:
1825 result = new(ctx) ir_constant(this->primary_expression.int_constant);
1826 break;
1827
1828 case ast_uint_constant:
1829 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1830 break;
1831
1832 case ast_float_constant:
1833 result = new(ctx) ir_constant(this->primary_expression.float_constant);
1834 break;
1835
1836 case ast_bool_constant:
1837 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1838 break;
1839
1840 case ast_double_constant:
1841 result = new(ctx) ir_constant(this->primary_expression.double_constant);
1842 break;
1843
1844 case ast_sequence: {
1845 /* It should not be possible to generate a sequence in the AST without
1846 * any expressions in it.
1847 */
1848 assert(!this->expressions.is_empty());
1849
1850 /* The r-value of a sequence is the last expression in the sequence. If
1851 * the other expressions in the sequence do not have side-effects (and
1852 * therefore add instructions to the instruction list), they get dropped
1853 * on the floor.
1854 */
1855 exec_node *previous_tail_pred = NULL;
1856 YYLTYPE previous_operand_loc = loc;
1857
1858 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1859 /* If one of the operands of comma operator does not generate any
1860 * code, we want to emit a warning. At each pass through the loop
1861 * previous_tail_pred will point to the last instruction in the
1862 * stream *before* processing the previous operand. Naturally,
1863 * instructions->tail_pred will point to the last instruction in the
1864 * stream *after* processing the previous operand. If the two
1865 * pointers match, then the previous operand had no effect.
1866 *
1867 * The warning behavior here differs slightly from GCC. GCC will
1868 * only emit a warning if none of the left-hand operands have an
1869 * effect. However, it will emit a warning for each. I believe that
1870 * there are some cases in C (especially with GCC extensions) where
1871 * it is useful to have an intermediate step in a sequence have no
1872 * effect, but I don't think these cases exist in GLSL. Either way,
1873 * it would be a giant hassle to replicate that behavior.
1874 */
1875 if (previous_tail_pred == instructions->tail_pred) {
1876 _mesa_glsl_warning(&previous_operand_loc, state,
1877 "left-hand operand of comma expression has "
1878 "no effect");
1879 }
1880
1881 /* tail_pred is directly accessed instead of using the get_tail()
1882 * method for performance reasons. get_tail() has extra code to
1883 * return NULL when the list is empty. We don't care about that
1884 * here, so using tail_pred directly is fine.
1885 */
1886 previous_tail_pred = instructions->tail_pred;
1887 previous_operand_loc = ast->get_location();
1888
1889 result = ast->hir(instructions, state);
1890 }
1891
1892 /* Any errors should have already been emitted in the loop above.
1893 */
1894 error_emitted = true;
1895 break;
1896 }
1897 }
1898 type = NULL; /* use result->type, not type. */
1899 assert(result != NULL || !needs_rvalue);
1900
1901 if (result && result->type->is_error() && !error_emitted)
1902 _mesa_glsl_error(& loc, state, "type mismatch");
1903
1904 return result;
1905 }
1906
1907 bool
1908 ast_expression::has_sequence_subexpression() const
1909 {
1910 switch (this->oper) {
1911 case ast_plus:
1912 case ast_neg:
1913 case ast_bit_not:
1914 case ast_logic_not:
1915 case ast_pre_inc:
1916 case ast_pre_dec:
1917 case ast_post_inc:
1918 case ast_post_dec:
1919 return this->subexpressions[0]->has_sequence_subexpression();
1920
1921 case ast_assign:
1922 case ast_add:
1923 case ast_sub:
1924 case ast_mul:
1925 case ast_div:
1926 case ast_mod:
1927 case ast_lshift:
1928 case ast_rshift:
1929 case ast_less:
1930 case ast_greater:
1931 case ast_lequal:
1932 case ast_gequal:
1933 case ast_nequal:
1934 case ast_equal:
1935 case ast_bit_and:
1936 case ast_bit_xor:
1937 case ast_bit_or:
1938 case ast_logic_and:
1939 case ast_logic_or:
1940 case ast_logic_xor:
1941 case ast_array_index:
1942 case ast_mul_assign:
1943 case ast_div_assign:
1944 case ast_add_assign:
1945 case ast_sub_assign:
1946 case ast_mod_assign:
1947 case ast_ls_assign:
1948 case ast_rs_assign:
1949 case ast_and_assign:
1950 case ast_xor_assign:
1951 case ast_or_assign:
1952 return this->subexpressions[0]->has_sequence_subexpression() ||
1953 this->subexpressions[1]->has_sequence_subexpression();
1954
1955 case ast_conditional:
1956 return this->subexpressions[0]->has_sequence_subexpression() ||
1957 this->subexpressions[1]->has_sequence_subexpression() ||
1958 this->subexpressions[2]->has_sequence_subexpression();
1959
1960 case ast_sequence:
1961 return true;
1962
1963 case ast_field_selection:
1964 case ast_identifier:
1965 case ast_int_constant:
1966 case ast_uint_constant:
1967 case ast_float_constant:
1968 case ast_bool_constant:
1969 case ast_double_constant:
1970 return false;
1971
1972 case ast_aggregate:
1973 unreachable("ast_aggregate: Should never get here.");
1974
1975 case ast_function_call:
1976 unreachable("should be handled by ast_function_expression::hir");
1977
1978 case ast_unsized_array_dim:
1979 unreachable("ast_unsized_array_dim: Should never get here.");
1980 }
1981
1982 return false;
1983 }
1984
1985 ir_rvalue *
1986 ast_expression_statement::hir(exec_list *instructions,
1987 struct _mesa_glsl_parse_state *state)
1988 {
1989 /* It is possible to have expression statements that don't have an
1990 * expression. This is the solitary semicolon:
1991 *
1992 * for (i = 0; i < 5; i++)
1993 * ;
1994 *
1995 * In this case the expression will be NULL. Test for NULL and don't do
1996 * anything in that case.
1997 */
1998 if (expression != NULL)
1999 expression->hir_no_rvalue(instructions, state);
2000
2001 /* Statements do not have r-values.
2002 */
2003 return NULL;
2004 }
2005
2006
2007 ir_rvalue *
2008 ast_compound_statement::hir(exec_list *instructions,
2009 struct _mesa_glsl_parse_state *state)
2010 {
2011 if (new_scope)
2012 state->symbols->push_scope();
2013
2014 foreach_list_typed (ast_node, ast, link, &this->statements)
2015 ast->hir(instructions, state);
2016
2017 if (new_scope)
2018 state->symbols->pop_scope();
2019
2020 /* Compound statements do not have r-values.
2021 */
2022 return NULL;
2023 }
2024
2025 /**
2026 * Evaluate the given exec_node (which should be an ast_node representing
2027 * a single array dimension) and return its integer value.
2028 */
2029 static unsigned
2030 process_array_size(exec_node *node,
2031 struct _mesa_glsl_parse_state *state)
2032 {
2033 exec_list dummy_instructions;
2034
2035 ast_node *array_size = exec_node_data(ast_node, node, link);
2036
2037 /**
2038 * Dimensions other than the outermost dimension can by unsized if they
2039 * are immediately sized by a constructor or initializer.
2040 */
2041 if (((ast_expression*)array_size)->oper == ast_unsized_array_dim)
2042 return 0;
2043
2044 ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
2045 YYLTYPE loc = array_size->get_location();
2046
2047 if (ir == NULL) {
2048 _mesa_glsl_error(& loc, state,
2049 "array size could not be resolved");
2050 return 0;
2051 }
2052
2053 if (!ir->type->is_integer()) {
2054 _mesa_glsl_error(& loc, state,
2055 "array size must be integer type");
2056 return 0;
2057 }
2058
2059 if (!ir->type->is_scalar()) {
2060 _mesa_glsl_error(& loc, state,
2061 "array size must be scalar type");
2062 return 0;
2063 }
2064
2065 ir_constant *const size = ir->constant_expression_value();
2066 if (size == NULL || array_size->has_sequence_subexpression()) {
2067 _mesa_glsl_error(& loc, state, "array size must be a "
2068 "constant valued expression");
2069 return 0;
2070 }
2071
2072 if (size->value.i[0] <= 0) {
2073 _mesa_glsl_error(& loc, state, "array size must be > 0");
2074 return 0;
2075 }
2076
2077 assert(size->type == ir->type);
2078
2079 /* If the array size is const (and we've verified that
2080 * it is) then no instructions should have been emitted
2081 * when we converted it to HIR. If they were emitted,
2082 * then either the array size isn't const after all, or
2083 * we are emitting unnecessary instructions.
2084 */
2085 assert(dummy_instructions.is_empty());
2086
2087 return size->value.u[0];
2088 }
2089
2090 static const glsl_type *
2091 process_array_type(YYLTYPE *loc, const glsl_type *base,
2092 ast_array_specifier *array_specifier,
2093 struct _mesa_glsl_parse_state *state)
2094 {
2095 const glsl_type *array_type = base;
2096
2097 if (array_specifier != NULL) {
2098 if (base->is_array()) {
2099
2100 /* From page 19 (page 25) of the GLSL 1.20 spec:
2101 *
2102 * "Only one-dimensional arrays may be declared."
2103 */
2104 if (!state->check_arrays_of_arrays_allowed(loc)) {
2105 return glsl_type::error_type;
2106 }
2107 }
2108
2109 for (exec_node *node = array_specifier->array_dimensions.tail_pred;
2110 !node->is_head_sentinel(); node = node->prev) {
2111 unsigned array_size = process_array_size(node, state);
2112 array_type = glsl_type::get_array_instance(array_type, array_size);
2113 }
2114 }
2115
2116 return array_type;
2117 }
2118
2119 static bool
2120 precision_qualifier_allowed(const glsl_type *type)
2121 {
2122 /* Precision qualifiers apply to floating point, integer and opaque
2123 * types.
2124 *
2125 * Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:
2126 * "Any floating point or any integer declaration can have the type
2127 * preceded by one of these precision qualifiers [...] Literal
2128 * constants do not have precision qualifiers. Neither do Boolean
2129 * variables.
2130 *
2131 * Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.30
2132 * spec also says:
2133 *
2134 * "Precision qualifiers are added for code portability with OpenGL
2135 * ES, not for functionality. They have the same syntax as in OpenGL
2136 * ES."
2137 *
2138 * Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:
2139 *
2140 * "uniform lowp sampler2D sampler;
2141 * highp vec2 coord;
2142 * ...
2143 * lowp vec4 col = texture2D (sampler, coord);
2144 * // texture2D returns lowp"
2145 *
2146 * From this, we infer that GLSL 1.30 (and later) should allow precision
2147 * qualifiers on sampler types just like float and integer types.
2148 */
2149 return type->is_float()
2150 || type->is_integer()
2151 || type->is_record()
2152 || type->contains_opaque();
2153 }
2154
2155 const glsl_type *
2156 ast_type_specifier::glsl_type(const char **name,
2157 struct _mesa_glsl_parse_state *state) const
2158 {
2159 const struct glsl_type *type;
2160
2161 type = state->symbols->get_type(this->type_name);
2162 *name = this->type_name;
2163
2164 YYLTYPE loc = this->get_location();
2165 type = process_array_type(&loc, type, this->array_specifier, state);
2166
2167 return type;
2168 }
2169
2170 const glsl_type *
2171 ast_fully_specified_type::glsl_type(const char **name,
2172 struct _mesa_glsl_parse_state *state) const
2173 {
2174 const struct glsl_type *type = this->specifier->glsl_type(name, state);
2175
2176 if (type == NULL)
2177 return NULL;
2178
2179 /* The fragment language does not define a default precision value
2180 * for float types, so check that one is defined if the type declaration
2181 * isn't providing one explictly.
2182 */
2183 if (type->base_type == GLSL_TYPE_FLOAT
2184 && state->es_shader
2185 && state->stage == MESA_SHADER_FRAGMENT
2186 && this->qualifier.precision == ast_precision_none
2187 && state->symbols->get_default_precision_qualifier("float") == ast_precision_none) {
2188 YYLTYPE loc = this->get_location();
2189 _mesa_glsl_error(&loc, state,
2190 "no precision specified this scope for type `%s'",
2191 type->name);
2192 }
2193
2194 return type;
2195 }
2196
2197 /**
2198 * Determine whether a toplevel variable declaration declares a varying. This
2199 * function operates by examining the variable's mode and the shader target,
2200 * so it correctly identifies linkage variables regardless of whether they are
2201 * declared using the deprecated "varying" syntax or the new "in/out" syntax.
2202 *
2203 * Passing a non-toplevel variable declaration (e.g. a function parameter) to
2204 * this function will produce undefined results.
2205 */
2206 static bool
2207 is_varying_var(ir_variable *var, gl_shader_stage target)
2208 {
2209 switch (target) {
2210 case MESA_SHADER_VERTEX:
2211 return var->data.mode == ir_var_shader_out;
2212 case MESA_SHADER_FRAGMENT:
2213 return var->data.mode == ir_var_shader_in;
2214 default:
2215 return var->data.mode == ir_var_shader_out || var->data.mode == ir_var_shader_in;
2216 }
2217 }
2218
2219
2220 /**
2221 * Matrix layout qualifiers are only allowed on certain types
2222 */
2223 static void
2224 validate_matrix_layout_for_type(struct _mesa_glsl_parse_state *state,
2225 YYLTYPE *loc,
2226 const glsl_type *type,
2227 ir_variable *var)
2228 {
2229 if (var && !var->is_in_buffer_block()) {
2230 /* Layout qualifiers may only apply to interface blocks and fields in
2231 * them.
2232 */
2233 _mesa_glsl_error(loc, state,
2234 "uniform block layout qualifiers row_major and "
2235 "column_major may not be applied to variables "
2236 "outside of uniform blocks");
2237 } else if (!type->is_matrix()) {
2238 /* The OpenGL ES 3.0 conformance tests did not originally allow
2239 * matrix layout qualifiers on non-matrices. However, the OpenGL
2240 * 4.4 and OpenGL ES 3.0 (revision TBD) specifications were
2241 * amended to specifically allow these layouts on all types. Emit
2242 * a warning so that people know their code may not be portable.
2243 */
2244 _mesa_glsl_warning(loc, state,
2245 "uniform block layout qualifiers row_major and "
2246 "column_major applied to non-matrix types may "
2247 "be rejected by older compilers");
2248 } else if (type->is_record()) {
2249 /* We allow 'layout(row_major)' on structure types because it's the only
2250 * way to get row-major layouts on matrices contained in structures.
2251 */
2252 _mesa_glsl_warning(loc, state,
2253 "uniform block layout qualifiers row_major and "
2254 "column_major applied to structure types is not "
2255 "strictly conformant and may be rejected by other "
2256 "compilers");
2257 }
2258 }
2259
2260 static bool
2261 validate_binding_qualifier(struct _mesa_glsl_parse_state *state,
2262 YYLTYPE *loc,
2263 const glsl_type *type,
2264 const ast_type_qualifier *qual)
2265 {
2266 if (!qual->flags.q.uniform && !qual->flags.q.buffer) {
2267 _mesa_glsl_error(loc, state,
2268 "the \"binding\" qualifier only applies to uniforms and "
2269 "shader storage buffer objects");
2270 return false;
2271 }
2272
2273 if (qual->binding < 0) {
2274 _mesa_glsl_error(loc, state, "binding values must be >= 0");
2275 return false;
2276 }
2277
2278 const struct gl_context *const ctx = state->ctx;
2279 unsigned elements = type->is_array() ? type->arrays_of_arrays_size() : 1;
2280 unsigned max_index = qual->binding + elements - 1;
2281 const glsl_type *base_type = type->without_array();
2282
2283 if (base_type->is_interface()) {
2284 /* UBOs. From page 60 of the GLSL 4.20 specification:
2285 * "If the binding point for any uniform block instance is less than zero,
2286 * or greater than or equal to the implementation-dependent maximum
2287 * number of uniform buffer bindings, a compilation error will occur.
2288 * When the binding identifier is used with a uniform block instanced as
2289 * an array of size N, all elements of the array from binding through
2290 * binding + N – 1 must be within this range."
2291 *
2292 * The implementation-dependent maximum is GL_MAX_UNIFORM_BUFFER_BINDINGS.
2293 */
2294 if (qual->flags.q.uniform &&
2295 max_index >= ctx->Const.MaxUniformBufferBindings) {
2296 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d UBOs exceeds "
2297 "the maximum number of UBO binding points (%d)",
2298 qual->binding, elements,
2299 ctx->Const.MaxUniformBufferBindings);
2300 return false;
2301 }
2302
2303 /* SSBOs. From page 67 of the GLSL 4.30 specification:
2304 * "If the binding point for any uniform or shader storage block instance
2305 * is less than zero, or greater than or equal to the
2306 * implementation-dependent maximum number of uniform buffer bindings, a
2307 * compile-time error will occur. When the binding identifier is used
2308 * with a uniform or shader storage block instanced as an array of size
2309 * N, all elements of the array from binding through binding + N – 1 must
2310 * be within this range."
2311 */
2312 if (qual->flags.q.buffer &&
2313 max_index >= ctx->Const.MaxShaderStorageBufferBindings) {
2314 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d SSBOs exceeds "
2315 "the maximum number of SSBO binding points (%d)",
2316 qual->binding, elements,
2317 ctx->Const.MaxShaderStorageBufferBindings);
2318 return false;
2319 }
2320 } else if (base_type->is_sampler()) {
2321 /* Samplers. From page 63 of the GLSL 4.20 specification:
2322 * "If the binding is less than zero, or greater than or equal to the
2323 * implementation-dependent maximum supported number of units, a
2324 * compilation error will occur. When the binding identifier is used
2325 * with an array of size N, all elements of the array from binding
2326 * through binding + N - 1 must be within this range."
2327 */
2328 unsigned limit = ctx->Const.MaxCombinedTextureImageUnits;
2329
2330 if (max_index >= limit) {
2331 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d samplers "
2332 "exceeds the maximum number of texture image units "
2333 "(%d)", qual->binding, elements, limit);
2334
2335 return false;
2336 }
2337 } else if (base_type->contains_atomic()) {
2338 assert(ctx->Const.MaxAtomicBufferBindings <= MAX_COMBINED_ATOMIC_BUFFERS);
2339 if (unsigned(qual->binding) >= ctx->Const.MaxAtomicBufferBindings) {
2340 _mesa_glsl_error(loc, state, "layout(binding = %d) exceeds the "
2341 " maximum number of atomic counter buffer bindings"
2342 "(%d)", qual->binding,
2343 ctx->Const.MaxAtomicBufferBindings);
2344
2345 return false;
2346 }
2347 } else if (state->is_version(420, 310) && base_type->is_image()) {
2348 assert(ctx->Const.MaxImageUnits <= MAX_IMAGE_UNITS);
2349 if (max_index >= ctx->Const.MaxImageUnits) {
2350 _mesa_glsl_error(loc, state, "Image binding %d exceeds the "
2351 " maximum number of image units (%d)", max_index,
2352 ctx->Const.MaxImageUnits);
2353 return false;
2354 }
2355
2356 } else {
2357 _mesa_glsl_error(loc, state,
2358 "the \"binding\" qualifier only applies to uniform "
2359 "blocks, opaque variables, or arrays thereof");
2360 return false;
2361 }
2362
2363 return true;
2364 }
2365
2366
2367 static glsl_interp_qualifier
2368 interpret_interpolation_qualifier(const struct ast_type_qualifier *qual,
2369 ir_variable_mode mode,
2370 struct _mesa_glsl_parse_state *state,
2371 YYLTYPE *loc)
2372 {
2373 glsl_interp_qualifier interpolation;
2374 if (qual->flags.q.flat)
2375 interpolation = INTERP_QUALIFIER_FLAT;
2376 else if (qual->flags.q.noperspective)
2377 interpolation = INTERP_QUALIFIER_NOPERSPECTIVE;
2378 else if (qual->flags.q.smooth)
2379 interpolation = INTERP_QUALIFIER_SMOOTH;
2380 else
2381 interpolation = INTERP_QUALIFIER_NONE;
2382
2383 if (interpolation != INTERP_QUALIFIER_NONE) {
2384 if (mode != ir_var_shader_in && mode != ir_var_shader_out) {
2385 _mesa_glsl_error(loc, state,
2386 "interpolation qualifier `%s' can only be applied to "
2387 "shader inputs or outputs.",
2388 interpolation_string(interpolation));
2389
2390 }
2391
2392 if ((state->stage == MESA_SHADER_VERTEX && mode == ir_var_shader_in) ||
2393 (state->stage == MESA_SHADER_FRAGMENT && mode == ir_var_shader_out)) {
2394 _mesa_glsl_error(loc, state,
2395 "interpolation qualifier `%s' cannot be applied to "
2396 "vertex shader inputs or fragment shader outputs",
2397 interpolation_string(interpolation));
2398 }
2399 }
2400
2401 return interpolation;
2402 }
2403
2404
2405 static void
2406 validate_explicit_location(const struct ast_type_qualifier *qual,
2407 ir_variable *var,
2408 struct _mesa_glsl_parse_state *state,
2409 YYLTYPE *loc)
2410 {
2411 bool fail = false;
2412
2413 /* Checks for GL_ARB_explicit_uniform_location. */
2414 if (qual->flags.q.uniform) {
2415 if (!state->check_explicit_uniform_location_allowed(loc, var))
2416 return;
2417
2418 const struct gl_context *const ctx = state->ctx;
2419 unsigned max_loc = qual->location + var->type->uniform_locations() - 1;
2420
2421 if (max_loc >= ctx->Const.MaxUserAssignableUniformLocations) {
2422 _mesa_glsl_error(loc, state, "location(s) consumed by uniform %s "
2423 ">= MAX_UNIFORM_LOCATIONS (%u)", var->name,
2424 ctx->Const.MaxUserAssignableUniformLocations);
2425 return;
2426 }
2427
2428 var->data.explicit_location = true;
2429 var->data.location = qual->location;
2430 return;
2431 }
2432
2433 /* Between GL_ARB_explicit_attrib_location an
2434 * GL_ARB_separate_shader_objects, the inputs and outputs of any shader
2435 * stage can be assigned explicit locations. The checking here associates
2436 * the correct extension with the correct stage's input / output:
2437 *
2438 * input output
2439 * ----- ------
2440 * vertex explicit_loc sso
2441 * tess control sso sso
2442 * tess eval sso sso
2443 * geometry sso sso
2444 * fragment sso explicit_loc
2445 */
2446 switch (state->stage) {
2447 case MESA_SHADER_VERTEX:
2448 if (var->data.mode == ir_var_shader_in) {
2449 if (!state->check_explicit_attrib_location_allowed(loc, var))
2450 return;
2451
2452 break;
2453 }
2454
2455 if (var->data.mode == ir_var_shader_out) {
2456 if (!state->check_separate_shader_objects_allowed(loc, var))
2457 return;
2458
2459 break;
2460 }
2461
2462 fail = true;
2463 break;
2464
2465 case MESA_SHADER_TESS_CTRL:
2466 case MESA_SHADER_TESS_EVAL:
2467 case MESA_SHADER_GEOMETRY:
2468 if (var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) {
2469 if (!state->check_separate_shader_objects_allowed(loc, var))
2470 return;
2471
2472 break;
2473 }
2474
2475 fail = true;
2476 break;
2477
2478 case MESA_SHADER_FRAGMENT:
2479 if (var->data.mode == ir_var_shader_in) {
2480 if (!state->check_separate_shader_objects_allowed(loc, var))
2481 return;
2482
2483 break;
2484 }
2485
2486 if (var->data.mode == ir_var_shader_out) {
2487 if (!state->check_explicit_attrib_location_allowed(loc, var))
2488 return;
2489
2490 break;
2491 }
2492
2493 fail = true;
2494 break;
2495
2496 case MESA_SHADER_COMPUTE:
2497 _mesa_glsl_error(loc, state,
2498 "compute shader variables cannot be given "
2499 "explicit locations");
2500 return;
2501 };
2502
2503 if (fail) {
2504 _mesa_glsl_error(loc, state,
2505 "%s cannot be given an explicit location in %s shader",
2506 mode_string(var),
2507 _mesa_shader_stage_to_string(state->stage));
2508 } else {
2509 var->data.explicit_location = true;
2510
2511 switch (state->stage) {
2512 case MESA_SHADER_VERTEX:
2513 var->data.location = (var->data.mode == ir_var_shader_in)
2514 ? (qual->location + VERT_ATTRIB_GENERIC0)
2515 : (qual->location + VARYING_SLOT_VAR0);
2516 break;
2517
2518 case MESA_SHADER_TESS_CTRL:
2519 case MESA_SHADER_TESS_EVAL:
2520 case MESA_SHADER_GEOMETRY:
2521 if (var->data.patch)
2522 var->data.location = qual->location + VARYING_SLOT_PATCH0;
2523 else
2524 var->data.location = qual->location + VARYING_SLOT_VAR0;
2525 break;
2526
2527 case MESA_SHADER_FRAGMENT:
2528 var->data.location = (var->data.mode == ir_var_shader_out)
2529 ? (qual->location + FRAG_RESULT_DATA0)
2530 : (qual->location + VARYING_SLOT_VAR0);
2531 break;
2532 case MESA_SHADER_COMPUTE:
2533 assert(!"Unexpected shader type");
2534 break;
2535 }
2536
2537 if (qual->flags.q.explicit_index) {
2538 /* From the GLSL 4.30 specification, section 4.4.2 (Output
2539 * Layout Qualifiers):
2540 *
2541 * "It is also a compile-time error if a fragment shader
2542 * sets a layout index to less than 0 or greater than 1."
2543 *
2544 * Older specifications don't mandate a behavior; we take
2545 * this as a clarification and always generate the error.
2546 */
2547 if (qual->index < 0 || qual->index > 1) {
2548 _mesa_glsl_error(loc, state,
2549 "explicit index may only be 0 or 1");
2550 } else {
2551 var->data.explicit_index = true;
2552 var->data.index = qual->index;
2553 }
2554 }
2555 }
2556 }
2557
2558 static void
2559 apply_image_qualifier_to_variable(const struct ast_type_qualifier *qual,
2560 ir_variable *var,
2561 struct _mesa_glsl_parse_state *state,
2562 YYLTYPE *loc)
2563 {
2564 const glsl_type *base_type = var->type->without_array();
2565
2566 if (base_type->is_image()) {
2567 if (var->data.mode != ir_var_uniform &&
2568 var->data.mode != ir_var_function_in) {
2569 _mesa_glsl_error(loc, state, "image variables may only be declared as "
2570 "function parameters or uniform-qualified "
2571 "global variables");
2572 }
2573
2574 var->data.image_read_only |= qual->flags.q.read_only;
2575 var->data.image_write_only |= qual->flags.q.write_only;
2576 var->data.image_coherent |= qual->flags.q.coherent;
2577 var->data.image_volatile |= qual->flags.q._volatile;
2578 var->data.image_restrict |= qual->flags.q.restrict_flag;
2579 var->data.read_only = true;
2580
2581 if (qual->flags.q.explicit_image_format) {
2582 if (var->data.mode == ir_var_function_in) {
2583 _mesa_glsl_error(loc, state, "format qualifiers cannot be "
2584 "used on image function parameters");
2585 }
2586
2587 if (qual->image_base_type != base_type->sampler_type) {
2588 _mesa_glsl_error(loc, state, "format qualifier doesn't match the "
2589 "base data type of the image");
2590 }
2591
2592 var->data.image_format = qual->image_format;
2593 } else {
2594 if (var->data.mode == ir_var_uniform) {
2595 if (state->es_shader) {
2596 _mesa_glsl_error(loc, state, "all image uniforms "
2597 "must have a format layout qualifier");
2598
2599 } else if (!qual->flags.q.write_only) {
2600 _mesa_glsl_error(loc, state, "image uniforms not qualified with "
2601 "`writeonly' must have a format layout "
2602 "qualifier");
2603 }
2604 }
2605
2606 var->data.image_format = GL_NONE;
2607 }
2608
2609 /* From page 70 of the GLSL ES 3.1 specification:
2610 *
2611 * "Except for image variables qualified with the format qualifiers
2612 * r32f, r32i, and r32ui, image variables must specify either memory
2613 * qualifier readonly or the memory qualifier writeonly."
2614 */
2615 if (state->es_shader &&
2616 var->data.image_format != GL_R32F &&
2617 var->data.image_format != GL_R32I &&
2618 var->data.image_format != GL_R32UI &&
2619 !var->data.image_read_only &&
2620 !var->data.image_write_only) {
2621 _mesa_glsl_error(loc, state, "image variables of format other than "
2622 "r32f, r32i or r32ui must be qualified `readonly' or "
2623 "`writeonly'");
2624 }
2625
2626 } else if (qual->flags.q.read_only ||
2627 qual->flags.q.write_only ||
2628 qual->flags.q.coherent ||
2629 qual->flags.q._volatile ||
2630 qual->flags.q.restrict_flag ||
2631 qual->flags.q.explicit_image_format) {
2632 _mesa_glsl_error(loc, state, "memory qualifiers may only be applied to "
2633 "images");
2634 }
2635 }
2636
2637 static inline const char*
2638 get_layout_qualifier_string(bool origin_upper_left, bool pixel_center_integer)
2639 {
2640 if (origin_upper_left && pixel_center_integer)
2641 return "origin_upper_left, pixel_center_integer";
2642 else if (origin_upper_left)
2643 return "origin_upper_left";
2644 else if (pixel_center_integer)
2645 return "pixel_center_integer";
2646 else
2647 return " ";
2648 }
2649
2650 static inline bool
2651 is_conflicting_fragcoord_redeclaration(struct _mesa_glsl_parse_state *state,
2652 const struct ast_type_qualifier *qual)
2653 {
2654 /* If gl_FragCoord was previously declared, and the qualifiers were
2655 * different in any way, return true.
2656 */
2657 if (state->fs_redeclares_gl_fragcoord) {
2658 return (state->fs_pixel_center_integer != qual->flags.q.pixel_center_integer
2659 || state->fs_origin_upper_left != qual->flags.q.origin_upper_left);
2660 }
2661
2662 return false;
2663 }
2664
2665 static inline void
2666 validate_array_dimensions(const glsl_type *t,
2667 struct _mesa_glsl_parse_state *state,
2668 YYLTYPE *loc) {
2669 if (t->is_array()) {
2670 t = t->fields.array;
2671 while (t->is_array()) {
2672 if (t->is_unsized_array()) {
2673 _mesa_glsl_error(loc, state,
2674 "only the outermost array dimension can "
2675 "be unsized",
2676 t->name);
2677 break;
2678 }
2679 t = t->fields.array;
2680 }
2681 }
2682 }
2683
2684 static void
2685 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
2686 ir_variable *var,
2687 struct _mesa_glsl_parse_state *state,
2688 YYLTYPE *loc,
2689 bool is_parameter)
2690 {
2691 STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));
2692
2693 if (qual->flags.q.invariant) {
2694 if (var->data.used) {
2695 _mesa_glsl_error(loc, state,
2696 "variable `%s' may not be redeclared "
2697 "`invariant' after being used",
2698 var->name);
2699 } else {
2700 var->data.invariant = 1;
2701 }
2702 }
2703
2704 if (qual->flags.q.precise) {
2705 if (var->data.used) {
2706 _mesa_glsl_error(loc, state,
2707 "variable `%s' may not be redeclared "
2708 "`precise' after being used",
2709 var->name);
2710 } else {
2711 var->data.precise = 1;
2712 }
2713 }
2714
2715 if (qual->flags.q.subroutine && !qual->flags.q.uniform) {
2716 _mesa_glsl_error(loc, state,
2717 "`subroutine' may only be applied to uniforms, "
2718 "subroutine type declarations, or function definitions");
2719 }
2720
2721 if (qual->flags.q.constant || qual->flags.q.attribute
2722 || qual->flags.q.uniform
2723 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2724 var->data.read_only = 1;
2725
2726 if (qual->flags.q.centroid)
2727 var->data.centroid = 1;
2728
2729 if (qual->flags.q.sample)
2730 var->data.sample = 1;
2731
2732 if (state->stage == MESA_SHADER_GEOMETRY &&
2733 qual->flags.q.out && qual->flags.q.stream) {
2734 var->data.stream = qual->stream;
2735 }
2736
2737 if (qual->flags.q.patch)
2738 var->data.patch = 1;
2739
2740 if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {
2741 var->type = glsl_type::error_type;
2742 _mesa_glsl_error(loc, state,
2743 "`attribute' variables may not be declared in the "
2744 "%s shader",
2745 _mesa_shader_stage_to_string(state->stage));
2746 }
2747
2748 /* Disallow layout qualifiers which may only appear on layout declarations. */
2749 if (qual->flags.q.prim_type) {
2750 _mesa_glsl_error(loc, state,
2751 "Primitive type may only be specified on GS input or output "
2752 "layout declaration, not on variables.");
2753 }
2754
2755 /* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:
2756 *
2757 * "However, the const qualifier cannot be used with out or inout."
2758 *
2759 * The same section of the GLSL 4.40 spec further clarifies this saying:
2760 *
2761 * "The const qualifier cannot be used with out or inout, or a
2762 * compile-time error results."
2763 */
2764 if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {
2765 _mesa_glsl_error(loc, state,
2766 "`const' may not be applied to `out' or `inout' "
2767 "function parameters");
2768 }
2769
2770 /* If there is no qualifier that changes the mode of the variable, leave
2771 * the setting alone.
2772 */
2773 assert(var->data.mode != ir_var_temporary);
2774 if (qual->flags.q.in && qual->flags.q.out)
2775 var->data.mode = ir_var_function_inout;
2776 else if (qual->flags.q.in)
2777 var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;
2778 else if (qual->flags.q.attribute
2779 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2780 var->data.mode = ir_var_shader_in;
2781 else if (qual->flags.q.out)
2782 var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;
2783 else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))
2784 var->data.mode = ir_var_shader_out;
2785 else if (qual->flags.q.uniform)
2786 var->data.mode = ir_var_uniform;
2787 else if (qual->flags.q.buffer)
2788 var->data.mode = ir_var_shader_storage;
2789 else if (qual->flags.q.shared_storage)
2790 var->data.mode = ir_var_shader_shared;
2791
2792 if (!is_parameter && is_varying_var(var, state->stage)) {
2793 /* User-defined ins/outs are not permitted in compute shaders. */
2794 if (state->stage == MESA_SHADER_COMPUTE) {
2795 _mesa_glsl_error(loc, state,
2796 "user-defined input and output variables are not "
2797 "permitted in compute shaders");
2798 }
2799
2800 /* This variable is being used to link data between shader stages (in
2801 * pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type
2802 * that is allowed for such purposes.
2803 *
2804 * From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
2805 *
2806 * "The varying qualifier can be used only with the data types
2807 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
2808 * these."
2809 *
2810 * This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From
2811 * page 31 (page 37 of the PDF) of the GLSL 1.30 spec:
2812 *
2813 * "Fragment inputs can only be signed and unsigned integers and
2814 * integer vectors, float, floating-point vectors, matrices, or
2815 * arrays of these. Structures cannot be input.
2816 *
2817 * Similar text exists in the section on vertex shader outputs.
2818 *
2819 * Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES
2820 * 3.00 spec allows structs as well. Varying structs are also allowed
2821 * in GLSL 1.50.
2822 */
2823 switch (var->type->get_scalar_type()->base_type) {
2824 case GLSL_TYPE_FLOAT:
2825 /* Ok in all GLSL versions */
2826 break;
2827 case GLSL_TYPE_UINT:
2828 case GLSL_TYPE_INT:
2829 if (state->is_version(130, 300))
2830 break;
2831 _mesa_glsl_error(loc, state,
2832 "varying variables must be of base type float in %s",
2833 state->get_version_string());
2834 break;
2835 case GLSL_TYPE_STRUCT:
2836 if (state->is_version(150, 300))
2837 break;
2838 _mesa_glsl_error(loc, state,
2839 "varying variables may not be of type struct");
2840 break;
2841 case GLSL_TYPE_DOUBLE:
2842 break;
2843 default:
2844 _mesa_glsl_error(loc, state, "illegal type for a varying variable");
2845 break;
2846 }
2847 }
2848
2849 if (state->all_invariant && (state->current_function == NULL)) {
2850 switch (state->stage) {
2851 case MESA_SHADER_VERTEX:
2852 if (var->data.mode == ir_var_shader_out)
2853 var->data.invariant = true;
2854 break;
2855 case MESA_SHADER_TESS_CTRL:
2856 case MESA_SHADER_TESS_EVAL:
2857 case MESA_SHADER_GEOMETRY:
2858 if ((var->data.mode == ir_var_shader_in)
2859 || (var->data.mode == ir_var_shader_out))
2860 var->data.invariant = true;
2861 break;
2862 case MESA_SHADER_FRAGMENT:
2863 if (var->data.mode == ir_var_shader_in)
2864 var->data.invariant = true;
2865 break;
2866 case MESA_SHADER_COMPUTE:
2867 /* Invariance isn't meaningful in compute shaders. */
2868 break;
2869 }
2870 }
2871
2872 var->data.interpolation =
2873 interpret_interpolation_qualifier(qual, (ir_variable_mode) var->data.mode,
2874 state, loc);
2875
2876 var->data.pixel_center_integer = qual->flags.q.pixel_center_integer;
2877 var->data.origin_upper_left = qual->flags.q.origin_upper_left;
2878 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
2879 && (strcmp(var->name, "gl_FragCoord") != 0)) {
2880 const char *const qual_string = (qual->flags.q.origin_upper_left)
2881 ? "origin_upper_left" : "pixel_center_integer";
2882
2883 _mesa_glsl_error(loc, state,
2884 "layout qualifier `%s' can only be applied to "
2885 "fragment shader input `gl_FragCoord'",
2886 qual_string);
2887 }
2888
2889 if (var->name != NULL && strcmp(var->name, "gl_FragCoord") == 0) {
2890
2891 /* Section 4.3.8.1, page 39 of GLSL 1.50 spec says:
2892 *
2893 * "Within any shader, the first redeclarations of gl_FragCoord
2894 * must appear before any use of gl_FragCoord."
2895 *
2896 * Generate a compiler error if above condition is not met by the
2897 * fragment shader.
2898 */
2899 ir_variable *earlier = state->symbols->get_variable("gl_FragCoord");
2900 if (earlier != NULL &&
2901 earlier->data.used &&
2902 !state->fs_redeclares_gl_fragcoord) {
2903 _mesa_glsl_error(loc, state,
2904 "gl_FragCoord used before its first redeclaration "
2905 "in fragment shader");
2906 }
2907
2908 /* Make sure all gl_FragCoord redeclarations specify the same layout
2909 * qualifiers.
2910 */
2911 if (is_conflicting_fragcoord_redeclaration(state, qual)) {
2912 const char *const qual_string =
2913 get_layout_qualifier_string(qual->flags.q.origin_upper_left,
2914 qual->flags.q.pixel_center_integer);
2915
2916 const char *const state_string =
2917 get_layout_qualifier_string(state->fs_origin_upper_left,
2918 state->fs_pixel_center_integer);
2919
2920 _mesa_glsl_error(loc, state,
2921 "gl_FragCoord redeclared with different layout "
2922 "qualifiers (%s) and (%s) ",
2923 state_string,
2924 qual_string);
2925 }
2926 state->fs_origin_upper_left = qual->flags.q.origin_upper_left;
2927 state->fs_pixel_center_integer = qual->flags.q.pixel_center_integer;
2928 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers =
2929 !qual->flags.q.origin_upper_left && !qual->flags.q.pixel_center_integer;
2930 state->fs_redeclares_gl_fragcoord =
2931 state->fs_origin_upper_left ||
2932 state->fs_pixel_center_integer ||
2933 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers;
2934 }
2935
2936 if (qual->flags.q.explicit_location) {
2937 validate_explicit_location(qual, var, state, loc);
2938 } else if (qual->flags.q.explicit_index) {
2939 _mesa_glsl_error(loc, state, "explicit index requires explicit location");
2940 }
2941
2942 if (qual->flags.q.explicit_binding &&
2943 validate_binding_qualifier(state, loc, var->type, qual)) {
2944 var->data.explicit_binding = true;
2945 var->data.binding = qual->binding;
2946 }
2947
2948 if (var->type->contains_atomic()) {
2949 if (var->data.mode == ir_var_uniform) {
2950 if (var->data.explicit_binding) {
2951 unsigned *offset =
2952 &state->atomic_counter_offsets[var->data.binding];
2953
2954 if (*offset % ATOMIC_COUNTER_SIZE)
2955 _mesa_glsl_error(loc, state,
2956 "misaligned atomic counter offset");
2957
2958 var->data.atomic.offset = *offset;
2959 *offset += var->type->atomic_size();
2960
2961 } else {
2962 _mesa_glsl_error(loc, state,
2963 "atomic counters require explicit binding point");
2964 }
2965 } else if (var->data.mode != ir_var_function_in) {
2966 _mesa_glsl_error(loc, state, "atomic counters may only be declared as "
2967 "function parameters or uniform-qualified "
2968 "global variables");
2969 }
2970 }
2971
2972 /* Does the declaration use the deprecated 'attribute' or 'varying'
2973 * keywords?
2974 */
2975 const bool uses_deprecated_qualifier = qual->flags.q.attribute
2976 || qual->flags.q.varying;
2977
2978
2979 /* Validate auxiliary storage qualifiers */
2980
2981 /* From section 4.3.4 of the GLSL 1.30 spec:
2982 * "It is an error to use centroid in in a vertex shader."
2983 *
2984 * From section 4.3.4 of the GLSL ES 3.00 spec:
2985 * "It is an error to use centroid in or interpolation qualifiers in
2986 * a vertex shader input."
2987 */
2988
2989 /* Section 4.3.6 of the GLSL 1.30 specification states:
2990 * "It is an error to use centroid out in a fragment shader."
2991 *
2992 * The GL_ARB_shading_language_420pack extension specification states:
2993 * "It is an error to use auxiliary storage qualifiers or interpolation
2994 * qualifiers on an output in a fragment shader."
2995 */
2996 if (qual->flags.q.sample && (!is_varying_var(var, state->stage) || uses_deprecated_qualifier)) {
2997 _mesa_glsl_error(loc, state,
2998 "sample qualifier may only be used on `in` or `out` "
2999 "variables between shader stages");
3000 }
3001 if (qual->flags.q.centroid && !is_varying_var(var, state->stage)) {
3002 _mesa_glsl_error(loc, state,
3003 "centroid qualifier may only be used with `in', "
3004 "`out' or `varying' variables between shader stages");
3005 }
3006
3007
3008 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
3009 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
3010 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
3011 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
3012 * These extensions and all following extensions that add the 'layout'
3013 * keyword have been modified to require the use of 'in' or 'out'.
3014 *
3015 * The following extension do not allow the deprecated keywords:
3016 *
3017 * GL_AMD_conservative_depth
3018 * GL_ARB_conservative_depth
3019 * GL_ARB_gpu_shader5
3020 * GL_ARB_separate_shader_objects
3021 * GL_ARB_tessellation_shader
3022 * GL_ARB_transform_feedback3
3023 * GL_ARB_uniform_buffer_object
3024 *
3025 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
3026 * allow layout with the deprecated keywords.
3027 */
3028 const bool relaxed_layout_qualifier_checking =
3029 state->ARB_fragment_coord_conventions_enable;
3030
3031 if (qual->has_layout() && uses_deprecated_qualifier) {
3032 if (relaxed_layout_qualifier_checking) {
3033 _mesa_glsl_warning(loc, state,
3034 "`layout' qualifier may not be used with "
3035 "`attribute' or `varying'");
3036 } else {
3037 _mesa_glsl_error(loc, state,
3038 "`layout' qualifier may not be used with "
3039 "`attribute' or `varying'");
3040 }
3041 }
3042
3043 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
3044 * AMD_conservative_depth.
3045 */
3046 int depth_layout_count = qual->flags.q.depth_any
3047 + qual->flags.q.depth_greater
3048 + qual->flags.q.depth_less
3049 + qual->flags.q.depth_unchanged;
3050 if (depth_layout_count > 0
3051 && !state->AMD_conservative_depth_enable
3052 && !state->ARB_conservative_depth_enable) {
3053 _mesa_glsl_error(loc, state,
3054 "extension GL_AMD_conservative_depth or "
3055 "GL_ARB_conservative_depth must be enabled "
3056 "to use depth layout qualifiers");
3057 } else if (depth_layout_count > 0
3058 && strcmp(var->name, "gl_FragDepth") != 0) {
3059 _mesa_glsl_error(loc, state,
3060 "depth layout qualifiers can be applied only to "
3061 "gl_FragDepth");
3062 } else if (depth_layout_count > 1
3063 && strcmp(var->name, "gl_FragDepth") == 0) {
3064 _mesa_glsl_error(loc, state,
3065 "at most one depth layout qualifier can be applied to "
3066 "gl_FragDepth");
3067 }
3068 if (qual->flags.q.depth_any)
3069 var->data.depth_layout = ir_depth_layout_any;
3070 else if (qual->flags.q.depth_greater)
3071 var->data.depth_layout = ir_depth_layout_greater;
3072 else if (qual->flags.q.depth_less)
3073 var->data.depth_layout = ir_depth_layout_less;
3074 else if (qual->flags.q.depth_unchanged)
3075 var->data.depth_layout = ir_depth_layout_unchanged;
3076 else
3077 var->data.depth_layout = ir_depth_layout_none;
3078
3079 if (qual->flags.q.std140 ||
3080 qual->flags.q.std430 ||
3081 qual->flags.q.packed ||
3082 qual->flags.q.shared) {
3083 _mesa_glsl_error(loc, state,
3084 "uniform and shader storage block layout qualifiers "
3085 "std140, std430, packed, and shared can only be "
3086 "applied to uniform or shader storage blocks, not "
3087 "members");
3088 }
3089
3090 if (qual->flags.q.shared_storage && state->stage != MESA_SHADER_COMPUTE) {
3091 _mesa_glsl_error(loc, state,
3092 "the shared storage qualifiers can only be used with "
3093 "compute shaders");
3094 }
3095
3096 if (qual->flags.q.row_major || qual->flags.q.column_major) {
3097 validate_matrix_layout_for_type(state, loc, var->type, var);
3098 }
3099
3100 apply_image_qualifier_to_variable(qual, var, state, loc);
3101
3102 /* From section 4.4.1.3 of the GLSL 4.50 specification (Fragment Shader
3103 * Inputs):
3104 *
3105 * "Fragment shaders also allow the following layout qualifier on in only
3106 * (not with variable declarations)
3107 * layout-qualifier-id
3108 * early_fragment_tests
3109 * [...]"
3110 */
3111 if (qual->flags.q.early_fragment_tests) {
3112 _mesa_glsl_error(loc, state, "early_fragment_tests layout qualifier only "
3113 "valid in fragment shader input layout declaration.");
3114 }
3115 }
3116
3117 /**
3118 * Get the variable that is being redeclared by this declaration
3119 *
3120 * Semantic checks to verify the validity of the redeclaration are also
3121 * performed. If semantic checks fail, compilation error will be emitted via
3122 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
3123 *
3124 * \returns
3125 * A pointer to an existing variable in the current scope if the declaration
3126 * is a redeclaration, \c NULL otherwise.
3127 */
3128 static ir_variable *
3129 get_variable_being_redeclared(ir_variable *var, YYLTYPE loc,
3130 struct _mesa_glsl_parse_state *state,
3131 bool allow_all_redeclarations)
3132 {
3133 /* Check if this declaration is actually a re-declaration, either to
3134 * resize an array or add qualifiers to an existing variable.
3135 *
3136 * This is allowed for variables in the current scope, or when at
3137 * global scope (for built-ins in the implicit outer scope).
3138 */
3139 ir_variable *earlier = state->symbols->get_variable(var->name);
3140 if (earlier == NULL ||
3141 (state->current_function != NULL &&
3142 !state->symbols->name_declared_this_scope(var->name))) {
3143 return NULL;
3144 }
3145
3146
3147 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
3148 *
3149 * "It is legal to declare an array without a size and then
3150 * later re-declare the same name as an array of the same
3151 * type and specify a size."
3152 */
3153 if (earlier->type->is_unsized_array() && var->type->is_array()
3154 && (var->type->fields.array == earlier->type->fields.array)) {
3155 /* FINISHME: This doesn't match the qualifiers on the two
3156 * FINISHME: declarations. It's not 100% clear whether this is
3157 * FINISHME: required or not.
3158 */
3159
3160 const unsigned size = unsigned(var->type->array_size());
3161 check_builtin_array_max_size(var->name, size, loc, state);
3162 if ((size > 0) && (size <= earlier->data.max_array_access)) {
3163 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
3164 "previous access",
3165 earlier->data.max_array_access);
3166 }
3167
3168 earlier->type = var->type;
3169 delete var;
3170 var = NULL;
3171 } else if ((state->ARB_fragment_coord_conventions_enable ||
3172 state->is_version(150, 0))
3173 && strcmp(var->name, "gl_FragCoord") == 0
3174 && earlier->type == var->type
3175 && earlier->data.mode == var->data.mode) {
3176 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
3177 * qualifiers.
3178 */
3179 earlier->data.origin_upper_left = var->data.origin_upper_left;
3180 earlier->data.pixel_center_integer = var->data.pixel_center_integer;
3181
3182 /* According to section 4.3.7 of the GLSL 1.30 spec,
3183 * the following built-in varaibles can be redeclared with an
3184 * interpolation qualifier:
3185 * * gl_FrontColor
3186 * * gl_BackColor
3187 * * gl_FrontSecondaryColor
3188 * * gl_BackSecondaryColor
3189 * * gl_Color
3190 * * gl_SecondaryColor
3191 */
3192 } else if (state->is_version(130, 0)
3193 && (strcmp(var->name, "gl_FrontColor") == 0
3194 || strcmp(var->name, "gl_BackColor") == 0
3195 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
3196 || strcmp(var->name, "gl_BackSecondaryColor") == 0
3197 || strcmp(var->name, "gl_Color") == 0
3198 || strcmp(var->name, "gl_SecondaryColor") == 0)
3199 && earlier->type == var->type
3200 && earlier->data.mode == var->data.mode) {
3201 earlier->data.interpolation = var->data.interpolation;
3202
3203 /* Layout qualifiers for gl_FragDepth. */
3204 } else if ((state->AMD_conservative_depth_enable ||
3205 state->ARB_conservative_depth_enable)
3206 && strcmp(var->name, "gl_FragDepth") == 0
3207 && earlier->type == var->type
3208 && earlier->data.mode == var->data.mode) {
3209
3210 /** From the AMD_conservative_depth spec:
3211 * Within any shader, the first redeclarations of gl_FragDepth
3212 * must appear before any use of gl_FragDepth.
3213 */
3214 if (earlier->data.used) {
3215 _mesa_glsl_error(&loc, state,
3216 "the first redeclaration of gl_FragDepth "
3217 "must appear before any use of gl_FragDepth");
3218 }
3219
3220 /* Prevent inconsistent redeclaration of depth layout qualifier. */
3221 if (earlier->data.depth_layout != ir_depth_layout_none
3222 && earlier->data.depth_layout != var->data.depth_layout) {
3223 _mesa_glsl_error(&loc, state,
3224 "gl_FragDepth: depth layout is declared here "
3225 "as '%s, but it was previously declared as "
3226 "'%s'",
3227 depth_layout_string(var->data.depth_layout),
3228 depth_layout_string(earlier->data.depth_layout));
3229 }
3230
3231 earlier->data.depth_layout = var->data.depth_layout;
3232
3233 } else if (allow_all_redeclarations) {
3234 if (earlier->data.mode != var->data.mode) {
3235 _mesa_glsl_error(&loc, state,
3236 "redeclaration of `%s' with incorrect qualifiers",
3237 var->name);
3238 } else if (earlier->type != var->type) {
3239 _mesa_glsl_error(&loc, state,
3240 "redeclaration of `%s' has incorrect type",
3241 var->name);
3242 }
3243 } else {
3244 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
3245 }
3246
3247 return earlier;
3248 }
3249
3250 /**
3251 * Generate the IR for an initializer in a variable declaration
3252 */
3253 ir_rvalue *
3254 process_initializer(ir_variable *var, ast_declaration *decl,
3255 ast_fully_specified_type *type,
3256 exec_list *initializer_instructions,
3257 struct _mesa_glsl_parse_state *state)
3258 {
3259 ir_rvalue *result = NULL;
3260
3261 YYLTYPE initializer_loc = decl->initializer->get_location();
3262
3263 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
3264 *
3265 * "All uniform variables are read-only and are initialized either
3266 * directly by an application via API commands, or indirectly by
3267 * OpenGL."
3268 */
3269 if (var->data.mode == ir_var_uniform) {
3270 state->check_version(120, 0, &initializer_loc,
3271 "cannot initialize uniform %s",
3272 var->name);
3273 }
3274
3275 /* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:
3276 *
3277 * "Buffer variables cannot have initializers."
3278 */
3279 if (var->data.mode == ir_var_shader_storage) {
3280 _mesa_glsl_error(&initializer_loc, state,
3281 "cannot initialize buffer variable %s",
3282 var->name);
3283 }
3284
3285 /* From section 4.1.7 of the GLSL 4.40 spec:
3286 *
3287 * "Opaque variables [...] are initialized only through the
3288 * OpenGL API; they cannot be declared with an initializer in a
3289 * shader."
3290 */
3291 if (var->type->contains_opaque()) {
3292 _mesa_glsl_error(&initializer_loc, state,
3293 "cannot initialize opaque variable %s",
3294 var->name);
3295 }
3296
3297 if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {
3298 _mesa_glsl_error(&initializer_loc, state,
3299 "cannot initialize %s shader input / %s %s",
3300 _mesa_shader_stage_to_string(state->stage),
3301 (state->stage == MESA_SHADER_VERTEX)
3302 ? "attribute" : "varying",
3303 var->name);
3304 }
3305
3306 if (var->data.mode == ir_var_shader_out && state->current_function == NULL) {
3307 _mesa_glsl_error(&initializer_loc, state,
3308 "cannot initialize %s shader output %s",
3309 _mesa_shader_stage_to_string(state->stage),
3310 var->name);
3311 }
3312
3313 /* If the initializer is an ast_aggregate_initializer, recursively store
3314 * type information from the LHS into it, so that its hir() function can do
3315 * type checking.
3316 */
3317 if (decl->initializer->oper == ast_aggregate)
3318 _mesa_ast_set_aggregate_type(var->type, decl->initializer);
3319
3320 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
3321 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions, state);
3322
3323 /* Calculate the constant value if this is a const or uniform
3324 * declaration.
3325 *
3326 * Section 4.3 (Storage Qualifiers) of the GLSL ES 1.00.17 spec says:
3327 *
3328 * "Declarations of globals without a storage qualifier, or with
3329 * just the const qualifier, may include initializers, in which case
3330 * they will be initialized before the first line of main() is
3331 * executed. Such initializers must be a constant expression."
3332 *
3333 * The same section of the GLSL ES 3.00.4 spec has similar language.
3334 */
3335 if (type->qualifier.flags.q.constant
3336 || type->qualifier.flags.q.uniform
3337 || (state->es_shader && state->current_function == NULL)) {
3338 ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,
3339 lhs, rhs, true);
3340 if (new_rhs != NULL) {
3341 rhs = new_rhs;
3342
3343 /* Section 4.3.3 (Constant Expressions) of the GLSL ES 3.00.4 spec
3344 * says:
3345 *
3346 * "A constant expression is one of
3347 *
3348 * ...
3349 *
3350 * - an expression formed by an operator on operands that are
3351 * all constant expressions, including getting an element of
3352 * a constant array, or a field of a constant structure, or
3353 * components of a constant vector. However, the sequence
3354 * operator ( , ) and the assignment operators ( =, +=, ...)
3355 * are not included in the operators that can create a
3356 * constant expression."
3357 *
3358 * Section 12.43 (Sequence operator and constant expressions) says:
3359 *
3360 * "Should the following construct be allowed?
3361 *
3362 * float a[2,3];
3363 *
3364 * The expression within the brackets uses the sequence operator
3365 * (',') and returns the integer 3 so the construct is declaring
3366 * a single-dimensional array of size 3. In some languages, the
3367 * construct declares a two-dimensional array. It would be
3368 * preferable to make this construct illegal to avoid confusion.
3369 *
3370 * One possibility is to change the definition of the sequence
3371 * operator so that it does not return a constant-expression and
3372 * hence cannot be used to declare an array size.
3373 *
3374 * RESOLUTION: The result of a sequence operator is not a
3375 * constant-expression."
3376 *
3377 * Section 4.3.3 (Constant Expressions) of the GLSL 4.30.9 spec
3378 * contains language almost identical to the section 4.3.3 in the
3379 * GLSL ES 3.00.4 spec. This is a new limitation for these GLSL
3380 * versions.
3381 */
3382 ir_constant *constant_value = rhs->constant_expression_value();
3383 if (!constant_value ||
3384 (state->is_version(430, 300) &&
3385 decl->initializer->has_sequence_subexpression())) {
3386 const char *const variable_mode =
3387 (type->qualifier.flags.q.constant)
3388 ? "const"
3389 : ((type->qualifier.flags.q.uniform) ? "uniform" : "global");
3390
3391 /* If ARB_shading_language_420pack is enabled, initializers of
3392 * const-qualified local variables do not have to be constant
3393 * expressions. Const-qualified global variables must still be
3394 * initialized with constant expressions.
3395 */
3396 if (!state->ARB_shading_language_420pack_enable
3397 || state->current_function == NULL) {
3398 _mesa_glsl_error(& initializer_loc, state,
3399 "initializer of %s variable `%s' must be a "
3400 "constant expression",
3401 variable_mode,
3402 decl->identifier);
3403 if (var->type->is_numeric()) {
3404 /* Reduce cascading errors. */
3405 var->constant_value = type->qualifier.flags.q.constant
3406 ? ir_constant::zero(state, var->type) : NULL;
3407 }
3408 }
3409 } else {
3410 rhs = constant_value;
3411 var->constant_value = type->qualifier.flags.q.constant
3412 ? constant_value : NULL;
3413 }
3414 } else {
3415 if (var->type->is_numeric()) {
3416 /* Reduce cascading errors. */
3417 var->constant_value = type->qualifier.flags.q.constant
3418 ? ir_constant::zero(state, var->type) : NULL;
3419 }
3420 }
3421 }
3422
3423 if (rhs && !rhs->type->is_error()) {
3424 bool temp = var->data.read_only;
3425 if (type->qualifier.flags.q.constant)
3426 var->data.read_only = false;
3427
3428 /* Never emit code to initialize a uniform.
3429 */
3430 const glsl_type *initializer_type;
3431 if (!type->qualifier.flags.q.uniform) {
3432 do_assignment(initializer_instructions, state,
3433 NULL,
3434 lhs, rhs,
3435 &result, true,
3436 true,
3437 type->get_location());
3438 initializer_type = result->type;
3439 } else
3440 initializer_type = rhs->type;
3441
3442 var->constant_initializer = rhs->constant_expression_value();
3443 var->data.has_initializer = true;
3444
3445 /* If the declared variable is an unsized array, it must inherrit
3446 * its full type from the initializer. A declaration such as
3447 *
3448 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
3449 *
3450 * becomes
3451 *
3452 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
3453 *
3454 * The assignment generated in the if-statement (below) will also
3455 * automatically handle this case for non-uniforms.
3456 *
3457 * If the declared variable is not an array, the types must
3458 * already match exactly. As a result, the type assignment
3459 * here can be done unconditionally. For non-uniforms the call
3460 * to do_assignment can change the type of the initializer (via
3461 * the implicit conversion rules). For uniforms the initializer
3462 * must be a constant expression, and the type of that expression
3463 * was validated above.
3464 */
3465 var->type = initializer_type;
3466
3467 var->data.read_only = temp;
3468 }
3469
3470 return result;
3471 }
3472
3473 static void
3474 validate_layout_qualifier_vertex_count(struct _mesa_glsl_parse_state *state,
3475 YYLTYPE loc, ir_variable *var,
3476 unsigned num_vertices,
3477 unsigned *size,
3478 const char *var_category)
3479 {
3480 if (var->type->is_unsized_array()) {
3481 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:
3482 *
3483 * All geometry shader input unsized array declarations will be
3484 * sized by an earlier input layout qualifier, when present, as per
3485 * the following table.
3486 *
3487 * Followed by a table mapping each allowed input layout qualifier to
3488 * the corresponding input length.
3489 *
3490 * Similarly for tessellation control shader outputs.
3491 */
3492 if (num_vertices != 0)
3493 var->type = glsl_type::get_array_instance(var->type->fields.array,
3494 num_vertices);
3495 } else {
3496 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec
3497 * includes the following examples of compile-time errors:
3498 *
3499 * // code sequence within one shader...
3500 * in vec4 Color1[]; // size unknown
3501 * ...Color1.length()...// illegal, length() unknown
3502 * in vec4 Color2[2]; // size is 2
3503 * ...Color1.length()...// illegal, Color1 still has no size
3504 * in vec4 Color3[3]; // illegal, input sizes are inconsistent
3505 * layout(lines) in; // legal, input size is 2, matching
3506 * in vec4 Color4[3]; // illegal, contradicts layout
3507 * ...
3508 *
3509 * To detect the case illustrated by Color3, we verify that the size of
3510 * an explicitly-sized array matches the size of any previously declared
3511 * explicitly-sized array. To detect the case illustrated by Color4, we
3512 * verify that the size of an explicitly-sized array is consistent with
3513 * any previously declared input layout.
3514 */
3515 if (num_vertices != 0 && var->type->length != num_vertices) {
3516 _mesa_glsl_error(&loc, state,
3517 "%s size contradicts previously declared layout "
3518 "(size is %u, but layout requires a size of %u)",
3519 var_category, var->type->length, num_vertices);
3520 } else if (*size != 0 && var->type->length != *size) {
3521 _mesa_glsl_error(&loc, state,
3522 "%s sizes are inconsistent (size is %u, but a "
3523 "previous declaration has size %u)",
3524 var_category, var->type->length, *size);
3525 } else {
3526 *size = var->type->length;
3527 }
3528 }
3529 }
3530
3531 static void
3532 handle_tess_ctrl_shader_output_decl(struct _mesa_glsl_parse_state *state,
3533 YYLTYPE loc, ir_variable *var)
3534 {
3535 unsigned num_vertices = 0;
3536
3537 if (state->tcs_output_vertices_specified) {
3538 num_vertices = state->out_qualifier->vertices;
3539 }
3540
3541 if (!var->type->is_array() && !var->data.patch) {
3542 _mesa_glsl_error(&loc, state,
3543 "tessellation control shader outputs must be arrays");
3544
3545 /* To avoid cascading failures, short circuit the checks below. */
3546 return;
3547 }
3548
3549 if (var->data.patch)
3550 return;
3551
3552 validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,
3553 &state->tcs_output_size,
3554 "tessellation control shader output");
3555 }
3556
3557 /**
3558 * Do additional processing necessary for tessellation control/evaluation shader
3559 * input declarations. This covers both interface block arrays and bare input
3560 * variables.
3561 */
3562 static void
3563 handle_tess_shader_input_decl(struct _mesa_glsl_parse_state *state,
3564 YYLTYPE loc, ir_variable *var)
3565 {
3566 if (!var->type->is_array() && !var->data.patch) {
3567 _mesa_glsl_error(&loc, state,
3568 "per-vertex tessellation shader inputs must be arrays");
3569 /* Avoid cascading failures. */
3570 return;
3571 }
3572
3573 if (var->data.patch)
3574 return;
3575
3576 /* Unsized arrays are implicitly sized to gl_MaxPatchVertices. */
3577 if (var->type->is_unsized_array()) {
3578 var->type = glsl_type::get_array_instance(var->type->fields.array,
3579 state->Const.MaxPatchVertices);
3580 }
3581 }
3582
3583
3584 /**
3585 * Do additional processing necessary for geometry shader input declarations
3586 * (this covers both interface blocks arrays and bare input variables).
3587 */
3588 static void
3589 handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,
3590 YYLTYPE loc, ir_variable *var)
3591 {
3592 unsigned num_vertices = 0;
3593
3594 if (state->gs_input_prim_type_specified) {
3595 num_vertices = vertices_per_prim(state->in_qualifier->prim_type);
3596 }
3597
3598 /* Geometry shader input variables must be arrays. Caller should have
3599 * reported an error for this.
3600 */
3601 if (!var->type->is_array()) {
3602 assert(state->error);
3603
3604 /* To avoid cascading failures, short circuit the checks below. */
3605 return;
3606 }
3607
3608 validate_layout_qualifier_vertex_count(state, loc, var, num_vertices,
3609 &state->gs_input_size,
3610 "geometry shader input");
3611 }
3612
3613 void
3614 validate_identifier(const char *identifier, YYLTYPE loc,
3615 struct _mesa_glsl_parse_state *state)
3616 {
3617 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3618 *
3619 * "Identifiers starting with "gl_" are reserved for use by
3620 * OpenGL, and may not be declared in a shader as either a
3621 * variable or a function."
3622 */
3623 if (is_gl_identifier(identifier)) {
3624 _mesa_glsl_error(&loc, state,
3625 "identifier `%s' uses reserved `gl_' prefix",
3626 identifier);
3627 } else if (strstr(identifier, "__")) {
3628 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
3629 * spec:
3630 *
3631 * "In addition, all identifiers containing two
3632 * consecutive underscores (__) are reserved as
3633 * possible future keywords."
3634 *
3635 * The intention is that names containing __ are reserved for internal
3636 * use by the implementation, and names prefixed with GL_ are reserved
3637 * for use by Khronos. Names simply containing __ are dangerous to use,
3638 * but should be allowed.
3639 *
3640 * A future version of the GLSL specification will clarify this.
3641 */
3642 _mesa_glsl_warning(&loc, state,
3643 "identifier `%s' uses reserved `__' string",
3644 identifier);
3645 }
3646 }
3647
3648 ir_rvalue *
3649 ast_declarator_list::hir(exec_list *instructions,
3650 struct _mesa_glsl_parse_state *state)
3651 {
3652 void *ctx = state;
3653 const struct glsl_type *decl_type;
3654 const char *type_name = NULL;
3655 ir_rvalue *result = NULL;
3656 YYLTYPE loc = this->get_location();
3657
3658 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
3659 *
3660 * "To ensure that a particular output variable is invariant, it is
3661 * necessary to use the invariant qualifier. It can either be used to
3662 * qualify a previously declared variable as being invariant
3663 *
3664 * invariant gl_Position; // make existing gl_Position be invariant"
3665 *
3666 * In these cases the parser will set the 'invariant' flag in the declarator
3667 * list, and the type will be NULL.
3668 */
3669 if (this->invariant) {
3670 assert(this->type == NULL);
3671
3672 if (state->current_function != NULL) {
3673 _mesa_glsl_error(& loc, state,
3674 "all uses of `invariant' keyword must be at global "
3675 "scope");
3676 }
3677
3678 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3679 assert(decl->array_specifier == NULL);
3680 assert(decl->initializer == NULL);
3681
3682 ir_variable *const earlier =
3683 state->symbols->get_variable(decl->identifier);
3684 if (earlier == NULL) {
3685 _mesa_glsl_error(& loc, state,
3686 "undeclared variable `%s' cannot be marked "
3687 "invariant", decl->identifier);
3688 } else if (!is_varying_var(earlier, state->stage)) {
3689 _mesa_glsl_error(&loc, state,
3690 "`%s' cannot be marked invariant; interfaces between "
3691 "shader stages only.", decl->identifier);
3692 } else if (earlier->data.used) {
3693 _mesa_glsl_error(& loc, state,
3694 "variable `%s' may not be redeclared "
3695 "`invariant' after being used",
3696 earlier->name);
3697 } else {
3698 earlier->data.invariant = true;
3699 }
3700 }
3701
3702 /* Invariant redeclarations do not have r-values.
3703 */
3704 return NULL;
3705 }
3706
3707 if (this->precise) {
3708 assert(this->type == NULL);
3709
3710 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3711 assert(decl->array_specifier == NULL);
3712 assert(decl->initializer == NULL);
3713
3714 ir_variable *const earlier =
3715 state->symbols->get_variable(decl->identifier);
3716 if (earlier == NULL) {
3717 _mesa_glsl_error(& loc, state,
3718 "undeclared variable `%s' cannot be marked "
3719 "precise", decl->identifier);
3720 } else if (state->current_function != NULL &&
3721 !state->symbols->name_declared_this_scope(decl->identifier)) {
3722 /* Note: we have to check if we're in a function, since
3723 * builtins are treated as having come from another scope.
3724 */
3725 _mesa_glsl_error(& loc, state,
3726 "variable `%s' from an outer scope may not be "
3727 "redeclared `precise' in this scope",
3728 earlier->name);
3729 } else if (earlier->data.used) {
3730 _mesa_glsl_error(& loc, state,
3731 "variable `%s' may not be redeclared "
3732 "`precise' after being used",
3733 earlier->name);
3734 } else {
3735 earlier->data.precise = true;
3736 }
3737 }
3738
3739 /* Precise redeclarations do not have r-values either. */
3740 return NULL;
3741 }
3742
3743 assert(this->type != NULL);
3744 assert(!this->invariant);
3745 assert(!this->precise);
3746
3747 /* The type specifier may contain a structure definition. Process that
3748 * before any of the variable declarations.
3749 */
3750 (void) this->type->specifier->hir(instructions, state);
3751
3752 decl_type = this->type->glsl_type(& type_name, state);
3753
3754 /* Section 4.3.7 "Buffer Variables" of the GLSL 4.30 spec:
3755 * "Buffer variables may only be declared inside interface blocks
3756 * (section 4.3.9 “Interface Blocks”), which are then referred to as
3757 * shader storage blocks. It is a compile-time error to declare buffer
3758 * variables at global scope (outside a block)."
3759 */
3760 if (type->qualifier.flags.q.buffer && !decl_type->is_interface()) {
3761 _mesa_glsl_error(&loc, state,
3762 "buffer variables cannot be declared outside "
3763 "interface blocks");
3764 }
3765
3766 /* An offset-qualified atomic counter declaration sets the default
3767 * offset for the next declaration within the same atomic counter
3768 * buffer.
3769 */
3770 if (decl_type && decl_type->contains_atomic()) {
3771 if (type->qualifier.flags.q.explicit_binding &&
3772 type->qualifier.flags.q.explicit_offset)
3773 state->atomic_counter_offsets[type->qualifier.binding] =
3774 type->qualifier.offset;
3775 }
3776
3777 if (this->declarations.is_empty()) {
3778 /* If there is no structure involved in the program text, there are two
3779 * possible scenarios:
3780 *
3781 * - The program text contained something like 'vec4;'. This is an
3782 * empty declaration. It is valid but weird. Emit a warning.
3783 *
3784 * - The program text contained something like 'S;' and 'S' is not the
3785 * name of a known structure type. This is both invalid and weird.
3786 * Emit an error.
3787 *
3788 * - The program text contained something like 'mediump float;'
3789 * when the programmer probably meant 'precision mediump
3790 * float;' Emit a warning with a description of what they
3791 * probably meant to do.
3792 *
3793 * Note that if decl_type is NULL and there is a structure involved,
3794 * there must have been some sort of error with the structure. In this
3795 * case we assume that an error was already generated on this line of
3796 * code for the structure. There is no need to generate an additional,
3797 * confusing error.
3798 */
3799 assert(this->type->specifier->structure == NULL || decl_type != NULL
3800 || state->error);
3801
3802 if (decl_type == NULL) {
3803 _mesa_glsl_error(&loc, state,
3804 "invalid type `%s' in empty declaration",
3805 type_name);
3806 } else if (decl_type->base_type == GLSL_TYPE_ATOMIC_UINT) {
3807 /* Empty atomic counter declarations are allowed and useful
3808 * to set the default offset qualifier.
3809 */
3810 return NULL;
3811 } else if (this->type->qualifier.precision != ast_precision_none) {
3812 if (this->type->specifier->structure != NULL) {
3813 _mesa_glsl_error(&loc, state,
3814 "precision qualifiers can't be applied "
3815 "to structures");
3816 } else {
3817 static const char *const precision_names[] = {
3818 "highp",
3819 "highp",
3820 "mediump",
3821 "lowp"
3822 };
3823
3824 _mesa_glsl_warning(&loc, state,
3825 "empty declaration with precision qualifier, "
3826 "to set the default precision, use "
3827 "`precision %s %s;'",
3828 precision_names[this->type->qualifier.precision],
3829 type_name);
3830 }
3831 } else if (this->type->specifier->structure == NULL) {
3832 _mesa_glsl_warning(&loc, state, "empty declaration");
3833 }
3834 }
3835
3836 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3837 const struct glsl_type *var_type;
3838 ir_variable *var;
3839 const char *identifier = decl->identifier;
3840 /* FINISHME: Emit a warning if a variable declaration shadows a
3841 * FINISHME: declaration at a higher scope.
3842 */
3843
3844 if ((decl_type == NULL) || decl_type->is_void()) {
3845 if (type_name != NULL) {
3846 _mesa_glsl_error(& loc, state,
3847 "invalid type `%s' in declaration of `%s'",
3848 type_name, decl->identifier);
3849 } else {
3850 _mesa_glsl_error(& loc, state,
3851 "invalid type in declaration of `%s'",
3852 decl->identifier);
3853 }
3854 continue;
3855 }
3856
3857 if (this->type->qualifier.flags.q.subroutine) {
3858 const glsl_type *t;
3859 const char *name;
3860
3861 t = state->symbols->get_type(this->type->specifier->type_name);
3862 if (!t)
3863 _mesa_glsl_error(& loc, state,
3864 "invalid type in declaration of `%s'",
3865 decl->identifier);
3866 name = ralloc_asprintf(ctx, "%s_%s", _mesa_shader_stage_to_subroutine_prefix(state->stage), decl->identifier);
3867
3868 identifier = name;
3869
3870 }
3871 var_type = process_array_type(&loc, decl_type, decl->array_specifier,
3872 state);
3873
3874 var = new(ctx) ir_variable(var_type, identifier, ir_var_auto);
3875
3876 /* The 'varying in' and 'varying out' qualifiers can only be used with
3877 * ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support
3878 * yet.
3879 */
3880 if (this->type->qualifier.flags.q.varying) {
3881 if (this->type->qualifier.flags.q.in) {
3882 _mesa_glsl_error(& loc, state,
3883 "`varying in' qualifier in declaration of "
3884 "`%s' only valid for geometry shaders using "
3885 "ARB_geometry_shader4 or EXT_geometry_shader4",
3886 decl->identifier);
3887 } else if (this->type->qualifier.flags.q.out) {
3888 _mesa_glsl_error(& loc, state,
3889 "`varying out' qualifier in declaration of "
3890 "`%s' only valid for geometry shaders using "
3891 "ARB_geometry_shader4 or EXT_geometry_shader4",
3892 decl->identifier);
3893 }
3894 }
3895
3896 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
3897 *
3898 * "Global variables can only use the qualifiers const,
3899 * attribute, uniform, or varying. Only one may be
3900 * specified.
3901 *
3902 * Local variables can only use the qualifier const."
3903 *
3904 * This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by
3905 * any extension that adds the 'layout' keyword.
3906 */
3907 if (!state->is_version(130, 300)
3908 && !state->has_explicit_attrib_location()
3909 && !state->has_separate_shader_objects()
3910 && !state->ARB_fragment_coord_conventions_enable) {
3911 if (this->type->qualifier.flags.q.out) {
3912 _mesa_glsl_error(& loc, state,
3913 "`out' qualifier in declaration of `%s' "
3914 "only valid for function parameters in %s",
3915 decl->identifier, state->get_version_string());
3916 }
3917 if (this->type->qualifier.flags.q.in) {
3918 _mesa_glsl_error(& loc, state,
3919 "`in' qualifier in declaration of `%s' "
3920 "only valid for function parameters in %s",
3921 decl->identifier, state->get_version_string());
3922 }
3923 /* FINISHME: Test for other invalid qualifiers. */
3924 }
3925
3926 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
3927 & loc, false);
3928
3929 if (this->type->qualifier.flags.q.invariant) {
3930 if (!is_varying_var(var, state->stage)) {
3931 _mesa_glsl_error(&loc, state,
3932 "`%s' cannot be marked invariant; interfaces between "
3933 "shader stages only", var->name);
3934 }
3935 }
3936
3937 if (state->current_function != NULL) {
3938 const char *mode = NULL;
3939 const char *extra = "";
3940
3941 /* There is no need to check for 'inout' here because the parser will
3942 * only allow that in function parameter lists.
3943 */
3944 if (this->type->qualifier.flags.q.attribute) {
3945 mode = "attribute";
3946 } else if (this->type->qualifier.flags.q.subroutine) {
3947 mode = "subroutine uniform";
3948 } else if (this->type->qualifier.flags.q.uniform) {
3949 mode = "uniform";
3950 } else if (this->type->qualifier.flags.q.varying) {
3951 mode = "varying";
3952 } else if (this->type->qualifier.flags.q.in) {
3953 mode = "in";
3954 extra = " or in function parameter list";
3955 } else if (this->type->qualifier.flags.q.out) {
3956 mode = "out";
3957 extra = " or in function parameter list";
3958 }
3959
3960 if (mode) {
3961 _mesa_glsl_error(& loc, state,
3962 "%s variable `%s' must be declared at "
3963 "global scope%s",
3964 mode, var->name, extra);
3965 }
3966 } else if (var->data.mode == ir_var_shader_in) {
3967 var->data.read_only = true;
3968
3969 if (state->stage == MESA_SHADER_VERTEX) {
3970 bool error_emitted = false;
3971
3972 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
3973 *
3974 * "Vertex shader inputs can only be float, floating-point
3975 * vectors, matrices, signed and unsigned integers and integer
3976 * vectors. Vertex shader inputs can also form arrays of these
3977 * types, but not structures."
3978 *
3979 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
3980 *
3981 * "Vertex shader inputs can only be float, floating-point
3982 * vectors, matrices, signed and unsigned integers and integer
3983 * vectors. They cannot be arrays or structures."
3984 *
3985 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
3986 *
3987 * "The attribute qualifier can be used only with float,
3988 * floating-point vectors, and matrices. Attribute variables
3989 * cannot be declared as arrays or structures."
3990 *
3991 * From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:
3992 *
3993 * "Vertex shader inputs can only be float, floating-point
3994 * vectors, matrices, signed and unsigned integers and integer
3995 * vectors. Vertex shader inputs cannot be arrays or
3996 * structures."
3997 */
3998 const glsl_type *check_type = var->type->without_array();
3999
4000 switch (check_type->base_type) {
4001 case GLSL_TYPE_FLOAT:
4002 break;
4003 case GLSL_TYPE_UINT:
4004 case GLSL_TYPE_INT:
4005 if (state->is_version(120, 300))
4006 break;
4007 case GLSL_TYPE_DOUBLE:
4008 if (check_type->base_type == GLSL_TYPE_DOUBLE && (state->is_version(410, 0) || state->ARB_vertex_attrib_64bit_enable))
4009 break;
4010 /* FALLTHROUGH */
4011 default:
4012 _mesa_glsl_error(& loc, state,
4013 "vertex shader input / attribute cannot have "
4014 "type %s`%s'",
4015 var->type->is_array() ? "array of " : "",
4016 check_type->name);
4017 error_emitted = true;
4018 }
4019
4020 if (!error_emitted && var->type->is_array() &&
4021 !state->check_version(150, 0, &loc,
4022 "vertex shader input / attribute "
4023 "cannot have array type")) {
4024 error_emitted = true;
4025 }
4026 } else if (state->stage == MESA_SHADER_GEOMETRY) {
4027 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
4028 *
4029 * Geometry shader input variables get the per-vertex values
4030 * written out by vertex shader output variables of the same
4031 * names. Since a geometry shader operates on a set of
4032 * vertices, each input varying variable (or input block, see
4033 * interface blocks below) needs to be declared as an array.
4034 */
4035 if (!var->type->is_array()) {
4036 _mesa_glsl_error(&loc, state,
4037 "geometry shader inputs must be arrays");
4038 }
4039
4040 handle_geometry_shader_input_decl(state, loc, var);
4041 } else if (state->stage == MESA_SHADER_FRAGMENT) {
4042 /* From section 4.3.4 (Input Variables) of the GLSL ES 3.10 spec:
4043 *
4044 * It is a compile-time error to declare a fragment shader
4045 * input with, or that contains, any of the following types:
4046 *
4047 * * A boolean type
4048 * * An opaque type
4049 * * An array of arrays
4050 * * An array of structures
4051 * * A structure containing an array
4052 * * A structure containing a structure
4053 */
4054 if (state->es_shader) {
4055 const glsl_type *check_type = var->type->without_array();
4056 if (check_type->is_boolean() ||
4057 check_type->contains_opaque()) {
4058 _mesa_glsl_error(&loc, state,
4059 "fragment shader input cannot have type %s",
4060 check_type->name);
4061 }
4062 if (var->type->is_array() &&
4063 var->type->fields.array->is_array()) {
4064 _mesa_glsl_error(&loc, state,
4065 "%s shader output "
4066 "cannot have an array of arrays",
4067 _mesa_shader_stage_to_string(state->stage));
4068 }
4069 if (var->type->is_array() &&
4070 var->type->fields.array->is_record()) {
4071 _mesa_glsl_error(&loc, state,
4072 "fragment shader input "
4073 "cannot have an array of structs");
4074 }
4075 if (var->type->is_record()) {
4076 for (unsigned i = 0; i < var->type->length; i++) {
4077 if (var->type->fields.structure[i].type->is_array() ||
4078 var->type->fields.structure[i].type->is_record())
4079 _mesa_glsl_error(&loc, state,
4080 "fragement shader input cannot have "
4081 "a struct that contains an "
4082 "array or struct");
4083 }
4084 }
4085 }
4086 } else if (state->stage == MESA_SHADER_TESS_CTRL ||
4087 state->stage == MESA_SHADER_TESS_EVAL) {
4088 handle_tess_shader_input_decl(state, loc, var);
4089 }
4090 } else if (var->data.mode == ir_var_shader_out) {
4091 const glsl_type *check_type = var->type->without_array();
4092
4093 /* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:
4094 *
4095 * It is a compile-time error to declare a vertex, tessellation
4096 * evaluation, tessellation control, or geometry shader output
4097 * that contains any of the following:
4098 *
4099 * * A Boolean type (bool, bvec2 ...)
4100 * * An opaque type
4101 */
4102 if (check_type->is_boolean() || check_type->contains_opaque())
4103 _mesa_glsl_error(&loc, state,
4104 "%s shader output cannot have type %s",
4105 _mesa_shader_stage_to_string(state->stage),
4106 check_type->name);
4107
4108 /* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:
4109 *
4110 * It is a compile-time error to declare a fragment shader output
4111 * that contains any of the following:
4112 *
4113 * * A Boolean type (bool, bvec2 ...)
4114 * * A double-precision scalar or vector (double, dvec2 ...)
4115 * * An opaque type
4116 * * Any matrix type
4117 * * A structure
4118 */
4119 if (state->stage == MESA_SHADER_FRAGMENT) {
4120 if (check_type->is_record() || check_type->is_matrix())
4121 _mesa_glsl_error(&loc, state,
4122 "fragment shader output "
4123 "cannot have struct or matrix type");
4124 switch (check_type->base_type) {
4125 case GLSL_TYPE_UINT:
4126 case GLSL_TYPE_INT:
4127 case GLSL_TYPE_FLOAT:
4128 break;
4129 default:
4130 _mesa_glsl_error(&loc, state,
4131 "fragment shader output cannot have "
4132 "type %s", check_type->name);
4133 }
4134 }
4135
4136 /* From section 4.3.6 (Output Variables) of the GLSL ES 3.10 spec:
4137 *
4138 * It is a compile-time error to declare a vertex shader output
4139 * with, or that contains, any of the following types:
4140 *
4141 * * A boolean type
4142 * * An opaque type
4143 * * An array of arrays
4144 * * An array of structures
4145 * * A structure containing an array
4146 * * A structure containing a structure
4147 *
4148 * It is a compile-time error to declare a fragment shader output
4149 * with, or that contains, any of the following types:
4150 *
4151 * * A boolean type
4152 * * An opaque type
4153 * * A matrix
4154 * * A structure
4155 * * An array of array
4156 */
4157 if (state->es_shader) {
4158 if (var->type->is_array() &&
4159 var->type->fields.array->is_array()) {
4160 _mesa_glsl_error(&loc, state,
4161 "%s shader output "
4162 "cannot have an array of arrays",
4163 _mesa_shader_stage_to_string(state->stage));
4164 }
4165 if (state->stage == MESA_SHADER_VERTEX) {
4166 if (var->type->is_array() &&
4167 var->type->fields.array->is_record()) {
4168 _mesa_glsl_error(&loc, state,
4169 "vertex shader output "
4170 "cannot have an array of structs");
4171 }
4172 if (var->type->is_record()) {
4173 for (unsigned i = 0; i < var->type->length; i++) {
4174 if (var->type->fields.structure[i].type->is_array() ||
4175 var->type->fields.structure[i].type->is_record())
4176 _mesa_glsl_error(&loc, state,
4177 "vertex shader output cannot have a "
4178 "struct that contains an "
4179 "array or struct");
4180 }
4181 }
4182 }
4183 }
4184
4185 if (state->stage == MESA_SHADER_TESS_CTRL) {
4186 handle_tess_ctrl_shader_output_decl(state, loc, var);
4187 }
4188 } else if (var->type->contains_subroutine()) {
4189 /* declare subroutine uniforms as hidden */
4190 var->data.how_declared = ir_var_hidden;
4191 }
4192
4193 /* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,
4194 * so must integer vertex outputs.
4195 *
4196 * From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:
4197 * "Fragment shader inputs that are signed or unsigned integers or
4198 * integer vectors must be qualified with the interpolation qualifier
4199 * flat."
4200 *
4201 * From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:
4202 * "Fragment shader inputs that are, or contain, signed or unsigned
4203 * integers or integer vectors must be qualified with the
4204 * interpolation qualifier flat."
4205 *
4206 * From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:
4207 * "Vertex shader outputs that are, or contain, signed or unsigned
4208 * integers or integer vectors must be qualified with the
4209 * interpolation qualifier flat."
4210 *
4211 * Note that prior to GLSL 1.50, this requirement applied to vertex
4212 * outputs rather than fragment inputs. That creates problems in the
4213 * presence of geometry shaders, so we adopt the GLSL 1.50 rule for all
4214 * desktop GL shaders. For GLSL ES shaders, we follow the spec and
4215 * apply the restriction to both vertex outputs and fragment inputs.
4216 *
4217 * Note also that the desktop GLSL specs are missing the text "or
4218 * contain"; this is presumably an oversight, since there is no
4219 * reasonable way to interpolate a fragment shader input that contains
4220 * an integer.
4221 */
4222 if (state->is_version(130, 300) &&
4223 var->type->contains_integer() &&
4224 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
4225 ((state->stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_in)
4226 || (state->stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_out
4227 && state->es_shader))) {
4228 const char *var_type = (state->stage == MESA_SHADER_VERTEX) ?
4229 "vertex output" : "fragment input";
4230 _mesa_glsl_error(&loc, state, "if a %s is (or contains) "
4231 "an integer, then it must be qualified with 'flat'",
4232 var_type);
4233 }
4234
4235 /* Double fragment inputs must be qualified with 'flat'. */
4236 if (var->type->contains_double() &&
4237 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
4238 state->stage == MESA_SHADER_FRAGMENT &&
4239 var->data.mode == ir_var_shader_in) {
4240 _mesa_glsl_error(&loc, state, "if a fragment input is (or contains) "
4241 "a double, then it must be qualified with 'flat'",
4242 var_type);
4243 }
4244
4245 /* Interpolation qualifiers cannot be applied to 'centroid' and
4246 * 'centroid varying'.
4247 *
4248 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
4249 * "interpolation qualifiers may only precede the qualifiers in,
4250 * centroid in, out, or centroid out in a declaration. They do not apply
4251 * to the deprecated storage qualifiers varying or centroid varying."
4252 *
4253 * These deprecated storage qualifiers do not exist in GLSL ES 3.00.
4254 */
4255 if (state->is_version(130, 0)
4256 && this->type->qualifier.has_interpolation()
4257 && this->type->qualifier.flags.q.varying) {
4258
4259 const char *i = this->type->qualifier.interpolation_string();
4260 assert(i != NULL);
4261 const char *s;
4262 if (this->type->qualifier.flags.q.centroid)
4263 s = "centroid varying";
4264 else
4265 s = "varying";
4266
4267 _mesa_glsl_error(&loc, state,
4268 "qualifier '%s' cannot be applied to the "
4269 "deprecated storage qualifier '%s'", i, s);
4270 }
4271
4272
4273 /* Interpolation qualifiers can only apply to vertex shader outputs and
4274 * fragment shader inputs.
4275 *
4276 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
4277 * "Outputs from a vertex shader (out) and inputs to a fragment
4278 * shader (in) can be further qualified with one or more of these
4279 * interpolation qualifiers"
4280 *
4281 * From page 31 (page 37 of the PDF) of the GLSL ES 3.00 spec:
4282 * "These interpolation qualifiers may only precede the qualifiers
4283 * in, centroid in, out, or centroid out in a declaration. They do
4284 * not apply to inputs into a vertex shader or outputs from a
4285 * fragment shader."
4286 */
4287 if (state->is_version(130, 300)
4288 && this->type->qualifier.has_interpolation()) {
4289
4290 const char *i = this->type->qualifier.interpolation_string();
4291 assert(i != NULL);
4292
4293 switch (state->stage) {
4294 case MESA_SHADER_VERTEX:
4295 if (this->type->qualifier.flags.q.in) {
4296 _mesa_glsl_error(&loc, state,
4297 "qualifier '%s' cannot be applied to vertex "
4298 "shader inputs", i);
4299 }
4300 break;
4301 case MESA_SHADER_FRAGMENT:
4302 if (this->type->qualifier.flags.q.out) {
4303 _mesa_glsl_error(&loc, state,
4304 "qualifier '%s' cannot be applied to fragment "
4305 "shader outputs", i);
4306 }
4307 break;
4308 default:
4309 break;
4310 }
4311 }
4312
4313
4314 /* From section 4.3.4 of the GLSL 4.00 spec:
4315 * "Input variables may not be declared using the patch in qualifier
4316 * in tessellation control or geometry shaders."
4317 *
4318 * From section 4.3.6 of the GLSL 4.00 spec:
4319 * "It is an error to use patch out in a vertex, tessellation
4320 * evaluation, or geometry shader."
4321 *
4322 * This doesn't explicitly forbid using them in a fragment shader, but
4323 * that's probably just an oversight.
4324 */
4325 if (state->stage != MESA_SHADER_TESS_EVAL
4326 && this->type->qualifier.flags.q.patch
4327 && this->type->qualifier.flags.q.in) {
4328
4329 _mesa_glsl_error(&loc, state, "'patch in' can only be used in a "
4330 "tessellation evaluation shader");
4331 }
4332
4333 if (state->stage != MESA_SHADER_TESS_CTRL
4334 && this->type->qualifier.flags.q.patch
4335 && this->type->qualifier.flags.q.out) {
4336
4337 _mesa_glsl_error(&loc, state, "'patch out' can only be used in a "
4338 "tessellation control shader");
4339 }
4340
4341 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
4342 */
4343 if (this->type->qualifier.precision != ast_precision_none) {
4344 state->check_precision_qualifiers_allowed(&loc);
4345 }
4346
4347
4348 /* If a precision qualifier is allowed on a type, it is allowed on
4349 * an array of that type.
4350 */
4351 if (!(this->type->qualifier.precision == ast_precision_none
4352 || precision_qualifier_allowed(var->type->without_array()))) {
4353
4354 _mesa_glsl_error(&loc, state,
4355 "precision qualifiers apply only to floating point"
4356 ", integer and opaque types");
4357 }
4358
4359 /* From section 4.1.7 of the GLSL 4.40 spec:
4360 *
4361 * "[Opaque types] can only be declared as function
4362 * parameters or uniform-qualified variables."
4363 */
4364 if (var_type->contains_opaque() &&
4365 !this->type->qualifier.flags.q.uniform) {
4366 _mesa_glsl_error(&loc, state,
4367 "opaque variables must be declared uniform");
4368 }
4369
4370 /* Process the initializer and add its instructions to a temporary
4371 * list. This list will be added to the instruction stream (below) after
4372 * the declaration is added. This is done because in some cases (such as
4373 * redeclarations) the declaration may not actually be added to the
4374 * instruction stream.
4375 */
4376 exec_list initializer_instructions;
4377
4378 /* Examine var name here since var may get deleted in the next call */
4379 bool var_is_gl_id = is_gl_identifier(var->name);
4380
4381 ir_variable *earlier =
4382 get_variable_being_redeclared(var, decl->get_location(), state,
4383 false /* allow_all_redeclarations */);
4384 if (earlier != NULL) {
4385 if (var_is_gl_id &&
4386 earlier->data.how_declared == ir_var_declared_in_block) {
4387 _mesa_glsl_error(&loc, state,
4388 "`%s' has already been redeclared using "
4389 "gl_PerVertex", earlier->name);
4390 }
4391 earlier->data.how_declared = ir_var_declared_normally;
4392 }
4393
4394 if (decl->initializer != NULL) {
4395 result = process_initializer((earlier == NULL) ? var : earlier,
4396 decl, this->type,
4397 &initializer_instructions, state);
4398 } else {
4399 validate_array_dimensions(var_type, state, &loc);
4400 }
4401
4402 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
4403 *
4404 * "It is an error to write to a const variable outside of
4405 * its declaration, so they must be initialized when
4406 * declared."
4407 */
4408 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
4409 _mesa_glsl_error(& loc, state,
4410 "const declaration of `%s' must be initialized",
4411 decl->identifier);
4412 }
4413
4414 if (state->es_shader) {
4415 const glsl_type *const t = (earlier == NULL)
4416 ? var->type : earlier->type;
4417
4418 if (t->is_unsized_array())
4419 /* Section 10.17 of the GLSL ES 1.00 specification states that
4420 * unsized array declarations have been removed from the language.
4421 * Arrays that are sized using an initializer are still explicitly
4422 * sized. However, GLSL ES 1.00 does not allow array
4423 * initializers. That is only allowed in GLSL ES 3.00.
4424 *
4425 * Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:
4426 *
4427 * "An array type can also be formed without specifying a size
4428 * if the definition includes an initializer:
4429 *
4430 * float x[] = float[2] (1.0, 2.0); // declares an array of size 2
4431 * float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 3
4432 *
4433 * float a[5];
4434 * float b[] = a;"
4435 */
4436 _mesa_glsl_error(& loc, state,
4437 "unsized array declarations are not allowed in "
4438 "GLSL ES");
4439 }
4440
4441 /* If the declaration is not a redeclaration, there are a few additional
4442 * semantic checks that must be applied. In addition, variable that was
4443 * created for the declaration should be added to the IR stream.
4444 */
4445 if (earlier == NULL) {
4446 validate_identifier(decl->identifier, loc, state);
4447
4448 /* Add the variable to the symbol table. Note that the initializer's
4449 * IR was already processed earlier (though it hasn't been emitted
4450 * yet), without the variable in scope.
4451 *
4452 * This differs from most C-like languages, but it follows the GLSL
4453 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
4454 * spec:
4455 *
4456 * "Within a declaration, the scope of a name starts immediately
4457 * after the initializer if present or immediately after the name
4458 * being declared if not."
4459 */
4460 if (!state->symbols->add_variable(var)) {
4461 YYLTYPE loc = this->get_location();
4462 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
4463 "current scope", decl->identifier);
4464 continue;
4465 }
4466
4467 /* Push the variable declaration to the top. It means that all the
4468 * variable declarations will appear in a funny last-to-first order,
4469 * but otherwise we run into trouble if a function is prototyped, a
4470 * global var is decled, then the function is defined with usage of
4471 * the global var. See glslparsertest's CorrectModule.frag.
4472 */
4473 instructions->push_head(var);
4474 }
4475
4476 instructions->append_list(&initializer_instructions);
4477 }
4478
4479
4480 /* Generally, variable declarations do not have r-values. However,
4481 * one is used for the declaration in
4482 *
4483 * while (bool b = some_condition()) {
4484 * ...
4485 * }
4486 *
4487 * so we return the rvalue from the last seen declaration here.
4488 */
4489 return result;
4490 }
4491
4492
4493 ir_rvalue *
4494 ast_parameter_declarator::hir(exec_list *instructions,
4495 struct _mesa_glsl_parse_state *state)
4496 {
4497 void *ctx = state;
4498 const struct glsl_type *type;
4499 const char *name = NULL;
4500 YYLTYPE loc = this->get_location();
4501
4502 type = this->type->glsl_type(& name, state);
4503
4504 if (type == NULL) {
4505 if (name != NULL) {
4506 _mesa_glsl_error(& loc, state,
4507 "invalid type `%s' in declaration of `%s'",
4508 name, this->identifier);
4509 } else {
4510 _mesa_glsl_error(& loc, state,
4511 "invalid type in declaration of `%s'",
4512 this->identifier);
4513 }
4514
4515 type = glsl_type::error_type;
4516 }
4517
4518 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
4519 *
4520 * "Functions that accept no input arguments need not use void in the
4521 * argument list because prototypes (or definitions) are required and
4522 * therefore there is no ambiguity when an empty argument list "( )" is
4523 * declared. The idiom "(void)" as a parameter list is provided for
4524 * convenience."
4525 *
4526 * Placing this check here prevents a void parameter being set up
4527 * for a function, which avoids tripping up checks for main taking
4528 * parameters and lookups of an unnamed symbol.
4529 */
4530 if (type->is_void()) {
4531 if (this->identifier != NULL)
4532 _mesa_glsl_error(& loc, state,
4533 "named parameter cannot have type `void'");
4534
4535 is_void = true;
4536 return NULL;
4537 }
4538
4539 if (formal_parameter && (this->identifier == NULL)) {
4540 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
4541 return NULL;
4542 }
4543
4544 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
4545 * call already handled the "vec4[..] foo" case.
4546 */
4547 type = process_array_type(&loc, type, this->array_specifier, state);
4548
4549 if (!type->is_error() && type->is_unsized_array()) {
4550 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
4551 "a declared size");
4552 type = glsl_type::error_type;
4553 }
4554
4555 is_void = false;
4556 ir_variable *var = new(ctx)
4557 ir_variable(type, this->identifier, ir_var_function_in);
4558
4559 /* Apply any specified qualifiers to the parameter declaration. Note that
4560 * for function parameters the default mode is 'in'.
4561 */
4562 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,
4563 true);
4564
4565 /* From section 4.1.7 of the GLSL 4.40 spec:
4566 *
4567 * "Opaque variables cannot be treated as l-values; hence cannot
4568 * be used as out or inout function parameters, nor can they be
4569 * assigned into."
4570 */
4571 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
4572 && type->contains_opaque()) {
4573 _mesa_glsl_error(&loc, state, "out and inout parameters cannot "
4574 "contain opaque variables");
4575 type = glsl_type::error_type;
4576 }
4577
4578 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
4579 *
4580 * "When calling a function, expressions that do not evaluate to
4581 * l-values cannot be passed to parameters declared as out or inout."
4582 *
4583 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
4584 *
4585 * "Other binary or unary expressions, non-dereferenced arrays,
4586 * function names, swizzles with repeated fields, and constants
4587 * cannot be l-values."
4588 *
4589 * So for GLSL 1.10, passing an array as an out or inout parameter is not
4590 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
4591 */
4592 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
4593 && type->is_array()
4594 && !state->check_version(120, 100, &loc,
4595 "arrays cannot be out or inout parameters")) {
4596 type = glsl_type::error_type;
4597 }
4598
4599 instructions->push_tail(var);
4600
4601 /* Parameter declarations do not have r-values.
4602 */
4603 return NULL;
4604 }
4605
4606
4607 void
4608 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
4609 bool formal,
4610 exec_list *ir_parameters,
4611 _mesa_glsl_parse_state *state)
4612 {
4613 ast_parameter_declarator *void_param = NULL;
4614 unsigned count = 0;
4615
4616 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
4617 param->formal_parameter = formal;
4618 param->hir(ir_parameters, state);
4619
4620 if (param->is_void)
4621 void_param = param;
4622
4623 count++;
4624 }
4625
4626 if ((void_param != NULL) && (count > 1)) {
4627 YYLTYPE loc = void_param->get_location();
4628
4629 _mesa_glsl_error(& loc, state,
4630 "`void' parameter must be only parameter");
4631 }
4632 }
4633
4634
4635 void
4636 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
4637 {
4638 /* IR invariants disallow function declarations or definitions
4639 * nested within other function definitions. But there is no
4640 * requirement about the relative order of function declarations
4641 * and definitions with respect to one another. So simply insert
4642 * the new ir_function block at the end of the toplevel instruction
4643 * list.
4644 */
4645 state->toplevel_ir->push_tail(f);
4646 }
4647
4648
4649 ir_rvalue *
4650 ast_function::hir(exec_list *instructions,
4651 struct _mesa_glsl_parse_state *state)
4652 {
4653 void *ctx = state;
4654 ir_function *f = NULL;
4655 ir_function_signature *sig = NULL;
4656 exec_list hir_parameters;
4657 YYLTYPE loc = this->get_location();
4658
4659 const char *const name = identifier;
4660
4661 /* New functions are always added to the top-level IR instruction stream,
4662 * so this instruction list pointer is ignored. See also emit_function
4663 * (called below).
4664 */
4665 (void) instructions;
4666
4667 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
4668 *
4669 * "Function declarations (prototypes) cannot occur inside of functions;
4670 * they must be at global scope, or for the built-in functions, outside
4671 * the global scope."
4672 *
4673 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
4674 *
4675 * "User defined functions may only be defined within the global scope."
4676 *
4677 * Note that this language does not appear in GLSL 1.10.
4678 */
4679 if ((state->current_function != NULL) &&
4680 state->is_version(120, 100)) {
4681 YYLTYPE loc = this->get_location();
4682 _mesa_glsl_error(&loc, state,
4683 "declaration of function `%s' not allowed within "
4684 "function body", name);
4685 }
4686
4687 validate_identifier(name, this->get_location(), state);
4688
4689 /* Convert the list of function parameters to HIR now so that they can be
4690 * used below to compare this function's signature with previously seen
4691 * signatures for functions with the same name.
4692 */
4693 ast_parameter_declarator::parameters_to_hir(& this->parameters,
4694 is_definition,
4695 & hir_parameters, state);
4696
4697 const char *return_type_name;
4698 const glsl_type *return_type =
4699 this->return_type->glsl_type(& return_type_name, state);
4700
4701 if (!return_type) {
4702 YYLTYPE loc = this->get_location();
4703 _mesa_glsl_error(&loc, state,
4704 "function `%s' has undeclared return type `%s'",
4705 name, return_type_name);
4706 return_type = glsl_type::error_type;
4707 }
4708
4709 /* ARB_shader_subroutine states:
4710 * "Subroutine declarations cannot be prototyped. It is an error to prepend
4711 * subroutine(...) to a function declaration."
4712 */
4713 if (this->return_type->qualifier.flags.q.subroutine_def && !is_definition) {
4714 YYLTYPE loc = this->get_location();
4715 _mesa_glsl_error(&loc, state,
4716 "function declaration `%s' cannot have subroutine prepended",
4717 name);
4718 }
4719
4720 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
4721 * "No qualifier is allowed on the return type of a function."
4722 */
4723 if (this->return_type->has_qualifiers()) {
4724 YYLTYPE loc = this->get_location();
4725 _mesa_glsl_error(& loc, state,
4726 "function `%s' return type has qualifiers", name);
4727 }
4728
4729 /* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:
4730 *
4731 * "Arrays are allowed as arguments and as the return type. In both
4732 * cases, the array must be explicitly sized."
4733 */
4734 if (return_type->is_unsized_array()) {
4735 YYLTYPE loc = this->get_location();
4736 _mesa_glsl_error(& loc, state,
4737 "function `%s' return type array must be explicitly "
4738 "sized", name);
4739 }
4740
4741 /* From section 4.1.7 of the GLSL 4.40 spec:
4742 *
4743 * "[Opaque types] can only be declared as function parameters
4744 * or uniform-qualified variables."
4745 */
4746 if (return_type->contains_opaque()) {
4747 YYLTYPE loc = this->get_location();
4748 _mesa_glsl_error(&loc, state,
4749 "function `%s' return type can't contain an opaque type",
4750 name);
4751 }
4752
4753 /* Create an ir_function if one doesn't already exist. */
4754 f = state->symbols->get_function(name);
4755 if (f == NULL) {
4756 f = new(ctx) ir_function(name);
4757 if (!this->return_type->qualifier.flags.q.subroutine) {
4758 if (!state->symbols->add_function(f)) {
4759 /* This function name shadows a non-function use of the same name. */
4760 YYLTYPE loc = this->get_location();
4761 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
4762 "non-function", name);
4763 return NULL;
4764 }
4765 }
4766 emit_function(state, f);
4767 }
4768
4769 /* From GLSL ES 3.0 spec, chapter 6.1 "Function Definitions", page 71:
4770 *
4771 * "A shader cannot redefine or overload built-in functions."
4772 *
4773 * While in GLSL ES 1.0 specification, chapter 8 "Built-in Functions":
4774 *
4775 * "User code can overload the built-in functions but cannot redefine
4776 * them."
4777 */
4778 if (state->es_shader && state->language_version >= 300) {
4779 /* Local shader has no exact candidates; check the built-ins. */
4780 _mesa_glsl_initialize_builtin_functions();
4781 if (_mesa_glsl_find_builtin_function_by_name(name)) {
4782 YYLTYPE loc = this->get_location();
4783 _mesa_glsl_error(& loc, state,
4784 "A shader cannot redefine or overload built-in "
4785 "function `%s' in GLSL ES 3.00", name);
4786 return NULL;
4787 }
4788 }
4789
4790 /* Verify that this function's signature either doesn't match a previously
4791 * seen signature for a function with the same name, or, if a match is found,
4792 * that the previously seen signature does not have an associated definition.
4793 */
4794 if (state->es_shader || f->has_user_signature()) {
4795 sig = f->exact_matching_signature(state, &hir_parameters);
4796 if (sig != NULL) {
4797 const char *badvar = sig->qualifiers_match(&hir_parameters);
4798 if (badvar != NULL) {
4799 YYLTYPE loc = this->get_location();
4800
4801 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
4802 "qualifiers don't match prototype", name, badvar);
4803 }
4804
4805 if (sig->return_type != return_type) {
4806 YYLTYPE loc = this->get_location();
4807
4808 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
4809 "match prototype", name);
4810 }
4811
4812 if (sig->is_defined) {
4813 if (is_definition) {
4814 YYLTYPE loc = this->get_location();
4815 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
4816 } else {
4817 /* We just encountered a prototype that exactly matches a
4818 * function that's already been defined. This is redundant,
4819 * and we should ignore it.
4820 */
4821 return NULL;
4822 }
4823 }
4824 }
4825 }
4826
4827 /* Verify the return type of main() */
4828 if (strcmp(name, "main") == 0) {
4829 if (! return_type->is_void()) {
4830 YYLTYPE loc = this->get_location();
4831
4832 _mesa_glsl_error(& loc, state, "main() must return void");
4833 }
4834
4835 if (!hir_parameters.is_empty()) {
4836 YYLTYPE loc = this->get_location();
4837
4838 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
4839 }
4840 }
4841
4842 /* Finish storing the information about this new function in its signature.
4843 */
4844 if (sig == NULL) {
4845 sig = new(ctx) ir_function_signature(return_type);
4846 f->add_signature(sig);
4847 }
4848
4849 sig->replace_parameters(&hir_parameters);
4850 signature = sig;
4851
4852 if (this->return_type->qualifier.flags.q.subroutine_def) {
4853 int idx;
4854
4855 f->num_subroutine_types = this->return_type->qualifier.subroutine_list->declarations.length();
4856 f->subroutine_types = ralloc_array(state, const struct glsl_type *,
4857 f->num_subroutine_types);
4858 idx = 0;
4859 foreach_list_typed(ast_declaration, decl, link, &this->return_type->qualifier.subroutine_list->declarations) {
4860 const struct glsl_type *type;
4861 /* the subroutine type must be already declared */
4862 type = state->symbols->get_type(decl->identifier);
4863 if (!type) {
4864 _mesa_glsl_error(& loc, state, "unknown type '%s' in subroutine function definition", decl->identifier);
4865 }
4866 f->subroutine_types[idx++] = type;
4867 }
4868 state->subroutines = (ir_function **)reralloc(state, state->subroutines,
4869 ir_function *,
4870 state->num_subroutines + 1);
4871 state->subroutines[state->num_subroutines] = f;
4872 state->num_subroutines++;
4873
4874 }
4875
4876 if (this->return_type->qualifier.flags.q.subroutine) {
4877 if (!state->symbols->add_type(this->identifier, glsl_type::get_subroutine_instance(this->identifier))) {
4878 _mesa_glsl_error(& loc, state, "type '%s' previously defined", this->identifier);
4879 return NULL;
4880 }
4881 state->subroutine_types = (ir_function **)reralloc(state, state->subroutine_types,
4882 ir_function *,
4883 state->num_subroutine_types + 1);
4884 state->subroutine_types[state->num_subroutine_types] = f;
4885 state->num_subroutine_types++;
4886
4887 f->is_subroutine = true;
4888 }
4889
4890 /* Function declarations (prototypes) do not have r-values.
4891 */
4892 return NULL;
4893 }
4894
4895
4896 ir_rvalue *
4897 ast_function_definition::hir(exec_list *instructions,
4898 struct _mesa_glsl_parse_state *state)
4899 {
4900 prototype->is_definition = true;
4901 prototype->hir(instructions, state);
4902
4903 ir_function_signature *signature = prototype->signature;
4904 if (signature == NULL)
4905 return NULL;
4906
4907 assert(state->current_function == NULL);
4908 state->current_function = signature;
4909 state->found_return = false;
4910
4911 /* Duplicate parameters declared in the prototype as concrete variables.
4912 * Add these to the symbol table.
4913 */
4914 state->symbols->push_scope();
4915 foreach_in_list(ir_variable, var, &signature->parameters) {
4916 assert(var->as_variable() != NULL);
4917
4918 /* The only way a parameter would "exist" is if two parameters have
4919 * the same name.
4920 */
4921 if (state->symbols->name_declared_this_scope(var->name)) {
4922 YYLTYPE loc = this->get_location();
4923
4924 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
4925 } else {
4926 state->symbols->add_variable(var);
4927 }
4928 }
4929
4930 /* Convert the body of the function to HIR. */
4931 this->body->hir(&signature->body, state);
4932 signature->is_defined = true;
4933
4934 state->symbols->pop_scope();
4935
4936 assert(state->current_function == signature);
4937 state->current_function = NULL;
4938
4939 if (!signature->return_type->is_void() && !state->found_return) {
4940 YYLTYPE loc = this->get_location();
4941 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
4942 "%s, but no return statement",
4943 signature->function_name(),
4944 signature->return_type->name);
4945 }
4946
4947 /* Function definitions do not have r-values.
4948 */
4949 return NULL;
4950 }
4951
4952
4953 ir_rvalue *
4954 ast_jump_statement::hir(exec_list *instructions,
4955 struct _mesa_glsl_parse_state *state)
4956 {
4957 void *ctx = state;
4958
4959 switch (mode) {
4960 case ast_return: {
4961 ir_return *inst;
4962 assert(state->current_function);
4963
4964 if (opt_return_value) {
4965 ir_rvalue *ret = opt_return_value->hir(instructions, state);
4966
4967 /* The value of the return type can be NULL if the shader says
4968 * 'return foo();' and foo() is a function that returns void.
4969 *
4970 * NOTE: The GLSL spec doesn't say that this is an error. The type
4971 * of the return value is void. If the return type of the function is
4972 * also void, then this should compile without error. Seriously.
4973 */
4974 const glsl_type *const ret_type =
4975 (ret == NULL) ? glsl_type::void_type : ret->type;
4976
4977 /* Implicit conversions are not allowed for return values prior to
4978 * ARB_shading_language_420pack.
4979 */
4980 if (state->current_function->return_type != ret_type) {
4981 YYLTYPE loc = this->get_location();
4982
4983 if (state->ARB_shading_language_420pack_enable) {
4984 if (!apply_implicit_conversion(state->current_function->return_type,
4985 ret, state)) {
4986 _mesa_glsl_error(& loc, state,
4987 "could not implicitly convert return value "
4988 "to %s, in function `%s'",
4989 state->current_function->return_type->name,
4990 state->current_function->function_name());
4991 }
4992 } else {
4993 _mesa_glsl_error(& loc, state,
4994 "`return' with wrong type %s, in function `%s' "
4995 "returning %s",
4996 ret_type->name,
4997 state->current_function->function_name(),
4998 state->current_function->return_type->name);
4999 }
5000 } else if (state->current_function->return_type->base_type ==
5001 GLSL_TYPE_VOID) {
5002 YYLTYPE loc = this->get_location();
5003
5004 /* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.20
5005 * specs add a clarification:
5006 *
5007 * "A void function can only use return without a return argument, even if
5008 * the return argument has void type. Return statements only accept values:
5009 *
5010 * void func1() { }
5011 * void func2() { return func1(); } // illegal return statement"
5012 */
5013 _mesa_glsl_error(& loc, state,
5014 "void functions can only use `return' without a "
5015 "return argument");
5016 }
5017
5018 inst = new(ctx) ir_return(ret);
5019 } else {
5020 if (state->current_function->return_type->base_type !=
5021 GLSL_TYPE_VOID) {
5022 YYLTYPE loc = this->get_location();
5023
5024 _mesa_glsl_error(& loc, state,
5025 "`return' with no value, in function %s returning "
5026 "non-void",
5027 state->current_function->function_name());
5028 }
5029 inst = new(ctx) ir_return;
5030 }
5031
5032 state->found_return = true;
5033 instructions->push_tail(inst);
5034 break;
5035 }
5036
5037 case ast_discard:
5038 if (state->stage != MESA_SHADER_FRAGMENT) {
5039 YYLTYPE loc = this->get_location();
5040
5041 _mesa_glsl_error(& loc, state,
5042 "`discard' may only appear in a fragment shader");
5043 }
5044 instructions->push_tail(new(ctx) ir_discard);
5045 break;
5046
5047 case ast_break:
5048 case ast_continue:
5049 if (mode == ast_continue &&
5050 state->loop_nesting_ast == NULL) {
5051 YYLTYPE loc = this->get_location();
5052
5053 _mesa_glsl_error(& loc, state, "continue may only appear in a loop");
5054 } else if (mode == ast_break &&
5055 state->loop_nesting_ast == NULL &&
5056 state->switch_state.switch_nesting_ast == NULL) {
5057 YYLTYPE loc = this->get_location();
5058
5059 _mesa_glsl_error(& loc, state,
5060 "break may only appear in a loop or a switch");
5061 } else {
5062 /* For a loop, inline the for loop expression again, since we don't
5063 * know where near the end of the loop body the normal copy of it is
5064 * going to be placed. Same goes for the condition for a do-while
5065 * loop.
5066 */
5067 if (state->loop_nesting_ast != NULL &&
5068 mode == ast_continue && !state->switch_state.is_switch_innermost) {
5069 if (state->loop_nesting_ast->rest_expression) {
5070 state->loop_nesting_ast->rest_expression->hir(instructions,
5071 state);
5072 }
5073 if (state->loop_nesting_ast->mode ==
5074 ast_iteration_statement::ast_do_while) {
5075 state->loop_nesting_ast->condition_to_hir(instructions, state);
5076 }
5077 }
5078
5079 if (state->switch_state.is_switch_innermost &&
5080 mode == ast_continue) {
5081 /* Set 'continue_inside' to true. */
5082 ir_rvalue *const true_val = new (ctx) ir_constant(true);
5083 ir_dereference_variable *deref_continue_inside_var =
5084 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
5085 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
5086 true_val));
5087
5088 /* Break out from the switch, continue for the loop will
5089 * be called right after switch. */
5090 ir_loop_jump *const jump =
5091 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
5092 instructions->push_tail(jump);
5093
5094 } else if (state->switch_state.is_switch_innermost &&
5095 mode == ast_break) {
5096 /* Force break out of switch by inserting a break. */
5097 ir_loop_jump *const jump =
5098 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
5099 instructions->push_tail(jump);
5100 } else {
5101 ir_loop_jump *const jump =
5102 new(ctx) ir_loop_jump((mode == ast_break)
5103 ? ir_loop_jump::jump_break
5104 : ir_loop_jump::jump_continue);
5105 instructions->push_tail(jump);
5106 }
5107 }
5108
5109 break;
5110 }
5111
5112 /* Jump instructions do not have r-values.
5113 */
5114 return NULL;
5115 }
5116
5117
5118 ir_rvalue *
5119 ast_selection_statement::hir(exec_list *instructions,
5120 struct _mesa_glsl_parse_state *state)
5121 {
5122 void *ctx = state;
5123
5124 ir_rvalue *const condition = this->condition->hir(instructions, state);
5125
5126 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
5127 *
5128 * "Any expression whose type evaluates to a Boolean can be used as the
5129 * conditional expression bool-expression. Vector types are not accepted
5130 * as the expression to if."
5131 *
5132 * The checks are separated so that higher quality diagnostics can be
5133 * generated for cases where both rules are violated.
5134 */
5135 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
5136 YYLTYPE loc = this->condition->get_location();
5137
5138 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
5139 "boolean");
5140 }
5141
5142 ir_if *const stmt = new(ctx) ir_if(condition);
5143
5144 if (then_statement != NULL) {
5145 state->symbols->push_scope();
5146 then_statement->hir(& stmt->then_instructions, state);
5147 state->symbols->pop_scope();
5148 }
5149
5150 if (else_statement != NULL) {
5151 state->symbols->push_scope();
5152 else_statement->hir(& stmt->else_instructions, state);
5153 state->symbols->pop_scope();
5154 }
5155
5156 instructions->push_tail(stmt);
5157
5158 /* if-statements do not have r-values.
5159 */
5160 return NULL;
5161 }
5162
5163
5164 ir_rvalue *
5165 ast_switch_statement::hir(exec_list *instructions,
5166 struct _mesa_glsl_parse_state *state)
5167 {
5168 void *ctx = state;
5169
5170 ir_rvalue *const test_expression =
5171 this->test_expression->hir(instructions, state);
5172
5173 /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
5174 *
5175 * "The type of init-expression in a switch statement must be a
5176 * scalar integer."
5177 */
5178 if (!test_expression->type->is_scalar() ||
5179 !test_expression->type->is_integer()) {
5180 YYLTYPE loc = this->test_expression->get_location();
5181
5182 _mesa_glsl_error(& loc,
5183 state,
5184 "switch-statement expression must be scalar "
5185 "integer");
5186 }
5187
5188 /* Track the switch-statement nesting in a stack-like manner.
5189 */
5190 struct glsl_switch_state saved = state->switch_state;
5191
5192 state->switch_state.is_switch_innermost = true;
5193 state->switch_state.switch_nesting_ast = this;
5194 state->switch_state.labels_ht = hash_table_ctor(0, hash_table_pointer_hash,
5195 hash_table_pointer_compare);
5196 state->switch_state.previous_default = NULL;
5197
5198 /* Initalize is_fallthru state to false.
5199 */
5200 ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
5201 state->switch_state.is_fallthru_var =
5202 new(ctx) ir_variable(glsl_type::bool_type,
5203 "switch_is_fallthru_tmp",
5204 ir_var_temporary);
5205 instructions->push_tail(state->switch_state.is_fallthru_var);
5206
5207 ir_dereference_variable *deref_is_fallthru_var =
5208 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
5209 instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
5210 is_fallthru_val));
5211
5212 /* Initialize continue_inside state to false.
5213 */
5214 state->switch_state.continue_inside =
5215 new(ctx) ir_variable(glsl_type::bool_type,
5216 "continue_inside_tmp",
5217 ir_var_temporary);
5218 instructions->push_tail(state->switch_state.continue_inside);
5219
5220 ir_rvalue *const false_val = new (ctx) ir_constant(false);
5221 ir_dereference_variable *deref_continue_inside_var =
5222 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
5223 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
5224 false_val));
5225
5226 state->switch_state.run_default =
5227 new(ctx) ir_variable(glsl_type::bool_type,
5228 "run_default_tmp",
5229 ir_var_temporary);
5230 instructions->push_tail(state->switch_state.run_default);
5231
5232 /* Loop around the switch is used for flow control. */
5233 ir_loop * loop = new(ctx) ir_loop();
5234 instructions->push_tail(loop);
5235
5236 /* Cache test expression.
5237 */
5238 test_to_hir(&loop->body_instructions, state);
5239
5240 /* Emit code for body of switch stmt.
5241 */
5242 body->hir(&loop->body_instructions, state);
5243
5244 /* Insert a break at the end to exit loop. */
5245 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
5246 loop->body_instructions.push_tail(jump);
5247
5248 /* If we are inside loop, check if continue got called inside switch. */
5249 if (state->loop_nesting_ast != NULL) {
5250 ir_dereference_variable *deref_continue_inside =
5251 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
5252 ir_if *irif = new(ctx) ir_if(deref_continue_inside);
5253 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_continue);
5254
5255 if (state->loop_nesting_ast != NULL) {
5256 if (state->loop_nesting_ast->rest_expression) {
5257 state->loop_nesting_ast->rest_expression->hir(&irif->then_instructions,
5258 state);
5259 }
5260 if (state->loop_nesting_ast->mode ==
5261 ast_iteration_statement::ast_do_while) {
5262 state->loop_nesting_ast->condition_to_hir(&irif->then_instructions, state);
5263 }
5264 }
5265 irif->then_instructions.push_tail(jump);
5266 instructions->push_tail(irif);
5267 }
5268
5269 hash_table_dtor(state->switch_state.labels_ht);
5270
5271 state->switch_state = saved;
5272
5273 /* Switch statements do not have r-values. */
5274 return NULL;
5275 }
5276
5277
5278 void
5279 ast_switch_statement::test_to_hir(exec_list *instructions,
5280 struct _mesa_glsl_parse_state *state)
5281 {
5282 void *ctx = state;
5283
5284 /* Cache value of test expression. */
5285 ir_rvalue *const test_val =
5286 test_expression->hir(instructions,
5287 state);
5288
5289 state->switch_state.test_var = new(ctx) ir_variable(test_val->type,
5290 "switch_test_tmp",
5291 ir_var_temporary);
5292 ir_dereference_variable *deref_test_var =
5293 new(ctx) ir_dereference_variable(state->switch_state.test_var);
5294
5295 instructions->push_tail(state->switch_state.test_var);
5296 instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));
5297 }
5298
5299
5300 ir_rvalue *
5301 ast_switch_body::hir(exec_list *instructions,
5302 struct _mesa_glsl_parse_state *state)
5303 {
5304 if (stmts != NULL)
5305 stmts->hir(instructions, state);
5306
5307 /* Switch bodies do not have r-values. */
5308 return NULL;
5309 }
5310
5311 ir_rvalue *
5312 ast_case_statement_list::hir(exec_list *instructions,
5313 struct _mesa_glsl_parse_state *state)
5314 {
5315 exec_list default_case, after_default, tmp;
5316
5317 foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases) {
5318 case_stmt->hir(&tmp, state);
5319
5320 /* Default case. */
5321 if (state->switch_state.previous_default && default_case.is_empty()) {
5322 default_case.append_list(&tmp);
5323 continue;
5324 }
5325
5326 /* If default case found, append 'after_default' list. */
5327 if (!default_case.is_empty())
5328 after_default.append_list(&tmp);
5329 else
5330 instructions->append_list(&tmp);
5331 }
5332
5333 /* Handle the default case. This is done here because default might not be
5334 * the last case. We need to add checks against following cases first to see
5335 * if default should be chosen or not.
5336 */
5337 if (!default_case.is_empty()) {
5338
5339 ir_rvalue *const true_val = new (state) ir_constant(true);
5340 ir_dereference_variable *deref_run_default_var =
5341 new(state) ir_dereference_variable(state->switch_state.run_default);
5342
5343 /* Choose to run default case initially, following conditional
5344 * assignments might change this.
5345 */
5346 ir_assignment *const init_var =
5347 new(state) ir_assignment(deref_run_default_var, true_val);
5348 instructions->push_tail(init_var);
5349
5350 /* Default case was the last one, no checks required. */
5351 if (after_default.is_empty()) {
5352 instructions->append_list(&default_case);
5353 return NULL;
5354 }
5355
5356 foreach_in_list(ir_instruction, ir, &after_default) {
5357 ir_assignment *assign = ir->as_assignment();
5358
5359 if (!assign)
5360 continue;
5361
5362 /* Clone the check between case label and init expression. */
5363 ir_expression *exp = (ir_expression*) assign->condition;
5364 ir_expression *clone = exp->clone(state, NULL);
5365
5366 ir_dereference_variable *deref_var =
5367 new(state) ir_dereference_variable(state->switch_state.run_default);
5368 ir_rvalue *const false_val = new (state) ir_constant(false);
5369
5370 ir_assignment *const set_false =
5371 new(state) ir_assignment(deref_var, false_val, clone);
5372
5373 instructions->push_tail(set_false);
5374 }
5375
5376 /* Append default case and all cases after it. */
5377 instructions->append_list(&default_case);
5378 instructions->append_list(&after_default);
5379 }
5380
5381 /* Case statements do not have r-values. */
5382 return NULL;
5383 }
5384
5385 ir_rvalue *
5386 ast_case_statement::hir(exec_list *instructions,
5387 struct _mesa_glsl_parse_state *state)
5388 {
5389 labels->hir(instructions, state);
5390
5391 /* Guard case statements depending on fallthru state. */
5392 ir_dereference_variable *const deref_fallthru_guard =
5393 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
5394 ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
5395
5396 foreach_list_typed (ast_node, stmt, link, & this->stmts)
5397 stmt->hir(& test_fallthru->then_instructions, state);
5398
5399 instructions->push_tail(test_fallthru);
5400
5401 /* Case statements do not have r-values. */
5402 return NULL;
5403 }
5404
5405
5406 ir_rvalue *
5407 ast_case_label_list::hir(exec_list *instructions,
5408 struct _mesa_glsl_parse_state *state)
5409 {
5410 foreach_list_typed (ast_case_label, label, link, & this->labels)
5411 label->hir(instructions, state);
5412
5413 /* Case labels do not have r-values. */
5414 return NULL;
5415 }
5416
5417 ir_rvalue *
5418 ast_case_label::hir(exec_list *instructions,
5419 struct _mesa_glsl_parse_state *state)
5420 {
5421 void *ctx = state;
5422
5423 ir_dereference_variable *deref_fallthru_var =
5424 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
5425
5426 ir_rvalue *const true_val = new(ctx) ir_constant(true);
5427
5428 /* If not default case, ... */
5429 if (this->test_value != NULL) {
5430 /* Conditionally set fallthru state based on
5431 * comparison of cached test expression value to case label.
5432 */
5433 ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
5434 ir_constant *label_const = label_rval->constant_expression_value();
5435
5436 if (!label_const) {
5437 YYLTYPE loc = this->test_value->get_location();
5438
5439 _mesa_glsl_error(& loc, state,
5440 "switch statement case label must be a "
5441 "constant expression");
5442
5443 /* Stuff a dummy value in to allow processing to continue. */
5444 label_const = new(ctx) ir_constant(0);
5445 } else {
5446 ast_expression *previous_label = (ast_expression *)
5447 hash_table_find(state->switch_state.labels_ht,
5448 (void *)(uintptr_t)label_const->value.u[0]);
5449
5450 if (previous_label) {
5451 YYLTYPE loc = this->test_value->get_location();
5452 _mesa_glsl_error(& loc, state, "duplicate case value");
5453
5454 loc = previous_label->get_location();
5455 _mesa_glsl_error(& loc, state, "this is the previous case label");
5456 } else {
5457 hash_table_insert(state->switch_state.labels_ht,
5458 this->test_value,
5459 (void *)(uintptr_t)label_const->value.u[0]);
5460 }
5461 }
5462
5463 ir_dereference_variable *deref_test_var =
5464 new(ctx) ir_dereference_variable(state->switch_state.test_var);
5465
5466 ir_expression *test_cond = new(ctx) ir_expression(ir_binop_all_equal,
5467 label_const,
5468 deref_test_var);
5469
5470 /*
5471 * From GLSL 4.40 specification section 6.2 ("Selection"):
5472 *
5473 * "The type of the init-expression value in a switch statement must
5474 * be a scalar int or uint. The type of the constant-expression value
5475 * in a case label also must be a scalar int or uint. When any pair
5476 * of these values is tested for "equal value" and the types do not
5477 * match, an implicit conversion will be done to convert the int to a
5478 * uint (see section 4.1.10 “Implicit Conversions”) before the compare
5479 * is done."
5480 */
5481 if (label_const->type != state->switch_state.test_var->type) {
5482 YYLTYPE loc = this->test_value->get_location();
5483
5484 const glsl_type *type_a = label_const->type;
5485 const glsl_type *type_b = state->switch_state.test_var->type;
5486
5487 /* Check if int->uint implicit conversion is supported. */
5488 bool integer_conversion_supported =
5489 glsl_type::int_type->can_implicitly_convert_to(glsl_type::uint_type,
5490 state);
5491
5492 if ((!type_a->is_integer() || !type_b->is_integer()) ||
5493 !integer_conversion_supported) {
5494 _mesa_glsl_error(&loc, state, "type mismatch with switch "
5495 "init-expression and case label (%s != %s)",
5496 type_a->name, type_b->name);
5497 } else {
5498 /* Conversion of the case label. */
5499 if (type_a->base_type == GLSL_TYPE_INT) {
5500 if (!apply_implicit_conversion(glsl_type::uint_type,
5501 test_cond->operands[0], state))
5502 _mesa_glsl_error(&loc, state, "implicit type conversion error");
5503 } else {
5504 /* Conversion of the init-expression value. */
5505 if (!apply_implicit_conversion(glsl_type::uint_type,
5506 test_cond->operands[1], state))
5507 _mesa_glsl_error(&loc, state, "implicit type conversion error");
5508 }
5509 }
5510 }
5511
5512 ir_assignment *set_fallthru_on_test =
5513 new(ctx) ir_assignment(deref_fallthru_var, true_val, test_cond);
5514
5515 instructions->push_tail(set_fallthru_on_test);
5516 } else { /* default case */
5517 if (state->switch_state.previous_default) {
5518 YYLTYPE loc = this->get_location();
5519 _mesa_glsl_error(& loc, state,
5520 "multiple default labels in one switch");
5521
5522 loc = state->switch_state.previous_default->get_location();
5523 _mesa_glsl_error(& loc, state, "this is the first default label");
5524 }
5525 state->switch_state.previous_default = this;
5526
5527 /* Set fallthru condition on 'run_default' bool. */
5528 ir_dereference_variable *deref_run_default =
5529 new(ctx) ir_dereference_variable(state->switch_state.run_default);
5530 ir_rvalue *const cond_true = new(ctx) ir_constant(true);
5531 ir_expression *test_cond = new(ctx) ir_expression(ir_binop_all_equal,
5532 cond_true,
5533 deref_run_default);
5534
5535 /* Set falltrhu state. */
5536 ir_assignment *set_fallthru =
5537 new(ctx) ir_assignment(deref_fallthru_var, true_val, test_cond);
5538
5539 instructions->push_tail(set_fallthru);
5540 }
5541
5542 /* Case statements do not have r-values. */
5543 return NULL;
5544 }
5545
5546 void
5547 ast_iteration_statement::condition_to_hir(exec_list *instructions,
5548 struct _mesa_glsl_parse_state *state)
5549 {
5550 void *ctx = state;
5551
5552 if (condition != NULL) {
5553 ir_rvalue *const cond =
5554 condition->hir(instructions, state);
5555
5556 if ((cond == NULL)
5557 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
5558 YYLTYPE loc = condition->get_location();
5559
5560 _mesa_glsl_error(& loc, state,
5561 "loop condition must be scalar boolean");
5562 } else {
5563 /* As the first code in the loop body, generate a block that looks
5564 * like 'if (!condition) break;' as the loop termination condition.
5565 */
5566 ir_rvalue *const not_cond =
5567 new(ctx) ir_expression(ir_unop_logic_not, cond);
5568
5569 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
5570
5571 ir_jump *const break_stmt =
5572 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
5573
5574 if_stmt->then_instructions.push_tail(break_stmt);
5575 instructions->push_tail(if_stmt);
5576 }
5577 }
5578 }
5579
5580
5581 ir_rvalue *
5582 ast_iteration_statement::hir(exec_list *instructions,
5583 struct _mesa_glsl_parse_state *state)
5584 {
5585 void *ctx = state;
5586
5587 /* For-loops and while-loops start a new scope, but do-while loops do not.
5588 */
5589 if (mode != ast_do_while)
5590 state->symbols->push_scope();
5591
5592 if (init_statement != NULL)
5593 init_statement->hir(instructions, state);
5594
5595 ir_loop *const stmt = new(ctx) ir_loop();
5596 instructions->push_tail(stmt);
5597
5598 /* Track the current loop nesting. */
5599 ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
5600
5601 state->loop_nesting_ast = this;
5602
5603 /* Likewise, indicate that following code is closest to a loop,
5604 * NOT closest to a switch.
5605 */
5606 bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
5607 state->switch_state.is_switch_innermost = false;
5608
5609 if (mode != ast_do_while)
5610 condition_to_hir(&stmt->body_instructions, state);
5611
5612 if (body != NULL)
5613 body->hir(& stmt->body_instructions, state);
5614
5615 if (rest_expression != NULL)
5616 rest_expression->hir(& stmt->body_instructions, state);
5617
5618 if (mode == ast_do_while)
5619 condition_to_hir(&stmt->body_instructions, state);
5620
5621 if (mode != ast_do_while)
5622 state->symbols->pop_scope();
5623
5624 /* Restore previous nesting before returning. */
5625 state->loop_nesting_ast = nesting_ast;
5626 state->switch_state.is_switch_innermost = saved_is_switch_innermost;
5627
5628 /* Loops do not have r-values.
5629 */
5630 return NULL;
5631 }
5632
5633
5634 /**
5635 * Determine if the given type is valid for establishing a default precision
5636 * qualifier.
5637 *
5638 * From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):
5639 *
5640 * "The precision statement
5641 *
5642 * precision precision-qualifier type;
5643 *
5644 * can be used to establish a default precision qualifier. The type field
5645 * can be either int or float or any of the sampler types, and the
5646 * precision-qualifier can be lowp, mediump, or highp."
5647 *
5648 * GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision
5649 * qualifiers on sampler types, but this seems like an oversight (since the
5650 * intention of including these in GLSL 1.30 is to allow compatibility with ES
5651 * shaders). So we allow int, float, and all sampler types regardless of GLSL
5652 * version.
5653 */
5654 static bool
5655 is_valid_default_precision_type(const struct glsl_type *const type)
5656 {
5657 if (type == NULL)
5658 return false;
5659
5660 switch (type->base_type) {
5661 case GLSL_TYPE_INT:
5662 case GLSL_TYPE_FLOAT:
5663 /* "int" and "float" are valid, but vectors and matrices are not. */
5664 return type->vector_elements == 1 && type->matrix_columns == 1;
5665 case GLSL_TYPE_SAMPLER:
5666 case GLSL_TYPE_IMAGE:
5667 case GLSL_TYPE_ATOMIC_UINT:
5668 return true;
5669 default:
5670 return false;
5671 }
5672 }
5673
5674
5675 ir_rvalue *
5676 ast_type_specifier::hir(exec_list *instructions,
5677 struct _mesa_glsl_parse_state *state)
5678 {
5679 if (this->default_precision == ast_precision_none && this->structure == NULL)
5680 return NULL;
5681
5682 YYLTYPE loc = this->get_location();
5683
5684 /* If this is a precision statement, check that the type to which it is
5685 * applied is either float or int.
5686 *
5687 * From section 4.5.3 of the GLSL 1.30 spec:
5688 * "The precision statement
5689 * precision precision-qualifier type;
5690 * can be used to establish a default precision qualifier. The type
5691 * field can be either int or float [...]. Any other types or
5692 * qualifiers will result in an error.
5693 */
5694 if (this->default_precision != ast_precision_none) {
5695 if (!state->check_precision_qualifiers_allowed(&loc))
5696 return NULL;
5697
5698 if (this->structure != NULL) {
5699 _mesa_glsl_error(&loc, state,
5700 "precision qualifiers do not apply to structures");
5701 return NULL;
5702 }
5703
5704 if (this->array_specifier != NULL) {
5705 _mesa_glsl_error(&loc, state,
5706 "default precision statements do not apply to "
5707 "arrays");
5708 return NULL;
5709 }
5710
5711 const struct glsl_type *const type =
5712 state->symbols->get_type(this->type_name);
5713 if (!is_valid_default_precision_type(type)) {
5714 _mesa_glsl_error(&loc, state,
5715 "default precision statements apply only to "
5716 "float, int, and opaque types");
5717 return NULL;
5718 }
5719
5720 if (state->es_shader) {
5721 /* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.00
5722 * spec says:
5723 *
5724 * "Non-precision qualified declarations will use the precision
5725 * qualifier specified in the most recent precision statement
5726 * that is still in scope. The precision statement has the same
5727 * scoping rules as variable declarations. If it is declared
5728 * inside a compound statement, its effect stops at the end of
5729 * the innermost statement it was declared in. Precision
5730 * statements in nested scopes override precision statements in
5731 * outer scopes. Multiple precision statements for the same basic
5732 * type can appear inside the same scope, with later statements
5733 * overriding earlier statements within that scope."
5734 *
5735 * Default precision specifications follow the same scope rules as
5736 * variables. So, we can track the state of the default precision
5737 * qualifiers in the symbol table, and the rules will just work. This
5738 * is a slight abuse of the symbol table, but it has the semantics
5739 * that we want.
5740 */
5741 state->symbols->add_default_precision_qualifier(this->type_name,
5742 this->default_precision);
5743 }
5744
5745 /* FINISHME: Translate precision statements into IR. */
5746 return NULL;
5747 }
5748
5749 /* _mesa_ast_set_aggregate_type() sets the <structure> field so that
5750 * process_record_constructor() can do type-checking on C-style initializer
5751 * expressions of structs, but ast_struct_specifier should only be translated
5752 * to HIR if it is declaring the type of a structure.
5753 *
5754 * The ->is_declaration field is false for initializers of variables
5755 * declared separately from the struct's type definition.
5756 *
5757 * struct S { ... }; (is_declaration = true)
5758 * struct T { ... } t = { ... }; (is_declaration = true)
5759 * S s = { ... }; (is_declaration = false)
5760 */
5761 if (this->structure != NULL && this->structure->is_declaration)
5762 return this->structure->hir(instructions, state);
5763
5764 return NULL;
5765 }
5766
5767
5768 /**
5769 * Process a structure or interface block tree into an array of structure fields
5770 *
5771 * After parsing, where there are some syntax differnces, structures and
5772 * interface blocks are almost identical. They are similar enough that the
5773 * AST for each can be processed the same way into a set of
5774 * \c glsl_struct_field to describe the members.
5775 *
5776 * If we're processing an interface block, var_mode should be the type of the
5777 * interface block (ir_var_shader_in, ir_var_shader_out, ir_var_uniform or
5778 * ir_var_shader_storage). If we're processing a structure, var_mode should be
5779 * ir_var_auto.
5780 *
5781 * \return
5782 * The number of fields processed. A pointer to the array structure fields is
5783 * stored in \c *fields_ret.
5784 */
5785 unsigned
5786 ast_process_structure_or_interface_block(exec_list *instructions,
5787 struct _mesa_glsl_parse_state *state,
5788 exec_list *declarations,
5789 YYLTYPE &loc,
5790 glsl_struct_field **fields_ret,
5791 bool is_interface,
5792 enum glsl_matrix_layout matrix_layout,
5793 bool allow_reserved_names,
5794 ir_variable_mode var_mode,
5795 ast_type_qualifier *layout)
5796 {
5797 unsigned decl_count = 0;
5798
5799 /* For blocks that accept memory qualifiers (i.e. shader storage), verify
5800 * that we don't have incompatible qualifiers
5801 */
5802 if (layout && layout->flags.q.read_only && layout->flags.q.write_only) {
5803 _mesa_glsl_error(&loc, state,
5804 "Interface block sets both readonly and writeonly");
5805 }
5806
5807 /* Make an initial pass over the list of fields to determine how
5808 * many there are. Each element in this list is an ast_declarator_list.
5809 * This means that we actually need to count the number of elements in the
5810 * 'declarations' list in each of the elements.
5811 */
5812 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
5813 decl_count += decl_list->declarations.length();
5814 }
5815
5816 /* Allocate storage for the fields and process the field
5817 * declarations. As the declarations are processed, try to also convert
5818 * the types to HIR. This ensures that structure definitions embedded in
5819 * other structure definitions or in interface blocks are processed.
5820 */
5821 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
5822 decl_count);
5823
5824 unsigned i = 0;
5825 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
5826 const char *type_name;
5827
5828 decl_list->type->specifier->hir(instructions, state);
5829
5830 /* Section 10.9 of the GLSL ES 1.00 specification states that
5831 * embedded structure definitions have been removed from the language.
5832 */
5833 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
5834 _mesa_glsl_error(&loc, state, "embedded structure definitions are "
5835 "not allowed in GLSL ES 1.00");
5836 }
5837
5838 const glsl_type *decl_type =
5839 decl_list->type->glsl_type(& type_name, state);
5840
5841 foreach_list_typed (ast_declaration, decl, link,
5842 &decl_list->declarations) {
5843 if (!allow_reserved_names)
5844 validate_identifier(decl->identifier, loc, state);
5845
5846 /* From section 4.3.9 of the GLSL 4.40 spec:
5847 *
5848 * "[In interface blocks] opaque types are not allowed."
5849 *
5850 * It should be impossible for decl_type to be NULL here. Cases that
5851 * might naturally lead to decl_type being NULL, especially for the
5852 * is_interface case, will have resulted in compilation having
5853 * already halted due to a syntax error.
5854 */
5855 assert(decl_type);
5856
5857 if (is_interface && decl_type->contains_opaque()) {
5858 YYLTYPE loc = decl_list->get_location();
5859 _mesa_glsl_error(&loc, state,
5860 "uniform/buffer in non-default interface block contains "
5861 "opaque variable");
5862 }
5863
5864 if (decl_type->contains_atomic()) {
5865 /* From section 4.1.7.3 of the GLSL 4.40 spec:
5866 *
5867 * "Members of structures cannot be declared as atomic counter
5868 * types."
5869 */
5870 YYLTYPE loc = decl_list->get_location();
5871 _mesa_glsl_error(&loc, state, "atomic counter in structure, "
5872 "shader storage block or uniform block");
5873 }
5874
5875 if (decl_type->contains_image()) {
5876 /* FINISHME: Same problem as with atomic counters.
5877 * FINISHME: Request clarification from Khronos and add
5878 * FINISHME: spec quotation here.
5879 */
5880 YYLTYPE loc = decl_list->get_location();
5881 _mesa_glsl_error(&loc, state,
5882 "image in structure, shader storage block or "
5883 "uniform block");
5884 }
5885
5886 const struct ast_type_qualifier *const qual =
5887 & decl_list->type->qualifier;
5888
5889 if (qual->flags.q.explicit_binding)
5890 validate_binding_qualifier(state, &loc, decl_type, qual);
5891
5892 if (qual->flags.q.std140 ||
5893 qual->flags.q.std430 ||
5894 qual->flags.q.packed ||
5895 qual->flags.q.shared) {
5896 _mesa_glsl_error(&loc, state,
5897 "uniform/shader storage block layout qualifiers "
5898 "std140, std430, packed, and shared can only be "
5899 "applied to uniform/shader storage blocks, not "
5900 "members");
5901 }
5902
5903 if (qual->flags.q.constant) {
5904 YYLTYPE loc = decl_list->get_location();
5905 _mesa_glsl_error(&loc, state,
5906 "const storage qualifier cannot be applied "
5907 "to struct or interface block members");
5908 }
5909
5910 const struct glsl_type *field_type =
5911 process_array_type(&loc, decl_type, decl->array_specifier, state);
5912 validate_array_dimensions(field_type, state, &loc);
5913 fields[i].type = field_type;
5914 fields[i].name = decl->identifier;
5915 fields[i].location = -1;
5916 fields[i].interpolation =
5917 interpret_interpolation_qualifier(qual, var_mode, state, &loc);
5918 fields[i].centroid = qual->flags.q.centroid ? 1 : 0;
5919 fields[i].sample = qual->flags.q.sample ? 1 : 0;
5920 fields[i].patch = qual->flags.q.patch ? 1 : 0;
5921
5922 /* From Section 4.4.2.3 (Geometry Outputs) of the GLSL 4.50 spec:
5923 *
5924 * "A block member may be declared with a stream identifier, but
5925 * the specified stream must match the stream associated with the
5926 * containing block."
5927 */
5928 if (qual->flags.q.explicit_stream &&
5929 qual->stream != layout->stream) {
5930 _mesa_glsl_error(&loc, state, "stream layout qualifier on "
5931 "interface block member `%s' does not match "
5932 "the interface block (%d vs %d)",
5933 fields[i].name, qual->stream, layout->stream);
5934 }
5935
5936 if (qual->flags.q.row_major || qual->flags.q.column_major) {
5937 if (!qual->flags.q.uniform && !qual->flags.q.buffer) {
5938 _mesa_glsl_error(&loc, state,
5939 "row_major and column_major can only be "
5940 "applied to interface blocks");
5941 } else
5942 validate_matrix_layout_for_type(state, &loc, field_type, NULL);
5943 }
5944
5945 if (qual->flags.q.uniform && qual->has_interpolation()) {
5946 _mesa_glsl_error(&loc, state,
5947 "interpolation qualifiers cannot be used "
5948 "with uniform interface blocks");
5949 }
5950
5951 if ((qual->flags.q.uniform || !is_interface) &&
5952 qual->has_auxiliary_storage()) {
5953 _mesa_glsl_error(&loc, state,
5954 "auxiliary storage qualifiers cannot be used "
5955 "in uniform blocks or structures.");
5956 }
5957
5958 /* Propogate row- / column-major information down the fields of the
5959 * structure or interface block. Structures need this data because
5960 * the structure may contain a structure that contains ... a matrix
5961 * that need the proper layout.
5962 */
5963 if (field_type->without_array()->is_matrix()
5964 || field_type->without_array()->is_record()) {
5965 /* If no layout is specified for the field, inherit the layout
5966 * from the block.
5967 */
5968 fields[i].matrix_layout = matrix_layout;
5969
5970 if (qual->flags.q.row_major)
5971 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
5972 else if (qual->flags.q.column_major)
5973 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
5974
5975 /* If we're processing an interface block, the matrix layout must
5976 * be decided by this point.
5977 */
5978 assert(!is_interface
5979 || fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR
5980 || fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR);
5981 }
5982
5983 /* Image qualifiers are allowed on buffer variables, which can only
5984 * be defined inside shader storage buffer objects
5985 */
5986 if (layout && var_mode == ir_var_shader_storage) {
5987 if (qual->flags.q.read_only && qual->flags.q.write_only) {
5988 _mesa_glsl_error(&loc, state,
5989 "buffer variable `%s' can't be "
5990 "readonly and writeonly.", fields[i].name);
5991 }
5992
5993 /* For readonly and writeonly qualifiers the field definition,
5994 * if set, overwrites the layout qualifier.
5995 */
5996 bool read_only = layout->flags.q.read_only;
5997 bool write_only = layout->flags.q.write_only;
5998
5999 if (qual->flags.q.read_only) {
6000 read_only = true;
6001 write_only = false;
6002 } else if (qual->flags.q.write_only) {
6003 read_only = false;
6004 write_only = true;
6005 }
6006
6007 fields[i].image_read_only = read_only;
6008 fields[i].image_write_only = write_only;
6009
6010 /* For other qualifiers, we set the flag if either the layout
6011 * qualifier or the field qualifier are set
6012 */
6013 fields[i].image_coherent = qual->flags.q.coherent ||
6014 layout->flags.q.coherent;
6015 fields[i].image_volatile = qual->flags.q._volatile ||
6016 layout->flags.q._volatile;
6017 fields[i].image_restrict = qual->flags.q.restrict_flag ||
6018 layout->flags.q.restrict_flag;
6019 }
6020
6021 i++;
6022 }
6023 }
6024
6025 assert(i == decl_count);
6026
6027 *fields_ret = fields;
6028 return decl_count;
6029 }
6030
6031
6032 ir_rvalue *
6033 ast_struct_specifier::hir(exec_list *instructions,
6034 struct _mesa_glsl_parse_state *state)
6035 {
6036 YYLTYPE loc = this->get_location();
6037
6038 /* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:
6039 *
6040 * "Anonymous structures are not supported; so embedded structures must
6041 * have a declarator. A name given to an embedded struct is scoped at
6042 * the same level as the struct it is embedded in."
6043 *
6044 * The same section of the GLSL 1.20 spec says:
6045 *
6046 * "Anonymous structures are not supported. Embedded structures are not
6047 * supported.
6048 *
6049 * struct S { float f; };
6050 * struct T {
6051 * S; // Error: anonymous structures disallowed
6052 * struct { ... }; // Error: embedded structures disallowed
6053 * S s; // Okay: nested structures with name are allowed
6054 * };"
6055 *
6056 * The GLSL ES 1.00 and 3.00 specs have similar langauge and examples. So,
6057 * we allow embedded structures in 1.10 only.
6058 */
6059 if (state->language_version != 110 && state->struct_specifier_depth != 0)
6060 _mesa_glsl_error(&loc, state,
6061 "embedded structure declarations are not allowed");
6062
6063 state->struct_specifier_depth++;
6064
6065 glsl_struct_field *fields;
6066 unsigned decl_count =
6067 ast_process_structure_or_interface_block(instructions,
6068 state,
6069 &this->declarations,
6070 loc,
6071 &fields,
6072 false,
6073 GLSL_MATRIX_LAYOUT_INHERITED,
6074 false /* allow_reserved_names */,
6075 ir_var_auto,
6076 NULL);
6077
6078 validate_identifier(this->name, loc, state);
6079
6080 const glsl_type *t =
6081 glsl_type::get_record_instance(fields, decl_count, this->name);
6082
6083 if (!state->symbols->add_type(name, t)) {
6084 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
6085 } else {
6086 const glsl_type **s = reralloc(state, state->user_structures,
6087 const glsl_type *,
6088 state->num_user_structures + 1);
6089 if (s != NULL) {
6090 s[state->num_user_structures] = t;
6091 state->user_structures = s;
6092 state->num_user_structures++;
6093 }
6094 }
6095
6096 state->struct_specifier_depth--;
6097
6098 /* Structure type definitions do not have r-values.
6099 */
6100 return NULL;
6101 }
6102
6103
6104 /**
6105 * Visitor class which detects whether a given interface block has been used.
6106 */
6107 class interface_block_usage_visitor : public ir_hierarchical_visitor
6108 {
6109 public:
6110 interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)
6111 : mode(mode), block(block), found(false)
6112 {
6113 }
6114
6115 virtual ir_visitor_status visit(ir_dereference_variable *ir)
6116 {
6117 if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {
6118 found = true;
6119 return visit_stop;
6120 }
6121 return visit_continue;
6122 }
6123
6124 bool usage_found() const
6125 {
6126 return this->found;
6127 }
6128
6129 private:
6130 ir_variable_mode mode;
6131 const glsl_type *block;
6132 bool found;
6133 };
6134
6135 static bool
6136 is_unsized_array_last_element(ir_variable *v)
6137 {
6138 const glsl_type *interface_type = v->get_interface_type();
6139 int length = interface_type->length;
6140
6141 assert(v->type->is_unsized_array());
6142
6143 /* Check if it is the last element of the interface */
6144 if (strcmp(interface_type->fields.structure[length-1].name, v->name) == 0)
6145 return true;
6146 return false;
6147 }
6148
6149 ir_rvalue *
6150 ast_interface_block::hir(exec_list *instructions,
6151 struct _mesa_glsl_parse_state *state)
6152 {
6153 YYLTYPE loc = this->get_location();
6154
6155 /* Interface blocks must be declared at global scope */
6156 if (state->current_function != NULL) {
6157 _mesa_glsl_error(&loc, state,
6158 "Interface block `%s' must be declared "
6159 "at global scope",
6160 this->block_name);
6161 }
6162
6163 if (!this->layout.flags.q.buffer &&
6164 this->layout.flags.q.std430) {
6165 _mesa_glsl_error(&loc, state,
6166 "std430 storage block layout qualifier is supported "
6167 "only for shader storage blocks");
6168 }
6169
6170 /* The ast_interface_block has a list of ast_declarator_lists. We
6171 * need to turn those into ir_variables with an association
6172 * with this uniform block.
6173 */
6174 enum glsl_interface_packing packing;
6175 if (this->layout.flags.q.shared) {
6176 packing = GLSL_INTERFACE_PACKING_SHARED;
6177 } else if (this->layout.flags.q.packed) {
6178 packing = GLSL_INTERFACE_PACKING_PACKED;
6179 } else if (this->layout.flags.q.std430) {
6180 packing = GLSL_INTERFACE_PACKING_STD430;
6181 } else {
6182 /* The default layout is std140.
6183 */
6184 packing = GLSL_INTERFACE_PACKING_STD140;
6185 }
6186
6187 ir_variable_mode var_mode;
6188 const char *iface_type_name;
6189 if (this->layout.flags.q.in) {
6190 var_mode = ir_var_shader_in;
6191 iface_type_name = "in";
6192 } else if (this->layout.flags.q.out) {
6193 var_mode = ir_var_shader_out;
6194 iface_type_name = "out";
6195 } else if (this->layout.flags.q.uniform) {
6196 var_mode = ir_var_uniform;
6197 iface_type_name = "uniform";
6198 } else if (this->layout.flags.q.buffer) {
6199 var_mode = ir_var_shader_storage;
6200 iface_type_name = "buffer";
6201 } else {
6202 var_mode = ir_var_auto;
6203 iface_type_name = "UNKNOWN";
6204 assert(!"interface block layout qualifier not found!");
6205 }
6206
6207 enum glsl_matrix_layout matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;
6208 if (this->layout.flags.q.row_major)
6209 matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
6210 else if (this->layout.flags.q.column_major)
6211 matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
6212
6213 bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;
6214 exec_list declared_variables;
6215 glsl_struct_field *fields;
6216
6217 /* Treat an interface block as one level of nesting, so that embedded struct
6218 * specifiers will be disallowed.
6219 */
6220 state->struct_specifier_depth++;
6221
6222 unsigned int num_variables =
6223 ast_process_structure_or_interface_block(&declared_variables,
6224 state,
6225 &this->declarations,
6226 loc,
6227 &fields,
6228 true,
6229 matrix_layout,
6230 redeclaring_per_vertex,
6231 var_mode,
6232 &this->layout);
6233
6234 state->struct_specifier_depth--;
6235
6236 if (!redeclaring_per_vertex) {
6237 validate_identifier(this->block_name, loc, state);
6238
6239 /* From section 4.3.9 ("Interface Blocks") of the GLSL 4.50 spec:
6240 *
6241 * "Block names have no other use within a shader beyond interface
6242 * matching; it is a compile-time error to use a block name at global
6243 * scope for anything other than as a block name."
6244 */
6245 ir_variable *var = state->symbols->get_variable(this->block_name);
6246 if (var && !var->type->is_interface()) {
6247 _mesa_glsl_error(&loc, state, "Block name `%s' is "
6248 "already used in the scope.",
6249 this->block_name);
6250 }
6251 }
6252
6253 const glsl_type *earlier_per_vertex = NULL;
6254 if (redeclaring_per_vertex) {
6255 /* Find the previous declaration of gl_PerVertex. If we're redeclaring
6256 * the named interface block gl_in, we can find it by looking at the
6257 * previous declaration of gl_in. Otherwise we can find it by looking
6258 * at the previous decalartion of any of the built-in outputs,
6259 * e.g. gl_Position.
6260 *
6261 * Also check that the instance name and array-ness of the redeclaration
6262 * are correct.
6263 */
6264 switch (var_mode) {
6265 case ir_var_shader_in:
6266 if (ir_variable *earlier_gl_in =
6267 state->symbols->get_variable("gl_in")) {
6268 earlier_per_vertex = earlier_gl_in->get_interface_type();
6269 } else {
6270 _mesa_glsl_error(&loc, state,
6271 "redeclaration of gl_PerVertex input not allowed "
6272 "in the %s shader",
6273 _mesa_shader_stage_to_string(state->stage));
6274 }
6275 if (this->instance_name == NULL ||
6276 strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL ||
6277 !this->array_specifier->is_single_dimension()) {
6278 _mesa_glsl_error(&loc, state,
6279 "gl_PerVertex input must be redeclared as "
6280 "gl_in[]");
6281 }
6282 break;
6283 case ir_var_shader_out:
6284 if (ir_variable *earlier_gl_Position =
6285 state->symbols->get_variable("gl_Position")) {
6286 earlier_per_vertex = earlier_gl_Position->get_interface_type();
6287 } else if (ir_variable *earlier_gl_out =
6288 state->symbols->get_variable("gl_out")) {
6289 earlier_per_vertex = earlier_gl_out->get_interface_type();
6290 } else {
6291 _mesa_glsl_error(&loc, state,
6292 "redeclaration of gl_PerVertex output not "
6293 "allowed in the %s shader",
6294 _mesa_shader_stage_to_string(state->stage));
6295 }
6296 if (state->stage == MESA_SHADER_TESS_CTRL) {
6297 if (this->instance_name == NULL ||
6298 strcmp(this->instance_name, "gl_out") != 0 || this->array_specifier == NULL) {
6299 _mesa_glsl_error(&loc, state,
6300 "gl_PerVertex output must be redeclared as "
6301 "gl_out[]");
6302 }
6303 } else {
6304 if (this->instance_name != NULL) {
6305 _mesa_glsl_error(&loc, state,
6306 "gl_PerVertex output may not be redeclared with "
6307 "an instance name");
6308 }
6309 }
6310 break;
6311 default:
6312 _mesa_glsl_error(&loc, state,
6313 "gl_PerVertex must be declared as an input or an "
6314 "output");
6315 break;
6316 }
6317
6318 if (earlier_per_vertex == NULL) {
6319 /* An error has already been reported. Bail out to avoid null
6320 * dereferences later in this function.
6321 */
6322 return NULL;
6323 }
6324
6325 /* Copy locations from the old gl_PerVertex interface block. */
6326 for (unsigned i = 0; i < num_variables; i++) {
6327 int j = earlier_per_vertex->field_index(fields[i].name);
6328 if (j == -1) {
6329 _mesa_glsl_error(&loc, state,
6330 "redeclaration of gl_PerVertex must be a subset "
6331 "of the built-in members of gl_PerVertex");
6332 } else {
6333 fields[i].location =
6334 earlier_per_vertex->fields.structure[j].location;
6335 fields[i].interpolation =
6336 earlier_per_vertex->fields.structure[j].interpolation;
6337 fields[i].centroid =
6338 earlier_per_vertex->fields.structure[j].centroid;
6339 fields[i].sample =
6340 earlier_per_vertex->fields.structure[j].sample;
6341 fields[i].patch =
6342 earlier_per_vertex->fields.structure[j].patch;
6343 }
6344 }
6345
6346 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10
6347 * spec:
6348 *
6349 * If a built-in interface block is redeclared, it must appear in
6350 * the shader before any use of any member included in the built-in
6351 * declaration, or a compilation error will result.
6352 *
6353 * This appears to be a clarification to the behaviour established for
6354 * gl_PerVertex by GLSL 1.50, therefore we implement this behaviour
6355 * regardless of GLSL version.
6356 */
6357 interface_block_usage_visitor v(var_mode, earlier_per_vertex);
6358 v.run(instructions);
6359 if (v.usage_found()) {
6360 _mesa_glsl_error(&loc, state,
6361 "redeclaration of a built-in interface block must "
6362 "appear before any use of any member of the "
6363 "interface block");
6364 }
6365 }
6366
6367 const glsl_type *block_type =
6368 glsl_type::get_interface_instance(fields,
6369 num_variables,
6370 packing,
6371 this->block_name);
6372 if (this->layout.flags.q.explicit_binding)
6373 validate_binding_qualifier(state, &loc, block_type, &this->layout);
6374
6375 if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {
6376 YYLTYPE loc = this->get_location();
6377 _mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "
6378 "already taken in the current scope",
6379 this->block_name, iface_type_name);
6380 }
6381
6382 /* Since interface blocks cannot contain statements, it should be
6383 * impossible for the block to generate any instructions.
6384 */
6385 assert(declared_variables.is_empty());
6386
6387 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
6388 *
6389 * Geometry shader input variables get the per-vertex values written
6390 * out by vertex shader output variables of the same names. Since a
6391 * geometry shader operates on a set of vertices, each input varying
6392 * variable (or input block, see interface blocks below) needs to be
6393 * declared as an array.
6394 */
6395 if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&
6396 var_mode == ir_var_shader_in) {
6397 _mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");
6398 } else if ((state->stage == MESA_SHADER_TESS_CTRL ||
6399 state->stage == MESA_SHADER_TESS_EVAL) &&
6400 this->array_specifier == NULL &&
6401 var_mode == ir_var_shader_in) {
6402 _mesa_glsl_error(&loc, state, "per-vertex tessellation shader inputs must be arrays");
6403 } else if (state->stage == MESA_SHADER_TESS_CTRL &&
6404 this->array_specifier == NULL &&
6405 var_mode == ir_var_shader_out) {
6406 _mesa_glsl_error(&loc, state, "tessellation control shader outputs must be arrays");
6407 }
6408
6409
6410 /* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec
6411 * says:
6412 *
6413 * "If an instance name (instance-name) is used, then it puts all the
6414 * members inside a scope within its own name space, accessed with the
6415 * field selector ( . ) operator (analogously to structures)."
6416 */
6417 if (this->instance_name) {
6418 if (redeclaring_per_vertex) {
6419 /* When a built-in in an unnamed interface block is redeclared,
6420 * get_variable_being_redeclared() calls
6421 * check_builtin_array_max_size() to make sure that built-in array
6422 * variables aren't redeclared to illegal sizes. But we're looking
6423 * at a redeclaration of a named built-in interface block. So we
6424 * have to manually call check_builtin_array_max_size() for all parts
6425 * of the interface that are arrays.
6426 */
6427 for (unsigned i = 0; i < num_variables; i++) {
6428 if (fields[i].type->is_array()) {
6429 const unsigned size = fields[i].type->array_size();
6430 check_builtin_array_max_size(fields[i].name, size, loc, state);
6431 }
6432 }
6433 } else {
6434 validate_identifier(this->instance_name, loc, state);
6435 }
6436
6437 ir_variable *var;
6438
6439 if (this->array_specifier != NULL) {
6440 const glsl_type *block_array_type =
6441 process_array_type(&loc, block_type, this->array_specifier, state);
6442
6443 /* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:
6444 *
6445 * For uniform blocks declared an array, each individual array
6446 * element corresponds to a separate buffer object backing one
6447 * instance of the block. As the array size indicates the number
6448 * of buffer objects needed, uniform block array declarations
6449 * must specify an array size.
6450 *
6451 * And a few paragraphs later:
6452 *
6453 * Geometry shader input blocks must be declared as arrays and
6454 * follow the array declaration and linking rules for all
6455 * geometry shader inputs. All other input and output block
6456 * arrays must specify an array size.
6457 *
6458 * The same applies to tessellation shaders.
6459 *
6460 * The upshot of this is that the only circumstance where an
6461 * interface array size *doesn't* need to be specified is on a
6462 * geometry shader input, tessellation control shader input,
6463 * tessellation control shader output, and tessellation evaluation
6464 * shader input.
6465 */
6466 if (block_array_type->is_unsized_array()) {
6467 bool allow_inputs = state->stage == MESA_SHADER_GEOMETRY ||
6468 state->stage == MESA_SHADER_TESS_CTRL ||
6469 state->stage == MESA_SHADER_TESS_EVAL;
6470 bool allow_outputs = state->stage == MESA_SHADER_TESS_CTRL;
6471
6472 if (this->layout.flags.q.in) {
6473 if (!allow_inputs)
6474 _mesa_glsl_error(&loc, state,
6475 "unsized input block arrays not allowed in "
6476 "%s shader",
6477 _mesa_shader_stage_to_string(state->stage));
6478 } else if (this->layout.flags.q.out) {
6479 if (!allow_outputs)
6480 _mesa_glsl_error(&loc, state,
6481 "unsized output block arrays not allowed in "
6482 "%s shader",
6483 _mesa_shader_stage_to_string(state->stage));
6484 } else {
6485 /* by elimination, this is a uniform block array */
6486 _mesa_glsl_error(&loc, state,
6487 "unsized uniform block arrays not allowed in "
6488 "%s shader",
6489 _mesa_shader_stage_to_string(state->stage));
6490 }
6491 }
6492
6493 /* From section 4.3.9 (Interface Blocks) of the GLSL ES 3.10 spec:
6494 *
6495 * * Arrays of arrays of blocks are not allowed
6496 */
6497 if (state->es_shader && block_array_type->is_array() &&
6498 block_array_type->fields.array->is_array()) {
6499 _mesa_glsl_error(&loc, state,
6500 "arrays of arrays interface blocks are "
6501 "not allowed");
6502 }
6503
6504 if (this->layout.flags.q.explicit_binding)
6505 validate_binding_qualifier(state, &loc, block_array_type,
6506 &this->layout);
6507
6508 var = new(state) ir_variable(block_array_type,
6509 this->instance_name,
6510 var_mode);
6511 } else {
6512 var = new(state) ir_variable(block_type,
6513 this->instance_name,
6514 var_mode);
6515 }
6516
6517 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
6518 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
6519
6520 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
6521 var->data.read_only = true;
6522
6523 if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)
6524 handle_geometry_shader_input_decl(state, loc, var);
6525 else if ((state->stage == MESA_SHADER_TESS_CTRL ||
6526 state->stage == MESA_SHADER_TESS_EVAL) && var_mode == ir_var_shader_in)
6527 handle_tess_shader_input_decl(state, loc, var);
6528 else if (state->stage == MESA_SHADER_TESS_CTRL && var_mode == ir_var_shader_out)
6529 handle_tess_ctrl_shader_output_decl(state, loc, var);
6530
6531 for (unsigned i = 0; i < num_variables; i++) {
6532 if (fields[i].type->is_unsized_array()) {
6533 if (var_mode == ir_var_shader_storage) {
6534 if (i != (num_variables - 1)) {
6535 _mesa_glsl_error(&loc, state, "unsized array `%s' definition: "
6536 "only last member of a shader storage block "
6537 "can be defined as unsized array",
6538 fields[i].name);
6539 }
6540 } else {
6541 /* From GLSL ES 3.10 spec, section 4.1.9 "Arrays":
6542 *
6543 * "If an array is declared as the last member of a shader storage
6544 * block and the size is not specified at compile-time, it is
6545 * sized at run-time. In all other cases, arrays are sized only
6546 * at compile-time."
6547 */
6548 if (state->es_shader) {
6549 _mesa_glsl_error(&loc, state, "unsized array `%s' definition: "
6550 "only last member of a shader storage block "
6551 "can be defined as unsized array",
6552 fields[i].name);
6553 }
6554 }
6555 }
6556 }
6557
6558 if (ir_variable *earlier =
6559 state->symbols->get_variable(this->instance_name)) {
6560 if (!redeclaring_per_vertex) {
6561 _mesa_glsl_error(&loc, state, "`%s' redeclared",
6562 this->instance_name);
6563 }
6564 earlier->data.how_declared = ir_var_declared_normally;
6565 earlier->type = var->type;
6566 earlier->reinit_interface_type(block_type);
6567 delete var;
6568 } else {
6569 /* Propagate the "binding" keyword into this UBO's fields;
6570 * the UBO declaration itself doesn't get an ir_variable unless it
6571 * has an instance name. This is ugly.
6572 */
6573 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
6574 var->data.binding = this->layout.binding;
6575
6576 var->data.stream = this->layout.stream;
6577
6578 state->symbols->add_variable(var);
6579 instructions->push_tail(var);
6580 }
6581 } else {
6582 /* In order to have an array size, the block must also be declared with
6583 * an instance name.
6584 */
6585 assert(this->array_specifier == NULL);
6586
6587 for (unsigned i = 0; i < num_variables; i++) {
6588 ir_variable *var =
6589 new(state) ir_variable(fields[i].type,
6590 ralloc_strdup(state, fields[i].name),
6591 var_mode);
6592 var->data.interpolation = fields[i].interpolation;
6593 var->data.centroid = fields[i].centroid;
6594 var->data.sample = fields[i].sample;
6595 var->data.patch = fields[i].patch;
6596 var->data.stream = this->layout.stream;
6597 var->init_interface_type(block_type);
6598
6599 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
6600 var->data.read_only = true;
6601
6602 if (fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED) {
6603 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
6604 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
6605 } else {
6606 var->data.matrix_layout = fields[i].matrix_layout;
6607 }
6608
6609 if (var->data.mode == ir_var_shader_storage) {
6610 var->data.image_read_only = fields[i].image_read_only;
6611 var->data.image_write_only = fields[i].image_write_only;
6612 var->data.image_coherent = fields[i].image_coherent;
6613 var->data.image_volatile = fields[i].image_volatile;
6614 var->data.image_restrict = fields[i].image_restrict;
6615 }
6616
6617 /* Examine var name here since var may get deleted in the next call */
6618 bool var_is_gl_id = is_gl_identifier(var->name);
6619
6620 if (redeclaring_per_vertex) {
6621 ir_variable *earlier =
6622 get_variable_being_redeclared(var, loc, state,
6623 true /* allow_all_redeclarations */);
6624 if (!var_is_gl_id || earlier == NULL) {
6625 _mesa_glsl_error(&loc, state,
6626 "redeclaration of gl_PerVertex can only "
6627 "include built-in variables");
6628 } else if (earlier->data.how_declared == ir_var_declared_normally) {
6629 _mesa_glsl_error(&loc, state,
6630 "`%s' has already been redeclared",
6631 earlier->name);
6632 } else {
6633 earlier->data.how_declared = ir_var_declared_in_block;
6634 earlier->reinit_interface_type(block_type);
6635 }
6636 continue;
6637 }
6638
6639 if (state->symbols->get_variable(var->name) != NULL)
6640 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
6641
6642 /* Propagate the "binding" keyword into this UBO/SSBO's fields.
6643 * The UBO declaration itself doesn't get an ir_variable unless it
6644 * has an instance name. This is ugly.
6645 */
6646 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
6647 var->data.binding = this->layout.binding;
6648
6649 if (var->type->is_unsized_array()) {
6650 if (var->is_in_shader_storage_block()) {
6651 if (!is_unsized_array_last_element(var)) {
6652 _mesa_glsl_error(&loc, state, "unsized array `%s' definition: "
6653 "only last member of a shader storage block "
6654 "can be defined as unsized array",
6655 var->name);
6656 }
6657 var->data.from_ssbo_unsized_array = true;
6658 } else {
6659 /* From GLSL ES 3.10 spec, section 4.1.9 "Arrays":
6660 *
6661 * "If an array is declared as the last member of a shader storage
6662 * block and the size is not specified at compile-time, it is
6663 * sized at run-time. In all other cases, arrays are sized only
6664 * at compile-time."
6665 */
6666 if (state->es_shader) {
6667 _mesa_glsl_error(&loc, state, "unsized array `%s' definition: "
6668 "only last member of a shader storage block "
6669 "can be defined as unsized array",
6670 var->name);
6671 }
6672 }
6673 }
6674
6675 state->symbols->add_variable(var);
6676 instructions->push_tail(var);
6677 }
6678
6679 if (redeclaring_per_vertex && block_type != earlier_per_vertex) {
6680 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:
6681 *
6682 * It is also a compilation error ... to redeclare a built-in
6683 * block and then use a member from that built-in block that was
6684 * not included in the redeclaration.
6685 *
6686 * This appears to be a clarification to the behaviour established
6687 * for gl_PerVertex by GLSL 1.50, therefore we implement this
6688 * behaviour regardless of GLSL version.
6689 *
6690 * To prevent the shader from using a member that was not included in
6691 * the redeclaration, we disable any ir_variables that are still
6692 * associated with the old declaration of gl_PerVertex (since we've
6693 * already updated all of the variables contained in the new
6694 * gl_PerVertex to point to it).
6695 *
6696 * As a side effect this will prevent
6697 * validate_intrastage_interface_blocks() from getting confused and
6698 * thinking there are conflicting definitions of gl_PerVertex in the
6699 * shader.
6700 */
6701 foreach_in_list_safe(ir_instruction, node, instructions) {
6702 ir_variable *const var = node->as_variable();
6703 if (var != NULL &&
6704 var->get_interface_type() == earlier_per_vertex &&
6705 var->data.mode == var_mode) {
6706 if (var->data.how_declared == ir_var_declared_normally) {
6707 _mesa_glsl_error(&loc, state,
6708 "redeclaration of gl_PerVertex cannot "
6709 "follow a redeclaration of `%s'",
6710 var->name);
6711 }
6712 state->symbols->disable_variable(var->name);
6713 var->remove();
6714 }
6715 }
6716 }
6717 }
6718
6719 return NULL;
6720 }
6721
6722
6723 ir_rvalue *
6724 ast_tcs_output_layout::hir(exec_list *instructions,
6725 struct _mesa_glsl_parse_state *state)
6726 {
6727 YYLTYPE loc = this->get_location();
6728
6729 /* If any tessellation control output layout declaration preceded this
6730 * one, make sure it was consistent with this one.
6731 */
6732 if (state->tcs_output_vertices_specified &&
6733 state->out_qualifier->vertices != this->vertices) {
6734 _mesa_glsl_error(&loc, state,
6735 "tessellation control shader output layout does not "
6736 "match previous declaration");
6737 return NULL;
6738 }
6739
6740 /* If any shader outputs occurred before this declaration and specified an
6741 * array size, make sure the size they specified is consistent with the
6742 * primitive type.
6743 */
6744 unsigned num_vertices = this->vertices;
6745 if (state->tcs_output_size != 0 && state->tcs_output_size != num_vertices) {
6746 _mesa_glsl_error(&loc, state,
6747 "this tessellation control shader output layout "
6748 "specifies %u vertices, but a previous output "
6749 "is declared with size %u",
6750 num_vertices, state->tcs_output_size);
6751 return NULL;
6752 }
6753
6754 state->tcs_output_vertices_specified = true;
6755
6756 /* If any shader outputs occurred before this declaration and did not
6757 * specify an array size, their size is determined now.
6758 */
6759 foreach_in_list (ir_instruction, node, instructions) {
6760 ir_variable *var = node->as_variable();
6761 if (var == NULL || var->data.mode != ir_var_shader_out)
6762 continue;
6763
6764 /* Note: Not all tessellation control shader output are arrays. */
6765 if (!var->type->is_unsized_array() || var->data.patch)
6766 continue;
6767
6768 if (var->data.max_array_access >= num_vertices) {
6769 _mesa_glsl_error(&loc, state,
6770 "this tessellation control shader output layout "
6771 "specifies %u vertices, but an access to element "
6772 "%u of output `%s' already exists", num_vertices,
6773 var->data.max_array_access, var->name);
6774 } else {
6775 var->type = glsl_type::get_array_instance(var->type->fields.array,
6776 num_vertices);
6777 }
6778 }
6779
6780 return NULL;
6781 }
6782
6783
6784 ir_rvalue *
6785 ast_gs_input_layout::hir(exec_list *instructions,
6786 struct _mesa_glsl_parse_state *state)
6787 {
6788 YYLTYPE loc = this->get_location();
6789
6790 /* If any geometry input layout declaration preceded this one, make sure it
6791 * was consistent with this one.
6792 */
6793 if (state->gs_input_prim_type_specified &&
6794 state->in_qualifier->prim_type != this->prim_type) {
6795 _mesa_glsl_error(&loc, state,
6796 "geometry shader input layout does not match"
6797 " previous declaration");
6798 return NULL;
6799 }
6800
6801 /* If any shader inputs occurred before this declaration and specified an
6802 * array size, make sure the size they specified is consistent with the
6803 * primitive type.
6804 */
6805 unsigned num_vertices = vertices_per_prim(this->prim_type);
6806 if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {
6807 _mesa_glsl_error(&loc, state,
6808 "this geometry shader input layout implies %u vertices"
6809 " per primitive, but a previous input is declared"
6810 " with size %u", num_vertices, state->gs_input_size);
6811 return NULL;
6812 }
6813
6814 state->gs_input_prim_type_specified = true;
6815
6816 /* If any shader inputs occurred before this declaration and did not
6817 * specify an array size, their size is determined now.
6818 */
6819 foreach_in_list(ir_instruction, node, instructions) {
6820 ir_variable *var = node->as_variable();
6821 if (var == NULL || var->data.mode != ir_var_shader_in)
6822 continue;
6823
6824 /* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an
6825 * array; skip it.
6826 */
6827
6828 if (var->type->is_unsized_array()) {
6829 if (var->data.max_array_access >= num_vertices) {
6830 _mesa_glsl_error(&loc, state,
6831 "this geometry shader input layout implies %u"
6832 " vertices, but an access to element %u of input"
6833 " `%s' already exists", num_vertices,
6834 var->data.max_array_access, var->name);
6835 } else {
6836 var->type = glsl_type::get_array_instance(var->type->fields.array,
6837 num_vertices);
6838 }
6839 }
6840 }
6841
6842 return NULL;
6843 }
6844
6845
6846 ir_rvalue *
6847 ast_cs_input_layout::hir(exec_list *instructions,
6848 struct _mesa_glsl_parse_state *state)
6849 {
6850 YYLTYPE loc = this->get_location();
6851
6852 /* If any compute input layout declaration preceded this one, make sure it
6853 * was consistent with this one.
6854 */
6855 if (state->cs_input_local_size_specified) {
6856 for (int i = 0; i < 3; i++) {
6857 if (state->cs_input_local_size[i] != this->local_size[i]) {
6858 _mesa_glsl_error(&loc, state,
6859 "compute shader input layout does not match"
6860 " previous declaration");
6861 return NULL;
6862 }
6863 }
6864 }
6865
6866 /* From the ARB_compute_shader specification:
6867 *
6868 * If the local size of the shader in any dimension is greater
6869 * than the maximum size supported by the implementation for that
6870 * dimension, a compile-time error results.
6871 *
6872 * It is not clear from the spec how the error should be reported if
6873 * the total size of the work group exceeds
6874 * MAX_COMPUTE_WORK_GROUP_INVOCATIONS, but it seems reasonable to
6875 * report it at compile time as well.
6876 */
6877 GLuint64 total_invocations = 1;
6878 for (int i = 0; i < 3; i++) {
6879 if (this->local_size[i] > state->ctx->Const.MaxComputeWorkGroupSize[i]) {
6880 _mesa_glsl_error(&loc, state,
6881 "local_size_%c exceeds MAX_COMPUTE_WORK_GROUP_SIZE"
6882 " (%d)", 'x' + i,
6883 state->ctx->Const.MaxComputeWorkGroupSize[i]);
6884 break;
6885 }
6886 total_invocations *= this->local_size[i];
6887 if (total_invocations >
6888 state->ctx->Const.MaxComputeWorkGroupInvocations) {
6889 _mesa_glsl_error(&loc, state,
6890 "product of local_sizes exceeds "
6891 "MAX_COMPUTE_WORK_GROUP_INVOCATIONS (%d)",
6892 state->ctx->Const.MaxComputeWorkGroupInvocations);
6893 break;
6894 }
6895 }
6896
6897 state->cs_input_local_size_specified = true;
6898 for (int i = 0; i < 3; i++)
6899 state->cs_input_local_size[i] = this->local_size[i];
6900
6901 /* We may now declare the built-in constant gl_WorkGroupSize (see
6902 * builtin_variable_generator::generate_constants() for why we didn't
6903 * declare it earlier).
6904 */
6905 ir_variable *var = new(state->symbols)
6906 ir_variable(glsl_type::uvec3_type, "gl_WorkGroupSize", ir_var_auto);
6907 var->data.how_declared = ir_var_declared_implicitly;
6908 var->data.read_only = true;
6909 instructions->push_tail(var);
6910 state->symbols->add_variable(var);
6911 ir_constant_data data;
6912 memset(&data, 0, sizeof(data));
6913 for (int i = 0; i < 3; i++)
6914 data.u[i] = this->local_size[i];
6915 var->constant_value = new(var) ir_constant(glsl_type::uvec3_type, &data);
6916 var->constant_initializer =
6917 new(var) ir_constant(glsl_type::uvec3_type, &data);
6918 var->data.has_initializer = true;
6919
6920 return NULL;
6921 }
6922
6923
6924 static void
6925 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
6926 exec_list *instructions)
6927 {
6928 bool gl_FragColor_assigned = false;
6929 bool gl_FragData_assigned = false;
6930 bool user_defined_fs_output_assigned = false;
6931 ir_variable *user_defined_fs_output = NULL;
6932
6933 /* It would be nice to have proper location information. */
6934 YYLTYPE loc;
6935 memset(&loc, 0, sizeof(loc));
6936
6937 foreach_in_list(ir_instruction, node, instructions) {
6938 ir_variable *var = node->as_variable();
6939
6940 if (!var || !var->data.assigned)
6941 continue;
6942
6943 if (strcmp(var->name, "gl_FragColor") == 0)
6944 gl_FragColor_assigned = true;
6945 else if (strcmp(var->name, "gl_FragData") == 0)
6946 gl_FragData_assigned = true;
6947 else if (!is_gl_identifier(var->name)) {
6948 if (state->stage == MESA_SHADER_FRAGMENT &&
6949 var->data.mode == ir_var_shader_out) {
6950 user_defined_fs_output_assigned = true;
6951 user_defined_fs_output = var;
6952 }
6953 }
6954 }
6955
6956 /* From the GLSL 1.30 spec:
6957 *
6958 * "If a shader statically assigns a value to gl_FragColor, it
6959 * may not assign a value to any element of gl_FragData. If a
6960 * shader statically writes a value to any element of
6961 * gl_FragData, it may not assign a value to
6962 * gl_FragColor. That is, a shader may assign values to either
6963 * gl_FragColor or gl_FragData, but not both. Multiple shaders
6964 * linked together must also consistently write just one of
6965 * these variables. Similarly, if user declared output
6966 * variables are in use (statically assigned to), then the
6967 * built-in variables gl_FragColor and gl_FragData may not be
6968 * assigned to. These incorrect usages all generate compile
6969 * time errors."
6970 */
6971 if (gl_FragColor_assigned && gl_FragData_assigned) {
6972 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6973 "`gl_FragColor' and `gl_FragData'");
6974 } else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {
6975 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6976 "`gl_FragColor' and `%s'",
6977 user_defined_fs_output->name);
6978 } else if (gl_FragData_assigned && user_defined_fs_output_assigned) {
6979 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6980 "`gl_FragData' and `%s'",
6981 user_defined_fs_output->name);
6982 }
6983 }
6984
6985
6986 static void
6987 remove_per_vertex_blocks(exec_list *instructions,
6988 _mesa_glsl_parse_state *state, ir_variable_mode mode)
6989 {
6990 /* Find the gl_PerVertex interface block of the appropriate (in/out) mode,
6991 * if it exists in this shader type.
6992 */
6993 const glsl_type *per_vertex = NULL;
6994 switch (mode) {
6995 case ir_var_shader_in:
6996 if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))
6997 per_vertex = gl_in->get_interface_type();
6998 break;
6999 case ir_var_shader_out:
7000 if (ir_variable *gl_Position =
7001 state->symbols->get_variable("gl_Position")) {
7002 per_vertex = gl_Position->get_interface_type();
7003 }
7004 break;
7005 default:
7006 assert(!"Unexpected mode");
7007 break;
7008 }
7009
7010 /* If we didn't find a built-in gl_PerVertex interface block, then we don't
7011 * need to do anything.
7012 */
7013 if (per_vertex == NULL)
7014 return;
7015
7016 /* If the interface block is used by the shader, then we don't need to do
7017 * anything.
7018 */
7019 interface_block_usage_visitor v(mode, per_vertex);
7020 v.run(instructions);
7021 if (v.usage_found())
7022 return;
7023
7024 /* Remove any ir_variable declarations that refer to the interface block
7025 * we're removing.
7026 */
7027 foreach_in_list_safe(ir_instruction, node, instructions) {
7028 ir_variable *const var = node->as_variable();
7029 if (var != NULL && var->get_interface_type() == per_vertex &&
7030 var->data.mode == mode) {
7031 state->symbols->disable_variable(var->name);
7032 var->remove();
7033 }
7034 }
7035 }