glsl: At link-time, check that globals have matching centroid qualifiers
[profile/ivi/mesa.git] / src / glsl / linker.cpp
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 /**
25  * \file linker.cpp
26  * GLSL linker implementation
27  *
28  * Given a set of shaders that are to be linked to generate a final program,
29  * there are three distinct stages.
30  *
31  * In the first stage shaders are partitioned into groups based on the shader
32  * type.  All shaders of a particular type (e.g., vertex shaders) are linked
33  * together.
34  *
35  *   - Undefined references in each shader are resolve to definitions in
36  *     another shader.
37  *   - Types and qualifiers of uniforms, outputs, and global variables defined
38  *     in multiple shaders with the same name are verified to be the same.
39  *   - Initializers for uniforms and global variables defined
40  *     in multiple shaders with the same name are verified to be the same.
41  *
42  * The result, in the terminology of the GLSL spec, is a set of shader
43  * executables for each processing unit.
44  *
45  * After the first stage is complete, a series of semantic checks are performed
46  * on each of the shader executables.
47  *
48  *   - Each shader executable must define a \c main function.
49  *   - Each vertex shader executable must write to \c gl_Position.
50  *   - Each fragment shader executable must write to either \c gl_FragData or
51  *     \c gl_FragColor.
52  *
53  * In the final stage individual shader executables are linked to create a
54  * complete exectuable.
55  *
56  *   - Types of uniforms defined in multiple shader stages with the same name
57  *     are verified to be the same.
58  *   - Initializers for uniforms defined in multiple shader stages with the
59  *     same name are verified to be the same.
60  *   - Types and qualifiers of outputs defined in one stage are verified to
61  *     be the same as the types and qualifiers of inputs defined with the same
62  *     name in a later stage.
63  *
64  * \author Ian Romanick <ian.d.romanick@intel.com>
65  */
66 #include <cstdlib>
67 #include <cstdio>
68 #include <cstdarg>
69 #include <climits>
70
71 extern "C" {
72 #include <talloc.h>
73 }
74
75 #include "main/core.h"
76 #include "glsl_symbol_table.h"
77 #include "ir.h"
78 #include "program.h"
79 #include "program/hash_table.h"
80 #include "linker.h"
81 #include "ir_optimization.h"
82
83 extern "C" {
84 #include "main/shaderobj.h"
85 }
86
87 /**
88  * Visitor that determines whether or not a variable is ever written.
89  */
90 class find_assignment_visitor : public ir_hierarchical_visitor {
91 public:
92    find_assignment_visitor(const char *name)
93       : name(name), found(false)
94    {
95       /* empty */
96    }
97
98    virtual ir_visitor_status visit_enter(ir_assignment *ir)
99    {
100       ir_variable *const var = ir->lhs->variable_referenced();
101
102       if (strcmp(name, var->name) == 0) {
103          found = true;
104          return visit_stop;
105       }
106
107       return visit_continue_with_parent;
108    }
109
110    virtual ir_visitor_status visit_enter(ir_call *ir)
111    {
112       exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
113       foreach_iter(exec_list_iterator, iter, *ir) {
114          ir_rvalue *param_rval = (ir_rvalue *)iter.get();
115          ir_variable *sig_param = (ir_variable *)sig_iter.get();
116
117          if (sig_param->mode == ir_var_out ||
118              sig_param->mode == ir_var_inout) {
119             ir_variable *var = param_rval->variable_referenced();
120             if (var && strcmp(name, var->name) == 0) {
121                found = true;
122                return visit_stop;
123             }
124          }
125          sig_iter.next();
126       }
127
128       return visit_continue_with_parent;
129    }
130
131    bool variable_found()
132    {
133       return found;
134    }
135
136 private:
137    const char *name;       /**< Find writes to a variable with this name. */
138    bool found;             /**< Was a write to the variable found? */
139 };
140
141
142 /**
143  * Visitor that determines whether or not a variable is ever read.
144  */
145 class find_deref_visitor : public ir_hierarchical_visitor {
146 public:
147    find_deref_visitor(const char *name)
148       : name(name), found(false)
149    {
150       /* empty */
151    }
152
153    virtual ir_visitor_status visit(ir_dereference_variable *ir)
154    {
155       if (strcmp(this->name, ir->var->name) == 0) {
156          this->found = true;
157          return visit_stop;
158       }
159
160       return visit_continue;
161    }
162
163    bool variable_found() const
164    {
165       return this->found;
166    }
167
168 private:
169    const char *name;       /**< Find writes to a variable with this name. */
170    bool found;             /**< Was a write to the variable found? */
171 };
172
173
174 void
175 linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
176 {
177    va_list ap;
178
179    prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
180    va_start(ap, fmt);
181    prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
182    va_end(ap);
183 }
184
185
186 void
187 invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
188                               int generic_base)
189 {
190    foreach_list(node, sh->ir) {
191       ir_variable *const var = ((ir_instruction *) node)->as_variable();
192
193       if ((var == NULL) || (var->mode != (unsigned) mode))
194          continue;
195
196       /* Only assign locations for generic attributes / varyings / etc.
197        */
198       if ((var->location >= generic_base) && !var->explicit_location)
199           var->location = -1;
200    }
201 }
202
203
204 /**
205  * Determine the number of attribute slots required for a particular type
206  *
207  * This code is here because it implements the language rules of a specific
208  * GLSL version.  Since it's a property of the language and not a property of
209  * types in general, it doesn't really belong in glsl_type.
210  */
211 unsigned
212 count_attribute_slots(const glsl_type *t)
213 {
214    /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
215     *
216     *     "A scalar input counts the same amount against this limit as a vec4,
217     *     so applications may want to consider packing groups of four
218     *     unrelated float inputs together into a vector to better utilize the
219     *     capabilities of the underlying hardware. A matrix input will use up
220     *     multiple locations.  The number of locations used will equal the
221     *     number of columns in the matrix."
222     *
223     * The spec does not explicitly say how arrays are counted.  However, it
224     * should be safe to assume the total number of slots consumed by an array
225     * is the number of entries in the array multiplied by the number of slots
226     * consumed by a single element of the array.
227     */
228
229    if (t->is_array())
230       return t->array_size() * count_attribute_slots(t->element_type());
231
232    if (t->is_matrix())
233       return t->matrix_columns;
234
235    return 1;
236 }
237
238
239 /**
240  * Verify that a vertex shader executable meets all semantic requirements
241  *
242  * \param shader  Vertex shader executable to be verified
243  */
244 bool
245 validate_vertex_shader_executable(struct gl_shader_program *prog,
246                                   struct gl_shader *shader)
247 {
248    if (shader == NULL)
249       return true;
250
251    find_assignment_visitor find("gl_Position");
252    find.run(shader->ir);
253    if (!find.variable_found()) {
254       linker_error_printf(prog,
255                           "vertex shader does not write to `gl_Position'\n");
256       return false;
257    }
258
259    return true;
260 }
261
262
263 /**
264  * Verify that a fragment shader executable meets all semantic requirements
265  *
266  * \param shader  Fragment shader executable to be verified
267  */
268 bool
269 validate_fragment_shader_executable(struct gl_shader_program *prog,
270                                     struct gl_shader *shader)
271 {
272    if (shader == NULL)
273       return true;
274
275    find_assignment_visitor frag_color("gl_FragColor");
276    find_assignment_visitor frag_data("gl_FragData");
277
278    frag_color.run(shader->ir);
279    frag_data.run(shader->ir);
280
281    if (frag_color.variable_found() && frag_data.variable_found()) {
282       linker_error_printf(prog,  "fragment shader writes to both "
283                           "`gl_FragColor' and `gl_FragData'\n");
284       return false;
285    }
286
287    return true;
288 }
289
290
291 /**
292  * Generate a string describing the mode of a variable
293  */
294 static const char *
295 mode_string(const ir_variable *var)
296 {
297    switch (var->mode) {
298    case ir_var_auto:
299       return (var->read_only) ? "global constant" : "global variable";
300
301    case ir_var_uniform: return "uniform";
302    case ir_var_in:      return "shader input";
303    case ir_var_out:     return "shader output";
304    case ir_var_inout:   return "shader inout";
305
306    case ir_var_temporary:
307    default:
308       assert(!"Should not get here.");
309       return "invalid variable";
310    }
311 }
312
313
314 /**
315  * Perform validation of global variables used across multiple shaders
316  */
317 bool
318 cross_validate_globals(struct gl_shader_program *prog,
319                        struct gl_shader **shader_list,
320                        unsigned num_shaders,
321                        bool uniforms_only)
322 {
323    /* Examine all of the uniforms in all of the shaders and cross validate
324     * them.
325     */
326    glsl_symbol_table variables;
327    for (unsigned i = 0; i < num_shaders; i++) {
328       if (shader_list[i] == NULL)
329          continue;
330
331       foreach_list(node, shader_list[i]->ir) {
332          ir_variable *const var = ((ir_instruction *) node)->as_variable();
333
334          if (var == NULL)
335             continue;
336
337          if (uniforms_only && (var->mode != ir_var_uniform))
338             continue;
339
340          /* Don't cross validate temporaries that are at global scope.  These
341           * will eventually get pulled into the shaders 'main'.
342           */
343          if (var->mode == ir_var_temporary)
344             continue;
345
346          /* If a global with this name has already been seen, verify that the
347           * new instance has the same type.  In addition, if the globals have
348           * initializers, the values of the initializers must be the same.
349           */
350          ir_variable *const existing = variables.get_variable(var->name);
351          if (existing != NULL) {
352             if (var->type != existing->type) {
353                /* Consider the types to be "the same" if both types are arrays
354                 * of the same type and one of the arrays is implicitly sized.
355                 * In addition, set the type of the linked variable to the
356                 * explicitly sized array.
357                 */
358                if (var->type->is_array()
359                    && existing->type->is_array()
360                    && (var->type->fields.array == existing->type->fields.array)
361                    && ((var->type->length == 0)
362                        || (existing->type->length == 0))) {
363                   if (existing->type->length == 0) {
364                      existing->type = var->type;
365                      existing->max_array_access =
366                         MAX2(existing->max_array_access,
367                              var->max_array_access);
368                   }
369                } else {
370                   linker_error_printf(prog, "%s `%s' declared as type "
371                                       "`%s' and type `%s'\n",
372                                       mode_string(var),
373                                       var->name, var->type->name,
374                                       existing->type->name);
375                   return false;
376                }
377             }
378
379             if (var->explicit_location) {
380                if (existing->explicit_location
381                    && (var->location != existing->location)) {
382                      linker_error_printf(prog, "explicit locations for %s "
383                                          "`%s' have differing values\n",
384                                          mode_string(var), var->name);
385                      return false;
386                }
387
388                existing->location = var->location;
389                existing->explicit_location = true;
390             }
391
392             /* FINISHME: Handle non-constant initializers.
393              */
394             if (var->constant_value != NULL) {
395                if (existing->constant_value != NULL) {
396                   if (!var->constant_value->has_value(existing->constant_value)) {
397                      linker_error_printf(prog, "initializers for %s "
398                                          "`%s' have differing values\n",
399                                          mode_string(var), var->name);
400                      return false;
401                   }
402                } else
403                   /* If the first-seen instance of a particular uniform did not
404                    * have an initializer but a later instance does, copy the
405                    * initializer to the version stored in the symbol table.
406                    */
407                   /* FINISHME: This is wrong.  The constant_value field should
408                    * FINISHME: not be modified!  Imagine a case where a shader
409                    * FINISHME: without an initializer is linked in two different
410                    * FINISHME: programs with shaders that have differing
411                    * FINISHME: initializers.  Linking with the first will
412                    * FINISHME: modify the shader, and linking with the second
413                    * FINISHME: will fail.
414                    */
415                   existing->constant_value =
416                      var->constant_value->clone(talloc_parent(existing), NULL);
417             }
418
419             if (existing->invariant != var->invariant) {
420                linker_error_printf(prog, "declarations for %s `%s' have "
421                                    "mismatching invariant qualifiers\n",
422                                    mode_string(var), var->name);
423                return false;
424             }
425             if (existing->centroid != var->centroid) {
426                linker_error_printf(prog, "declarations for %s `%s' have "
427                                    "mismatching centroid qualifiers\n",
428                                    mode_string(var), var->name);
429                return false;
430             }
431          } else
432             variables.add_variable(var);
433       }
434    }
435
436    return true;
437 }
438
439
440 /**
441  * Perform validation of uniforms used across multiple shader stages
442  */
443 bool
444 cross_validate_uniforms(struct gl_shader_program *prog)
445 {
446    return cross_validate_globals(prog, prog->_LinkedShaders,
447                                  MESA_SHADER_TYPES, true);
448 }
449
450
451 /**
452  * Validate that outputs from one stage match inputs of another
453  */
454 bool
455 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
456                                  gl_shader *producer, gl_shader *consumer)
457 {
458    glsl_symbol_table parameters;
459    /* FINISHME: Figure these out dynamically. */
460    const char *const producer_stage = "vertex";
461    const char *const consumer_stage = "fragment";
462
463    /* Find all shader outputs in the "producer" stage.
464     */
465    foreach_list(node, producer->ir) {
466       ir_variable *const var = ((ir_instruction *) node)->as_variable();
467
468       /* FINISHME: For geometry shaders, this should also look for inout
469        * FINISHME: variables.
470        */
471       if ((var == NULL) || (var->mode != ir_var_out))
472          continue;
473
474       parameters.add_variable(var);
475    }
476
477
478    /* Find all shader inputs in the "consumer" stage.  Any variables that have
479     * matching outputs already in the symbol table must have the same type and
480     * qualifiers.
481     */
482    foreach_list(node, consumer->ir) {
483       ir_variable *const input = ((ir_instruction *) node)->as_variable();
484
485       /* FINISHME: For geometry shaders, this should also look for inout
486        * FINISHME: variables.
487        */
488       if ((input == NULL) || (input->mode != ir_var_in))
489          continue;
490
491       ir_variable *const output = parameters.get_variable(input->name);
492       if (output != NULL) {
493          /* Check that the types match between stages.
494           */
495          if (input->type != output->type) {
496             /* There is a bit of a special case for gl_TexCoord.  This
497              * built-in is unsized by default.  Appliations that variable
498              * access it must redeclare it with a size.  There is some
499              * language in the GLSL spec that implies the fragment shader
500              * and vertex shader do not have to agree on this size.  Other
501              * driver behave this way, and one or two applications seem to
502              * rely on it.
503              *
504              * Neither declaration needs to be modified here because the array
505              * sizes are fixed later when update_array_sizes is called.
506              *
507              * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
508              *
509              *     "Unlike user-defined varying variables, the built-in
510              *     varying variables don't have a strict one-to-one
511              *     correspondence between the vertex language and the
512              *     fragment language."
513              */
514             if (!output->type->is_array()
515                 || (strncmp("gl_", output->name, 3) != 0)) {
516                linker_error_printf(prog,
517                                    "%s shader output `%s' declared as "
518                                    "type `%s', but %s shader input declared "
519                                    "as type `%s'\n",
520                                    producer_stage, output->name,
521                                    output->type->name,
522                                    consumer_stage, input->type->name);
523                return false;
524             }
525          }
526
527          /* Check that all of the qualifiers match between stages.
528           */
529          if (input->centroid != output->centroid) {
530             linker_error_printf(prog,
531                                 "%s shader output `%s' %s centroid qualifier, "
532                                 "but %s shader input %s centroid qualifier\n",
533                                 producer_stage,
534                                 output->name,
535                                 (output->centroid) ? "has" : "lacks",
536                                 consumer_stage,
537                                 (input->centroid) ? "has" : "lacks");
538             return false;
539          }
540
541          if (input->invariant != output->invariant) {
542             linker_error_printf(prog,
543                                 "%s shader output `%s' %s invariant qualifier, "
544                                 "but %s shader input %s invariant qualifier\n",
545                                 producer_stage,
546                                 output->name,
547                                 (output->invariant) ? "has" : "lacks",
548                                 consumer_stage,
549                                 (input->invariant) ? "has" : "lacks");
550             return false;
551          }
552
553          if (input->interpolation != output->interpolation) {
554             linker_error_printf(prog,
555                                 "%s shader output `%s' specifies %s "
556                                 "interpolation qualifier, "
557                                 "but %s shader input specifies %s "
558                                 "interpolation qualifier\n",
559                                 producer_stage,
560                                 output->name,
561                                 output->interpolation_string(),
562                                 consumer_stage,
563                                 input->interpolation_string());
564             return false;
565          }
566       }
567    }
568
569    return true;
570 }
571
572
573 /**
574  * Populates a shaders symbol table with all global declarations
575  */
576 static void
577 populate_symbol_table(gl_shader *sh)
578 {
579    sh->symbols = new(sh) glsl_symbol_table;
580
581    foreach_list(node, sh->ir) {
582       ir_instruction *const inst = (ir_instruction *) node;
583       ir_variable *var;
584       ir_function *func;
585
586       if ((func = inst->as_function()) != NULL) {
587          sh->symbols->add_function(func);
588       } else if ((var = inst->as_variable()) != NULL) {
589          sh->symbols->add_variable(var);
590       }
591    }
592 }
593
594
595 /**
596  * Remap variables referenced in an instruction tree
597  *
598  * This is used when instruction trees are cloned from one shader and placed in
599  * another.  These trees will contain references to \c ir_variable nodes that
600  * do not exist in the target shader.  This function finds these \c ir_variable
601  * references and replaces the references with matching variables in the target
602  * shader.
603  *
604  * If there is no matching variable in the target shader, a clone of the
605  * \c ir_variable is made and added to the target shader.  The new variable is
606  * added to \b both the instruction stream and the symbol table.
607  *
608  * \param inst         IR tree that is to be processed.
609  * \param symbols      Symbol table containing global scope symbols in the
610  *                     linked shader.
611  * \param instructions Instruction stream where new variable declarations
612  *                     should be added.
613  */
614 void
615 remap_variables(ir_instruction *inst, struct gl_shader *target,
616                 hash_table *temps)
617 {
618    class remap_visitor : public ir_hierarchical_visitor {
619    public:
620          remap_visitor(struct gl_shader *target,
621                     hash_table *temps)
622       {
623          this->target = target;
624          this->symbols = target->symbols;
625          this->instructions = target->ir;
626          this->temps = temps;
627       }
628
629       virtual ir_visitor_status visit(ir_dereference_variable *ir)
630       {
631          if (ir->var->mode == ir_var_temporary) {
632             ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
633
634             assert(var != NULL);
635             ir->var = var;
636             return visit_continue;
637          }
638
639          ir_variable *const existing =
640             this->symbols->get_variable(ir->var->name);
641          if (existing != NULL)
642             ir->var = existing;
643          else {
644             ir_variable *copy = ir->var->clone(this->target, NULL);
645
646             this->symbols->add_variable(copy);
647             this->instructions->push_head(copy);
648             ir->var = copy;
649          }
650
651          return visit_continue;
652       }
653
654    private:
655       struct gl_shader *target;
656       glsl_symbol_table *symbols;
657       exec_list *instructions;
658       hash_table *temps;
659    };
660
661    remap_visitor v(target, temps);
662
663    inst->accept(&v);
664 }
665
666
667 /**
668  * Move non-declarations from one instruction stream to another
669  *
670  * The intended usage pattern of this function is to pass the pointer to the
671  * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
672  * pointer) for \c last and \c false for \c make_copies on the first
673  * call.  Successive calls pass the return value of the previous call for
674  * \c last and \c true for \c make_copies.
675  *
676  * \param instructions Source instruction stream
677  * \param last         Instruction after which new instructions should be
678  *                     inserted in the target instruction stream
679  * \param make_copies  Flag selecting whether instructions in \c instructions
680  *                     should be copied (via \c ir_instruction::clone) into the
681  *                     target list or moved.
682  *
683  * \return
684  * The new "last" instruction in the target instruction stream.  This pointer
685  * is suitable for use as the \c last parameter of a later call to this
686  * function.
687  */
688 exec_node *
689 move_non_declarations(exec_list *instructions, exec_node *last,
690                       bool make_copies, gl_shader *target)
691 {
692    hash_table *temps = NULL;
693
694    if (make_copies)
695       temps = hash_table_ctor(0, hash_table_pointer_hash,
696                               hash_table_pointer_compare);
697
698    foreach_list_safe(node, instructions) {
699       ir_instruction *inst = (ir_instruction *) node;
700
701       if (inst->as_function())
702          continue;
703
704       ir_variable *var = inst->as_variable();
705       if ((var != NULL) && (var->mode != ir_var_temporary))
706          continue;
707
708       assert(inst->as_assignment()
709              || ((var != NULL) && (var->mode == ir_var_temporary)));
710
711       if (make_copies) {
712          inst = inst->clone(target, NULL);
713
714          if (var != NULL)
715             hash_table_insert(temps, inst, var);
716          else
717             remap_variables(inst, target, temps);
718       } else {
719          inst->remove();
720       }
721
722       last->insert_after(inst);
723       last = inst;
724    }
725
726    if (make_copies)
727       hash_table_dtor(temps);
728
729    return last;
730 }
731
732 /**
733  * Get the function signature for main from a shader
734  */
735 static ir_function_signature *
736 get_main_function_signature(gl_shader *sh)
737 {
738    ir_function *const f = sh->symbols->get_function("main");
739    if (f != NULL) {
740       exec_list void_parameters;
741
742       /* Look for the 'void main()' signature and ensure that it's defined.
743        * This keeps the linker from accidentally pick a shader that just
744        * contains a prototype for main.
745        *
746        * We don't have to check for multiple definitions of main (in multiple
747        * shaders) because that would have already been caught above.
748        */
749       ir_function_signature *sig = f->matching_signature(&void_parameters);
750       if ((sig != NULL) && sig->is_defined) {
751          return sig;
752       }
753    }
754
755    return NULL;
756 }
757
758
759 /**
760  * Combine a group of shaders for a single stage to generate a linked shader
761  *
762  * \note
763  * If this function is supplied a single shader, it is cloned, and the new
764  * shader is returned.
765  */
766 static struct gl_shader *
767 link_intrastage_shaders(void *mem_ctx,
768                         struct gl_context *ctx,
769                         struct gl_shader_program *prog,
770                         struct gl_shader **shader_list,
771                         unsigned num_shaders)
772 {
773    /* Check that global variables defined in multiple shaders are consistent.
774     */
775    if (!cross_validate_globals(prog, shader_list, num_shaders, false))
776       return NULL;
777
778    /* Check that there is only a single definition of each function signature
779     * across all shaders.
780     */
781    for (unsigned i = 0; i < (num_shaders - 1); i++) {
782       foreach_list(node, shader_list[i]->ir) {
783          ir_function *const f = ((ir_instruction *) node)->as_function();
784
785          if (f == NULL)
786             continue;
787
788          for (unsigned j = i + 1; j < num_shaders; j++) {
789             ir_function *const other =
790                shader_list[j]->symbols->get_function(f->name);
791
792             /* If the other shader has no function (and therefore no function
793              * signatures) with the same name, skip to the next shader.
794              */
795             if (other == NULL)
796                continue;
797
798             foreach_iter (exec_list_iterator, iter, *f) {
799                ir_function_signature *sig =
800                   (ir_function_signature *) iter.get();
801
802                if (!sig->is_defined || sig->is_builtin)
803                   continue;
804
805                ir_function_signature *other_sig =
806                   other->exact_matching_signature(& sig->parameters);
807
808                if ((other_sig != NULL) && other_sig->is_defined
809                    && !other_sig->is_builtin) {
810                   linker_error_printf(prog,
811                                       "function `%s' is multiply defined",
812                                       f->name);
813                   return NULL;
814                }
815             }
816          }
817       }
818    }
819
820    /* Find the shader that defines main, and make a clone of it.
821     *
822     * Starting with the clone, search for undefined references.  If one is
823     * found, find the shader that defines it.  Clone the reference and add
824     * it to the shader.  Repeat until there are no undefined references or
825     * until a reference cannot be resolved.
826     */
827    gl_shader *main = NULL;
828    for (unsigned i = 0; i < num_shaders; i++) {
829       if (get_main_function_signature(shader_list[i]) != NULL) {
830          main = shader_list[i];
831          break;
832       }
833    }
834
835    if (main == NULL) {
836       linker_error_printf(prog, "%s shader lacks `main'\n",
837                           (shader_list[0]->Type == GL_VERTEX_SHADER)
838                           ? "vertex" : "fragment");
839       return NULL;
840    }
841
842    gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
843    linked->ir = new(linked) exec_list;
844    clone_ir_list(mem_ctx, linked->ir, main->ir);
845
846    populate_symbol_table(linked);
847
848    /* The a pointer to the main function in the final linked shader (i.e., the
849     * copy of the original shader that contained the main function).
850     */
851    ir_function_signature *const main_sig = get_main_function_signature(linked);
852
853    /* Move any instructions other than variable declarations or function
854     * declarations into main.
855     */
856    exec_node *insertion_point =
857       move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
858                             linked);
859
860    for (unsigned i = 0; i < num_shaders; i++) {
861       if (shader_list[i] == main)
862          continue;
863
864       insertion_point = move_non_declarations(shader_list[i]->ir,
865                                               insertion_point, true, linked);
866    }
867
868    /* Resolve initializers for global variables in the linked shader.
869     */
870    unsigned num_linking_shaders = num_shaders;
871    for (unsigned i = 0; i < num_shaders; i++)
872       num_linking_shaders += shader_list[i]->num_builtins_to_link;
873
874    gl_shader **linking_shaders =
875       (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
876
877    memcpy(linking_shaders, shader_list,
878           sizeof(linking_shaders[0]) * num_shaders);
879
880    unsigned idx = num_shaders;
881    for (unsigned i = 0; i < num_shaders; i++) {
882       memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
883              sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
884       idx += shader_list[i]->num_builtins_to_link;
885    }
886
887    assert(idx == num_linking_shaders);
888
889    if (!link_function_calls(prog, linked, linking_shaders,
890                             num_linking_shaders)) {
891       ctx->Driver.DeleteShader(ctx, linked);
892       linked = NULL;
893    }
894
895    free(linking_shaders);
896
897    /* Make a pass over all global variables to ensure that arrays with
898     * unspecified sizes have a size specified.  The size is inferred from the
899     * max_array_access field.
900     */
901    if (linked != NULL) {
902       foreach_list(node, linked->ir) {
903          ir_variable *const var = ((ir_instruction *) node)->as_variable();
904
905          if (var == NULL)
906             continue;
907
908          if ((var->mode != ir_var_auto) && (var->mode != ir_var_temporary))
909             continue;
910
911          if (!var->type->is_array() || (var->type->length != 0))
912             continue;
913
914          const glsl_type *type =
915             glsl_type::get_array_instance(var->type->fields.array,
916                                           var->max_array_access);
917
918          assert(type != NULL);
919          var->type = type;
920       }
921    }
922
923    return linked;
924 }
925
926
927 struct uniform_node {
928    exec_node link;
929    struct gl_uniform *u;
930    unsigned slots;
931 };
932
933 /**
934  * Update the sizes of linked shader uniform arrays to the maximum
935  * array index used.
936  *
937  * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
938  *
939  *     If one or more elements of an array are active,
940  *     GetActiveUniform will return the name of the array in name,
941  *     subject to the restrictions listed above. The type of the array
942  *     is returned in type. The size parameter contains the highest
943  *     array element index used, plus one. The compiler or linker
944  *     determines the highest index used.  There will be only one
945  *     active uniform reported by the GL per uniform array.
946
947  */
948 static void
949 update_array_sizes(struct gl_shader_program *prog)
950 {
951    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
952          if (prog->_LinkedShaders[i] == NULL)
953             continue;
954
955       foreach_list(node, prog->_LinkedShaders[i]->ir) {
956          ir_variable *const var = ((ir_instruction *) node)->as_variable();
957
958          if ((var == NULL) || (var->mode != ir_var_uniform &&
959                                var->mode != ir_var_in &&
960                                var->mode != ir_var_out) ||
961              !var->type->is_array())
962             continue;
963
964          unsigned int size = var->max_array_access;
965          for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
966                if (prog->_LinkedShaders[j] == NULL)
967                   continue;
968
969             foreach_list(node2, prog->_LinkedShaders[j]->ir) {
970                ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
971                if (!other_var)
972                   continue;
973
974                if (strcmp(var->name, other_var->name) == 0 &&
975                    other_var->max_array_access > size) {
976                   size = other_var->max_array_access;
977                }
978             }
979          }
980
981          if (size + 1 != var->type->fields.array->length) {
982             var->type = glsl_type::get_array_instance(var->type->fields.array,
983                                                       size + 1);
984             /* FINISHME: We should update the types of array
985              * dereferences of this variable now.
986              */
987          }
988       }
989    }
990 }
991
992 static void
993 add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
994             const char *name, const glsl_type *type, GLenum shader_type,
995             unsigned *next_shader_pos, unsigned *total_uniforms)
996 {
997    if (type->is_record()) {
998       for (unsigned int i = 0; i < type->length; i++) {
999          const glsl_type *field_type = type->fields.structure[i].type;
1000          char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
1001                                             type->fields.structure[i].name);
1002
1003          add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
1004                      shader_type, next_shader_pos, total_uniforms);
1005       }
1006    } else {
1007       uniform_node *n = (uniform_node *) hash_table_find(ht, name);
1008       unsigned int vec4_slots;
1009       const glsl_type *array_elem_type = NULL;
1010
1011       if (type->is_array()) {
1012          array_elem_type = type->fields.array;
1013          /* Array of structures. */
1014          if (array_elem_type->is_record()) {
1015             for (unsigned int i = 0; i < type->length; i++) {
1016                char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
1017                add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
1018                            shader_type, next_shader_pos, total_uniforms);
1019             }
1020             return;
1021          }
1022       }
1023
1024       /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
1025        * vectors to vec4 slots.
1026        */
1027       if (type->is_array()) {
1028          if (array_elem_type->is_sampler())
1029             vec4_slots = type->length;
1030          else
1031             vec4_slots = type->length * array_elem_type->matrix_columns;
1032       } else if (type->is_sampler()) {
1033          vec4_slots = 1;
1034       } else {
1035          vec4_slots = type->matrix_columns;
1036       }
1037
1038       if (n == NULL) {
1039          n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
1040          n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
1041          n->slots = vec4_slots;
1042
1043          n->u->Name = strdup(name);
1044          n->u->Type = type;
1045          n->u->VertPos = -1;
1046          n->u->FragPos = -1;
1047          n->u->GeomPos = -1;
1048          (*total_uniforms)++;
1049
1050          hash_table_insert(ht, n, name);
1051          uniforms->push_tail(& n->link);
1052       }
1053
1054       switch (shader_type) {
1055       case GL_VERTEX_SHADER:
1056          n->u->VertPos = *next_shader_pos;
1057          break;
1058       case GL_FRAGMENT_SHADER:
1059          n->u->FragPos = *next_shader_pos;
1060          break;
1061       case GL_GEOMETRY_SHADER:
1062          n->u->GeomPos = *next_shader_pos;
1063          break;
1064       }
1065
1066       (*next_shader_pos) += vec4_slots;
1067    }
1068 }
1069
1070 void
1071 assign_uniform_locations(struct gl_shader_program *prog)
1072 {
1073    /* */
1074    exec_list uniforms;
1075    unsigned total_uniforms = 0;
1076    hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
1077                                     hash_table_string_compare);
1078    void *mem_ctx = talloc_new(NULL);
1079
1080    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1081       if (prog->_LinkedShaders[i] == NULL)
1082          continue;
1083
1084       unsigned next_position = 0;
1085
1086       foreach_list(node, prog->_LinkedShaders[i]->ir) {
1087          ir_variable *const var = ((ir_instruction *) node)->as_variable();
1088
1089          if ((var == NULL) || (var->mode != ir_var_uniform))
1090             continue;
1091
1092          if (strncmp(var->name, "gl_", 3) == 0) {
1093             /* At the moment, we don't allocate uniform locations for
1094              * builtin uniforms.  It's permitted by spec, and we'll
1095              * likely switch to doing that at some point, but not yet.
1096              */
1097             continue;
1098          }
1099
1100          var->location = next_position;
1101          add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
1102                      prog->_LinkedShaders[i]->Type,
1103                      &next_position, &total_uniforms);
1104       }
1105    }
1106
1107    talloc_free(mem_ctx);
1108
1109    gl_uniform_list *ul = (gl_uniform_list *)
1110       calloc(1, sizeof(gl_uniform_list));
1111
1112    ul->Size = total_uniforms;
1113    ul->NumUniforms = total_uniforms;
1114    ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
1115
1116    unsigned idx = 0;
1117    uniform_node *next;
1118    for (uniform_node *node = (uniform_node *) uniforms.head
1119            ; node->link.next != NULL
1120            ; node = next) {
1121       next = (uniform_node *) node->link.next;
1122
1123       node->link.remove();
1124       memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
1125       idx++;
1126
1127       free(node->u);
1128       free(node);
1129    }
1130
1131    hash_table_dtor(ht);
1132
1133    prog->Uniforms = ul;
1134 }
1135
1136
1137 /**
1138  * Find a contiguous set of available bits in a bitmask
1139  *
1140  * \param used_mask     Bits representing used (1) and unused (0) locations
1141  * \param needed_count  Number of contiguous bits needed.
1142  *
1143  * \return
1144  * Base location of the available bits on success or -1 on failure.
1145  */
1146 int
1147 find_available_slots(unsigned used_mask, unsigned needed_count)
1148 {
1149    unsigned needed_mask = (1 << needed_count) - 1;
1150    const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1151
1152    /* The comparison to 32 is redundant, but without it GCC emits "warning:
1153     * cannot optimize possibly infinite loops" for the loop below.
1154     */
1155    if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1156       return -1;
1157
1158    for (int i = 0; i <= max_bit_to_test; i++) {
1159       if ((needed_mask & ~used_mask) == needed_mask)
1160          return i;
1161
1162       needed_mask <<= 1;
1163    }
1164
1165    return -1;
1166 }
1167
1168
1169 bool
1170 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
1171 {
1172    /* Mark invalid attribute locations as being used.
1173     */
1174    unsigned used_locations = (max_attribute_index >= 32)
1175       ? ~0 : ~((1 << max_attribute_index) - 1);
1176
1177    gl_shader *const sh = prog->_LinkedShaders[0];
1178    assert(sh->Type == GL_VERTEX_SHADER);
1179
1180    /* Operate in a total of four passes.
1181     *
1182     * 1. Invalidate the location assignments for all vertex shader inputs.
1183     *
1184     * 2. Assign locations for inputs that have user-defined (via
1185     *    glBindVertexAttribLocation) locatoins.
1186     *
1187     * 3. Sort the attributes without assigned locations by number of slots
1188     *    required in decreasing order.  Fragmentation caused by attribute
1189     *    locations assigned by the application may prevent large attributes
1190     *    from having enough contiguous space.
1191     *
1192     * 4. Assign locations to any inputs without assigned locations.
1193     */
1194
1195    invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1196
1197    if (prog->Attributes != NULL) {
1198       for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
1199          ir_variable *const var =
1200             sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
1201
1202          /* Note: attributes that occupy multiple slots, such as arrays or
1203           * matrices, may appear in the attrib array multiple times.
1204           */
1205          if ((var == NULL) || (var->location != -1))
1206             continue;
1207
1208          /* From page 61 of the OpenGL 4.0 spec:
1209           *
1210           *     "LinkProgram will fail if the attribute bindings assigned by
1211           *     BindAttribLocation do not leave not enough space to assign a
1212           *     location for an active matrix attribute or an active attribute
1213           *     array, both of which require multiple contiguous generic
1214           *     attributes."
1215           *
1216           * Previous versions of the spec contain similar language but omit the
1217           * bit about attribute arrays.
1218           *
1219           * Page 61 of the OpenGL 4.0 spec also says:
1220           *
1221           *     "It is possible for an application to bind more than one
1222           *     attribute name to the same location. This is referred to as
1223           *     aliasing. This will only work if only one of the aliased
1224           *     attributes is active in the executable program, or if no path
1225           *     through the shader consumes more than one attribute of a set
1226           *     of attributes aliased to the same location. A link error can
1227           *     occur if the linker determines that every path through the
1228           *     shader consumes multiple aliased attributes, but
1229           *     implementations are not required to generate an error in this
1230           *     case."
1231           *
1232           * These two paragraphs are either somewhat contradictory, or I don't
1233           * fully understand one or both of them.
1234           */
1235          /* FINISHME: The code as currently written does not support attribute
1236           * FINISHME: location aliasing (see comment above).
1237           */
1238          const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
1239          const unsigned slots = count_attribute_slots(var->type);
1240
1241          /* Mask representing the contiguous slots that will be used by this
1242           * attribute.
1243           */
1244          const unsigned use_mask = (1 << slots) - 1;
1245
1246          /* Generate a link error if the set of bits requested for this
1247           * attribute overlaps any previously allocated bits.
1248           */
1249          if ((~(use_mask << attr) & used_locations) != used_locations) {
1250             linker_error_printf(prog,
1251                                 "insufficient contiguous attribute locations "
1252                                 "available for vertex shader input `%s'",
1253                                 var->name);
1254             return false;
1255          }
1256
1257          var->location = VERT_ATTRIB_GENERIC0 + attr;
1258          used_locations |= (use_mask << attr);
1259       }
1260    }
1261
1262    /* Temporary storage for the set of attributes that need locations assigned.
1263     */
1264    struct temp_attr {
1265       unsigned slots;
1266       ir_variable *var;
1267
1268       /* Used below in the call to qsort. */
1269       static int compare(const void *a, const void *b)
1270       {
1271          const temp_attr *const l = (const temp_attr *) a;
1272          const temp_attr *const r = (const temp_attr *) b;
1273
1274          /* Reversed because we want a descending order sort below. */
1275          return r->slots - l->slots;
1276       }
1277    } to_assign[16];
1278
1279    unsigned num_attr = 0;
1280
1281    foreach_list(node, sh->ir) {
1282       ir_variable *const var = ((ir_instruction *) node)->as_variable();
1283
1284       if ((var == NULL) || (var->mode != ir_var_in))
1285          continue;
1286
1287       if (var->explicit_location) {
1288          const unsigned slots = count_attribute_slots(var->type);
1289          const unsigned use_mask = (1 << slots) - 1;
1290          const int attr = var->location - VERT_ATTRIB_GENERIC0;
1291
1292          if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
1293              || (var->location < 0)) {
1294             linker_error_printf(prog,
1295                                 "invalid explicit location %d specified for "
1296                                 "`%s'\n",
1297                                 (var->location < 0) ? var->location : attr,
1298                                 var->name);
1299             return false;
1300          } else if (var->location >= VERT_ATTRIB_GENERIC0) {
1301             used_locations |= (use_mask << attr);
1302          }
1303       }
1304
1305       /* The location was explicitly assigned, nothing to do here.
1306        */
1307       if (var->location != -1)
1308          continue;
1309
1310       to_assign[num_attr].slots = count_attribute_slots(var->type);
1311       to_assign[num_attr].var = var;
1312       num_attr++;
1313    }
1314
1315    /* If all of the attributes were assigned locations by the application (or
1316     * are built-in attributes with fixed locations), return early.  This should
1317     * be the common case.
1318     */
1319    if (num_attr == 0)
1320       return true;
1321
1322    qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1323
1324    /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS.  It can only
1325     * be explicitly assigned by via glBindAttribLocation.  Mark it as reserved
1326     * to prevent it from being automatically allocated below.
1327     */
1328    find_deref_visitor find("gl_Vertex");
1329    find.run(sh->ir);
1330    if (find.variable_found())
1331       used_locations |= (1 << 0);
1332
1333    for (unsigned i = 0; i < num_attr; i++) {
1334       /* Mask representing the contiguous slots that will be used by this
1335        * attribute.
1336        */
1337       const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1338
1339       int location = find_available_slots(used_locations, to_assign[i].slots);
1340
1341       if (location < 0) {
1342          linker_error_printf(prog,
1343                              "insufficient contiguous attribute locations "
1344                              "available for vertex shader input `%s'",
1345                              to_assign[i].var->name);
1346          return false;
1347       }
1348
1349       to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1350       used_locations |= (use_mask << location);
1351    }
1352
1353    return true;
1354 }
1355
1356
1357 /**
1358  * Demote shader inputs and outputs that are not used in other stages
1359  */
1360 void
1361 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1362 {
1363    foreach_list(node, sh->ir) {
1364       ir_variable *const var = ((ir_instruction *) node)->as_variable();
1365
1366       if ((var == NULL) || (var->mode != int(mode)))
1367          continue;
1368
1369       /* A shader 'in' or 'out' variable is only really an input or output if
1370        * its value is used by other shader stages.  This will cause the variable
1371        * to have a location assigned.
1372        */
1373       if (var->location == -1) {
1374          var->mode = ir_var_auto;
1375       }
1376    }
1377 }
1378
1379
1380 void
1381 assign_varying_locations(struct gl_shader_program *prog,
1382                          gl_shader *producer, gl_shader *consumer)
1383 {
1384    /* FINISHME: Set dynamically when geometry shader support is added. */
1385    unsigned output_index = VERT_RESULT_VAR0;
1386    unsigned input_index = FRAG_ATTRIB_VAR0;
1387
1388    /* Operate in a total of three passes.
1389     *
1390     * 1. Assign locations for any matching inputs and outputs.
1391     *
1392     * 2. Mark output variables in the producer that do not have locations as
1393     *    not being outputs.  This lets the optimizer eliminate them.
1394     *
1395     * 3. Mark input variables in the consumer that do not have locations as
1396     *    not being inputs.  This lets the optimizer eliminate them.
1397     */
1398
1399    invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1400    invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1401
1402    foreach_list(node, producer->ir) {
1403       ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1404
1405       if ((output_var == NULL) || (output_var->mode != ir_var_out)
1406           || (output_var->location != -1))
1407          continue;
1408
1409       ir_variable *const input_var =
1410          consumer->symbols->get_variable(output_var->name);
1411
1412       if ((input_var == NULL) || (input_var->mode != ir_var_in))
1413          continue;
1414
1415       assert(input_var->location == -1);
1416
1417       output_var->location = output_index;
1418       input_var->location = input_index;
1419
1420       /* FINISHME: Support for "varying" records in GLSL 1.50. */
1421       assert(!output_var->type->is_record());
1422
1423       if (output_var->type->is_array()) {
1424          const unsigned slots = output_var->type->length
1425             * output_var->type->fields.array->matrix_columns;
1426
1427          output_index += slots;
1428          input_index += slots;
1429       } else {
1430          const unsigned slots = output_var->type->matrix_columns;
1431
1432          output_index += slots;
1433          input_index += slots;
1434       }
1435    }
1436
1437    foreach_list(node, consumer->ir) {
1438       ir_variable *const var = ((ir_instruction *) node)->as_variable();
1439
1440       if ((var == NULL) || (var->mode != ir_var_in))
1441          continue;
1442
1443       if (var->location == -1) {
1444          if (prog->Version <= 120) {
1445             /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1446              *
1447              *     Only those varying variables used (i.e. read) in
1448              *     the fragment shader executable must be written to
1449              *     by the vertex shader executable; declaring
1450              *     superfluous varying variables in a vertex shader is
1451              *     permissible.
1452              *
1453              * We interpret this text as meaning that the VS must
1454              * write the variable for the FS to read it.  See
1455              * "glsl1-varying read but not written" in piglit.
1456              */
1457
1458             linker_error_printf(prog, "fragment shader varying %s not written "
1459                                 "by vertex shader\n.", var->name);
1460             prog->LinkStatus = false;
1461          }
1462
1463          /* An 'in' variable is only really a shader input if its
1464           * value is written by the previous stage.
1465           */
1466          var->mode = ir_var_auto;
1467       }
1468    }
1469 }
1470
1471
1472 void
1473 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
1474 {
1475    void *mem_ctx = talloc_init("temporary linker context");
1476
1477    prog->LinkStatus = false;
1478    prog->Validated = false;
1479    prog->_Used = false;
1480
1481    if (prog->InfoLog != NULL)
1482       talloc_free(prog->InfoLog);
1483
1484    prog->InfoLog = talloc_strdup(NULL, "");
1485
1486    /* Separate the shaders into groups based on their type.
1487     */
1488    struct gl_shader **vert_shader_list;
1489    unsigned num_vert_shaders = 0;
1490    struct gl_shader **frag_shader_list;
1491    unsigned num_frag_shaders = 0;
1492
1493    vert_shader_list = (struct gl_shader **)
1494       calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1495    frag_shader_list =  &vert_shader_list[prog->NumShaders];
1496
1497    unsigned min_version = UINT_MAX;
1498    unsigned max_version = 0;
1499    for (unsigned i = 0; i < prog->NumShaders; i++) {
1500       min_version = MIN2(min_version, prog->Shaders[i]->Version);
1501       max_version = MAX2(max_version, prog->Shaders[i]->Version);
1502
1503       switch (prog->Shaders[i]->Type) {
1504       case GL_VERTEX_SHADER:
1505          vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1506          num_vert_shaders++;
1507          break;
1508       case GL_FRAGMENT_SHADER:
1509          frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1510          num_frag_shaders++;
1511          break;
1512       case GL_GEOMETRY_SHADER:
1513          /* FINISHME: Support geometry shaders. */
1514          assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1515          break;
1516       }
1517    }
1518
1519    /* Previous to GLSL version 1.30, different compilation units could mix and
1520     * match shading language versions.  With GLSL 1.30 and later, the versions
1521     * of all shaders must match.
1522     */
1523    assert(min_version >= 100);
1524    assert(max_version <= 130);
1525    if ((max_version >= 130 || min_version == 100)
1526        && min_version != max_version) {
1527       linker_error_printf(prog, "all shaders must use same shading "
1528                           "language version\n");
1529       goto done;
1530    }
1531
1532    prog->Version = max_version;
1533
1534    for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
1535       if (prog->_LinkedShaders[i] != NULL)
1536          ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1537
1538       prog->_LinkedShaders[i] = NULL;
1539    }
1540
1541    /* Link all shaders for a particular stage and validate the result.
1542     */
1543    if (num_vert_shaders > 0) {
1544       gl_shader *const sh =
1545          link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
1546                                  num_vert_shaders);
1547
1548       if (sh == NULL)
1549          goto done;
1550
1551       if (!validate_vertex_shader_executable(prog, sh))
1552          goto done;
1553
1554       _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
1555                              sh);
1556    }
1557
1558    if (num_frag_shaders > 0) {
1559       gl_shader *const sh =
1560          link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
1561                                  num_frag_shaders);
1562
1563       if (sh == NULL)
1564          goto done;
1565
1566       if (!validate_fragment_shader_executable(prog, sh))
1567          goto done;
1568
1569       _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1570                              sh);
1571    }
1572
1573    /* Here begins the inter-stage linking phase.  Some initial validation is
1574     * performed, then locations are assigned for uniforms, attributes, and
1575     * varyings.
1576     */
1577    if (cross_validate_uniforms(prog)) {
1578       unsigned prev;
1579
1580       for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1581          if (prog->_LinkedShaders[prev] != NULL)
1582             break;
1583       }
1584
1585       /* Validate the inputs of each stage with the output of the preceeding
1586        * stage.
1587        */
1588       for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1589          if (prog->_LinkedShaders[i] == NULL)
1590             continue;
1591
1592          if (!cross_validate_outputs_to_inputs(prog,
1593                                                prog->_LinkedShaders[prev],
1594                                                prog->_LinkedShaders[i]))
1595             goto done;
1596
1597          prev = i;
1598       }
1599
1600       prog->LinkStatus = true;
1601    }
1602
1603    /* Do common optimization before assigning storage for attributes,
1604     * uniforms, and varyings.  Later optimization could possibly make
1605     * some of that unused.
1606     */
1607    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1608       if (prog->_LinkedShaders[i] == NULL)
1609          continue;
1610
1611       while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
1612          ;
1613    }
1614
1615    update_array_sizes(prog);
1616
1617    assign_uniform_locations(prog);
1618
1619    if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1620       /* FINISHME: The value of the max_attribute_index parameter is
1621        * FINISHME: implementation dependent based on the value of
1622        * FINISHME: GL_MAX_VERTEX_ATTRIBS.  GL_MAX_VERTEX_ATTRIBS must be
1623        * FINISHME: at least 16, so hardcode 16 for now.
1624        */
1625       if (!assign_attribute_locations(prog, 16)) {
1626          prog->LinkStatus = false;
1627          goto done;
1628       }
1629    }
1630
1631    unsigned prev;
1632    for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1633       if (prog->_LinkedShaders[prev] != NULL)
1634          break;
1635    }
1636
1637    for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1638       if (prog->_LinkedShaders[i] == NULL)
1639          continue;
1640
1641       assign_varying_locations(prog,
1642                                prog->_LinkedShaders[prev],
1643                                prog->_LinkedShaders[i]);
1644       prev = i;
1645    }
1646
1647    if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1648       demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
1649                                        ir_var_out);
1650    }
1651
1652    if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
1653       gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
1654
1655       demote_shader_inputs_and_outputs(sh, ir_var_in);
1656       demote_shader_inputs_and_outputs(sh, ir_var_inout);
1657       demote_shader_inputs_and_outputs(sh, ir_var_out);
1658    }
1659
1660    if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
1661       gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1662
1663       demote_shader_inputs_and_outputs(sh, ir_var_in);
1664    }
1665
1666    /* FINISHME: Assign fragment shader output locations. */
1667
1668 done:
1669    free(vert_shader_list);
1670
1671    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1672       if (prog->_LinkedShaders[i] == NULL)
1673          continue;
1674
1675       /* Retain any live IR, but trash the rest. */
1676       reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
1677    }
1678
1679    talloc_free(mem_ctx);
1680 }