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#include "glsl_symbol_table.h"
25#include "ast.h"
26#include "compiler/glsl_types.h"
27#include "ir.h"
28#include "main/core.h" /* for MIN2 */
29#include "main/shaderobj.h"
30
31static ir_rvalue *
32convert_component(ir_rvalue *src, const glsl_type *desired_type);
33
34static unsigned
35process_parameters(exec_list *instructions, exec_list *actual_parameters,
36                   exec_list *parameters,
37                   struct _mesa_glsl_parse_state *state)
38{
39   unsigned count = 0;
40
41   foreach_list_typed(ast_node, ast, link, parameters) {
42      /* We need to process the parameters first in order to know if we can
43       * raise or not a unitialized warning. Calling set_is_lhs silence the
44       * warning for now. Raising the warning or not will be checked at
45       * verify_parameter_modes.
46       */
47      ast->set_is_lhs(true);
48      ir_rvalue *result = ast->hir(instructions, state);
49
50      ir_constant *const constant = result->constant_expression_value();
51      if (constant != NULL)
52         result = constant;
53
54      actual_parameters->push_tail(result);
55      count++;
56   }
57
58   return count;
59}
60
61
62/**
63 * Generate a source prototype for a function signature
64 *
65 * \param return_type Return type of the function.  May be \c NULL.
66 * \param name        Name of the function.
67 * \param parameters  List of \c ir_instruction nodes representing the
68 *                    parameter list for the function.  This may be either a
69 *                    formal (\c ir_variable) or actual (\c ir_rvalue)
70 *                    parameter list.  Only the type is used.
71 *
72 * \return
73 * A ralloced string representing the prototype of the function.
74 */
75char *
76prototype_string(const glsl_type *return_type, const char *name,
77                 exec_list *parameters)
78{
79   char *str = NULL;
80
81   if (return_type != NULL)
82      str = ralloc_asprintf(NULL, "%s ", return_type->name);
83
84   ralloc_asprintf_append(&str, "%s(", name);
85
86   const char *comma = "";
87   foreach_in_list(const ir_variable, param, parameters) {
88      ralloc_asprintf_append(&str, "%s%s", comma, param->type->name);
89      comma = ", ";
90   }
91
92   ralloc_strcat(&str, ")");
93   return str;
94}
95
96static bool
97verify_image_parameter(YYLTYPE *loc, _mesa_glsl_parse_state *state,
98                       const ir_variable *formal, const ir_variable *actual)
99{
100   /**
101    * From the ARB_shader_image_load_store specification:
102    *
103    * "The values of image variables qualified with coherent,
104    *  volatile, restrict, readonly, or writeonly may not be passed
105    *  to functions whose formal parameters lack such
106    *  qualifiers. [...] It is legal to have additional qualifiers
107    *  on a formal parameter, but not to have fewer."
108    */
109   if (actual->data.image_coherent && !formal->data.image_coherent) {
110      _mesa_glsl_error(loc, state,
111                       "function call parameter `%s' drops "
112                       "`coherent' qualifier", formal->name);
113      return false;
114   }
115
116   if (actual->data.image_volatile && !formal->data.image_volatile) {
117      _mesa_glsl_error(loc, state,
118                       "function call parameter `%s' drops "
119                       "`volatile' qualifier", formal->name);
120      return false;
121   }
122
123   if (actual->data.image_restrict && !formal->data.image_restrict) {
124      _mesa_glsl_error(loc, state,
125                       "function call parameter `%s' drops "
126                       "`restrict' qualifier", formal->name);
127      return false;
128   }
129
130   if (actual->data.image_read_only && !formal->data.image_read_only) {
131      _mesa_glsl_error(loc, state,
132                       "function call parameter `%s' drops "
133                       "`readonly' qualifier", formal->name);
134      return false;
135   }
136
137   if (actual->data.image_write_only && !formal->data.image_write_only) {
138      _mesa_glsl_error(loc, state,
139                       "function call parameter `%s' drops "
140                       "`writeonly' qualifier", formal->name);
141      return false;
142   }
143
144   return true;
145}
146
147static bool
148verify_first_atomic_parameter(YYLTYPE *loc, _mesa_glsl_parse_state *state,
149                              ir_variable *var)
150{
151   if (!var ||
152       (!var->is_in_shader_storage_block() &&
153        var->data.mode != ir_var_shader_shared)) {
154      _mesa_glsl_error(loc, state, "First argument to atomic function "
155                       "must be a buffer or shared variable");
156      return false;
157   }
158   return true;
159}
160
161static bool
162is_atomic_function(const char *func_name)
163{
164   return !strcmp(func_name, "atomicAdd") ||
165          !strcmp(func_name, "atomicMin") ||
166          !strcmp(func_name, "atomicMax") ||
167          !strcmp(func_name, "atomicAnd") ||
168          !strcmp(func_name, "atomicOr") ||
169          !strcmp(func_name, "atomicXor") ||
170          !strcmp(func_name, "atomicExchange") ||
171          !strcmp(func_name, "atomicCompSwap");
172}
173
174/**
175 * Verify that 'out' and 'inout' actual parameters are lvalues.  Also, verify
176 * that 'const_in' formal parameters (an extension in our IR) correspond to
177 * ir_constant actual parameters.
178 */
179static bool
180verify_parameter_modes(_mesa_glsl_parse_state *state,
181                       ir_function_signature *sig,
182                       exec_list &actual_ir_parameters,
183                       exec_list &actual_ast_parameters)
184{
185   exec_node *actual_ir_node  = actual_ir_parameters.get_head_raw();
186   exec_node *actual_ast_node = actual_ast_parameters.get_head_raw();
187
188   foreach_in_list(const ir_variable, formal, &sig->parameters) {
189      /* The lists must be the same length. */
190      assert(!actual_ir_node->is_tail_sentinel());
191      assert(!actual_ast_node->is_tail_sentinel());
192
193      const ir_rvalue *const actual = (ir_rvalue *) actual_ir_node;
194      const ast_expression *const actual_ast =
195         exec_node_data(ast_expression, actual_ast_node, link);
196
197      /* FIXME: 'loc' is incorrect (as of 2011-01-21). It is always
198       * FIXME: 0:0(0).
199       */
200      YYLTYPE loc = actual_ast->get_location();
201
202      /* Verify that 'const_in' parameters are ir_constants. */
203      if (formal->data.mode == ir_var_const_in &&
204          actual->ir_type != ir_type_constant) {
205         _mesa_glsl_error(&loc, state,
206                          "parameter `in %s' must be a constant expression",
207                          formal->name);
208         return false;
209      }
210
211      /* Verify that shader_in parameters are shader inputs */
212      if (formal->data.must_be_shader_input) {
213         const ir_rvalue *val = actual;
214
215         /* GLSL 4.40 allows swizzles, while earlier GLSL versions do not. */
216         if (val->ir_type == ir_type_swizzle) {
217            if (!state->is_version(440, 0)) {
218               _mesa_glsl_error(&loc, state,
219                                "parameter `%s` must not be swizzled",
220                                formal->name);
221               return false;
222            }
223            val = ((ir_swizzle *)val)->val;
224         }
225
226         while (val->ir_type == ir_type_dereference_array) {
227            val = ((ir_dereference_array *)val)->array;
228         }
229
230         if (!val->as_dereference_variable() ||
231             val->variable_referenced()->data.mode != ir_var_shader_in) {
232            _mesa_glsl_error(&loc, state,
233                             "parameter `%s` must be a shader input",
234                             formal->name);
235            return false;
236         }
237      }
238
239      /* Verify that 'out' and 'inout' actual parameters are lvalues. */
240      if (formal->data.mode == ir_var_function_out
241          || formal->data.mode == ir_var_function_inout) {
242         const char *mode = NULL;
243         switch (formal->data.mode) {
244         case ir_var_function_out:   mode = "out";   break;
245         case ir_var_function_inout: mode = "inout"; break;
246         default:                    assert(false);  break;
247         }
248
249         /* This AST-based check catches errors like f(i++).  The IR-based
250          * is_lvalue() is insufficient because the actual parameter at the
251          * IR-level is just a temporary value, which is an l-value.
252          */
253         if (actual_ast->non_lvalue_description != NULL) {
254            _mesa_glsl_error(&loc, state,
255                             "function parameter '%s %s' references a %s",
256                             mode, formal->name,
257                             actual_ast->non_lvalue_description);
258            return false;
259         }
260
261         ir_variable *var = actual->variable_referenced();
262
263         if (var && formal->data.mode == ir_var_function_inout) {
264            if ((var->data.mode == ir_var_auto ||
265                 var->data.mode == ir_var_shader_out) &&
266                !var->data.assigned &&
267                !is_gl_identifier(var->name)) {
268               _mesa_glsl_warning(&loc, state, "`%s' used uninitialized",
269                                  var->name);
270            }
271         }
272
273         if (var)
274            var->data.assigned = true;
275
276         if (var && var->data.read_only) {
277            _mesa_glsl_error(&loc, state,
278                             "function parameter '%s %s' references the "
279                             "read-only variable '%s'",
280                             mode, formal->name,
281                             actual->variable_referenced()->name);
282            return false;
283         } else if (!actual->is_lvalue()) {
284            _mesa_glsl_error(&loc, state,
285                             "function parameter '%s %s' is not an lvalue",
286                             mode, formal->name);
287            return false;
288         }
289      } else {
290         assert(formal->data.mode == ir_var_function_in ||
291                formal->data.mode == ir_var_const_in);
292         ir_variable *var = actual->variable_referenced();
293         if (var) {
294            if ((var->data.mode == ir_var_auto ||
295                 var->data.mode == ir_var_shader_out) &&
296                !var->data.assigned &&
297                !is_gl_identifier(var->name)) {
298               _mesa_glsl_warning(&loc, state, "`%s' used uninitialized",
299                                  var->name);
300            }
301         }
302      }
303
304      if (formal->type->is_image() &&
305          actual->variable_referenced()) {
306         if (!verify_image_parameter(&loc, state, formal,
307                                     actual->variable_referenced()))
308            return false;
309      }
310
311      actual_ir_node  = actual_ir_node->next;
312      actual_ast_node = actual_ast_node->next;
313   }
314
315   /* The first parameter of atomic functions must be a buffer variable */
316   const char *func_name = sig->function_name();
317   bool is_atomic = is_atomic_function(func_name);
318   if (is_atomic) {
319      const ir_rvalue *const actual =
320         (ir_rvalue *) actual_ir_parameters.get_head_raw();
321
322      const ast_expression *const actual_ast =
323         exec_node_data(ast_expression,
324                        actual_ast_parameters.get_head_raw(), link);
325      YYLTYPE loc = actual_ast->get_location();
326
327      if (!verify_first_atomic_parameter(&loc, state,
328                                         actual->variable_referenced())) {
329         return false;
330      }
331   }
332
333   return true;
334}
335
336static void
337fix_parameter(void *mem_ctx, ir_rvalue *actual, const glsl_type *formal_type,
338              exec_list *before_instructions, exec_list *after_instructions,
339              bool parameter_is_inout)
340{
341   ir_expression *const expr = actual->as_expression();
342
343   /* If the types match exactly and the parameter is not a vector-extract,
344    * nothing needs to be done to fix the parameter.
345    */
346   if (formal_type == actual->type
347       && (expr == NULL || expr->operation != ir_binop_vector_extract))
348      return;
349
350   /* To convert an out parameter, we need to create a temporary variable to
351    * hold the value before conversion, and then perform the conversion after
352    * the function call returns.
353    *
354    * This has the effect of transforming code like this:
355    *
356    *   void f(out int x);
357    *   float value;
358    *   f(value);
359    *
360    * Into IR that's equivalent to this:
361    *
362    *   void f(out int x);
363    *   float value;
364    *   int out_parameter_conversion;
365    *   f(out_parameter_conversion);
366    *   value = float(out_parameter_conversion);
367    *
368    * If the parameter is an ir_expression of ir_binop_vector_extract,
369    * additional conversion is needed in the post-call re-write.
370    */
371   ir_variable *tmp =
372      new(mem_ctx) ir_variable(formal_type, "inout_tmp", ir_var_temporary);
373
374   before_instructions->push_tail(tmp);
375
376   /* If the parameter is an inout parameter, copy the value of the actual
377    * parameter to the new temporary.  Note that no type conversion is allowed
378    * here because inout parameters must match types exactly.
379    */
380   if (parameter_is_inout) {
381      /* Inout parameters should never require conversion, since that would
382       * require an implicit conversion to exist both to and from the formal
383       * parameter type, and there are no bidirectional implicit conversions.
384       */
385      assert (actual->type == formal_type);
386
387      ir_dereference_variable *const deref_tmp_1 =
388         new(mem_ctx) ir_dereference_variable(tmp);
389      ir_assignment *const assignment =
390         new(mem_ctx) ir_assignment(deref_tmp_1, actual);
391      before_instructions->push_tail(assignment);
392   }
393
394   /* Replace the parameter in the call with a dereference of the new
395    * temporary.
396    */
397   ir_dereference_variable *const deref_tmp_2 =
398      new(mem_ctx) ir_dereference_variable(tmp);
399   actual->replace_with(deref_tmp_2);
400
401
402   /* Copy the temporary variable to the actual parameter with optional
403    * type conversion applied.
404    */
405   ir_rvalue *rhs = new(mem_ctx) ir_dereference_variable(tmp);
406   if (actual->type != formal_type)
407      rhs = convert_component(rhs, actual->type);
408
409   ir_rvalue *lhs = actual;
410   if (expr != NULL && expr->operation == ir_binop_vector_extract) {
411      lhs = new(mem_ctx) ir_dereference_array(expr->operands[0]->clone(mem_ctx,
412                                                                       NULL),
413                                              expr->operands[1]->clone(mem_ctx,
414                                                                       NULL));
415   }
416
417   ir_assignment *const assignment_2 = new(mem_ctx) ir_assignment(lhs, rhs);
418   after_instructions->push_tail(assignment_2);
419}
420
421/**
422 * Generate a function call.
423 *
424 * For non-void functions, this returns a dereference of the temporary
425 * variable which stores the return value for the call.  For void functions,
426 * this returns NULL.
427 */
428static ir_rvalue *
429generate_call(exec_list *instructions, ir_function_signature *sig,
430              exec_list *actual_parameters,
431              ir_variable *sub_var,
432              ir_rvalue *array_idx,
433              struct _mesa_glsl_parse_state *state,
434              bool inline_immediately)
435{
436   void *ctx = state;
437   exec_list post_call_conversions;
438
439   /* Perform implicit conversion of arguments.  For out parameters, we need
440    * to place them in a temporary variable and do the conversion after the
441    * call takes place.  Since we haven't emitted the call yet, we'll place
442    * the post-call conversions in a temporary exec_list, and emit them later.
443    */
444   foreach_two_lists(formal_node, &sig->parameters,
445                     actual_node, actual_parameters) {
446      ir_rvalue *actual = (ir_rvalue *) actual_node;
447      ir_variable *formal = (ir_variable *) formal_node;
448
449      if (formal->type->is_numeric() || formal->type->is_boolean()) {
450         switch (formal->data.mode) {
451         case ir_var_const_in:
452         case ir_var_function_in: {
453            ir_rvalue *converted
454               = convert_component(actual, formal->type);
455            actual->replace_with(converted);
456            break;
457         }
458         case ir_var_function_out:
459         case ir_var_function_inout:
460            fix_parameter(ctx, actual, formal->type,
461                          instructions, &post_call_conversions,
462                          formal->data.mode == ir_var_function_inout);
463            break;
464         default:
465            assert (!"Illegal formal parameter mode");
466            break;
467         }
468      }
469   }
470
471   /* Section 4.3.2 (Const) of the GLSL 1.10.59 spec says:
472    *
473    *     "Initializers for const declarations must be formed from literal
474    *     values, other const variables (not including function call
475    *     paramaters), or expressions of these.
476    *
477    *     Constructors may be used in such expressions, but function calls may
478    *     not."
479    *
480    * Section 4.3.3 (Constant Expressions) of the GLSL 1.20.8 spec says:
481    *
482    *     "A constant expression is one of
483    *
484    *         ...
485    *
486    *         - a built-in function call whose arguments are all constant
487    *           expressions, with the exception of the texture lookup
488    *           functions, the noise functions, and ftransform. The built-in
489    *           functions dFdx, dFdy, and fwidth must return 0 when evaluated
490    *           inside an initializer with an argument that is a constant
491    *           expression."
492    *
493    * Section 5.10 (Constant Expressions) of the GLSL ES 1.00.17 spec says:
494    *
495    *     "A constant expression is one of
496    *
497    *         ...
498    *
499    *         - a built-in function call whose arguments are all constant
500    *           expressions, with the exception of the texture lookup
501    *           functions."
502    *
503    * Section 4.3.3 (Constant Expressions) of the GLSL ES 3.00.4 spec says:
504    *
505    *     "A constant expression is one of
506    *
507    *         ...
508    *
509    *         - a built-in function call whose arguments are all constant
510    *           expressions, with the exception of the texture lookup
511    *           functions.  The built-in functions dFdx, dFdy, and fwidth must
512    *           return 0 when evaluated inside an initializer with an argument
513    *           that is a constant expression."
514    *
515    * If the function call is a constant expression, don't generate any
516    * instructions; just generate an ir_constant.
517    */
518   if (state->is_version(120, 100)) {
519      ir_constant *value = sig->constant_expression_value(actual_parameters,
520                                                          NULL);
521      if (value != NULL) {
522         return value;
523      }
524   }
525
526   ir_dereference_variable *deref = NULL;
527   if (!sig->return_type->is_void()) {
528      /* Create a new temporary to hold the return value. */
529      char *const name = ir_variable::temporaries_allocate_names
530         ? ralloc_asprintf(ctx, "%s_retval", sig->function_name())
531         : NULL;
532
533      ir_variable *var;
534
535      var = new(ctx) ir_variable(sig->return_type, name, ir_var_temporary);
536      instructions->push_tail(var);
537
538      ralloc_free(name);
539
540      deref = new(ctx) ir_dereference_variable(var);
541   }
542
543   ir_call *call = new(ctx) ir_call(sig, deref,
544                                    actual_parameters, sub_var, array_idx);
545   instructions->push_tail(call);
546   if (inline_immediately) {
547      call->generate_inline(call);
548      call->remove();
549   }
550
551   /* Also emit any necessary out-parameter conversions. */
552   instructions->append_list(&post_call_conversions);
553
554   return deref ? deref->clone(ctx, NULL) : NULL;
555}
556
557/**
558 * Given a function name and parameter list, find the matching signature.
559 */
560static ir_function_signature *
561match_function_by_name(const char *name,
562                       exec_list *actual_parameters,
563                       struct _mesa_glsl_parse_state *state)
564{
565   ir_function *f = state->symbols->get_function(name);
566   ir_function_signature *local_sig = NULL;
567   ir_function_signature *sig = NULL;
568
569   /* Is the function hidden by a record type constructor? */
570   if (state->symbols->get_type(name))
571      return sig; /* no match */
572
573   /* Is the function hidden by a variable (impossible in 1.10)? */
574   if (!state->symbols->separate_function_namespace
575       && state->symbols->get_variable(name))
576      return sig; /* no match */
577
578   if (f != NULL) {
579      /* In desktop GL, the presence of a user-defined signature hides any
580       * built-in signatures, so we must ignore them.  In contrast, in ES2
581       * user-defined signatures add new overloads, so we must consider them.
582       */
583      bool allow_builtins = state->es_shader || !f->has_user_signature();
584
585      /* Look for a match in the local shader.  If exact, we're done. */
586      bool is_exact = false;
587      sig = local_sig = f->matching_signature(state, actual_parameters,
588                                              allow_builtins, &is_exact);
589      if (is_exact)
590         return sig;
591
592      if (!allow_builtins)
593         return sig;
594   }
595
596   /* Local shader has no exact candidates; check the built-ins. */
597   _mesa_glsl_initialize_builtin_functions();
598   sig = _mesa_glsl_find_builtin_function(state, name, actual_parameters);
599   return sig;
600}
601
602static ir_function_signature *
603match_subroutine_by_name(const char *name,
604                         exec_list *actual_parameters,
605                         struct _mesa_glsl_parse_state *state,
606                         ir_variable **var_r)
607{
608   void *ctx = state;
609   ir_function_signature *sig = NULL;
610   ir_function *f, *found = NULL;
611   const char *new_name;
612   ir_variable *var;
613   bool is_exact = false;
614
615   new_name =
616      ralloc_asprintf(ctx, "%s_%s",
617                      _mesa_shader_stage_to_subroutine_prefix(state->stage),
618                      name);
619   var = state->symbols->get_variable(new_name);
620   if (!var)
621      return NULL;
622
623   for (int i = 0; i < state->num_subroutine_types; i++) {
624      f = state->subroutine_types[i];
625      if (strcmp(f->name, var->type->without_array()->name))
626         continue;
627      found = f;
628      break;
629   }
630
631   if (!found)
632      return NULL;
633   *var_r = var;
634   sig = found->matching_signature(state, actual_parameters,
635                                   false, &is_exact);
636   return sig;
637}
638
639static ir_rvalue *
640generate_array_index(void *mem_ctx, exec_list *instructions,
641                     struct _mesa_glsl_parse_state *state, YYLTYPE loc,
642                     const ast_expression *array, ast_expression *idx,
643                     const char **function_name, exec_list *actual_parameters)
644{
645   if (array->oper == ast_array_index) {
646      /* This handles arrays of arrays */
647      ir_rvalue *outer_array = generate_array_index(mem_ctx, instructions,
648                                                    state, loc,
649                                                    array->subexpressions[0],
650                                                    array->subexpressions[1],
651                                                    function_name,
652                                                    actual_parameters);
653      ir_rvalue *outer_array_idx = idx->hir(instructions, state);
654
655      YYLTYPE index_loc = idx->get_location();
656      return _mesa_ast_array_index_to_hir(mem_ctx, state, outer_array,
657                                          outer_array_idx, loc,
658                                          index_loc);
659   } else {
660      ir_variable *sub_var = NULL;
661      *function_name = array->primary_expression.identifier;
662
663      match_subroutine_by_name(*function_name, actual_parameters,
664                               state, &sub_var);
665
666      ir_rvalue *outer_array_idx = idx->hir(instructions, state);
667      return new(mem_ctx) ir_dereference_array(sub_var, outer_array_idx);
668   }
669}
670
671static void
672print_function_prototypes(_mesa_glsl_parse_state *state, YYLTYPE *loc,
673                          ir_function *f)
674{
675   if (f == NULL)
676      return;
677
678   foreach_in_list(ir_function_signature, sig, &f->signatures) {
679      if (sig->is_builtin() && !sig->is_builtin_available(state))
680         continue;
681
682      char *str = prototype_string(sig->return_type, f->name,
683                                   &sig->parameters);
684      _mesa_glsl_error(loc, state, "   %s", str);
685      ralloc_free(str);
686   }
687}
688
689/**
690 * Raise a "no matching function" error, listing all possible overloads the
691 * compiler considered so developers can figure out what went wrong.
692 */
693static void
694no_matching_function_error(const char *name,
695                           YYLTYPE *loc,
696                           exec_list *actual_parameters,
697                           _mesa_glsl_parse_state *state)
698{
699   gl_shader *sh = _mesa_glsl_get_builtin_function_shader();
700
701   if (state->symbols->get_function(name) == NULL
702       && (!state->uses_builtin_functions
703           || sh->symbols->get_function(name) == NULL)) {
704      _mesa_glsl_error(loc, state, "no function with name '%s'", name);
705   } else {
706      char *str = prototype_string(NULL, name, actual_parameters);
707      _mesa_glsl_error(loc, state,
708                       "no matching function for call to `%s';"
709                       " candidates are:",
710                       str);
711      ralloc_free(str);
712
713      print_function_prototypes(state, loc,
714                                state->symbols->get_function(name));
715
716      if (state->uses_builtin_functions) {
717         print_function_prototypes(state, loc,
718                                   sh->symbols->get_function(name));
719      }
720   }
721}
722
723/**
724 * Perform automatic type conversion of constructor parameters
725 *
726 * This implements the rules in the "Conversion and Scalar Constructors"
727 * section (GLSL 1.10 section 5.4.1), not the "Implicit Conversions" rules.
728 */
729static ir_rvalue *
730convert_component(ir_rvalue *src, const glsl_type *desired_type)
731{
732   void *ctx = ralloc_parent(src);
733   const unsigned a = desired_type->base_type;
734   const unsigned b = src->type->base_type;
735   ir_expression *result = NULL;
736
737   if (src->type->is_error())
738      return src;
739
740   assert(a <= GLSL_TYPE_BOOL);
741   assert(b <= GLSL_TYPE_BOOL);
742
743   if (a == b)
744      return src;
745
746   switch (a) {
747   case GLSL_TYPE_UINT:
748      switch (b) {
749      case GLSL_TYPE_INT:
750         result = new(ctx) ir_expression(ir_unop_i2u, src);
751         break;
752      case GLSL_TYPE_FLOAT:
753         result = new(ctx) ir_expression(ir_unop_f2u, src);
754         break;
755      case GLSL_TYPE_BOOL:
756         result = new(ctx) ir_expression(ir_unop_i2u,
757                                         new(ctx) ir_expression(ir_unop_b2i,
758                                                                src));
759         break;
760      case GLSL_TYPE_DOUBLE:
761         result = new(ctx) ir_expression(ir_unop_d2u, src);
762         break;
763      }
764      break;
765   case GLSL_TYPE_INT:
766      switch (b) {
767      case GLSL_TYPE_UINT:
768         result = new(ctx) ir_expression(ir_unop_u2i, src);
769         break;
770      case GLSL_TYPE_FLOAT:
771         result = new(ctx) ir_expression(ir_unop_f2i, src);
772         break;
773      case GLSL_TYPE_BOOL:
774         result = new(ctx) ir_expression(ir_unop_b2i, src);
775         break;
776      case GLSL_TYPE_DOUBLE:
777         result = new(ctx) ir_expression(ir_unop_d2i, src);
778         break;
779      }
780      break;
781   case GLSL_TYPE_FLOAT:
782      switch (b) {
783      case GLSL_TYPE_UINT:
784         result = new(ctx) ir_expression(ir_unop_u2f, desired_type, src, NULL);
785         break;
786      case GLSL_TYPE_INT:
787         result = new(ctx) ir_expression(ir_unop_i2f, desired_type, src, NULL);
788         break;
789      case GLSL_TYPE_BOOL:
790         result = new(ctx) ir_expression(ir_unop_b2f, desired_type, src, NULL);
791         break;
792      case GLSL_TYPE_DOUBLE:
793         result = new(ctx) ir_expression(ir_unop_d2f, desired_type, src, NULL);
794         break;
795      }
796      break;
797   case GLSL_TYPE_BOOL:
798      switch (b) {
799      case GLSL_TYPE_UINT:
800         result = new(ctx) ir_expression(ir_unop_i2b,
801                                         new(ctx) ir_expression(ir_unop_u2i,
802                                                                src));
803         break;
804      case GLSL_TYPE_INT:
805         result = new(ctx) ir_expression(ir_unop_i2b, desired_type, src, NULL);
806         break;
807      case GLSL_TYPE_FLOAT:
808         result = new(ctx) ir_expression(ir_unop_f2b, desired_type, src, NULL);
809         break;
810      case GLSL_TYPE_DOUBLE:
811         result = new(ctx) ir_expression(ir_unop_d2b, desired_type, src, NULL);
812         break;
813      }
814      break;
815   case GLSL_TYPE_DOUBLE:
816      switch (b) {
817      case GLSL_TYPE_INT:
818         result = new(ctx) ir_expression(ir_unop_i2d, src);
819         break;
820      case GLSL_TYPE_UINT:
821         result = new(ctx) ir_expression(ir_unop_u2d, src);
822         break;
823      case GLSL_TYPE_BOOL:
824         result = new(ctx) ir_expression(ir_unop_f2d,
825                                         new(ctx) ir_expression(ir_unop_b2f,
826                                                                src));
827         break;
828      case GLSL_TYPE_FLOAT:
829         result = new(ctx) ir_expression(ir_unop_f2d, desired_type, src, NULL);
830         break;
831      }
832   }
833
834   assert(result != NULL);
835   assert(result->type == desired_type);
836
837   /* Try constant folding; it may fold in the conversion we just added. */
838   ir_constant *const constant = result->constant_expression_value();
839   return (constant != NULL) ? (ir_rvalue *) constant : (ir_rvalue *) result;
840}
841
842
843/**
844 * Perform automatic type and constant conversion of constructor parameters
845 *
846 * This implements the rules in the "Implicit Conversions" rules, not the
847 * "Conversion and Scalar Constructors".
848 *
849 * After attempting the implicit conversion, an attempt to convert into a
850 * constant valued expression is also done.
851 *
852 * The \c from \c ir_rvalue is converted "in place".
853 *
854 * \param from   Operand that is being converted
855 * \param to     Base type the operand will be converted to
856 * \param state  GLSL compiler state
857 *
858 * \return
859 * If the attempt to convert into a constant expression succeeds, \c true is
860 * returned. Otherwise \c false is returned.
861 */
862static bool
863implicitly_convert_component(ir_rvalue * &from, const glsl_base_type to,
864                             struct _mesa_glsl_parse_state *state)
865{
866   ir_rvalue *result = from;
867
868   if (to != from->type->base_type) {
869      const glsl_type *desired_type =
870         glsl_type::get_instance(to,
871                                 from->type->vector_elements,
872                                 from->type->matrix_columns);
873
874      if (from->type->can_implicitly_convert_to(desired_type, state)) {
875         /* Even though convert_component() implements the constructor
876          * conversion rules (not the implicit conversion rules), its safe
877          * to use it here because we already checked that the implicit
878          * conversion is legal.
879          */
880         result = convert_component(from, desired_type);
881      }
882   }
883
884   ir_rvalue *const constant = result->constant_expression_value();
885
886   if (constant != NULL)
887      result = constant;
888
889   if (from != result) {
890      from->replace_with(result);
891      from = result;
892   }
893
894   return constant != NULL;
895}
896
897
898/**
899 * Dereference a specific component from a scalar, vector, or matrix
900 */
901static ir_rvalue *
902dereference_component(ir_rvalue *src, unsigned component)
903{
904   void *ctx = ralloc_parent(src);
905   assert(component < src->type->components());
906
907   /* If the source is a constant, just create a new constant instead of a
908    * dereference of the existing constant.
909    */
910   ir_constant *constant = src->as_constant();
911   if (constant)
912      return new(ctx) ir_constant(constant, component);
913
914   if (src->type->is_scalar()) {
915      return src;
916   } else if (src->type->is_vector()) {
917      return new(ctx) ir_swizzle(src, component, 0, 0, 0, 1);
918   } else {
919      assert(src->type->is_matrix());
920
921      /* Dereference a row of the matrix, then call this function again to get
922       * a specific element from that row.
923       */
924      const int c = component / src->type->column_type()->vector_elements;
925      const int r = component % src->type->column_type()->vector_elements;
926      ir_constant *const col_index = new(ctx) ir_constant(c);
927      ir_dereference *const col = new(ctx) ir_dereference_array(src,
928                                                                col_index);
929
930      col->type = src->type->column_type();
931
932      return dereference_component(col, r);
933   }
934
935   assert(!"Should not get here.");
936   return NULL;
937}
938
939
940static ir_rvalue *
941process_vec_mat_constructor(exec_list *instructions,
942                            const glsl_type *constructor_type,
943                            YYLTYPE *loc, exec_list *parameters,
944                            struct _mesa_glsl_parse_state *state)
945{
946   void *ctx = state;
947
948   /* The ARB_shading_language_420pack spec says:
949    *
950    * "If an initializer is a list of initializers enclosed in curly braces,
951    *  the variable being declared must be a vector, a matrix, an array, or a
952    *  structure.
953    *
954    *      int i = { 1 }; // illegal, i is not an aggregate"
955    */
956   if (constructor_type->vector_elements <= 1) {
957      _mesa_glsl_error(loc, state, "aggregates can only initialize vectors, "
958                       "matrices, arrays, and structs");
959      return ir_rvalue::error_value(ctx);
960   }
961
962   exec_list actual_parameters;
963   const unsigned parameter_count =
964      process_parameters(instructions, &actual_parameters, parameters, state);
965
966   if (parameter_count == 0
967       || (constructor_type->is_vector() &&
968           constructor_type->vector_elements != parameter_count)
969       || (constructor_type->is_matrix() &&
970           constructor_type->matrix_columns != parameter_count)) {
971      _mesa_glsl_error(loc, state, "%s constructor must have %u parameters",
972                       constructor_type->is_vector() ? "vector" : "matrix",
973                       constructor_type->vector_elements);
974      return ir_rvalue::error_value(ctx);
975   }
976
977   bool all_parameters_are_constant = true;
978
979   /* Type cast each parameter and, if possible, fold constants. */
980   foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
981      /* Apply implicit conversions (not the scalar constructor rules, see the
982       * spec quote above!) and attempt to convert the parameter to a constant
983       * valued expression. After doing so, track whether or not all the
984       * parameters to the constructor are trivially constant valued
985       * expressions.
986       */
987      all_parameters_are_constant &=
988         implicitly_convert_component(ir, constructor_type->base_type, state);
989
990      if (constructor_type->is_matrix()) {
991         if (ir->type != constructor_type->column_type()) {
992            _mesa_glsl_error(loc, state, "type error in matrix constructor: "
993                             "expected: %s, found %s",
994                             constructor_type->column_type()->name,
995                             ir->type->name);
996            return ir_rvalue::error_value(ctx);
997         }
998      } else if (ir->type != constructor_type->get_scalar_type()) {
999         _mesa_glsl_error(loc, state, "type error in vector constructor: "
1000                          "expected: %s, found %s",
1001                          constructor_type->get_scalar_type()->name,
1002                          ir->type->name);
1003         return ir_rvalue::error_value(ctx);
1004      }
1005   }
1006
1007   if (all_parameters_are_constant)
1008      return new(ctx) ir_constant(constructor_type, &actual_parameters);
1009
1010   ir_variable *var = new(ctx) ir_variable(constructor_type, "vec_mat_ctor",
1011                                           ir_var_temporary);
1012   instructions->push_tail(var);
1013
1014   int i = 0;
1015
1016   foreach_in_list(ir_rvalue, rhs, &actual_parameters) {
1017      ir_instruction *assignment = NULL;
1018
1019      if (var->type->is_matrix()) {
1020         ir_rvalue *lhs =
1021            new(ctx) ir_dereference_array(var, new(ctx) ir_constant(i));
1022         assignment = new(ctx) ir_assignment(lhs, rhs, NULL);
1023      } else {
1024         /* use writemask rather than index for vector */
1025         assert(var->type->is_vector());
1026         assert(i < 4);
1027         ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1028         assignment = new(ctx) ir_assignment(lhs, rhs, NULL,
1029                                             (unsigned)(1 << i));
1030      }
1031
1032      instructions->push_tail(assignment);
1033
1034      i++;
1035   }
1036
1037   return new(ctx) ir_dereference_variable(var);
1038}
1039
1040
1041static ir_rvalue *
1042process_array_constructor(exec_list *instructions,
1043                          const glsl_type *constructor_type,
1044                          YYLTYPE *loc, exec_list *parameters,
1045                          struct _mesa_glsl_parse_state *state)
1046{
1047   void *ctx = state;
1048   /* Array constructors come in two forms: sized and unsized.  Sized array
1049    * constructors look like 'vec4[2](a, b)', where 'a' and 'b' are vec4
1050    * variables.  In this case the number of parameters must exactly match the
1051    * specified size of the array.
1052    *
1053    * Unsized array constructors look like 'vec4[](a, b)', where 'a' and 'b'
1054    * are vec4 variables.  In this case the size of the array being constructed
1055    * is determined by the number of parameters.
1056    *
1057    * From page 52 (page 58 of the PDF) of the GLSL 1.50 spec:
1058    *
1059    *    "There must be exactly the same number of arguments as the size of
1060    *    the array being constructed. If no size is present in the
1061    *    constructor, then the array is explicitly sized to the number of
1062    *    arguments provided. The arguments are assigned in order, starting at
1063    *    element 0, to the elements of the constructed array. Each argument
1064    *    must be the same type as the element type of the array, or be a type
1065    *    that can be converted to the element type of the array according to
1066    *    Section 4.1.10 "Implicit Conversions.""
1067    */
1068   exec_list actual_parameters;
1069   const unsigned parameter_count =
1070      process_parameters(instructions, &actual_parameters, parameters, state);
1071   bool is_unsized_array = constructor_type->is_unsized_array();
1072
1073   if ((parameter_count == 0) ||
1074       (!is_unsized_array && (constructor_type->length != parameter_count))) {
1075      const unsigned min_param = is_unsized_array
1076         ? 1 : constructor_type->length;
1077
1078      _mesa_glsl_error(loc, state, "array constructor must have %s %u "
1079                       "parameter%s",
1080                       is_unsized_array ? "at least" : "exactly",
1081                       min_param, (min_param <= 1) ? "" : "s");
1082      return ir_rvalue::error_value(ctx);
1083   }
1084
1085   if (is_unsized_array) {
1086      constructor_type =
1087         glsl_type::get_array_instance(constructor_type->fields.array,
1088                                       parameter_count);
1089      assert(constructor_type != NULL);
1090      assert(constructor_type->length == parameter_count);
1091   }
1092
1093   bool all_parameters_are_constant = true;
1094   const glsl_type *element_type = constructor_type->fields.array;
1095
1096   /* Type cast each parameter and, if possible, fold constants. */
1097   foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
1098      /* Apply implicit conversions (not the scalar constructor rules, see the
1099       * spec quote above!) and attempt to convert the parameter to a constant
1100       * valued expression. After doing so, track whether or not all the
1101       * parameters to the constructor are trivially constant valued
1102       * expressions.
1103       */
1104      all_parameters_are_constant &=
1105         implicitly_convert_component(ir, element_type->base_type, state);
1106
1107      if (constructor_type->fields.array->is_unsized_array()) {
1108         /* As the inner parameters of the constructor are created without
1109          * knowledge of each other we need to check to make sure unsized
1110          * parameters of unsized constructors all end up with the same size.
1111          *
1112          * e.g we make sure to fail for a constructor like this:
1113          * vec4[][] a = vec4[][](vec4[](vec4(0.0), vec4(1.0)),
1114          *                       vec4[](vec4(0.0), vec4(1.0), vec4(1.0)),
1115          *                       vec4[](vec4(0.0), vec4(1.0)));
1116          */
1117         if (element_type->is_unsized_array()) {
1118            /* This is the first parameter so just get the type */
1119            element_type = ir->type;
1120         } else if (element_type != ir->type) {
1121            _mesa_glsl_error(loc, state, "type error in array constructor: "
1122                             "expected: %s, found %s",
1123                             element_type->name,
1124                             ir->type->name);
1125            return ir_rvalue::error_value(ctx);
1126         }
1127      } else if (ir->type != constructor_type->fields.array) {
1128         _mesa_glsl_error(loc, state, "type error in array constructor: "
1129                          "expected: %s, found %s",
1130                          constructor_type->fields.array->name,
1131                          ir->type->name);
1132         return ir_rvalue::error_value(ctx);
1133      } else {
1134         element_type = ir->type;
1135      }
1136   }
1137
1138   if (constructor_type->fields.array->is_unsized_array()) {
1139      constructor_type =
1140         glsl_type::get_array_instance(element_type,
1141                                       parameter_count);
1142      assert(constructor_type != NULL);
1143      assert(constructor_type->length == parameter_count);
1144   }
1145
1146   if (all_parameters_are_constant)
1147      return new(ctx) ir_constant(constructor_type, &actual_parameters);
1148
1149   ir_variable *var = new(ctx) ir_variable(constructor_type, "array_ctor",
1150                                           ir_var_temporary);
1151   instructions->push_tail(var);
1152
1153   int i = 0;
1154   foreach_in_list(ir_rvalue, rhs, &actual_parameters) {
1155      ir_rvalue *lhs = new(ctx) ir_dereference_array(var,
1156                                                     new(ctx) ir_constant(i));
1157
1158      ir_instruction *assignment = new(ctx) ir_assignment(lhs, rhs, NULL);
1159      instructions->push_tail(assignment);
1160
1161      i++;
1162   }
1163
1164   return new(ctx) ir_dereference_variable(var);
1165}
1166
1167
1168/**
1169 * Determine if a list consists of a single scalar r-value
1170 */
1171bool
1172single_scalar_parameter(exec_list *parameters)
1173{
1174   const ir_rvalue *const p = (ir_rvalue *) parameters->get_head_raw();
1175   assert(((ir_rvalue *)p)->as_rvalue() != NULL);
1176
1177   return (p->type->is_scalar() && p->next->is_tail_sentinel());
1178}
1179
1180
1181/**
1182 * Generate inline code for a vector constructor
1183 *
1184 * The generated constructor code will consist of a temporary variable
1185 * declaration of the same type as the constructor.  A sequence of assignments
1186 * from constructor parameters to the temporary will follow.
1187 *
1188 * \return
1189 * An \c ir_dereference_variable of the temprorary generated in the constructor
1190 * body.
1191 */
1192ir_rvalue *
1193emit_inline_vector_constructor(const glsl_type *type,
1194                               exec_list *instructions,
1195                               exec_list *parameters,
1196                               void *ctx)
1197{
1198   assert(!parameters->is_empty());
1199
1200   ir_variable *var = new(ctx) ir_variable(type, "vec_ctor", ir_var_temporary);
1201   instructions->push_tail(var);
1202
1203   /* There are three kinds of vector constructors.
1204    *
1205    *  - Construct a vector from a single scalar by replicating that scalar to
1206    *    all components of the vector.
1207    *
1208    *  - Construct a vector from at least a matrix. This case should already
1209    *    have been taken care of in ast_function_expression::hir by breaking
1210    *    down the matrix into a series of column vectors.
1211    *
1212    *  - Construct a vector from an arbirary combination of vectors and
1213    *    scalars.  The components of the constructor parameters are assigned
1214    *    to the vector in order until the vector is full.
1215    */
1216   const unsigned lhs_components = type->components();
1217   if (single_scalar_parameter(parameters)) {
1218      ir_rvalue *first_param = (ir_rvalue *)parameters->get_head_raw();
1219      ir_rvalue *rhs = new(ctx) ir_swizzle(first_param, 0, 0, 0, 0,
1220                                           lhs_components);
1221      ir_dereference_variable *lhs = new(ctx) ir_dereference_variable(var);
1222      const unsigned mask = (1U << lhs_components) - 1;
1223
1224      assert(rhs->type == lhs->type);
1225
1226      ir_instruction *inst = new(ctx) ir_assignment(lhs, rhs, NULL, mask);
1227      instructions->push_tail(inst);
1228   } else {
1229      unsigned base_component = 0;
1230      unsigned base_lhs_component = 0;
1231      ir_constant_data data;
1232      unsigned constant_mask = 0, constant_components = 0;
1233
1234      memset(&data, 0, sizeof(data));
1235
1236      foreach_in_list(ir_rvalue, param, parameters) {
1237         unsigned rhs_components = param->type->components();
1238
1239         /* Do not try to assign more components to the vector than it has! */
1240         if ((rhs_components + base_lhs_component) > lhs_components) {
1241            rhs_components = lhs_components - base_lhs_component;
1242         }
1243
1244         const ir_constant *const c = param->as_constant();
1245         if (c != NULL) {
1246            for (unsigned i = 0; i < rhs_components; i++) {
1247               switch (c->type->base_type) {
1248               case GLSL_TYPE_UINT:
1249                  data.u[i + base_component] = c->get_uint_component(i);
1250                  break;
1251               case GLSL_TYPE_INT:
1252                  data.i[i + base_component] = c->get_int_component(i);
1253                  break;
1254               case GLSL_TYPE_FLOAT:
1255                  data.f[i + base_component] = c->get_float_component(i);
1256                  break;
1257               case GLSL_TYPE_DOUBLE:
1258                  data.d[i + base_component] = c->get_double_component(i);
1259                  break;
1260               case GLSL_TYPE_BOOL:
1261                  data.b[i + base_component] = c->get_bool_component(i);
1262                  break;
1263               default:
1264                  assert(!"Should not get here.");
1265                  break;
1266               }
1267            }
1268
1269            /* Mask of fields to be written in the assignment. */
1270            constant_mask |=
1271               ((1U << rhs_components) - 1) << base_lhs_component;
1272            constant_components += rhs_components;
1273
1274            base_component += rhs_components;
1275         }
1276         /* Advance the component index by the number of components
1277          * that were just assigned.
1278          */
1279         base_lhs_component += rhs_components;
1280      }
1281
1282      if (constant_mask != 0) {
1283         ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1284         const glsl_type *rhs_type =
1285            glsl_type::get_instance(var->type->base_type,
1286                                    constant_components,
1287                                    1);
1288         ir_rvalue *rhs = new(ctx) ir_constant(rhs_type, &data);
1289
1290         ir_instruction *inst =
1291            new(ctx) ir_assignment(lhs, rhs, NULL, constant_mask);
1292         instructions->push_tail(inst);
1293      }
1294
1295      base_component = 0;
1296      foreach_in_list(ir_rvalue, param, parameters) {
1297         unsigned rhs_components = param->type->components();
1298
1299         /* Do not try to assign more components to the vector than it has! */
1300         if ((rhs_components + base_component) > lhs_components) {
1301            rhs_components = lhs_components - base_component;
1302         }
1303
1304         /* If we do not have any components left to copy, break out of the
1305          * loop. This can happen when initializing a vec4 with a mat3 as the
1306          * mat3 would have been broken into a series of column vectors.
1307          */
1308         if (rhs_components == 0) {
1309            break;
1310         }
1311
1312         const ir_constant *const c = param->as_constant();
1313         if (c == NULL) {
1314            /* Mask of fields to be written in the assignment. */
1315            const unsigned write_mask = ((1U << rhs_components) - 1)
1316               << base_component;
1317
1318            ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1319
1320            /* Generate a swizzle so that LHS and RHS sizes match. */
1321            ir_rvalue *rhs =
1322               new(ctx) ir_swizzle(param, 0, 1, 2, 3, rhs_components);
1323
1324            ir_instruction *inst =
1325               new(ctx) ir_assignment(lhs, rhs, NULL, write_mask);
1326            instructions->push_tail(inst);
1327         }
1328
1329         /* Advance the component index by the number of components that were
1330          * just assigned.
1331          */
1332         base_component += rhs_components;
1333      }
1334   }
1335   return new(ctx) ir_dereference_variable(var);
1336}
1337
1338
1339/**
1340 * Generate assignment of a portion of a vector to a portion of a matrix column
1341 *
1342 * \param src_base  First component of the source to be used in assignment
1343 * \param column    Column of destination to be assiged
1344 * \param row_base  First component of the destination column to be assigned
1345 * \param count     Number of components to be assigned
1346 *
1347 * \note
1348 * \c src_base + \c count must be less than or equal to the number of
1349 * components in the source vector.
1350 */
1351ir_instruction *
1352assign_to_matrix_column(ir_variable *var, unsigned column, unsigned row_base,
1353                        ir_rvalue *src, unsigned src_base, unsigned count,
1354                        void *mem_ctx)
1355{
1356   ir_constant *col_idx = new(mem_ctx) ir_constant(column);
1357   ir_dereference *column_ref = new(mem_ctx) ir_dereference_array(var,
1358                                                                  col_idx);
1359
1360   assert(column_ref->type->components() >= (row_base + count));
1361   assert(src->type->components() >= (src_base + count));
1362
1363   /* Generate a swizzle that extracts the number of components from the source
1364    * that are to be assigned to the column of the matrix.
1365    */
1366   if (count < src->type->vector_elements) {
1367      src = new(mem_ctx) ir_swizzle(src,
1368                                    src_base + 0, src_base + 1,
1369                                    src_base + 2, src_base + 3,
1370                                    count);
1371   }
1372
1373   /* Mask of fields to be written in the assignment. */
1374   const unsigned write_mask = ((1U << count) - 1) << row_base;
1375
1376   return new(mem_ctx) ir_assignment(column_ref, src, NULL, write_mask);
1377}
1378
1379
1380/**
1381 * Generate inline code for a matrix constructor
1382 *
1383 * The generated constructor code will consist of a temporary variable
1384 * declaration of the same type as the constructor.  A sequence of assignments
1385 * from constructor parameters to the temporary will follow.
1386 *
1387 * \return
1388 * An \c ir_dereference_variable of the temprorary generated in the constructor
1389 * body.
1390 */
1391ir_rvalue *
1392emit_inline_matrix_constructor(const glsl_type *type,
1393                               exec_list *instructions,
1394                               exec_list *parameters,
1395                               void *ctx)
1396{
1397   assert(!parameters->is_empty());
1398
1399   ir_variable *var = new(ctx) ir_variable(type, "mat_ctor", ir_var_temporary);
1400   instructions->push_tail(var);
1401
1402   /* There are three kinds of matrix constructors.
1403    *
1404    *  - Construct a matrix from a single scalar by replicating that scalar to
1405    *    along the diagonal of the matrix and setting all other components to
1406    *    zero.
1407    *
1408    *  - Construct a matrix from an arbirary combination of vectors and
1409    *    scalars.  The components of the constructor parameters are assigned
1410    *    to the matrix in column-major order until the matrix is full.
1411    *
1412    *  - Construct a matrix from a single matrix.  The source matrix is copied
1413    *    to the upper left portion of the constructed matrix, and the remaining
1414    *    elements take values from the identity matrix.
1415    */
1416   ir_rvalue *const first_param = (ir_rvalue *) parameters->get_head_raw();
1417   if (single_scalar_parameter(parameters)) {
1418      /* Assign the scalar to the X component of a vec4, and fill the remaining
1419       * components with zero.
1420       */
1421      glsl_base_type param_base_type = first_param->type->base_type;
1422      assert(param_base_type == GLSL_TYPE_FLOAT ||
1423             param_base_type == GLSL_TYPE_DOUBLE);
1424      ir_variable *rhs_var =
1425         new(ctx) ir_variable(glsl_type::get_instance(param_base_type, 4, 1),
1426                              "mat_ctor_vec",
1427                              ir_var_temporary);
1428      instructions->push_tail(rhs_var);
1429
1430      ir_constant_data zero;
1431      for (unsigned i = 0; i < 4; i++)
1432         if (param_base_type == GLSL_TYPE_FLOAT)
1433            zero.f[i] = 0.0;
1434         else
1435            zero.d[i] = 0.0;
1436
1437      ir_instruction *inst =
1438         new(ctx) ir_assignment(new(ctx) ir_dereference_variable(rhs_var),
1439                                new(ctx) ir_constant(rhs_var->type, &zero),
1440                                NULL);
1441      instructions->push_tail(inst);
1442
1443      ir_dereference *const rhs_ref =
1444         new(ctx) ir_dereference_variable(rhs_var);
1445
1446      inst = new(ctx) ir_assignment(rhs_ref, first_param, NULL, 0x01);
1447      instructions->push_tail(inst);
1448
1449      /* Assign the temporary vector to each column of the destination matrix
1450       * with a swizzle that puts the X component on the diagonal of the
1451       * matrix.  In some cases this may mean that the X component does not
1452       * get assigned into the column at all (i.e., when the matrix has more
1453       * columns than rows).
1454       */
1455      static const unsigned rhs_swiz[4][4] = {
1456         { 0, 1, 1, 1 },
1457         { 1, 0, 1, 1 },
1458         { 1, 1, 0, 1 },
1459         { 1, 1, 1, 0 }
1460      };
1461
1462      const unsigned cols_to_init = MIN2(type->matrix_columns,
1463                                         type->vector_elements);
1464      for (unsigned i = 0; i < cols_to_init; i++) {
1465         ir_constant *const col_idx = new(ctx) ir_constant(i);
1466         ir_rvalue *const col_ref = new(ctx) ir_dereference_array(var,
1467                                                                  col_idx);
1468
1469         ir_rvalue *const rhs_ref = new(ctx) ir_dereference_variable(rhs_var);
1470         ir_rvalue *const rhs = new(ctx) ir_swizzle(rhs_ref, rhs_swiz[i],
1471                                                    type->vector_elements);
1472
1473         inst = new(ctx) ir_assignment(col_ref, rhs, NULL);
1474         instructions->push_tail(inst);
1475      }
1476
1477      for (unsigned i = cols_to_init; i < type->matrix_columns; i++) {
1478         ir_constant *const col_idx = new(ctx) ir_constant(i);
1479         ir_rvalue *const col_ref = new(ctx) ir_dereference_array(var,
1480                                                                  col_idx);
1481
1482         ir_rvalue *const rhs_ref = new(ctx) ir_dereference_variable(rhs_var);
1483         ir_rvalue *const rhs = new(ctx) ir_swizzle(rhs_ref, 1, 1, 1, 1,
1484                                                    type->vector_elements);
1485
1486         inst = new(ctx) ir_assignment(col_ref, rhs, NULL);
1487         instructions->push_tail(inst);
1488      }
1489   } else if (first_param->type->is_matrix()) {
1490      /* From page 50 (56 of the PDF) of the GLSL 1.50 spec:
1491       *
1492       *     "If a matrix is constructed from a matrix, then each component
1493       *     (column i, row j) in the result that has a corresponding
1494       *     component (column i, row j) in the argument will be initialized
1495       *     from there. All other components will be initialized to the
1496       *     identity matrix. If a matrix argument is given to a matrix
1497       *     constructor, it is an error to have any other arguments."
1498       */
1499      assert(first_param->next->is_tail_sentinel());
1500      ir_rvalue *const src_matrix = first_param;
1501
1502      /* If the source matrix is smaller, pre-initialize the relavent parts of
1503       * the destination matrix to the identity matrix.
1504       */
1505      if ((src_matrix->type->matrix_columns < var->type->matrix_columns) ||
1506          (src_matrix->type->vector_elements < var->type->vector_elements)) {
1507
1508         /* If the source matrix has fewer rows, every column of the
1509          * destination must be initialized.  Otherwise only the columns in
1510          * the destination that do not exist in the source must be
1511          * initialized.
1512          */
1513         unsigned col =
1514            (src_matrix->type->vector_elements < var->type->vector_elements)
1515            ? 0 : src_matrix->type->matrix_columns;
1516
1517         const glsl_type *const col_type = var->type->column_type();
1518         for (/* empty */; col < var->type->matrix_columns; col++) {
1519            ir_constant_data ident;
1520
1521            if (!col_type->is_double()) {
1522               ident.f[0] = 0.0f;
1523               ident.f[1] = 0.0f;
1524               ident.f[2] = 0.0f;
1525               ident.f[3] = 0.0f;
1526               ident.f[col] = 1.0f;
1527            } else {
1528               ident.d[0] = 0.0;
1529               ident.d[1] = 0.0;
1530               ident.d[2] = 0.0;
1531               ident.d[3] = 0.0;
1532               ident.d[col] = 1.0;
1533            }
1534
1535            ir_rvalue *const rhs = new(ctx) ir_constant(col_type, &ident);
1536
1537            ir_rvalue *const lhs =
1538               new(ctx) ir_dereference_array(var, new(ctx) ir_constant(col));
1539
1540            ir_instruction *inst = new(ctx) ir_assignment(lhs, rhs, NULL);
1541            instructions->push_tail(inst);
1542         }
1543      }
1544
1545      /* Assign columns from the source matrix to the destination matrix.
1546       *
1547       * Since the parameter will be used in the RHS of multiple assignments,
1548       * generate a temporary and copy the paramter there.
1549       */
1550      ir_variable *const rhs_var =
1551         new(ctx) ir_variable(first_param->type, "mat_ctor_mat",
1552                              ir_var_temporary);
1553      instructions->push_tail(rhs_var);
1554
1555      ir_dereference *const rhs_var_ref =
1556         new(ctx) ir_dereference_variable(rhs_var);
1557      ir_instruction *const inst =
1558         new(ctx) ir_assignment(rhs_var_ref, first_param, NULL);
1559      instructions->push_tail(inst);
1560
1561      const unsigned last_row = MIN2(src_matrix->type->vector_elements,
1562                                     var->type->vector_elements);
1563      const unsigned last_col = MIN2(src_matrix->type->matrix_columns,
1564                                     var->type->matrix_columns);
1565
1566      unsigned swiz[4] = { 0, 0, 0, 0 };
1567      for (unsigned i = 1; i < last_row; i++)
1568         swiz[i] = i;
1569
1570      const unsigned write_mask = (1U << last_row) - 1;
1571
1572      for (unsigned i = 0; i < last_col; i++) {
1573         ir_dereference *const lhs =
1574            new(ctx) ir_dereference_array(var, new(ctx) ir_constant(i));
1575         ir_rvalue *const rhs_col =
1576            new(ctx) ir_dereference_array(rhs_var, new(ctx) ir_constant(i));
1577
1578         /* If one matrix has columns that are smaller than the columns of the
1579          * other matrix, wrap the column access of the larger with a swizzle
1580          * so that the LHS and RHS of the assignment have the same size (and
1581          * therefore have the same type).
1582          *
1583          * It would be perfectly valid to unconditionally generate the
1584          * swizzles, this this will typically result in a more compact IR
1585          * tree.
1586          */
1587         ir_rvalue *rhs;
1588         if (lhs->type->vector_elements != rhs_col->type->vector_elements) {
1589            rhs = new(ctx) ir_swizzle(rhs_col, swiz, last_row);
1590         } else {
1591            rhs = rhs_col;
1592         }
1593
1594         ir_instruction *inst =
1595            new(ctx) ir_assignment(lhs, rhs, NULL, write_mask);
1596         instructions->push_tail(inst);
1597      }
1598   } else {
1599      const unsigned cols = type->matrix_columns;
1600      const unsigned rows = type->vector_elements;
1601      unsigned remaining_slots = rows * cols;
1602      unsigned col_idx = 0;
1603      unsigned row_idx = 0;
1604
1605      foreach_in_list(ir_rvalue, rhs, parameters) {
1606         unsigned rhs_components = rhs->type->components();
1607         unsigned rhs_base = 0;
1608
1609         if (remaining_slots == 0)
1610            break;
1611
1612         /* Since the parameter might be used in the RHS of two assignments,
1613          * generate a temporary and copy the paramter there.
1614          */
1615         ir_variable *rhs_var =
1616            new(ctx) ir_variable(rhs->type, "mat_ctor_vec", ir_var_temporary);
1617         instructions->push_tail(rhs_var);
1618
1619         ir_dereference *rhs_var_ref =
1620            new(ctx) ir_dereference_variable(rhs_var);
1621         ir_instruction *inst = new(ctx) ir_assignment(rhs_var_ref, rhs, NULL);
1622         instructions->push_tail(inst);
1623
1624         do {
1625            /* Assign the current parameter to as many components of the matrix
1626             * as it will fill.
1627             *
1628             * NOTE: A single vector parameter can span two matrix columns.  A
1629             * single vec4, for example, can completely fill a mat2.
1630             */
1631            unsigned count = MIN2(rows - row_idx,
1632                                  rhs_components - rhs_base);
1633
1634            rhs_var_ref = new(ctx) ir_dereference_variable(rhs_var);
1635            ir_instruction *inst = assign_to_matrix_column(var, col_idx,
1636                                                           row_idx,
1637                                                           rhs_var_ref,
1638                                                           rhs_base,
1639                                                           count, ctx);
1640            instructions->push_tail(inst);
1641            rhs_base += count;
1642            row_idx += count;
1643            remaining_slots -= count;
1644
1645            /* Sometimes, there is still data left in the parameters and
1646             * components left to be set in the destination but in other
1647             * column.
1648             */
1649            if (row_idx >= rows) {
1650               row_idx = 0;
1651               col_idx++;
1652            }
1653         } while(remaining_slots > 0 && rhs_base < rhs_components);
1654      }
1655   }
1656
1657   return new(ctx) ir_dereference_variable(var);
1658}
1659
1660
1661ir_rvalue *
1662emit_inline_record_constructor(const glsl_type *type,
1663                               exec_list *instructions,
1664                               exec_list *parameters,
1665                               void *mem_ctx)
1666{
1667   ir_variable *const var =
1668      new(mem_ctx) ir_variable(type, "record_ctor", ir_var_temporary);
1669   ir_dereference_variable *const d =
1670      new(mem_ctx) ir_dereference_variable(var);
1671
1672   instructions->push_tail(var);
1673
1674   exec_node *node = parameters->get_head_raw();
1675   for (unsigned i = 0; i < type->length; i++) {
1676      assert(!node->is_tail_sentinel());
1677
1678      ir_dereference *const lhs =
1679         new(mem_ctx) ir_dereference_record(d->clone(mem_ctx, NULL),
1680                                            type->fields.structure[i].name);
1681
1682      ir_rvalue *const rhs = ((ir_instruction *) node)->as_rvalue();
1683      assert(rhs != NULL);
1684
1685      ir_instruction *const assign =
1686         new(mem_ctx) ir_assignment(lhs, rhs, NULL);
1687
1688      instructions->push_tail(assign);
1689      node = node->next;
1690   }
1691
1692   return d;
1693}
1694
1695
1696static ir_rvalue *
1697process_record_constructor(exec_list *instructions,
1698                           const glsl_type *constructor_type,
1699                           YYLTYPE *loc, exec_list *parameters,
1700                           struct _mesa_glsl_parse_state *state)
1701{
1702   void *ctx = state;
1703   /* From page 32 (page 38 of the PDF) of the GLSL 1.20 spec:
1704    *
1705    *    "The arguments to the constructor will be used to set the structure's
1706    *     fields, in order, using one argument per field. Each argument must
1707    *     be the same type as the field it sets, or be a type that can be
1708    *     converted to the field's type according to Section 4.1.10 “Implicit
1709    *     Conversions.”"
1710    *
1711    * From page 35 (page 41 of the PDF) of the GLSL 4.20 spec:
1712    *
1713    *    "In all cases, the innermost initializer (i.e., not a list of
1714    *     initializers enclosed in curly braces) applied to an object must
1715    *     have the same type as the object being initialized or be a type that
1716    *     can be converted to the object's type according to section 4.1.10
1717    *     "Implicit Conversions". In the latter case, an implicit conversion
1718    *     will be done on the initializer before the assignment is done."
1719    */
1720   exec_list actual_parameters;
1721
1722   const unsigned parameter_count =
1723         process_parameters(instructions, &actual_parameters, parameters,
1724                            state);
1725
1726   if (parameter_count != constructor_type->length) {
1727      _mesa_glsl_error(loc, state,
1728                       "%s parameters in constructor for `%s'",
1729                       parameter_count > constructor_type->length
1730                       ? "too many": "insufficient",
1731                       constructor_type->name);
1732      return ir_rvalue::error_value(ctx);
1733   }
1734
1735   bool all_parameters_are_constant = true;
1736
1737   int i = 0;
1738   /* Type cast each parameter and, if possible, fold constants. */
1739   foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
1740
1741      const glsl_struct_field *struct_field =
1742         &constructor_type->fields.structure[i];
1743
1744      /* Apply implicit conversions (not the scalar constructor rules, see the
1745       * spec quote above!) and attempt to convert the parameter to a constant
1746       * valued expression. After doing so, track whether or not all the
1747       * parameters to the constructor are trivially constant valued
1748       * expressions.
1749       */
1750      all_parameters_are_constant &=
1751         implicitly_convert_component(ir, struct_field->type->base_type,
1752                                      state);
1753
1754      if (ir->type != struct_field->type) {
1755         _mesa_glsl_error(loc, state,
1756                          "parameter type mismatch in constructor for `%s.%s' "
1757                          "(%s vs %s)",
1758                          constructor_type->name,
1759                          struct_field->name,
1760                          ir->type->name,
1761                          struct_field->type->name);
1762         return ir_rvalue::error_value(ctx);
1763      }
1764
1765      i++;
1766   }
1767
1768   if (all_parameters_are_constant) {
1769      return new(ctx) ir_constant(constructor_type, &actual_parameters);
1770   } else {
1771      return emit_inline_record_constructor(constructor_type, instructions,
1772                                            &actual_parameters, state);
1773   }
1774}
1775
1776ir_rvalue *
1777ast_function_expression::handle_method(exec_list *instructions,
1778                                       struct _mesa_glsl_parse_state *state)
1779{
1780   const ast_expression *field = subexpressions[0];
1781   ir_rvalue *op;
1782   ir_rvalue *result;
1783   void *ctx = state;
1784   /* Handle "method calls" in GLSL 1.20 - namely, array.length() */
1785   YYLTYPE loc = get_location();
1786   state->check_version(120, 300, &loc, "methods not supported");
1787
1788   const char *method;
1789   method = field->primary_expression.identifier;
1790
1791   /* This would prevent to raise "uninitialized variable" warnings when
1792    * calling array.length.
1793    */
1794   field->subexpressions[0]->set_is_lhs(true);
1795   op = field->subexpressions[0]->hir(instructions, state);
1796   if (strcmp(method, "length") == 0) {
1797      if (!this->expressions.is_empty()) {
1798         _mesa_glsl_error(&loc, state, "length method takes no arguments");
1799         goto fail;
1800      }
1801
1802      if (op->type->is_array()) {
1803         if (op->type->is_unsized_array()) {
1804            if (!state->has_shader_storage_buffer_objects()) {
1805               _mesa_glsl_error(&loc, state,
1806                                "length called on unsized array"
1807                                " only available with"
1808                                " ARB_shader_storage_buffer_object");
1809            }
1810            /* Calculate length of an unsized array in run-time */
1811            result = new(ctx) ir_expression(ir_unop_ssbo_unsized_array_length,
1812                                            op);
1813         } else {
1814            result = new(ctx) ir_constant(op->type->array_size());
1815         }
1816      } else if (op->type->is_vector()) {
1817         if (state->has_420pack()) {
1818            /* .length() returns int. */
1819            result = new(ctx) ir_constant((int) op->type->vector_elements);
1820         } else {
1821            _mesa_glsl_error(&loc, state, "length method on matrix only"
1822                             " available with ARB_shading_language_420pack");
1823            goto fail;
1824         }
1825      } else if (op->type->is_matrix()) {
1826         if (state->has_420pack()) {
1827            /* .length() returns int. */
1828            result = new(ctx) ir_constant((int) op->type->matrix_columns);
1829         } else {
1830            _mesa_glsl_error(&loc, state, "length method on matrix only"
1831                             " available with ARB_shading_language_420pack");
1832            goto fail;
1833         }
1834      } else {
1835         _mesa_glsl_error(&loc, state, "length called on scalar.");
1836         goto fail;
1837      }
1838   } else {
1839      _mesa_glsl_error(&loc, state, "unknown method: `%s'", method);
1840      goto fail;
1841   }
1842   return result;
1843 fail:
1844   return ir_rvalue::error_value(ctx);
1845}
1846
1847ir_rvalue *
1848ast_function_expression::hir(exec_list *instructions,
1849                             struct _mesa_glsl_parse_state *state)
1850{
1851   void *ctx = state;
1852   /* There are three sorts of function calls.
1853    *
1854    * 1. constructors - The first subexpression is an ast_type_specifier.
1855    * 2. methods - Only the .length() method of array types.
1856    * 3. functions - Calls to regular old functions.
1857    *
1858    */
1859   if (is_constructor()) {
1860      const ast_type_specifier *type =
1861         (ast_type_specifier *) subexpressions[0];
1862      YYLTYPE loc = type->get_location();
1863      const char *name;
1864
1865      const glsl_type *const constructor_type = type->glsl_type(& name, state);
1866
1867      /* constructor_type can be NULL if a variable with the same name as the
1868       * structure has come into scope.
1869       */
1870      if (constructor_type == NULL) {
1871         _mesa_glsl_error(& loc, state, "unknown type `%s' (structure name "
1872                          "may be shadowed by a variable with the same name)",
1873                          type->type_name);
1874         return ir_rvalue::error_value(ctx);
1875      }
1876
1877
1878      /* Constructors for opaque types are illegal.
1879       */
1880      if (constructor_type->contains_opaque()) {
1881         _mesa_glsl_error(& loc, state, "cannot construct opaque type `%s'",
1882                          constructor_type->name);
1883         return ir_rvalue::error_value(ctx);
1884      }
1885
1886      if (constructor_type->is_subroutine()) {
1887         _mesa_glsl_error(& loc, state,
1888                          "subroutine name cannot be a constructor `%s'",
1889                          constructor_type->name);
1890         return ir_rvalue::error_value(ctx);
1891      }
1892
1893      if (constructor_type->is_array()) {
1894         if (!state->check_version(120, 300, &loc,
1895                                   "array constructors forbidden")) {
1896            return ir_rvalue::error_value(ctx);
1897         }
1898
1899         return process_array_constructor(instructions, constructor_type,
1900                                          & loc, &this->expressions, state);
1901      }
1902
1903
1904      /* There are two kinds of constructor calls.  Constructors for arrays and
1905       * structures must have the exact number of arguments with matching types
1906       * in the correct order.  These constructors follow essentially the same
1907       * type matching rules as functions.
1908       *
1909       * Constructors for built-in language types, such as mat4 and vec2, are
1910       * free form.  The only requirements are that the parameters must provide
1911       * enough values of the correct scalar type and that no arguments are
1912       * given past the last used argument.
1913       *
1914       * When using the C-style initializer syntax from GLSL 4.20, constructors
1915       * must have the exact number of arguments with matching types in the
1916       * correct order.
1917       */
1918      if (constructor_type->is_record()) {
1919         return process_record_constructor(instructions, constructor_type,
1920                                           &loc, &this->expressions,
1921                                           state);
1922      }
1923
1924      if (!constructor_type->is_numeric() && !constructor_type->is_boolean())
1925         return ir_rvalue::error_value(ctx);
1926
1927      /* Total number of components of the type being constructed. */
1928      const unsigned type_components = constructor_type->components();
1929
1930      /* Number of components from parameters that have actually been
1931       * consumed.  This is used to perform several kinds of error checking.
1932       */
1933      unsigned components_used = 0;
1934
1935      unsigned matrix_parameters = 0;
1936      unsigned nonmatrix_parameters = 0;
1937      exec_list actual_parameters;
1938
1939      foreach_list_typed(ast_node, ast, link, &this->expressions) {
1940         ir_rvalue *result = ast->hir(instructions, state);
1941
1942         /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
1943          *
1944          *    "It is an error to provide extra arguments beyond this
1945          *    last used argument."
1946          */
1947         if (components_used >= type_components) {
1948            _mesa_glsl_error(& loc, state, "too many parameters to `%s' "
1949                             "constructor",
1950                             constructor_type->name);
1951            return ir_rvalue::error_value(ctx);
1952         }
1953
1954         if (!result->type->is_numeric() && !result->type->is_boolean()) {
1955            _mesa_glsl_error(& loc, state, "cannot construct `%s' from a "
1956                             "non-numeric data type",
1957                             constructor_type->name);
1958            return ir_rvalue::error_value(ctx);
1959         }
1960
1961         /* Count the number of matrix and nonmatrix parameters.  This
1962          * is used below to enforce some of the constructor rules.
1963          */
1964         if (result->type->is_matrix())
1965            matrix_parameters++;
1966         else
1967            nonmatrix_parameters++;
1968
1969         actual_parameters.push_tail(result);
1970         components_used += result->type->components();
1971      }
1972
1973      /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
1974       *
1975       *    "It is an error to construct matrices from other matrices. This
1976       *    is reserved for future use."
1977       */
1978      if (matrix_parameters > 0
1979          && constructor_type->is_matrix()
1980          && !state->check_version(120, 100, &loc,
1981                                   "cannot construct `%s' from a matrix",
1982                                   constructor_type->name)) {
1983         return ir_rvalue::error_value(ctx);
1984      }
1985
1986      /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
1987       *
1988       *    "If a matrix argument is given to a matrix constructor, it is
1989       *    an error to have any other arguments."
1990       */
1991      if ((matrix_parameters > 0)
1992          && ((matrix_parameters + nonmatrix_parameters) > 1)
1993          && constructor_type->is_matrix()) {
1994         _mesa_glsl_error(& loc, state, "for matrix `%s' constructor, "
1995                          "matrix must be only parameter",
1996                          constructor_type->name);
1997         return ir_rvalue::error_value(ctx);
1998      }
1999
2000      /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
2001       *
2002       *    "In these cases, there must be enough components provided in the
2003       *    arguments to provide an initializer for every component in the
2004       *    constructed value."
2005       */
2006      if (components_used < type_components && components_used != 1
2007          && matrix_parameters == 0) {
2008         _mesa_glsl_error(& loc, state, "too few components to construct "
2009                          "`%s'",
2010                          constructor_type->name);
2011         return ir_rvalue::error_value(ctx);
2012      }
2013
2014      /* Matrices can never be consumed as is by any constructor but matrix
2015       * constructors. If the constructor type is not matrix, always break the
2016       * matrix up into a series of column vectors.
2017       */
2018      if (!constructor_type->is_matrix()) {
2019         foreach_in_list_safe(ir_rvalue, matrix, &actual_parameters) {
2020            if (!matrix->type->is_matrix())
2021               continue;
2022
2023            /* Create a temporary containing the matrix. */
2024            ir_variable *var = new(ctx) ir_variable(matrix->type, "matrix_tmp",
2025                                                    ir_var_temporary);
2026            instructions->push_tail(var);
2027            instructions->push_tail(
2028               new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
2029                                      matrix, NULL));
2030            var->constant_value = matrix->constant_expression_value();
2031
2032            /* Replace the matrix with dereferences of its columns. */
2033            for (int i = 0; i < matrix->type->matrix_columns; i++) {
2034               matrix->insert_before(
2035                  new (ctx) ir_dereference_array(var,
2036                                                 new(ctx) ir_constant(i)));
2037            }
2038            matrix->remove();
2039         }
2040      }
2041
2042      bool all_parameters_are_constant = true;
2043
2044      /* Type cast each parameter and, if possible, fold constants.*/
2045      foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
2046         const glsl_type *desired_type =
2047            glsl_type::get_instance(constructor_type->base_type,
2048                                    ir->type->vector_elements,
2049                                    ir->type->matrix_columns);
2050         ir_rvalue *result = convert_component(ir, desired_type);
2051
2052         /* Attempt to convert the parameter to a constant valued expression.
2053          * After doing so, track whether or not all the parameters to the
2054          * constructor are trivially constant valued expressions.
2055          */
2056         ir_rvalue *const constant = result->constant_expression_value();
2057
2058         if (constant != NULL)
2059            result = constant;
2060         else
2061            all_parameters_are_constant = false;
2062
2063         if (result != ir) {
2064            ir->replace_with(result);
2065         }
2066      }
2067
2068      /* If all of the parameters are trivially constant, create a
2069       * constant representing the complete collection of parameters.
2070       */
2071      if (all_parameters_are_constant) {
2072         return new(ctx) ir_constant(constructor_type, &actual_parameters);
2073      } else if (constructor_type->is_scalar()) {
2074         return dereference_component((ir_rvalue *)
2075                                      actual_parameters.get_head_raw(),
2076                                      0);
2077      } else if (constructor_type->is_vector()) {
2078         return emit_inline_vector_constructor(constructor_type,
2079                                               instructions,
2080                                               &actual_parameters,
2081                                               ctx);
2082      } else {
2083         assert(constructor_type->is_matrix());
2084         return emit_inline_matrix_constructor(constructor_type,
2085                                               instructions,
2086                                               &actual_parameters,
2087                                               ctx);
2088      }
2089   } else if (subexpressions[0]->oper == ast_field_selection) {
2090      return handle_method(instructions, state);
2091   } else {
2092      const ast_expression *id = subexpressions[0];
2093      const char *func_name = NULL;
2094      YYLTYPE loc = get_location();
2095      exec_list actual_parameters;
2096      ir_variable *sub_var = NULL;
2097      ir_rvalue *array_idx = NULL;
2098
2099      process_parameters(instructions, &actual_parameters, &this->expressions,
2100                         state);
2101
2102      if (id->oper == ast_array_index) {
2103         array_idx = generate_array_index(ctx, instructions, state, loc,
2104                                          id->subexpressions[0],
2105                                          id->subexpressions[1], &func_name,
2106                                          &actual_parameters);
2107      } else if (id->oper == ast_identifier) {
2108         func_name = id->primary_expression.identifier;
2109      } else {
2110         _mesa_glsl_error(&loc, state, "function name is not an identifier");
2111      }
2112
2113      /* an error was emitted earlier */
2114      if (!func_name)
2115         return ir_rvalue::error_value(ctx);
2116
2117      ir_function_signature *sig =
2118         match_function_by_name(func_name, &actual_parameters, state);
2119
2120      ir_rvalue *value = NULL;
2121      if (sig == NULL) {
2122         sig = match_subroutine_by_name(func_name, &actual_parameters,
2123                                        state, &sub_var);
2124      }
2125
2126      if (sig == NULL) {
2127         no_matching_function_error(func_name, &loc,
2128                                    &actual_parameters, state);
2129         value = ir_rvalue::error_value(ctx);
2130      } else if (!verify_parameter_modes(state, sig,
2131                                         actual_parameters,
2132                                         this->expressions)) {
2133         /* an error has already been emitted */
2134         value = ir_rvalue::error_value(ctx);
2135      } else if (sig->is_builtin() && strcmp(func_name, "ftransform") == 0) {
2136         /* ftransform refers to global variables, and we don't have any code
2137          * for remapping the variable references in the built-in shader.
2138          */
2139         ir_variable *mvp =
2140            state->symbols->get_variable("gl_ModelViewProjectionMatrix");
2141         ir_variable *vtx = state->symbols->get_variable("gl_Vertex");
2142         value = new(ctx) ir_expression(ir_binop_mul, glsl_type::vec4_type,
2143                                        new(ctx) ir_dereference_variable(mvp),
2144                                        new(ctx) ir_dereference_variable(vtx));
2145      } else {
2146         if (state->stage == MESA_SHADER_TESS_CTRL &&
2147             sig->is_builtin() && strcmp(func_name, "barrier") == 0) {
2148            if (state->current_function == NULL ||
2149                strcmp(state->current_function->function_name(), "main") != 0) {
2150               _mesa_glsl_error(&loc, state,
2151                                "barrier() may only be used in main()");
2152            }
2153
2154            if (state->found_return) {
2155               _mesa_glsl_error(&loc, state,
2156                                "barrier() may not be used after return");
2157            }
2158
2159            if (instructions != &state->current_function->body) {
2160               _mesa_glsl_error(&loc, state,
2161                                "barrier() may not be used in control flow");
2162            }
2163         }
2164
2165         value = generate_call(instructions, sig, &actual_parameters, sub_var,
2166                               array_idx, state, sig->is_builtin());
2167         if (!value) {
2168            ir_variable *const tmp = new(ctx) ir_variable(glsl_type::void_type,
2169                                                          "void_var",
2170                                                          ir_var_temporary);
2171            instructions->push_tail(tmp);
2172            value = new(ctx) ir_dereference_variable(tmp);
2173         }
2174      }
2175
2176      return value;
2177   }
2178
2179   unreachable("not reached");
2180}
2181
2182bool
2183ast_function_expression::has_sequence_subexpression() const
2184{
2185   foreach_list_typed(const ast_node, ast, link, &this->expressions) {
2186      if (ast->has_sequence_subexpression())
2187         return true;
2188   }
2189
2190   return false;
2191}
2192
2193ir_rvalue *
2194ast_aggregate_initializer::hir(exec_list *instructions,
2195                               struct _mesa_glsl_parse_state *state)
2196{
2197   void *ctx = state;
2198   YYLTYPE loc = this->get_location();
2199
2200   if (!this->constructor_type) {
2201      _mesa_glsl_error(&loc, state, "type of C-style initializer unknown");
2202      return ir_rvalue::error_value(ctx);
2203   }
2204   const glsl_type *const constructor_type = this->constructor_type;
2205
2206   if (!state->has_420pack()) {
2207      _mesa_glsl_error(&loc, state, "C-style initialization requires the "
2208                       "GL_ARB_shading_language_420pack extension");
2209      return ir_rvalue::error_value(ctx);
2210   }
2211
2212   if (constructor_type->is_array()) {
2213      return process_array_constructor(instructions, constructor_type, &loc,
2214                                       &this->expressions, state);
2215   }
2216
2217   if (constructor_type->is_record()) {
2218      return process_record_constructor(instructions, constructor_type, &loc,
2219                                        &this->expressions, state);
2220   }
2221
2222   return process_vec_mat_constructor(instructions, constructor_type, &loc,
2223                                      &this->expressions, state);
2224}
2225