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>
75 #include "main/core.h"
76 #include "glsl_symbol_table.h"
79 #include "program/hash_table.h"
81 #include "ir_optimization.h"
84 #include "main/shaderobj.h"
88 * Visitor that determines whether or not a variable is ever written.
90 class find_assignment_visitor : public ir_hierarchical_visitor {
92 find_assignment_visitor(const char *name)
93 : name(name), found(false)
98 virtual ir_visitor_status visit_enter(ir_assignment *ir)
100 ir_variable *const var = ir->lhs->variable_referenced();
102 if (strcmp(name, var->name) == 0) {
107 return visit_continue_with_parent;
110 virtual ir_visitor_status visit_enter(ir_call *ir)
112 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
113 foreach_iter(exec_list_iterator, iter, *ir) {
114 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
115 ir_variable *sig_param = (ir_variable *)sig_iter.get();
117 if (sig_param->mode == ir_var_out ||
118 sig_param->mode == ir_var_inout) {
119 ir_variable *var = param_rval->variable_referenced();
120 if (var && strcmp(name, var->name) == 0) {
128 return visit_continue_with_parent;
131 bool variable_found()
137 const char *name; /**< Find writes to a variable with this name. */
138 bool found; /**< Was a write to the variable found? */
143 * Visitor that determines whether or not a variable is ever read.
145 class find_deref_visitor : public ir_hierarchical_visitor {
147 find_deref_visitor(const char *name)
148 : name(name), found(false)
153 virtual ir_visitor_status visit(ir_dereference_variable *ir)
155 if (strcmp(this->name, ir->var->name) == 0) {
160 return visit_continue;
163 bool variable_found() const
169 const char *name; /**< Find writes to a variable with this name. */
170 bool found; /**< Was a write to the variable found? */
175 linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
179 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
181 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
187 invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
190 foreach_list(node, sh->ir) {
191 ir_variable *const var = ((ir_instruction *) node)->as_variable();
193 if ((var == NULL) || (var->mode != (unsigned) mode))
196 /* Only assign locations for generic attributes / varyings / etc.
198 if ((var->location >= generic_base) && !var->explicit_location)
205 * Determine the number of attribute slots required for a particular type
207 * This code is here because it implements the language rules of a specific
208 * GLSL version. Since it's a property of the language and not a property of
209 * types in general, it doesn't really belong in glsl_type.
212 count_attribute_slots(const glsl_type *t)
214 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
216 * "A scalar input counts the same amount against this limit as a vec4,
217 * so applications may want to consider packing groups of four
218 * unrelated float inputs together into a vector to better utilize the
219 * capabilities of the underlying hardware. A matrix input will use up
220 * multiple locations. The number of locations used will equal the
221 * number of columns in the matrix."
223 * The spec does not explicitly say how arrays are counted. However, it
224 * should be safe to assume the total number of slots consumed by an array
225 * is the number of entries in the array multiplied by the number of slots
226 * consumed by a single element of the array.
230 return t->array_size() * count_attribute_slots(t->element_type());
233 return t->matrix_columns;
240 * Verify that a vertex shader executable meets all semantic requirements
242 * \param shader Vertex shader executable to be verified
245 validate_vertex_shader_executable(struct gl_shader_program *prog,
246 struct gl_shader *shader)
251 find_assignment_visitor find("gl_Position");
252 find.run(shader->ir);
253 if (!find.variable_found()) {
254 linker_error_printf(prog,
255 "vertex shader does not write to `gl_Position'\n");
264 * Verify that a fragment shader executable meets all semantic requirements
266 * \param shader Fragment shader executable to be verified
269 validate_fragment_shader_executable(struct gl_shader_program *prog,
270 struct gl_shader *shader)
275 find_assignment_visitor frag_color("gl_FragColor");
276 find_assignment_visitor frag_data("gl_FragData");
278 frag_color.run(shader->ir);
279 frag_data.run(shader->ir);
281 if (frag_color.variable_found() && frag_data.variable_found()) {
282 linker_error_printf(prog, "fragment shader writes to both "
283 "`gl_FragColor' and `gl_FragData'\n");
292 * Generate a string describing the mode of a variable
295 mode_string(const ir_variable *var)
299 return (var->read_only) ? "global constant" : "global variable";
301 case ir_var_uniform: return "uniform";
302 case ir_var_in: return "shader input";
303 case ir_var_out: return "shader output";
304 case ir_var_inout: return "shader inout";
306 case ir_var_temporary:
308 assert(!"Should not get here.");
309 return "invalid variable";
315 * Perform validation of global variables used across multiple shaders
318 cross_validate_globals(struct gl_shader_program *prog,
319 struct gl_shader **shader_list,
320 unsigned num_shaders,
323 /* Examine all of the uniforms in all of the shaders and cross validate
326 glsl_symbol_table variables;
327 for (unsigned i = 0; i < num_shaders; i++) {
328 if (shader_list[i] == NULL)
331 foreach_list(node, shader_list[i]->ir) {
332 ir_variable *const var = ((ir_instruction *) node)->as_variable();
337 if (uniforms_only && (var->mode != ir_var_uniform))
340 /* Don't cross validate temporaries that are at global scope. These
341 * will eventually get pulled into the shaders 'main'.
343 if (var->mode == ir_var_temporary)
346 /* If a global with this name has already been seen, verify that the
347 * new instance has the same type. In addition, if the globals have
348 * initializers, the values of the initializers must be the same.
350 ir_variable *const existing = variables.get_variable(var->name);
351 if (existing != NULL) {
352 if (var->type != existing->type) {
353 /* Consider the types to be "the same" if both types are arrays
354 * of the same type and one of the arrays is implicitly sized.
355 * In addition, set the type of the linked variable to the
356 * explicitly sized array.
358 if (var->type->is_array()
359 && existing->type->is_array()
360 && (var->type->fields.array == existing->type->fields.array)
361 && ((var->type->length == 0)
362 || (existing->type->length == 0))) {
363 if (existing->type->length == 0) {
364 existing->type = var->type;
365 existing->max_array_access =
366 MAX2(existing->max_array_access,
367 var->max_array_access);
370 linker_error_printf(prog, "%s `%s' declared as type "
371 "`%s' and type `%s'\n",
373 var->name, var->type->name,
374 existing->type->name);
379 if (var->explicit_location) {
380 if (existing->explicit_location
381 && (var->location != existing->location)) {
382 linker_error_printf(prog, "explicit locations for %s "
383 "`%s' have differing values\n",
384 mode_string(var), var->name);
388 existing->location = var->location;
389 existing->explicit_location = true;
392 /* FINISHME: Handle non-constant initializers.
394 if (var->constant_value != NULL) {
395 if (existing->constant_value != NULL) {
396 if (!var->constant_value->has_value(existing->constant_value)) {
397 linker_error_printf(prog, "initializers for %s "
398 "`%s' have differing values\n",
399 mode_string(var), var->name);
403 /* If the first-seen instance of a particular uniform did not
404 * have an initializer but a later instance does, copy the
405 * initializer to the version stored in the symbol table.
407 /* FINISHME: This is wrong. The constant_value field should
408 * FINISHME: not be modified! Imagine a case where a shader
409 * FINISHME: without an initializer is linked in two different
410 * FINISHME: programs with shaders that have differing
411 * FINISHME: initializers. Linking with the first will
412 * FINISHME: modify the shader, and linking with the second
413 * FINISHME: will fail.
415 existing->constant_value =
416 var->constant_value->clone(talloc_parent(existing), NULL);
419 if (existing->invariant != var->invariant) {
420 linker_error_printf(prog, "declarations for %s `%s' have "
421 "mismatching invariant qualifiers\n",
422 mode_string(var), var->name);
426 variables.add_variable(var);
435 * Perform validation of uniforms used across multiple shader stages
438 cross_validate_uniforms(struct gl_shader_program *prog)
440 return cross_validate_globals(prog, prog->_LinkedShaders,
441 MESA_SHADER_TYPES, true);
446 * Validate that outputs from one stage match inputs of another
449 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
450 gl_shader *producer, gl_shader *consumer)
452 glsl_symbol_table parameters;
453 /* FINISHME: Figure these out dynamically. */
454 const char *const producer_stage = "vertex";
455 const char *const consumer_stage = "fragment";
457 /* Find all shader outputs in the "producer" stage.
459 foreach_list(node, producer->ir) {
460 ir_variable *const var = ((ir_instruction *) node)->as_variable();
462 /* FINISHME: For geometry shaders, this should also look for inout
463 * FINISHME: variables.
465 if ((var == NULL) || (var->mode != ir_var_out))
468 parameters.add_variable(var);
472 /* Find all shader inputs in the "consumer" stage. Any variables that have
473 * matching outputs already in the symbol table must have the same type and
476 foreach_list(node, consumer->ir) {
477 ir_variable *const input = ((ir_instruction *) node)->as_variable();
479 /* FINISHME: For geometry shaders, this should also look for inout
480 * FINISHME: variables.
482 if ((input == NULL) || (input->mode != ir_var_in))
485 ir_variable *const output = parameters.get_variable(input->name);
486 if (output != NULL) {
487 /* Check that the types match between stages.
489 if (input->type != output->type) {
490 linker_error_printf(prog,
491 "%s shader output `%s' declared as "
492 "type `%s', but %s shader input declared "
494 producer_stage, output->name,
496 consumer_stage, input->type->name);
500 /* Check that all of the qualifiers match between stages.
502 if (input->centroid != output->centroid) {
503 linker_error_printf(prog,
504 "%s shader output `%s' %s centroid qualifier, "
505 "but %s shader input %s centroid qualifier\n",
508 (output->centroid) ? "has" : "lacks",
510 (input->centroid) ? "has" : "lacks");
514 if (input->invariant != output->invariant) {
515 linker_error_printf(prog,
516 "%s shader output `%s' %s invariant qualifier, "
517 "but %s shader input %s invariant qualifier\n",
520 (output->invariant) ? "has" : "lacks",
522 (input->invariant) ? "has" : "lacks");
526 if (input->interpolation != output->interpolation) {
527 linker_error_printf(prog,
528 "%s shader output `%s' specifies %s "
529 "interpolation qualifier, "
530 "but %s shader input specifies %s "
531 "interpolation qualifier\n",
534 output->interpolation_string(),
536 input->interpolation_string());
547 * Populates a shaders symbol table with all global declarations
550 populate_symbol_table(gl_shader *sh)
552 sh->symbols = new(sh) glsl_symbol_table;
554 foreach_list(node, sh->ir) {
555 ir_instruction *const inst = (ir_instruction *) node;
559 if ((func = inst->as_function()) != NULL) {
560 sh->symbols->add_function(func);
561 } else if ((var = inst->as_variable()) != NULL) {
562 sh->symbols->add_variable(var);
569 * Remap variables referenced in an instruction tree
571 * This is used when instruction trees are cloned from one shader and placed in
572 * another. These trees will contain references to \c ir_variable nodes that
573 * do not exist in the target shader. This function finds these \c ir_variable
574 * references and replaces the references with matching variables in the target
577 * If there is no matching variable in the target shader, a clone of the
578 * \c ir_variable is made and added to the target shader. The new variable is
579 * added to \b both the instruction stream and the symbol table.
581 * \param inst IR tree that is to be processed.
582 * \param symbols Symbol table containing global scope symbols in the
584 * \param instructions Instruction stream where new variable declarations
588 remap_variables(ir_instruction *inst, struct gl_shader *target,
591 class remap_visitor : public ir_hierarchical_visitor {
593 remap_visitor(struct gl_shader *target,
596 this->target = target;
597 this->symbols = target->symbols;
598 this->instructions = target->ir;
602 virtual ir_visitor_status visit(ir_dereference_variable *ir)
604 if (ir->var->mode == ir_var_temporary) {
605 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
609 return visit_continue;
612 ir_variable *const existing =
613 this->symbols->get_variable(ir->var->name);
614 if (existing != NULL)
617 ir_variable *copy = ir->var->clone(this->target, NULL);
619 this->symbols->add_variable(copy);
620 this->instructions->push_head(copy);
624 return visit_continue;
628 struct gl_shader *target;
629 glsl_symbol_table *symbols;
630 exec_list *instructions;
634 remap_visitor v(target, temps);
641 * Move non-declarations from one instruction stream to another
643 * The intended usage pattern of this function is to pass the pointer to the
644 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
645 * pointer) for \c last and \c false for \c make_copies on the first
646 * call. Successive calls pass the return value of the previous call for
647 * \c last and \c true for \c make_copies.
649 * \param instructions Source instruction stream
650 * \param last Instruction after which new instructions should be
651 * inserted in the target instruction stream
652 * \param make_copies Flag selecting whether instructions in \c instructions
653 * should be copied (via \c ir_instruction::clone) into the
654 * target list or moved.
657 * The new "last" instruction in the target instruction stream. This pointer
658 * is suitable for use as the \c last parameter of a later call to this
662 move_non_declarations(exec_list *instructions, exec_node *last,
663 bool make_copies, gl_shader *target)
665 hash_table *temps = NULL;
668 temps = hash_table_ctor(0, hash_table_pointer_hash,
669 hash_table_pointer_compare);
671 foreach_list_safe(node, instructions) {
672 ir_instruction *inst = (ir_instruction *) node;
674 if (inst->as_function())
677 ir_variable *var = inst->as_variable();
678 if ((var != NULL) && (var->mode != ir_var_temporary))
681 assert(inst->as_assignment()
682 || ((var != NULL) && (var->mode == ir_var_temporary)));
685 inst = inst->clone(target, NULL);
688 hash_table_insert(temps, inst, var);
690 remap_variables(inst, target, temps);
695 last->insert_after(inst);
700 hash_table_dtor(temps);
706 * Get the function signature for main from a shader
708 static ir_function_signature *
709 get_main_function_signature(gl_shader *sh)
711 ir_function *const f = sh->symbols->get_function("main");
713 exec_list void_parameters;
715 /* Look for the 'void main()' signature and ensure that it's defined.
716 * This keeps the linker from accidentally pick a shader that just
717 * contains a prototype for main.
719 * We don't have to check for multiple definitions of main (in multiple
720 * shaders) because that would have already been caught above.
722 ir_function_signature *sig = f->matching_signature(&void_parameters);
723 if ((sig != NULL) && sig->is_defined) {
733 * Combine a group of shaders for a single stage to generate a linked shader
736 * If this function is supplied a single shader, it is cloned, and the new
737 * shader is returned.
739 static struct gl_shader *
740 link_intrastage_shaders(void *mem_ctx,
741 struct gl_context *ctx,
742 struct gl_shader_program *prog,
743 struct gl_shader **shader_list,
744 unsigned num_shaders)
746 /* Check that global variables defined in multiple shaders are consistent.
748 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
751 /* Check that there is only a single definition of each function signature
752 * across all shaders.
754 for (unsigned i = 0; i < (num_shaders - 1); i++) {
755 foreach_list(node, shader_list[i]->ir) {
756 ir_function *const f = ((ir_instruction *) node)->as_function();
761 for (unsigned j = i + 1; j < num_shaders; j++) {
762 ir_function *const other =
763 shader_list[j]->symbols->get_function(f->name);
765 /* If the other shader has no function (and therefore no function
766 * signatures) with the same name, skip to the next shader.
771 foreach_iter (exec_list_iterator, iter, *f) {
772 ir_function_signature *sig =
773 (ir_function_signature *) iter.get();
775 if (!sig->is_defined || sig->is_builtin)
778 ir_function_signature *other_sig =
779 other->exact_matching_signature(& sig->parameters);
781 if ((other_sig != NULL) && other_sig->is_defined
782 && !other_sig->is_builtin) {
783 linker_error_printf(prog,
784 "function `%s' is multiply defined",
793 /* Find the shader that defines main, and make a clone of it.
795 * Starting with the clone, search for undefined references. If one is
796 * found, find the shader that defines it. Clone the reference and add
797 * it to the shader. Repeat until there are no undefined references or
798 * until a reference cannot be resolved.
800 gl_shader *main = NULL;
801 for (unsigned i = 0; i < num_shaders; i++) {
802 if (get_main_function_signature(shader_list[i]) != NULL) {
803 main = shader_list[i];
809 linker_error_printf(prog, "%s shader lacks `main'\n",
810 (shader_list[0]->Type == GL_VERTEX_SHADER)
811 ? "vertex" : "fragment");
815 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
816 linked->ir = new(linked) exec_list;
817 clone_ir_list(mem_ctx, linked->ir, main->ir);
819 populate_symbol_table(linked);
821 /* The a pointer to the main function in the final linked shader (i.e., the
822 * copy of the original shader that contained the main function).
824 ir_function_signature *const main_sig = get_main_function_signature(linked);
826 /* Move any instructions other than variable declarations or function
827 * declarations into main.
829 exec_node *insertion_point =
830 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
833 for (unsigned i = 0; i < num_shaders; i++) {
834 if (shader_list[i] == main)
837 insertion_point = move_non_declarations(shader_list[i]->ir,
838 insertion_point, true, linked);
841 /* Resolve initializers for global variables in the linked shader.
843 unsigned num_linking_shaders = num_shaders;
844 for (unsigned i = 0; i < num_shaders; i++)
845 num_linking_shaders += shader_list[i]->num_builtins_to_link;
847 gl_shader **linking_shaders =
848 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
850 memcpy(linking_shaders, shader_list,
851 sizeof(linking_shaders[0]) * num_shaders);
853 unsigned idx = num_shaders;
854 for (unsigned i = 0; i < num_shaders; i++) {
855 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
856 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
857 idx += shader_list[i]->num_builtins_to_link;
860 assert(idx == num_linking_shaders);
862 if (!link_function_calls(prog, linked, linking_shaders,
863 num_linking_shaders)) {
864 ctx->Driver.DeleteShader(ctx, linked);
868 free(linking_shaders);
870 /* Make a pass over all global variables to ensure that arrays with
871 * unspecified sizes have a size specified. The size is inferred from the
872 * max_array_access field.
874 foreach_list(node, linked->ir) {
875 ir_variable *const var = ((ir_instruction *) node)->as_variable();
880 if (!var->type->is_array() || (var->type->length != 0))
883 const glsl_type *type =
884 glsl_type::get_array_instance(var->type->fields.array,
885 var->max_array_access);
887 assert(type != NULL);
896 struct uniform_node {
898 struct gl_uniform *u;
903 * Update the sizes of linked shader uniform arrays to the maximum
906 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
908 * If one or more elements of an array are active,
909 * GetActiveUniform will return the name of the array in name,
910 * subject to the restrictions listed above. The type of the array
911 * is returned in type. The size parameter contains the highest
912 * array element index used, plus one. The compiler or linker
913 * determines the highest index used. There will be only one
914 * active uniform reported by the GL per uniform array.
918 update_array_sizes(struct gl_shader_program *prog)
920 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
921 if (prog->_LinkedShaders[i] == NULL)
924 foreach_list(node, prog->_LinkedShaders[i]->ir) {
925 ir_variable *const var = ((ir_instruction *) node)->as_variable();
927 if ((var == NULL) || (var->mode != ir_var_uniform &&
928 var->mode != ir_var_in &&
929 var->mode != ir_var_out) ||
930 !var->type->is_array())
933 unsigned int size = var->max_array_access;
934 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
935 if (prog->_LinkedShaders[j] == NULL)
938 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
939 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
943 if (strcmp(var->name, other_var->name) == 0 &&
944 other_var->max_array_access > size) {
945 size = other_var->max_array_access;
950 if (size + 1 != var->type->fields.array->length) {
951 var->type = glsl_type::get_array_instance(var->type->fields.array,
953 /* FINISHME: We should update the types of array
954 * dereferences of this variable now.
962 add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
963 const char *name, const glsl_type *type, GLenum shader_type,
964 unsigned *next_shader_pos, unsigned *total_uniforms)
966 if (type->is_record()) {
967 for (unsigned int i = 0; i < type->length; i++) {
968 const glsl_type *field_type = type->fields.structure[i].type;
969 char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
970 type->fields.structure[i].name);
972 add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
973 shader_type, next_shader_pos, total_uniforms);
976 uniform_node *n = (uniform_node *) hash_table_find(ht, name);
977 unsigned int vec4_slots;
978 const glsl_type *array_elem_type = NULL;
980 if (type->is_array()) {
981 array_elem_type = type->fields.array;
982 /* Array of structures. */
983 if (array_elem_type->is_record()) {
984 for (unsigned int i = 0; i < type->length; i++) {
985 char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
986 add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
987 shader_type, next_shader_pos, total_uniforms);
993 /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
994 * vectors to vec4 slots.
996 if (type->is_array()) {
997 if (array_elem_type->is_sampler())
998 vec4_slots = type->length;
1000 vec4_slots = type->length * array_elem_type->matrix_columns;
1001 } else if (type->is_sampler()) {
1004 vec4_slots = type->matrix_columns;
1008 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
1009 n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
1010 n->slots = vec4_slots;
1012 n->u->Name = strdup(name);
1017 (*total_uniforms)++;
1019 hash_table_insert(ht, n, name);
1020 uniforms->push_tail(& n->link);
1023 switch (shader_type) {
1024 case GL_VERTEX_SHADER:
1025 n->u->VertPos = *next_shader_pos;
1027 case GL_FRAGMENT_SHADER:
1028 n->u->FragPos = *next_shader_pos;
1030 case GL_GEOMETRY_SHADER:
1031 n->u->GeomPos = *next_shader_pos;
1035 (*next_shader_pos) += vec4_slots;
1040 assign_uniform_locations(struct gl_shader_program *prog)
1044 unsigned total_uniforms = 0;
1045 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
1046 hash_table_string_compare);
1047 void *mem_ctx = talloc_new(NULL);
1049 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1050 if (prog->_LinkedShaders[i] == NULL)
1053 unsigned next_position = 0;
1055 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1056 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1058 if ((var == NULL) || (var->mode != ir_var_uniform))
1061 if (strncmp(var->name, "gl_", 3) == 0) {
1062 /* At the moment, we don't allocate uniform locations for
1063 * builtin uniforms. It's permitted by spec, and we'll
1064 * likely switch to doing that at some point, but not yet.
1069 var->location = next_position;
1070 add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
1071 prog->_LinkedShaders[i]->Type,
1072 &next_position, &total_uniforms);
1076 talloc_free(mem_ctx);
1078 gl_uniform_list *ul = (gl_uniform_list *)
1079 calloc(1, sizeof(gl_uniform_list));
1081 ul->Size = total_uniforms;
1082 ul->NumUniforms = total_uniforms;
1083 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
1087 for (uniform_node *node = (uniform_node *) uniforms.head
1088 ; node->link.next != NULL
1090 next = (uniform_node *) node->link.next;
1092 node->link.remove();
1093 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
1100 hash_table_dtor(ht);
1102 prog->Uniforms = ul;
1107 * Find a contiguous set of available bits in a bitmask
1109 * \param used_mask Bits representing used (1) and unused (0) locations
1110 * \param needed_count Number of contiguous bits needed.
1113 * Base location of the available bits on success or -1 on failure.
1116 find_available_slots(unsigned used_mask, unsigned needed_count)
1118 unsigned needed_mask = (1 << needed_count) - 1;
1119 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1121 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1122 * cannot optimize possibly infinite loops" for the loop below.
1124 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1127 for (int i = 0; i <= max_bit_to_test; i++) {
1128 if ((needed_mask & ~used_mask) == needed_mask)
1139 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
1141 /* Mark invalid attribute locations as being used.
1143 unsigned used_locations = (max_attribute_index >= 32)
1144 ? ~0 : ~((1 << max_attribute_index) - 1);
1146 gl_shader *const sh = prog->_LinkedShaders[0];
1147 assert(sh->Type == GL_VERTEX_SHADER);
1149 /* Operate in a total of four passes.
1151 * 1. Invalidate the location assignments for all vertex shader inputs.
1153 * 2. Assign locations for inputs that have user-defined (via
1154 * glBindVertexAttribLocation) locatoins.
1156 * 3. Sort the attributes without assigned locations by number of slots
1157 * required in decreasing order. Fragmentation caused by attribute
1158 * locations assigned by the application may prevent large attributes
1159 * from having enough contiguous space.
1161 * 4. Assign locations to any inputs without assigned locations.
1164 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1166 if (prog->Attributes != NULL) {
1167 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
1168 ir_variable *const var =
1169 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
1171 /* Note: attributes that occupy multiple slots, such as arrays or
1172 * matrices, may appear in the attrib array multiple times.
1174 if ((var == NULL) || (var->location != -1))
1177 /* From page 61 of the OpenGL 4.0 spec:
1179 * "LinkProgram will fail if the attribute bindings assigned by
1180 * BindAttribLocation do not leave not enough space to assign a
1181 * location for an active matrix attribute or an active attribute
1182 * array, both of which require multiple contiguous generic
1185 * Previous versions of the spec contain similar language but omit the
1186 * bit about attribute arrays.
1188 * Page 61 of the OpenGL 4.0 spec also says:
1190 * "It is possible for an application to bind more than one
1191 * attribute name to the same location. This is referred to as
1192 * aliasing. This will only work if only one of the aliased
1193 * attributes is active in the executable program, or if no path
1194 * through the shader consumes more than one attribute of a set
1195 * of attributes aliased to the same location. A link error can
1196 * occur if the linker determines that every path through the
1197 * shader consumes multiple aliased attributes, but
1198 * implementations are not required to generate an error in this
1201 * These two paragraphs are either somewhat contradictory, or I don't
1202 * fully understand one or both of them.
1204 /* FINISHME: The code as currently written does not support attribute
1205 * FINISHME: location aliasing (see comment above).
1207 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
1208 const unsigned slots = count_attribute_slots(var->type);
1210 /* Mask representing the contiguous slots that will be used by this
1213 const unsigned use_mask = (1 << slots) - 1;
1215 /* Generate a link error if the set of bits requested for this
1216 * attribute overlaps any previously allocated bits.
1218 if ((~(use_mask << attr) & used_locations) != used_locations) {
1219 linker_error_printf(prog,
1220 "insufficient contiguous attribute locations "
1221 "available for vertex shader input `%s'",
1226 var->location = VERT_ATTRIB_GENERIC0 + attr;
1227 used_locations |= (use_mask << attr);
1231 /* Temporary storage for the set of attributes that need locations assigned.
1237 /* Used below in the call to qsort. */
1238 static int compare(const void *a, const void *b)
1240 const temp_attr *const l = (const temp_attr *) a;
1241 const temp_attr *const r = (const temp_attr *) b;
1243 /* Reversed because we want a descending order sort below. */
1244 return r->slots - l->slots;
1248 unsigned num_attr = 0;
1250 foreach_list(node, sh->ir) {
1251 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1253 if ((var == NULL) || (var->mode != ir_var_in))
1256 if (var->explicit_location) {
1257 const unsigned slots = count_attribute_slots(var->type);
1258 const unsigned use_mask = (1 << slots) - 1;
1259 const int attr = var->location - VERT_ATTRIB_GENERIC0;
1261 if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
1262 || (var->location < 0)) {
1263 linker_error_printf(prog,
1264 "invalid explicit location %d specified for "
1266 (var->location < 0) ? var->location : attr,
1269 } else if (var->location >= VERT_ATTRIB_GENERIC0) {
1270 used_locations |= (use_mask << attr);
1274 /* The location was explicitly assigned, nothing to do here.
1276 if (var->location != -1)
1279 to_assign[num_attr].slots = count_attribute_slots(var->type);
1280 to_assign[num_attr].var = var;
1284 /* If all of the attributes were assigned locations by the application (or
1285 * are built-in attributes with fixed locations), return early. This should
1286 * be the common case.
1291 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1293 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1294 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1295 * to prevent it from being automatically allocated below.
1297 find_deref_visitor find("gl_Vertex");
1299 if (find.variable_found())
1300 used_locations |= (1 << 0);
1302 for (unsigned i = 0; i < num_attr; i++) {
1303 /* Mask representing the contiguous slots that will be used by this
1306 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1308 int location = find_available_slots(used_locations, to_assign[i].slots);
1311 linker_error_printf(prog,
1312 "insufficient contiguous attribute locations "
1313 "available for vertex shader input `%s'",
1314 to_assign[i].var->name);
1318 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1319 used_locations |= (use_mask << location);
1327 * Demote shader inputs and outputs that are not used in other stages
1330 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1332 foreach_list(node, sh->ir) {
1333 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1335 if ((var == NULL) || (var->mode != int(mode)))
1338 /* A shader 'in' or 'out' variable is only really an input or output if
1339 * its value is used by other shader stages. This will cause the variable
1340 * to have a location assigned.
1342 if (var->location == -1) {
1343 var->mode = ir_var_auto;
1350 assign_varying_locations(struct gl_shader_program *prog,
1351 gl_shader *producer, gl_shader *consumer)
1353 /* FINISHME: Set dynamically when geometry shader support is added. */
1354 unsigned output_index = VERT_RESULT_VAR0;
1355 unsigned input_index = FRAG_ATTRIB_VAR0;
1357 /* Operate in a total of three passes.
1359 * 1. Assign locations for any matching inputs and outputs.
1361 * 2. Mark output variables in the producer that do not have locations as
1362 * not being outputs. This lets the optimizer eliminate them.
1364 * 3. Mark input variables in the consumer that do not have locations as
1365 * not being inputs. This lets the optimizer eliminate them.
1368 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1369 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1371 foreach_list(node, producer->ir) {
1372 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1374 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1375 || (output_var->location != -1))
1378 ir_variable *const input_var =
1379 consumer->symbols->get_variable(output_var->name);
1381 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1384 assert(input_var->location == -1);
1386 output_var->location = output_index;
1387 input_var->location = input_index;
1389 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1390 assert(!output_var->type->is_record());
1392 if (output_var->type->is_array()) {
1393 const unsigned slots = output_var->type->length
1394 * output_var->type->fields.array->matrix_columns;
1396 output_index += slots;
1397 input_index += slots;
1399 const unsigned slots = output_var->type->matrix_columns;
1401 output_index += slots;
1402 input_index += slots;
1406 foreach_list(node, consumer->ir) {
1407 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1409 if ((var == NULL) || (var->mode != ir_var_in))
1412 if (var->location == -1) {
1413 if (prog->Version <= 120) {
1414 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1416 * Only those varying variables used (i.e. read) in
1417 * the fragment shader executable must be written to
1418 * by the vertex shader executable; declaring
1419 * superfluous varying variables in a vertex shader is
1422 * We interpret this text as meaning that the VS must
1423 * write the variable for the FS to read it. See
1424 * "glsl1-varying read but not written" in piglit.
1427 linker_error_printf(prog, "fragment shader varying %s not written "
1428 "by vertex shader\n.", var->name);
1429 prog->LinkStatus = false;
1432 /* An 'in' variable is only really a shader input if its
1433 * value is written by the previous stage.
1435 var->mode = ir_var_auto;
1442 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
1444 void *mem_ctx = talloc_init("temporary linker context");
1446 prog->LinkStatus = false;
1447 prog->Validated = false;
1448 prog->_Used = false;
1450 if (prog->InfoLog != NULL)
1451 talloc_free(prog->InfoLog);
1453 prog->InfoLog = talloc_strdup(NULL, "");
1455 /* Separate the shaders into groups based on their type.
1457 struct gl_shader **vert_shader_list;
1458 unsigned num_vert_shaders = 0;
1459 struct gl_shader **frag_shader_list;
1460 unsigned num_frag_shaders = 0;
1462 vert_shader_list = (struct gl_shader **)
1463 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1464 frag_shader_list = &vert_shader_list[prog->NumShaders];
1466 unsigned min_version = UINT_MAX;
1467 unsigned max_version = 0;
1468 for (unsigned i = 0; i < prog->NumShaders; i++) {
1469 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1470 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1472 switch (prog->Shaders[i]->Type) {
1473 case GL_VERTEX_SHADER:
1474 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1477 case GL_FRAGMENT_SHADER:
1478 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1481 case GL_GEOMETRY_SHADER:
1482 /* FINISHME: Support geometry shaders. */
1483 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1488 /* Previous to GLSL version 1.30, different compilation units could mix and
1489 * match shading language versions. With GLSL 1.30 and later, the versions
1490 * of all shaders must match.
1492 assert(min_version >= 100);
1493 assert(max_version <= 130);
1494 if ((max_version >= 130 || min_version == 100)
1495 && min_version != max_version) {
1496 linker_error_printf(prog, "all shaders must use same shading "
1497 "language version\n");
1501 prog->Version = max_version;
1503 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
1504 if (prog->_LinkedShaders[i] != NULL)
1505 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1507 prog->_LinkedShaders[i] = NULL;
1510 /* Link all shaders for a particular stage and validate the result.
1512 if (num_vert_shaders > 0) {
1513 gl_shader *const sh =
1514 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
1520 if (!validate_vertex_shader_executable(prog, sh))
1523 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
1527 if (num_frag_shaders > 0) {
1528 gl_shader *const sh =
1529 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
1535 if (!validate_fragment_shader_executable(prog, sh))
1538 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1542 /* Here begins the inter-stage linking phase. Some initial validation is
1543 * performed, then locations are assigned for uniforms, attributes, and
1546 if (cross_validate_uniforms(prog)) {
1549 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1550 if (prog->_LinkedShaders[prev] != NULL)
1554 /* Validate the inputs of each stage with the output of the preceeding
1557 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1558 if (prog->_LinkedShaders[i] == NULL)
1561 if (!cross_validate_outputs_to_inputs(prog,
1562 prog->_LinkedShaders[prev],
1563 prog->_LinkedShaders[i]))
1569 prog->LinkStatus = true;
1572 /* Do common optimization before assigning storage for attributes,
1573 * uniforms, and varyings. Later optimization could possibly make
1574 * some of that unused.
1576 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1577 if (prog->_LinkedShaders[i] == NULL)
1580 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
1584 update_array_sizes(prog);
1586 assign_uniform_locations(prog);
1588 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1589 /* FINISHME: The value of the max_attribute_index parameter is
1590 * FINISHME: implementation dependent based on the value of
1591 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1592 * FINISHME: at least 16, so hardcode 16 for now.
1594 if (!assign_attribute_locations(prog, 16)) {
1595 prog->LinkStatus = false;
1601 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1602 if (prog->_LinkedShaders[prev] != NULL)
1606 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1607 if (prog->_LinkedShaders[i] == NULL)
1610 assign_varying_locations(prog,
1611 prog->_LinkedShaders[prev],
1612 prog->_LinkedShaders[i]);
1616 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1617 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
1621 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
1622 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
1624 demote_shader_inputs_and_outputs(sh, ir_var_in);
1625 demote_shader_inputs_and_outputs(sh, ir_var_inout);
1626 demote_shader_inputs_and_outputs(sh, ir_var_out);
1629 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
1630 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1632 demote_shader_inputs_and_outputs(sh, ir_var_in);
1635 /* FINISHME: Assign fragment shader output locations. */
1638 free(vert_shader_list);
1640 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1641 if (prog->_LinkedShaders[i] == NULL)
1644 /* Retain any live IR, but trash the rest. */
1645 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
1648 talloc_free(mem_ctx);