2 * Copyright © 2010 Intel Corporation
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:
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
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.
26 * GLSL linker implementation
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
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
35 * - Undefined references in each shader are resolve to definitions in
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.
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
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
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
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.
64 * \author Ian Romanick <ian.d.romanick@intel.com>
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
71 #include "program/hash_table.h"
73 #include "ir_optimization.h"
76 #include "main/shaderobj.h"
80 * Visitor that determines whether or not a variable is ever written.
82 class find_assignment_visitor : public ir_hierarchical_visitor {
84 find_assignment_visitor(const char *name)
85 : name(name), found(false)
90 virtual ir_visitor_status visit_enter(ir_assignment *ir)
92 ir_variable *const var = ir->lhs->variable_referenced();
94 if (strcmp(name, var->name) == 0) {
99 return visit_continue_with_parent;
102 virtual ir_visitor_status visit_enter(ir_call *ir)
104 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
105 foreach_iter(exec_list_iterator, iter, *ir) {
106 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
107 ir_variable *sig_param = (ir_variable *)sig_iter.get();
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) {
120 return visit_continue_with_parent;
123 bool variable_found()
129 const char *name; /**< Find writes to a variable with this name. */
130 bool found; /**< Was a write to the variable found? */
135 * Visitor that determines whether or not a variable is ever read.
137 class find_deref_visitor : public ir_hierarchical_visitor {
139 find_deref_visitor(const char *name)
140 : name(name), found(false)
145 virtual ir_visitor_status visit(ir_dereference_variable *ir)
147 if (strcmp(this->name, ir->var->name) == 0) {
152 return visit_continue;
155 bool variable_found() const
161 const char *name; /**< Find writes to a variable with this name. */
162 bool found; /**< Was a write to the variable found? */
167 linker_error(gl_shader_program *prog, const char *fmt, ...)
171 ralloc_strcat(&prog->InfoLog, "error: ");
173 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
176 prog->LinkStatus = false;
181 linker_warning(gl_shader_program *prog, const char *fmt, ...)
185 ralloc_strcat(&prog->InfoLog, "error: ");
187 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
194 link_invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
197 foreach_list(node, sh->ir) {
198 ir_variable *const var = ((ir_instruction *) node)->as_variable();
200 if ((var == NULL) || (var->mode != (unsigned) mode))
203 /* Only assign locations for generic attributes / varyings / etc.
205 if ((var->location >= generic_base) && !var->explicit_location)
212 * Determine the number of attribute slots required for a particular type
214 * This code is here because it implements the language rules of a specific
215 * GLSL version. Since it's a property of the language and not a property of
216 * types in general, it doesn't really belong in glsl_type.
219 count_attribute_slots(const glsl_type *t)
221 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
223 * "A scalar input counts the same amount against this limit as a vec4,
224 * so applications may want to consider packing groups of four
225 * unrelated float inputs together into a vector to better utilize the
226 * capabilities of the underlying hardware. A matrix input will use up
227 * multiple locations. The number of locations used will equal the
228 * number of columns in the matrix."
230 * The spec does not explicitly say how arrays are counted. However, it
231 * should be safe to assume the total number of slots consumed by an array
232 * is the number of entries in the array multiplied by the number of slots
233 * consumed by a single element of the array.
237 return t->array_size() * count_attribute_slots(t->element_type());
240 return t->matrix_columns;
247 * Verify that a vertex shader executable meets all semantic requirements.
249 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
252 * \param shader Vertex shader executable to be verified
255 validate_vertex_shader_executable(struct gl_shader_program *prog,
256 struct gl_shader *shader)
261 /* From the GLSL 1.10 spec, page 48:
263 * "The variable gl_Position is available only in the vertex
264 * language and is intended for writing the homogeneous vertex
265 * position. All executions of a well-formed vertex shader
266 * executable must write a value into this variable. [...] The
267 * variable gl_Position is available only in the vertex
268 * language and is intended for writing the homogeneous vertex
269 * position. All executions of a well-formed vertex shader
270 * executable must write a value into this variable."
272 * while in GLSL 1.40 this text is changed to:
274 * "The variable gl_Position is available only in the vertex
275 * language and is intended for writing the homogeneous vertex
276 * position. It can be written at any time during shader
277 * execution. It may also be read back by a vertex shader
278 * after being written. This value will be used by primitive
279 * assembly, clipping, culling, and other fixed functionality
280 * operations, if present, that operate on primitives after
281 * vertex processing has occurred. Its value is undefined if
282 * the vertex shader executable does not write gl_Position."
284 if (prog->Version < 140) {
285 find_assignment_visitor find("gl_Position");
286 find.run(shader->ir);
287 if (!find.variable_found()) {
288 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
293 prog->Vert.ClipDistanceArraySize = 0;
295 if (prog->Version >= 130) {
296 /* From section 7.1 (Vertex Shader Special Variables) of the
299 * "It is an error for a shader to statically write both
300 * gl_ClipVertex and gl_ClipDistance."
302 find_assignment_visitor clip_vertex("gl_ClipVertex");
303 find_assignment_visitor clip_distance("gl_ClipDistance");
305 clip_vertex.run(shader->ir);
306 clip_distance.run(shader->ir);
307 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
308 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
309 "and `gl_ClipDistance'\n");
312 prog->Vert.UsesClipDistance = clip_distance.variable_found();
313 ir_variable *clip_distance_var =
314 shader->symbols->get_variable("gl_ClipDistance");
315 if (clip_distance_var)
316 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
324 * Verify that a fragment shader executable meets all semantic requirements
326 * \param shader Fragment shader executable to be verified
329 validate_fragment_shader_executable(struct gl_shader_program *prog,
330 struct gl_shader *shader)
335 find_assignment_visitor frag_color("gl_FragColor");
336 find_assignment_visitor frag_data("gl_FragData");
338 frag_color.run(shader->ir);
339 frag_data.run(shader->ir);
341 if (frag_color.variable_found() && frag_data.variable_found()) {
342 linker_error(prog, "fragment shader writes to both "
343 "`gl_FragColor' and `gl_FragData'\n");
352 * Generate a string describing the mode of a variable
355 mode_string(const ir_variable *var)
359 return (var->read_only) ? "global constant" : "global variable";
361 case ir_var_uniform: return "uniform";
362 case ir_var_in: return "shader input";
363 case ir_var_out: return "shader output";
364 case ir_var_inout: return "shader inout";
366 case ir_var_const_in:
367 case ir_var_temporary:
369 assert(!"Should not get here.");
370 return "invalid variable";
376 * Perform validation of global variables used across multiple shaders
379 cross_validate_globals(struct gl_shader_program *prog,
380 struct gl_shader **shader_list,
381 unsigned num_shaders,
384 /* Examine all of the uniforms in all of the shaders and cross validate
387 glsl_symbol_table variables;
388 for (unsigned i = 0; i < num_shaders; i++) {
389 if (shader_list[i] == NULL)
392 foreach_list(node, shader_list[i]->ir) {
393 ir_variable *const var = ((ir_instruction *) node)->as_variable();
398 if (uniforms_only && (var->mode != ir_var_uniform))
401 /* Don't cross validate temporaries that are at global scope. These
402 * will eventually get pulled into the shaders 'main'.
404 if (var->mode == ir_var_temporary)
407 /* If a global with this name has already been seen, verify that the
408 * new instance has the same type. In addition, if the globals have
409 * initializers, the values of the initializers must be the same.
411 ir_variable *const existing = variables.get_variable(var->name);
412 if (existing != NULL) {
413 if (var->type != existing->type) {
414 /* Consider the types to be "the same" if both types are arrays
415 * of the same type and one of the arrays is implicitly sized.
416 * In addition, set the type of the linked variable to the
417 * explicitly sized array.
419 if (var->type->is_array()
420 && existing->type->is_array()
421 && (var->type->fields.array == existing->type->fields.array)
422 && ((var->type->length == 0)
423 || (existing->type->length == 0))) {
424 if (var->type->length != 0) {
425 existing->type = var->type;
428 linker_error(prog, "%s `%s' declared as type "
429 "`%s' and type `%s'\n",
431 var->name, var->type->name,
432 existing->type->name);
437 if (var->explicit_location) {
438 if (existing->explicit_location
439 && (var->location != existing->location)) {
440 linker_error(prog, "explicit locations for %s "
441 "`%s' have differing values\n",
442 mode_string(var), var->name);
446 existing->location = var->location;
447 existing->explicit_location = true;
450 /* Validate layout qualifiers for gl_FragDepth.
452 * From the AMD/ARB_conservative_depth specs:
454 * "If gl_FragDepth is redeclared in any fragment shader in a
455 * program, it must be redeclared in all fragment shaders in
456 * that program that have static assignments to
457 * gl_FragDepth. All redeclarations of gl_FragDepth in all
458 * fragment shaders in a single program must have the same set
461 if (strcmp(var->name, "gl_FragDepth") == 0) {
462 bool layout_declared = var->depth_layout != ir_depth_layout_none;
463 bool layout_differs =
464 var->depth_layout != existing->depth_layout;
466 if (layout_declared && layout_differs) {
468 "All redeclarations of gl_FragDepth in all "
469 "fragment shaders in a single program must have "
470 "the same set of qualifiers.");
473 if (var->used && layout_differs) {
475 "If gl_FragDepth is redeclared with a layout "
476 "qualifier in any fragment shader, it must be "
477 "redeclared with the same layout qualifier in "
478 "all fragment shaders that have assignments to "
483 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
485 * "If a shared global has multiple initializers, the
486 * initializers must all be constant expressions, and they
487 * must all have the same value. Otherwise, a link error will
488 * result. (A shared global having only one initializer does
489 * not require that initializer to be a constant expression.)"
491 * Previous to 4.20 the GLSL spec simply said that initializers
492 * must have the same value. In this case of non-constant
493 * initializers, this was impossible to determine. As a result,
494 * no vendor actually implemented that behavior. The 4.20
495 * behavior matches the implemented behavior of at least one other
496 * vendor, so we'll implement that for all GLSL versions.
498 if (var->constant_initializer != NULL) {
499 if (existing->constant_initializer != NULL) {
500 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
501 linker_error(prog, "initializers for %s "
502 "`%s' have differing values\n",
503 mode_string(var), var->name);
507 /* If the first-seen instance of a particular uniform did not
508 * have an initializer but a later instance does, copy the
509 * initializer to the version stored in the symbol table.
511 /* FINISHME: This is wrong. The constant_value field should
512 * FINISHME: not be modified! Imagine a case where a shader
513 * FINISHME: without an initializer is linked in two different
514 * FINISHME: programs with shaders that have differing
515 * FINISHME: initializers. Linking with the first will
516 * FINISHME: modify the shader, and linking with the second
517 * FINISHME: will fail.
519 existing->constant_initializer =
520 var->constant_initializer->clone(ralloc_parent(existing),
525 if (var->has_initializer) {
526 if (existing->has_initializer
527 && (var->constant_initializer == NULL
528 || existing->constant_initializer == NULL)) {
530 "shared global variable `%s' has multiple "
531 "non-constant initializers.\n",
536 /* Some instance had an initializer, so keep track of that. In
537 * this location, all sorts of initializers (constant or
538 * otherwise) will propagate the existence to the variable
539 * stored in the symbol table.
541 existing->has_initializer = true;
544 if (existing->invariant != var->invariant) {
545 linker_error(prog, "declarations for %s `%s' have "
546 "mismatching invariant qualifiers\n",
547 mode_string(var), var->name);
550 if (existing->centroid != var->centroid) {
551 linker_error(prog, "declarations for %s `%s' have "
552 "mismatching centroid qualifiers\n",
553 mode_string(var), var->name);
557 variables.add_variable(var);
566 * Perform validation of uniforms used across multiple shader stages
569 cross_validate_uniforms(struct gl_shader_program *prog)
571 return cross_validate_globals(prog, prog->_LinkedShaders,
572 MESA_SHADER_TYPES, true);
577 * Validate that outputs from one stage match inputs of another
580 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
581 gl_shader *producer, gl_shader *consumer)
583 glsl_symbol_table parameters;
584 /* FINISHME: Figure these out dynamically. */
585 const char *const producer_stage = "vertex";
586 const char *const consumer_stage = "fragment";
588 /* Find all shader outputs in the "producer" stage.
590 foreach_list(node, producer->ir) {
591 ir_variable *const var = ((ir_instruction *) node)->as_variable();
593 /* FINISHME: For geometry shaders, this should also look for inout
594 * FINISHME: variables.
596 if ((var == NULL) || (var->mode != ir_var_out))
599 parameters.add_variable(var);
603 /* Find all shader inputs in the "consumer" stage. Any variables that have
604 * matching outputs already in the symbol table must have the same type and
607 foreach_list(node, consumer->ir) {
608 ir_variable *const input = ((ir_instruction *) node)->as_variable();
610 /* FINISHME: For geometry shaders, this should also look for inout
611 * FINISHME: variables.
613 if ((input == NULL) || (input->mode != ir_var_in))
616 ir_variable *const output = parameters.get_variable(input->name);
617 if (output != NULL) {
618 /* Check that the types match between stages.
620 if (input->type != output->type) {
621 /* There is a bit of a special case for gl_TexCoord. This
622 * built-in is unsized by default. Applications that variable
623 * access it must redeclare it with a size. There is some
624 * language in the GLSL spec that implies the fragment shader
625 * and vertex shader do not have to agree on this size. Other
626 * driver behave this way, and one or two applications seem to
629 * Neither declaration needs to be modified here because the array
630 * sizes are fixed later when update_array_sizes is called.
632 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
634 * "Unlike user-defined varying variables, the built-in
635 * varying variables don't have a strict one-to-one
636 * correspondence between the vertex language and the
637 * fragment language."
639 if (!output->type->is_array()
640 || (strncmp("gl_", output->name, 3) != 0)) {
642 "%s shader output `%s' declared as type `%s', "
643 "but %s shader input declared as type `%s'\n",
644 producer_stage, output->name,
646 consumer_stage, input->type->name);
651 /* Check that all of the qualifiers match between stages.
653 if (input->centroid != output->centroid) {
655 "%s shader output `%s' %s centroid qualifier, "
656 "but %s shader input %s centroid qualifier\n",
659 (output->centroid) ? "has" : "lacks",
661 (input->centroid) ? "has" : "lacks");
665 if (input->invariant != output->invariant) {
667 "%s shader output `%s' %s invariant qualifier, "
668 "but %s shader input %s invariant qualifier\n",
671 (output->invariant) ? "has" : "lacks",
673 (input->invariant) ? "has" : "lacks");
677 if (input->interpolation != output->interpolation) {
679 "%s shader output `%s' specifies %s "
680 "interpolation qualifier, "
681 "but %s shader input specifies %s "
682 "interpolation qualifier\n",
685 output->interpolation_string(),
687 input->interpolation_string());
698 * Populates a shaders symbol table with all global declarations
701 populate_symbol_table(gl_shader *sh)
703 sh->symbols = new(sh) glsl_symbol_table;
705 foreach_list(node, sh->ir) {
706 ir_instruction *const inst = (ir_instruction *) node;
710 if ((func = inst->as_function()) != NULL) {
711 sh->symbols->add_function(func);
712 } else if ((var = inst->as_variable()) != NULL) {
713 sh->symbols->add_variable(var);
720 * Remap variables referenced in an instruction tree
722 * This is used when instruction trees are cloned from one shader and placed in
723 * another. These trees will contain references to \c ir_variable nodes that
724 * do not exist in the target shader. This function finds these \c ir_variable
725 * references and replaces the references with matching variables in the target
728 * If there is no matching variable in the target shader, a clone of the
729 * \c ir_variable is made and added to the target shader. The new variable is
730 * added to \b both the instruction stream and the symbol table.
732 * \param inst IR tree that is to be processed.
733 * \param symbols Symbol table containing global scope symbols in the
735 * \param instructions Instruction stream where new variable declarations
739 remap_variables(ir_instruction *inst, struct gl_shader *target,
742 class remap_visitor : public ir_hierarchical_visitor {
744 remap_visitor(struct gl_shader *target,
747 this->target = target;
748 this->symbols = target->symbols;
749 this->instructions = target->ir;
753 virtual ir_visitor_status visit(ir_dereference_variable *ir)
755 if (ir->var->mode == ir_var_temporary) {
756 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
760 return visit_continue;
763 ir_variable *const existing =
764 this->symbols->get_variable(ir->var->name);
765 if (existing != NULL)
768 ir_variable *copy = ir->var->clone(this->target, NULL);
770 this->symbols->add_variable(copy);
771 this->instructions->push_head(copy);
775 return visit_continue;
779 struct gl_shader *target;
780 glsl_symbol_table *symbols;
781 exec_list *instructions;
785 remap_visitor v(target, temps);
792 * Move non-declarations from one instruction stream to another
794 * The intended usage pattern of this function is to pass the pointer to the
795 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
796 * pointer) for \c last and \c false for \c make_copies on the first
797 * call. Successive calls pass the return value of the previous call for
798 * \c last and \c true for \c make_copies.
800 * \param instructions Source instruction stream
801 * \param last Instruction after which new instructions should be
802 * inserted in the target instruction stream
803 * \param make_copies Flag selecting whether instructions in \c instructions
804 * should be copied (via \c ir_instruction::clone) into the
805 * target list or moved.
808 * The new "last" instruction in the target instruction stream. This pointer
809 * is suitable for use as the \c last parameter of a later call to this
813 move_non_declarations(exec_list *instructions, exec_node *last,
814 bool make_copies, gl_shader *target)
816 hash_table *temps = NULL;
819 temps = hash_table_ctor(0, hash_table_pointer_hash,
820 hash_table_pointer_compare);
822 foreach_list_safe(node, instructions) {
823 ir_instruction *inst = (ir_instruction *) node;
825 if (inst->as_function())
828 ir_variable *var = inst->as_variable();
829 if ((var != NULL) && (var->mode != ir_var_temporary))
832 assert(inst->as_assignment()
833 || ((var != NULL) && (var->mode == ir_var_temporary)));
836 inst = inst->clone(target, NULL);
839 hash_table_insert(temps, inst, var);
841 remap_variables(inst, target, temps);
846 last->insert_after(inst);
851 hash_table_dtor(temps);
857 * Get the function signature for main from a shader
859 static ir_function_signature *
860 get_main_function_signature(gl_shader *sh)
862 ir_function *const f = sh->symbols->get_function("main");
864 exec_list void_parameters;
866 /* Look for the 'void main()' signature and ensure that it's defined.
867 * This keeps the linker from accidentally pick a shader that just
868 * contains a prototype for main.
870 * We don't have to check for multiple definitions of main (in multiple
871 * shaders) because that would have already been caught above.
873 ir_function_signature *sig = f->matching_signature(&void_parameters);
874 if ((sig != NULL) && sig->is_defined) {
884 * This class is only used in link_intrastage_shaders() below but declaring
885 * it inside that function leads to compiler warnings with some versions of
888 class array_sizing_visitor : public ir_hierarchical_visitor {
890 virtual ir_visitor_status visit(ir_variable *var)
892 if (var->type->is_array() && (var->type->length == 0)) {
893 const glsl_type *type =
894 glsl_type::get_array_instance(var->type->fields.array,
895 var->max_array_access + 1);
896 assert(type != NULL);
899 return visit_continue;
905 * Combine a group of shaders for a single stage to generate a linked shader
908 * If this function is supplied a single shader, it is cloned, and the new
909 * shader is returned.
911 static struct gl_shader *
912 link_intrastage_shaders(void *mem_ctx,
913 struct gl_context *ctx,
914 struct gl_shader_program *prog,
915 struct gl_shader **shader_list,
916 unsigned num_shaders)
918 /* Check that global variables defined in multiple shaders are consistent.
920 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
923 /* Check that there is only a single definition of each function signature
924 * across all shaders.
926 for (unsigned i = 0; i < (num_shaders - 1); i++) {
927 foreach_list(node, shader_list[i]->ir) {
928 ir_function *const f = ((ir_instruction *) node)->as_function();
933 for (unsigned j = i + 1; j < num_shaders; j++) {
934 ir_function *const other =
935 shader_list[j]->symbols->get_function(f->name);
937 /* If the other shader has no function (and therefore no function
938 * signatures) with the same name, skip to the next shader.
943 foreach_iter (exec_list_iterator, iter, *f) {
944 ir_function_signature *sig =
945 (ir_function_signature *) iter.get();
947 if (!sig->is_defined || sig->is_builtin)
950 ir_function_signature *other_sig =
951 other->exact_matching_signature(& sig->parameters);
953 if ((other_sig != NULL) && other_sig->is_defined
954 && !other_sig->is_builtin) {
955 linker_error(prog, "function `%s' is multiply defined",
964 /* Find the shader that defines main, and make a clone of it.
966 * Starting with the clone, search for undefined references. If one is
967 * found, find the shader that defines it. Clone the reference and add
968 * it to the shader. Repeat until there are no undefined references or
969 * until a reference cannot be resolved.
971 gl_shader *main = NULL;
972 for (unsigned i = 0; i < num_shaders; i++) {
973 if (get_main_function_signature(shader_list[i]) != NULL) {
974 main = shader_list[i];
980 linker_error(prog, "%s shader lacks `main'\n",
981 (shader_list[0]->Type == GL_VERTEX_SHADER)
982 ? "vertex" : "fragment");
986 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
987 linked->ir = new(linked) exec_list;
988 clone_ir_list(mem_ctx, linked->ir, main->ir);
990 populate_symbol_table(linked);
992 /* The a pointer to the main function in the final linked shader (i.e., the
993 * copy of the original shader that contained the main function).
995 ir_function_signature *const main_sig = get_main_function_signature(linked);
997 /* Move any instructions other than variable declarations or function
998 * declarations into main.
1000 exec_node *insertion_point =
1001 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1004 for (unsigned i = 0; i < num_shaders; i++) {
1005 if (shader_list[i] == main)
1008 insertion_point = move_non_declarations(shader_list[i]->ir,
1009 insertion_point, true, linked);
1012 /* Resolve initializers for global variables in the linked shader.
1014 unsigned num_linking_shaders = num_shaders;
1015 for (unsigned i = 0; i < num_shaders; i++)
1016 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1018 gl_shader **linking_shaders =
1019 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1021 memcpy(linking_shaders, shader_list,
1022 sizeof(linking_shaders[0]) * num_shaders);
1024 unsigned idx = num_shaders;
1025 for (unsigned i = 0; i < num_shaders; i++) {
1026 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1027 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1028 idx += shader_list[i]->num_builtins_to_link;
1031 assert(idx == num_linking_shaders);
1033 if (!link_function_calls(prog, linked, linking_shaders,
1034 num_linking_shaders)) {
1035 ctx->Driver.DeleteShader(ctx, linked);
1039 free(linking_shaders);
1042 /* At this point linked should contain all of the linked IR, so
1043 * validate it to make sure nothing went wrong.
1046 validate_ir_tree(linked->ir);
1049 /* Make a pass over all variable declarations to ensure that arrays with
1050 * unspecified sizes have a size specified. The size is inferred from the
1051 * max_array_access field.
1053 if (linked != NULL) {
1054 array_sizing_visitor v;
1063 * Update the sizes of linked shader uniform arrays to the maximum
1066 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1068 * If one or more elements of an array are active,
1069 * GetActiveUniform will return the name of the array in name,
1070 * subject to the restrictions listed above. The type of the array
1071 * is returned in type. The size parameter contains the highest
1072 * array element index used, plus one. The compiler or linker
1073 * determines the highest index used. There will be only one
1074 * active uniform reported by the GL per uniform array.
1078 update_array_sizes(struct gl_shader_program *prog)
1080 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1081 if (prog->_LinkedShaders[i] == NULL)
1084 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1085 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1087 if ((var == NULL) || (var->mode != ir_var_uniform &&
1088 var->mode != ir_var_in &&
1089 var->mode != ir_var_out) ||
1090 !var->type->is_array())
1093 unsigned int size = var->max_array_access;
1094 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1095 if (prog->_LinkedShaders[j] == NULL)
1098 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1099 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1103 if (strcmp(var->name, other_var->name) == 0 &&
1104 other_var->max_array_access > size) {
1105 size = other_var->max_array_access;
1110 if (size + 1 != var->type->fields.array->length) {
1111 /* If this is a built-in uniform (i.e., it's backed by some
1112 * fixed-function state), adjust the number of state slots to
1113 * match the new array size. The number of slots per array entry
1114 * is not known. It seems safe to assume that the total number of
1115 * slots is an integer multiple of the number of array elements.
1116 * Determine the number of slots per array element by dividing by
1117 * the old (total) size.
1119 if (var->num_state_slots > 0) {
1120 var->num_state_slots = (size + 1)
1121 * (var->num_state_slots / var->type->length);
1124 var->type = glsl_type::get_array_instance(var->type->fields.array,
1126 /* FINISHME: We should update the types of array
1127 * dereferences of this variable now.
1135 * Find a contiguous set of available bits in a bitmask.
1137 * \param used_mask Bits representing used (1) and unused (0) locations
1138 * \param needed_count Number of contiguous bits needed.
1141 * Base location of the available bits on success or -1 on failure.
1144 find_available_slots(unsigned used_mask, unsigned needed_count)
1146 unsigned needed_mask = (1 << needed_count) - 1;
1147 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1149 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1150 * cannot optimize possibly infinite loops" for the loop below.
1152 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1155 for (int i = 0; i <= max_bit_to_test; i++) {
1156 if ((needed_mask & ~used_mask) == needed_mask)
1167 * Assign locations for either VS inputs for FS outputs
1169 * \param prog Shader program whose variables need locations assigned
1170 * \param target_index Selector for the program target to receive location
1171 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1172 * \c MESA_SHADER_FRAGMENT.
1173 * \param max_index Maximum number of generic locations. This corresponds
1174 * to either the maximum number of draw buffers or the
1175 * maximum number of generic attributes.
1178 * If locations are successfully assigned, true is returned. Otherwise an
1179 * error is emitted to the shader link log and false is returned.
1182 assign_attribute_or_color_locations(gl_shader_program *prog,
1183 unsigned target_index,
1186 /* Mark invalid locations as being used.
1188 unsigned used_locations = (max_index >= 32)
1189 ? ~0 : ~((1 << max_index) - 1);
1191 assert((target_index == MESA_SHADER_VERTEX)
1192 || (target_index == MESA_SHADER_FRAGMENT));
1194 gl_shader *const sh = prog->_LinkedShaders[target_index];
1198 /* Operate in a total of four passes.
1200 * 1. Invalidate the location assignments for all vertex shader inputs.
1202 * 2. Assign locations for inputs that have user-defined (via
1203 * glBindVertexAttribLocation) locations and outputs that have
1204 * user-defined locations (via glBindFragDataLocation).
1206 * 3. Sort the attributes without assigned locations by number of slots
1207 * required in decreasing order. Fragmentation caused by attribute
1208 * locations assigned by the application may prevent large attributes
1209 * from having enough contiguous space.
1211 * 4. Assign locations to any inputs without assigned locations.
1214 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1215 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1217 const enum ir_variable_mode direction =
1218 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1221 link_invalidate_variable_locations(sh, direction, generic_base);
1223 /* Temporary storage for the set of attributes that need locations assigned.
1229 /* Used below in the call to qsort. */
1230 static int compare(const void *a, const void *b)
1232 const temp_attr *const l = (const temp_attr *) a;
1233 const temp_attr *const r = (const temp_attr *) b;
1235 /* Reversed because we want a descending order sort below. */
1236 return r->slots - l->slots;
1240 unsigned num_attr = 0;
1242 foreach_list(node, sh->ir) {
1243 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1245 if ((var == NULL) || (var->mode != (unsigned) direction))
1248 if (var->explicit_location) {
1249 if ((var->location >= (int)(max_index + generic_base))
1250 || (var->location < 0)) {
1252 "invalid explicit location %d specified for `%s'\n",
1254 ? var->location : var->location - generic_base,
1258 } else if (target_index == MESA_SHADER_VERTEX) {
1261 if (prog->AttributeBindings->get(binding, var->name)) {
1262 assert(binding >= VERT_ATTRIB_GENERIC0);
1263 var->location = binding;
1265 } else if (target_index == MESA_SHADER_FRAGMENT) {
1268 if (prog->FragDataBindings->get(binding, var->name)) {
1269 assert(binding >= FRAG_RESULT_DATA0);
1270 var->location = binding;
1274 /* If the variable is not a built-in and has a location statically
1275 * assigned in the shader (presumably via a layout qualifier), make sure
1276 * that it doesn't collide with other assigned locations. Otherwise,
1277 * add it to the list of variables that need linker-assigned locations.
1279 const unsigned slots = count_attribute_slots(var->type);
1280 if (var->location != -1) {
1281 if (var->location >= generic_base) {
1282 /* From page 61 of the OpenGL 4.0 spec:
1284 * "LinkProgram will fail if the attribute bindings assigned
1285 * by BindAttribLocation do not leave not enough space to
1286 * assign a location for an active matrix attribute or an
1287 * active attribute array, both of which require multiple
1288 * contiguous generic attributes."
1290 * Previous versions of the spec contain similar language but omit
1291 * the bit about attribute arrays.
1293 * Page 61 of the OpenGL 4.0 spec also says:
1295 * "It is possible for an application to bind more than one
1296 * attribute name to the same location. This is referred to as
1297 * aliasing. This will only work if only one of the aliased
1298 * attributes is active in the executable program, or if no
1299 * path through the shader consumes more than one attribute of
1300 * a set of attributes aliased to the same location. A link
1301 * error can occur if the linker determines that every path
1302 * through the shader consumes multiple aliased attributes,
1303 * but implementations are not required to generate an error
1306 * These two paragraphs are either somewhat contradictory, or I
1307 * don't fully understand one or both of them.
1309 /* FINISHME: The code as currently written does not support
1310 * FINISHME: attribute location aliasing (see comment above).
1312 /* Mask representing the contiguous slots that will be used by
1315 const unsigned attr = var->location - generic_base;
1316 const unsigned use_mask = (1 << slots) - 1;
1318 /* Generate a link error if the set of bits requested for this
1319 * attribute overlaps any previously allocated bits.
1321 if ((~(use_mask << attr) & used_locations) != used_locations) {
1323 "insufficient contiguous attribute locations "
1324 "available for vertex shader input `%s'",
1329 used_locations |= (use_mask << attr);
1335 to_assign[num_attr].slots = slots;
1336 to_assign[num_attr].var = var;
1340 /* If all of the attributes were assigned locations by the application (or
1341 * are built-in attributes with fixed locations), return early. This should
1342 * be the common case.
1347 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1349 if (target_index == MESA_SHADER_VERTEX) {
1350 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1351 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1352 * reserved to prevent it from being automatically allocated below.
1354 find_deref_visitor find("gl_Vertex");
1356 if (find.variable_found())
1357 used_locations |= (1 << 0);
1360 for (unsigned i = 0; i < num_attr; i++) {
1361 /* Mask representing the contiguous slots that will be used by this
1364 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1366 int location = find_available_slots(used_locations, to_assign[i].slots);
1369 const char *const string = (target_index == MESA_SHADER_VERTEX)
1370 ? "vertex shader input" : "fragment shader output";
1373 "insufficient contiguous attribute locations "
1374 "available for %s `%s'",
1375 string, to_assign[i].var->name);
1379 to_assign[i].var->location = generic_base + location;
1380 used_locations |= (use_mask << location);
1388 * Demote shader inputs and outputs that are not used in other stages
1391 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1393 foreach_list(node, sh->ir) {
1394 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1396 if ((var == NULL) || (var->mode != int(mode)))
1399 /* A shader 'in' or 'out' variable is only really an input or output if
1400 * its value is used by other shader stages. This will cause the variable
1401 * to have a location assigned.
1403 if (var->location == -1) {
1404 var->mode = ir_var_auto;
1411 * Data structure tracking information about a transform feedback declaration
1414 class tfeedback_decl
1417 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1418 const void *mem_ctx, const char *input);
1419 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1420 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1421 ir_variable *output_var);
1422 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
1423 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
1424 struct gl_transform_feedback_info *info, unsigned buffer,
1425 unsigned varying, const unsigned max_outputs) const;
1429 * True if assign_location() has been called for this object.
1431 bool is_assigned() const
1433 return this->location != -1;
1437 * Determine whether this object refers to the variable var.
1439 bool matches_var(ir_variable *var) const
1441 if (this->is_clip_distance_mesa)
1442 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1444 return strcmp(var->name, this->var_name) == 0;
1448 * The total number of varying components taken up by this variable. Only
1449 * valid if is_assigned() is true.
1451 unsigned num_components() const
1453 if (this->is_clip_distance_mesa)
1456 return this->vector_elements * this->matrix_columns * this->size;
1461 * The name that was supplied to glTransformFeedbackVaryings. Used for
1462 * error reporting and glGetTransformFeedbackVarying().
1464 const char *orig_name;
1467 * The name of the variable, parsed from orig_name.
1469 const char *var_name;
1472 * True if the declaration in orig_name represents an array.
1474 bool is_subscripted;
1477 * If is_subscripted is true, the subscript that was specified in orig_name.
1479 unsigned array_subscript;
1482 * True if the variable is gl_ClipDistance and the driver lowers
1483 * gl_ClipDistance to gl_ClipDistanceMESA.
1485 bool is_clip_distance_mesa;
1488 * The vertex shader output location that the linker assigned for this
1489 * variable. -1 if a location hasn't been assigned yet.
1494 * If location != -1, the number of vector elements in this variable, or 1
1495 * if this variable is a scalar.
1497 unsigned vector_elements;
1500 * If location != -1, the number of matrix columns in this variable, or 1
1501 * if this variable is not a matrix.
1503 unsigned matrix_columns;
1505 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1509 * If location != -1, the size that should be returned by
1510 * glGetTransformFeedbackVarying().
1517 * Initialize this object based on a string that was passed to
1518 * glTransformFeedbackVaryings. If there is a parse error, the error is
1519 * reported using linker_error(), and false is returned.
1522 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1523 const void *mem_ctx, const char *input)
1525 /* We don't have to be pedantic about what is a valid GLSL variable name,
1526 * because any variable with an invalid name can't exist in the IR anyway.
1529 this->location = -1;
1530 this->orig_name = input;
1531 this->is_clip_distance_mesa = false;
1533 const char *bracket = strrchr(input, '[');
1536 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
1537 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
1538 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1541 this->is_subscripted = true;
1543 this->var_name = ralloc_strdup(mem_ctx, input);
1544 this->is_subscripted = false;
1547 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1548 * class must behave specially to account for the fact that gl_ClipDistance
1549 * is converted from a float[8] to a vec4[2].
1551 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1552 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1553 this->is_clip_distance_mesa = true;
1561 * Determine whether two tfeedback_decl objects refer to the same variable and
1562 * array index (if applicable).
1565 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1567 if (strcmp(x.var_name, y.var_name) != 0)
1569 if (x.is_subscripted != y.is_subscripted)
1571 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1578 * Assign a location for this tfeedback_decl object based on the location
1579 * assignment in output_var.
1581 * If an error occurs, the error is reported through linker_error() and false
1585 tfeedback_decl::assign_location(struct gl_context *ctx,
1586 struct gl_shader_program *prog,
1587 ir_variable *output_var)
1589 if (output_var->type->is_array()) {
1590 /* Array variable */
1591 const unsigned matrix_cols =
1592 output_var->type->fields.array->matrix_columns;
1593 unsigned actual_array_size = this->is_clip_distance_mesa ?
1594 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
1596 if (this->is_subscripted) {
1597 /* Check array bounds. */
1598 if (this->array_subscript >= actual_array_size) {
1599 linker_error(prog, "Transform feedback varying %s has index "
1600 "%i, but the array size is %u.",
1601 this->orig_name, this->array_subscript,
1605 if (this->is_clip_distance_mesa) {
1607 output_var->location + this->array_subscript / 4;
1610 output_var->location + this->array_subscript * matrix_cols;
1614 this->location = output_var->location;
1615 this->size = actual_array_size;
1617 this->vector_elements = output_var->type->fields.array->vector_elements;
1618 this->matrix_columns = matrix_cols;
1619 if (this->is_clip_distance_mesa)
1620 this->type = GL_FLOAT;
1622 this->type = output_var->type->fields.array->gl_type;
1624 /* Regular variable (scalar, vector, or matrix) */
1625 if (this->is_subscripted) {
1626 linker_error(prog, "Transform feedback varying %s requested, "
1627 "but %s is not an array.",
1628 this->orig_name, this->var_name);
1631 this->location = output_var->location;
1633 this->vector_elements = output_var->type->vector_elements;
1634 this->matrix_columns = output_var->type->matrix_columns;
1635 this->type = output_var->type->gl_type;
1638 /* From GL_EXT_transform_feedback:
1639 * A program will fail to link if:
1641 * * the total number of components to capture in any varying
1642 * variable in <varyings> is greater than the constant
1643 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1644 * buffer mode is SEPARATE_ATTRIBS_EXT;
1646 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1647 this->num_components() >
1648 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1649 linker_error(prog, "Transform feedback varying %s exceeds "
1650 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1660 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1663 if (!this->is_assigned()) {
1664 /* From GL_EXT_transform_feedback:
1665 * A program will fail to link if:
1667 * * any variable name specified in the <varyings> array is not
1668 * declared as an output in the geometry shader (if present) or
1669 * the vertex shader (if no geometry shader is present);
1671 linker_error(prog, "Transform feedback varying %s undeclared.",
1676 unsigned translated_size = this->size;
1677 if (this->is_clip_distance_mesa)
1678 translated_size = (translated_size + 3) / 4;
1680 *count += translated_size * this->matrix_columns;
1687 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1689 * If an error occurs, the error is reported through linker_error() and false
1693 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1694 struct gl_transform_feedback_info *info,
1696 unsigned varying, const unsigned max_outputs) const
1698 /* From GL_EXT_transform_feedback:
1699 * A program will fail to link if:
1701 * * the total number of components to capture is greater than
1702 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1703 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1705 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1706 info->BufferStride[buffer] + this->num_components() >
1707 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1708 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1709 "limit has been exceeded.");
1713 unsigned translated_size = this->size;
1714 if (this->is_clip_distance_mesa)
1715 translated_size = (translated_size + 3) / 4;
1716 unsigned components_so_far = 0;
1717 for (unsigned index = 0; index < translated_size; ++index) {
1718 for (unsigned v = 0; v < this->matrix_columns; ++v) {
1719 unsigned num_components = this->vector_elements;
1720 assert(info->NumOutputs < max_outputs);
1721 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1722 if (this->is_clip_distance_mesa) {
1723 if (this->is_subscripted) {
1725 info->Outputs[info->NumOutputs].ComponentOffset =
1726 this->array_subscript % 4;
1728 num_components = MIN2(4, this->size - components_so_far);
1731 info->Outputs[info->NumOutputs].OutputRegister =
1732 this->location + v + index * this->matrix_columns;
1733 info->Outputs[info->NumOutputs].NumComponents = num_components;
1734 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1735 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
1737 info->BufferStride[buffer] += num_components;
1738 components_so_far += num_components;
1741 assert(components_so_far == this->num_components());
1743 info->Varyings[varying].Name = ralloc_strdup(prog, this->orig_name);
1744 info->Varyings[varying].Type = this->type;
1745 info->Varyings[varying].Size = this->size;
1753 * Parse all the transform feedback declarations that were passed to
1754 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1756 * If an error occurs, the error is reported through linker_error() and false
1760 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1761 const void *mem_ctx, unsigned num_names,
1762 char **varying_names, tfeedback_decl *decls)
1764 for (unsigned i = 0; i < num_names; ++i) {
1765 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1767 /* From GL_EXT_transform_feedback:
1768 * A program will fail to link if:
1770 * * any two entries in the <varyings> array specify the same varying
1773 * We interpret this to mean "any two entries in the <varyings> array
1774 * specify the same varying variable and array index", since transform
1775 * feedback of arrays would be useless otherwise.
1777 for (unsigned j = 0; j < i; ++j) {
1778 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1779 linker_error(prog, "Transform feedback varying %s specified "
1780 "more than once.", varying_names[i]);
1790 * Assign a location for a variable that is produced in one pipeline stage
1791 * (the "producer") and consumed in the next stage (the "consumer").
1793 * \param input_var is the input variable declaration in the consumer.
1795 * \param output_var is the output variable declaration in the producer.
1797 * \param input_index is the counter that keeps track of assigned input
1798 * locations in the consumer.
1800 * \param output_index is the counter that keeps track of assigned output
1801 * locations in the producer.
1803 * It is permissible for \c input_var to be NULL (this happens if a variable
1804 * is output by the producer and consumed by transform feedback, but not
1805 * consumed by the consumer).
1807 * If the variable has already been assigned a location, this function has no
1811 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1812 unsigned *input_index, unsigned *output_index)
1814 if (output_var->location != -1) {
1815 /* Location already assigned. */
1820 assert(input_var->location == -1);
1821 input_var->location = *input_index;
1824 output_var->location = *output_index;
1826 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1827 assert(!output_var->type->is_record());
1829 if (output_var->type->is_array()) {
1830 const unsigned slots = output_var->type->length
1831 * output_var->type->fields.array->matrix_columns;
1833 *output_index += slots;
1834 *input_index += slots;
1836 const unsigned slots = output_var->type->matrix_columns;
1838 *output_index += slots;
1839 *input_index += slots;
1845 * Assign locations for all variables that are produced in one pipeline stage
1846 * (the "producer") and consumed in the next stage (the "consumer").
1848 * Variables produced by the producer may also be consumed by transform
1851 * \param num_tfeedback_decls is the number of declarations indicating
1852 * variables that may be consumed by transform feedback.
1854 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1855 * representing the result of parsing the strings passed to
1856 * glTransformFeedbackVaryings(). assign_location() will be called for
1857 * each of these objects that matches one of the outputs of the
1860 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1861 * be NULL. In this case, varying locations are assigned solely based on the
1862 * requirements of transform feedback.
1865 assign_varying_locations(struct gl_context *ctx,
1866 struct gl_shader_program *prog,
1867 gl_shader *producer, gl_shader *consumer,
1868 unsigned num_tfeedback_decls,
1869 tfeedback_decl *tfeedback_decls)
1871 /* FINISHME: Set dynamically when geometry shader support is added. */
1872 unsigned output_index = VERT_RESULT_VAR0;
1873 unsigned input_index = FRAG_ATTRIB_VAR0;
1875 /* Operate in a total of three passes.
1877 * 1. Assign locations for any matching inputs and outputs.
1879 * 2. Mark output variables in the producer that do not have locations as
1880 * not being outputs. This lets the optimizer eliminate them.
1882 * 3. Mark input variables in the consumer that do not have locations as
1883 * not being inputs. This lets the optimizer eliminate them.
1886 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1888 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1890 foreach_list(node, producer->ir) {
1891 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1893 if ((output_var == NULL) || (output_var->mode != ir_var_out))
1896 ir_variable *input_var =
1897 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
1899 if (input_var && input_var->mode != ir_var_in)
1903 assign_varying_location(input_var, output_var, &input_index,
1907 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1908 if (!tfeedback_decls[i].is_assigned() &&
1909 tfeedback_decls[i].matches_var(output_var)) {
1910 if (output_var->location == -1) {
1911 assign_varying_location(input_var, output_var, &input_index,
1914 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
1920 unsigned varying_vectors = 0;
1923 foreach_list(node, consumer->ir) {
1924 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1926 if ((var == NULL) || (var->mode != ir_var_in))
1929 if (var->location == -1) {
1930 if (prog->Version <= 120) {
1931 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1933 * Only those varying variables used (i.e. read) in
1934 * the fragment shader executable must be written to
1935 * by the vertex shader executable; declaring
1936 * superfluous varying variables in a vertex shader is
1939 * We interpret this text as meaning that the VS must
1940 * write the variable for the FS to read it. See
1941 * "glsl1-varying read but not written" in piglit.
1944 linker_error(prog, "fragment shader varying %s not written "
1945 "by vertex shader\n.", var->name);
1948 /* An 'in' variable is only really a shader input if its
1949 * value is written by the previous stage.
1951 var->mode = ir_var_auto;
1953 /* The packing rules are used for vertex shader inputs are also
1954 * used for fragment shader inputs.
1956 varying_vectors += count_attribute_slots(var->type);
1961 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
1962 if (varying_vectors > ctx->Const.MaxVarying) {
1963 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1964 linker_warning(prog, "shader uses too many varying vectors "
1965 "(%u > %u), but the driver will try to optimize "
1966 "them out; this is non-portable out-of-spec "
1968 varying_vectors, ctx->Const.MaxVarying);
1970 linker_error(prog, "shader uses too many varying vectors "
1972 varying_vectors, ctx->Const.MaxVarying);
1977 const unsigned float_components = varying_vectors * 4;
1978 if (float_components > ctx->Const.MaxVarying * 4) {
1979 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1980 linker_warning(prog, "shader uses too many varying components "
1981 "(%u > %u), but the driver will try to optimize "
1982 "them out; this is non-portable out-of-spec "
1984 float_components, ctx->Const.MaxVarying * 4);
1986 linker_error(prog, "shader uses too many varying components "
1988 float_components, ctx->Const.MaxVarying * 4);
1999 * Store transform feedback location assignments into
2000 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2002 * If an error occurs, the error is reported through linker_error() and false
2006 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2007 unsigned num_tfeedback_decls,
2008 tfeedback_decl *tfeedback_decls)
2010 bool separate_attribs_mode =
2011 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
2013 ralloc_free(prog->LinkedTransformFeedback.Varyings);
2014 ralloc_free(prog->LinkedTransformFeedback.Outputs);
2016 memset(&prog->LinkedTransformFeedback, 0,
2017 sizeof(prog->LinkedTransformFeedback));
2019 prog->LinkedTransformFeedback.NumBuffers =
2020 separate_attribs_mode ? num_tfeedback_decls : 1;
2022 prog->LinkedTransformFeedback.Varyings =
2024 struct gl_transform_feedback_varying_info,
2025 num_tfeedback_decls);
2027 unsigned num_outputs = 0;
2028 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2029 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2032 prog->LinkedTransformFeedback.Outputs =
2034 struct gl_transform_feedback_output,
2037 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2038 unsigned buffer = separate_attribs_mode ? i : 0;
2039 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
2040 buffer, i, num_outputs))
2043 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2049 * Store the gl_FragDepth layout in the gl_shader_program struct.
2052 store_fragdepth_layout(struct gl_shader_program *prog)
2054 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2058 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2060 /* We don't look up the gl_FragDepth symbol directly because if
2061 * gl_FragDepth is not used in the shader, it's removed from the IR.
2062 * However, the symbol won't be removed from the symbol table.
2064 * We're only interested in the cases where the variable is NOT removed
2067 foreach_list(node, ir) {
2068 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2070 if (var == NULL || var->mode != ir_var_out) {
2074 if (strcmp(var->name, "gl_FragDepth") == 0) {
2075 switch (var->depth_layout) {
2076 case ir_depth_layout_none:
2077 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2079 case ir_depth_layout_any:
2080 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2082 case ir_depth_layout_greater:
2083 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2085 case ir_depth_layout_less:
2086 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2088 case ir_depth_layout_unchanged:
2089 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2100 * Validate the resources used by a program versus the implementation limits
2103 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2105 static const char *const shader_names[MESA_SHADER_TYPES] = {
2106 "vertex", "fragment", "geometry"
2109 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2110 ctx->Const.MaxVertexTextureImageUnits,
2111 ctx->Const.MaxTextureImageUnits,
2112 ctx->Const.MaxGeometryTextureImageUnits
2115 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2116 ctx->Const.VertexProgram.MaxUniformComponents,
2117 ctx->Const.FragmentProgram.MaxUniformComponents,
2118 0 /* FINISHME: Geometry shaders. */
2121 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2122 struct gl_shader *sh = prog->_LinkedShaders[i];
2127 if (sh->num_samplers > max_samplers[i]) {
2128 linker_error(prog, "Too many %s shader texture samplers",
2132 if (sh->num_uniform_components > max_uniform_components[i]) {
2133 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2134 linker_warning(prog, "Too many %s shader uniform components, "
2135 "but the driver will try to optimize them out; "
2136 "this is non-portable out-of-spec behavior\n",
2139 linker_error(prog, "Too many %s shader uniform components",
2145 return prog->LinkStatus;
2149 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2151 tfeedback_decl *tfeedback_decls = NULL;
2152 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2154 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2156 prog->LinkStatus = false;
2157 prog->Validated = false;
2158 prog->_Used = false;
2160 if (prog->InfoLog != NULL)
2161 ralloc_free(prog->InfoLog);
2163 prog->InfoLog = ralloc_strdup(NULL, "");
2165 /* Separate the shaders into groups based on their type.
2167 struct gl_shader **vert_shader_list;
2168 unsigned num_vert_shaders = 0;
2169 struct gl_shader **frag_shader_list;
2170 unsigned num_frag_shaders = 0;
2172 vert_shader_list = (struct gl_shader **)
2173 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
2174 frag_shader_list = &vert_shader_list[prog->NumShaders];
2176 unsigned min_version = UINT_MAX;
2177 unsigned max_version = 0;
2178 for (unsigned i = 0; i < prog->NumShaders; i++) {
2179 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2180 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2182 switch (prog->Shaders[i]->Type) {
2183 case GL_VERTEX_SHADER:
2184 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2187 case GL_FRAGMENT_SHADER:
2188 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2191 case GL_GEOMETRY_SHADER:
2192 /* FINISHME: Support geometry shaders. */
2193 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2198 /* Previous to GLSL version 1.30, different compilation units could mix and
2199 * match shading language versions. With GLSL 1.30 and later, the versions
2200 * of all shaders must match.
2202 assert(min_version >= 100);
2203 assert(max_version <= 140);
2204 if ((max_version >= 130 || min_version == 100)
2205 && min_version != max_version) {
2206 linker_error(prog, "all shaders must use same shading "
2207 "language version\n");
2211 prog->Version = max_version;
2213 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2214 if (prog->_LinkedShaders[i] != NULL)
2215 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2217 prog->_LinkedShaders[i] = NULL;
2220 /* Link all shaders for a particular stage and validate the result.
2222 if (num_vert_shaders > 0) {
2223 gl_shader *const sh =
2224 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2230 if (!validate_vertex_shader_executable(prog, sh))
2233 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2237 if (num_frag_shaders > 0) {
2238 gl_shader *const sh =
2239 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2245 if (!validate_fragment_shader_executable(prog, sh))
2248 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2252 /* Here begins the inter-stage linking phase. Some initial validation is
2253 * performed, then locations are assigned for uniforms, attributes, and
2256 if (cross_validate_uniforms(prog)) {
2259 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2260 if (prog->_LinkedShaders[prev] != NULL)
2264 /* Validate the inputs of each stage with the output of the preceding
2267 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2268 if (prog->_LinkedShaders[i] == NULL)
2271 if (!cross_validate_outputs_to_inputs(prog,
2272 prog->_LinkedShaders[prev],
2273 prog->_LinkedShaders[i]))
2279 prog->LinkStatus = true;
2282 /* Do common optimization before assigning storage for attributes,
2283 * uniforms, and varyings. Later optimization could possibly make
2284 * some of that unused.
2286 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2287 if (prog->_LinkedShaders[i] == NULL)
2290 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2291 if (!prog->LinkStatus)
2294 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2295 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2297 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2299 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
2303 /* FINISHME: The value of the max_attribute_index parameter is
2304 * FINISHME: implementation dependent based on the value of
2305 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2306 * FINISHME: at least 16, so hardcode 16 for now.
2308 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2312 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, ctx->Const.MaxDrawBuffers)) {
2317 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2318 if (prog->_LinkedShaders[prev] != NULL)
2322 if (num_tfeedback_decls != 0) {
2323 /* From GL_EXT_transform_feedback:
2324 * A program will fail to link if:
2326 * * the <count> specified by TransformFeedbackVaryingsEXT is
2327 * non-zero, but the program object has no vertex or geometry
2330 if (prev >= MESA_SHADER_FRAGMENT) {
2331 linker_error(prog, "Transform feedback varyings specified, but "
2332 "no vertex or geometry shader is present.");
2336 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2337 prog->TransformFeedback.NumVarying);
2338 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2339 prog->TransformFeedback.VaryingNames,
2344 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2345 if (prog->_LinkedShaders[i] == NULL)
2348 if (!assign_varying_locations(
2349 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2350 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2357 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2358 /* There was no fragment shader, but we still have to assign varying
2359 * locations for use by transform feedback.
2361 if (!assign_varying_locations(
2362 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2367 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2370 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2371 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2374 /* Eliminate code that is now dead due to unused vertex outputs being
2377 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2381 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2382 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2384 demote_shader_inputs_and_outputs(sh, ir_var_in);
2385 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2386 demote_shader_inputs_and_outputs(sh, ir_var_out);
2388 /* Eliminate code that is now dead due to unused geometry outputs being
2391 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2395 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2396 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2398 demote_shader_inputs_and_outputs(sh, ir_var_in);
2400 /* Eliminate code that is now dead due to unused fragment inputs being
2401 * demoted. This shouldn't actually do anything other than remove
2402 * declarations of the (now unused) global variables.
2404 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2408 update_array_sizes(prog);
2409 link_assign_uniform_locations(prog);
2410 store_fragdepth_layout(prog);
2412 if (!check_resources(ctx, prog))
2415 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2416 * present in a linked program. By checking for use of shading language
2417 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2419 if (!prog->InternalSeparateShader &&
2420 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
2421 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2422 linker_error(prog, "program lacks a vertex shader\n");
2423 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2424 linker_error(prog, "program lacks a fragment shader\n");
2428 /* FINISHME: Assign fragment shader output locations. */
2431 free(vert_shader_list);
2433 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2434 if (prog->_LinkedShaders[i] == NULL)
2437 /* Retain any live IR, but trash the rest. */
2438 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2440 /* The symbol table in the linked shaders may contain references to
2441 * variables that were removed (e.g., unused uniforms). Since it may
2442 * contain junk, there is no possible valid use. Delete it and set the
2445 delete prog->_LinkedShaders[i]->symbols;
2446 prog->_LinkedShaders[i]->symbols = NULL;
2449 ralloc_free(mem_ctx);