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