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