ast_to_hir.cpp revision 2c3e10e71935506798c413363df27afc4348fb53
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 "main/core.h" /* for struct gl_extensions */
53#include "glsl_symbol_table.h"
54#include "glsl_parser_extras.h"
55#include "ast.h"
56#include "glsl_types.h"
57#include "ir.h"
58
59void
60_mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
61{
62   _mesa_glsl_initialize_variables(instructions, state);
63
64   state->symbols->language_version = state->language_version;
65
66   state->current_function = NULL;
67
68   state->toplevel_ir = instructions;
69
70   /* Section 4.2 of the GLSL 1.20 specification states:
71    * "The built-in functions are scoped in a scope outside the global scope
72    *  users declare global variables in.  That is, a shader's global scope,
73    *  available for user-defined functions and global variables, is nested
74    *  inside the scope containing the built-in functions."
75    *
76    * Since built-in functions like ftransform() access built-in variables,
77    * it follows that those must be in the outer scope as well.
78    *
79    * We push scope here to create this nesting effect...but don't pop.
80    * This way, a shader's globals are still in the symbol table for use
81    * by the linker.
82    */
83   state->symbols->push_scope();
84
85   foreach_list_typed (ast_node, ast, link, & state->translation_unit)
86      ast->hir(instructions, state);
87
88   detect_recursion_unlinked(state, instructions);
89
90   state->toplevel_ir = NULL;
91}
92
93
94/**
95 * If a conversion is available, convert one operand to a different type
96 *
97 * The \c from \c ir_rvalue is converted "in place".
98 *
99 * \param to     Type that the operand it to be converted to
100 * \param from   Operand that is being converted
101 * \param state  GLSL compiler state
102 *
103 * \return
104 * If a conversion is possible (or unnecessary), \c true is returned.
105 * Otherwise \c false is returned.
106 */
107bool
108apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
109			  struct _mesa_glsl_parse_state *state)
110{
111   void *ctx = state;
112   if (to->base_type == from->type->base_type)
113      return true;
114
115   /* This conversion was added in GLSL 1.20.  If the compilation mode is
116    * GLSL 1.10, the conversion is skipped.
117    */
118   if (state->language_version < 120)
119      return false;
120
121   /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
122    *
123    *    "There are no implicit array or structure conversions. For
124    *    example, an array of int cannot be implicitly converted to an
125    *    array of float. There are no implicit conversions between
126    *    signed and unsigned integers."
127    */
128   /* FINISHME: The above comment is partially a lie.  There is int/uint
129    * FINISHME: conversion for immediate constants.
130    */
131   if (!to->is_float() || !from->type->is_numeric())
132      return false;
133
134   /* Convert to a floating point type with the same number of components
135    * as the original type - i.e. int to float, not int to vec4.
136    */
137   to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
138			        from->type->matrix_columns);
139
140   switch (from->type->base_type) {
141   case GLSL_TYPE_INT:
142      from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
143      break;
144   case GLSL_TYPE_UINT:
145      from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
146      break;
147   case GLSL_TYPE_BOOL:
148      from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
149      break;
150   default:
151      assert(0);
152   }
153
154   return true;
155}
156
157
158static const struct glsl_type *
159arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
160		       bool multiply,
161		       struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
162{
163   const glsl_type *type_a = value_a->type;
164   const glsl_type *type_b = value_b->type;
165
166   /* From GLSL 1.50 spec, page 56:
167    *
168    *    "The arithmetic binary operators add (+), subtract (-),
169    *    multiply (*), and divide (/) operate on integer and
170    *    floating-point scalars, vectors, and matrices."
171    */
172   if (!type_a->is_numeric() || !type_b->is_numeric()) {
173      _mesa_glsl_error(loc, state,
174		       "Operands to arithmetic operators must be numeric");
175      return glsl_type::error_type;
176   }
177
178
179   /*    "If one operand is floating-point based and the other is
180    *    not, then the conversions from Section 4.1.10 "Implicit
181    *    Conversions" are applied to the non-floating-point-based operand."
182    */
183   if (!apply_implicit_conversion(type_a, value_b, state)
184       && !apply_implicit_conversion(type_b, value_a, state)) {
185      _mesa_glsl_error(loc, state,
186		       "Could not implicitly convert operands to "
187		       "arithmetic operator");
188      return glsl_type::error_type;
189   }
190   type_a = value_a->type;
191   type_b = value_b->type;
192
193   /*    "If the operands are integer types, they must both be signed or
194    *    both be unsigned."
195    *
196    * From this rule and the preceeding conversion it can be inferred that
197    * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
198    * The is_numeric check above already filtered out the case where either
199    * type is not one of these, so now the base types need only be tested for
200    * equality.
201    */
202   if (type_a->base_type != type_b->base_type) {
203      _mesa_glsl_error(loc, state,
204		       "base type mismatch for arithmetic operator");
205      return glsl_type::error_type;
206   }
207
208   /*    "All arithmetic binary operators result in the same fundamental type
209    *    (signed integer, unsigned integer, or floating-point) as the
210    *    operands they operate on, after operand type conversion. After
211    *    conversion, the following cases are valid
212    *
213    *    * The two operands are scalars. In this case the operation is
214    *      applied, resulting in a scalar."
215    */
216   if (type_a->is_scalar() && type_b->is_scalar())
217      return type_a;
218
219   /*   "* One operand is a scalar, and the other is a vector or matrix.
220    *      In this case, the scalar operation is applied independently to each
221    *      component of the vector or matrix, resulting in the same size
222    *      vector or matrix."
223    */
224   if (type_a->is_scalar()) {
225      if (!type_b->is_scalar())
226	 return type_b;
227   } else if (type_b->is_scalar()) {
228      return type_a;
229   }
230
231   /* All of the combinations of <scalar, scalar>, <vector, scalar>,
232    * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
233    * handled.
234    */
235   assert(!type_a->is_scalar());
236   assert(!type_b->is_scalar());
237
238   /*   "* The two operands are vectors of the same size. In this case, the
239    *      operation is done component-wise resulting in the same size
240    *      vector."
241    */
242   if (type_a->is_vector() && type_b->is_vector()) {
243      if (type_a == type_b) {
244	 return type_a;
245      } else {
246	 _mesa_glsl_error(loc, state,
247			  "vector size mismatch for arithmetic operator");
248	 return glsl_type::error_type;
249      }
250   }
251
252   /* All of the combinations of <scalar, scalar>, <vector, scalar>,
253    * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
254    * <vector, vector> have been handled.  At least one of the operands must
255    * be matrix.  Further, since there are no integer matrix types, the base
256    * type of both operands must be float.
257    */
258   assert(type_a->is_matrix() || type_b->is_matrix());
259   assert(type_a->base_type == GLSL_TYPE_FLOAT);
260   assert(type_b->base_type == GLSL_TYPE_FLOAT);
261
262   /*   "* The operator is add (+), subtract (-), or divide (/), and the
263    *      operands are matrices with the same number of rows and the same
264    *      number of columns. In this case, the operation is done component-
265    *      wise resulting in the same size matrix."
266    *    * The operator is multiply (*), where both operands are matrices or
267    *      one operand is a vector and the other a matrix. A right vector
268    *      operand is treated as a column vector and a left vector operand as a
269    *      row vector. In all these cases, it is required that the number of
270    *      columns of the left operand is equal to the number of rows of the
271    *      right operand. Then, the multiply (*) operation does a linear
272    *      algebraic multiply, yielding an object that has the same number of
273    *      rows as the left operand and the same number of columns as the right
274    *      operand. Section 5.10 "Vector and Matrix Operations" explains in
275    *      more detail how vectors and matrices are operated on."
276    */
277   if (! multiply) {
278      if (type_a == type_b)
279	 return type_a;
280   } else {
281      if (type_a->is_matrix() && type_b->is_matrix()) {
282	 /* Matrix multiply.  The columns of A must match the rows of B.  Given
283	  * the other previously tested constraints, this means the vector type
284	  * of a row from A must be the same as the vector type of a column from
285	  * B.
286	  */
287	 if (type_a->row_type() == type_b->column_type()) {
288	    /* The resulting matrix has the number of columns of matrix B and
289	     * the number of rows of matrix A.  We get the row count of A by
290	     * looking at the size of a vector that makes up a column.  The
291	     * transpose (size of a row) is done for B.
292	     */
293	    const glsl_type *const type =
294	       glsl_type::get_instance(type_a->base_type,
295				       type_a->column_type()->vector_elements,
296				       type_b->row_type()->vector_elements);
297	    assert(type != glsl_type::error_type);
298
299	    return type;
300	 }
301      } else if (type_a->is_matrix()) {
302	 /* A is a matrix and B is a column vector.  Columns of A must match
303	  * rows of B.  Given the other previously tested constraints, this
304	  * means the vector type of a row from A must be the same as the
305	  * vector the type of B.
306	  */
307	 if (type_a->row_type() == type_b) {
308	    /* The resulting vector has a number of elements equal to
309	     * the number of rows of matrix A. */
310	    const glsl_type *const type =
311	       glsl_type::get_instance(type_a->base_type,
312				       type_a->column_type()->vector_elements,
313				       1);
314	    assert(type != glsl_type::error_type);
315
316	    return type;
317	 }
318      } else {
319	 assert(type_b->is_matrix());
320
321	 /* A is a row vector and B is a matrix.  Columns of A must match rows
322	  * of B.  Given the other previously tested constraints, this means
323	  * the type of A must be the same as the vector type of a column from
324	  * B.
325	  */
326	 if (type_a == type_b->column_type()) {
327	    /* The resulting vector has a number of elements equal to
328	     * the number of columns of matrix B. */
329	    const glsl_type *const type =
330	       glsl_type::get_instance(type_a->base_type,
331				       type_b->row_type()->vector_elements,
332				       1);
333	    assert(type != glsl_type::error_type);
334
335	    return type;
336	 }
337      }
338
339      _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
340      return glsl_type::error_type;
341   }
342
343
344   /*    "All other cases are illegal."
345    */
346   _mesa_glsl_error(loc, state, "type mismatch");
347   return glsl_type::error_type;
348}
349
350
351static const struct glsl_type *
352unary_arithmetic_result_type(const struct glsl_type *type,
353			     struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
354{
355   /* From GLSL 1.50 spec, page 57:
356    *
357    *    "The arithmetic unary operators negate (-), post- and pre-increment
358    *     and decrement (-- and ++) operate on integer or floating-point
359    *     values (including vectors and matrices). All unary operators work
360    *     component-wise on their operands. These result with the same type
361    *     they operated on."
362    */
363   if (!type->is_numeric()) {
364      _mesa_glsl_error(loc, state,
365		       "Operands to arithmetic operators must be numeric");
366      return glsl_type::error_type;
367   }
368
369   return type;
370}
371
372/**
373 * \brief Return the result type of a bit-logic operation.
374 *
375 * If the given types to the bit-logic operator are invalid, return
376 * glsl_type::error_type.
377 *
378 * \param type_a Type of LHS of bit-logic op
379 * \param type_b Type of RHS of bit-logic op
380 */
381static const struct glsl_type *
382bit_logic_result_type(const struct glsl_type *type_a,
383                      const struct glsl_type *type_b,
384                      ast_operators op,
385                      struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
386{
387    if (state->language_version < 130) {
388       _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
389       return glsl_type::error_type;
390    }
391
392    /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
393     *
394     *     "The bitwise operators and (&), exclusive-or (^), and inclusive-or
395     *     (|). The operands must be of type signed or unsigned integers or
396     *     integer vectors."
397     */
398    if (!type_a->is_integer()) {
399       _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
400                         ast_expression::operator_string(op));
401       return glsl_type::error_type;
402    }
403    if (!type_b->is_integer()) {
404       _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
405                        ast_expression::operator_string(op));
406       return glsl_type::error_type;
407    }
408
409    /*     "The fundamental types of the operands (signed or unsigned) must
410     *     match,"
411     */
412    if (type_a->base_type != type_b->base_type) {
413       _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
414                        "base type", ast_expression::operator_string(op));
415       return glsl_type::error_type;
416    }
417
418    /*     "The operands cannot be vectors of differing size." */
419    if (type_a->is_vector() &&
420        type_b->is_vector() &&
421        type_a->vector_elements != type_b->vector_elements) {
422       _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
423                        "different sizes", ast_expression::operator_string(op));
424       return glsl_type::error_type;
425    }
426
427    /*     "If one operand is a scalar and the other a vector, the scalar is
428     *     applied component-wise to the vector, resulting in the same type as
429     *     the vector. The fundamental types of the operands [...] will be the
430     *     resulting fundamental type."
431     */
432    if (type_a->is_scalar())
433        return type_b;
434    else
435        return type_a;
436}
437
438static const struct glsl_type *
439modulus_result_type(const struct glsl_type *type_a,
440		    const struct glsl_type *type_b,
441		    struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
442{
443   if (state->language_version < 130) {
444      _mesa_glsl_error(loc, state,
445                       "operator '%%' is reserved in %s",
446                       state->version_string);
447      return glsl_type::error_type;
448   }
449
450   /* From GLSL 1.50 spec, page 56:
451    *    "The operator modulus (%) operates on signed or unsigned integers or
452    *    integer vectors. The operand types must both be signed or both be
453    *    unsigned."
454    */
455   if (!type_a->is_integer()) {
456      _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer.");
457      return glsl_type::error_type;
458   }
459   if (!type_b->is_integer()) {
460      _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer.");
461      return glsl_type::error_type;
462   }
463   if (type_a->base_type != type_b->base_type) {
464      _mesa_glsl_error(loc, state,
465		       "operands of %% must have the same base type");
466      return glsl_type::error_type;
467   }
468
469   /*    "The operands cannot be vectors of differing size. If one operand is
470    *    a scalar and the other vector, then the scalar is applied component-
471    *    wise to the vector, resulting in the same type as the vector. If both
472    *    are vectors of the same size, the result is computed component-wise."
473    */
474   if (type_a->is_vector()) {
475      if (!type_b->is_vector()
476	  || (type_a->vector_elements == type_b->vector_elements))
477	 return type_a;
478   } else
479      return type_b;
480
481   /*    "The operator modulus (%) is not defined for any other data types
482    *    (non-integer types)."
483    */
484   _mesa_glsl_error(loc, state, "type mismatch");
485   return glsl_type::error_type;
486}
487
488
489static const struct glsl_type *
490relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
491		       struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
492{
493   const glsl_type *type_a = value_a->type;
494   const glsl_type *type_b = value_b->type;
495
496   /* From GLSL 1.50 spec, page 56:
497    *    "The relational operators greater than (>), less than (<), greater
498    *    than or equal (>=), and less than or equal (<=) operate only on
499    *    scalar integer and scalar floating-point expressions."
500    */
501   if (!type_a->is_numeric()
502       || !type_b->is_numeric()
503       || !type_a->is_scalar()
504       || !type_b->is_scalar()) {
505      _mesa_glsl_error(loc, state,
506		       "Operands to relational operators must be scalar and "
507		       "numeric");
508      return glsl_type::error_type;
509   }
510
511   /*    "Either the operands' types must match, or the conversions from
512    *    Section 4.1.10 "Implicit Conversions" will be applied to the integer
513    *    operand, after which the types must match."
514    */
515   if (!apply_implicit_conversion(type_a, value_b, state)
516       && !apply_implicit_conversion(type_b, value_a, state)) {
517      _mesa_glsl_error(loc, state,
518		       "Could not implicitly convert operands to "
519		       "relational operator");
520      return glsl_type::error_type;
521   }
522   type_a = value_a->type;
523   type_b = value_b->type;
524
525   if (type_a->base_type != type_b->base_type) {
526      _mesa_glsl_error(loc, state, "base type mismatch");
527      return glsl_type::error_type;
528   }
529
530   /*    "The result is scalar Boolean."
531    */
532   return glsl_type::bool_type;
533}
534
535/**
536 * \brief Return the result type of a bit-shift operation.
537 *
538 * If the given types to the bit-shift operator are invalid, return
539 * glsl_type::error_type.
540 *
541 * \param type_a Type of LHS of bit-shift op
542 * \param type_b Type of RHS of bit-shift op
543 */
544static const struct glsl_type *
545shift_result_type(const struct glsl_type *type_a,
546                  const struct glsl_type *type_b,
547                  ast_operators op,
548                  struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
549{
550   if (state->language_version < 130) {
551      _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
552      return glsl_type::error_type;
553   }
554
555   /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
556    *
557    *     "The shift operators (<<) and (>>). For both operators, the operands
558    *     must be signed or unsigned integers or integer vectors. One operand
559    *     can be signed while the other is unsigned."
560    */
561   if (!type_a->is_integer()) {
562      _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
563              "integer vector", ast_expression::operator_string(op));
564     return glsl_type::error_type;
565
566   }
567   if (!type_b->is_integer()) {
568      _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
569              "integer vector", ast_expression::operator_string(op));
570     return glsl_type::error_type;
571   }
572
573   /*     "If the first operand is a scalar, the second operand has to be
574    *     a scalar as well."
575    */
576   if (type_a->is_scalar() && !type_b->is_scalar()) {
577      _mesa_glsl_error(loc, state, "If the first operand of %s is scalar, the "
578              "second must be scalar as well",
579              ast_expression::operator_string(op));
580     return glsl_type::error_type;
581   }
582
583   /* If both operands are vectors, check that they have same number of
584    * elements.
585    */
586   if (type_a->is_vector() &&
587      type_b->is_vector() &&
588      type_a->vector_elements != type_b->vector_elements) {
589      _mesa_glsl_error(loc, state, "Vector operands to operator %s must "
590              "have same number of elements",
591              ast_expression::operator_string(op));
592     return glsl_type::error_type;
593   }
594
595   /*     "In all cases, the resulting type will be the same type as the left
596    *     operand."
597    */
598   return type_a;
599}
600
601/**
602 * Validates that a value can be assigned to a location with a specified type
603 *
604 * Validates that \c rhs can be assigned to some location.  If the types are
605 * not an exact match but an automatic conversion is possible, \c rhs will be
606 * converted.
607 *
608 * \return
609 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
610 * Otherwise the actual RHS to be assigned will be returned.  This may be
611 * \c rhs, or it may be \c rhs after some type conversion.
612 *
613 * \note
614 * In addition to being used for assignments, this function is used to
615 * type-check return values.
616 */
617ir_rvalue *
618validate_assignment(struct _mesa_glsl_parse_state *state,
619		    const glsl_type *lhs_type, ir_rvalue *rhs,
620		    bool is_initializer)
621{
622   /* If there is already some error in the RHS, just return it.  Anything
623    * else will lead to an avalanche of error message back to the user.
624    */
625   if (rhs->type->is_error())
626      return rhs;
627
628   /* If the types are identical, the assignment can trivially proceed.
629    */
630   if (rhs->type == lhs_type)
631      return rhs;
632
633   /* If the array element types are the same and the size of the LHS is zero,
634    * the assignment is okay for initializers embedded in variable
635    * declarations.
636    *
637    * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
638    * is handled by ir_dereference::is_lvalue.
639    */
640   if (is_initializer && lhs_type->is_array() && rhs->type->is_array()
641       && (lhs_type->element_type() == rhs->type->element_type())
642       && (lhs_type->array_size() == 0)) {
643      return rhs;
644   }
645
646   /* Check for implicit conversion in GLSL 1.20 */
647   if (apply_implicit_conversion(lhs_type, rhs, state)) {
648      if (rhs->type == lhs_type)
649	 return rhs;
650   }
651
652   return NULL;
653}
654
655static void
656mark_whole_array_access(ir_rvalue *access)
657{
658   ir_dereference_variable *deref = access->as_dereference_variable();
659
660   if (deref && deref->var) {
661      deref->var->max_array_access = deref->type->length - 1;
662   }
663}
664
665ir_rvalue *
666do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
667	      const char *non_lvalue_description,
668	      ir_rvalue *lhs, ir_rvalue *rhs, bool is_initializer,
669	      YYLTYPE lhs_loc)
670{
671   void *ctx = state;
672   bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
673
674   if (!error_emitted) {
675      if (non_lvalue_description != NULL) {
676         _mesa_glsl_error(&lhs_loc, state,
677                          "assignment to %s",
678			  non_lvalue_description);
679	 error_emitted = true;
680      } else if (lhs->variable_referenced() != NULL
681		 && lhs->variable_referenced()->read_only) {
682         _mesa_glsl_error(&lhs_loc, state,
683                          "assignment to read-only variable '%s'",
684                          lhs->variable_referenced()->name);
685         error_emitted = true;
686
687      } else if (state->language_version <= 110 && lhs->type->is_array()) {
688	 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
689	  *
690	  *    "Other binary or unary expressions, non-dereferenced
691	  *     arrays, function names, swizzles with repeated fields,
692	  *     and constants cannot be l-values."
693	  */
694	 _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
695			  "allowed in GLSL 1.10 or GLSL ES 1.00.");
696	 error_emitted = true;
697      } else if (!lhs->is_lvalue()) {
698	 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
699	 error_emitted = true;
700      }
701   }
702
703   ir_rvalue *new_rhs =
704      validate_assignment(state, lhs->type, rhs, is_initializer);
705   if (new_rhs == NULL) {
706      _mesa_glsl_error(& lhs_loc, state, "type mismatch");
707   } else {
708      rhs = new_rhs;
709
710      /* If the LHS array was not declared with a size, it takes it size from
711       * the RHS.  If the LHS is an l-value and a whole array, it must be a
712       * dereference of a variable.  Any other case would require that the LHS
713       * is either not an l-value or not a whole array.
714       */
715      if (lhs->type->array_size() == 0) {
716	 ir_dereference *const d = lhs->as_dereference();
717
718	 assert(d != NULL);
719
720	 ir_variable *const var = d->variable_referenced();
721
722	 assert(var != NULL);
723
724	 if (var->max_array_access >= unsigned(rhs->type->array_size())) {
725	    /* FINISHME: This should actually log the location of the RHS. */
726	    _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
727			     "previous access",
728			     var->max_array_access);
729	 }
730
731	 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
732						   rhs->type->array_size());
733	 d->type = var->type;
734      }
735      mark_whole_array_access(rhs);
736      mark_whole_array_access(lhs);
737   }
738
739   /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
740    * but not post_inc) need the converted assigned value as an rvalue
741    * to handle things like:
742    *
743    * i = j += 1;
744    *
745    * So we always just store the computed value being assigned to a
746    * temporary and return a deref of that temporary.  If the rvalue
747    * ends up not being used, the temp will get copy-propagated out.
748    */
749   ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
750					   ir_var_temporary);
751   ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
752   instructions->push_tail(var);
753   instructions->push_tail(new(ctx) ir_assignment(deref_var,
754						  rhs,
755						  NULL));
756   deref_var = new(ctx) ir_dereference_variable(var);
757
758   if (!error_emitted)
759      instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
760
761   return new(ctx) ir_dereference_variable(var);
762}
763
764static ir_rvalue *
765get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
766{
767   void *ctx = ralloc_parent(lvalue);
768   ir_variable *var;
769
770   var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
771			      ir_var_temporary);
772   instructions->push_tail(var);
773   var->mode = ir_var_auto;
774
775   instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
776						  lvalue, NULL));
777
778   return new(ctx) ir_dereference_variable(var);
779}
780
781
782ir_rvalue *
783ast_node::hir(exec_list *instructions,
784	      struct _mesa_glsl_parse_state *state)
785{
786   (void) instructions;
787   (void) state;
788
789   return NULL;
790}
791
792static ir_rvalue *
793do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
794{
795   int join_op;
796   ir_rvalue *cmp = NULL;
797
798   if (operation == ir_binop_all_equal)
799      join_op = ir_binop_logic_and;
800   else
801      join_op = ir_binop_logic_or;
802
803   switch (op0->type->base_type) {
804   case GLSL_TYPE_FLOAT:
805   case GLSL_TYPE_UINT:
806   case GLSL_TYPE_INT:
807   case GLSL_TYPE_BOOL:
808      return new(mem_ctx) ir_expression(operation, op0, op1);
809
810   case GLSL_TYPE_ARRAY: {
811      for (unsigned int i = 0; i < op0->type->length; i++) {
812	 ir_rvalue *e0, *e1, *result;
813
814	 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
815						new(mem_ctx) ir_constant(i));
816	 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
817						new(mem_ctx) ir_constant(i));
818	 result = do_comparison(mem_ctx, operation, e0, e1);
819
820	 if (cmp) {
821	    cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
822	 } else {
823	    cmp = result;
824	 }
825      }
826
827      mark_whole_array_access(op0);
828      mark_whole_array_access(op1);
829      break;
830   }
831
832   case GLSL_TYPE_STRUCT: {
833      for (unsigned int i = 0; i < op0->type->length; i++) {
834	 ir_rvalue *e0, *e1, *result;
835	 const char *field_name = op0->type->fields.structure[i].name;
836
837	 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
838						 field_name);
839	 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
840						 field_name);
841	 result = do_comparison(mem_ctx, operation, e0, e1);
842
843	 if (cmp) {
844	    cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
845	 } else {
846	    cmp = result;
847	 }
848      }
849      break;
850   }
851
852   case GLSL_TYPE_ERROR:
853   case GLSL_TYPE_VOID:
854   case GLSL_TYPE_SAMPLER:
855      /* I assume a comparison of a struct containing a sampler just
856       * ignores the sampler present in the type.
857       */
858      break;
859
860   default:
861      assert(!"Should not get here.");
862      break;
863   }
864
865   if (cmp == NULL)
866      cmp = new(mem_ctx) ir_constant(true);
867
868   return cmp;
869}
870
871/* For logical operations, we want to ensure that the operands are
872 * scalar booleans.  If it isn't, emit an error and return a constant
873 * boolean to avoid triggering cascading error messages.
874 */
875ir_rvalue *
876get_scalar_boolean_operand(exec_list *instructions,
877			   struct _mesa_glsl_parse_state *state,
878			   ast_expression *parent_expr,
879			   int operand,
880			   const char *operand_name,
881			   bool *error_emitted)
882{
883   ast_expression *expr = parent_expr->subexpressions[operand];
884   void *ctx = state;
885   ir_rvalue *val = expr->hir(instructions, state);
886
887   if (val->type->is_boolean() && val->type->is_scalar())
888      return val;
889
890   if (!*error_emitted) {
891      YYLTYPE loc = expr->get_location();
892      _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
893		       operand_name,
894		       parent_expr->operator_string(parent_expr->oper));
895      *error_emitted = true;
896   }
897
898   return new(ctx) ir_constant(true);
899}
900
901/**
902 * If name refers to a builtin array whose maximum allowed size is less than
903 * size, report an error and return true.  Otherwise return false.
904 */
905static bool
906check_builtin_array_max_size(const char *name, unsigned size,
907                             YYLTYPE loc, struct _mesa_glsl_parse_state *state)
908{
909   if ((strcmp("gl_TexCoord", name) == 0)
910       && (size > state->Const.MaxTextureCoords)) {
911      /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
912       *
913       *     "The size [of gl_TexCoord] can be at most
914       *     gl_MaxTextureCoords."
915       */
916      _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
917                       "be larger than gl_MaxTextureCoords (%u)\n",
918                       state->Const.MaxTextureCoords);
919      return true;
920   } else if (strcmp("gl_ClipDistance", name) == 0
921              && size > state->Const.MaxClipPlanes) {
922      /* From section 7.1 (Vertex Shader Special Variables) of the
923       * GLSL 1.30 spec:
924       *
925       *   "The gl_ClipDistance array is predeclared as unsized and
926       *   must be sized by the shader either redeclaring it with a
927       *   size or indexing it only with integral constant
928       *   expressions. ... The size can be at most
929       *   gl_MaxClipDistances."
930       */
931      _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
932                       "be larger than gl_MaxClipDistances (%u)\n",
933                       state->Const.MaxClipPlanes);
934      return true;
935   }
936   return false;
937}
938
939/**
940 * Create the constant 1, of a which is appropriate for incrementing and
941 * decrementing values of the given GLSL type.  For example, if type is vec4,
942 * this creates a constant value of 1.0 having type float.
943 *
944 * If the given type is invalid for increment and decrement operators, return
945 * a floating point 1--the error will be detected later.
946 */
947static ir_rvalue *
948constant_one_for_inc_dec(void *ctx, const glsl_type *type)
949{
950   switch (type->base_type) {
951   case GLSL_TYPE_UINT:
952      return new(ctx) ir_constant((unsigned) 1);
953   case GLSL_TYPE_INT:
954      return new(ctx) ir_constant(1);
955   default:
956   case GLSL_TYPE_FLOAT:
957      return new(ctx) ir_constant(1.0f);
958   }
959}
960
961ir_rvalue *
962ast_expression::hir(exec_list *instructions,
963		    struct _mesa_glsl_parse_state *state)
964{
965   void *ctx = state;
966   static const int operations[AST_NUM_OPERATORS] = {
967      -1,               /* ast_assign doesn't convert to ir_expression. */
968      -1,               /* ast_plus doesn't convert to ir_expression. */
969      ir_unop_neg,
970      ir_binop_add,
971      ir_binop_sub,
972      ir_binop_mul,
973      ir_binop_div,
974      ir_binop_mod,
975      ir_binop_lshift,
976      ir_binop_rshift,
977      ir_binop_less,
978      ir_binop_greater,
979      ir_binop_lequal,
980      ir_binop_gequal,
981      ir_binop_all_equal,
982      ir_binop_any_nequal,
983      ir_binop_bit_and,
984      ir_binop_bit_xor,
985      ir_binop_bit_or,
986      ir_unop_bit_not,
987      ir_binop_logic_and,
988      ir_binop_logic_xor,
989      ir_binop_logic_or,
990      ir_unop_logic_not,
991
992      /* Note: The following block of expression types actually convert
993       * to multiple IR instructions.
994       */
995      ir_binop_mul,     /* ast_mul_assign */
996      ir_binop_div,     /* ast_div_assign */
997      ir_binop_mod,     /* ast_mod_assign */
998      ir_binop_add,     /* ast_add_assign */
999      ir_binop_sub,     /* ast_sub_assign */
1000      ir_binop_lshift,  /* ast_ls_assign */
1001      ir_binop_rshift,  /* ast_rs_assign */
1002      ir_binop_bit_and, /* ast_and_assign */
1003      ir_binop_bit_xor, /* ast_xor_assign */
1004      ir_binop_bit_or,  /* ast_or_assign */
1005
1006      -1,               /* ast_conditional doesn't convert to ir_expression. */
1007      ir_binop_add,     /* ast_pre_inc. */
1008      ir_binop_sub,     /* ast_pre_dec. */
1009      ir_binop_add,     /* ast_post_inc. */
1010      ir_binop_sub,     /* ast_post_dec. */
1011      -1,               /* ast_field_selection doesn't conv to ir_expression. */
1012      -1,               /* ast_array_index doesn't convert to ir_expression. */
1013      -1,               /* ast_function_call doesn't conv to ir_expression. */
1014      -1,               /* ast_identifier doesn't convert to ir_expression. */
1015      -1,               /* ast_int_constant doesn't convert to ir_expression. */
1016      -1,               /* ast_uint_constant doesn't conv to ir_expression. */
1017      -1,               /* ast_float_constant doesn't conv to ir_expression. */
1018      -1,               /* ast_bool_constant doesn't conv to ir_expression. */
1019      -1,               /* ast_sequence doesn't convert to ir_expression. */
1020   };
1021   ir_rvalue *result = NULL;
1022   ir_rvalue *op[3];
1023   const struct glsl_type *type; /* a temporary variable for switch cases */
1024   bool error_emitted = false;
1025   YYLTYPE loc;
1026
1027   loc = this->get_location();
1028
1029   switch (this->oper) {
1030   case ast_assign: {
1031      op[0] = this->subexpressions[0]->hir(instructions, state);
1032      op[1] = this->subexpressions[1]->hir(instructions, state);
1033
1034      result = do_assignment(instructions, state,
1035			     this->subexpressions[0]->non_lvalue_description,
1036			     op[0], op[1], false,
1037			     this->subexpressions[0]->get_location());
1038      error_emitted = result->type->is_error();
1039      break;
1040   }
1041
1042   case ast_plus:
1043      op[0] = this->subexpressions[0]->hir(instructions, state);
1044
1045      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1046
1047      error_emitted = type->is_error();
1048
1049      result = op[0];
1050      break;
1051
1052   case ast_neg:
1053      op[0] = this->subexpressions[0]->hir(instructions, state);
1054
1055      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1056
1057      error_emitted = type->is_error();
1058
1059      result = new(ctx) ir_expression(operations[this->oper], type,
1060				      op[0], NULL);
1061      break;
1062
1063   case ast_add:
1064   case ast_sub:
1065   case ast_mul:
1066   case ast_div:
1067      op[0] = this->subexpressions[0]->hir(instructions, state);
1068      op[1] = this->subexpressions[1]->hir(instructions, state);
1069
1070      type = arithmetic_result_type(op[0], op[1],
1071				    (this->oper == ast_mul),
1072				    state, & loc);
1073      error_emitted = type->is_error();
1074
1075      result = new(ctx) ir_expression(operations[this->oper], type,
1076				      op[0], op[1]);
1077      break;
1078
1079   case ast_mod:
1080      op[0] = this->subexpressions[0]->hir(instructions, state);
1081      op[1] = this->subexpressions[1]->hir(instructions, state);
1082
1083      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1084
1085      assert(operations[this->oper] == ir_binop_mod);
1086
1087      result = new(ctx) ir_expression(operations[this->oper], type,
1088				      op[0], op[1]);
1089      error_emitted = type->is_error();
1090      break;
1091
1092   case ast_lshift:
1093   case ast_rshift:
1094       if (state->language_version < 130) {
1095          _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
1096              operator_string(this->oper));
1097          error_emitted = true;
1098       }
1099
1100       op[0] = this->subexpressions[0]->hir(instructions, state);
1101       op[1] = this->subexpressions[1]->hir(instructions, state);
1102       type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1103                                &loc);
1104       result = new(ctx) ir_expression(operations[this->oper], type,
1105                                       op[0], op[1]);
1106       error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1107       break;
1108
1109   case ast_less:
1110   case ast_greater:
1111   case ast_lequal:
1112   case ast_gequal:
1113      op[0] = this->subexpressions[0]->hir(instructions, state);
1114      op[1] = this->subexpressions[1]->hir(instructions, state);
1115
1116      type = relational_result_type(op[0], op[1], state, & loc);
1117
1118      /* The relational operators must either generate an error or result
1119       * in a scalar boolean.  See page 57 of the GLSL 1.50 spec.
1120       */
1121      assert(type->is_error()
1122	     || ((type->base_type == GLSL_TYPE_BOOL)
1123		 && type->is_scalar()));
1124
1125      result = new(ctx) ir_expression(operations[this->oper], type,
1126				      op[0], op[1]);
1127      error_emitted = type->is_error();
1128      break;
1129
1130   case ast_nequal:
1131   case ast_equal:
1132      op[0] = this->subexpressions[0]->hir(instructions, state);
1133      op[1] = this->subexpressions[1]->hir(instructions, state);
1134
1135      /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1136       *
1137       *    "The equality operators equal (==), and not equal (!=)
1138       *    operate on all types. They result in a scalar Boolean. If
1139       *    the operand types do not match, then there must be a
1140       *    conversion from Section 4.1.10 "Implicit Conversions"
1141       *    applied to one operand that can make them match, in which
1142       *    case this conversion is done."
1143       */
1144      if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1145	   && !apply_implicit_conversion(op[1]->type, op[0], state))
1146	  || (op[0]->type != op[1]->type)) {
1147	 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1148			  "type", (this->oper == ast_equal) ? "==" : "!=");
1149	 error_emitted = true;
1150      } else if ((state->language_version <= 110)
1151		 && (op[0]->type->is_array() || op[1]->type->is_array())) {
1152	 _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
1153			  "GLSL 1.10");
1154	 error_emitted = true;
1155      }
1156
1157      if (error_emitted) {
1158	 result = new(ctx) ir_constant(false);
1159      } else {
1160	 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1161	 assert(result->type == glsl_type::bool_type);
1162      }
1163      break;
1164
1165   case ast_bit_and:
1166   case ast_bit_xor:
1167   case ast_bit_or:
1168      op[0] = this->subexpressions[0]->hir(instructions, state);
1169      op[1] = this->subexpressions[1]->hir(instructions, state);
1170      type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1171                                   state, &loc);
1172      result = new(ctx) ir_expression(operations[this->oper], type,
1173				      op[0], op[1]);
1174      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1175      break;
1176
1177   case ast_bit_not:
1178      op[0] = this->subexpressions[0]->hir(instructions, state);
1179
1180      if (state->language_version < 130) {
1181	 _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
1182	 error_emitted = true;
1183      }
1184
1185      if (!op[0]->type->is_integer()) {
1186	 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1187	 error_emitted = true;
1188      }
1189
1190      type = error_emitted ? glsl_type::error_type : op[0]->type;
1191      result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1192      break;
1193
1194   case ast_logic_and: {
1195      exec_list rhs_instructions;
1196      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1197					 "LHS", &error_emitted);
1198      op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1199					 "RHS", &error_emitted);
1200
1201      ir_constant *op0_const = op[0]->constant_expression_value();
1202      if (op0_const) {
1203	 if (op0_const->value.b[0]) {
1204	    instructions->append_list(&rhs_instructions);
1205	    result = op[1];
1206	 } else {
1207	    result = op0_const;
1208	 }
1209	 type = glsl_type::bool_type;
1210      } else {
1211	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1212						       "and_tmp",
1213						       ir_var_temporary);
1214	 instructions->push_tail(tmp);
1215
1216	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1217	 instructions->push_tail(stmt);
1218
1219	 stmt->then_instructions.append_list(&rhs_instructions);
1220	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1221	 ir_assignment *const then_assign =
1222	    new(ctx) ir_assignment(then_deref, op[1], NULL);
1223	 stmt->then_instructions.push_tail(then_assign);
1224
1225	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1226	 ir_assignment *const else_assign =
1227	    new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
1228	 stmt->else_instructions.push_tail(else_assign);
1229
1230	 result = new(ctx) ir_dereference_variable(tmp);
1231	 type = tmp->type;
1232      }
1233      break;
1234   }
1235
1236   case ast_logic_or: {
1237      exec_list rhs_instructions;
1238      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1239					 "LHS", &error_emitted);
1240      op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1241					 "RHS", &error_emitted);
1242
1243      ir_constant *op0_const = op[0]->constant_expression_value();
1244      if (op0_const) {
1245	 if (op0_const->value.b[0]) {
1246	    result = op0_const;
1247	 } else {
1248	    result = op[1];
1249	 }
1250	 type = glsl_type::bool_type;
1251      } else {
1252	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1253						       "or_tmp",
1254						       ir_var_temporary);
1255	 instructions->push_tail(tmp);
1256
1257	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1258	 instructions->push_tail(stmt);
1259
1260	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1261	 ir_assignment *const then_assign =
1262	    new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
1263	 stmt->then_instructions.push_tail(then_assign);
1264
1265	 stmt->else_instructions.append_list(&rhs_instructions);
1266	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1267	 ir_assignment *const else_assign =
1268	    new(ctx) ir_assignment(else_deref, op[1], NULL);
1269	 stmt->else_instructions.push_tail(else_assign);
1270
1271	 result = new(ctx) ir_dereference_variable(tmp);
1272	 type = tmp->type;
1273      }
1274      break;
1275   }
1276
1277   case ast_logic_xor:
1278      /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1279       *
1280       *    "The logical binary operators and (&&), or ( | | ), and
1281       *     exclusive or (^^). They operate only on two Boolean
1282       *     expressions and result in a Boolean expression."
1283       */
1284      op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1285					 &error_emitted);
1286      op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1287					 &error_emitted);
1288
1289      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1290				      op[0], op[1]);
1291      break;
1292
1293   case ast_logic_not:
1294      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1295					 "operand", &error_emitted);
1296
1297      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1298				      op[0], NULL);
1299      break;
1300
1301   case ast_mul_assign:
1302   case ast_div_assign:
1303   case ast_add_assign:
1304   case ast_sub_assign: {
1305      op[0] = this->subexpressions[0]->hir(instructions, state);
1306      op[1] = this->subexpressions[1]->hir(instructions, state);
1307
1308      type = arithmetic_result_type(op[0], op[1],
1309				    (this->oper == ast_mul_assign),
1310				    state, & loc);
1311
1312      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1313						   op[0], op[1]);
1314
1315      result = do_assignment(instructions, state,
1316			     this->subexpressions[0]->non_lvalue_description,
1317			     op[0]->clone(ctx, NULL), temp_rhs, false,
1318			     this->subexpressions[0]->get_location());
1319      error_emitted = (op[0]->type->is_error());
1320
1321      /* GLSL 1.10 does not allow array assignment.  However, we don't have to
1322       * explicitly test for this because none of the binary expression
1323       * operators allow array operands either.
1324       */
1325
1326      break;
1327   }
1328
1329   case ast_mod_assign: {
1330      op[0] = this->subexpressions[0]->hir(instructions, state);
1331      op[1] = this->subexpressions[1]->hir(instructions, state);
1332
1333      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1334
1335      assert(operations[this->oper] == ir_binop_mod);
1336
1337      ir_rvalue *temp_rhs;
1338      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1339					op[0], op[1]);
1340
1341      result = do_assignment(instructions, state,
1342			     this->subexpressions[0]->non_lvalue_description,
1343			     op[0]->clone(ctx, NULL), temp_rhs, false,
1344			     this->subexpressions[0]->get_location());
1345      error_emitted = type->is_error();
1346      break;
1347   }
1348
1349   case ast_ls_assign:
1350   case ast_rs_assign: {
1351      op[0] = this->subexpressions[0]->hir(instructions, state);
1352      op[1] = this->subexpressions[1]->hir(instructions, state);
1353      type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1354                               &loc);
1355      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1356                                                   type, op[0], op[1]);
1357      result = do_assignment(instructions, state,
1358			     this->subexpressions[0]->non_lvalue_description,
1359			     op[0]->clone(ctx, NULL), temp_rhs, false,
1360                             this->subexpressions[0]->get_location());
1361      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1362      break;
1363   }
1364
1365   case ast_and_assign:
1366   case ast_xor_assign:
1367   case ast_or_assign: {
1368      op[0] = this->subexpressions[0]->hir(instructions, state);
1369      op[1] = this->subexpressions[1]->hir(instructions, state);
1370      type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1371                                   state, &loc);
1372      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1373                                                   type, op[0], op[1]);
1374      result = do_assignment(instructions, state,
1375			     this->subexpressions[0]->non_lvalue_description,
1376			     op[0]->clone(ctx, NULL), temp_rhs, false,
1377                             this->subexpressions[0]->get_location());
1378      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1379      break;
1380   }
1381
1382   case ast_conditional: {
1383      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1384       *
1385       *    "The ternary selection operator (?:). It operates on three
1386       *    expressions (exp1 ? exp2 : exp3). This operator evaluates the
1387       *    first expression, which must result in a scalar Boolean."
1388       */
1389      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1390					 "condition", &error_emitted);
1391
1392      /* The :? operator is implemented by generating an anonymous temporary
1393       * followed by an if-statement.  The last instruction in each branch of
1394       * the if-statement assigns a value to the anonymous temporary.  This
1395       * temporary is the r-value of the expression.
1396       */
1397      exec_list then_instructions;
1398      exec_list else_instructions;
1399
1400      op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1401      op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1402
1403      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1404       *
1405       *     "The second and third expressions can be any type, as
1406       *     long their types match, or there is a conversion in
1407       *     Section 4.1.10 "Implicit Conversions" that can be applied
1408       *     to one of the expressions to make their types match. This
1409       *     resulting matching type is the type of the entire
1410       *     expression."
1411       */
1412      if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1413	   && !apply_implicit_conversion(op[2]->type, op[1], state))
1414	  || (op[1]->type != op[2]->type)) {
1415	 YYLTYPE loc = this->subexpressions[1]->get_location();
1416
1417	 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1418			  "operator must have matching types.");
1419	 error_emitted = true;
1420	 type = glsl_type::error_type;
1421      } else {
1422	 type = op[1]->type;
1423      }
1424
1425      /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1426       *
1427       *    "The second and third expressions must be the same type, but can
1428       *    be of any type other than an array."
1429       */
1430      if ((state->language_version <= 110) && type->is_array()) {
1431	 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1432			  "operator must not be arrays.");
1433	 error_emitted = true;
1434      }
1435
1436      ir_constant *cond_val = op[0]->constant_expression_value();
1437      ir_constant *then_val = op[1]->constant_expression_value();
1438      ir_constant *else_val = op[2]->constant_expression_value();
1439
1440      if (then_instructions.is_empty()
1441	  && else_instructions.is_empty()
1442	  && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1443	 result = (cond_val->value.b[0]) ? then_val : else_val;
1444      } else {
1445	 ir_variable *const tmp =
1446	    new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1447	 instructions->push_tail(tmp);
1448
1449	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1450	 instructions->push_tail(stmt);
1451
1452	 then_instructions.move_nodes_to(& stmt->then_instructions);
1453	 ir_dereference *const then_deref =
1454	    new(ctx) ir_dereference_variable(tmp);
1455	 ir_assignment *const then_assign =
1456	    new(ctx) ir_assignment(then_deref, op[1], NULL);
1457	 stmt->then_instructions.push_tail(then_assign);
1458
1459	 else_instructions.move_nodes_to(& stmt->else_instructions);
1460	 ir_dereference *const else_deref =
1461	    new(ctx) ir_dereference_variable(tmp);
1462	 ir_assignment *const else_assign =
1463	    new(ctx) ir_assignment(else_deref, op[2], NULL);
1464	 stmt->else_instructions.push_tail(else_assign);
1465
1466	 result = new(ctx) ir_dereference_variable(tmp);
1467      }
1468      break;
1469   }
1470
1471   case ast_pre_inc:
1472   case ast_pre_dec: {
1473      this->non_lvalue_description = (this->oper == ast_pre_inc)
1474	 ? "pre-increment operation" : "pre-decrement operation";
1475
1476      op[0] = this->subexpressions[0]->hir(instructions, state);
1477      op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1478
1479      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1480
1481      ir_rvalue *temp_rhs;
1482      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1483					op[0], op[1]);
1484
1485      result = do_assignment(instructions, state,
1486			     this->subexpressions[0]->non_lvalue_description,
1487			     op[0]->clone(ctx, NULL), temp_rhs, false,
1488			     this->subexpressions[0]->get_location());
1489      error_emitted = op[0]->type->is_error();
1490      break;
1491   }
1492
1493   case ast_post_inc:
1494   case ast_post_dec: {
1495      this->non_lvalue_description = (this->oper == ast_post_inc)
1496	 ? "post-increment operation" : "post-decrement operation";
1497      op[0] = this->subexpressions[0]->hir(instructions, state);
1498      op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1499
1500      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1501
1502      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1503
1504      ir_rvalue *temp_rhs;
1505      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1506					op[0], op[1]);
1507
1508      /* Get a temporary of a copy of the lvalue before it's modified.
1509       * This may get thrown away later.
1510       */
1511      result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1512
1513      (void)do_assignment(instructions, state,
1514			  this->subexpressions[0]->non_lvalue_description,
1515			  op[0]->clone(ctx, NULL), temp_rhs, false,
1516			  this->subexpressions[0]->get_location());
1517
1518      error_emitted = op[0]->type->is_error();
1519      break;
1520   }
1521
1522   case ast_field_selection:
1523      result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1524      break;
1525
1526   case ast_array_index: {
1527      YYLTYPE index_loc = subexpressions[1]->get_location();
1528
1529      op[0] = subexpressions[0]->hir(instructions, state);
1530      op[1] = subexpressions[1]->hir(instructions, state);
1531
1532      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1533
1534      ir_rvalue *const array = op[0];
1535
1536      result = new(ctx) ir_dereference_array(op[0], op[1]);
1537
1538      /* Do not use op[0] after this point.  Use array.
1539       */
1540      op[0] = NULL;
1541
1542
1543      if (error_emitted)
1544	 break;
1545
1546      if (!array->type->is_array()
1547	  && !array->type->is_matrix()
1548	  && !array->type->is_vector()) {
1549	 _mesa_glsl_error(& index_loc, state,
1550			  "cannot dereference non-array / non-matrix / "
1551			  "non-vector");
1552	 error_emitted = true;
1553      }
1554
1555      if (!op[1]->type->is_integer()) {
1556	 _mesa_glsl_error(& index_loc, state,
1557			  "array index must be integer type");
1558	 error_emitted = true;
1559      } else if (!op[1]->type->is_scalar()) {
1560	 _mesa_glsl_error(& index_loc, state,
1561			  "array index must be scalar");
1562	 error_emitted = true;
1563      }
1564
1565      /* If the array index is a constant expression and the array has a
1566       * declared size, ensure that the access is in-bounds.  If the array
1567       * index is not a constant expression, ensure that the array has a
1568       * declared size.
1569       */
1570      ir_constant *const const_index = op[1]->constant_expression_value();
1571      if (const_index != NULL) {
1572	 const int idx = const_index->value.i[0];
1573	 const char *type_name;
1574	 unsigned bound = 0;
1575
1576	 if (array->type->is_matrix()) {
1577	    type_name = "matrix";
1578	 } else if (array->type->is_vector()) {
1579	    type_name = "vector";
1580	 } else {
1581	    type_name = "array";
1582	 }
1583
1584	 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
1585	  *
1586	  *    "It is illegal to declare an array with a size, and then
1587	  *    later (in the same shader) index the same array with an
1588	  *    integral constant expression greater than or equal to the
1589	  *    declared size. It is also illegal to index an array with a
1590	  *    negative constant expression."
1591	  */
1592	 if (array->type->is_matrix()) {
1593	    if (array->type->row_type()->vector_elements <= idx) {
1594	       bound = array->type->row_type()->vector_elements;
1595	    }
1596	 } else if (array->type->is_vector()) {
1597	    if (array->type->vector_elements <= idx) {
1598	       bound = array->type->vector_elements;
1599	    }
1600	 } else {
1601	    if ((array->type->array_size() > 0)
1602		&& (array->type->array_size() <= idx)) {
1603	       bound = array->type->array_size();
1604	    }
1605	 }
1606
1607	 if (bound > 0) {
1608	    _mesa_glsl_error(& loc, state, "%s index must be < %u",
1609			     type_name, bound);
1610	    error_emitted = true;
1611	 } else if (idx < 0) {
1612	    _mesa_glsl_error(& loc, state, "%s index must be >= 0",
1613			     type_name);
1614	    error_emitted = true;
1615	 }
1616
1617	 if (array->type->is_array()) {
1618	    /* If the array is a variable dereference, it dereferences the
1619	     * whole array, by definition.  Use this to get the variable.
1620	     *
1621	     * FINISHME: Should some methods for getting / setting / testing
1622	     * FINISHME: array access limits be added to ir_dereference?
1623	     */
1624	    ir_variable *const v = array->whole_variable_referenced();
1625	    if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
1626	       v->max_array_access = idx;
1627
1628               /* Check whether this access will, as a side effect, implicitly
1629                * cause the size of a built-in array to be too large.
1630                */
1631               if (check_builtin_array_max_size(v->name, idx+1, loc, state))
1632                  error_emitted = true;
1633            }
1634	 }
1635      } else if (array->type->array_size() == 0) {
1636	 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
1637      } else {
1638	 if (array->type->is_array()) {
1639	    /* whole_variable_referenced can return NULL if the array is a
1640	     * member of a structure.  In this case it is safe to not update
1641	     * the max_array_access field because it is never used for fields
1642	     * of structures.
1643	     */
1644	    ir_variable *v = array->whole_variable_referenced();
1645	    if (v != NULL)
1646	       v->max_array_access = array->type->array_size() - 1;
1647	 }
1648      }
1649
1650      /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
1651       *
1652       *    "Samplers aggregated into arrays within a shader (using square
1653       *    brackets [ ]) can only be indexed with integral constant
1654       *    expressions [...]."
1655       *
1656       * This restriction was added in GLSL 1.30.  Shaders using earlier version
1657       * of the language should not be rejected by the compiler front-end for
1658       * using this construct.  This allows useful things such as using a loop
1659       * counter as the index to an array of samplers.  If the loop in unrolled,
1660       * the code should compile correctly.  Instead, emit a warning.
1661       */
1662      if (array->type->is_array() &&
1663          array->type->element_type()->is_sampler() &&
1664          const_index == NULL) {
1665
1666	 if (state->language_version == 100) {
1667	    _mesa_glsl_warning(&loc, state,
1668			       "sampler arrays indexed with non-constant "
1669			       "expressions is optional in GLSL ES 1.00");
1670	 } else if (state->language_version < 130) {
1671	    _mesa_glsl_warning(&loc, state,
1672			       "sampler arrays indexed with non-constant "
1673			       "expressions is forbidden in GLSL 1.30 and "
1674			       "later");
1675	 } else {
1676	    _mesa_glsl_error(&loc, state,
1677			     "sampler arrays indexed with non-constant "
1678			     "expressions is forbidden in GLSL 1.30 and "
1679			     "later");
1680	    error_emitted = true;
1681	 }
1682      }
1683
1684      if (error_emitted)
1685	 result->type = glsl_type::error_type;
1686
1687      break;
1688   }
1689
1690   case ast_function_call:
1691      /* Should *NEVER* get here.  ast_function_call should always be handled
1692       * by ast_function_expression::hir.
1693       */
1694      assert(0);
1695      break;
1696
1697   case ast_identifier: {
1698      /* ast_identifier can appear several places in a full abstract syntax
1699       * tree.  This particular use must be at location specified in the grammar
1700       * as 'variable_identifier'.
1701       */
1702      ir_variable *var =
1703	 state->symbols->get_variable(this->primary_expression.identifier);
1704
1705      result = new(ctx) ir_dereference_variable(var);
1706
1707      if (var != NULL) {
1708	 var->used = true;
1709      } else {
1710	 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1711			  this->primary_expression.identifier);
1712
1713	 error_emitted = true;
1714      }
1715      break;
1716   }
1717
1718   case ast_int_constant:
1719      result = new(ctx) ir_constant(this->primary_expression.int_constant);
1720      break;
1721
1722   case ast_uint_constant:
1723      result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1724      break;
1725
1726   case ast_float_constant:
1727      result = new(ctx) ir_constant(this->primary_expression.float_constant);
1728      break;
1729
1730   case ast_bool_constant:
1731      result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1732      break;
1733
1734   case ast_sequence: {
1735      /* It should not be possible to generate a sequence in the AST without
1736       * any expressions in it.
1737       */
1738      assert(!this->expressions.is_empty());
1739
1740      /* The r-value of a sequence is the last expression in the sequence.  If
1741       * the other expressions in the sequence do not have side-effects (and
1742       * therefore add instructions to the instruction list), they get dropped
1743       * on the floor.
1744       */
1745      exec_node *previous_tail_pred = NULL;
1746      YYLTYPE previous_operand_loc = loc;
1747
1748      foreach_list_typed (ast_node, ast, link, &this->expressions) {
1749	 /* If one of the operands of comma operator does not generate any
1750	  * code, we want to emit a warning.  At each pass through the loop
1751	  * previous_tail_pred will point to the last instruction in the
1752	  * stream *before* processing the previous operand.  Naturally,
1753	  * instructions->tail_pred will point to the last instruction in the
1754	  * stream *after* processing the previous operand.  If the two
1755	  * pointers match, then the previous operand had no effect.
1756	  *
1757	  * The warning behavior here differs slightly from GCC.  GCC will
1758	  * only emit a warning if none of the left-hand operands have an
1759	  * effect.  However, it will emit a warning for each.  I believe that
1760	  * there are some cases in C (especially with GCC extensions) where
1761	  * it is useful to have an intermediate step in a sequence have no
1762	  * effect, but I don't think these cases exist in GLSL.  Either way,
1763	  * it would be a giant hassle to replicate that behavior.
1764	  */
1765	 if (previous_tail_pred == instructions->tail_pred) {
1766	    _mesa_glsl_warning(&previous_operand_loc, state,
1767			       "left-hand operand of comma expression has "
1768			       "no effect");
1769	 }
1770
1771	 /* tail_pred is directly accessed instead of using the get_tail()
1772	  * method for performance reasons.  get_tail() has extra code to
1773	  * return NULL when the list is empty.  We don't care about that
1774	  * here, so using tail_pred directly is fine.
1775	  */
1776	 previous_tail_pred = instructions->tail_pred;
1777	 previous_operand_loc = ast->get_location();
1778
1779	 result = ast->hir(instructions, state);
1780      }
1781
1782      /* Any errors should have already been emitted in the loop above.
1783       */
1784      error_emitted = true;
1785      break;
1786   }
1787   }
1788   type = NULL; /* use result->type, not type. */
1789   assert(result != NULL);
1790
1791   if (result->type->is_error() && !error_emitted)
1792      _mesa_glsl_error(& loc, state, "type mismatch");
1793
1794   return result;
1795}
1796
1797
1798ir_rvalue *
1799ast_expression_statement::hir(exec_list *instructions,
1800			      struct _mesa_glsl_parse_state *state)
1801{
1802   /* It is possible to have expression statements that don't have an
1803    * expression.  This is the solitary semicolon:
1804    *
1805    * for (i = 0; i < 5; i++)
1806    *     ;
1807    *
1808    * In this case the expression will be NULL.  Test for NULL and don't do
1809    * anything in that case.
1810    */
1811   if (expression != NULL)
1812      expression->hir(instructions, state);
1813
1814   /* Statements do not have r-values.
1815    */
1816   return NULL;
1817}
1818
1819
1820ir_rvalue *
1821ast_compound_statement::hir(exec_list *instructions,
1822			    struct _mesa_glsl_parse_state *state)
1823{
1824   if (new_scope)
1825      state->symbols->push_scope();
1826
1827   foreach_list_typed (ast_node, ast, link, &this->statements)
1828      ast->hir(instructions, state);
1829
1830   if (new_scope)
1831      state->symbols->pop_scope();
1832
1833   /* Compound statements do not have r-values.
1834    */
1835   return NULL;
1836}
1837
1838
1839static const glsl_type *
1840process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
1841		   struct _mesa_glsl_parse_state *state)
1842{
1843   unsigned length = 0;
1844
1845   /* From page 19 (page 25) of the GLSL 1.20 spec:
1846    *
1847    *     "Only one-dimensional arrays may be declared."
1848    */
1849   if (base->is_array()) {
1850      _mesa_glsl_error(loc, state,
1851		       "invalid array of `%s' (only one-dimensional arrays "
1852		       "may be declared)",
1853		       base->name);
1854      return glsl_type::error_type;
1855   }
1856
1857   if (array_size != NULL) {
1858      exec_list dummy_instructions;
1859      ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1860      YYLTYPE loc = array_size->get_location();
1861
1862      if (ir != NULL) {
1863	 if (!ir->type->is_integer()) {
1864	    _mesa_glsl_error(& loc, state, "array size must be integer type");
1865	 } else if (!ir->type->is_scalar()) {
1866	    _mesa_glsl_error(& loc, state, "array size must be scalar type");
1867	 } else {
1868	    ir_constant *const size = ir->constant_expression_value();
1869
1870	    if (size == NULL) {
1871	       _mesa_glsl_error(& loc, state, "array size must be a "
1872				"constant valued expression");
1873	    } else if (size->value.i[0] <= 0) {
1874	       _mesa_glsl_error(& loc, state, "array size must be > 0");
1875	    } else {
1876	       assert(size->type == ir->type);
1877	       length = size->value.u[0];
1878
1879               /* If the array size is const (and we've verified that
1880                * it is) then no instructions should have been emitted
1881                * when we converted it to HIR.  If they were emitted,
1882                * then either the array size isn't const after all, or
1883                * we are emitting unnecessary instructions.
1884                */
1885               assert(dummy_instructions.is_empty());
1886	    }
1887	 }
1888      }
1889   } else if (state->es_shader) {
1890      /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
1891       * array declarations have been removed from the language.
1892       */
1893      _mesa_glsl_error(loc, state, "unsized array declarations are not "
1894		       "allowed in GLSL ES 1.00.");
1895   }
1896
1897   return glsl_type::get_array_instance(base, length);
1898}
1899
1900
1901const glsl_type *
1902ast_type_specifier::glsl_type(const char **name,
1903			      struct _mesa_glsl_parse_state *state) const
1904{
1905   const struct glsl_type *type;
1906
1907   type = state->symbols->get_type(this->type_name);
1908   *name = this->type_name;
1909
1910   if (this->is_array) {
1911      YYLTYPE loc = this->get_location();
1912      type = process_array_type(&loc, type, this->array_size, state);
1913   }
1914
1915   return type;
1916}
1917
1918
1919static void
1920apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
1921				 ir_variable *var,
1922				 struct _mesa_glsl_parse_state *state,
1923				 YYLTYPE *loc)
1924{
1925   if (qual->flags.q.invariant) {
1926      if (var->used) {
1927	 _mesa_glsl_error(loc, state,
1928			  "variable `%s' may not be redeclared "
1929			  "`invariant' after being used",
1930			  var->name);
1931      } else {
1932	 var->invariant = 1;
1933      }
1934   }
1935
1936   if (qual->flags.q.constant || qual->flags.q.attribute
1937       || qual->flags.q.uniform
1938       || (qual->flags.q.varying && (state->target == fragment_shader)))
1939      var->read_only = 1;
1940
1941   if (qual->flags.q.centroid)
1942      var->centroid = 1;
1943
1944   if (qual->flags.q.attribute && state->target != vertex_shader) {
1945      var->type = glsl_type::error_type;
1946      _mesa_glsl_error(loc, state,
1947		       "`attribute' variables may not be declared in the "
1948		       "%s shader",
1949		       _mesa_glsl_shader_target_name(state->target));
1950   }
1951
1952   /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
1953    *
1954    *     "The varying qualifier can be used only with the data types
1955    *     float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
1956    *     these."
1957    */
1958   if (qual->flags.q.varying) {
1959      const glsl_type *non_array_type;
1960
1961      if (var->type && var->type->is_array())
1962	 non_array_type = var->type->fields.array;
1963      else
1964	 non_array_type = var->type;
1965
1966      if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
1967	 var->type = glsl_type::error_type;
1968	 _mesa_glsl_error(loc, state,
1969			  "varying variables must be of base type float");
1970      }
1971   }
1972
1973   /* If there is no qualifier that changes the mode of the variable, leave
1974    * the setting alone.
1975    */
1976   if (qual->flags.q.in && qual->flags.q.out)
1977      var->mode = ir_var_inout;
1978   else if (qual->flags.q.attribute || qual->flags.q.in
1979	    || (qual->flags.q.varying && (state->target == fragment_shader)))
1980      var->mode = ir_var_in;
1981   else if (qual->flags.q.out
1982	    || (qual->flags.q.varying && (state->target == vertex_shader)))
1983      var->mode = ir_var_out;
1984   else if (qual->flags.q.uniform)
1985      var->mode = ir_var_uniform;
1986
1987   if (state->all_invariant && (state->current_function == NULL)) {
1988      switch (state->target) {
1989      case vertex_shader:
1990	 if (var->mode == ir_var_out)
1991	    var->invariant = true;
1992	 break;
1993      case geometry_shader:
1994	 if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
1995	    var->invariant = true;
1996	 break;
1997      case fragment_shader:
1998	 if (var->mode == ir_var_in)
1999	    var->invariant = true;
2000	 break;
2001      }
2002   }
2003
2004   if (qual->flags.q.flat)
2005      var->interpolation = INTERP_QUALIFIER_FLAT;
2006   else if (qual->flags.q.noperspective)
2007      var->interpolation = INTERP_QUALIFIER_NOPERSPECTIVE;
2008   else if (qual->flags.q.smooth)
2009      var->interpolation = INTERP_QUALIFIER_SMOOTH;
2010   else
2011      var->interpolation = INTERP_QUALIFIER_NONE;
2012
2013   if (var->interpolation != INTERP_QUALIFIER_NONE &&
2014       !(state->target == vertex_shader && var->mode == ir_var_out) &&
2015       !(state->target == fragment_shader && var->mode == ir_var_in)) {
2016      const char *qual_string = NULL;
2017      switch (var->interpolation) {
2018      case INTERP_QUALIFIER_FLAT:
2019	 qual_string = "flat";
2020	 break;
2021      case INTERP_QUALIFIER_NOPERSPECTIVE:
2022	 qual_string = "noperspective";
2023	 break;
2024      case INTERP_QUALIFIER_SMOOTH:
2025	 qual_string = "smooth";
2026	 break;
2027      }
2028
2029      _mesa_glsl_error(loc, state,
2030		       "interpolation qualifier `%s' can only be applied to "
2031		       "vertex shader outputs and fragment shader inputs.",
2032		       qual_string);
2033
2034   }
2035
2036   var->pixel_center_integer = qual->flags.q.pixel_center_integer;
2037   var->origin_upper_left = qual->flags.q.origin_upper_left;
2038   if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
2039       && (strcmp(var->name, "gl_FragCoord") != 0)) {
2040      const char *const qual_string = (qual->flags.q.origin_upper_left)
2041	 ? "origin_upper_left" : "pixel_center_integer";
2042
2043      _mesa_glsl_error(loc, state,
2044		       "layout qualifier `%s' can only be applied to "
2045		       "fragment shader input `gl_FragCoord'",
2046		       qual_string);
2047   }
2048
2049   if (qual->flags.q.explicit_location) {
2050      const bool global_scope = (state->current_function == NULL);
2051      bool fail = false;
2052      const char *string = "";
2053
2054      /* In the vertex shader only shader inputs can be given explicit
2055       * locations.
2056       *
2057       * In the fragment shader only shader outputs can be given explicit
2058       * locations.
2059       */
2060      switch (state->target) {
2061      case vertex_shader:
2062	 if (!global_scope || (var->mode != ir_var_in)) {
2063	    fail = true;
2064	    string = "input";
2065	 }
2066	 break;
2067
2068      case geometry_shader:
2069	 _mesa_glsl_error(loc, state,
2070			  "geometry shader variables cannot be given "
2071			  "explicit locations\n");
2072	 break;
2073
2074      case fragment_shader:
2075	 if (!global_scope || (var->mode != ir_var_out)) {
2076	    fail = true;
2077	    string = "output";
2078	 }
2079	 break;
2080      };
2081
2082      if (fail) {
2083	 _mesa_glsl_error(loc, state,
2084			  "only %s shader %s variables can be given an "
2085			  "explicit location\n",
2086			  _mesa_glsl_shader_target_name(state->target),
2087			  string);
2088      } else {
2089	 var->explicit_location = true;
2090
2091	 /* This bit of silliness is needed because invalid explicit locations
2092	  * are supposed to be flagged during linking.  Small negative values
2093	  * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
2094	  * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
2095	  * The linker needs to be able to differentiate these cases.  This
2096	  * ensures that negative values stay negative.
2097	  */
2098	 if (qual->location >= 0) {
2099	    var->location = (state->target == vertex_shader)
2100	       ? (qual->location + VERT_ATTRIB_GENERIC0)
2101	       : (qual->location + FRAG_RESULT_DATA0);
2102	 } else {
2103	    var->location = qual->location;
2104	 }
2105      }
2106   }
2107
2108   /* Does the declaration use the 'layout' keyword?
2109    */
2110   const bool uses_layout = qual->flags.q.pixel_center_integer
2111      || qual->flags.q.origin_upper_left
2112      || qual->flags.q.explicit_location;
2113
2114   /* Does the declaration use the deprecated 'attribute' or 'varying'
2115    * keywords?
2116    */
2117   const bool uses_deprecated_qualifier = qual->flags.q.attribute
2118      || qual->flags.q.varying;
2119
2120   /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2121    * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2122    * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2123    * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2124    * These extensions and all following extensions that add the 'layout'
2125    * keyword have been modified to require the use of 'in' or 'out'.
2126    *
2127    * The following extension do not allow the deprecated keywords:
2128    *
2129    *    GL_AMD_conservative_depth
2130    *    GL_ARB_conservative_depth
2131    *    GL_ARB_gpu_shader5
2132    *    GL_ARB_separate_shader_objects
2133    *    GL_ARB_tesselation_shader
2134    *    GL_ARB_transform_feedback3
2135    *    GL_ARB_uniform_buffer_object
2136    *
2137    * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2138    * allow layout with the deprecated keywords.
2139    */
2140   const bool relaxed_layout_qualifier_checking =
2141      state->ARB_fragment_coord_conventions_enable;
2142
2143   if (uses_layout && uses_deprecated_qualifier) {
2144      if (relaxed_layout_qualifier_checking) {
2145	 _mesa_glsl_warning(loc, state,
2146			    "`layout' qualifier may not be used with "
2147			    "`attribute' or `varying'");
2148      } else {
2149	 _mesa_glsl_error(loc, state,
2150			  "`layout' qualifier may not be used with "
2151			  "`attribute' or `varying'");
2152      }
2153   }
2154
2155   /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2156    * AMD_conservative_depth.
2157    */
2158   int depth_layout_count = qual->flags.q.depth_any
2159      + qual->flags.q.depth_greater
2160      + qual->flags.q.depth_less
2161      + qual->flags.q.depth_unchanged;
2162   if (depth_layout_count > 0
2163       && !state->AMD_conservative_depth_enable
2164       && !state->ARB_conservative_depth_enable) {
2165       _mesa_glsl_error(loc, state,
2166                        "extension GL_AMD_conservative_depth or "
2167                        "GL_ARB_conservative_depth must be enabled "
2168			"to use depth layout qualifiers");
2169   } else if (depth_layout_count > 0
2170              && strcmp(var->name, "gl_FragDepth") != 0) {
2171       _mesa_glsl_error(loc, state,
2172                        "depth layout qualifiers can be applied only to "
2173                        "gl_FragDepth");
2174   } else if (depth_layout_count > 1
2175              && strcmp(var->name, "gl_FragDepth") == 0) {
2176      _mesa_glsl_error(loc, state,
2177                       "at most one depth layout qualifier can be applied to "
2178                       "gl_FragDepth");
2179   }
2180   if (qual->flags.q.depth_any)
2181      var->depth_layout = ir_depth_layout_any;
2182   else if (qual->flags.q.depth_greater)
2183      var->depth_layout = ir_depth_layout_greater;
2184   else if (qual->flags.q.depth_less)
2185      var->depth_layout = ir_depth_layout_less;
2186   else if (qual->flags.q.depth_unchanged)
2187       var->depth_layout = ir_depth_layout_unchanged;
2188   else
2189       var->depth_layout = ir_depth_layout_none;
2190}
2191
2192/**
2193 * Get the variable that is being redeclared by this declaration
2194 *
2195 * Semantic checks to verify the validity of the redeclaration are also
2196 * performed.  If semantic checks fail, compilation error will be emitted via
2197 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2198 *
2199 * \returns
2200 * A pointer to an existing variable in the current scope if the declaration
2201 * is a redeclaration, \c NULL otherwise.
2202 */
2203ir_variable *
2204get_variable_being_redeclared(ir_variable *var, ast_declaration *decl,
2205			      struct _mesa_glsl_parse_state *state)
2206{
2207   /* Check if this declaration is actually a re-declaration, either to
2208    * resize an array or add qualifiers to an existing variable.
2209    *
2210    * This is allowed for variables in the current scope, or when at
2211    * global scope (for built-ins in the implicit outer scope).
2212    */
2213   ir_variable *earlier = state->symbols->get_variable(decl->identifier);
2214   if (earlier == NULL ||
2215       (state->current_function != NULL &&
2216	!state->symbols->name_declared_this_scope(decl->identifier))) {
2217      return NULL;
2218   }
2219
2220
2221   YYLTYPE loc = decl->get_location();
2222
2223   /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2224    *
2225    * "It is legal to declare an array without a size and then
2226    *  later re-declare the same name as an array of the same
2227    *  type and specify a size."
2228    */
2229   if ((earlier->type->array_size() == 0)
2230       && var->type->is_array()
2231       && (var->type->element_type() == earlier->type->element_type())) {
2232      /* FINISHME: This doesn't match the qualifiers on the two
2233       * FINISHME: declarations.  It's not 100% clear whether this is
2234       * FINISHME: required or not.
2235       */
2236
2237      const unsigned size = unsigned(var->type->array_size());
2238      check_builtin_array_max_size(var->name, size, loc, state);
2239      if ((size > 0) && (size <= earlier->max_array_access)) {
2240	 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2241			  "previous access",
2242			  earlier->max_array_access);
2243      }
2244
2245      earlier->type = var->type;
2246      delete var;
2247      var = NULL;
2248   } else if (state->ARB_fragment_coord_conventions_enable
2249	      && strcmp(var->name, "gl_FragCoord") == 0
2250	      && earlier->type == var->type
2251	      && earlier->mode == var->mode) {
2252      /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2253       * qualifiers.
2254       */
2255      earlier->origin_upper_left = var->origin_upper_left;
2256      earlier->pixel_center_integer = var->pixel_center_integer;
2257
2258      /* According to section 4.3.7 of the GLSL 1.30 spec,
2259       * the following built-in varaibles can be redeclared with an
2260       * interpolation qualifier:
2261       *    * gl_FrontColor
2262       *    * gl_BackColor
2263       *    * gl_FrontSecondaryColor
2264       *    * gl_BackSecondaryColor
2265       *    * gl_Color
2266       *    * gl_SecondaryColor
2267       */
2268   } else if (state->language_version >= 130
2269	      && (strcmp(var->name, "gl_FrontColor") == 0
2270		  || strcmp(var->name, "gl_BackColor") == 0
2271		  || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2272		  || strcmp(var->name, "gl_BackSecondaryColor") == 0
2273		  || strcmp(var->name, "gl_Color") == 0
2274		  || strcmp(var->name, "gl_SecondaryColor") == 0)
2275	      && earlier->type == var->type
2276	      && earlier->mode == var->mode) {
2277      earlier->interpolation = var->interpolation;
2278
2279      /* Layout qualifiers for gl_FragDepth. */
2280   } else if ((state->AMD_conservative_depth_enable ||
2281               state->ARB_conservative_depth_enable)
2282	      && strcmp(var->name, "gl_FragDepth") == 0
2283	      && earlier->type == var->type
2284	      && earlier->mode == var->mode) {
2285
2286      /** From the AMD_conservative_depth spec:
2287       *     Within any shader, the first redeclarations of gl_FragDepth
2288       *     must appear before any use of gl_FragDepth.
2289       */
2290      if (earlier->used) {
2291	 _mesa_glsl_error(&loc, state,
2292			  "the first redeclaration of gl_FragDepth "
2293			  "must appear before any use of gl_FragDepth");
2294      }
2295
2296      /* Prevent inconsistent redeclaration of depth layout qualifier. */
2297      if (earlier->depth_layout != ir_depth_layout_none
2298	  && earlier->depth_layout != var->depth_layout) {
2299	 _mesa_glsl_error(&loc, state,
2300			  "gl_FragDepth: depth layout is declared here "
2301			  "as '%s, but it was previously declared as "
2302			  "'%s'",
2303			  depth_layout_string(var->depth_layout),
2304			  depth_layout_string(earlier->depth_layout));
2305      }
2306
2307      earlier->depth_layout = var->depth_layout;
2308
2309   } else {
2310      _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
2311   }
2312
2313   return earlier;
2314}
2315
2316/**
2317 * Generate the IR for an initializer in a variable declaration
2318 */
2319ir_rvalue *
2320process_initializer(ir_variable *var, ast_declaration *decl,
2321		    ast_fully_specified_type *type,
2322		    exec_list *initializer_instructions,
2323		    struct _mesa_glsl_parse_state *state)
2324{
2325   ir_rvalue *result = NULL;
2326
2327   YYLTYPE initializer_loc = decl->initializer->get_location();
2328
2329   /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2330    *
2331    *    "All uniform variables are read-only and are initialized either
2332    *    directly by an application via API commands, or indirectly by
2333    *    OpenGL."
2334    */
2335   if ((state->language_version <= 110)
2336       && (var->mode == ir_var_uniform)) {
2337      _mesa_glsl_error(& initializer_loc, state,
2338		       "cannot initialize uniforms in GLSL 1.10");
2339   }
2340
2341   if (var->type->is_sampler()) {
2342      _mesa_glsl_error(& initializer_loc, state,
2343		       "cannot initialize samplers");
2344   }
2345
2346   if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
2347      _mesa_glsl_error(& initializer_loc, state,
2348		       "cannot initialize %s shader input / %s",
2349		       _mesa_glsl_shader_target_name(state->target),
2350		       (state->target == vertex_shader)
2351		       ? "attribute" : "varying");
2352   }
2353
2354   ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2355   ir_rvalue *rhs = decl->initializer->hir(initializer_instructions,
2356					   state);
2357
2358   /* Calculate the constant value if this is a const or uniform
2359    * declaration.
2360    */
2361   if (type->qualifier.flags.q.constant
2362       || type->qualifier.flags.q.uniform) {
2363      ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs, true);
2364      if (new_rhs != NULL) {
2365	 rhs = new_rhs;
2366
2367	 ir_constant *constant_value = rhs->constant_expression_value();
2368	 if (!constant_value) {
2369	    _mesa_glsl_error(& initializer_loc, state,
2370			     "initializer of %s variable `%s' must be a "
2371			     "constant expression",
2372			     (type->qualifier.flags.q.constant)
2373			     ? "const" : "uniform",
2374			     decl->identifier);
2375	    if (var->type->is_numeric()) {
2376	       /* Reduce cascading errors. */
2377	       var->constant_value = ir_constant::zero(state, var->type);
2378	    }
2379	 } else {
2380	    rhs = constant_value;
2381	    var->constant_value = constant_value;
2382	 }
2383      } else {
2384	 _mesa_glsl_error(&initializer_loc, state,
2385			  "initializer of type %s cannot be assigned to "
2386			  "variable of type %s",
2387			  rhs->type->name, var->type->name);
2388	 if (var->type->is_numeric()) {
2389	    /* Reduce cascading errors. */
2390	    var->constant_value = ir_constant::zero(state, var->type);
2391	 }
2392      }
2393   }
2394
2395   if (rhs && !rhs->type->is_error()) {
2396      bool temp = var->read_only;
2397      if (type->qualifier.flags.q.constant)
2398	 var->read_only = false;
2399
2400      /* Never emit code to initialize a uniform.
2401       */
2402      const glsl_type *initializer_type;
2403      if (!type->qualifier.flags.q.uniform) {
2404	 result = do_assignment(initializer_instructions, state,
2405				NULL,
2406				lhs, rhs, true,
2407				type->get_location());
2408	 initializer_type = result->type;
2409      } else
2410	 initializer_type = rhs->type;
2411
2412      var->constant_initializer = rhs->constant_expression_value();
2413      var->has_initializer = true;
2414
2415      /* If the declared variable is an unsized array, it must inherrit
2416       * its full type from the initializer.  A declaration such as
2417       *
2418       *     uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2419       *
2420       * becomes
2421       *
2422       *     uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2423       *
2424       * The assignment generated in the if-statement (below) will also
2425       * automatically handle this case for non-uniforms.
2426       *
2427       * If the declared variable is not an array, the types must
2428       * already match exactly.  As a result, the type assignment
2429       * here can be done unconditionally.  For non-uniforms the call
2430       * to do_assignment can change the type of the initializer (via
2431       * the implicit conversion rules).  For uniforms the initializer
2432       * must be a constant expression, and the type of that expression
2433       * was validated above.
2434       */
2435      var->type = initializer_type;
2436
2437      var->read_only = temp;
2438   }
2439
2440   return result;
2441}
2442
2443ir_rvalue *
2444ast_declarator_list::hir(exec_list *instructions,
2445			 struct _mesa_glsl_parse_state *state)
2446{
2447   void *ctx = state;
2448   const struct glsl_type *decl_type;
2449   const char *type_name = NULL;
2450   ir_rvalue *result = NULL;
2451   YYLTYPE loc = this->get_location();
2452
2453   /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
2454    *
2455    *     "To ensure that a particular output variable is invariant, it is
2456    *     necessary to use the invariant qualifier. It can either be used to
2457    *     qualify a previously declared variable as being invariant
2458    *
2459    *         invariant gl_Position; // make existing gl_Position be invariant"
2460    *
2461    * In these cases the parser will set the 'invariant' flag in the declarator
2462    * list, and the type will be NULL.
2463    */
2464   if (this->invariant) {
2465      assert(this->type == NULL);
2466
2467      if (state->current_function != NULL) {
2468	 _mesa_glsl_error(& loc, state,
2469			  "All uses of `invariant' keyword must be at global "
2470			  "scope\n");
2471      }
2472
2473      foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2474	 assert(!decl->is_array);
2475	 assert(decl->array_size == NULL);
2476	 assert(decl->initializer == NULL);
2477
2478	 ir_variable *const earlier =
2479	    state->symbols->get_variable(decl->identifier);
2480	 if (earlier == NULL) {
2481	    _mesa_glsl_error(& loc, state,
2482			     "Undeclared variable `%s' cannot be marked "
2483			     "invariant\n", decl->identifier);
2484	 } else if ((state->target == vertex_shader)
2485	       && (earlier->mode != ir_var_out)) {
2486	    _mesa_glsl_error(& loc, state,
2487			     "`%s' cannot be marked invariant, vertex shader "
2488			     "outputs only\n", decl->identifier);
2489	 } else if ((state->target == fragment_shader)
2490	       && (earlier->mode != ir_var_in)) {
2491	    _mesa_glsl_error(& loc, state,
2492			     "`%s' cannot be marked invariant, fragment shader "
2493			     "inputs only\n", decl->identifier);
2494	 } else if (earlier->used) {
2495	    _mesa_glsl_error(& loc, state,
2496			     "variable `%s' may not be redeclared "
2497			     "`invariant' after being used",
2498			     earlier->name);
2499	 } else {
2500	    earlier->invariant = true;
2501	 }
2502      }
2503
2504      /* Invariant redeclarations do not have r-values.
2505       */
2506      return NULL;
2507   }
2508
2509   assert(this->type != NULL);
2510   assert(!this->invariant);
2511
2512   /* The type specifier may contain a structure definition.  Process that
2513    * before any of the variable declarations.
2514    */
2515   (void) this->type->specifier->hir(instructions, state);
2516
2517   decl_type = this->type->specifier->glsl_type(& type_name, state);
2518   if (this->declarations.is_empty()) {
2519      /* If there is no structure involved in the program text, there are two
2520       * possible scenarios:
2521       *
2522       * - The program text contained something like 'vec4;'.  This is an
2523       *   empty declaration.  It is valid but weird.  Emit a warning.
2524       *
2525       * - The program text contained something like 'S;' and 'S' is not the
2526       *   name of a known structure type.  This is both invalid and weird.
2527       *   Emit an error.
2528       *
2529       * Note that if decl_type is NULL and there is a structure involved,
2530       * there must have been some sort of error with the structure.  In this
2531       * case we assume that an error was already generated on this line of
2532       * code for the structure.  There is no need to generate an additional,
2533       * confusing error.
2534       */
2535      assert(this->type->specifier->structure == NULL || decl_type != NULL
2536	     || state->error);
2537      if (this->type->specifier->structure == NULL) {
2538	 if (decl_type != NULL) {
2539	    _mesa_glsl_warning(&loc, state, "empty declaration");
2540	 } else {
2541	    _mesa_glsl_error(&loc, state,
2542			     "invalid type `%s' in empty declaration",
2543			     type_name);
2544	 }
2545      }
2546   }
2547
2548   foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2549      const struct glsl_type *var_type;
2550      ir_variable *var;
2551
2552      /* FINISHME: Emit a warning if a variable declaration shadows a
2553       * FINISHME: declaration at a higher scope.
2554       */
2555
2556      if ((decl_type == NULL) || decl_type->is_void()) {
2557	 if (type_name != NULL) {
2558	    _mesa_glsl_error(& loc, state,
2559			     "invalid type `%s' in declaration of `%s'",
2560			     type_name, decl->identifier);
2561	 } else {
2562	    _mesa_glsl_error(& loc, state,
2563			     "invalid type in declaration of `%s'",
2564			     decl->identifier);
2565	 }
2566	 continue;
2567      }
2568
2569      if (decl->is_array) {
2570	 var_type = process_array_type(&loc, decl_type, decl->array_size,
2571				       state);
2572	 if (var_type->is_error())
2573	    continue;
2574      } else {
2575	 var_type = decl_type;
2576      }
2577
2578      var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
2579
2580      /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
2581       *
2582       *     "Global variables can only use the qualifiers const,
2583       *     attribute, uni form, or varying. Only one may be
2584       *     specified.
2585       *
2586       *     Local variables can only use the qualifier const."
2587       *
2588       * This is relaxed in GLSL 1.30.  It is also relaxed by any extension
2589       * that adds the 'layout' keyword.
2590       */
2591      if ((state->language_version < 130)
2592	  && !state->ARB_explicit_attrib_location_enable
2593	  && !state->ARB_fragment_coord_conventions_enable) {
2594	 if (this->type->qualifier.flags.q.out) {
2595	    _mesa_glsl_error(& loc, state,
2596			     "`out' qualifier in declaration of `%s' "
2597			     "only valid for function parameters in %s.",
2598			     decl->identifier, state->version_string);
2599	 }
2600	 if (this->type->qualifier.flags.q.in) {
2601	    _mesa_glsl_error(& loc, state,
2602			     "`in' qualifier in declaration of `%s' "
2603			     "only valid for function parameters in %s.",
2604			     decl->identifier, state->version_string);
2605	 }
2606	 /* FINISHME: Test for other invalid qualifiers. */
2607      }
2608
2609      apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
2610				       & loc);
2611
2612      if (this->type->qualifier.flags.q.invariant) {
2613	 if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
2614						   var->mode == ir_var_inout)) {
2615	    /* FINISHME: Note that this doesn't work for invariant on
2616	     * a function signature outval
2617	     */
2618	    _mesa_glsl_error(& loc, state,
2619			     "`%s' cannot be marked invariant, vertex shader "
2620			     "outputs only\n", var->name);
2621	 } else if ((state->target == fragment_shader) &&
2622		    !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
2623	    /* FINISHME: Note that this doesn't work for invariant on
2624	     * a function signature inval
2625	     */
2626	    _mesa_glsl_error(& loc, state,
2627			     "`%s' cannot be marked invariant, fragment shader "
2628			     "inputs only\n", var->name);
2629	 }
2630      }
2631
2632      if (state->current_function != NULL) {
2633	 const char *mode = NULL;
2634	 const char *extra = "";
2635
2636	 /* There is no need to check for 'inout' here because the parser will
2637	  * only allow that in function parameter lists.
2638	  */
2639	 if (this->type->qualifier.flags.q.attribute) {
2640	    mode = "attribute";
2641	 } else if (this->type->qualifier.flags.q.uniform) {
2642	    mode = "uniform";
2643	 } else if (this->type->qualifier.flags.q.varying) {
2644	    mode = "varying";
2645	 } else if (this->type->qualifier.flags.q.in) {
2646	    mode = "in";
2647	    extra = " or in function parameter list";
2648	 } else if (this->type->qualifier.flags.q.out) {
2649	    mode = "out";
2650	    extra = " or in function parameter list";
2651	 }
2652
2653	 if (mode) {
2654	    _mesa_glsl_error(& loc, state,
2655			     "%s variable `%s' must be declared at "
2656			     "global scope%s",
2657			     mode, var->name, extra);
2658	 }
2659      } else if (var->mode == ir_var_in) {
2660         var->read_only = true;
2661
2662	 if (state->target == vertex_shader) {
2663	    bool error_emitted = false;
2664
2665	    /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
2666	     *
2667	     *    "Vertex shader inputs can only be float, floating-point
2668	     *    vectors, matrices, signed and unsigned integers and integer
2669	     *    vectors. Vertex shader inputs can also form arrays of these
2670	     *    types, but not structures."
2671	     *
2672	     * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
2673	     *
2674	     *    "Vertex shader inputs can only be float, floating-point
2675	     *    vectors, matrices, signed and unsigned integers and integer
2676	     *    vectors. They cannot be arrays or structures."
2677	     *
2678	     * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
2679	     *
2680	     *    "The attribute qualifier can be used only with float,
2681	     *    floating-point vectors, and matrices. Attribute variables
2682	     *    cannot be declared as arrays or structures."
2683	     */
2684	    const glsl_type *check_type = var->type->is_array()
2685	       ? var->type->fields.array : var->type;
2686
2687	    switch (check_type->base_type) {
2688	    case GLSL_TYPE_FLOAT:
2689	       break;
2690	    case GLSL_TYPE_UINT:
2691	    case GLSL_TYPE_INT:
2692	       if (state->language_version > 120)
2693		  break;
2694	       /* FALLTHROUGH */
2695	    default:
2696	       _mesa_glsl_error(& loc, state,
2697				"vertex shader input / attribute cannot have "
2698				"type %s`%s'",
2699				var->type->is_array() ? "array of " : "",
2700				check_type->name);
2701	       error_emitted = true;
2702	    }
2703
2704	    if (!error_emitted && (state->language_version <= 130)
2705		&& var->type->is_array()) {
2706	       _mesa_glsl_error(& loc, state,
2707				"vertex shader input / attribute cannot have "
2708				"array type");
2709	       error_emitted = true;
2710	    }
2711	 }
2712      }
2713
2714      /* Integer vertex outputs must be qualified with 'flat'.
2715       *
2716       * From section 4.3.6 of the GLSL 1.30 spec:
2717       *    "If a vertex output is a signed or unsigned integer or integer
2718       *    vector, then it must be qualified with the interpolation qualifier
2719       *    flat."
2720       */
2721      if (state->language_version >= 130
2722          && state->target == vertex_shader
2723          && state->current_function == NULL
2724          && var->type->is_integer()
2725          && var->mode == ir_var_out
2726          && var->interpolation != INTERP_QUALIFIER_FLAT) {
2727
2728         _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
2729                          "then it must be qualified with 'flat'");
2730      }
2731
2732
2733      /* Interpolation qualifiers cannot be applied to 'centroid' and
2734       * 'centroid varying'.
2735       *
2736       * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2737       *    "interpolation qualifiers may only precede the qualifiers in,
2738       *    centroid in, out, or centroid out in a declaration. They do not apply
2739       *    to the deprecated storage qualifiers varying or centroid varying."
2740       */
2741      if (state->language_version >= 130
2742          && this->type->qualifier.has_interpolation()
2743          && this->type->qualifier.flags.q.varying) {
2744
2745         const char *i = this->type->qualifier.interpolation_string();
2746         assert(i != NULL);
2747         const char *s;
2748         if (this->type->qualifier.flags.q.centroid)
2749            s = "centroid varying";
2750         else
2751            s = "varying";
2752
2753         _mesa_glsl_error(&loc, state,
2754                          "qualifier '%s' cannot be applied to the "
2755                          "deprecated storage qualifier '%s'", i, s);
2756      }
2757
2758
2759      /* Interpolation qualifiers can only apply to vertex shader outputs and
2760       * fragment shader inputs.
2761       *
2762       * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2763       *    "Outputs from a vertex shader (out) and inputs to a fragment
2764       *    shader (in) can be further qualified with one or more of these
2765       *    interpolation qualifiers"
2766       */
2767      if (state->language_version >= 130
2768          && this->type->qualifier.has_interpolation()) {
2769
2770         const char *i = this->type->qualifier.interpolation_string();
2771         assert(i != NULL);
2772
2773         switch (state->target) {
2774         case vertex_shader:
2775            if (this->type->qualifier.flags.q.in) {
2776               _mesa_glsl_error(&loc, state,
2777                                "qualifier '%s' cannot be applied to vertex "
2778                                "shader inputs", i);
2779            }
2780            break;
2781         case fragment_shader:
2782            if (this->type->qualifier.flags.q.out) {
2783               _mesa_glsl_error(&loc, state,
2784                                "qualifier '%s' cannot be applied to fragment "
2785                                "shader outputs", i);
2786            }
2787            break;
2788         default:
2789            assert(0);
2790         }
2791      }
2792
2793
2794      /* From section 4.3.4 of the GLSL 1.30 spec:
2795       *    "It is an error to use centroid in in a vertex shader."
2796       */
2797      if (state->language_version >= 130
2798          && this->type->qualifier.flags.q.centroid
2799          && this->type->qualifier.flags.q.in
2800          && state->target == vertex_shader) {
2801
2802         _mesa_glsl_error(&loc, state,
2803                          "'centroid in' cannot be used in a vertex shader");
2804      }
2805
2806
2807      /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
2808       */
2809      if (this->type->specifier->precision != ast_precision_none
2810          && state->language_version != 100
2811          && state->language_version < 130) {
2812
2813         _mesa_glsl_error(&loc, state,
2814                          "precision qualifiers are supported only in GLSL ES "
2815                          "1.00, and GLSL 1.30 and later");
2816      }
2817
2818
2819      /* Precision qualifiers only apply to floating point and integer types.
2820       *
2821       * From section 4.5.2 of the GLSL 1.30 spec:
2822       *    "Any floating point or any integer declaration can have the type
2823       *    preceded by one of these precision qualifiers [...] Literal
2824       *    constants do not have precision qualifiers. Neither do Boolean
2825       *    variables.
2826       *
2827       * In GLSL ES, sampler types are also allowed.
2828       *
2829       * From page 87 of the GLSL ES spec:
2830       *    "RESOLUTION: Allow sampler types to take a precision qualifier."
2831       */
2832      if (this->type->specifier->precision != ast_precision_none
2833          && !var->type->is_float()
2834          && !var->type->is_integer()
2835          && !(var->type->is_sampler() && state->es_shader)
2836          && !(var->type->is_array()
2837               && (var->type->fields.array->is_float()
2838                   || var->type->fields.array->is_integer()))) {
2839
2840         _mesa_glsl_error(&loc, state,
2841                          "precision qualifiers apply only to floating point"
2842                          "%s types", state->es_shader ? ", integer, and sampler"
2843						       : "and integer");
2844      }
2845
2846      /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2847       *
2848       *    "[Sampler types] can only be declared as function
2849       *    parameters or uniform variables (see Section 4.3.5
2850       *    "Uniform")".
2851       */
2852      if (var_type->contains_sampler() &&
2853          !this->type->qualifier.flags.q.uniform) {
2854         _mesa_glsl_error(&loc, state, "samplers must be declared uniform");
2855      }
2856
2857      /* Process the initializer and add its instructions to a temporary
2858       * list.  This list will be added to the instruction stream (below) after
2859       * the declaration is added.  This is done because in some cases (such as
2860       * redeclarations) the declaration may not actually be added to the
2861       * instruction stream.
2862       */
2863      exec_list initializer_instructions;
2864      ir_variable *earlier = get_variable_being_redeclared(var, decl, state);
2865
2866      if (decl->initializer != NULL) {
2867	 result = process_initializer((earlier == NULL) ? var : earlier,
2868				      decl, this->type,
2869				      &initializer_instructions, state);
2870      }
2871
2872      /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
2873       *
2874       *     "It is an error to write to a const variable outside of
2875       *      its declaration, so they must be initialized when
2876       *      declared."
2877       */
2878      if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
2879	 _mesa_glsl_error(& loc, state,
2880			  "const declaration of `%s' must be initialized",
2881			  decl->identifier);
2882      }
2883
2884      /* If the declaration is not a redeclaration, there are a few additional
2885       * semantic checks that must be applied.  In addition, variable that was
2886       * created for the declaration should be added to the IR stream.
2887       */
2888      if (earlier == NULL) {
2889	 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2890	  *
2891	  *   "Identifiers starting with "gl_" are reserved for use by
2892	  *   OpenGL, and may not be declared in a shader as either a
2893	  *   variable or a function."
2894	  */
2895	 if (strncmp(decl->identifier, "gl_", 3) == 0)
2896	    _mesa_glsl_error(& loc, state,
2897			     "identifier `%s' uses reserved `gl_' prefix",
2898			     decl->identifier);
2899	 else if (strstr(decl->identifier, "__")) {
2900	    /* From page 14 (page 20 of the PDF) of the GLSL 1.10
2901	     * spec:
2902	     *
2903	     *     "In addition, all identifiers containing two
2904	     *      consecutive underscores (__) are reserved as
2905	     *      possible future keywords."
2906	     */
2907	    _mesa_glsl_error(& loc, state,
2908			     "identifier `%s' uses reserved `__' string",
2909			     decl->identifier);
2910	 }
2911
2912	 /* Add the variable to the symbol table.  Note that the initializer's
2913	  * IR was already processed earlier (though it hasn't been emitted
2914	  * yet), without the variable in scope.
2915	  *
2916	  * This differs from most C-like languages, but it follows the GLSL
2917	  * specification.  From page 28 (page 34 of the PDF) of the GLSL 1.50
2918	  * spec:
2919	  *
2920	  *     "Within a declaration, the scope of a name starts immediately
2921	  *     after the initializer if present or immediately after the name
2922	  *     being declared if not."
2923	  */
2924	 if (!state->symbols->add_variable(var)) {
2925	    YYLTYPE loc = this->get_location();
2926	    _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
2927			     "current scope", decl->identifier);
2928	    continue;
2929	 }
2930
2931	 /* Push the variable declaration to the top.  It means that all the
2932	  * variable declarations will appear in a funny last-to-first order,
2933	  * but otherwise we run into trouble if a function is prototyped, a
2934	  * global var is decled, then the function is defined with usage of
2935	  * the global var.  See glslparsertest's CorrectModule.frag.
2936	  */
2937	 instructions->push_head(var);
2938      }
2939
2940      instructions->append_list(&initializer_instructions);
2941   }
2942
2943
2944   /* Generally, variable declarations do not have r-values.  However,
2945    * one is used for the declaration in
2946    *
2947    * while (bool b = some_condition()) {
2948    *   ...
2949    * }
2950    *
2951    * so we return the rvalue from the last seen declaration here.
2952    */
2953   return result;
2954}
2955
2956
2957ir_rvalue *
2958ast_parameter_declarator::hir(exec_list *instructions,
2959			      struct _mesa_glsl_parse_state *state)
2960{
2961   void *ctx = state;
2962   const struct glsl_type *type;
2963   const char *name = NULL;
2964   YYLTYPE loc = this->get_location();
2965
2966   type = this->type->specifier->glsl_type(& name, state);
2967
2968   if (type == NULL) {
2969      if (name != NULL) {
2970	 _mesa_glsl_error(& loc, state,
2971			  "invalid type `%s' in declaration of `%s'",
2972			  name, this->identifier);
2973      } else {
2974	 _mesa_glsl_error(& loc, state,
2975			  "invalid type in declaration of `%s'",
2976			  this->identifier);
2977      }
2978
2979      type = glsl_type::error_type;
2980   }
2981
2982   /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
2983    *
2984    *    "Functions that accept no input arguments need not use void in the
2985    *    argument list because prototypes (or definitions) are required and
2986    *    therefore there is no ambiguity when an empty argument list "( )" is
2987    *    declared. The idiom "(void)" as a parameter list is provided for
2988    *    convenience."
2989    *
2990    * Placing this check here prevents a void parameter being set up
2991    * for a function, which avoids tripping up checks for main taking
2992    * parameters and lookups of an unnamed symbol.
2993    */
2994   if (type->is_void()) {
2995      if (this->identifier != NULL)
2996	 _mesa_glsl_error(& loc, state,
2997			  "named parameter cannot have type `void'");
2998
2999      is_void = true;
3000      return NULL;
3001   }
3002
3003   if (formal_parameter && (this->identifier == NULL)) {
3004      _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
3005      return NULL;
3006   }
3007
3008   /* This only handles "vec4 foo[..]".  The earlier specifier->glsl_type(...)
3009    * call already handled the "vec4[..] foo" case.
3010    */
3011   if (this->is_array) {
3012      type = process_array_type(&loc, type, this->array_size, state);
3013   }
3014
3015   if (!type->is_error() && type->array_size() == 0) {
3016      _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
3017		       "a declared size.");
3018      type = glsl_type::error_type;
3019   }
3020
3021   is_void = false;
3022   ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
3023
3024   /* Apply any specified qualifiers to the parameter declaration.  Note that
3025    * for function parameters the default mode is 'in'.
3026    */
3027   apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
3028
3029   /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3030    *
3031    *    "Samplers cannot be treated as l-values; hence cannot be used
3032    *    as out or inout function parameters, nor can they be assigned
3033    *    into."
3034    */
3035   if ((var->mode == ir_var_inout || var->mode == ir_var_out)
3036       && type->contains_sampler()) {
3037      _mesa_glsl_error(&loc, state, "out and inout parameters cannot contain samplers");
3038      type = glsl_type::error_type;
3039   }
3040
3041   /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
3042    *
3043    *    "When calling a function, expressions that do not evaluate to
3044    *     l-values cannot be passed to parameters declared as out or inout."
3045    *
3046    * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
3047    *
3048    *    "Other binary or unary expressions, non-dereferenced arrays,
3049    *     function names, swizzles with repeated fields, and constants
3050    *     cannot be l-values."
3051    *
3052    * So for GLSL 1.10, passing an array as an out or inout parameter is not
3053    * allowed.  This restriction is removed in GLSL 1.20, and in GLSL ES.
3054    */
3055   if ((var->mode == ir_var_inout || var->mode == ir_var_out)
3056       && type->is_array() && state->language_version == 110) {
3057      _mesa_glsl_error(&loc, state, "Arrays cannot be out or inout parameters in GLSL 1.10");
3058      type = glsl_type::error_type;
3059   }
3060
3061   instructions->push_tail(var);
3062
3063   /* Parameter declarations do not have r-values.
3064    */
3065   return NULL;
3066}
3067
3068
3069void
3070ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
3071					    bool formal,
3072					    exec_list *ir_parameters,
3073					    _mesa_glsl_parse_state *state)
3074{
3075   ast_parameter_declarator *void_param = NULL;
3076   unsigned count = 0;
3077
3078   foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
3079      param->formal_parameter = formal;
3080      param->hir(ir_parameters, state);
3081
3082      if (param->is_void)
3083	 void_param = param;
3084
3085      count++;
3086   }
3087
3088   if ((void_param != NULL) && (count > 1)) {
3089      YYLTYPE loc = void_param->get_location();
3090
3091      _mesa_glsl_error(& loc, state,
3092		       "`void' parameter must be only parameter");
3093   }
3094}
3095
3096
3097void
3098emit_function(_mesa_glsl_parse_state *state, ir_function *f)
3099{
3100   /* IR invariants disallow function declarations or definitions
3101    * nested within other function definitions.  But there is no
3102    * requirement about the relative order of function declarations
3103    * and definitions with respect to one another.  So simply insert
3104    * the new ir_function block at the end of the toplevel instruction
3105    * list.
3106    */
3107   state->toplevel_ir->push_tail(f);
3108}
3109
3110
3111ir_rvalue *
3112ast_function::hir(exec_list *instructions,
3113		  struct _mesa_glsl_parse_state *state)
3114{
3115   void *ctx = state;
3116   ir_function *f = NULL;
3117   ir_function_signature *sig = NULL;
3118   exec_list hir_parameters;
3119
3120   const char *const name = identifier;
3121
3122   /* New functions are always added to the top-level IR instruction stream,
3123    * so this instruction list pointer is ignored.  See also emit_function
3124    * (called below).
3125    */
3126   (void) instructions;
3127
3128   /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
3129    *
3130    *   "Function declarations (prototypes) cannot occur inside of functions;
3131    *   they must be at global scope, or for the built-in functions, outside
3132    *   the global scope."
3133    *
3134    * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
3135    *
3136    *   "User defined functions may only be defined within the global scope."
3137    *
3138    * Note that this language does not appear in GLSL 1.10.
3139    */
3140   if ((state->current_function != NULL) && (state->language_version != 110)) {
3141      YYLTYPE loc = this->get_location();
3142      _mesa_glsl_error(&loc, state,
3143		       "declaration of function `%s' not allowed within "
3144		       "function body", name);
3145   }
3146
3147   /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3148    *
3149    *   "Identifiers starting with "gl_" are reserved for use by
3150    *   OpenGL, and may not be declared in a shader as either a
3151    *   variable or a function."
3152    */
3153   if (strncmp(name, "gl_", 3) == 0) {
3154      YYLTYPE loc = this->get_location();
3155      _mesa_glsl_error(&loc, state,
3156		       "identifier `%s' uses reserved `gl_' prefix", name);
3157   }
3158
3159   /* Convert the list of function parameters to HIR now so that they can be
3160    * used below to compare this function's signature with previously seen
3161    * signatures for functions with the same name.
3162    */
3163   ast_parameter_declarator::parameters_to_hir(& this->parameters,
3164					       is_definition,
3165					       & hir_parameters, state);
3166
3167   const char *return_type_name;
3168   const glsl_type *return_type =
3169      this->return_type->specifier->glsl_type(& return_type_name, state);
3170
3171   if (!return_type) {
3172      YYLTYPE loc = this->get_location();
3173      _mesa_glsl_error(&loc, state,
3174		       "function `%s' has undeclared return type `%s'",
3175		       name, return_type_name);
3176      return_type = glsl_type::error_type;
3177   }
3178
3179   /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3180    * "No qualifier is allowed on the return type of a function."
3181    */
3182   if (this->return_type->has_qualifiers()) {
3183      YYLTYPE loc = this->get_location();
3184      _mesa_glsl_error(& loc, state,
3185		       "function `%s' return type has qualifiers", name);
3186   }
3187
3188   /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3189    *
3190    *    "[Sampler types] can only be declared as function parameters
3191    *    or uniform variables (see Section 4.3.5 "Uniform")".
3192    */
3193   if (return_type->contains_sampler()) {
3194      YYLTYPE loc = this->get_location();
3195      _mesa_glsl_error(&loc, state,
3196                       "function `%s' return type can't contain a sampler",
3197                       name);
3198   }
3199
3200   /* Verify that this function's signature either doesn't match a previously
3201    * seen signature for a function with the same name, or, if a match is found,
3202    * that the previously seen signature does not have an associated definition.
3203    */
3204   f = state->symbols->get_function(name);
3205   if (f != NULL && (state->es_shader || f->has_user_signature())) {
3206      sig = f->exact_matching_signature(&hir_parameters);
3207      if (sig != NULL) {
3208	 const char *badvar = sig->qualifiers_match(&hir_parameters);
3209	 if (badvar != NULL) {
3210	    YYLTYPE loc = this->get_location();
3211
3212	    _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
3213			     "qualifiers don't match prototype", name, badvar);
3214	 }
3215
3216	 if (sig->return_type != return_type) {
3217	    YYLTYPE loc = this->get_location();
3218
3219	    _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
3220			     "match prototype", name);
3221	 }
3222
3223	 if (is_definition && sig->is_defined) {
3224	    YYLTYPE loc = this->get_location();
3225
3226	    _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
3227	 }
3228      }
3229   } else {
3230      f = new(ctx) ir_function(name);
3231      if (!state->symbols->add_function(f)) {
3232	 /* This function name shadows a non-function use of the same name. */
3233	 YYLTYPE loc = this->get_location();
3234
3235	 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
3236			  "non-function", name);
3237	 return NULL;
3238      }
3239
3240      emit_function(state, f);
3241   }
3242
3243   /* Verify the return type of main() */
3244   if (strcmp(name, "main") == 0) {
3245      if (! return_type->is_void()) {
3246	 YYLTYPE loc = this->get_location();
3247
3248	 _mesa_glsl_error(& loc, state, "main() must return void");
3249      }
3250
3251      if (!hir_parameters.is_empty()) {
3252	 YYLTYPE loc = this->get_location();
3253
3254	 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
3255      }
3256   }
3257
3258   /* Finish storing the information about this new function in its signature.
3259    */
3260   if (sig == NULL) {
3261      sig = new(ctx) ir_function_signature(return_type);
3262      f->add_signature(sig);
3263   }
3264
3265   sig->replace_parameters(&hir_parameters);
3266   signature = sig;
3267
3268   /* Function declarations (prototypes) do not have r-values.
3269    */
3270   return NULL;
3271}
3272
3273
3274ir_rvalue *
3275ast_function_definition::hir(exec_list *instructions,
3276			     struct _mesa_glsl_parse_state *state)
3277{
3278   prototype->is_definition = true;
3279   prototype->hir(instructions, state);
3280
3281   ir_function_signature *signature = prototype->signature;
3282   if (signature == NULL)
3283      return NULL;
3284
3285   assert(state->current_function == NULL);
3286   state->current_function = signature;
3287   state->found_return = false;
3288
3289   /* Duplicate parameters declared in the prototype as concrete variables.
3290    * Add these to the symbol table.
3291    */
3292   state->symbols->push_scope();
3293   foreach_iter(exec_list_iterator, iter, signature->parameters) {
3294      ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
3295
3296      assert(var != NULL);
3297
3298      /* The only way a parameter would "exist" is if two parameters have
3299       * the same name.
3300       */
3301      if (state->symbols->name_declared_this_scope(var->name)) {
3302	 YYLTYPE loc = this->get_location();
3303
3304	 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
3305      } else {
3306	 state->symbols->add_variable(var);
3307      }
3308   }
3309
3310   /* Convert the body of the function to HIR. */
3311   this->body->hir(&signature->body, state);
3312   signature->is_defined = true;
3313
3314   state->symbols->pop_scope();
3315
3316   assert(state->current_function == signature);
3317   state->current_function = NULL;
3318
3319   if (!signature->return_type->is_void() && !state->found_return) {
3320      YYLTYPE loc = this->get_location();
3321      _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
3322		       "%s, but no return statement",
3323		       signature->function_name(),
3324		       signature->return_type->name);
3325   }
3326
3327   /* Function definitions do not have r-values.
3328    */
3329   return NULL;
3330}
3331
3332
3333ir_rvalue *
3334ast_jump_statement::hir(exec_list *instructions,
3335			struct _mesa_glsl_parse_state *state)
3336{
3337   void *ctx = state;
3338
3339   switch (mode) {
3340   case ast_return: {
3341      ir_return *inst;
3342      assert(state->current_function);
3343
3344      if (opt_return_value) {
3345	 ir_rvalue *const ret = opt_return_value->hir(instructions, state);
3346
3347	 /* The value of the return type can be NULL if the shader says
3348	  * 'return foo();' and foo() is a function that returns void.
3349	  *
3350	  * NOTE: The GLSL spec doesn't say that this is an error.  The type
3351	  * of the return value is void.  If the return type of the function is
3352	  * also void, then this should compile without error.  Seriously.
3353	  */
3354	 const glsl_type *const ret_type =
3355	    (ret == NULL) ? glsl_type::void_type : ret->type;
3356
3357	 /* Implicit conversions are not allowed for return values. */
3358	 if (state->current_function->return_type != ret_type) {
3359	    YYLTYPE loc = this->get_location();
3360
3361	    _mesa_glsl_error(& loc, state,
3362			     "`return' with wrong type %s, in function `%s' "
3363			     "returning %s",
3364			     ret_type->name,
3365			     state->current_function->function_name(),
3366			     state->current_function->return_type->name);
3367	 }
3368
3369	 inst = new(ctx) ir_return(ret);
3370      } else {
3371	 if (state->current_function->return_type->base_type !=
3372	     GLSL_TYPE_VOID) {
3373	    YYLTYPE loc = this->get_location();
3374
3375	    _mesa_glsl_error(& loc, state,
3376			     "`return' with no value, in function %s returning "
3377			     "non-void",
3378			     state->current_function->function_name());
3379	 }
3380	 inst = new(ctx) ir_return;
3381      }
3382
3383      state->found_return = true;
3384      instructions->push_tail(inst);
3385      break;
3386   }
3387
3388   case ast_discard:
3389      if (state->target != fragment_shader) {
3390	 YYLTYPE loc = this->get_location();
3391
3392	 _mesa_glsl_error(& loc, state,
3393			  "`discard' may only appear in a fragment shader");
3394      }
3395      instructions->push_tail(new(ctx) ir_discard);
3396      break;
3397
3398   case ast_break:
3399   case ast_continue:
3400      if (mode == ast_continue &&
3401	  state->loop_nesting_ast == NULL) {
3402	 YYLTYPE loc = this->get_location();
3403
3404	 _mesa_glsl_error(& loc, state,
3405			  "continue may only appear in a loop");
3406      } else if (mode == ast_break &&
3407		 state->loop_nesting_ast == NULL &&
3408		 state->switch_state.switch_nesting_ast == NULL) {
3409	 YYLTYPE loc = this->get_location();
3410
3411	 _mesa_glsl_error(& loc, state,
3412			  "break may only appear in a loop or a switch");
3413      } else {
3414	 /* For a loop, inline the for loop expression again,
3415	  * since we don't know where near the end of
3416	  * the loop body the normal copy of it
3417	  * is going to be placed.
3418	  */
3419	 if (state->loop_nesting_ast != NULL &&
3420	     mode == ast_continue &&
3421	     state->loop_nesting_ast->rest_expression) {
3422	    state->loop_nesting_ast->rest_expression->hir(instructions,
3423							  state);
3424	 }
3425
3426	 if (state->switch_state.is_switch_innermost &&
3427	     mode == ast_break) {
3428	    /* Force break out of switch by setting is_break switch state.
3429	     */
3430	    ir_variable *const is_break_var = state->switch_state.is_break_var;
3431	    ir_dereference_variable *const deref_is_break_var =
3432	       new(ctx) ir_dereference_variable(is_break_var);
3433	    ir_constant *const true_val = new(ctx) ir_constant(true);
3434	    ir_assignment *const set_break_var =
3435	       new(ctx) ir_assignment(deref_is_break_var,
3436				      true_val,
3437				      NULL);
3438
3439	    instructions->push_tail(set_break_var);
3440	 }
3441	 else {
3442	    ir_loop_jump *const jump =
3443	       new(ctx) ir_loop_jump((mode == ast_break)
3444				     ? ir_loop_jump::jump_break
3445				     : ir_loop_jump::jump_continue);
3446	    instructions->push_tail(jump);
3447	 }
3448      }
3449
3450      break;
3451   }
3452
3453   /* Jump instructions do not have r-values.
3454    */
3455   return NULL;
3456}
3457
3458
3459ir_rvalue *
3460ast_selection_statement::hir(exec_list *instructions,
3461			     struct _mesa_glsl_parse_state *state)
3462{
3463   void *ctx = state;
3464
3465   ir_rvalue *const condition = this->condition->hir(instructions, state);
3466
3467   /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
3468    *
3469    *    "Any expression whose type evaluates to a Boolean can be used as the
3470    *    conditional expression bool-expression. Vector types are not accepted
3471    *    as the expression to if."
3472    *
3473    * The checks are separated so that higher quality diagnostics can be
3474    * generated for cases where both rules are violated.
3475    */
3476   if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
3477      YYLTYPE loc = this->condition->get_location();
3478
3479      _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
3480		       "boolean");
3481   }
3482
3483   ir_if *const stmt = new(ctx) ir_if(condition);
3484
3485   if (then_statement != NULL) {
3486      state->symbols->push_scope();
3487      then_statement->hir(& stmt->then_instructions, state);
3488      state->symbols->pop_scope();
3489   }
3490
3491   if (else_statement != NULL) {
3492      state->symbols->push_scope();
3493      else_statement->hir(& stmt->else_instructions, state);
3494      state->symbols->pop_scope();
3495   }
3496
3497   instructions->push_tail(stmt);
3498
3499   /* if-statements do not have r-values.
3500    */
3501   return NULL;
3502}
3503
3504
3505ir_rvalue *
3506ast_switch_statement::hir(exec_list *instructions,
3507			  struct _mesa_glsl_parse_state *state)
3508{
3509   void *ctx = state;
3510
3511   ir_rvalue *const test_expression =
3512      this->test_expression->hir(instructions, state);
3513
3514   /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
3515    *
3516    *    "The type of init-expression in a switch statement must be a
3517    *     scalar integer."
3518    *
3519    * The checks are separated so that higher quality diagnostics can be
3520    * generated for cases where the rule is violated.
3521    */
3522   if (!test_expression->type->is_integer()) {
3523      YYLTYPE loc = this->test_expression->get_location();
3524
3525      _mesa_glsl_error(& loc,
3526		       state,
3527		       "switch-statement expression must be scalar "
3528		       "integer");
3529   }
3530
3531   /* Track the switch-statement nesting in a stack-like manner.
3532    */
3533   struct glsl_switch_state saved = state->switch_state;
3534
3535   state->switch_state.is_switch_innermost = true;
3536   state->switch_state.switch_nesting_ast = this;
3537
3538   /* Initalize is_fallthru state to false.
3539    */
3540   ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
3541   state->switch_state.is_fallthru_var =
3542      new(ctx) ir_variable(glsl_type::bool_type,
3543			   "switch_is_fallthru_tmp",
3544			   ir_var_temporary);
3545   instructions->push_tail(state->switch_state.is_fallthru_var);
3546
3547   ir_dereference_variable *deref_is_fallthru_var =
3548      new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
3549   instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
3550						  is_fallthru_val,
3551						  NULL));
3552
3553   /* Initalize is_break state to false.
3554    */
3555   ir_rvalue *const is_break_val = new (ctx) ir_constant(false);
3556   state->switch_state.is_break_var = new(ctx) ir_variable(glsl_type::bool_type,
3557							   "switch_is_break_tmp",
3558							   ir_var_temporary);
3559   instructions->push_tail(state->switch_state.is_break_var);
3560
3561   ir_dereference_variable *deref_is_break_var =
3562      new(ctx) ir_dereference_variable(state->switch_state.is_break_var);
3563   instructions->push_tail(new(ctx) ir_assignment(deref_is_break_var,
3564						  is_break_val,
3565						  NULL));
3566
3567   /* Cache test expression.
3568    */
3569   test_to_hir(instructions, state);
3570
3571   /* Emit code for body of switch stmt.
3572    */
3573   body->hir(instructions, state);
3574
3575   state->switch_state = saved;
3576
3577     /* Switch statements do not have r-values.
3578      */
3579     return NULL;
3580  }
3581
3582
3583  void
3584  ast_switch_statement::test_to_hir(exec_list *instructions,
3585				    struct _mesa_glsl_parse_state *state)
3586  {
3587     void *ctx = state;
3588
3589     /* Cache value of test expression.
3590      */
3591     ir_rvalue *const test_val =
3592	test_expression->hir(instructions,
3593			     state);
3594
3595     state->switch_state.test_var = new(ctx) ir_variable(glsl_type::int_type,
3596							 "switch_test_tmp",
3597							 ir_var_temporary);
3598     ir_dereference_variable *deref_test_var =
3599	new(ctx) ir_dereference_variable(state->switch_state.test_var);
3600
3601     instructions->push_tail(state->switch_state.test_var);
3602     instructions->push_tail(new(ctx) ir_assignment(deref_test_var,
3603						    test_val,
3604						    NULL));
3605  }
3606
3607
3608  ir_rvalue *
3609  ast_switch_body::hir(exec_list *instructions,
3610		       struct _mesa_glsl_parse_state *state)
3611  {
3612     if (stmts != NULL)
3613	stmts->hir(instructions, state);
3614
3615     /* Switch bodies do not have r-values.
3616      */
3617     return NULL;
3618  }
3619
3620
3621  ir_rvalue *
3622  ast_case_statement_list::hir(exec_list *instructions,
3623			       struct _mesa_glsl_parse_state *state)
3624  {
3625     foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases)
3626	case_stmt->hir(instructions, state);
3627
3628     /* Case statements do not have r-values.
3629      */
3630     return NULL;
3631  }
3632
3633
3634  ir_rvalue *
3635  ast_case_statement::hir(exec_list *instructions,
3636			  struct _mesa_glsl_parse_state *state)
3637  {
3638     labels->hir(instructions, state);
3639
3640     /* Conditionally set fallthru state based on break state.
3641      */
3642     ir_constant *const false_val = new(state) ir_constant(false);
3643     ir_dereference_variable *const deref_is_fallthru_var =
3644	new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
3645     ir_dereference_variable *const deref_is_break_var =
3646	new(state) ir_dereference_variable(state->switch_state.is_break_var);
3647     ir_assignment *const reset_fallthru_on_break =
3648	new(state) ir_assignment(deref_is_fallthru_var,
3649				 false_val,
3650				 deref_is_break_var);
3651     instructions->push_tail(reset_fallthru_on_break);
3652
3653     /* Guard case statements depending on fallthru state.
3654      */
3655     ir_dereference_variable *const deref_fallthru_guard =
3656	new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
3657     ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
3658
3659     foreach_list_typed (ast_node, stmt, link, & this->stmts)
3660	stmt->hir(& test_fallthru->then_instructions, state);
3661
3662     instructions->push_tail(test_fallthru);
3663
3664     /* Case statements do not have r-values.
3665      */
3666     return NULL;
3667  }
3668
3669
3670  ir_rvalue *
3671  ast_case_label_list::hir(exec_list *instructions,
3672			   struct _mesa_glsl_parse_state *state)
3673  {
3674     foreach_list_typed (ast_case_label, label, link, & this->labels)
3675	label->hir(instructions, state);
3676
3677     /* Case labels do not have r-values.
3678      */
3679     return NULL;
3680  }
3681
3682
3683  ir_rvalue *
3684  ast_case_label::hir(exec_list *instructions,
3685		      struct _mesa_glsl_parse_state *state)
3686  {
3687     void *ctx = state;
3688
3689     ir_dereference_variable *deref_fallthru_var =
3690	new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
3691
3692     ir_rvalue *const true_val = new(ctx) ir_constant(true);
3693
3694     /* If not default case, ...
3695      */
3696     if (this->test_value != NULL) {
3697	/* Conditionally set fallthru state based on
3698	 * comparison of cached test expression value to case label.
3699	 */
3700	ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
3701	ir_constant *label_const = label_rval->constant_expression_value();
3702
3703	if (!label_const) {
3704	   YYLTYPE loc = this->test_value->get_location();
3705
3706	   _mesa_glsl_error(& loc, state,
3707			    "switch statement case label must be a "
3708			    "constant expression");
3709
3710	   /* Stuff a dummy value in to allow processing to continue. */
3711	   label_const = new(ctx) ir_constant(0);
3712	}
3713
3714	ir_dereference_variable *deref_test_var =
3715	   new(ctx) ir_dereference_variable(state->switch_state.test_var);
3716
3717	ir_rvalue *const test_cond = new(ctx) ir_expression(ir_binop_all_equal,
3718							    glsl_type::bool_type,
3719							    label_const,
3720							    deref_test_var);
3721
3722	ir_assignment *set_fallthru_on_test =
3723	   new(ctx) ir_assignment(deref_fallthru_var,
3724				  true_val,
3725				  test_cond);
3726
3727	instructions->push_tail(set_fallthru_on_test);
3728     } else { /* default case */
3729	/* Set falltrhu state.
3730	 */
3731	ir_assignment *set_fallthru =
3732	   new(ctx) ir_assignment(deref_fallthru_var,
3733				  true_val,
3734				  NULL);
3735
3736	instructions->push_tail(set_fallthru);
3737     }
3738
3739     /* Case statements do not have r-values.
3740      */
3741     return NULL;
3742  }
3743
3744
3745  void
3746  ast_iteration_statement::condition_to_hir(ir_loop *stmt,
3747					    struct _mesa_glsl_parse_state *state)
3748  {
3749     void *ctx = state;
3750
3751     if (condition != NULL) {
3752	ir_rvalue *const cond =
3753	   condition->hir(& stmt->body_instructions, state);
3754
3755	if ((cond == NULL)
3756	    || !cond->type->is_boolean() || !cond->type->is_scalar()) {
3757	   YYLTYPE loc = condition->get_location();
3758
3759	   _mesa_glsl_error(& loc, state,
3760			    "loop condition must be scalar boolean");
3761	} else {
3762	   /* As the first code in the loop body, generate a block that looks
3763	    * like 'if (!condition) break;' as the loop termination condition.
3764	    */
3765	   ir_rvalue *const not_cond =
3766	      new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
3767				     NULL);
3768
3769	   ir_if *const if_stmt = new(ctx) ir_if(not_cond);
3770
3771	   ir_jump *const break_stmt =
3772	      new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
3773
3774	   if_stmt->then_instructions.push_tail(break_stmt);
3775	   stmt->body_instructions.push_tail(if_stmt);
3776	}
3777     }
3778  }
3779
3780
3781  ir_rvalue *
3782  ast_iteration_statement::hir(exec_list *instructions,
3783			       struct _mesa_glsl_parse_state *state)
3784  {
3785     void *ctx = state;
3786
3787     /* For-loops and while-loops start a new scope, but do-while loops do not.
3788      */
3789     if (mode != ast_do_while)
3790	state->symbols->push_scope();
3791
3792     if (init_statement != NULL)
3793	init_statement->hir(instructions, state);
3794
3795     ir_loop *const stmt = new(ctx) ir_loop();
3796     instructions->push_tail(stmt);
3797
3798     /* Track the current loop nesting.
3799      */
3800     ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
3801
3802     state->loop_nesting_ast = this;
3803
3804     /* Likewise, indicate that following code is closest to a loop,
3805      * NOT closest to a switch.
3806      */
3807     bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
3808     state->switch_state.is_switch_innermost = false;
3809
3810     if (mode != ast_do_while)
3811	condition_to_hir(stmt, state);
3812
3813     if (body != NULL)
3814	body->hir(& stmt->body_instructions, state);
3815
3816     if (rest_expression != NULL)
3817	rest_expression->hir(& stmt->body_instructions, state);
3818
3819     if (mode == ast_do_while)
3820	condition_to_hir(stmt, state);
3821
3822     if (mode != ast_do_while)
3823	state->symbols->pop_scope();
3824
3825     /* Restore previous nesting before returning.
3826      */
3827     state->loop_nesting_ast = nesting_ast;
3828     state->switch_state.is_switch_innermost = saved_is_switch_innermost;
3829
3830   /* Loops do not have r-values.
3831    */
3832   return NULL;
3833}
3834
3835
3836ir_rvalue *
3837ast_type_specifier::hir(exec_list *instructions,
3838			  struct _mesa_glsl_parse_state *state)
3839{
3840   if (!this->is_precision_statement && this->structure == NULL)
3841      return NULL;
3842
3843   YYLTYPE loc = this->get_location();
3844
3845   if (this->precision != ast_precision_none
3846       && state->language_version != 100
3847       && state->language_version < 130) {
3848      _mesa_glsl_error(&loc, state,
3849                       "precision qualifiers exist only in "
3850                       "GLSL ES 1.00, and GLSL 1.30 and later");
3851      return NULL;
3852   }
3853   if (this->precision != ast_precision_none
3854       && this->structure != NULL) {
3855      _mesa_glsl_error(&loc, state,
3856                       "precision qualifiers do not apply to structures");
3857      return NULL;
3858   }
3859
3860   /* If this is a precision statement, check that the type to which it is
3861    * applied is either float or int.
3862    *
3863    * From section 4.5.3 of the GLSL 1.30 spec:
3864    *    "The precision statement
3865    *       precision precision-qualifier type;
3866    *    can be used to establish a default precision qualifier. The type
3867    *    field can be either int or float [...].  Any other types or
3868    *    qualifiers will result in an error.
3869    */
3870   if (this->is_precision_statement) {
3871      assert(this->precision != ast_precision_none);
3872      assert(this->structure == NULL); /* The check for structures was
3873                                        * performed above. */
3874      if (this->is_array) {
3875         _mesa_glsl_error(&loc, state,
3876                          "default precision statements do not apply to "
3877                          "arrays");
3878         return NULL;
3879      }
3880      if (this->type_specifier != ast_float
3881          && this->type_specifier != ast_int) {
3882         _mesa_glsl_error(&loc, state,
3883                          "default precision statements apply only to types "
3884                          "float and int");
3885         return NULL;
3886      }
3887
3888      /* FINISHME: Translate precision statements into IR. */
3889      return NULL;
3890   }
3891
3892   if (this->structure != NULL)
3893      return this->structure->hir(instructions, state);
3894
3895   return NULL;
3896}
3897
3898
3899ir_rvalue *
3900ast_struct_specifier::hir(exec_list *instructions,
3901			  struct _mesa_glsl_parse_state *state)
3902{
3903   unsigned decl_count = 0;
3904
3905   /* Make an initial pass over the list of structure fields to determine how
3906    * many there are.  Each element in this list is an ast_declarator_list.
3907    * This means that we actually need to count the number of elements in the
3908    * 'declarations' list in each of the elements.
3909    */
3910   foreach_list_typed (ast_declarator_list, decl_list, link,
3911		       &this->declarations) {
3912      foreach_list_const (decl_ptr, & decl_list->declarations) {
3913	 decl_count++;
3914      }
3915   }
3916
3917   /* Allocate storage for the structure fields and process the field
3918    * declarations.  As the declarations are processed, try to also convert
3919    * the types to HIR.  This ensures that structure definitions embedded in
3920    * other structure definitions are processed.
3921    */
3922   glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
3923						  decl_count);
3924
3925   unsigned i = 0;
3926   foreach_list_typed (ast_declarator_list, decl_list, link,
3927		       &this->declarations) {
3928      const char *type_name;
3929
3930      decl_list->type->specifier->hir(instructions, state);
3931
3932      /* Section 10.9 of the GLSL ES 1.00 specification states that
3933       * embedded structure definitions have been removed from the language.
3934       */
3935      if (state->es_shader && decl_list->type->specifier->structure != NULL) {
3936	 YYLTYPE loc = this->get_location();
3937	 _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
3938			  "not allowed in GLSL ES 1.00.");
3939      }
3940
3941      const glsl_type *decl_type =
3942	 decl_list->type->specifier->glsl_type(& type_name, state);
3943
3944      foreach_list_typed (ast_declaration, decl, link,
3945			  &decl_list->declarations) {
3946	 const struct glsl_type *field_type = decl_type;
3947	 if (decl->is_array) {
3948	    YYLTYPE loc = decl->get_location();
3949	    field_type = process_array_type(&loc, decl_type, decl->array_size,
3950					    state);
3951	 }
3952	 fields[i].type = (field_type != NULL)
3953	    ? field_type : glsl_type::error_type;
3954	 fields[i].name = decl->identifier;
3955	 i++;
3956      }
3957   }
3958
3959   assert(i == decl_count);
3960
3961   const glsl_type *t =
3962      glsl_type::get_record_instance(fields, decl_count, this->name);
3963
3964   YYLTYPE loc = this->get_location();
3965   if (!state->symbols->add_type(name, t)) {
3966      _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
3967   } else {
3968      const glsl_type **s = reralloc(state, state->user_structures,
3969				     const glsl_type *,
3970				     state->num_user_structures + 1);
3971      if (s != NULL) {
3972	 s[state->num_user_structures] = t;
3973	 state->user_structures = s;
3974	 state->num_user_structures++;
3975      }
3976   }
3977
3978   /* Structure type definitions do not have r-values.
3979    */
3980   return NULL;
3981}
3982