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