OSDN Git Service

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