glsl: implement ARB_transform_feedback3 in the linker
[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->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       if (ir->return_deref != NULL) {
121          ir_variable *const var = ir->return_deref->variable_referenced();
122
123          if (strcmp(name, var->name) == 0) {
124             found = true;
125             return visit_stop;
126          }
127       }
128
129       return visit_continue_with_parent;
130    }
131
132    bool variable_found()
133    {
134       return found;
135    }
136
137 private:
138    const char *name;       /**< Find writes to a variable with this name. */
139    bool found;             /**< Was a write to the variable found? */
140 };
141
142
143 /**
144  * Visitor that determines whether or not a variable is ever read.
145  */
146 class find_deref_visitor : public ir_hierarchical_visitor {
147 public:
148    find_deref_visitor(const char *name)
149       : name(name), found(false)
150    {
151       /* empty */
152    }
153
154    virtual ir_visitor_status visit(ir_dereference_variable *ir)
155    {
156       if (strcmp(this->name, ir->var->name) == 0) {
157          this->found = true;
158          return visit_stop;
159       }
160
161       return visit_continue;
162    }
163
164    bool variable_found() const
165    {
166       return this->found;
167    }
168
169 private:
170    const char *name;       /**< Find writes to a variable with this name. */
171    bool found;             /**< Was a write to the variable found? */
172 };
173
174
175 void
176 linker_error(gl_shader_program *prog, const char *fmt, ...)
177 {
178    va_list ap;
179
180    ralloc_strcat(&prog->InfoLog, "error: ");
181    va_start(ap, fmt);
182    ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
183    va_end(ap);
184
185    prog->LinkStatus = false;
186 }
187
188
189 void
190 linker_warning(gl_shader_program *prog, const char *fmt, ...)
191 {
192    va_list ap;
193
194    ralloc_strcat(&prog->InfoLog, "error: ");
195    va_start(ap, fmt);
196    ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
197    va_end(ap);
198
199 }
200
201
202 void
203 link_invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
204                                    int generic_base)
205 {
206    foreach_list(node, sh->ir) {
207       ir_variable *const var = ((ir_instruction *) node)->as_variable();
208
209       if ((var == NULL) || (var->mode != (unsigned) mode))
210          continue;
211
212       /* Only assign locations for generic attributes / varyings / etc.
213        */
214       if ((var->location >= generic_base) && !var->explicit_location)
215           var->location = -1;
216    }
217 }
218
219
220 /**
221  * Determine the number of attribute slots required for a particular type
222  *
223  * This code is here because it implements the language rules of a specific
224  * GLSL version.  Since it's a property of the language and not a property of
225  * types in general, it doesn't really belong in glsl_type.
226  */
227 unsigned
228 count_attribute_slots(const glsl_type *t)
229 {
230    /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
231     *
232     *     "A scalar input counts the same amount against this limit as a vec4,
233     *     so applications may want to consider packing groups of four
234     *     unrelated float inputs together into a vector to better utilize the
235     *     capabilities of the underlying hardware. A matrix input will use up
236     *     multiple locations.  The number of locations used will equal the
237     *     number of columns in the matrix."
238     *
239     * The spec does not explicitly say how arrays are counted.  However, it
240     * should be safe to assume the total number of slots consumed by an array
241     * is the number of entries in the array multiplied by the number of slots
242     * consumed by a single element of the array.
243     */
244
245    if (t->is_array())
246       return t->array_size() * count_attribute_slots(t->element_type());
247
248    if (t->is_matrix())
249       return t->matrix_columns;
250
251    return 1;
252 }
253
254
255 /**
256  * Verify that a vertex shader executable meets all semantic requirements.
257  *
258  * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
259  * as a side effect.
260  *
261  * \param shader  Vertex shader executable to be verified
262  */
263 bool
264 validate_vertex_shader_executable(struct gl_shader_program *prog,
265                                   struct gl_shader *shader)
266 {
267    if (shader == NULL)
268       return true;
269
270    /* From the GLSL 1.10 spec, page 48:
271     *
272     *     "The variable gl_Position is available only in the vertex
273     *      language and is intended for writing the homogeneous vertex
274     *      position. All executions of a well-formed vertex shader
275     *      executable must write a value into this variable. [...] The
276     *      variable gl_Position is available only in the vertex
277     *      language and is intended for writing the homogeneous vertex
278     *      position. All executions of a well-formed vertex shader
279     *      executable must write a value into this variable."
280     *
281     * while in GLSL 1.40 this text is changed to:
282     *
283     *     "The variable gl_Position is available only in the vertex
284     *      language and is intended for writing the homogeneous vertex
285     *      position. It can be written at any time during shader
286     *      execution. It may also be read back by a vertex shader
287     *      after being written. This value will be used by primitive
288     *      assembly, clipping, culling, and other fixed functionality
289     *      operations, if present, that operate on primitives after
290     *      vertex processing has occurred. Its value is undefined if
291     *      the vertex shader executable does not write gl_Position."
292     */
293    if (prog->Version < 140) {
294       find_assignment_visitor find("gl_Position");
295       find.run(shader->ir);
296       if (!find.variable_found()) {
297          linker_error(prog, "vertex shader does not write to `gl_Position'\n");
298          return false;
299       }
300    }
301
302    prog->Vert.ClipDistanceArraySize = 0;
303
304    if (prog->Version >= 130) {
305       /* From section 7.1 (Vertex Shader Special Variables) of the
306        * GLSL 1.30 spec:
307        *
308        *   "It is an error for a shader to statically write both
309        *   gl_ClipVertex and gl_ClipDistance."
310        */
311       find_assignment_visitor clip_vertex("gl_ClipVertex");
312       find_assignment_visitor clip_distance("gl_ClipDistance");
313
314       clip_vertex.run(shader->ir);
315       clip_distance.run(shader->ir);
316       if (clip_vertex.variable_found() && clip_distance.variable_found()) {
317          linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
318                       "and `gl_ClipDistance'\n");
319          return false;
320       }
321       prog->Vert.UsesClipDistance = clip_distance.variable_found();
322       ir_variable *clip_distance_var =
323          shader->symbols->get_variable("gl_ClipDistance");
324       if (clip_distance_var)
325          prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
326    }
327
328    return true;
329 }
330
331
332 /**
333  * Verify that a fragment shader executable meets all semantic requirements
334  *
335  * \param shader  Fragment shader executable to be verified
336  */
337 bool
338 validate_fragment_shader_executable(struct gl_shader_program *prog,
339                                     struct gl_shader *shader)
340 {
341    if (shader == NULL)
342       return true;
343
344    find_assignment_visitor frag_color("gl_FragColor");
345    find_assignment_visitor frag_data("gl_FragData");
346
347    frag_color.run(shader->ir);
348    frag_data.run(shader->ir);
349
350    if (frag_color.variable_found() && frag_data.variable_found()) {
351       linker_error(prog,  "fragment shader writes to both "
352                    "`gl_FragColor' and `gl_FragData'\n");
353       return false;
354    }
355
356    return true;
357 }
358
359
360 /**
361  * Generate a string describing the mode of a variable
362  */
363 static const char *
364 mode_string(const ir_variable *var)
365 {
366    switch (var->mode) {
367    case ir_var_auto:
368       return (var->read_only) ? "global constant" : "global variable";
369
370    case ir_var_uniform: return "uniform";
371    case ir_var_in:      return "shader input";
372    case ir_var_out:     return "shader output";
373    case ir_var_inout:   return "shader inout";
374
375    case ir_var_const_in:
376    case ir_var_temporary:
377    default:
378       assert(!"Should not get here.");
379       return "invalid variable";
380    }
381 }
382
383
384 /**
385  * Perform validation of global variables used across multiple shaders
386  */
387 bool
388 cross_validate_globals(struct gl_shader_program *prog,
389                        struct gl_shader **shader_list,
390                        unsigned num_shaders,
391                        bool uniforms_only)
392 {
393    /* Examine all of the uniforms in all of the shaders and cross validate
394     * them.
395     */
396    glsl_symbol_table variables;
397    for (unsigned i = 0; i < num_shaders; i++) {
398       if (shader_list[i] == NULL)
399          continue;
400
401       foreach_list(node, shader_list[i]->ir) {
402          ir_variable *const var = ((ir_instruction *) node)->as_variable();
403
404          if (var == NULL)
405             continue;
406
407          if (uniforms_only && (var->mode != ir_var_uniform))
408             continue;
409
410          /* Don't cross validate temporaries that are at global scope.  These
411           * will eventually get pulled into the shaders 'main'.
412           */
413          if (var->mode == ir_var_temporary)
414             continue;
415
416          /* If a global with this name has already been seen, verify that the
417           * new instance has the same type.  In addition, if the globals have
418           * initializers, the values of the initializers must be the same.
419           */
420          ir_variable *const existing = variables.get_variable(var->name);
421          if (existing != NULL) {
422             if (var->type != existing->type) {
423                /* Consider the types to be "the same" if both types are arrays
424                 * of the same type and one of the arrays is implicitly sized.
425                 * In addition, set the type of the linked variable to the
426                 * explicitly sized array.
427                 */
428                if (var->type->is_array()
429                    && existing->type->is_array()
430                    && (var->type->fields.array == existing->type->fields.array)
431                    && ((var->type->length == 0)
432                        || (existing->type->length == 0))) {
433                   if (var->type->length != 0) {
434                      existing->type = var->type;
435                   }
436                } else {
437                   linker_error(prog, "%s `%s' declared as type "
438                                "`%s' and type `%s'\n",
439                                mode_string(var),
440                                var->name, var->type->name,
441                                existing->type->name);
442                   return false;
443                }
444             }
445
446             if (var->explicit_location) {
447                if (existing->explicit_location
448                    && (var->location != existing->location)) {
449                      linker_error(prog, "explicit locations for %s "
450                                   "`%s' have differing values\n",
451                                   mode_string(var), var->name);
452                      return false;
453                }
454
455                existing->location = var->location;
456                existing->explicit_location = true;
457             }
458
459             /* Validate layout qualifiers for gl_FragDepth.
460              *
461              * From the AMD/ARB_conservative_depth specs:
462              *
463              *    "If gl_FragDepth is redeclared in any fragment shader in a
464              *    program, it must be redeclared in all fragment shaders in
465              *    that program that have static assignments to
466              *    gl_FragDepth. All redeclarations of gl_FragDepth in all
467              *    fragment shaders in a single program must have the same set
468              *    of qualifiers."
469              */
470             if (strcmp(var->name, "gl_FragDepth") == 0) {
471                bool layout_declared = var->depth_layout != ir_depth_layout_none;
472                bool layout_differs =
473                   var->depth_layout != existing->depth_layout;
474
475                if (layout_declared && layout_differs) {
476                   linker_error(prog,
477                                "All redeclarations of gl_FragDepth in all "
478                                "fragment shaders in a single program must have "
479                                "the same set of qualifiers.");
480                }
481
482                if (var->used && layout_differs) {
483                   linker_error(prog,
484                                "If gl_FragDepth is redeclared with a layout "
485                                "qualifier in any fragment shader, it must be "
486                                "redeclared with the same layout qualifier in "
487                                "all fragment shaders that have assignments to "
488                                "gl_FragDepth");
489                }
490             }
491
492             /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
493              *
494              *     "If a shared global has multiple initializers, the
495              *     initializers must all be constant expressions, and they
496              *     must all have the same value. Otherwise, a link error will
497              *     result. (A shared global having only one initializer does
498              *     not require that initializer to be a constant expression.)"
499              *
500              * Previous to 4.20 the GLSL spec simply said that initializers
501              * must have the same value.  In this case of non-constant
502              * initializers, this was impossible to determine.  As a result,
503              * no vendor actually implemented that behavior.  The 4.20
504              * behavior matches the implemented behavior of at least one other
505              * vendor, so we'll implement that for all GLSL versions.
506              */
507             if (var->constant_initializer != NULL) {
508                if (existing->constant_initializer != NULL) {
509                   if (!var->constant_initializer->has_value(existing->constant_initializer)) {
510                      linker_error(prog, "initializers for %s "
511                                   "`%s' have differing values\n",
512                                   mode_string(var), var->name);
513                      return false;
514                   }
515                } else {
516                   /* If the first-seen instance of a particular uniform did not
517                    * have an initializer but a later instance does, copy the
518                    * initializer to the version stored in the symbol table.
519                    */
520                   /* FINISHME: This is wrong.  The constant_value field should
521                    * FINISHME: not be modified!  Imagine a case where a shader
522                    * FINISHME: without an initializer is linked in two different
523                    * FINISHME: programs with shaders that have differing
524                    * FINISHME: initializers.  Linking with the first will
525                    * FINISHME: modify the shader, and linking with the second
526                    * FINISHME: will fail.
527                    */
528                   existing->constant_initializer =
529                      var->constant_initializer->clone(ralloc_parent(existing),
530                                                       NULL);
531                }
532             }
533
534             if (var->has_initializer) {
535                if (existing->has_initializer
536                    && (var->constant_initializer == NULL
537                        || existing->constant_initializer == NULL)) {
538                   linker_error(prog,
539                                "shared global variable `%s' has multiple "
540                                "non-constant initializers.\n",
541                                var->name);
542                   return false;
543                }
544
545                /* Some instance had an initializer, so keep track of that.  In
546                 * this location, all sorts of initializers (constant or
547                 * otherwise) will propagate the existence to the variable
548                 * stored in the symbol table.
549                 */
550                existing->has_initializer = true;
551             }
552
553             if (existing->invariant != var->invariant) {
554                linker_error(prog, "declarations for %s `%s' have "
555                             "mismatching invariant qualifiers\n",
556                             mode_string(var), var->name);
557                return false;
558             }
559             if (existing->centroid != var->centroid) {
560                linker_error(prog, "declarations for %s `%s' have "
561                             "mismatching centroid qualifiers\n",
562                             mode_string(var), var->name);
563                return false;
564             }
565          } else
566             variables.add_variable(var);
567       }
568    }
569
570    return true;
571 }
572
573
574 /**
575  * Perform validation of uniforms used across multiple shader stages
576  */
577 bool
578 cross_validate_uniforms(struct gl_shader_program *prog)
579 {
580    return cross_validate_globals(prog, prog->_LinkedShaders,
581                                  MESA_SHADER_TYPES, true);
582 }
583
584
585 /**
586  * Validate that outputs from one stage match inputs of another
587  */
588 bool
589 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
590                                  gl_shader *producer, gl_shader *consumer)
591 {
592    glsl_symbol_table parameters;
593    /* FINISHME: Figure these out dynamically. */
594    const char *const producer_stage = "vertex";
595    const char *const consumer_stage = "fragment";
596
597    /* Find all shader outputs in the "producer" stage.
598     */
599    foreach_list(node, producer->ir) {
600       ir_variable *const var = ((ir_instruction *) node)->as_variable();
601
602       /* FINISHME: For geometry shaders, this should also look for inout
603        * FINISHME: variables.
604        */
605       if ((var == NULL) || (var->mode != ir_var_out))
606          continue;
607
608       parameters.add_variable(var);
609    }
610
611
612    /* Find all shader inputs in the "consumer" stage.  Any variables that have
613     * matching outputs already in the symbol table must have the same type and
614     * qualifiers.
615     */
616    foreach_list(node, consumer->ir) {
617       ir_variable *const input = ((ir_instruction *) node)->as_variable();
618
619       /* FINISHME: For geometry shaders, this should also look for inout
620        * FINISHME: variables.
621        */
622       if ((input == NULL) || (input->mode != ir_var_in))
623          continue;
624
625       ir_variable *const output = parameters.get_variable(input->name);
626       if (output != NULL) {
627          /* Check that the types match between stages.
628           */
629          if (input->type != output->type) {
630             /* There is a bit of a special case for gl_TexCoord.  This
631              * built-in is unsized by default.  Applications that variable
632              * access it must redeclare it with a size.  There is some
633              * language in the GLSL spec that implies the fragment shader
634              * and vertex shader do not have to agree on this size.  Other
635              * driver behave this way, and one or two applications seem to
636              * rely on it.
637              *
638              * Neither declaration needs to be modified here because the array
639              * sizes are fixed later when update_array_sizes is called.
640              *
641              * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
642              *
643              *     "Unlike user-defined varying variables, the built-in
644              *     varying variables don't have a strict one-to-one
645              *     correspondence between the vertex language and the
646              *     fragment language."
647              */
648             if (!output->type->is_array()
649                 || (strncmp("gl_", output->name, 3) != 0)) {
650                linker_error(prog,
651                             "%s shader output `%s' declared as type `%s', "
652                             "but %s shader input declared as type `%s'\n",
653                             producer_stage, output->name,
654                             output->type->name,
655                             consumer_stage, input->type->name);
656                return false;
657             }
658          }
659
660          /* Check that all of the qualifiers match between stages.
661           */
662          if (input->centroid != output->centroid) {
663             linker_error(prog,
664                          "%s shader output `%s' %s centroid qualifier, "
665                          "but %s shader input %s centroid qualifier\n",
666                          producer_stage,
667                          output->name,
668                          (output->centroid) ? "has" : "lacks",
669                          consumer_stage,
670                          (input->centroid) ? "has" : "lacks");
671             return false;
672          }
673
674          if (input->invariant != output->invariant) {
675             linker_error(prog,
676                          "%s shader output `%s' %s invariant qualifier, "
677                          "but %s shader input %s invariant qualifier\n",
678                          producer_stage,
679                          output->name,
680                          (output->invariant) ? "has" : "lacks",
681                          consumer_stage,
682                          (input->invariant) ? "has" : "lacks");
683             return false;
684          }
685
686          if (input->interpolation != output->interpolation) {
687             linker_error(prog,
688                          "%s shader output `%s' specifies %s "
689                          "interpolation qualifier, "
690                          "but %s shader input specifies %s "
691                          "interpolation qualifier\n",
692                          producer_stage,
693                          output->name,
694                          output->interpolation_string(),
695                          consumer_stage,
696                          input->interpolation_string());
697             return false;
698          }
699       }
700    }
701
702    return true;
703 }
704
705
706 /**
707  * Populates a shaders symbol table with all global declarations
708  */
709 static void
710 populate_symbol_table(gl_shader *sh)
711 {
712    sh->symbols = new(sh) glsl_symbol_table;
713
714    foreach_list(node, sh->ir) {
715       ir_instruction *const inst = (ir_instruction *) node;
716       ir_variable *var;
717       ir_function *func;
718
719       if ((func = inst->as_function()) != NULL) {
720          sh->symbols->add_function(func);
721       } else if ((var = inst->as_variable()) != NULL) {
722          sh->symbols->add_variable(var);
723       }
724    }
725 }
726
727
728 /**
729  * Remap variables referenced in an instruction tree
730  *
731  * This is used when instruction trees are cloned from one shader and placed in
732  * another.  These trees will contain references to \c ir_variable nodes that
733  * do not exist in the target shader.  This function finds these \c ir_variable
734  * references and replaces the references with matching variables in the target
735  * shader.
736  *
737  * If there is no matching variable in the target shader, a clone of the
738  * \c ir_variable is made and added to the target shader.  The new variable is
739  * added to \b both the instruction stream and the symbol table.
740  *
741  * \param inst         IR tree that is to be processed.
742  * \param symbols      Symbol table containing global scope symbols in the
743  *                     linked shader.
744  * \param instructions Instruction stream where new variable declarations
745  *                     should be added.
746  */
747 void
748 remap_variables(ir_instruction *inst, struct gl_shader *target,
749                 hash_table *temps)
750 {
751    class remap_visitor : public ir_hierarchical_visitor {
752    public:
753          remap_visitor(struct gl_shader *target,
754                     hash_table *temps)
755       {
756          this->target = target;
757          this->symbols = target->symbols;
758          this->instructions = target->ir;
759          this->temps = temps;
760       }
761
762       virtual ir_visitor_status visit(ir_dereference_variable *ir)
763       {
764          if (ir->var->mode == ir_var_temporary) {
765             ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
766
767             assert(var != NULL);
768             ir->var = var;
769             return visit_continue;
770          }
771
772          ir_variable *const existing =
773             this->symbols->get_variable(ir->var->name);
774          if (existing != NULL)
775             ir->var = existing;
776          else {
777             ir_variable *copy = ir->var->clone(this->target, NULL);
778
779             this->symbols->add_variable(copy);
780             this->instructions->push_head(copy);
781             ir->var = copy;
782          }
783
784          return visit_continue;
785       }
786
787    private:
788       struct gl_shader *target;
789       glsl_symbol_table *symbols;
790       exec_list *instructions;
791       hash_table *temps;
792    };
793
794    remap_visitor v(target, temps);
795
796    inst->accept(&v);
797 }
798
799
800 /**
801  * Move non-declarations from one instruction stream to another
802  *
803  * The intended usage pattern of this function is to pass the pointer to the
804  * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
805  * pointer) for \c last and \c false for \c make_copies on the first
806  * call.  Successive calls pass the return value of the previous call for
807  * \c last and \c true for \c make_copies.
808  *
809  * \param instructions Source instruction stream
810  * \param last         Instruction after which new instructions should be
811  *                     inserted in the target instruction stream
812  * \param make_copies  Flag selecting whether instructions in \c instructions
813  *                     should be copied (via \c ir_instruction::clone) into the
814  *                     target list or moved.
815  *
816  * \return
817  * The new "last" instruction in the target instruction stream.  This pointer
818  * is suitable for use as the \c last parameter of a later call to this
819  * function.
820  */
821 exec_node *
822 move_non_declarations(exec_list *instructions, exec_node *last,
823                       bool make_copies, gl_shader *target)
824 {
825    hash_table *temps = NULL;
826
827    if (make_copies)
828       temps = hash_table_ctor(0, hash_table_pointer_hash,
829                               hash_table_pointer_compare);
830
831    foreach_list_safe(node, instructions) {
832       ir_instruction *inst = (ir_instruction *) node;
833
834       if (inst->as_function())
835          continue;
836
837       ir_variable *var = inst->as_variable();
838       if ((var != NULL) && (var->mode != ir_var_temporary))
839          continue;
840
841       assert(inst->as_assignment()
842              || inst->as_call()
843              || ((var != NULL) && (var->mode == ir_var_temporary)));
844
845       if (make_copies) {
846          inst = inst->clone(target, NULL);
847
848          if (var != NULL)
849             hash_table_insert(temps, inst, var);
850          else
851             remap_variables(inst, target, temps);
852       } else {
853          inst->remove();
854       }
855
856       last->insert_after(inst);
857       last = inst;
858    }
859
860    if (make_copies)
861       hash_table_dtor(temps);
862
863    return last;
864 }
865
866 /**
867  * Get the function signature for main from a shader
868  */
869 static ir_function_signature *
870 get_main_function_signature(gl_shader *sh)
871 {
872    ir_function *const f = sh->symbols->get_function("main");
873    if (f != NULL) {
874       exec_list void_parameters;
875
876       /* Look for the 'void main()' signature and ensure that it's defined.
877        * This keeps the linker from accidentally pick a shader that just
878        * contains a prototype for main.
879        *
880        * We don't have to check for multiple definitions of main (in multiple
881        * shaders) because that would have already been caught above.
882        */
883       ir_function_signature *sig = f->matching_signature(&void_parameters);
884       if ((sig != NULL) && sig->is_defined) {
885          return sig;
886       }
887    }
888
889    return NULL;
890 }
891
892
893 /**
894  * This class is only used in link_intrastage_shaders() below but declaring
895  * it inside that function leads to compiler warnings with some versions of
896  * gcc.
897  */
898 class array_sizing_visitor : public ir_hierarchical_visitor {
899 public:
900    virtual ir_visitor_status visit(ir_variable *var)
901    {
902       if (var->type->is_array() && (var->type->length == 0)) {
903          const glsl_type *type =
904             glsl_type::get_array_instance(var->type->fields.array,
905                                           var->max_array_access + 1);
906          assert(type != NULL);
907          var->type = type;
908       }
909       return visit_continue;
910    }
911 };
912
913
914 /**
915  * Combine a group of shaders for a single stage to generate a linked shader
916  *
917  * \note
918  * If this function is supplied a single shader, it is cloned, and the new
919  * shader is returned.
920  */
921 static struct gl_shader *
922 link_intrastage_shaders(void *mem_ctx,
923                         struct gl_context *ctx,
924                         struct gl_shader_program *prog,
925                         struct gl_shader **shader_list,
926                         unsigned num_shaders)
927 {
928    /* Check that global variables defined in multiple shaders are consistent.
929     */
930    if (!cross_validate_globals(prog, shader_list, num_shaders, false))
931       return NULL;
932
933    /* Check that there is only a single definition of each function signature
934     * across all shaders.
935     */
936    for (unsigned i = 0; i < (num_shaders - 1); i++) {
937       foreach_list(node, shader_list[i]->ir) {
938          ir_function *const f = ((ir_instruction *) node)->as_function();
939
940          if (f == NULL)
941             continue;
942
943          for (unsigned j = i + 1; j < num_shaders; j++) {
944             ir_function *const other =
945                shader_list[j]->symbols->get_function(f->name);
946
947             /* If the other shader has no function (and therefore no function
948              * signatures) with the same name, skip to the next shader.
949              */
950             if (other == NULL)
951                continue;
952
953             foreach_iter (exec_list_iterator, iter, *f) {
954                ir_function_signature *sig =
955                   (ir_function_signature *) iter.get();
956
957                if (!sig->is_defined || sig->is_builtin)
958                   continue;
959
960                ir_function_signature *other_sig =
961                   other->exact_matching_signature(& sig->parameters);
962
963                if ((other_sig != NULL) && other_sig->is_defined
964                    && !other_sig->is_builtin) {
965                   linker_error(prog, "function `%s' is multiply defined",
966                                f->name);
967                   return NULL;
968                }
969             }
970          }
971       }
972    }
973
974    /* Find the shader that defines main, and make a clone of it.
975     *
976     * Starting with the clone, search for undefined references.  If one is
977     * found, find the shader that defines it.  Clone the reference and add
978     * it to the shader.  Repeat until there are no undefined references or
979     * until a reference cannot be resolved.
980     */
981    gl_shader *main = NULL;
982    for (unsigned i = 0; i < num_shaders; i++) {
983       if (get_main_function_signature(shader_list[i]) != NULL) {
984          main = shader_list[i];
985          break;
986       }
987    }
988
989    if (main == NULL) {
990       linker_error(prog, "%s shader lacks `main'\n",
991                    (shader_list[0]->Type == GL_VERTEX_SHADER)
992                    ? "vertex" : "fragment");
993       return NULL;
994    }
995
996    gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
997    linked->ir = new(linked) exec_list;
998    clone_ir_list(mem_ctx, linked->ir, main->ir);
999
1000    populate_symbol_table(linked);
1001
1002    /* The a pointer to the main function in the final linked shader (i.e., the
1003     * copy of the original shader that contained the main function).
1004     */
1005    ir_function_signature *const main_sig = get_main_function_signature(linked);
1006
1007    /* Move any instructions other than variable declarations or function
1008     * declarations into main.
1009     */
1010    exec_node *insertion_point =
1011       move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1012                             linked);
1013
1014    for (unsigned i = 0; i < num_shaders; i++) {
1015       if (shader_list[i] == main)
1016          continue;
1017
1018       insertion_point = move_non_declarations(shader_list[i]->ir,
1019                                               insertion_point, true, linked);
1020    }
1021
1022    /* Resolve initializers for global variables in the linked shader.
1023     */
1024    unsigned num_linking_shaders = num_shaders;
1025    for (unsigned i = 0; i < num_shaders; i++)
1026       num_linking_shaders += shader_list[i]->num_builtins_to_link;
1027
1028    gl_shader **linking_shaders =
1029       (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1030
1031    memcpy(linking_shaders, shader_list,
1032           sizeof(linking_shaders[0]) * num_shaders);
1033
1034    unsigned idx = num_shaders;
1035    for (unsigned i = 0; i < num_shaders; i++) {
1036       memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1037              sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1038       idx += shader_list[i]->num_builtins_to_link;
1039    }
1040
1041    assert(idx == num_linking_shaders);
1042
1043    if (!link_function_calls(prog, linked, linking_shaders,
1044                             num_linking_shaders)) {
1045       ctx->Driver.DeleteShader(ctx, linked);
1046       linked = NULL;
1047    }
1048
1049    free(linking_shaders);
1050
1051 #ifdef DEBUG
1052    /* At this point linked should contain all of the linked IR, so
1053     * validate it to make sure nothing went wrong.
1054     */
1055    if (linked)
1056       validate_ir_tree(linked->ir);
1057 #endif
1058
1059    /* Make a pass over all variable declarations to ensure that arrays with
1060     * unspecified sizes have a size specified.  The size is inferred from the
1061     * max_array_access field.
1062     */
1063    if (linked != NULL) {
1064       array_sizing_visitor v;
1065
1066       v.run(linked->ir);
1067    }
1068
1069    return linked;
1070 }
1071
1072 /**
1073  * Update the sizes of linked shader uniform arrays to the maximum
1074  * array index used.
1075  *
1076  * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1077  *
1078  *     If one or more elements of an array are active,
1079  *     GetActiveUniform will return the name of the array in name,
1080  *     subject to the restrictions listed above. The type of the array
1081  *     is returned in type. The size parameter contains the highest
1082  *     array element index used, plus one. The compiler or linker
1083  *     determines the highest index used.  There will be only one
1084  *     active uniform reported by the GL per uniform array.
1085
1086  */
1087 static void
1088 update_array_sizes(struct gl_shader_program *prog)
1089 {
1090    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1091          if (prog->_LinkedShaders[i] == NULL)
1092             continue;
1093
1094       foreach_list(node, prog->_LinkedShaders[i]->ir) {
1095          ir_variable *const var = ((ir_instruction *) node)->as_variable();
1096
1097          if ((var == NULL) || (var->mode != ir_var_uniform &&
1098                                var->mode != ir_var_in &&
1099                                var->mode != ir_var_out) ||
1100              !var->type->is_array())
1101             continue;
1102
1103          unsigned int size = var->max_array_access;
1104          for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1105                if (prog->_LinkedShaders[j] == NULL)
1106                   continue;
1107
1108             foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1109                ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1110                if (!other_var)
1111                   continue;
1112
1113                if (strcmp(var->name, other_var->name) == 0 &&
1114                    other_var->max_array_access > size) {
1115                   size = other_var->max_array_access;
1116                }
1117             }
1118          }
1119
1120          if (size + 1 != var->type->fields.array->length) {
1121             /* If this is a built-in uniform (i.e., it's backed by some
1122              * fixed-function state), adjust the number of state slots to
1123              * match the new array size.  The number of slots per array entry
1124              * is not known.  It seems safe to assume that the total number of
1125              * slots is an integer multiple of the number of array elements.
1126              * Determine the number of slots per array element by dividing by
1127              * the old (total) size.
1128              */
1129             if (var->num_state_slots > 0) {
1130                var->num_state_slots = (size + 1)
1131                   * (var->num_state_slots / var->type->length);
1132             }
1133
1134             var->type = glsl_type::get_array_instance(var->type->fields.array,
1135                                                       size + 1);
1136             /* FINISHME: We should update the types of array
1137              * dereferences of this variable now.
1138              */
1139          }
1140       }
1141    }
1142 }
1143
1144 /**
1145  * Find a contiguous set of available bits in a bitmask.
1146  *
1147  * \param used_mask     Bits representing used (1) and unused (0) locations
1148  * \param needed_count  Number of contiguous bits needed.
1149  *
1150  * \return
1151  * Base location of the available bits on success or -1 on failure.
1152  */
1153 int
1154 find_available_slots(unsigned used_mask, unsigned needed_count)
1155 {
1156    unsigned needed_mask = (1 << needed_count) - 1;
1157    const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1158
1159    /* The comparison to 32 is redundant, but without it GCC emits "warning:
1160     * cannot optimize possibly infinite loops" for the loop below.
1161     */
1162    if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1163       return -1;
1164
1165    for (int i = 0; i <= max_bit_to_test; i++) {
1166       if ((needed_mask & ~used_mask) == needed_mask)
1167          return i;
1168
1169       needed_mask <<= 1;
1170    }
1171
1172    return -1;
1173 }
1174
1175
1176 /**
1177  * Assign locations for either VS inputs for FS outputs
1178  *
1179  * \param prog          Shader program whose variables need locations assigned
1180  * \param target_index  Selector for the program target to receive location
1181  *                      assignmnets.  Must be either \c MESA_SHADER_VERTEX or
1182  *                      \c MESA_SHADER_FRAGMENT.
1183  * \param max_index     Maximum number of generic locations.  This corresponds
1184  *                      to either the maximum number of draw buffers or the
1185  *                      maximum number of generic attributes.
1186  *
1187  * \return
1188  * If locations are successfully assigned, true is returned.  Otherwise an
1189  * error is emitted to the shader link log and false is returned.
1190  */
1191 bool
1192 assign_attribute_or_color_locations(gl_shader_program *prog,
1193                                     unsigned target_index,
1194                                     unsigned max_index)
1195 {
1196    /* Mark invalid locations as being used.
1197     */
1198    unsigned used_locations = (max_index >= 32)
1199       ? ~0 : ~((1 << max_index) - 1);
1200
1201    assert((target_index == MESA_SHADER_VERTEX)
1202           || (target_index == MESA_SHADER_FRAGMENT));
1203
1204    gl_shader *const sh = prog->_LinkedShaders[target_index];
1205    if (sh == NULL)
1206       return true;
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 and outputs that have
1214     *    user-defined locations (via glBindFragDataLocation).
1215     *
1216     * 3. Sort the attributes without assigned locations by number of slots
1217     *    required in decreasing order.  Fragmentation caused by attribute
1218     *    locations assigned by the application may prevent large attributes
1219     *    from having enough contiguous space.
1220     *
1221     * 4. Assign locations to any inputs without assigned locations.
1222     */
1223
1224    const int generic_base = (target_index == MESA_SHADER_VERTEX)
1225       ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1226
1227    const enum ir_variable_mode direction =
1228       (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1229
1230
1231    link_invalidate_variable_locations(sh, direction, generic_base);
1232
1233    /* Temporary storage for the set of attributes that need locations assigned.
1234     */
1235    struct temp_attr {
1236       unsigned slots;
1237       ir_variable *var;
1238
1239       /* Used below in the call to qsort. */
1240       static int compare(const void *a, const void *b)
1241       {
1242          const temp_attr *const l = (const temp_attr *) a;
1243          const temp_attr *const r = (const temp_attr *) b;
1244
1245          /* Reversed because we want a descending order sort below. */
1246          return r->slots - l->slots;
1247       }
1248    } to_assign[16];
1249
1250    unsigned num_attr = 0;
1251
1252    foreach_list(node, sh->ir) {
1253       ir_variable *const var = ((ir_instruction *) node)->as_variable();
1254
1255       if ((var == NULL) || (var->mode != (unsigned) direction))
1256          continue;
1257
1258       if (var->explicit_location) {
1259          if ((var->location >= (int)(max_index + generic_base))
1260              || (var->location < 0)) {
1261             linker_error(prog,
1262                          "invalid explicit location %d specified for `%s'\n",
1263                          (var->location < 0)
1264                          ? var->location : var->location - generic_base,
1265                          var->name);
1266             return false;
1267          }
1268       } else if (target_index == MESA_SHADER_VERTEX) {
1269          unsigned binding;
1270
1271          if (prog->AttributeBindings->get(binding, var->name)) {
1272             assert(binding >= VERT_ATTRIB_GENERIC0);
1273             var->location = binding;
1274          }
1275       } else if (target_index == MESA_SHADER_FRAGMENT) {
1276          unsigned binding;
1277          unsigned index;
1278
1279          if (prog->FragDataBindings->get(binding, var->name)) {
1280             assert(binding >= FRAG_RESULT_DATA0);
1281             var->location = binding;
1282
1283             if (prog->FragDataIndexBindings->get(index, var->name)) {
1284                var->index = index;
1285             }
1286          }
1287       }
1288
1289       /* If the variable is not a built-in and has a location statically
1290        * assigned in the shader (presumably via a layout qualifier), make sure
1291        * that it doesn't collide with other assigned locations.  Otherwise,
1292        * add it to the list of variables that need linker-assigned locations.
1293        */
1294       const unsigned slots = count_attribute_slots(var->type);
1295       if (var->location != -1) {
1296          if (var->location >= generic_base && var->index < 1) {
1297             /* From page 61 of the OpenGL 4.0 spec:
1298              *
1299              *     "LinkProgram will fail if the attribute bindings assigned
1300              *     by BindAttribLocation do not leave not enough space to
1301              *     assign a location for an active matrix attribute or an
1302              *     active attribute array, both of which require multiple
1303              *     contiguous generic attributes."
1304              *
1305              * Previous versions of the spec contain similar language but omit
1306              * the bit about attribute arrays.
1307              *
1308              * Page 61 of the OpenGL 4.0 spec also says:
1309              *
1310              *     "It is possible for an application to bind more than one
1311              *     attribute name to the same location. This is referred to as
1312              *     aliasing. This will only work if only one of the aliased
1313              *     attributes is active in the executable program, or if no
1314              *     path through the shader consumes more than one attribute of
1315              *     a set of attributes aliased to the same location. A link
1316              *     error can occur if the linker determines that every path
1317              *     through the shader consumes multiple aliased attributes,
1318              *     but implementations are not required to generate an error
1319              *     in this case."
1320              *
1321              * These two paragraphs are either somewhat contradictory, or I
1322              * don't fully understand one or both of them.
1323              */
1324             /* FINISHME: The code as currently written does not support
1325              * FINISHME: attribute location aliasing (see comment above).
1326              */
1327             /* Mask representing the contiguous slots that will be used by
1328              * this attribute.
1329              */
1330             const unsigned attr = var->location - generic_base;
1331             const unsigned use_mask = (1 << slots) - 1;
1332
1333             /* Generate a link error if the set of bits requested for this
1334              * attribute overlaps any previously allocated bits.
1335              */
1336             if ((~(use_mask << attr) & used_locations) != used_locations) {
1337                const char *const string = (target_index == MESA_SHADER_VERTEX)
1338                   ? "vertex shader input" : "fragment shader output";
1339                linker_error(prog,
1340                             "insufficient contiguous locations "
1341                             "available for %s `%s' %d %d %d", string,
1342                             var->name, used_locations, use_mask, attr);
1343                return false;
1344             }
1345
1346             used_locations |= (use_mask << attr);
1347          }
1348
1349          continue;
1350       }
1351
1352       to_assign[num_attr].slots = slots;
1353       to_assign[num_attr].var = var;
1354       num_attr++;
1355    }
1356
1357    /* If all of the attributes were assigned locations by the application (or
1358     * are built-in attributes with fixed locations), return early.  This should
1359     * be the common case.
1360     */
1361    if (num_attr == 0)
1362       return true;
1363
1364    qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1365
1366    if (target_index == MESA_SHADER_VERTEX) {
1367       /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS.  It can
1368        * only be explicitly assigned by via glBindAttribLocation.  Mark it as
1369        * reserved to prevent it from being automatically allocated below.
1370        */
1371       find_deref_visitor find("gl_Vertex");
1372       find.run(sh->ir);
1373       if (find.variable_found())
1374          used_locations |= (1 << 0);
1375    }
1376
1377    for (unsigned i = 0; i < num_attr; i++) {
1378       /* Mask representing the contiguous slots that will be used by this
1379        * attribute.
1380        */
1381       const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1382
1383       int location = find_available_slots(used_locations, to_assign[i].slots);
1384
1385       if (location < 0) {
1386          const char *const string = (target_index == MESA_SHADER_VERTEX)
1387             ? "vertex shader input" : "fragment shader output";
1388
1389          linker_error(prog,
1390                       "insufficient contiguous locations "
1391                       "available for %s `%s'",
1392                       string, to_assign[i].var->name);
1393          return false;
1394       }
1395
1396       to_assign[i].var->location = generic_base + location;
1397       used_locations |= (use_mask << location);
1398    }
1399
1400    return true;
1401 }
1402
1403
1404 /**
1405  * Demote shader inputs and outputs that are not used in other stages
1406  */
1407 void
1408 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1409 {
1410    foreach_list(node, sh->ir) {
1411       ir_variable *const var = ((ir_instruction *) node)->as_variable();
1412
1413       if ((var == NULL) || (var->mode != int(mode)))
1414          continue;
1415
1416       /* A shader 'in' or 'out' variable is only really an input or output if
1417        * its value is used by other shader stages.  This will cause the variable
1418        * to have a location assigned.
1419        */
1420       if (var->location == -1) {
1421          var->mode = ir_var_auto;
1422       }
1423    }
1424 }
1425
1426
1427 /**
1428  * Data structure tracking information about a transform feedback declaration
1429  * during linking.
1430  */
1431 class tfeedback_decl
1432 {
1433 public:
1434    bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1435              const void *mem_ctx, const char *input);
1436    static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1437    bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1438                         ir_variable *output_var);
1439    bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
1440    bool store(struct gl_context *ctx, struct gl_shader_program *prog,
1441               struct gl_transform_feedback_info *info, unsigned buffer,
1442               const unsigned max_outputs) const;
1443
1444    /**
1445     * True if assign_location() has been called for this object.
1446     */
1447    bool is_assigned() const
1448    {
1449       return this->location != -1;
1450    }
1451
1452    bool is_next_buffer_separator() const
1453    {
1454       return this->next_buffer_separator;
1455    }
1456
1457    bool is_varying() const
1458    {
1459       return !this->next_buffer_separator && !this->skip_components;
1460    }
1461
1462    /**
1463     * Determine whether this object refers to the variable var.
1464     */
1465    bool matches_var(ir_variable *var) const
1466    {
1467       if (this->is_clip_distance_mesa)
1468          return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1469       else
1470          return strcmp(var->name, this->var_name) == 0;
1471    }
1472
1473    /**
1474     * The total number of varying components taken up by this variable.  Only
1475     * valid if is_assigned() is true.
1476     */
1477    unsigned num_components() const
1478    {
1479       if (this->is_clip_distance_mesa)
1480          return this->size;
1481       else
1482          return this->vector_elements * this->matrix_columns * this->size;
1483    }
1484
1485 private:
1486    /**
1487     * The name that was supplied to glTransformFeedbackVaryings.  Used for
1488     * error reporting and glGetTransformFeedbackVarying().
1489     */
1490    const char *orig_name;
1491
1492    /**
1493     * The name of the variable, parsed from orig_name.
1494     */
1495    const char *var_name;
1496
1497    /**
1498     * True if the declaration in orig_name represents an array.
1499     */
1500    bool is_subscripted;
1501
1502    /**
1503     * If is_subscripted is true, the subscript that was specified in orig_name.
1504     */
1505    unsigned array_subscript;
1506
1507    /**
1508     * True if the variable is gl_ClipDistance and the driver lowers
1509     * gl_ClipDistance to gl_ClipDistanceMESA.
1510     */
1511    bool is_clip_distance_mesa;
1512
1513    /**
1514     * The vertex shader output location that the linker assigned for this
1515     * variable.  -1 if a location hasn't been assigned yet.
1516     */
1517    int location;
1518
1519    /**
1520     * If location != -1, the number of vector elements in this variable, or 1
1521     * if this variable is a scalar.
1522     */
1523    unsigned vector_elements;
1524
1525    /**
1526     * If location != -1, the number of matrix columns in this variable, or 1
1527     * if this variable is not a matrix.
1528     */
1529    unsigned matrix_columns;
1530
1531    /** Type of the varying returned by glGetTransformFeedbackVarying() */
1532    GLenum type;
1533
1534    /**
1535     * If location != -1, the size that should be returned by
1536     * glGetTransformFeedbackVarying().
1537     */
1538    unsigned size;
1539
1540    /**
1541     * How many components to skip. If non-zero, this is
1542     * gl_SkipComponents{1,2,3,4} from ARB_transform_feedback3.
1543     */
1544    unsigned skip_components;
1545
1546    /**
1547     * Whether this is gl_NextBuffer from ARB_transform_feedback3.
1548     */
1549    bool next_buffer_separator;
1550 };
1551
1552
1553 /**
1554  * Initialize this object based on a string that was passed to
1555  * glTransformFeedbackVaryings.  If there is a parse error, the error is
1556  * reported using linker_error(), and false is returned.
1557  */
1558 bool
1559 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1560                      const void *mem_ctx, const char *input)
1561 {
1562    /* We don't have to be pedantic about what is a valid GLSL variable name,
1563     * because any variable with an invalid name can't exist in the IR anyway.
1564     */
1565
1566    this->location = -1;
1567    this->orig_name = input;
1568    this->is_clip_distance_mesa = false;
1569    this->skip_components = 0;
1570    this->next_buffer_separator = false;
1571
1572    if (ctx->Extensions.ARB_transform_feedback3) {
1573       /* Parse gl_NextBuffer. */
1574       if (strcmp(input, "gl_NextBuffer") == 0) {
1575          this->next_buffer_separator = true;
1576          return true;
1577       }
1578
1579       /* Parse gl_SkipComponents. */
1580       if (strcmp(input, "gl_SkipComponents1") == 0)
1581          this->skip_components = 1;
1582       else if (strcmp(input, "gl_SkipComponents2") == 0)
1583          this->skip_components = 2;
1584       else if (strcmp(input, "gl_SkipComponents3") == 0)
1585          this->skip_components = 3;
1586       else if (strcmp(input, "gl_SkipComponents4") == 0)
1587          this->skip_components = 4;
1588
1589       if (this->skip_components)
1590          return true;
1591    }
1592
1593    /* Parse a declaration. */
1594    const char *bracket = strrchr(input, '[');
1595
1596    if (bracket) {
1597       this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
1598       if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
1599          linker_error(prog, "Cannot parse transform feedback varying %s", input);
1600          return false;
1601       }
1602       this->is_subscripted = true;
1603    } else {
1604       this->var_name = ralloc_strdup(mem_ctx, input);
1605       this->is_subscripted = false;
1606    }
1607
1608    /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1609     * class must behave specially to account for the fact that gl_ClipDistance
1610     * is converted from a float[8] to a vec4[2].
1611     */
1612    if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1613        strcmp(this->var_name, "gl_ClipDistance") == 0) {
1614       this->is_clip_distance_mesa = true;
1615    }
1616
1617    return true;
1618 }
1619
1620
1621 /**
1622  * Determine whether two tfeedback_decl objects refer to the same variable and
1623  * array index (if applicable).
1624  */
1625 bool
1626 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1627 {
1628    assert(x.is_varying() && y.is_varying());
1629
1630    if (strcmp(x.var_name, y.var_name) != 0)
1631       return false;
1632    if (x.is_subscripted != y.is_subscripted)
1633       return false;
1634    if (x.is_subscripted && x.array_subscript != y.array_subscript)
1635       return false;
1636    return true;
1637 }
1638
1639
1640 /**
1641  * Assign a location for this tfeedback_decl object based on the location
1642  * assignment in output_var.
1643  *
1644  * If an error occurs, the error is reported through linker_error() and false
1645  * is returned.
1646  */
1647 bool
1648 tfeedback_decl::assign_location(struct gl_context *ctx,
1649                                 struct gl_shader_program *prog,
1650                                 ir_variable *output_var)
1651 {
1652    assert(this->is_varying());
1653
1654    if (output_var->type->is_array()) {
1655       /* Array variable */
1656       const unsigned matrix_cols =
1657          output_var->type->fields.array->matrix_columns;
1658       unsigned actual_array_size = this->is_clip_distance_mesa ?
1659          prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
1660
1661       if (this->is_subscripted) {
1662          /* Check array bounds. */
1663          if (this->array_subscript >= actual_array_size) {
1664             linker_error(prog, "Transform feedback varying %s has index "
1665                          "%i, but the array size is %u.",
1666                          this->orig_name, this->array_subscript,
1667                          actual_array_size);
1668             return false;
1669          }
1670          if (this->is_clip_distance_mesa) {
1671             this->location =
1672                output_var->location + this->array_subscript / 4;
1673          } else {
1674             this->location =
1675                output_var->location + this->array_subscript * matrix_cols;
1676          }
1677          this->size = 1;
1678       } else {
1679          this->location = output_var->location;
1680          this->size = actual_array_size;
1681       }
1682       this->vector_elements = output_var->type->fields.array->vector_elements;
1683       this->matrix_columns = matrix_cols;
1684       if (this->is_clip_distance_mesa)
1685          this->type = GL_FLOAT;
1686       else
1687          this->type = output_var->type->fields.array->gl_type;
1688    } else {
1689       /* Regular variable (scalar, vector, or matrix) */
1690       if (this->is_subscripted) {
1691          linker_error(prog, "Transform feedback varying %s requested, "
1692                       "but %s is not an array.",
1693                       this->orig_name, this->var_name);
1694          return false;
1695       }
1696       this->location = output_var->location;
1697       this->size = 1;
1698       this->vector_elements = output_var->type->vector_elements;
1699       this->matrix_columns = output_var->type->matrix_columns;
1700       this->type = output_var->type->gl_type;
1701    }
1702
1703    /* From GL_EXT_transform_feedback:
1704     *   A program will fail to link if:
1705     *
1706     *   * the total number of components to capture in any varying
1707     *     variable in <varyings> is greater than the constant
1708     *     MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1709     *     buffer mode is SEPARATE_ATTRIBS_EXT;
1710     */
1711    if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1712        this->num_components() >
1713        ctx->Const.MaxTransformFeedbackSeparateComponents) {
1714       linker_error(prog, "Transform feedback varying %s exceeds "
1715                    "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1716                    this->orig_name);
1717       return false;
1718    }
1719
1720    return true;
1721 }
1722
1723
1724 bool
1725 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1726                                        unsigned *count)
1727 {
1728    if (!this->is_varying()) {
1729       return true;
1730    }
1731
1732    if (!this->is_assigned()) {
1733       /* From GL_EXT_transform_feedback:
1734        *   A program will fail to link if:
1735        *
1736        *   * any variable name specified in the <varyings> array is not
1737        *     declared as an output in the geometry shader (if present) or
1738        *     the vertex shader (if no geometry shader is present);
1739        */
1740       linker_error(prog, "Transform feedback varying %s undeclared.",
1741                    this->orig_name);
1742       return false;
1743    }
1744
1745    unsigned translated_size = this->size;
1746    if (this->is_clip_distance_mesa)
1747       translated_size = (translated_size + 3) / 4;
1748
1749    *count += translated_size * this->matrix_columns;
1750
1751    return true;
1752 }
1753
1754
1755 /**
1756  * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1757  *
1758  * If an error occurs, the error is reported through linker_error() and false
1759  * is returned.
1760  */
1761 bool
1762 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1763                       struct gl_transform_feedback_info *info,
1764                       unsigned buffer, const unsigned max_outputs) const
1765 {
1766    assert(!this->next_buffer_separator);
1767
1768    /* Handle gl_SkipComponents. */
1769    if (this->skip_components) {
1770       info->BufferStride[buffer] += this->skip_components;
1771       return true;
1772    }
1773
1774    /* From GL_EXT_transform_feedback:
1775     *   A program will fail to link if:
1776     *
1777     *     * the total number of components to capture is greater than
1778     *       the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1779     *       and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1780     */
1781    if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1782        info->BufferStride[buffer] + this->num_components() >
1783        ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1784       linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1785                    "limit has been exceeded.");
1786       return false;
1787    }
1788
1789    unsigned translated_size = this->size;
1790    if (this->is_clip_distance_mesa)
1791       translated_size = (translated_size + 3) / 4;
1792    unsigned components_so_far = 0;
1793    for (unsigned index = 0; index < translated_size; ++index) {
1794       for (unsigned v = 0; v < this->matrix_columns; ++v) {
1795          unsigned num_components = this->vector_elements;
1796          assert(info->NumOutputs < max_outputs);
1797          info->Outputs[info->NumOutputs].ComponentOffset = 0;
1798          if (this->is_clip_distance_mesa) {
1799             if (this->is_subscripted) {
1800                num_components = 1;
1801                info->Outputs[info->NumOutputs].ComponentOffset =
1802                   this->array_subscript % 4;
1803             } else {
1804                num_components = MIN2(4, this->size - components_so_far);
1805             }
1806          }
1807          info->Outputs[info->NumOutputs].OutputRegister =
1808             this->location + v + index * this->matrix_columns;
1809          info->Outputs[info->NumOutputs].NumComponents = num_components;
1810          info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1811          info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
1812          ++info->NumOutputs;
1813          info->BufferStride[buffer] += num_components;
1814          components_so_far += num_components;
1815       }
1816    }
1817    assert(components_so_far == this->num_components());
1818
1819    info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
1820    info->Varyings[info->NumVarying].Type = this->type;
1821    info->Varyings[info->NumVarying].Size = this->size;
1822    info->NumVarying++;
1823
1824    return true;
1825 }
1826
1827
1828 /**
1829  * Parse all the transform feedback declarations that were passed to
1830  * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1831  *
1832  * If an error occurs, the error is reported through linker_error() and false
1833  * is returned.
1834  */
1835 static bool
1836 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1837                       const void *mem_ctx, unsigned num_names,
1838                       char **varying_names, tfeedback_decl *decls)
1839 {
1840    for (unsigned i = 0; i < num_names; ++i) {
1841       if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1842          return false;
1843
1844       if (!decls[i].is_varying())
1845          continue;
1846
1847       /* From GL_EXT_transform_feedback:
1848        *   A program will fail to link if:
1849        *
1850        *   * any two entries in the <varyings> array specify the same varying
1851        *     variable;
1852        *
1853        * We interpret this to mean "any two entries in the <varyings> array
1854        * specify the same varying variable and array index", since transform
1855        * feedback of arrays would be useless otherwise.
1856        */
1857       for (unsigned j = 0; j < i; ++j) {
1858          if (!decls[j].is_varying())
1859             continue;
1860
1861          if (tfeedback_decl::is_same(decls[i], decls[j])) {
1862             linker_error(prog, "Transform feedback varying %s specified "
1863                          "more than once.", varying_names[i]);
1864             return false;
1865          }
1866       }
1867    }
1868    return true;
1869 }
1870
1871
1872 /**
1873  * Assign a location for a variable that is produced in one pipeline stage
1874  * (the "producer") and consumed in the next stage (the "consumer").
1875  *
1876  * \param input_var is the input variable declaration in the consumer.
1877  *
1878  * \param output_var is the output variable declaration in the producer.
1879  *
1880  * \param input_index is the counter that keeps track of assigned input
1881  *        locations in the consumer.
1882  *
1883  * \param output_index is the counter that keeps track of assigned output
1884  *        locations in the producer.
1885  *
1886  * It is permissible for \c input_var to be NULL (this happens if a variable
1887  * is output by the producer and consumed by transform feedback, but not
1888  * consumed by the consumer).
1889  *
1890  * If the variable has already been assigned a location, this function has no
1891  * effect.
1892  */
1893 void
1894 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1895                         unsigned *input_index, unsigned *output_index)
1896 {
1897    if (output_var->location != -1) {
1898       /* Location already assigned. */
1899       return;
1900    }
1901
1902    if (input_var) {
1903       assert(input_var->location == -1);
1904       input_var->location = *input_index;
1905    }
1906
1907    output_var->location = *output_index;
1908
1909    /* FINISHME: Support for "varying" records in GLSL 1.50. */
1910    assert(!output_var->type->is_record());
1911
1912    if (output_var->type->is_array()) {
1913       const unsigned slots = output_var->type->length
1914          * output_var->type->fields.array->matrix_columns;
1915
1916       *output_index += slots;
1917       *input_index += slots;
1918    } else {
1919       const unsigned slots = output_var->type->matrix_columns;
1920
1921       *output_index += slots;
1922       *input_index += slots;
1923    }
1924 }
1925
1926
1927 /**
1928  * Is the given variable a varying variable to be counted against the
1929  * limit in ctx->Const.MaxVarying?
1930  * This includes variables such as texcoords, colors and generic
1931  * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
1932  */
1933 static bool
1934 is_varying_var(GLenum shaderType, const ir_variable *var)
1935 {
1936    /* Only fragment shaders will take a varying variable as an input */
1937    if (shaderType == GL_FRAGMENT_SHADER &&
1938        var->mode == ir_var_in &&
1939        var->explicit_location) {
1940       switch (var->location) {
1941       case FRAG_ATTRIB_WPOS:
1942       case FRAG_ATTRIB_FACE:
1943       case FRAG_ATTRIB_PNTC:
1944          return false;
1945       default:
1946          return true;
1947       }
1948    }
1949    return false;
1950 }
1951
1952
1953 /**
1954  * Assign locations for all variables that are produced in one pipeline stage
1955  * (the "producer") and consumed in the next stage (the "consumer").
1956  *
1957  * Variables produced by the producer may also be consumed by transform
1958  * feedback.
1959  *
1960  * \param num_tfeedback_decls is the number of declarations indicating
1961  *        variables that may be consumed by transform feedback.
1962  *
1963  * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1964  *        representing the result of parsing the strings passed to
1965  *        glTransformFeedbackVaryings().  assign_location() will be called for
1966  *        each of these objects that matches one of the outputs of the
1967  *        producer.
1968  *
1969  * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1970  * be NULL.  In this case, varying locations are assigned solely based on the
1971  * requirements of transform feedback.
1972  */
1973 bool
1974 assign_varying_locations(struct gl_context *ctx,
1975                          struct gl_shader_program *prog,
1976                          gl_shader *producer, gl_shader *consumer,
1977                          unsigned num_tfeedback_decls,
1978                          tfeedback_decl *tfeedback_decls)
1979 {
1980    /* FINISHME: Set dynamically when geometry shader support is added. */
1981    unsigned output_index = VERT_RESULT_VAR0;
1982    unsigned input_index = FRAG_ATTRIB_VAR0;
1983
1984    /* Operate in a total of three passes.
1985     *
1986     * 1. Assign locations for any matching inputs and outputs.
1987     *
1988     * 2. Mark output variables in the producer that do not have locations as
1989     *    not being outputs.  This lets the optimizer eliminate them.
1990     *
1991     * 3. Mark input variables in the consumer that do not have locations as
1992     *    not being inputs.  This lets the optimizer eliminate them.
1993     */
1994
1995    link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1996    if (consumer)
1997       link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1998
1999    foreach_list(node, producer->ir) {
2000       ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
2001
2002       if ((output_var == NULL) || (output_var->mode != ir_var_out))
2003          continue;
2004
2005       ir_variable *input_var =
2006          consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
2007
2008       if (input_var && input_var->mode != ir_var_in)
2009          input_var = NULL;
2010
2011       if (input_var) {
2012          assign_varying_location(input_var, output_var, &input_index,
2013                                  &output_index);
2014       }
2015
2016       for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2017          if (!tfeedback_decls[i].is_varying())
2018             continue;
2019
2020          if (!tfeedback_decls[i].is_assigned() &&
2021              tfeedback_decls[i].matches_var(output_var)) {
2022             if (output_var->location == -1) {
2023                assign_varying_location(input_var, output_var, &input_index,
2024                                        &output_index);
2025             }
2026             if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
2027                return false;
2028          }
2029       }
2030    }
2031
2032    unsigned varying_vectors = 0;
2033
2034    if (consumer) {
2035       foreach_list(node, consumer->ir) {
2036          ir_variable *const var = ((ir_instruction *) node)->as_variable();
2037
2038          if ((var == NULL) || (var->mode != ir_var_in))
2039             continue;
2040
2041          if (var->location == -1) {
2042             if (prog->Version <= 120) {
2043                /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
2044                 *
2045                 *     Only those varying variables used (i.e. read) in
2046                 *     the fragment shader executable must be written to
2047                 *     by the vertex shader executable; declaring
2048                 *     superfluous varying variables in a vertex shader is
2049                 *     permissible.
2050                 *
2051                 * We interpret this text as meaning that the VS must
2052                 * write the variable for the FS to read it.  See
2053                 * "glsl1-varying read but not written" in piglit.
2054                 */
2055
2056                linker_error(prog, "fragment shader varying %s not written "
2057                             "by vertex shader\n.", var->name);
2058             }
2059
2060             /* An 'in' variable is only really a shader input if its
2061              * value is written by the previous stage.
2062              */
2063             var->mode = ir_var_auto;
2064          } else if (is_varying_var(consumer->Type, var)) {
2065             /* The packing rules are used for vertex shader inputs are also
2066              * used for fragment shader inputs.
2067              */
2068             varying_vectors += count_attribute_slots(var->type);
2069          }
2070       }
2071    }
2072
2073    if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
2074       if (varying_vectors > ctx->Const.MaxVarying) {
2075          if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
2076             linker_warning(prog, "shader uses too many varying vectors "
2077                            "(%u > %u), but the driver will try to optimize "
2078                            "them out; this is non-portable out-of-spec "
2079                            "behavior\n",
2080                            varying_vectors, ctx->Const.MaxVarying);
2081          } else {
2082             linker_error(prog, "shader uses too many varying vectors "
2083                          "(%u > %u)\n",
2084                          varying_vectors, ctx->Const.MaxVarying);
2085             return false;
2086          }
2087       }
2088    } else {
2089       const unsigned float_components = varying_vectors * 4;
2090       if (float_components > ctx->Const.MaxVarying * 4) {
2091          if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
2092             linker_warning(prog, "shader uses too many varying components "
2093                            "(%u > %u), but the driver will try to optimize "
2094                            "them out; this is non-portable out-of-spec "
2095                            "behavior\n",
2096                            float_components, ctx->Const.MaxVarying * 4);
2097          } else {
2098             linker_error(prog, "shader uses too many varying components "
2099                          "(%u > %u)\n",
2100                          float_components, ctx->Const.MaxVarying * 4);
2101             return false;
2102          }
2103       }
2104    }
2105
2106    return true;
2107 }
2108
2109
2110 /**
2111  * Store transform feedback location assignments into
2112  * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2113  *
2114  * If an error occurs, the error is reported through linker_error() and false
2115  * is returned.
2116  */
2117 static bool
2118 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2119                      unsigned num_tfeedback_decls,
2120                      tfeedback_decl *tfeedback_decls)
2121 {
2122    bool separate_attribs_mode =
2123       prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
2124
2125    ralloc_free(prog->LinkedTransformFeedback.Varyings);
2126    ralloc_free(prog->LinkedTransformFeedback.Outputs);
2127
2128    memset(&prog->LinkedTransformFeedback, 0,
2129           sizeof(prog->LinkedTransformFeedback));
2130
2131    prog->LinkedTransformFeedback.Varyings =
2132       rzalloc_array(prog,
2133                     struct gl_transform_feedback_varying_info,
2134                     num_tfeedback_decls);
2135
2136    unsigned num_outputs = 0;
2137    for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2138       if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2139          return false;
2140
2141    prog->LinkedTransformFeedback.Outputs =
2142       rzalloc_array(prog,
2143                     struct gl_transform_feedback_output,
2144                     num_outputs);
2145
2146    unsigned num_buffers = 0;
2147
2148    if (separate_attribs_mode) {
2149       /* GL_SEPARATE_ATTRIBS */
2150       for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2151          if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
2152                                        num_buffers, num_outputs))
2153             return false;
2154
2155          num_buffers++;
2156       }
2157    }
2158    else {
2159       /* GL_INVERLEAVED_ATTRIBS */
2160       for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2161          if (tfeedback_decls[i].is_next_buffer_separator()) {
2162             num_buffers++;
2163             continue;
2164          }
2165
2166          if (!tfeedback_decls[i].store(ctx, prog,
2167                                        &prog->LinkedTransformFeedback,
2168                                        num_buffers, num_outputs))
2169             return false;
2170       }
2171       num_buffers++;
2172    }
2173
2174    assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2175
2176    prog->LinkedTransformFeedback.NumBuffers = num_buffers;
2177    return true;
2178 }
2179
2180 /**
2181  * Store the gl_FragDepth layout in the gl_shader_program struct.
2182  */
2183 static void
2184 store_fragdepth_layout(struct gl_shader_program *prog)
2185 {
2186    if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2187       return;
2188    }
2189
2190    struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2191
2192    /* We don't look up the gl_FragDepth symbol directly because if
2193     * gl_FragDepth is not used in the shader, it's removed from the IR.
2194     * However, the symbol won't be removed from the symbol table.
2195     *
2196     * We're only interested in the cases where the variable is NOT removed
2197     * from the IR.
2198     */
2199    foreach_list(node, ir) {
2200       ir_variable *const var = ((ir_instruction *) node)->as_variable();
2201
2202       if (var == NULL || var->mode != ir_var_out) {
2203          continue;
2204       }
2205
2206       if (strcmp(var->name, "gl_FragDepth") == 0) {
2207          switch (var->depth_layout) {
2208          case ir_depth_layout_none:
2209             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2210             return;
2211          case ir_depth_layout_any:
2212             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2213             return;
2214          case ir_depth_layout_greater:
2215             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2216             return;
2217          case ir_depth_layout_less:
2218             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2219             return;
2220          case ir_depth_layout_unchanged:
2221             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2222             return;
2223          default:
2224             assert(0);
2225             return;
2226          }
2227       }
2228    }
2229 }
2230
2231 /**
2232  * Validate the resources used by a program versus the implementation limits
2233  */
2234 static bool
2235 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2236 {
2237    static const char *const shader_names[MESA_SHADER_TYPES] = {
2238       "vertex", "fragment", "geometry"
2239    };
2240
2241    const unsigned max_samplers[MESA_SHADER_TYPES] = {
2242       ctx->Const.MaxVertexTextureImageUnits,
2243       ctx->Const.MaxTextureImageUnits,
2244       ctx->Const.MaxGeometryTextureImageUnits
2245    };
2246
2247    const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2248       ctx->Const.VertexProgram.MaxUniformComponents,
2249       ctx->Const.FragmentProgram.MaxUniformComponents,
2250       0          /* FINISHME: Geometry shaders. */
2251    };
2252
2253    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2254       struct gl_shader *sh = prog->_LinkedShaders[i];
2255
2256       if (sh == NULL)
2257          continue;
2258
2259       if (sh->num_samplers > max_samplers[i]) {
2260          linker_error(prog, "Too many %s shader texture samplers",
2261                       shader_names[i]);
2262       }
2263
2264       if (sh->num_uniform_components > max_uniform_components[i]) {
2265          if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2266             linker_warning(prog, "Too many %s shader uniform components, "
2267                            "but the driver will try to optimize them out; "
2268                            "this is non-portable out-of-spec behavior\n",
2269                            shader_names[i]);
2270          } else {
2271             linker_error(prog, "Too many %s shader uniform components",
2272                          shader_names[i]);
2273          }
2274       }
2275    }
2276
2277    return prog->LinkStatus;
2278 }
2279
2280 void
2281 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2282 {
2283    tfeedback_decl *tfeedback_decls = NULL;
2284    unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2285
2286    void *mem_ctx = ralloc_context(NULL); // temporary linker context
2287
2288    prog->LinkStatus = false;
2289    prog->Validated = false;
2290    prog->_Used = false;
2291
2292    if (prog->InfoLog != NULL)
2293       ralloc_free(prog->InfoLog);
2294
2295    prog->InfoLog = ralloc_strdup(NULL, "");
2296
2297    /* Separate the shaders into groups based on their type.
2298     */
2299    struct gl_shader **vert_shader_list;
2300    unsigned num_vert_shaders = 0;
2301    struct gl_shader **frag_shader_list;
2302    unsigned num_frag_shaders = 0;
2303
2304    vert_shader_list = (struct gl_shader **)
2305       calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
2306    frag_shader_list =  &vert_shader_list[prog->NumShaders];
2307
2308    unsigned min_version = UINT_MAX;
2309    unsigned max_version = 0;
2310    for (unsigned i = 0; i < prog->NumShaders; i++) {
2311       min_version = MIN2(min_version, prog->Shaders[i]->Version);
2312       max_version = MAX2(max_version, prog->Shaders[i]->Version);
2313
2314       switch (prog->Shaders[i]->Type) {
2315       case GL_VERTEX_SHADER:
2316          vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2317          num_vert_shaders++;
2318          break;
2319       case GL_FRAGMENT_SHADER:
2320          frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2321          num_frag_shaders++;
2322          break;
2323       case GL_GEOMETRY_SHADER:
2324          /* FINISHME: Support geometry shaders. */
2325          assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2326          break;
2327       }
2328    }
2329
2330    /* Previous to GLSL version 1.30, different compilation units could mix and
2331     * match shading language versions.  With GLSL 1.30 and later, the versions
2332     * of all shaders must match.
2333     */
2334    assert(min_version >= 100);
2335    assert(max_version <= 140);
2336    if ((max_version >= 130 || min_version == 100)
2337        && min_version != max_version) {
2338       linker_error(prog, "all shaders must use same shading "
2339                    "language version\n");
2340       goto done;
2341    }
2342
2343    prog->Version = max_version;
2344
2345    for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2346       if (prog->_LinkedShaders[i] != NULL)
2347          ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2348
2349       prog->_LinkedShaders[i] = NULL;
2350    }
2351
2352    /* Link all shaders for a particular stage and validate the result.
2353     */
2354    if (num_vert_shaders > 0) {
2355       gl_shader *const sh =
2356          link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2357                                  num_vert_shaders);
2358
2359       if (sh == NULL)
2360          goto done;
2361
2362       if (!validate_vertex_shader_executable(prog, sh))
2363          goto done;
2364
2365       _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2366                              sh);
2367    }
2368
2369    if (num_frag_shaders > 0) {
2370       gl_shader *const sh =
2371          link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2372                                  num_frag_shaders);
2373
2374       if (sh == NULL)
2375          goto done;
2376
2377       if (!validate_fragment_shader_executable(prog, sh))
2378          goto done;
2379
2380       _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2381                              sh);
2382    }
2383
2384    /* Here begins the inter-stage linking phase.  Some initial validation is
2385     * performed, then locations are assigned for uniforms, attributes, and
2386     * varyings.
2387     */
2388    if (cross_validate_uniforms(prog)) {
2389       unsigned prev;
2390
2391       for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2392          if (prog->_LinkedShaders[prev] != NULL)
2393             break;
2394       }
2395
2396       /* Validate the inputs of each stage with the output of the preceding
2397        * stage.
2398        */
2399       for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2400          if (prog->_LinkedShaders[i] == NULL)
2401             continue;
2402
2403          if (!cross_validate_outputs_to_inputs(prog,
2404                                                prog->_LinkedShaders[prev],
2405                                                prog->_LinkedShaders[i]))
2406             goto done;
2407
2408          prev = i;
2409       }
2410
2411       prog->LinkStatus = true;
2412    }
2413
2414    /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2415     * it before optimization because we want most of the checks to get
2416     * dropped thanks to constant propagation.
2417     */
2418    if (max_version >= 130) {
2419       struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2420       if (sh) {
2421          lower_discard_flow(sh->ir);
2422       }
2423    }
2424
2425    /* Do common optimization before assigning storage for attributes,
2426     * uniforms, and varyings.  Later optimization could possibly make
2427     * some of that unused.
2428     */
2429    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2430       if (prog->_LinkedShaders[i] == NULL)
2431          continue;
2432
2433       detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2434       if (!prog->LinkStatus)
2435          goto done;
2436
2437       if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2438          lower_clip_distance(prog->_LinkedShaders[i]->ir);
2439
2440       unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2441
2442       while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
2443          ;
2444    }
2445
2446    /* FINISHME: The value of the max_attribute_index parameter is
2447     * FINISHME: implementation dependent based on the value of
2448     * FINISHME: GL_MAX_VERTEX_ATTRIBS.  GL_MAX_VERTEX_ATTRIBS must be
2449     * FINISHME: at least 16, so hardcode 16 for now.
2450     */
2451    if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2452       goto done;
2453    }
2454
2455    if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2456       goto done;
2457    }
2458
2459    unsigned prev;
2460    for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2461       if (prog->_LinkedShaders[prev] != NULL)
2462          break;
2463    }
2464
2465    if (num_tfeedback_decls != 0) {
2466       /* From GL_EXT_transform_feedback:
2467        *   A program will fail to link if:
2468        *
2469        *   * the <count> specified by TransformFeedbackVaryingsEXT is
2470        *     non-zero, but the program object has no vertex or geometry
2471        *     shader;
2472        */
2473       if (prev >= MESA_SHADER_FRAGMENT) {
2474          linker_error(prog, "Transform feedback varyings specified, but "
2475                       "no vertex or geometry shader is present.");
2476          goto done;
2477       }
2478
2479       tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2480                                      prog->TransformFeedback.NumVarying);
2481       if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2482                                  prog->TransformFeedback.VaryingNames,
2483                                  tfeedback_decls))
2484          goto done;
2485    }
2486
2487    for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2488       if (prog->_LinkedShaders[i] == NULL)
2489          continue;
2490
2491       if (!assign_varying_locations(
2492              ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2493              i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2494              tfeedback_decls))
2495          goto done;
2496
2497       prev = i;
2498    }
2499
2500    if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2501       /* There was no fragment shader, but we still have to assign varying
2502        * locations for use by transform feedback.
2503        */
2504       if (!assign_varying_locations(
2505              ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2506              tfeedback_decls))
2507          goto done;
2508    }
2509
2510    if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2511       goto done;
2512
2513    if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2514       demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2515                                        ir_var_out);
2516
2517       /* Eliminate code that is now dead due to unused vertex outputs being
2518        * demoted.
2519        */
2520       while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2521          ;
2522    }
2523
2524    if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2525       gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2526
2527       demote_shader_inputs_and_outputs(sh, ir_var_in);
2528       demote_shader_inputs_and_outputs(sh, ir_var_inout);
2529       demote_shader_inputs_and_outputs(sh, ir_var_out);
2530
2531       /* Eliminate code that is now dead due to unused geometry outputs being
2532        * demoted.
2533        */
2534       while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2535          ;
2536    }
2537
2538    if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2539       gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2540
2541       demote_shader_inputs_and_outputs(sh, ir_var_in);
2542
2543       /* Eliminate code that is now dead due to unused fragment inputs being
2544        * demoted.  This shouldn't actually do anything other than remove
2545        * declarations of the (now unused) global variables.
2546        */
2547       while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2548          ;
2549    }
2550
2551    update_array_sizes(prog);
2552    link_assign_uniform_locations(prog);
2553    store_fragdepth_layout(prog);
2554
2555    if (!check_resources(ctx, prog))
2556       goto done;
2557
2558    /* OpenGL ES requires that a vertex shader and a fragment shader both be
2559     * present in a linked program.  By checking for use of shading language
2560     * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2561     */
2562    if (!prog->InternalSeparateShader &&
2563        (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
2564       if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2565          linker_error(prog, "program lacks a vertex shader\n");
2566       } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2567          linker_error(prog, "program lacks a fragment shader\n");
2568       }
2569    }
2570
2571    /* FINISHME: Assign fragment shader output locations. */
2572
2573 done:
2574    free(vert_shader_list);
2575
2576    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2577       if (prog->_LinkedShaders[i] == NULL)
2578          continue;
2579
2580       /* Retain any live IR, but trash the rest. */
2581       reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2582
2583       /* The symbol table in the linked shaders may contain references to
2584        * variables that were removed (e.g., unused uniforms).  Since it may
2585        * contain junk, there is no possible valid use.  Delete it and set the
2586        * pointer to NULL.
2587        */
2588       delete prog->_LinkedShaders[i]->symbols;
2589       prog->_LinkedShaders[i]->symbols = NULL;
2590    }
2591
2592    ralloc_free(mem_ctx);
2593 }