ast_to_hir.cpp revision c475a54578bf5473c6c62bc5468ef4fe555164d7
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	      ir_rvalue *lhs, ir_rvalue *rhs, bool is_initializer,
668	      YYLTYPE lhs_loc)
669{
670   void *ctx = state;
671   bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
672
673   if (!error_emitted) {
674      if (lhs->variable_referenced() != NULL
675          && lhs->variable_referenced()->read_only) {
676         _mesa_glsl_error(&lhs_loc, state,
677                          "assignment to read-only variable '%s'",
678                          lhs->variable_referenced()->name);
679         error_emitted = true;
680
681      } else if (state->language_version <= 110 && lhs->type->is_array()) {
682	 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
683	  *
684	  *    "Other binary or unary expressions, non-dereferenced
685	  *     arrays, function names, swizzles with repeated fields,
686	  *     and constants cannot be l-values."
687	  */
688	 _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
689			  "allowed in GLSL 1.10 or GLSL ES 1.00.");
690	 error_emitted = true;
691      } else if (!lhs->is_lvalue()) {
692	 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
693	 error_emitted = true;
694      }
695   }
696
697   ir_rvalue *new_rhs =
698      validate_assignment(state, lhs->type, rhs, is_initializer);
699   if (new_rhs == NULL) {
700      _mesa_glsl_error(& lhs_loc, state, "type mismatch");
701   } else {
702      rhs = new_rhs;
703
704      /* If the LHS array was not declared with a size, it takes it size from
705       * the RHS.  If the LHS is an l-value and a whole array, it must be a
706       * dereference of a variable.  Any other case would require that the LHS
707       * is either not an l-value or not a whole array.
708       */
709      if (lhs->type->array_size() == 0) {
710	 ir_dereference *const d = lhs->as_dereference();
711
712	 assert(d != NULL);
713
714	 ir_variable *const var = d->variable_referenced();
715
716	 assert(var != NULL);
717
718	 if (var->max_array_access >= unsigned(rhs->type->array_size())) {
719	    /* FINISHME: This should actually log the location of the RHS. */
720	    _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
721			     "previous access",
722			     var->max_array_access);
723	 }
724
725	 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
726						   rhs->type->array_size());
727	 d->type = var->type;
728      }
729      mark_whole_array_access(rhs);
730      mark_whole_array_access(lhs);
731   }
732
733   /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
734    * but not post_inc) need the converted assigned value as an rvalue
735    * to handle things like:
736    *
737    * i = j += 1;
738    *
739    * So we always just store the computed value being assigned to a
740    * temporary and return a deref of that temporary.  If the rvalue
741    * ends up not being used, the temp will get copy-propagated out.
742    */
743   ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
744					   ir_var_temporary);
745   ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
746   instructions->push_tail(var);
747   instructions->push_tail(new(ctx) ir_assignment(deref_var,
748						  rhs,
749						  NULL));
750   deref_var = new(ctx) ir_dereference_variable(var);
751
752   if (!error_emitted)
753      instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
754
755   return new(ctx) ir_dereference_variable(var);
756}
757
758static ir_rvalue *
759get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
760{
761   void *ctx = ralloc_parent(lvalue);
762   ir_variable *var;
763
764   var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
765			      ir_var_temporary);
766   instructions->push_tail(var);
767   var->mode = ir_var_auto;
768
769   instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
770						  lvalue, NULL));
771
772   /* Once we've created this temporary, mark it read only so it's no
773    * longer considered an lvalue.
774    */
775   var->read_only = true;
776
777   return new(ctx) ir_dereference_variable(var);
778}
779
780
781ir_rvalue *
782ast_node::hir(exec_list *instructions,
783	      struct _mesa_glsl_parse_state *state)
784{
785   (void) instructions;
786   (void) state;
787
788   return NULL;
789}
790
791static ir_rvalue *
792do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
793{
794   int join_op;
795   ir_rvalue *cmp = NULL;
796
797   if (operation == ir_binop_all_equal)
798      join_op = ir_binop_logic_and;
799   else
800      join_op = ir_binop_logic_or;
801
802   switch (op0->type->base_type) {
803   case GLSL_TYPE_FLOAT:
804   case GLSL_TYPE_UINT:
805   case GLSL_TYPE_INT:
806   case GLSL_TYPE_BOOL:
807      return new(mem_ctx) ir_expression(operation, op0, op1);
808
809   case GLSL_TYPE_ARRAY: {
810      for (unsigned int i = 0; i < op0->type->length; i++) {
811	 ir_rvalue *e0, *e1, *result;
812
813	 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
814						new(mem_ctx) ir_constant(i));
815	 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
816						new(mem_ctx) ir_constant(i));
817	 result = do_comparison(mem_ctx, operation, e0, e1);
818
819	 if (cmp) {
820	    cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
821	 } else {
822	    cmp = result;
823	 }
824      }
825
826      mark_whole_array_access(op0);
827      mark_whole_array_access(op1);
828      break;
829   }
830
831   case GLSL_TYPE_STRUCT: {
832      for (unsigned int i = 0; i < op0->type->length; i++) {
833	 ir_rvalue *e0, *e1, *result;
834	 const char *field_name = op0->type->fields.structure[i].name;
835
836	 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
837						 field_name);
838	 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
839						 field_name);
840	 result = do_comparison(mem_ctx, operation, e0, e1);
841
842	 if (cmp) {
843	    cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
844	 } else {
845	    cmp = result;
846	 }
847      }
848      break;
849   }
850
851   case GLSL_TYPE_ERROR:
852   case GLSL_TYPE_VOID:
853   case GLSL_TYPE_SAMPLER:
854      /* I assume a comparison of a struct containing a sampler just
855       * ignores the sampler present in the type.
856       */
857      break;
858
859   default:
860      assert(!"Should not get here.");
861      break;
862   }
863
864   if (cmp == NULL)
865      cmp = new(mem_ctx) ir_constant(true);
866
867   return cmp;
868}
869
870/* For logical operations, we want to ensure that the operands are
871 * scalar booleans.  If it isn't, emit an error and return a constant
872 * boolean to avoid triggering cascading error messages.
873 */
874ir_rvalue *
875get_scalar_boolean_operand(exec_list *instructions,
876			   struct _mesa_glsl_parse_state *state,
877			   ast_expression *parent_expr,
878			   int operand,
879			   const char *operand_name,
880			   bool *error_emitted)
881{
882   ast_expression *expr = parent_expr->subexpressions[operand];
883   void *ctx = state;
884   ir_rvalue *val = expr->hir(instructions, state);
885
886   if (val->type->is_boolean() && val->type->is_scalar())
887      return val;
888
889   if (!*error_emitted) {
890      YYLTYPE loc = expr->get_location();
891      _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
892		       operand_name,
893		       parent_expr->operator_string(parent_expr->oper));
894      *error_emitted = true;
895   }
896
897   return new(ctx) ir_constant(true);
898}
899
900/**
901 * If name refers to a builtin array whose maximum allowed size is less than
902 * size, report an error and return true.  Otherwise return false.
903 */
904static bool
905check_builtin_array_max_size(const char *name, unsigned size,
906                             YYLTYPE loc, struct _mesa_glsl_parse_state *state)
907{
908   if ((strcmp("gl_TexCoord", name) == 0)
909       && (size > state->Const.MaxTextureCoords)) {
910      /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
911       *
912       *     "The size [of gl_TexCoord] can be at most
913       *     gl_MaxTextureCoords."
914       */
915      _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
916                       "be larger than gl_MaxTextureCoords (%u)\n",
917                       state->Const.MaxTextureCoords);
918      return true;
919   } else if (strcmp("gl_ClipDistance", name) == 0
920              && size > state->Const.MaxClipPlanes) {
921      /* From section 7.1 (Vertex Shader Special Variables) of the
922       * GLSL 1.30 spec:
923       *
924       *   "The gl_ClipDistance array is predeclared as unsized and
925       *   must be sized by the shader either redeclaring it with a
926       *   size or indexing it only with integral constant
927       *   expressions. ... The size can be at most
928       *   gl_MaxClipDistances."
929       */
930      _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
931                       "be larger than gl_MaxClipDistances (%u)\n",
932                       state->Const.MaxClipPlanes);
933      return true;
934   }
935   return false;
936}
937
938ir_rvalue *
939ast_expression::hir(exec_list *instructions,
940		    struct _mesa_glsl_parse_state *state)
941{
942   void *ctx = state;
943   static const int operations[AST_NUM_OPERATORS] = {
944      -1,               /* ast_assign doesn't convert to ir_expression. */
945      -1,               /* ast_plus doesn't convert to ir_expression. */
946      ir_unop_neg,
947      ir_binop_add,
948      ir_binop_sub,
949      ir_binop_mul,
950      ir_binop_div,
951      ir_binop_mod,
952      ir_binop_lshift,
953      ir_binop_rshift,
954      ir_binop_less,
955      ir_binop_greater,
956      ir_binop_lequal,
957      ir_binop_gequal,
958      ir_binop_all_equal,
959      ir_binop_any_nequal,
960      ir_binop_bit_and,
961      ir_binop_bit_xor,
962      ir_binop_bit_or,
963      ir_unop_bit_not,
964      ir_binop_logic_and,
965      ir_binop_logic_xor,
966      ir_binop_logic_or,
967      ir_unop_logic_not,
968
969      /* Note: The following block of expression types actually convert
970       * to multiple IR instructions.
971       */
972      ir_binop_mul,     /* ast_mul_assign */
973      ir_binop_div,     /* ast_div_assign */
974      ir_binop_mod,     /* ast_mod_assign */
975      ir_binop_add,     /* ast_add_assign */
976      ir_binop_sub,     /* ast_sub_assign */
977      ir_binop_lshift,  /* ast_ls_assign */
978      ir_binop_rshift,  /* ast_rs_assign */
979      ir_binop_bit_and, /* ast_and_assign */
980      ir_binop_bit_xor, /* ast_xor_assign */
981      ir_binop_bit_or,  /* ast_or_assign */
982
983      -1,               /* ast_conditional doesn't convert to ir_expression. */
984      ir_binop_add,     /* ast_pre_inc. */
985      ir_binop_sub,     /* ast_pre_dec. */
986      ir_binop_add,     /* ast_post_inc. */
987      ir_binop_sub,     /* ast_post_dec. */
988      -1,               /* ast_field_selection doesn't conv to ir_expression. */
989      -1,               /* ast_array_index doesn't convert to ir_expression. */
990      -1,               /* ast_function_call doesn't conv to ir_expression. */
991      -1,               /* ast_identifier doesn't convert to ir_expression. */
992      -1,               /* ast_int_constant doesn't convert to ir_expression. */
993      -1,               /* ast_uint_constant doesn't conv to ir_expression. */
994      -1,               /* ast_float_constant doesn't conv to ir_expression. */
995      -1,               /* ast_bool_constant doesn't conv to ir_expression. */
996      -1,               /* ast_sequence doesn't convert to ir_expression. */
997   };
998   ir_rvalue *result = NULL;
999   ir_rvalue *op[3];
1000   const struct glsl_type *type; /* a temporary variable for switch cases */
1001   bool error_emitted = false;
1002   YYLTYPE loc;
1003
1004   loc = this->get_location();
1005
1006   switch (this->oper) {
1007   case ast_assign: {
1008      op[0] = this->subexpressions[0]->hir(instructions, state);
1009      op[1] = this->subexpressions[1]->hir(instructions, state);
1010
1011      result = do_assignment(instructions, state, op[0], op[1], false,
1012			     this->subexpressions[0]->get_location());
1013      error_emitted = result->type->is_error();
1014      break;
1015   }
1016
1017   case ast_plus:
1018      op[0] = this->subexpressions[0]->hir(instructions, state);
1019
1020      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1021
1022      error_emitted = type->is_error();
1023
1024      result = op[0];
1025      break;
1026
1027   case ast_neg:
1028      op[0] = this->subexpressions[0]->hir(instructions, state);
1029
1030      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1031
1032      error_emitted = type->is_error();
1033
1034      result = new(ctx) ir_expression(operations[this->oper], type,
1035				      op[0], NULL);
1036      break;
1037
1038   case ast_add:
1039   case ast_sub:
1040   case ast_mul:
1041   case ast_div:
1042      op[0] = this->subexpressions[0]->hir(instructions, state);
1043      op[1] = this->subexpressions[1]->hir(instructions, state);
1044
1045      type = arithmetic_result_type(op[0], op[1],
1046				    (this->oper == ast_mul),
1047				    state, & loc);
1048      error_emitted = type->is_error();
1049
1050      result = new(ctx) ir_expression(operations[this->oper], type,
1051				      op[0], op[1]);
1052      break;
1053
1054   case ast_mod:
1055      op[0] = this->subexpressions[0]->hir(instructions, state);
1056      op[1] = this->subexpressions[1]->hir(instructions, state);
1057
1058      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1059
1060      assert(operations[this->oper] == ir_binop_mod);
1061
1062      result = new(ctx) ir_expression(operations[this->oper], type,
1063				      op[0], op[1]);
1064      error_emitted = type->is_error();
1065      break;
1066
1067   case ast_lshift:
1068   case ast_rshift:
1069       if (state->language_version < 130) {
1070          _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
1071              operator_string(this->oper));
1072          error_emitted = true;
1073       }
1074
1075       op[0] = this->subexpressions[0]->hir(instructions, state);
1076       op[1] = this->subexpressions[1]->hir(instructions, state);
1077       type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1078                                &loc);
1079       result = new(ctx) ir_expression(operations[this->oper], type,
1080                                       op[0], op[1]);
1081       error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1082       break;
1083
1084   case ast_less:
1085   case ast_greater:
1086   case ast_lequal:
1087   case ast_gequal:
1088      op[0] = this->subexpressions[0]->hir(instructions, state);
1089      op[1] = this->subexpressions[1]->hir(instructions, state);
1090
1091      type = relational_result_type(op[0], op[1], state, & loc);
1092
1093      /* The relational operators must either generate an error or result
1094       * in a scalar boolean.  See page 57 of the GLSL 1.50 spec.
1095       */
1096      assert(type->is_error()
1097	     || ((type->base_type == GLSL_TYPE_BOOL)
1098		 && type->is_scalar()));
1099
1100      result = new(ctx) ir_expression(operations[this->oper], type,
1101				      op[0], op[1]);
1102      error_emitted = type->is_error();
1103      break;
1104
1105   case ast_nequal:
1106   case ast_equal:
1107      op[0] = this->subexpressions[0]->hir(instructions, state);
1108      op[1] = this->subexpressions[1]->hir(instructions, state);
1109
1110      /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1111       *
1112       *    "The equality operators equal (==), and not equal (!=)
1113       *    operate on all types. They result in a scalar Boolean. If
1114       *    the operand types do not match, then there must be a
1115       *    conversion from Section 4.1.10 "Implicit Conversions"
1116       *    applied to one operand that can make them match, in which
1117       *    case this conversion is done."
1118       */
1119      if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1120	   && !apply_implicit_conversion(op[1]->type, op[0], state))
1121	  || (op[0]->type != op[1]->type)) {
1122	 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1123			  "type", (this->oper == ast_equal) ? "==" : "!=");
1124	 error_emitted = true;
1125      } else if ((state->language_version <= 110)
1126		 && (op[0]->type->is_array() || op[1]->type->is_array())) {
1127	 _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
1128			  "GLSL 1.10");
1129	 error_emitted = true;
1130      }
1131
1132      if (error_emitted) {
1133	 result = new(ctx) ir_constant(false);
1134      } else {
1135	 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1136	 assert(result->type == glsl_type::bool_type);
1137      }
1138      break;
1139
1140   case ast_bit_and:
1141   case ast_bit_xor:
1142   case ast_bit_or:
1143      op[0] = this->subexpressions[0]->hir(instructions, state);
1144      op[1] = this->subexpressions[1]->hir(instructions, state);
1145      type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1146                                   state, &loc);
1147      result = new(ctx) ir_expression(operations[this->oper], type,
1148				      op[0], op[1]);
1149      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1150      break;
1151
1152   case ast_bit_not:
1153      op[0] = this->subexpressions[0]->hir(instructions, state);
1154
1155      if (state->language_version < 130) {
1156	 _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
1157	 error_emitted = true;
1158      }
1159
1160      if (!op[0]->type->is_integer()) {
1161	 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1162	 error_emitted = true;
1163      }
1164
1165      type = op[0]->type;
1166      result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1167      break;
1168
1169   case ast_logic_and: {
1170      exec_list rhs_instructions;
1171      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1172					 "LHS", &error_emitted);
1173      op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1174					 "RHS", &error_emitted);
1175
1176      ir_constant *op0_const = op[0]->constant_expression_value();
1177      if (op0_const) {
1178	 if (op0_const->value.b[0]) {
1179	    instructions->append_list(&rhs_instructions);
1180	    result = op[1];
1181	 } else {
1182	    result = op0_const;
1183	 }
1184	 type = glsl_type::bool_type;
1185      } else {
1186	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1187						       "and_tmp",
1188						       ir_var_temporary);
1189	 instructions->push_tail(tmp);
1190
1191	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1192	 instructions->push_tail(stmt);
1193
1194	 stmt->then_instructions.append_list(&rhs_instructions);
1195	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1196	 ir_assignment *const then_assign =
1197	    new(ctx) ir_assignment(then_deref, op[1], NULL);
1198	 stmt->then_instructions.push_tail(then_assign);
1199
1200	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1201	 ir_assignment *const else_assign =
1202	    new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
1203	 stmt->else_instructions.push_tail(else_assign);
1204
1205	 result = new(ctx) ir_dereference_variable(tmp);
1206	 type = tmp->type;
1207      }
1208      break;
1209   }
1210
1211   case ast_logic_or: {
1212      exec_list rhs_instructions;
1213      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1214					 "LHS", &error_emitted);
1215      op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1216					 "RHS", &error_emitted);
1217
1218      ir_constant *op0_const = op[0]->constant_expression_value();
1219      if (op0_const) {
1220	 if (op0_const->value.b[0]) {
1221	    result = op0_const;
1222	 } else {
1223	    result = op[1];
1224	 }
1225	 type = glsl_type::bool_type;
1226      } else {
1227	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1228						       "or_tmp",
1229						       ir_var_temporary);
1230	 instructions->push_tail(tmp);
1231
1232	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1233	 instructions->push_tail(stmt);
1234
1235	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1236	 ir_assignment *const then_assign =
1237	    new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
1238	 stmt->then_instructions.push_tail(then_assign);
1239
1240	 stmt->else_instructions.append_list(&rhs_instructions);
1241	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1242	 ir_assignment *const else_assign =
1243	    new(ctx) ir_assignment(else_deref, op[1], NULL);
1244	 stmt->else_instructions.push_tail(else_assign);
1245
1246	 result = new(ctx) ir_dereference_variable(tmp);
1247	 type = tmp->type;
1248      }
1249      break;
1250   }
1251
1252   case ast_logic_xor:
1253      /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1254       *
1255       *    "The logical binary operators and (&&), or ( | | ), and
1256       *     exclusive or (^^). They operate only on two Boolean
1257       *     expressions and result in a Boolean expression."
1258       */
1259      op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1260					 &error_emitted);
1261      op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1262					 &error_emitted);
1263
1264      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1265				      op[0], op[1]);
1266      break;
1267
1268   case ast_logic_not:
1269      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1270					 "operand", &error_emitted);
1271
1272      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1273				      op[0], NULL);
1274      break;
1275
1276   case ast_mul_assign:
1277   case ast_div_assign:
1278   case ast_add_assign:
1279   case ast_sub_assign: {
1280      op[0] = this->subexpressions[0]->hir(instructions, state);
1281      op[1] = this->subexpressions[1]->hir(instructions, state);
1282
1283      type = arithmetic_result_type(op[0], op[1],
1284				    (this->oper == ast_mul_assign),
1285				    state, & loc);
1286
1287      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1288						   op[0], op[1]);
1289
1290      result = do_assignment(instructions, state,
1291			     op[0]->clone(ctx, NULL), temp_rhs, false,
1292			     this->subexpressions[0]->get_location());
1293      error_emitted = (op[0]->type->is_error());
1294
1295      /* GLSL 1.10 does not allow array assignment.  However, we don't have to
1296       * explicitly test for this because none of the binary expression
1297       * operators allow array operands either.
1298       */
1299
1300      break;
1301   }
1302
1303   case ast_mod_assign: {
1304      op[0] = this->subexpressions[0]->hir(instructions, state);
1305      op[1] = this->subexpressions[1]->hir(instructions, state);
1306
1307      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1308
1309      assert(operations[this->oper] == ir_binop_mod);
1310
1311      ir_rvalue *temp_rhs;
1312      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1313					op[0], op[1]);
1314
1315      result = do_assignment(instructions, state,
1316			     op[0]->clone(ctx, NULL), temp_rhs, false,
1317			     this->subexpressions[0]->get_location());
1318      error_emitted = type->is_error();
1319      break;
1320   }
1321
1322   case ast_ls_assign:
1323   case ast_rs_assign: {
1324      op[0] = this->subexpressions[0]->hir(instructions, state);
1325      op[1] = this->subexpressions[1]->hir(instructions, state);
1326      type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1327                               &loc);
1328      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1329                                                   type, op[0], op[1]);
1330      result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1331                             temp_rhs, false,
1332                             this->subexpressions[0]->get_location());
1333      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1334      break;
1335   }
1336
1337   case ast_and_assign:
1338   case ast_xor_assign:
1339   case ast_or_assign: {
1340      op[0] = this->subexpressions[0]->hir(instructions, state);
1341      op[1] = this->subexpressions[1]->hir(instructions, state);
1342      type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1343                                   state, &loc);
1344      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1345                                                   type, op[0], op[1]);
1346      result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
1347                             temp_rhs, false,
1348                             this->subexpressions[0]->get_location());
1349      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1350      break;
1351   }
1352
1353   case ast_conditional: {
1354      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1355       *
1356       *    "The ternary selection operator (?:). It operates on three
1357       *    expressions (exp1 ? exp2 : exp3). This operator evaluates the
1358       *    first expression, which must result in a scalar Boolean."
1359       */
1360      op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1361					 "condition", &error_emitted);
1362
1363      /* The :? operator is implemented by generating an anonymous temporary
1364       * followed by an if-statement.  The last instruction in each branch of
1365       * the if-statement assigns a value to the anonymous temporary.  This
1366       * temporary is the r-value of the expression.
1367       */
1368      exec_list then_instructions;
1369      exec_list else_instructions;
1370
1371      op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1372      op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1373
1374      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1375       *
1376       *     "The second and third expressions can be any type, as
1377       *     long their types match, or there is a conversion in
1378       *     Section 4.1.10 "Implicit Conversions" that can be applied
1379       *     to one of the expressions to make their types match. This
1380       *     resulting matching type is the type of the entire
1381       *     expression."
1382       */
1383      if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1384	   && !apply_implicit_conversion(op[2]->type, op[1], state))
1385	  || (op[1]->type != op[2]->type)) {
1386	 YYLTYPE loc = this->subexpressions[1]->get_location();
1387
1388	 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1389			  "operator must have matching types.");
1390	 error_emitted = true;
1391	 type = glsl_type::error_type;
1392      } else {
1393	 type = op[1]->type;
1394      }
1395
1396      /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1397       *
1398       *    "The second and third expressions must be the same type, but can
1399       *    be of any type other than an array."
1400       */
1401      if ((state->language_version <= 110) && type->is_array()) {
1402	 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1403			  "operator must not be arrays.");
1404	 error_emitted = true;
1405      }
1406
1407      ir_constant *cond_val = op[0]->constant_expression_value();
1408      ir_constant *then_val = op[1]->constant_expression_value();
1409      ir_constant *else_val = op[2]->constant_expression_value();
1410
1411      if (then_instructions.is_empty()
1412	  && else_instructions.is_empty()
1413	  && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1414	 result = (cond_val->value.b[0]) ? then_val : else_val;
1415      } else {
1416	 ir_variable *const tmp =
1417	    new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1418	 instructions->push_tail(tmp);
1419
1420	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1421	 instructions->push_tail(stmt);
1422
1423	 then_instructions.move_nodes_to(& stmt->then_instructions);
1424	 ir_dereference *const then_deref =
1425	    new(ctx) ir_dereference_variable(tmp);
1426	 ir_assignment *const then_assign =
1427	    new(ctx) ir_assignment(then_deref, op[1], NULL);
1428	 stmt->then_instructions.push_tail(then_assign);
1429
1430	 else_instructions.move_nodes_to(& stmt->else_instructions);
1431	 ir_dereference *const else_deref =
1432	    new(ctx) ir_dereference_variable(tmp);
1433	 ir_assignment *const else_assign =
1434	    new(ctx) ir_assignment(else_deref, op[2], NULL);
1435	 stmt->else_instructions.push_tail(else_assign);
1436
1437	 result = new(ctx) ir_dereference_variable(tmp);
1438      }
1439      break;
1440   }
1441
1442   case ast_pre_inc:
1443   case ast_pre_dec: {
1444      op[0] = this->subexpressions[0]->hir(instructions, state);
1445      if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1446	 op[1] = new(ctx) ir_constant(1.0f);
1447      else
1448	 op[1] = new(ctx) ir_constant(1);
1449
1450      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1451
1452      ir_rvalue *temp_rhs;
1453      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1454					op[0], op[1]);
1455
1456      result = do_assignment(instructions, state,
1457			     op[0]->clone(ctx, NULL), temp_rhs, false,
1458			     this->subexpressions[0]->get_location());
1459      error_emitted = op[0]->type->is_error();
1460      break;
1461   }
1462
1463   case ast_post_inc:
1464   case ast_post_dec: {
1465      op[0] = this->subexpressions[0]->hir(instructions, state);
1466      if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1467	 op[1] = new(ctx) ir_constant(1.0f);
1468      else
1469	 op[1] = new(ctx) ir_constant(1);
1470
1471      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1472
1473      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1474
1475      ir_rvalue *temp_rhs;
1476      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1477					op[0], op[1]);
1478
1479      /* Get a temporary of a copy of the lvalue before it's modified.
1480       * This may get thrown away later.
1481       */
1482      result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1483
1484      (void)do_assignment(instructions, state,
1485			  op[0]->clone(ctx, NULL), temp_rhs, false,
1486			  this->subexpressions[0]->get_location());
1487
1488      error_emitted = op[0]->type->is_error();
1489      break;
1490   }
1491
1492   case ast_field_selection:
1493      result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1494      break;
1495
1496   case ast_array_index: {
1497      YYLTYPE index_loc = subexpressions[1]->get_location();
1498
1499      op[0] = subexpressions[0]->hir(instructions, state);
1500      op[1] = subexpressions[1]->hir(instructions, state);
1501
1502      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1503
1504      ir_rvalue *const array = op[0];
1505
1506      result = new(ctx) ir_dereference_array(op[0], op[1]);
1507
1508      /* Do not use op[0] after this point.  Use array.
1509       */
1510      op[0] = NULL;
1511
1512
1513      if (error_emitted)
1514	 break;
1515
1516      if (!array->type->is_array()
1517	  && !array->type->is_matrix()
1518	  && !array->type->is_vector()) {
1519	 _mesa_glsl_error(& index_loc, state,
1520			  "cannot dereference non-array / non-matrix / "
1521			  "non-vector");
1522	 error_emitted = true;
1523      }
1524
1525      if (!op[1]->type->is_integer()) {
1526	 _mesa_glsl_error(& index_loc, state,
1527			  "array index must be integer type");
1528	 error_emitted = true;
1529      } else if (!op[1]->type->is_scalar()) {
1530	 _mesa_glsl_error(& index_loc, state,
1531			  "array index must be scalar");
1532	 error_emitted = true;
1533      }
1534
1535      /* If the array index is a constant expression and the array has a
1536       * declared size, ensure that the access is in-bounds.  If the array
1537       * index is not a constant expression, ensure that the array has a
1538       * declared size.
1539       */
1540      ir_constant *const const_index = op[1]->constant_expression_value();
1541      if (const_index != NULL) {
1542	 const int idx = const_index->value.i[0];
1543	 const char *type_name;
1544	 unsigned bound = 0;
1545
1546	 if (array->type->is_matrix()) {
1547	    type_name = "matrix";
1548	 } else if (array->type->is_vector()) {
1549	    type_name = "vector";
1550	 } else {
1551	    type_name = "array";
1552	 }
1553
1554	 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
1555	  *
1556	  *    "It is illegal to declare an array with a size, and then
1557	  *    later (in the same shader) index the same array with an
1558	  *    integral constant expression greater than or equal to the
1559	  *    declared size. It is also illegal to index an array with a
1560	  *    negative constant expression."
1561	  */
1562	 if (array->type->is_matrix()) {
1563	    if (array->type->row_type()->vector_elements <= idx) {
1564	       bound = array->type->row_type()->vector_elements;
1565	    }
1566	 } else if (array->type->is_vector()) {
1567	    if (array->type->vector_elements <= idx) {
1568	       bound = array->type->vector_elements;
1569	    }
1570	 } else {
1571	    if ((array->type->array_size() > 0)
1572		&& (array->type->array_size() <= idx)) {
1573	       bound = array->type->array_size();
1574	    }
1575	 }
1576
1577	 if (bound > 0) {
1578	    _mesa_glsl_error(& loc, state, "%s index must be < %u",
1579			     type_name, bound);
1580	    error_emitted = true;
1581	 } else if (idx < 0) {
1582	    _mesa_glsl_error(& loc, state, "%s index must be >= 0",
1583			     type_name);
1584	    error_emitted = true;
1585	 }
1586
1587	 if (array->type->is_array()) {
1588	    /* If the array is a variable dereference, it dereferences the
1589	     * whole array, by definition.  Use this to get the variable.
1590	     *
1591	     * FINISHME: Should some methods for getting / setting / testing
1592	     * FINISHME: array access limits be added to ir_dereference?
1593	     */
1594	    ir_variable *const v = array->whole_variable_referenced();
1595	    if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
1596	       v->max_array_access = idx;
1597
1598               /* Check whether this access will, as a side effect, implicitly
1599                * cause the size of a built-in array to be too large.
1600                */
1601               if (check_builtin_array_max_size(v->name, idx+1, loc, state))
1602                  error_emitted = true;
1603            }
1604	 }
1605      } else if (array->type->array_size() == 0) {
1606	 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
1607      } else {
1608	 if (array->type->is_array()) {
1609	    /* whole_variable_referenced can return NULL if the array is a
1610	     * member of a structure.  In this case it is safe to not update
1611	     * the max_array_access field because it is never used for fields
1612	     * of structures.
1613	     */
1614	    ir_variable *v = array->whole_variable_referenced();
1615	    if (v != NULL)
1616	       v->max_array_access = array->type->array_size() - 1;
1617	 }
1618      }
1619
1620      /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
1621       *
1622       *    "Samplers aggregated into arrays within a shader (using square
1623       *    brackets [ ]) can only be indexed with integral constant
1624       *    expressions [...]."
1625       *
1626       * This restriction was added in GLSL 1.30.  Shaders using earlier version
1627       * of the language should not be rejected by the compiler front-end for
1628       * using this construct.  This allows useful things such as using a loop
1629       * counter as the index to an array of samplers.  If the loop in unrolled,
1630       * the code should compile correctly.  Instead, emit a warning.
1631       */
1632      if (array->type->is_array() &&
1633          array->type->element_type()->is_sampler() &&
1634          const_index == NULL) {
1635
1636	 if (state->language_version == 100) {
1637	    _mesa_glsl_warning(&loc, state,
1638			       "sampler arrays indexed with non-constant "
1639			       "expressions is optional in GLSL ES 1.00");
1640	 } else if (state->language_version < 130) {
1641	    _mesa_glsl_warning(&loc, state,
1642			       "sampler arrays indexed with non-constant "
1643			       "expressions is forbidden in GLSL 1.30 and "
1644			       "later");
1645	 } else {
1646	    _mesa_glsl_error(&loc, state,
1647			     "sampler arrays indexed with non-constant "
1648			     "expressions is forbidden in GLSL 1.30 and "
1649			     "later");
1650	    error_emitted = true;
1651	 }
1652      }
1653
1654      if (error_emitted)
1655	 result->type = glsl_type::error_type;
1656
1657      break;
1658   }
1659
1660   case ast_function_call:
1661      /* Should *NEVER* get here.  ast_function_call should always be handled
1662       * by ast_function_expression::hir.
1663       */
1664      assert(0);
1665      break;
1666
1667   case ast_identifier: {
1668      /* ast_identifier can appear several places in a full abstract syntax
1669       * tree.  This particular use must be at location specified in the grammar
1670       * as 'variable_identifier'.
1671       */
1672      ir_variable *var =
1673	 state->symbols->get_variable(this->primary_expression.identifier);
1674
1675      result = new(ctx) ir_dereference_variable(var);
1676
1677      if (var != NULL) {
1678	 var->used = true;
1679      } else {
1680	 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1681			  this->primary_expression.identifier);
1682
1683	 error_emitted = true;
1684      }
1685      break;
1686   }
1687
1688   case ast_int_constant:
1689      result = new(ctx) ir_constant(this->primary_expression.int_constant);
1690      break;
1691
1692   case ast_uint_constant:
1693      result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1694      break;
1695
1696   case ast_float_constant:
1697      result = new(ctx) ir_constant(this->primary_expression.float_constant);
1698      break;
1699
1700   case ast_bool_constant:
1701      result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1702      break;
1703
1704   case ast_sequence: {
1705      /* It should not be possible to generate a sequence in the AST without
1706       * any expressions in it.
1707       */
1708      assert(!this->expressions.is_empty());
1709
1710      /* The r-value of a sequence is the last expression in the sequence.  If
1711       * the other expressions in the sequence do not have side-effects (and
1712       * therefore add instructions to the instruction list), they get dropped
1713       * on the floor.
1714       */
1715      exec_node *previous_tail_pred = NULL;
1716      YYLTYPE previous_operand_loc = loc;
1717
1718      foreach_list_typed (ast_node, ast, link, &this->expressions) {
1719	 /* If one of the operands of comma operator does not generate any
1720	  * code, we want to emit a warning.  At each pass through the loop
1721	  * previous_tail_pred will point to the last instruction in the
1722	  * stream *before* processing the previous operand.  Naturally,
1723	  * instructions->tail_pred will point to the last instruction in the
1724	  * stream *after* processing the previous operand.  If the two
1725	  * pointers match, then the previous operand had no effect.
1726	  *
1727	  * The warning behavior here differs slightly from GCC.  GCC will
1728	  * only emit a warning if none of the left-hand operands have an
1729	  * effect.  However, it will emit a warning for each.  I believe that
1730	  * there are some cases in C (especially with GCC extensions) where
1731	  * it is useful to have an intermediate step in a sequence have no
1732	  * effect, but I don't think these cases exist in GLSL.  Either way,
1733	  * it would be a giant hassle to replicate that behavior.
1734	  */
1735	 if (previous_tail_pred == instructions->tail_pred) {
1736	    _mesa_glsl_warning(&previous_operand_loc, state,
1737			       "left-hand operand of comma expression has "
1738			       "no effect");
1739	 }
1740
1741	 /* tail_pred is directly accessed instead of using the get_tail()
1742	  * method for performance reasons.  get_tail() has extra code to
1743	  * return NULL when the list is empty.  We don't care about that
1744	  * here, so using tail_pred directly is fine.
1745	  */
1746	 previous_tail_pred = instructions->tail_pred;
1747	 previous_operand_loc = ast->get_location();
1748
1749	 result = ast->hir(instructions, state);
1750      }
1751
1752      /* Any errors should have already been emitted in the loop above.
1753       */
1754      error_emitted = true;
1755      break;
1756   }
1757   }
1758   type = NULL; /* use result->type, not type. */
1759   assert(result != NULL);
1760
1761   if (result->type->is_error() && !error_emitted)
1762      _mesa_glsl_error(& loc, state, "type mismatch");
1763
1764   return result;
1765}
1766
1767
1768ir_rvalue *
1769ast_expression_statement::hir(exec_list *instructions,
1770			      struct _mesa_glsl_parse_state *state)
1771{
1772   /* It is possible to have expression statements that don't have an
1773    * expression.  This is the solitary semicolon:
1774    *
1775    * for (i = 0; i < 5; i++)
1776    *     ;
1777    *
1778    * In this case the expression will be NULL.  Test for NULL and don't do
1779    * anything in that case.
1780    */
1781   if (expression != NULL)
1782      expression->hir(instructions, state);
1783
1784   /* Statements do not have r-values.
1785    */
1786   return NULL;
1787}
1788
1789
1790ir_rvalue *
1791ast_compound_statement::hir(exec_list *instructions,
1792			    struct _mesa_glsl_parse_state *state)
1793{
1794   if (new_scope)
1795      state->symbols->push_scope();
1796
1797   foreach_list_typed (ast_node, ast, link, &this->statements)
1798      ast->hir(instructions, state);
1799
1800   if (new_scope)
1801      state->symbols->pop_scope();
1802
1803   /* Compound statements do not have r-values.
1804    */
1805   return NULL;
1806}
1807
1808
1809static const glsl_type *
1810process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
1811		   struct _mesa_glsl_parse_state *state)
1812{
1813   unsigned length = 0;
1814
1815   /* FINISHME: Reject delcarations of multidimensional arrays. */
1816
1817   if (array_size != NULL) {
1818      exec_list dummy_instructions;
1819      ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1820      YYLTYPE loc = array_size->get_location();
1821
1822      if (ir != NULL) {
1823	 if (!ir->type->is_integer()) {
1824	    _mesa_glsl_error(& loc, state, "array size must be integer type");
1825	 } else if (!ir->type->is_scalar()) {
1826	    _mesa_glsl_error(& loc, state, "array size must be scalar type");
1827	 } else {
1828	    ir_constant *const size = ir->constant_expression_value();
1829
1830	    if (size == NULL) {
1831	       _mesa_glsl_error(& loc, state, "array size must be a "
1832				"constant valued expression");
1833	    } else if (size->value.i[0] <= 0) {
1834	       _mesa_glsl_error(& loc, state, "array size must be > 0");
1835	    } else {
1836	       assert(size->type == ir->type);
1837	       length = size->value.u[0];
1838
1839               /* If the array size is const (and we've verified that
1840                * it is) then no instructions should have been emitted
1841                * when we converted it to HIR.  If they were emitted,
1842                * then either the array size isn't const after all, or
1843                * we are emitting unnecessary instructions.
1844                */
1845               assert(dummy_instructions.is_empty());
1846	    }
1847	 }
1848      }
1849   } else if (state->es_shader) {
1850      /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
1851       * array declarations have been removed from the language.
1852       */
1853      _mesa_glsl_error(loc, state, "unsized array declarations are not "
1854		       "allowed in GLSL ES 1.00.");
1855   }
1856
1857   return glsl_type::get_array_instance(base, length);
1858}
1859
1860
1861const glsl_type *
1862ast_type_specifier::glsl_type(const char **name,
1863			      struct _mesa_glsl_parse_state *state) const
1864{
1865   const struct glsl_type *type;
1866
1867   type = state->symbols->get_type(this->type_name);
1868   *name = this->type_name;
1869
1870   if (this->is_array) {
1871      YYLTYPE loc = this->get_location();
1872      type = process_array_type(&loc, type, this->array_size, state);
1873   }
1874
1875   return type;
1876}
1877
1878
1879static void
1880apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
1881				 ir_variable *var,
1882				 struct _mesa_glsl_parse_state *state,
1883				 YYLTYPE *loc)
1884{
1885   if (qual->flags.q.invariant) {
1886      if (var->used) {
1887	 _mesa_glsl_error(loc, state,
1888			  "variable `%s' may not be redeclared "
1889			  "`invariant' after being used",
1890			  var->name);
1891      } else {
1892	 var->invariant = 1;
1893      }
1894   }
1895
1896   if (qual->flags.q.constant || qual->flags.q.attribute
1897       || qual->flags.q.uniform
1898       || (qual->flags.q.varying && (state->target == fragment_shader)))
1899      var->read_only = 1;
1900
1901   if (qual->flags.q.centroid)
1902      var->centroid = 1;
1903
1904   if (qual->flags.q.attribute && state->target != vertex_shader) {
1905      var->type = glsl_type::error_type;
1906      _mesa_glsl_error(loc, state,
1907		       "`attribute' variables may not be declared in the "
1908		       "%s shader",
1909		       _mesa_glsl_shader_target_name(state->target));
1910   }
1911
1912   /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
1913    *
1914    *     "The varying qualifier can be used only with the data types
1915    *     float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
1916    *     these."
1917    */
1918   if (qual->flags.q.varying) {
1919      const glsl_type *non_array_type;
1920
1921      if (var->type && var->type->is_array())
1922	 non_array_type = var->type->fields.array;
1923      else
1924	 non_array_type = var->type;
1925
1926      if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
1927	 var->type = glsl_type::error_type;
1928	 _mesa_glsl_error(loc, state,
1929			  "varying variables must be of base type float");
1930      }
1931   }
1932
1933   /* If there is no qualifier that changes the mode of the variable, leave
1934    * the setting alone.
1935    */
1936   if (qual->flags.q.in && qual->flags.q.out)
1937      var->mode = ir_var_inout;
1938   else if (qual->flags.q.attribute || qual->flags.q.in
1939	    || (qual->flags.q.varying && (state->target == fragment_shader)))
1940      var->mode = ir_var_in;
1941   else if (qual->flags.q.out
1942	    || (qual->flags.q.varying && (state->target == vertex_shader)))
1943      var->mode = ir_var_out;
1944   else if (qual->flags.q.uniform)
1945      var->mode = ir_var_uniform;
1946
1947   if (state->all_invariant && (state->current_function == NULL)) {
1948      switch (state->target) {
1949      case vertex_shader:
1950	 if (var->mode == ir_var_out)
1951	    var->invariant = true;
1952	 break;
1953      case geometry_shader:
1954	 if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
1955	    var->invariant = true;
1956	 break;
1957      case fragment_shader:
1958	 if (var->mode == ir_var_in)
1959	    var->invariant = true;
1960	 break;
1961      }
1962   }
1963
1964   if (qual->flags.q.flat)
1965      var->interpolation = ir_var_flat;
1966   else if (qual->flags.q.noperspective)
1967      var->interpolation = ir_var_noperspective;
1968   else
1969      var->interpolation = ir_var_smooth;
1970
1971   var->pixel_center_integer = qual->flags.q.pixel_center_integer;
1972   var->origin_upper_left = qual->flags.q.origin_upper_left;
1973   if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
1974       && (strcmp(var->name, "gl_FragCoord") != 0)) {
1975      const char *const qual_string = (qual->flags.q.origin_upper_left)
1976	 ? "origin_upper_left" : "pixel_center_integer";
1977
1978      _mesa_glsl_error(loc, state,
1979		       "layout qualifier `%s' can only be applied to "
1980		       "fragment shader input `gl_FragCoord'",
1981		       qual_string);
1982   }
1983
1984   if (qual->flags.q.explicit_location) {
1985      const bool global_scope = (state->current_function == NULL);
1986      bool fail = false;
1987      const char *string = "";
1988
1989      /* In the vertex shader only shader inputs can be given explicit
1990       * locations.
1991       *
1992       * In the fragment shader only shader outputs can be given explicit
1993       * locations.
1994       */
1995      switch (state->target) {
1996      case vertex_shader:
1997	 if (!global_scope || (var->mode != ir_var_in)) {
1998	    fail = true;
1999	    string = "input";
2000	 }
2001	 break;
2002
2003      case geometry_shader:
2004	 _mesa_glsl_error(loc, state,
2005			  "geometry shader variables cannot be given "
2006			  "explicit locations\n");
2007	 break;
2008
2009      case fragment_shader:
2010	 if (!global_scope || (var->mode != ir_var_out)) {
2011	    fail = true;
2012	    string = "output";
2013	 }
2014	 break;
2015      };
2016
2017      if (fail) {
2018	 _mesa_glsl_error(loc, state,
2019			  "only %s shader %s variables can be given an "
2020			  "explicit location\n",
2021			  _mesa_glsl_shader_target_name(state->target),
2022			  string);
2023      } else {
2024	 var->explicit_location = true;
2025
2026	 /* This bit of silliness is needed because invalid explicit locations
2027	  * are supposed to be flagged during linking.  Small negative values
2028	  * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
2029	  * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
2030	  * The linker needs to be able to differentiate these cases.  This
2031	  * ensures that negative values stay negative.
2032	  */
2033	 if (qual->location >= 0) {
2034	    var->location = (state->target == vertex_shader)
2035	       ? (qual->location + VERT_ATTRIB_GENERIC0)
2036	       : (qual->location + FRAG_RESULT_DATA0);
2037	 } else {
2038	    var->location = qual->location;
2039	 }
2040      }
2041   }
2042
2043   /* Does the declaration use the 'layout' keyword?
2044    */
2045   const bool uses_layout = qual->flags.q.pixel_center_integer
2046      || qual->flags.q.origin_upper_left
2047      || qual->flags.q.explicit_location;
2048
2049   /* Does the declaration use the deprecated 'attribute' or 'varying'
2050    * keywords?
2051    */
2052   const bool uses_deprecated_qualifier = qual->flags.q.attribute
2053      || qual->flags.q.varying;
2054
2055   /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2056    * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2057    * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2058    * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2059    * These extensions and all following extensions that add the 'layout'
2060    * keyword have been modified to require the use of 'in' or 'out'.
2061    *
2062    * The following extension do not allow the deprecated keywords:
2063    *
2064    *    GL_AMD_conservative_depth
2065    *    GL_ARB_gpu_shader5
2066    *    GL_ARB_separate_shader_objects
2067    *    GL_ARB_tesselation_shader
2068    *    GL_ARB_transform_feedback3
2069    *    GL_ARB_uniform_buffer_object
2070    *
2071    * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2072    * allow layout with the deprecated keywords.
2073    */
2074   const bool relaxed_layout_qualifier_checking =
2075      state->ARB_fragment_coord_conventions_enable;
2076
2077   if (uses_layout && uses_deprecated_qualifier) {
2078      if (relaxed_layout_qualifier_checking) {
2079	 _mesa_glsl_warning(loc, state,
2080			    "`layout' qualifier may not be used with "
2081			    "`attribute' or `varying'");
2082      } else {
2083	 _mesa_glsl_error(loc, state,
2084			  "`layout' qualifier may not be used with "
2085			  "`attribute' or `varying'");
2086      }
2087   }
2088
2089   /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2090    * AMD_conservative_depth.
2091    */
2092   int depth_layout_count = qual->flags.q.depth_any
2093      + qual->flags.q.depth_greater
2094      + qual->flags.q.depth_less
2095      + qual->flags.q.depth_unchanged;
2096   if (depth_layout_count > 0
2097       && !state->AMD_conservative_depth_enable) {
2098       _mesa_glsl_error(loc, state,
2099                        "extension GL_AMD_conservative_depth must be enabled "
2100			"to use depth layout qualifiers");
2101   } else if (depth_layout_count > 0
2102              && strcmp(var->name, "gl_FragDepth") != 0) {
2103       _mesa_glsl_error(loc, state,
2104                        "depth layout qualifiers can be applied only to "
2105                        "gl_FragDepth");
2106   } else if (depth_layout_count > 1
2107              && strcmp(var->name, "gl_FragDepth") == 0) {
2108      _mesa_glsl_error(loc, state,
2109                       "at most one depth layout qualifier can be applied to "
2110                       "gl_FragDepth");
2111   }
2112   if (qual->flags.q.depth_any)
2113      var->depth_layout = ir_depth_layout_any;
2114   else if (qual->flags.q.depth_greater)
2115      var->depth_layout = ir_depth_layout_greater;
2116   else if (qual->flags.q.depth_less)
2117      var->depth_layout = ir_depth_layout_less;
2118   else if (qual->flags.q.depth_unchanged)
2119       var->depth_layout = ir_depth_layout_unchanged;
2120   else
2121       var->depth_layout = ir_depth_layout_none;
2122}
2123
2124/**
2125 * Get the variable that is being redeclared by this declaration
2126 *
2127 * Semantic checks to verify the validity of the redeclaration are also
2128 * performed.  If semantic checks fail, compilation error will be emitted via
2129 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2130 *
2131 * \returns
2132 * A pointer to an existing variable in the current scope if the declaration
2133 * is a redeclaration, \c NULL otherwise.
2134 */
2135ir_variable *
2136get_variable_being_redeclared(ir_variable *var, ast_declaration *decl,
2137			      struct _mesa_glsl_parse_state *state)
2138{
2139   /* Check if this declaration is actually a re-declaration, either to
2140    * resize an array or add qualifiers to an existing variable.
2141    *
2142    * This is allowed for variables in the current scope, or when at
2143    * global scope (for built-ins in the implicit outer scope).
2144    */
2145   ir_variable *earlier = state->symbols->get_variable(decl->identifier);
2146   if (earlier == NULL ||
2147       (state->current_function != NULL &&
2148	!state->symbols->name_declared_this_scope(decl->identifier))) {
2149      return NULL;
2150   }
2151
2152
2153   YYLTYPE loc = decl->get_location();
2154
2155   /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2156    *
2157    * "It is legal to declare an array without a size and then
2158    *  later re-declare the same name as an array of the same
2159    *  type and specify a size."
2160    */
2161   if ((earlier->type->array_size() == 0)
2162       && var->type->is_array()
2163       && (var->type->element_type() == earlier->type->element_type())) {
2164      /* FINISHME: This doesn't match the qualifiers on the two
2165       * FINISHME: declarations.  It's not 100% clear whether this is
2166       * FINISHME: required or not.
2167       */
2168
2169      const unsigned size = unsigned(var->type->array_size());
2170      check_builtin_array_max_size(var->name, size, loc, state);
2171      if ((size > 0) && (size <= earlier->max_array_access)) {
2172	 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2173			  "previous access",
2174			  earlier->max_array_access);
2175      }
2176
2177      earlier->type = var->type;
2178      delete var;
2179      var = NULL;
2180   } else if (state->ARB_fragment_coord_conventions_enable
2181	      && strcmp(var->name, "gl_FragCoord") == 0
2182	      && earlier->type == var->type
2183	      && earlier->mode == var->mode) {
2184      /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2185       * qualifiers.
2186       */
2187      earlier->origin_upper_left = var->origin_upper_left;
2188      earlier->pixel_center_integer = var->pixel_center_integer;
2189
2190      /* According to section 4.3.7 of the GLSL 1.30 spec,
2191       * the following built-in varaibles can be redeclared with an
2192       * interpolation qualifier:
2193       *    * gl_FrontColor
2194       *    * gl_BackColor
2195       *    * gl_FrontSecondaryColor
2196       *    * gl_BackSecondaryColor
2197       *    * gl_Color
2198       *    * gl_SecondaryColor
2199       */
2200   } else if (state->language_version >= 130
2201	      && (strcmp(var->name, "gl_FrontColor") == 0
2202		  || strcmp(var->name, "gl_BackColor") == 0
2203		  || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2204		  || strcmp(var->name, "gl_BackSecondaryColor") == 0
2205		  || strcmp(var->name, "gl_Color") == 0
2206		  || strcmp(var->name, "gl_SecondaryColor") == 0)
2207	      && earlier->type == var->type
2208	      && earlier->mode == var->mode) {
2209      earlier->interpolation = var->interpolation;
2210
2211      /* Layout qualifiers for gl_FragDepth. */
2212   } else if (state->AMD_conservative_depth_enable
2213	      && strcmp(var->name, "gl_FragDepth") == 0
2214	      && earlier->type == var->type
2215	      && earlier->mode == var->mode) {
2216
2217      /** From the AMD_conservative_depth spec:
2218       *     Within any shader, the first redeclarations of gl_FragDepth
2219       *     must appear before any use of gl_FragDepth.
2220       */
2221      if (earlier->used) {
2222	 _mesa_glsl_error(&loc, state,
2223			  "the first redeclaration of gl_FragDepth "
2224			  "must appear before any use of gl_FragDepth");
2225      }
2226
2227      /* Prevent inconsistent redeclaration of depth layout qualifier. */
2228      if (earlier->depth_layout != ir_depth_layout_none
2229	  && earlier->depth_layout != var->depth_layout) {
2230	 _mesa_glsl_error(&loc, state,
2231			  "gl_FragDepth: depth layout is declared here "
2232			  "as '%s, but it was previously declared as "
2233			  "'%s'",
2234			  depth_layout_string(var->depth_layout),
2235			  depth_layout_string(earlier->depth_layout));
2236      }
2237
2238      earlier->depth_layout = var->depth_layout;
2239
2240   } else {
2241      _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
2242   }
2243
2244   return earlier;
2245}
2246
2247/**
2248 * Generate the IR for an initializer in a variable declaration
2249 */
2250ir_rvalue *
2251process_initializer(ir_variable *var, ast_declaration *decl,
2252		    ast_fully_specified_type *type,
2253		    exec_list *initializer_instructions,
2254		    struct _mesa_glsl_parse_state *state)
2255{
2256   ir_rvalue *result = NULL;
2257
2258   YYLTYPE initializer_loc = decl->initializer->get_location();
2259
2260   /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2261    *
2262    *    "All uniform variables are read-only and are initialized either
2263    *    directly by an application via API commands, or indirectly by
2264    *    OpenGL."
2265    */
2266   if ((state->language_version <= 110)
2267       && (var->mode == ir_var_uniform)) {
2268      _mesa_glsl_error(& initializer_loc, state,
2269		       "cannot initialize uniforms in GLSL 1.10");
2270   }
2271
2272   if (var->type->is_sampler()) {
2273      _mesa_glsl_error(& initializer_loc, state,
2274		       "cannot initialize samplers");
2275   }
2276
2277   if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
2278      _mesa_glsl_error(& initializer_loc, state,
2279		       "cannot initialize %s shader input / %s",
2280		       _mesa_glsl_shader_target_name(state->target),
2281		       (state->target == vertex_shader)
2282		       ? "attribute" : "varying");
2283   }
2284
2285   ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2286   ir_rvalue *rhs = decl->initializer->hir(initializer_instructions,
2287					   state);
2288
2289   /* Calculate the constant value if this is a const or uniform
2290    * declaration.
2291    */
2292   if (type->qualifier.flags.q.constant
2293       || type->qualifier.flags.q.uniform) {
2294      ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs, true);
2295      if (new_rhs != NULL) {
2296	 rhs = new_rhs;
2297
2298	 ir_constant *constant_value = rhs->constant_expression_value();
2299	 if (!constant_value) {
2300	    _mesa_glsl_error(& initializer_loc, state,
2301			     "initializer of %s variable `%s' must be a "
2302			     "constant expression",
2303			     (type->qualifier.flags.q.constant)
2304			     ? "const" : "uniform",
2305			     decl->identifier);
2306	    if (var->type->is_numeric()) {
2307	       /* Reduce cascading errors. */
2308	       var->constant_value = ir_constant::zero(state, var->type);
2309	    }
2310	 } else {
2311	    rhs = constant_value;
2312	    var->constant_value = constant_value;
2313	 }
2314      } else {
2315	 _mesa_glsl_error(&initializer_loc, state,
2316			  "initializer of type %s cannot be assigned to "
2317			  "variable of type %s",
2318			  rhs->type->name, var->type->name);
2319	 if (var->type->is_numeric()) {
2320	    /* Reduce cascading errors. */
2321	    var->constant_value = ir_constant::zero(state, var->type);
2322	 }
2323      }
2324   }
2325
2326   if (rhs && !rhs->type->is_error()) {
2327      bool temp = var->read_only;
2328      if (type->qualifier.flags.q.constant)
2329	 var->read_only = false;
2330
2331      /* Never emit code to initialize a uniform.
2332       */
2333      const glsl_type *initializer_type;
2334      if (!type->qualifier.flags.q.uniform) {
2335	 result = do_assignment(initializer_instructions, state,
2336				lhs, rhs, true,
2337				type->get_location());
2338	 initializer_type = result->type;
2339      } else
2340	 initializer_type = rhs->type;
2341
2342      /* If the declared variable is an unsized array, it must inherrit
2343       * its full type from the initializer.  A declaration such as
2344       *
2345       *     uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2346       *
2347       * becomes
2348       *
2349       *     uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2350       *
2351       * The assignment generated in the if-statement (below) will also
2352       * automatically handle this case for non-uniforms.
2353       *
2354       * If the declared variable is not an array, the types must
2355       * already match exactly.  As a result, the type assignment
2356       * here can be done unconditionally.  For non-uniforms the call
2357       * to do_assignment can change the type of the initializer (via
2358       * the implicit conversion rules).  For uniforms the initializer
2359       * must be a constant expression, and the type of that expression
2360       * was validated above.
2361       */
2362      var->type = initializer_type;
2363
2364      var->read_only = temp;
2365   }
2366
2367   return result;
2368}
2369
2370ir_rvalue *
2371ast_declarator_list::hir(exec_list *instructions,
2372			 struct _mesa_glsl_parse_state *state)
2373{
2374   void *ctx = state;
2375   const struct glsl_type *decl_type;
2376   const char *type_name = NULL;
2377   ir_rvalue *result = NULL;
2378   YYLTYPE loc = this->get_location();
2379
2380   /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
2381    *
2382    *     "To ensure that a particular output variable is invariant, it is
2383    *     necessary to use the invariant qualifier. It can either be used to
2384    *     qualify a previously declared variable as being invariant
2385    *
2386    *         invariant gl_Position; // make existing gl_Position be invariant"
2387    *
2388    * In these cases the parser will set the 'invariant' flag in the declarator
2389    * list, and the type will be NULL.
2390    */
2391   if (this->invariant) {
2392      assert(this->type == NULL);
2393
2394      if (state->current_function != NULL) {
2395	 _mesa_glsl_error(& loc, state,
2396			  "All uses of `invariant' keyword must be at global "
2397			  "scope\n");
2398      }
2399
2400      foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2401	 assert(!decl->is_array);
2402	 assert(decl->array_size == NULL);
2403	 assert(decl->initializer == NULL);
2404
2405	 ir_variable *const earlier =
2406	    state->symbols->get_variable(decl->identifier);
2407	 if (earlier == NULL) {
2408	    _mesa_glsl_error(& loc, state,
2409			     "Undeclared variable `%s' cannot be marked "
2410			     "invariant\n", decl->identifier);
2411	 } else if ((state->target == vertex_shader)
2412	       && (earlier->mode != ir_var_out)) {
2413	    _mesa_glsl_error(& loc, state,
2414			     "`%s' cannot be marked invariant, vertex shader "
2415			     "outputs only\n", decl->identifier);
2416	 } else if ((state->target == fragment_shader)
2417	       && (earlier->mode != ir_var_in)) {
2418	    _mesa_glsl_error(& loc, state,
2419			     "`%s' cannot be marked invariant, fragment shader "
2420			     "inputs only\n", decl->identifier);
2421	 } else if (earlier->used) {
2422	    _mesa_glsl_error(& loc, state,
2423			     "variable `%s' may not be redeclared "
2424			     "`invariant' after being used",
2425			     earlier->name);
2426	 } else {
2427	    earlier->invariant = true;
2428	 }
2429      }
2430
2431      /* Invariant redeclarations do not have r-values.
2432       */
2433      return NULL;
2434   }
2435
2436   assert(this->type != NULL);
2437   assert(!this->invariant);
2438
2439   /* The type specifier may contain a structure definition.  Process that
2440    * before any of the variable declarations.
2441    */
2442   (void) this->type->specifier->hir(instructions, state);
2443
2444   decl_type = this->type->specifier->glsl_type(& type_name, state);
2445   if (this->declarations.is_empty()) {
2446      if (decl_type != NULL) {
2447	 /* Warn if this empty declaration is not for declaring a structure.
2448	  */
2449	 if (this->type->specifier->structure == NULL) {
2450	    _mesa_glsl_warning(&loc, state, "empty declaration");
2451	 }
2452      } else {
2453	    _mesa_glsl_error(& loc, state, "incomplete declaration");
2454      }
2455   }
2456
2457   foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2458      const struct glsl_type *var_type;
2459      ir_variable *var;
2460
2461      /* FINISHME: Emit a warning if a variable declaration shadows a
2462       * FINISHME: declaration at a higher scope.
2463       */
2464
2465      if ((decl_type == NULL) || decl_type->is_void()) {
2466	 if (type_name != NULL) {
2467	    _mesa_glsl_error(& loc, state,
2468			     "invalid type `%s' in declaration of `%s'",
2469			     type_name, decl->identifier);
2470	 } else {
2471	    _mesa_glsl_error(& loc, state,
2472			     "invalid type in declaration of `%s'",
2473			     decl->identifier);
2474	 }
2475	 continue;
2476      }
2477
2478      if (decl->is_array) {
2479	 var_type = process_array_type(&loc, decl_type, decl->array_size,
2480				       state);
2481      } else {
2482	 var_type = decl_type;
2483      }
2484
2485      var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
2486
2487      /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
2488       *
2489       *     "Global variables can only use the qualifiers const,
2490       *     attribute, uni form, or varying. Only one may be
2491       *     specified.
2492       *
2493       *     Local variables can only use the qualifier const."
2494       *
2495       * This is relaxed in GLSL 1.30.  It is also relaxed by any extension
2496       * that adds the 'layout' keyword.
2497       */
2498      if ((state->language_version < 130)
2499	  && !state->ARB_explicit_attrib_location_enable
2500	  && !state->ARB_fragment_coord_conventions_enable) {
2501	 if (this->type->qualifier.flags.q.out) {
2502	    _mesa_glsl_error(& loc, state,
2503			     "`out' qualifier in declaration of `%s' "
2504			     "only valid for function parameters in %s.",
2505			     decl->identifier, state->version_string);
2506	 }
2507	 if (this->type->qualifier.flags.q.in) {
2508	    _mesa_glsl_error(& loc, state,
2509			     "`in' qualifier in declaration of `%s' "
2510			     "only valid for function parameters in %s.",
2511			     decl->identifier, state->version_string);
2512	 }
2513	 /* FINISHME: Test for other invalid qualifiers. */
2514      }
2515
2516      apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
2517				       & loc);
2518
2519      if (this->type->qualifier.flags.q.invariant) {
2520	 if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
2521						   var->mode == ir_var_inout)) {
2522	    /* FINISHME: Note that this doesn't work for invariant on
2523	     * a function signature outval
2524	     */
2525	    _mesa_glsl_error(& loc, state,
2526			     "`%s' cannot be marked invariant, vertex shader "
2527			     "outputs only\n", var->name);
2528	 } else if ((state->target == fragment_shader) &&
2529		    !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
2530	    /* FINISHME: Note that this doesn't work for invariant on
2531	     * a function signature inval
2532	     */
2533	    _mesa_glsl_error(& loc, state,
2534			     "`%s' cannot be marked invariant, fragment shader "
2535			     "inputs only\n", var->name);
2536	 }
2537      }
2538
2539      if (state->current_function != NULL) {
2540	 const char *mode = NULL;
2541	 const char *extra = "";
2542
2543	 /* There is no need to check for 'inout' here because the parser will
2544	  * only allow that in function parameter lists.
2545	  */
2546	 if (this->type->qualifier.flags.q.attribute) {
2547	    mode = "attribute";
2548	 } else if (this->type->qualifier.flags.q.uniform) {
2549	    mode = "uniform";
2550	 } else if (this->type->qualifier.flags.q.varying) {
2551	    mode = "varying";
2552	 } else if (this->type->qualifier.flags.q.in) {
2553	    mode = "in";
2554	    extra = " or in function parameter list";
2555	 } else if (this->type->qualifier.flags.q.out) {
2556	    mode = "out";
2557	    extra = " or in function parameter list";
2558	 }
2559
2560	 if (mode) {
2561	    _mesa_glsl_error(& loc, state,
2562			     "%s variable `%s' must be declared at "
2563			     "global scope%s",
2564			     mode, var->name, extra);
2565	 }
2566      } else if (var->mode == ir_var_in) {
2567         var->read_only = true;
2568
2569	 if (state->target == vertex_shader) {
2570	    bool error_emitted = false;
2571
2572	    /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
2573	     *
2574	     *    "Vertex shader inputs can only be float, floating-point
2575	     *    vectors, matrices, signed and unsigned integers and integer
2576	     *    vectors. Vertex shader inputs can also form arrays of these
2577	     *    types, but not structures."
2578	     *
2579	     * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
2580	     *
2581	     *    "Vertex shader inputs can only be float, floating-point
2582	     *    vectors, matrices, signed and unsigned integers and integer
2583	     *    vectors. They cannot be arrays or structures."
2584	     *
2585	     * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
2586	     *
2587	     *    "The attribute qualifier can be used only with float,
2588	     *    floating-point vectors, and matrices. Attribute variables
2589	     *    cannot be declared as arrays or structures."
2590	     */
2591	    const glsl_type *check_type = var->type->is_array()
2592	       ? var->type->fields.array : var->type;
2593
2594	    switch (check_type->base_type) {
2595	    case GLSL_TYPE_FLOAT:
2596	       break;
2597	    case GLSL_TYPE_UINT:
2598	    case GLSL_TYPE_INT:
2599	       if (state->language_version > 120)
2600		  break;
2601	       /* FALLTHROUGH */
2602	    default:
2603	       _mesa_glsl_error(& loc, state,
2604				"vertex shader input / attribute cannot have "
2605				"type %s`%s'",
2606				var->type->is_array() ? "array of " : "",
2607				check_type->name);
2608	       error_emitted = true;
2609	    }
2610
2611	    if (!error_emitted && (state->language_version <= 130)
2612		&& var->type->is_array()) {
2613	       _mesa_glsl_error(& loc, state,
2614				"vertex shader input / attribute cannot have "
2615				"array type");
2616	       error_emitted = true;
2617	    }
2618	 }
2619      }
2620
2621      /* Integer vertex outputs must be qualified with 'flat'.
2622       *
2623       * From section 4.3.6 of the GLSL 1.30 spec:
2624       *    "If a vertex output is a signed or unsigned integer or integer
2625       *    vector, then it must be qualified with the interpolation qualifier
2626       *    flat."
2627       */
2628      if (state->language_version >= 130
2629          && state->target == vertex_shader
2630          && state->current_function == NULL
2631          && var->type->is_integer()
2632          && var->mode == ir_var_out
2633          && var->interpolation != ir_var_flat) {
2634
2635         _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
2636                          "then it must be qualified with 'flat'");
2637      }
2638
2639
2640      /* Interpolation qualifiers cannot be applied to 'centroid' and
2641       * 'centroid varying'.
2642       *
2643       * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2644       *    "interpolation qualifiers may only precede the qualifiers in,
2645       *    centroid in, out, or centroid out in a declaration. They do not apply
2646       *    to the deprecated storage qualifiers varying or centroid varying."
2647       */
2648      if (state->language_version >= 130
2649          && this->type->qualifier.has_interpolation()
2650          && this->type->qualifier.flags.q.varying) {
2651
2652         const char *i = this->type->qualifier.interpolation_string();
2653         assert(i != NULL);
2654         const char *s;
2655         if (this->type->qualifier.flags.q.centroid)
2656            s = "centroid varying";
2657         else
2658            s = "varying";
2659
2660         _mesa_glsl_error(&loc, state,
2661                          "qualifier '%s' cannot be applied to the "
2662                          "deprecated storage qualifier '%s'", i, s);
2663      }
2664
2665
2666      /* Interpolation qualifiers can only apply to vertex shader outputs and
2667       * fragment shader inputs.
2668       *
2669       * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
2670       *    "Outputs from a vertex shader (out) and inputs to a fragment
2671       *    shader (in) can be further qualified with one or more of these
2672       *    interpolation qualifiers"
2673       */
2674      if (state->language_version >= 130
2675          && this->type->qualifier.has_interpolation()) {
2676
2677         const char *i = this->type->qualifier.interpolation_string();
2678         assert(i != NULL);
2679
2680         switch (state->target) {
2681         case vertex_shader:
2682            if (this->type->qualifier.flags.q.in) {
2683               _mesa_glsl_error(&loc, state,
2684                                "qualifier '%s' cannot be applied to vertex "
2685                                "shader inputs", i);
2686            }
2687            break;
2688         case fragment_shader:
2689            if (this->type->qualifier.flags.q.out) {
2690               _mesa_glsl_error(&loc, state,
2691                                "qualifier '%s' cannot be applied to fragment "
2692                                "shader outputs", i);
2693            }
2694            break;
2695         default:
2696            assert(0);
2697         }
2698      }
2699
2700
2701      /* From section 4.3.4 of the GLSL 1.30 spec:
2702       *    "It is an error to use centroid in in a vertex shader."
2703       */
2704      if (state->language_version >= 130
2705          && this->type->qualifier.flags.q.centroid
2706          && this->type->qualifier.flags.q.in
2707          && state->target == vertex_shader) {
2708
2709         _mesa_glsl_error(&loc, state,
2710                          "'centroid in' cannot be used in a vertex shader");
2711      }
2712
2713
2714      /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
2715       */
2716      if (this->type->specifier->precision != ast_precision_none
2717          && state->language_version != 100
2718          && state->language_version < 130) {
2719
2720         _mesa_glsl_error(&loc, state,
2721                          "precision qualifiers are supported only in GLSL ES "
2722                          "1.00, and GLSL 1.30 and later");
2723      }
2724
2725
2726      /* Precision qualifiers only apply to floating point and integer types.
2727       *
2728       * From section 4.5.2 of the GLSL 1.30 spec:
2729       *    "Any floating point or any integer declaration can have the type
2730       *    preceded by one of these precision qualifiers [...] Literal
2731       *    constants do not have precision qualifiers. Neither do Boolean
2732       *    variables.
2733       *
2734       * In GLSL ES, sampler types are also allowed.
2735       *
2736       * From page 87 of the GLSL ES spec:
2737       *    "RESOLUTION: Allow sampler types to take a precision qualifier."
2738       */
2739      if (this->type->specifier->precision != ast_precision_none
2740          && !var->type->is_float()
2741          && !var->type->is_integer()
2742          && !(var->type->is_sampler() && state->es_shader)
2743          && !(var->type->is_array()
2744               && (var->type->fields.array->is_float()
2745                   || var->type->fields.array->is_integer()))) {
2746
2747         _mesa_glsl_error(&loc, state,
2748                          "precision qualifiers apply only to floating point"
2749                          "%s types", state->es_shader ? ", integer, and sampler"
2750						       : "and integer");
2751      }
2752
2753      /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2754       *
2755       *    "[Sampler types] can only be declared as function
2756       *    parameters or uniform variables (see Section 4.3.5
2757       *    "Uniform")".
2758       */
2759      if (var_type->contains_sampler() &&
2760          !this->type->qualifier.flags.q.uniform) {
2761         _mesa_glsl_error(&loc, state, "samplers must be declared uniform");
2762      }
2763
2764      /* Process the initializer and add its instructions to a temporary
2765       * list.  This list will be added to the instruction stream (below) after
2766       * the declaration is added.  This is done because in some cases (such as
2767       * redeclarations) the declaration may not actually be added to the
2768       * instruction stream.
2769       */
2770      exec_list initializer_instructions;
2771      ir_variable *earlier = get_variable_being_redeclared(var, decl, state);
2772
2773      if (decl->initializer != NULL) {
2774	 result = process_initializer((earlier == NULL) ? var : earlier,
2775				      decl, this->type,
2776				      &initializer_instructions, state);
2777      }
2778
2779      /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
2780       *
2781       *     "It is an error to write to a const variable outside of
2782       *      its declaration, so they must be initialized when
2783       *      declared."
2784       */
2785      if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
2786	 _mesa_glsl_error(& loc, state,
2787			  "const declaration of `%s' must be initialized",
2788			  decl->identifier);
2789      }
2790
2791      /* If the declaration is not a redeclaration, there are a few additional
2792       * semantic checks that must be applied.  In addition, variable that was
2793       * created for the declaration should be added to the IR stream.
2794       */
2795      if (earlier == NULL) {
2796	 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2797	  *
2798	  *   "Identifiers starting with "gl_" are reserved for use by
2799	  *   OpenGL, and may not be declared in a shader as either a
2800	  *   variable or a function."
2801	  */
2802	 if (strncmp(decl->identifier, "gl_", 3) == 0)
2803	    _mesa_glsl_error(& loc, state,
2804			     "identifier `%s' uses reserved `gl_' prefix",
2805			     decl->identifier);
2806	 else if (strstr(decl->identifier, "__")) {
2807	    /* From page 14 (page 20 of the PDF) of the GLSL 1.10
2808	     * spec:
2809	     *
2810	     *     "In addition, all identifiers containing two
2811	     *      consecutive underscores (__) are reserved as
2812	     *      possible future keywords."
2813	     */
2814	    _mesa_glsl_error(& loc, state,
2815			     "identifier `%s' uses reserved `__' string",
2816			     decl->identifier);
2817	 }
2818
2819	 /* Add the variable to the symbol table.  Note that the initializer's
2820	  * IR was already processed earlier (though it hasn't been emitted
2821	  * yet), without the variable in scope.
2822	  *
2823	  * This differs from most C-like languages, but it follows the GLSL
2824	  * specification.  From page 28 (page 34 of the PDF) of the GLSL 1.50
2825	  * spec:
2826	  *
2827	  *     "Within a declaration, the scope of a name starts immediately
2828	  *     after the initializer if present or immediately after the name
2829	  *     being declared if not."
2830	  */
2831	 if (!state->symbols->add_variable(var)) {
2832	    YYLTYPE loc = this->get_location();
2833	    _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
2834			     "current scope", decl->identifier);
2835	    continue;
2836	 }
2837
2838	 /* Push the variable declaration to the top.  It means that all the
2839	  * variable declarations will appear in a funny last-to-first order,
2840	  * but otherwise we run into trouble if a function is prototyped, a
2841	  * global var is decled, then the function is defined with usage of
2842	  * the global var.  See glslparsertest's CorrectModule.frag.
2843	  */
2844	 instructions->push_head(var);
2845      }
2846
2847      instructions->append_list(&initializer_instructions);
2848   }
2849
2850
2851   /* Generally, variable declarations do not have r-values.  However,
2852    * one is used for the declaration in
2853    *
2854    * while (bool b = some_condition()) {
2855    *   ...
2856    * }
2857    *
2858    * so we return the rvalue from the last seen declaration here.
2859    */
2860   return result;
2861}
2862
2863
2864ir_rvalue *
2865ast_parameter_declarator::hir(exec_list *instructions,
2866			      struct _mesa_glsl_parse_state *state)
2867{
2868   void *ctx = state;
2869   const struct glsl_type *type;
2870   const char *name = NULL;
2871   YYLTYPE loc = this->get_location();
2872
2873   type = this->type->specifier->glsl_type(& name, state);
2874
2875   if (type == NULL) {
2876      if (name != NULL) {
2877	 _mesa_glsl_error(& loc, state,
2878			  "invalid type `%s' in declaration of `%s'",
2879			  name, this->identifier);
2880      } else {
2881	 _mesa_glsl_error(& loc, state,
2882			  "invalid type in declaration of `%s'",
2883			  this->identifier);
2884      }
2885
2886      type = glsl_type::error_type;
2887   }
2888
2889   /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
2890    *
2891    *    "Functions that accept no input arguments need not use void in the
2892    *    argument list because prototypes (or definitions) are required and
2893    *    therefore there is no ambiguity when an empty argument list "( )" is
2894    *    declared. The idiom "(void)" as a parameter list is provided for
2895    *    convenience."
2896    *
2897    * Placing this check here prevents a void parameter being set up
2898    * for a function, which avoids tripping up checks for main taking
2899    * parameters and lookups of an unnamed symbol.
2900    */
2901   if (type->is_void()) {
2902      if (this->identifier != NULL)
2903	 _mesa_glsl_error(& loc, state,
2904			  "named parameter cannot have type `void'");
2905
2906      is_void = true;
2907      return NULL;
2908   }
2909
2910   if (formal_parameter && (this->identifier == NULL)) {
2911      _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
2912      return NULL;
2913   }
2914
2915   /* This only handles "vec4 foo[..]".  The earlier specifier->glsl_type(...)
2916    * call already handled the "vec4[..] foo" case.
2917    */
2918   if (this->is_array) {
2919      type = process_array_type(&loc, type, this->array_size, state);
2920   }
2921
2922   if (type->array_size() == 0) {
2923      _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
2924		       "a declared size.");
2925      type = glsl_type::error_type;
2926   }
2927
2928   is_void = false;
2929   ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
2930
2931   /* Apply any specified qualifiers to the parameter declaration.  Note that
2932    * for function parameters the default mode is 'in'.
2933    */
2934   apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
2935
2936   /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
2937    *
2938    *    "Samplers cannot be treated as l-values; hence cannot be used
2939    *    as out or inout function parameters, nor can they be assigned
2940    *    into."
2941    */
2942   if ((var->mode == ir_var_inout || var->mode == ir_var_out)
2943       && type->contains_sampler()) {
2944      _mesa_glsl_error(&loc, state, "out and inout parameters cannot contain samplers");
2945      type = glsl_type::error_type;
2946   }
2947
2948   /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
2949    *
2950    *    "When calling a function, expressions that do not evaluate to
2951    *     l-values cannot be passed to parameters declared as out or inout."
2952    *
2953    * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
2954    *
2955    *    "Other binary or unary expressions, non-dereferenced arrays,
2956    *     function names, swizzles with repeated fields, and constants
2957    *     cannot be l-values."
2958    *
2959    * So for GLSL 1.10, passing an array as an out or inout parameter is not
2960    * allowed.  This restriction is removed in GLSL 1.20, and in GLSL ES.
2961    */
2962   if ((var->mode == ir_var_inout || var->mode == ir_var_out)
2963       && type->is_array() && state->language_version == 110) {
2964      _mesa_glsl_error(&loc, state, "Arrays cannot be out or inout parameters in GLSL 1.10");
2965      type = glsl_type::error_type;
2966   }
2967
2968   instructions->push_tail(var);
2969
2970   /* Parameter declarations do not have r-values.
2971    */
2972   return NULL;
2973}
2974
2975
2976void
2977ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
2978					    bool formal,
2979					    exec_list *ir_parameters,
2980					    _mesa_glsl_parse_state *state)
2981{
2982   ast_parameter_declarator *void_param = NULL;
2983   unsigned count = 0;
2984
2985   foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
2986      param->formal_parameter = formal;
2987      param->hir(ir_parameters, state);
2988
2989      if (param->is_void)
2990	 void_param = param;
2991
2992      count++;
2993   }
2994
2995   if ((void_param != NULL) && (count > 1)) {
2996      YYLTYPE loc = void_param->get_location();
2997
2998      _mesa_glsl_error(& loc, state,
2999		       "`void' parameter must be only parameter");
3000   }
3001}
3002
3003
3004void
3005emit_function(_mesa_glsl_parse_state *state, ir_function *f)
3006{
3007   /* IR invariants disallow function declarations or definitions
3008    * nested within other function definitions.  But there is no
3009    * requirement about the relative order of function declarations
3010    * and definitions with respect to one another.  So simply insert
3011    * the new ir_function block at the end of the toplevel instruction
3012    * list.
3013    */
3014   state->toplevel_ir->push_tail(f);
3015}
3016
3017
3018ir_rvalue *
3019ast_function::hir(exec_list *instructions,
3020		  struct _mesa_glsl_parse_state *state)
3021{
3022   void *ctx = state;
3023   ir_function *f = NULL;
3024   ir_function_signature *sig = NULL;
3025   exec_list hir_parameters;
3026
3027   const char *const name = identifier;
3028
3029   /* New functions are always added to the top-level IR instruction stream,
3030    * so this instruction list pointer is ignored.  See also emit_function
3031    * (called below).
3032    */
3033   (void) instructions;
3034
3035   /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
3036    *
3037    *   "Function declarations (prototypes) cannot occur inside of functions;
3038    *   they must be at global scope, or for the built-in functions, outside
3039    *   the global scope."
3040    *
3041    * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
3042    *
3043    *   "User defined functions may only be defined within the global scope."
3044    *
3045    * Note that this language does not appear in GLSL 1.10.
3046    */
3047   if ((state->current_function != NULL) && (state->language_version != 110)) {
3048      YYLTYPE loc = this->get_location();
3049      _mesa_glsl_error(&loc, state,
3050		       "declaration of function `%s' not allowed within "
3051		       "function body", name);
3052   }
3053
3054   /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3055    *
3056    *   "Identifiers starting with "gl_" are reserved for use by
3057    *   OpenGL, and may not be declared in a shader as either a
3058    *   variable or a function."
3059    */
3060   if (strncmp(name, "gl_", 3) == 0) {
3061      YYLTYPE loc = this->get_location();
3062      _mesa_glsl_error(&loc, state,
3063		       "identifier `%s' uses reserved `gl_' prefix", name);
3064   }
3065
3066   /* Convert the list of function parameters to HIR now so that they can be
3067    * used below to compare this function's signature with previously seen
3068    * signatures for functions with the same name.
3069    */
3070   ast_parameter_declarator::parameters_to_hir(& this->parameters,
3071					       is_definition,
3072					       & hir_parameters, state);
3073
3074   const char *return_type_name;
3075   const glsl_type *return_type =
3076      this->return_type->specifier->glsl_type(& return_type_name, state);
3077
3078   if (!return_type) {
3079      YYLTYPE loc = this->get_location();
3080      _mesa_glsl_error(&loc, state,
3081		       "function `%s' has undeclared return type `%s'",
3082		       name, return_type_name);
3083      return_type = glsl_type::error_type;
3084   }
3085
3086   /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3087    * "No qualifier is allowed on the return type of a function."
3088    */
3089   if (this->return_type->has_qualifiers()) {
3090      YYLTYPE loc = this->get_location();
3091      _mesa_glsl_error(& loc, state,
3092		       "function `%s' return type has qualifiers", name);
3093   }
3094
3095   /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3096    *
3097    *    "[Sampler types] can only be declared as function parameters
3098    *    or uniform variables (see Section 4.3.5 "Uniform")".
3099    */
3100   if (return_type->contains_sampler()) {
3101      YYLTYPE loc = this->get_location();
3102      _mesa_glsl_error(&loc, state,
3103                       "function `%s' return type can't contain a sampler",
3104                       name);
3105   }
3106
3107   /* Verify that this function's signature either doesn't match a previously
3108    * seen signature for a function with the same name, or, if a match is found,
3109    * that the previously seen signature does not have an associated definition.
3110    */
3111   f = state->symbols->get_function(name);
3112   if (f != NULL && (state->es_shader || f->has_user_signature())) {
3113      sig = f->exact_matching_signature(&hir_parameters);
3114      if (sig != NULL) {
3115	 const char *badvar = sig->qualifiers_match(&hir_parameters);
3116	 if (badvar != NULL) {
3117	    YYLTYPE loc = this->get_location();
3118
3119	    _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
3120			     "qualifiers don't match prototype", name, badvar);
3121	 }
3122
3123	 if (sig->return_type != return_type) {
3124	    YYLTYPE loc = this->get_location();
3125
3126	    _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
3127			     "match prototype", name);
3128	 }
3129
3130	 if (is_definition && sig->is_defined) {
3131	    YYLTYPE loc = this->get_location();
3132
3133	    _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
3134	 }
3135      }
3136   } else {
3137      f = new(ctx) ir_function(name);
3138      if (!state->symbols->add_function(f)) {
3139	 /* This function name shadows a non-function use of the same name. */
3140	 YYLTYPE loc = this->get_location();
3141
3142	 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
3143			  "non-function", name);
3144	 return NULL;
3145      }
3146
3147      emit_function(state, f);
3148   }
3149
3150   /* Verify the return type of main() */
3151   if (strcmp(name, "main") == 0) {
3152      if (! return_type->is_void()) {
3153	 YYLTYPE loc = this->get_location();
3154
3155	 _mesa_glsl_error(& loc, state, "main() must return void");
3156      }
3157
3158      if (!hir_parameters.is_empty()) {
3159	 YYLTYPE loc = this->get_location();
3160
3161	 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
3162      }
3163   }
3164
3165   /* Finish storing the information about this new function in its signature.
3166    */
3167   if (sig == NULL) {
3168      sig = new(ctx) ir_function_signature(return_type);
3169      f->add_signature(sig);
3170   }
3171
3172   sig->replace_parameters(&hir_parameters);
3173   signature = sig;
3174
3175   /* Function declarations (prototypes) do not have r-values.
3176    */
3177   return NULL;
3178}
3179
3180
3181ir_rvalue *
3182ast_function_definition::hir(exec_list *instructions,
3183			     struct _mesa_glsl_parse_state *state)
3184{
3185   prototype->is_definition = true;
3186   prototype->hir(instructions, state);
3187
3188   ir_function_signature *signature = prototype->signature;
3189   if (signature == NULL)
3190      return NULL;
3191
3192   assert(state->current_function == NULL);
3193   state->current_function = signature;
3194   state->found_return = false;
3195
3196   /* Duplicate parameters declared in the prototype as concrete variables.
3197    * Add these to the symbol table.
3198    */
3199   state->symbols->push_scope();
3200   foreach_iter(exec_list_iterator, iter, signature->parameters) {
3201      ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
3202
3203      assert(var != NULL);
3204
3205      /* The only way a parameter would "exist" is if two parameters have
3206       * the same name.
3207       */
3208      if (state->symbols->name_declared_this_scope(var->name)) {
3209	 YYLTYPE loc = this->get_location();
3210
3211	 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
3212      } else {
3213	 state->symbols->add_variable(var);
3214      }
3215   }
3216
3217   /* Convert the body of the function to HIR. */
3218   this->body->hir(&signature->body, state);
3219   signature->is_defined = true;
3220
3221   state->symbols->pop_scope();
3222
3223   assert(state->current_function == signature);
3224   state->current_function = NULL;
3225
3226   if (!signature->return_type->is_void() && !state->found_return) {
3227      YYLTYPE loc = this->get_location();
3228      _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
3229		       "%s, but no return statement",
3230		       signature->function_name(),
3231		       signature->return_type->name);
3232   }
3233
3234   /* Function definitions do not have r-values.
3235    */
3236   return NULL;
3237}
3238
3239
3240ir_rvalue *
3241ast_jump_statement::hir(exec_list *instructions,
3242			struct _mesa_glsl_parse_state *state)
3243{
3244   void *ctx = state;
3245
3246   switch (mode) {
3247   case ast_return: {
3248      ir_return *inst;
3249      assert(state->current_function);
3250
3251      if (opt_return_value) {
3252	 ir_rvalue *const ret = opt_return_value->hir(instructions, state);
3253
3254	 /* The value of the return type can be NULL if the shader says
3255	  * 'return foo();' and foo() is a function that returns void.
3256	  *
3257	  * NOTE: The GLSL spec doesn't say that this is an error.  The type
3258	  * of the return value is void.  If the return type of the function is
3259	  * also void, then this should compile without error.  Seriously.
3260	  */
3261	 const glsl_type *const ret_type =
3262	    (ret == NULL) ? glsl_type::void_type : ret->type;
3263
3264	 /* Implicit conversions are not allowed for return values. */
3265	 if (state->current_function->return_type != ret_type) {
3266	    YYLTYPE loc = this->get_location();
3267
3268	    _mesa_glsl_error(& loc, state,
3269			     "`return' with wrong type %s, in function `%s' "
3270			     "returning %s",
3271			     ret_type->name,
3272			     state->current_function->function_name(),
3273			     state->current_function->return_type->name);
3274	 }
3275
3276	 inst = new(ctx) ir_return(ret);
3277      } else {
3278	 if (state->current_function->return_type->base_type !=
3279	     GLSL_TYPE_VOID) {
3280	    YYLTYPE loc = this->get_location();
3281
3282	    _mesa_glsl_error(& loc, state,
3283			     "`return' with no value, in function %s returning "
3284			     "non-void",
3285			     state->current_function->function_name());
3286	 }
3287	 inst = new(ctx) ir_return;
3288      }
3289
3290      state->found_return = true;
3291      instructions->push_tail(inst);
3292      break;
3293   }
3294
3295   case ast_discard:
3296      if (state->target != fragment_shader) {
3297	 YYLTYPE loc = this->get_location();
3298
3299	 _mesa_glsl_error(& loc, state,
3300			  "`discard' may only appear in a fragment shader");
3301      }
3302      instructions->push_tail(new(ctx) ir_discard);
3303      break;
3304
3305   case ast_break:
3306   case ast_continue:
3307      /* FINISHME: Handle switch-statements.  They cannot contain 'continue',
3308       * FINISHME: and they use a different IR instruction for 'break'.
3309       */
3310      /* FINISHME: Correctly handle the nesting.  If a switch-statement is
3311       * FINISHME: inside a loop, a 'continue' is valid and will bind to the
3312       * FINISHME: loop.
3313       */
3314      if (state->loop_or_switch_nesting == NULL) {
3315	 YYLTYPE loc = this->get_location();
3316
3317	 _mesa_glsl_error(& loc, state,
3318			  "`%s' may only appear in a loop",
3319			  (mode == ast_break) ? "break" : "continue");
3320      } else {
3321	 ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
3322
3323	 /* Inline the for loop expression again, since we don't know
3324	  * where near the end of the loop body the normal copy of it
3325	  * is going to be placed.
3326	  */
3327	 if (mode == ast_continue &&
3328	     state->loop_or_switch_nesting_ast->rest_expression) {
3329	    state->loop_or_switch_nesting_ast->rest_expression->hir(instructions,
3330								    state);
3331	 }
3332
3333	 if (loop != NULL) {
3334	    ir_loop_jump *const jump =
3335	       new(ctx) ir_loop_jump((mode == ast_break)
3336				     ? ir_loop_jump::jump_break
3337				     : ir_loop_jump::jump_continue);
3338	    instructions->push_tail(jump);
3339	 }
3340      }
3341
3342      break;
3343   }
3344
3345   /* Jump instructions do not have r-values.
3346    */
3347   return NULL;
3348}
3349
3350
3351ir_rvalue *
3352ast_selection_statement::hir(exec_list *instructions,
3353			     struct _mesa_glsl_parse_state *state)
3354{
3355   void *ctx = state;
3356
3357   ir_rvalue *const condition = this->condition->hir(instructions, state);
3358
3359   /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
3360    *
3361    *    "Any expression whose type evaluates to a Boolean can be used as the
3362    *    conditional expression bool-expression. Vector types are not accepted
3363    *    as the expression to if."
3364    *
3365    * The checks are separated so that higher quality diagnostics can be
3366    * generated for cases where both rules are violated.
3367    */
3368   if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
3369      YYLTYPE loc = this->condition->get_location();
3370
3371      _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
3372		       "boolean");
3373   }
3374
3375   ir_if *const stmt = new(ctx) ir_if(condition);
3376
3377   if (then_statement != NULL) {
3378      state->symbols->push_scope();
3379      then_statement->hir(& stmt->then_instructions, state);
3380      state->symbols->pop_scope();
3381   }
3382
3383   if (else_statement != NULL) {
3384      state->symbols->push_scope();
3385      else_statement->hir(& stmt->else_instructions, state);
3386      state->symbols->pop_scope();
3387   }
3388
3389   instructions->push_tail(stmt);
3390
3391   /* if-statements do not have r-values.
3392    */
3393   return NULL;
3394}
3395
3396
3397void
3398ast_iteration_statement::condition_to_hir(ir_loop *stmt,
3399					  struct _mesa_glsl_parse_state *state)
3400{
3401   void *ctx = state;
3402
3403   if (condition != NULL) {
3404      ir_rvalue *const cond =
3405	 condition->hir(& stmt->body_instructions, state);
3406
3407      if ((cond == NULL)
3408	  || !cond->type->is_boolean() || !cond->type->is_scalar()) {
3409	 YYLTYPE loc = condition->get_location();
3410
3411	 _mesa_glsl_error(& loc, state,
3412			  "loop condition must be scalar boolean");
3413      } else {
3414	 /* As the first code in the loop body, generate a block that looks
3415	  * like 'if (!condition) break;' as the loop termination condition.
3416	  */
3417	 ir_rvalue *const not_cond =
3418	    new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
3419				   NULL);
3420
3421	 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
3422
3423	 ir_jump *const break_stmt =
3424	    new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
3425
3426	 if_stmt->then_instructions.push_tail(break_stmt);
3427	 stmt->body_instructions.push_tail(if_stmt);
3428      }
3429   }
3430}
3431
3432
3433ir_rvalue *
3434ast_iteration_statement::hir(exec_list *instructions,
3435			     struct _mesa_glsl_parse_state *state)
3436{
3437   void *ctx = state;
3438
3439   /* For-loops and while-loops start a new scope, but do-while loops do not.
3440    */
3441   if (mode != ast_do_while)
3442      state->symbols->push_scope();
3443
3444   if (init_statement != NULL)
3445      init_statement->hir(instructions, state);
3446
3447   ir_loop *const stmt = new(ctx) ir_loop();
3448   instructions->push_tail(stmt);
3449
3450   /* Track the current loop and / or switch-statement nesting.
3451    */
3452   ir_instruction *const nesting = state->loop_or_switch_nesting;
3453   ast_iteration_statement *nesting_ast = state->loop_or_switch_nesting_ast;
3454
3455   state->loop_or_switch_nesting = stmt;
3456   state->loop_or_switch_nesting_ast = this;
3457
3458   if (mode != ast_do_while)
3459      condition_to_hir(stmt, state);
3460
3461   if (body != NULL)
3462      body->hir(& stmt->body_instructions, state);
3463
3464   if (rest_expression != NULL)
3465      rest_expression->hir(& stmt->body_instructions, state);
3466
3467   if (mode == ast_do_while)
3468      condition_to_hir(stmt, state);
3469
3470   if (mode != ast_do_while)
3471      state->symbols->pop_scope();
3472
3473   /* Restore previous nesting before returning.
3474    */
3475   state->loop_or_switch_nesting = nesting;
3476   state->loop_or_switch_nesting_ast = nesting_ast;
3477
3478   /* Loops do not have r-values.
3479    */
3480   return NULL;
3481}
3482
3483
3484ir_rvalue *
3485ast_type_specifier::hir(exec_list *instructions,
3486			  struct _mesa_glsl_parse_state *state)
3487{
3488   if (!this->is_precision_statement && this->structure == NULL)
3489      return NULL;
3490
3491   YYLTYPE loc = this->get_location();
3492
3493   if (this->precision != ast_precision_none
3494       && state->language_version != 100
3495       && state->language_version < 130) {
3496      _mesa_glsl_error(&loc, state,
3497                       "precision qualifiers exist only in "
3498                       "GLSL ES 1.00, and GLSL 1.30 and later");
3499      return NULL;
3500   }
3501   if (this->precision != ast_precision_none
3502       && this->structure != NULL) {
3503      _mesa_glsl_error(&loc, state,
3504                       "precision qualifiers do not apply to structures");
3505      return NULL;
3506   }
3507
3508   /* If this is a precision statement, check that the type to which it is
3509    * applied is either float or int.
3510    *
3511    * From section 4.5.3 of the GLSL 1.30 spec:
3512    *    "The precision statement
3513    *       precision precision-qualifier type;
3514    *    can be used to establish a default precision qualifier. The type
3515    *    field can be either int or float [...].  Any other types or
3516    *    qualifiers will result in an error.
3517    */
3518   if (this->is_precision_statement) {
3519      assert(this->precision != ast_precision_none);
3520      assert(this->structure == NULL); /* The check for structures was
3521                                        * performed above. */
3522      if (this->is_array) {
3523         _mesa_glsl_error(&loc, state,
3524                          "default precision statements do not apply to "
3525                          "arrays");
3526         return NULL;
3527      }
3528      if (this->type_specifier != ast_float
3529          && this->type_specifier != ast_int) {
3530         _mesa_glsl_error(&loc, state,
3531                          "default precision statements apply only to types "
3532                          "float and int");
3533         return NULL;
3534      }
3535
3536      /* FINISHME: Translate precision statements into IR. */
3537      return NULL;
3538   }
3539
3540   if (this->structure != NULL)
3541      return this->structure->hir(instructions, state);
3542
3543   return NULL;
3544}
3545
3546
3547ir_rvalue *
3548ast_struct_specifier::hir(exec_list *instructions,
3549			  struct _mesa_glsl_parse_state *state)
3550{
3551   unsigned decl_count = 0;
3552
3553   /* Make an initial pass over the list of structure fields to determine how
3554    * many there are.  Each element in this list is an ast_declarator_list.
3555    * This means that we actually need to count the number of elements in the
3556    * 'declarations' list in each of the elements.
3557    */
3558   foreach_list_typed (ast_declarator_list, decl_list, link,
3559		       &this->declarations) {
3560      foreach_list_const (decl_ptr, & decl_list->declarations) {
3561	 decl_count++;
3562      }
3563   }
3564
3565   /* Allocate storage for the structure fields and process the field
3566    * declarations.  As the declarations are processed, try to also convert
3567    * the types to HIR.  This ensures that structure definitions embedded in
3568    * other structure definitions are processed.
3569    */
3570   glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
3571						  decl_count);
3572
3573   unsigned i = 0;
3574   foreach_list_typed (ast_declarator_list, decl_list, link,
3575		       &this->declarations) {
3576      const char *type_name;
3577
3578      decl_list->type->specifier->hir(instructions, state);
3579
3580      /* Section 10.9 of the GLSL ES 1.00 specification states that
3581       * embedded structure definitions have been removed from the language.
3582       */
3583      if (state->es_shader && decl_list->type->specifier->structure != NULL) {
3584	 YYLTYPE loc = this->get_location();
3585	 _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
3586			  "not allowed in GLSL ES 1.00.");
3587      }
3588
3589      const glsl_type *decl_type =
3590	 decl_list->type->specifier->glsl_type(& type_name, state);
3591
3592      foreach_list_typed (ast_declaration, decl, link,
3593			  &decl_list->declarations) {
3594	 const struct glsl_type *field_type = decl_type;
3595	 if (decl->is_array) {
3596	    YYLTYPE loc = decl->get_location();
3597	    field_type = process_array_type(&loc, decl_type, decl->array_size,
3598					    state);
3599	 }
3600	 fields[i].type = (field_type != NULL)
3601	    ? field_type : glsl_type::error_type;
3602	 fields[i].name = decl->identifier;
3603	 i++;
3604      }
3605   }
3606
3607   assert(i == decl_count);
3608
3609   const glsl_type *t =
3610      glsl_type::get_record_instance(fields, decl_count, this->name);
3611
3612   YYLTYPE loc = this->get_location();
3613   if (!state->symbols->add_type(name, t)) {
3614      _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
3615   } else {
3616      const glsl_type **s = reralloc(state, state->user_structures,
3617				     const glsl_type *,
3618				     state->num_user_structures + 1);
3619      if (s != NULL) {
3620	 s[state->num_user_structures] = t;
3621	 state->user_structures = s;
3622	 state->num_user_structures++;
3623      }
3624   }
3625
3626   /* Structure type definitions do not have r-values.
3627    */
3628   return NULL;
3629}
3630