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 * Visitor that determines whether or not a variable is ever written.
86 class find_assignment_visitor
: public ir_hierarchical_visitor
{
88 find_assignment_visitor(const char *name
)
89 : name(name
), found(false)
94 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
96 ir_variable
*const var
= ir
->lhs
->variable_referenced();
98 if (strcmp(name
, var
->name
) == 0) {
103 return visit_continue_with_parent
;
106 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
108 exec_list_iterator sig_iter
= ir
->get_callee()->parameters
.iterator();
109 foreach_iter(exec_list_iterator
, iter
, *ir
) {
110 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
111 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
113 if (sig_param
->mode
== ir_var_out
||
114 sig_param
->mode
== ir_var_inout
) {
115 ir_variable
*var
= param_rval
->variable_referenced();
116 if (var
&& strcmp(name
, var
->name
) == 0) {
124 return visit_continue_with_parent
;
127 bool variable_found()
133 const char *name
; /**< Find writes to a variable with this name. */
134 bool found
; /**< Was a write to the variable found? */
139 * Visitor that determines whether or not a variable is ever read.
141 class find_deref_visitor
: public ir_hierarchical_visitor
{
143 find_deref_visitor(const char *name
)
144 : name(name
), found(false)
149 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
151 if (strcmp(this->name
, ir
->var
->name
) == 0) {
156 return visit_continue
;
159 bool variable_found() const
165 const char *name
; /**< Find writes to a variable with this name. */
166 bool found
; /**< Was a write to the variable found? */
171 linker_error_printf(gl_shader_program
*prog
, const char *fmt
, ...)
175 prog
->InfoLog
= talloc_strdup_append(prog
->InfoLog
, "error: ");
177 prog
->InfoLog
= talloc_vasprintf_append(prog
->InfoLog
, fmt
, ap
);
183 invalidate_variable_locations(gl_shader
*sh
, enum ir_variable_mode mode
,
186 foreach_list(node
, sh
->ir
) {
187 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
189 if ((var
== NULL
) || (var
->mode
!= (unsigned) mode
))
192 /* Only assign locations for generic attributes / varyings / etc.
194 if ((var
->location
>= generic_base
) && !var
->explicit_location
)
201 * Determine the number of attribute slots required for a particular type
203 * This code is here because it implements the language rules of a specific
204 * GLSL version. Since it's a property of the language and not a property of
205 * types in general, it doesn't really belong in glsl_type.
208 count_attribute_slots(const glsl_type
*t
)
210 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
212 * "A scalar input counts the same amount against this limit as a vec4,
213 * so applications may want to consider packing groups of four
214 * unrelated float inputs together into a vector to better utilize the
215 * capabilities of the underlying hardware. A matrix input will use up
216 * multiple locations. The number of locations used will equal the
217 * number of columns in the matrix."
219 * The spec does not explicitly say how arrays are counted. However, it
220 * should be safe to assume the total number of slots consumed by an array
221 * is the number of entries in the array multiplied by the number of slots
222 * consumed by a single element of the array.
226 return t
->array_size() * count_attribute_slots(t
->element_type());
229 return t
->matrix_columns
;
236 * Verify that a vertex shader executable meets all semantic requirements
238 * \param shader Vertex shader executable to be verified
241 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
242 struct gl_shader
*shader
)
247 find_assignment_visitor
find("gl_Position");
248 find
.run(shader
->ir
);
249 if (!find
.variable_found()) {
250 linker_error_printf(prog
,
251 "vertex shader does not write to `gl_Position'\n");
260 * Verify that a fragment shader executable meets all semantic requirements
262 * \param shader Fragment shader executable to be verified
265 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
266 struct gl_shader
*shader
)
271 find_assignment_visitor
frag_color("gl_FragColor");
272 find_assignment_visitor
frag_data("gl_FragData");
274 frag_color
.run(shader
->ir
);
275 frag_data
.run(shader
->ir
);
277 if (frag_color
.variable_found() && frag_data
.variable_found()) {
278 linker_error_printf(prog
, "fragment shader writes to both "
279 "`gl_FragColor' and `gl_FragData'\n");
288 * Generate a string describing the mode of a variable
291 mode_string(const ir_variable
*var
)
295 return (var
->read_only
) ? "global constant" : "global variable";
297 case ir_var_uniform
: return "uniform";
298 case ir_var_in
: return "shader input";
299 case ir_var_out
: return "shader output";
300 case ir_var_inout
: return "shader inout";
302 case ir_var_temporary
:
304 assert(!"Should not get here.");
305 return "invalid variable";
311 * Perform validation of global variables used across multiple shaders
314 cross_validate_globals(struct gl_shader_program
*prog
,
315 struct gl_shader
**shader_list
,
316 unsigned num_shaders
,
319 /* Examine all of the uniforms in all of the shaders and cross validate
322 glsl_symbol_table variables
;
323 for (unsigned i
= 0; i
< num_shaders
; i
++) {
324 foreach_list(node
, shader_list
[i
]->ir
) {
325 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
330 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
333 /* Don't cross validate temporaries that are at global scope. These
334 * will eventually get pulled into the shaders 'main'.
336 if (var
->mode
== ir_var_temporary
)
339 /* If a global with this name has already been seen, verify that the
340 * new instance has the same type. In addition, if the globals have
341 * initializers, the values of the initializers must be the same.
343 ir_variable
*const existing
= variables
.get_variable(var
->name
);
344 if (existing
!= NULL
) {
345 if (var
->type
!= existing
->type
) {
346 /* Consider the types to be "the same" if both types are arrays
347 * of the same type and one of the arrays is implicitly sized.
348 * In addition, set the type of the linked variable to the
349 * explicitly sized array.
351 if (var
->type
->is_array()
352 && existing
->type
->is_array()
353 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
354 && ((var
->type
->length
== 0)
355 || (existing
->type
->length
== 0))) {
356 if (existing
->type
->length
== 0)
357 existing
->type
= var
->type
;
359 linker_error_printf(prog
, "%s `%s' declared as type "
360 "`%s' and type `%s'\n",
362 var
->name
, var
->type
->name
,
363 existing
->type
->name
);
368 if (var
->explicit_location
) {
369 if (existing
->explicit_location
370 && (var
->location
!= existing
->location
)) {
371 linker_error_printf(prog
, "explicit locations for %s "
372 "`%s' have differing values\n",
373 mode_string(var
), var
->name
);
377 existing
->location
= var
->location
;
378 existing
->explicit_location
= true;
381 /* FINISHME: Handle non-constant initializers.
383 if (var
->constant_value
!= NULL
) {
384 if (existing
->constant_value
!= NULL
) {
385 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
386 linker_error_printf(prog
, "initializers for %s "
387 "`%s' have differing values\n",
388 mode_string(var
), var
->name
);
392 /* If the first-seen instance of a particular uniform did not
393 * have an initializer but a later instance does, copy the
394 * initializer to the version stored in the symbol table.
396 /* FINISHME: This is wrong. The constant_value field should
397 * FINISHME: not be modified! Imagine a case where a shader
398 * FINISHME: without an initializer is linked in two different
399 * FINISHME: programs with shaders that have differing
400 * FINISHME: initializers. Linking with the first will
401 * FINISHME: modify the shader, and linking with the second
402 * FINISHME: will fail.
404 existing
->constant_value
=
405 var
->constant_value
->clone(talloc_parent(existing
), NULL
);
408 variables
.add_variable(var
->name
, var
);
417 * Perform validation of uniforms used across multiple shader stages
420 cross_validate_uniforms(struct gl_shader_program
*prog
)
422 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
423 prog
->_NumLinkedShaders
, true);
428 * Validate that outputs from one stage match inputs of another
431 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
432 gl_shader
*producer
, gl_shader
*consumer
)
434 glsl_symbol_table parameters
;
435 /* FINISHME: Figure these out dynamically. */
436 const char *const producer_stage
= "vertex";
437 const char *const consumer_stage
= "fragment";
439 /* Find all shader outputs in the "producer" stage.
441 foreach_list(node
, producer
->ir
) {
442 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
444 /* FINISHME: For geometry shaders, this should also look for inout
445 * FINISHME: variables.
447 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
450 parameters
.add_variable(var
->name
, var
);
454 /* Find all shader inputs in the "consumer" stage. Any variables that have
455 * matching outputs already in the symbol table must have the same type and
458 foreach_list(node
, consumer
->ir
) {
459 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
461 /* FINISHME: For geometry shaders, this should also look for inout
462 * FINISHME: variables.
464 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
467 ir_variable
*const output
= parameters
.get_variable(input
->name
);
468 if (output
!= NULL
) {
469 /* Check that the types match between stages.
471 if (input
->type
!= output
->type
) {
472 linker_error_printf(prog
,
473 "%s shader output `%s' declared as "
474 "type `%s', but %s shader input declared "
476 producer_stage
, output
->name
,
478 consumer_stage
, input
->type
->name
);
482 /* Check that all of the qualifiers match between stages.
484 if (input
->centroid
!= output
->centroid
) {
485 linker_error_printf(prog
,
486 "%s shader output `%s' %s centroid qualifier, "
487 "but %s shader input %s centroid qualifier\n",
490 (output
->centroid
) ? "has" : "lacks",
492 (input
->centroid
) ? "has" : "lacks");
496 if (input
->invariant
!= output
->invariant
) {
497 linker_error_printf(prog
,
498 "%s shader output `%s' %s invariant qualifier, "
499 "but %s shader input %s invariant qualifier\n",
502 (output
->invariant
) ? "has" : "lacks",
504 (input
->invariant
) ? "has" : "lacks");
508 if (input
->interpolation
!= output
->interpolation
) {
509 linker_error_printf(prog
,
510 "%s shader output `%s' specifies %s "
511 "interpolation qualifier, "
512 "but %s shader input specifies %s "
513 "interpolation qualifier\n",
516 output
->interpolation_string(),
518 input
->interpolation_string());
529 * Populates a shaders symbol table with all global declarations
532 populate_symbol_table(gl_shader
*sh
)
534 sh
->symbols
= new(sh
) glsl_symbol_table
;
536 foreach_list(node
, sh
->ir
) {
537 ir_instruction
*const inst
= (ir_instruction
*) node
;
541 if ((func
= inst
->as_function()) != NULL
) {
542 sh
->symbols
->add_function(func
->name
, func
);
543 } else if ((var
= inst
->as_variable()) != NULL
) {
544 sh
->symbols
->add_variable(var
->name
, var
);
551 * Remap variables referenced in an instruction tree
553 * This is used when instruction trees are cloned from one shader and placed in
554 * another. These trees will contain references to \c ir_variable nodes that
555 * do not exist in the target shader. This function finds these \c ir_variable
556 * references and replaces the references with matching variables in the target
559 * If there is no matching variable in the target shader, a clone of the
560 * \c ir_variable is made and added to the target shader. The new variable is
561 * added to \b both the instruction stream and the symbol table.
563 * \param inst IR tree that is to be processed.
564 * \param symbols Symbol table containing global scope symbols in the
566 * \param instructions Instruction stream where new variable declarations
570 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
573 class remap_visitor
: public ir_hierarchical_visitor
{
575 remap_visitor(struct gl_shader
*target
,
578 this->target
= target
;
579 this->symbols
= target
->symbols
;
580 this->instructions
= target
->ir
;
584 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
586 if (ir
->var
->mode
== ir_var_temporary
) {
587 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
591 return visit_continue
;
594 ir_variable
*const existing
=
595 this->symbols
->get_variable(ir
->var
->name
);
596 if (existing
!= NULL
)
599 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
601 this->symbols
->add_variable(copy
->name
, copy
);
602 this->instructions
->push_head(copy
);
606 return visit_continue
;
610 struct gl_shader
*target
;
611 glsl_symbol_table
*symbols
;
612 exec_list
*instructions
;
616 remap_visitor
v(target
, temps
);
623 * Move non-declarations from one instruction stream to another
625 * The intended usage pattern of this function is to pass the pointer to the
626 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
627 * pointer) for \c last and \c false for \c make_copies on the first
628 * call. Successive calls pass the return value of the previous call for
629 * \c last and \c true for \c make_copies.
631 * \param instructions Source instruction stream
632 * \param last Instruction after which new instructions should be
633 * inserted in the target instruction stream
634 * \param make_copies Flag selecting whether instructions in \c instructions
635 * should be copied (via \c ir_instruction::clone) into the
636 * target list or moved.
639 * The new "last" instruction in the target instruction stream. This pointer
640 * is suitable for use as the \c last parameter of a later call to this
644 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
645 bool make_copies
, gl_shader
*target
)
647 hash_table
*temps
= NULL
;
650 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
651 hash_table_pointer_compare
);
653 foreach_list_safe(node
, instructions
) {
654 ir_instruction
*inst
= (ir_instruction
*) node
;
656 if (inst
->as_function())
659 ir_variable
*var
= inst
->as_variable();
660 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
663 assert(inst
->as_assignment()
664 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
667 inst
= inst
->clone(target
, NULL
);
670 hash_table_insert(temps
, inst
, var
);
672 remap_variables(inst
, target
, temps
);
677 last
->insert_after(inst
);
682 hash_table_dtor(temps
);
688 * Get the function signature for main from a shader
690 static ir_function_signature
*
691 get_main_function_signature(gl_shader
*sh
)
693 ir_function
*const f
= sh
->symbols
->get_function("main");
695 exec_list void_parameters
;
697 /* Look for the 'void main()' signature and ensure that it's defined.
698 * This keeps the linker from accidentally pick a shader that just
699 * contains a prototype for main.
701 * We don't have to check for multiple definitions of main (in multiple
702 * shaders) because that would have already been caught above.
704 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
705 if ((sig
!= NULL
) && sig
->is_defined
) {
715 * Combine a group of shaders for a single stage to generate a linked shader
718 * If this function is supplied a single shader, it is cloned, and the new
719 * shader is returned.
721 static struct gl_shader
*
722 link_intrastage_shaders(struct gl_context
*ctx
,
723 struct gl_shader_program
*prog
,
724 struct gl_shader
**shader_list
,
725 unsigned num_shaders
)
727 /* Check that global variables defined in multiple shaders are consistent.
729 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
732 /* Check that there is only a single definition of each function signature
733 * across all shaders.
735 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
736 foreach_list(node
, shader_list
[i
]->ir
) {
737 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
742 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
743 ir_function
*const other
=
744 shader_list
[j
]->symbols
->get_function(f
->name
);
746 /* If the other shader has no function (and therefore no function
747 * signatures) with the same name, skip to the next shader.
752 foreach_iter (exec_list_iterator
, iter
, *f
) {
753 ir_function_signature
*sig
=
754 (ir_function_signature
*) iter
.get();
756 if (!sig
->is_defined
|| sig
->is_builtin
)
759 ir_function_signature
*other_sig
=
760 other
->exact_matching_signature(& sig
->parameters
);
762 if ((other_sig
!= NULL
) && other_sig
->is_defined
763 && !other_sig
->is_builtin
) {
764 linker_error_printf(prog
,
765 "function `%s' is multiply defined",
774 /* Find the shader that defines main, and make a clone of it.
776 * Starting with the clone, search for undefined references. If one is
777 * found, find the shader that defines it. Clone the reference and add
778 * it to the shader. Repeat until there are no undefined references or
779 * until a reference cannot be resolved.
781 gl_shader
*main
= NULL
;
782 for (unsigned i
= 0; i
< num_shaders
; i
++) {
783 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
784 main
= shader_list
[i
];
790 linker_error_printf(prog
, "%s shader lacks `main'\n",
791 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
792 ? "vertex" : "fragment");
796 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
797 linked
->ir
= new(linked
) exec_list
;
798 clone_ir_list(linked
, linked
->ir
, main
->ir
);
800 populate_symbol_table(linked
);
802 /* The a pointer to the main function in the final linked shader (i.e., the
803 * copy of the original shader that contained the main function).
805 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
807 /* Move any instructions other than variable declarations or function
808 * declarations into main.
810 exec_node
*insertion_point
=
811 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
814 for (unsigned i
= 0; i
< num_shaders
; i
++) {
815 if (shader_list
[i
] == main
)
818 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
819 insertion_point
, true, linked
);
822 /* Resolve initializers for global variables in the linked shader.
824 unsigned num_linking_shaders
= num_shaders
;
825 for (unsigned i
= 0; i
< num_shaders
; i
++)
826 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
828 gl_shader
**linking_shaders
=
829 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
831 memcpy(linking_shaders
, shader_list
,
832 sizeof(linking_shaders
[0]) * num_shaders
);
834 unsigned idx
= num_shaders
;
835 for (unsigned i
= 0; i
< num_shaders
; i
++) {
836 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
837 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
838 idx
+= shader_list
[i
]->num_builtins_to_link
;
841 assert(idx
== num_linking_shaders
);
843 if (!link_function_calls(prog
, linked
, linking_shaders
,
844 num_linking_shaders
)) {
845 ctx
->Driver
.DeleteShader(ctx
, linked
);
849 free(linking_shaders
);
855 struct uniform_node
{
857 struct gl_uniform
*u
;
862 * Update the sizes of linked shader uniform arrays to the maximum
865 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
867 * If one or more elements of an array are active,
868 * GetActiveUniform will return the name of the array in name,
869 * subject to the restrictions listed above. The type of the array
870 * is returned in type. The size parameter contains the highest
871 * array element index used, plus one. The compiler or linker
872 * determines the highest index used. There will be only one
873 * active uniform reported by the GL per uniform array.
877 update_array_sizes(struct gl_shader_program
*prog
)
879 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
880 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
881 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
883 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
884 var
->mode
!= ir_var_in
&&
885 var
->mode
!= ir_var_out
) ||
886 !var
->type
->is_array())
889 unsigned int size
= var
->max_array_access
;
890 for (unsigned j
= 0; j
< prog
->_NumLinkedShaders
; j
++) {
891 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
892 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
896 if (strcmp(var
->name
, other_var
->name
) == 0 &&
897 other_var
->max_array_access
> size
) {
898 size
= other_var
->max_array_access
;
903 if (size
+ 1 != var
->type
->fields
.array
->length
) {
904 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
906 /* FINISHME: We should update the types of array
907 * dereferences of this variable now.
915 add_uniform(void *mem_ctx
, exec_list
*uniforms
, struct hash_table
*ht
,
916 const char *name
, const glsl_type
*type
, GLenum shader_type
,
917 unsigned *next_shader_pos
, unsigned *total_uniforms
)
919 if (type
->is_record()) {
920 for (unsigned int i
= 0; i
< type
->length
; i
++) {
921 const glsl_type
*field_type
= type
->fields
.structure
[i
].type
;
922 char *field_name
= talloc_asprintf(mem_ctx
, "%s.%s", name
,
923 type
->fields
.structure
[i
].name
);
925 add_uniform(mem_ctx
, uniforms
, ht
, field_name
, field_type
,
926 shader_type
, next_shader_pos
, total_uniforms
);
929 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, name
);
930 unsigned int vec4_slots
;
931 const glsl_type
*array_elem_type
= NULL
;
933 if (type
->is_array()) {
934 array_elem_type
= type
->fields
.array
;
935 /* Array of structures. */
936 if (array_elem_type
->is_record()) {
937 for (unsigned int i
= 0; i
< type
->length
; i
++) {
938 char *elem_name
= talloc_asprintf(mem_ctx
, "%s[%d]", name
, i
);
939 add_uniform(mem_ctx
, uniforms
, ht
, elem_name
, array_elem_type
,
940 shader_type
, next_shader_pos
, total_uniforms
);
946 /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
947 * vectors to vec4 slots.
949 if (type
->is_array()) {
950 if (array_elem_type
->is_sampler())
951 vec4_slots
= type
->length
;
953 vec4_slots
= type
->length
* array_elem_type
->matrix_columns
;
954 } else if (type
->is_sampler()) {
957 vec4_slots
= type
->matrix_columns
;
961 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
962 n
->u
= (gl_uniform
*) calloc(1, sizeof(struct gl_uniform
));
963 n
->slots
= vec4_slots
;
965 n
->u
->Name
= strdup(name
);
972 hash_table_insert(ht
, n
, name
);
973 uniforms
->push_tail(& n
->link
);
976 switch (shader_type
) {
977 case GL_VERTEX_SHADER
:
978 n
->u
->VertPos
= *next_shader_pos
;
980 case GL_FRAGMENT_SHADER
:
981 n
->u
->FragPos
= *next_shader_pos
;
983 case GL_GEOMETRY_SHADER
:
984 n
->u
->GeomPos
= *next_shader_pos
;
988 (*next_shader_pos
) += vec4_slots
;
993 assign_uniform_locations(struct gl_shader_program
*prog
)
997 unsigned total_uniforms
= 0;
998 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
999 hash_table_string_compare
);
1000 void *mem_ctx
= talloc_new(NULL
);
1002 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1003 unsigned next_position
= 0;
1005 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1006 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1008 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
1011 if (strncmp(var
->name
, "gl_", 3) == 0) {
1012 /* At the moment, we don't allocate uniform locations for
1013 * builtin uniforms. It's permitted by spec, and we'll
1014 * likely switch to doing that at some point, but not yet.
1019 var
->location
= next_position
;
1020 add_uniform(mem_ctx
, &uniforms
, ht
, var
->name
, var
->type
,
1021 prog
->_LinkedShaders
[i
]->Type
,
1022 &next_position
, &total_uniforms
);
1026 talloc_free(mem_ctx
);
1028 gl_uniform_list
*ul
= (gl_uniform_list
*)
1029 calloc(1, sizeof(gl_uniform_list
));
1031 ul
->Size
= total_uniforms
;
1032 ul
->NumUniforms
= total_uniforms
;
1033 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
1037 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
1038 ; node
->link
.next
!= NULL
1040 next
= (uniform_node
*) node
->link
.next
;
1042 node
->link
.remove();
1043 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
));
1050 hash_table_dtor(ht
);
1052 prog
->Uniforms
= ul
;
1057 * Find a contiguous set of available bits in a bitmask
1059 * \param used_mask Bits representing used (1) and unused (0) locations
1060 * \param needed_count Number of contiguous bits needed.
1063 * Base location of the available bits on success or -1 on failure.
1066 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1068 unsigned needed_mask
= (1 << needed_count
) - 1;
1069 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1071 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1072 * cannot optimize possibly infinite loops" for the loop below.
1074 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1077 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1078 if ((needed_mask
& ~used_mask
) == needed_mask
)
1089 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
1091 /* Mark invalid attribute locations as being used.
1093 unsigned used_locations
= (max_attribute_index
>= 32)
1094 ? ~0 : ~((1 << max_attribute_index
) - 1);
1096 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
1097 assert(sh
->Type
== GL_VERTEX_SHADER
);
1099 /* Operate in a total of four passes.
1101 * 1. Invalidate the location assignments for all vertex shader inputs.
1103 * 2. Assign locations for inputs that have user-defined (via
1104 * glBindVertexAttribLocation) locatoins.
1106 * 3. Sort the attributes without assigned locations by number of slots
1107 * required in decreasing order. Fragmentation caused by attribute
1108 * locations assigned by the application may prevent large attributes
1109 * from having enough contiguous space.
1111 * 4. Assign locations to any inputs without assigned locations.
1114 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
1116 if (prog
->Attributes
!= NULL
) {
1117 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
1118 ir_variable
*const var
=
1119 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
1121 /* Note: attributes that occupy multiple slots, such as arrays or
1122 * matrices, may appear in the attrib array multiple times.
1124 if ((var
== NULL
) || (var
->location
!= -1))
1127 /* From page 61 of the OpenGL 4.0 spec:
1129 * "LinkProgram will fail if the attribute bindings assigned by
1130 * BindAttribLocation do not leave not enough space to assign a
1131 * location for an active matrix attribute or an active attribute
1132 * array, both of which require multiple contiguous generic
1135 * Previous versions of the spec contain similar language but omit the
1136 * bit about attribute arrays.
1138 * Page 61 of the OpenGL 4.0 spec also says:
1140 * "It is possible for an application to bind more than one
1141 * attribute name to the same location. This is referred to as
1142 * aliasing. This will only work if only one of the aliased
1143 * attributes is active in the executable program, or if no path
1144 * through the shader consumes more than one attribute of a set
1145 * of attributes aliased to the same location. A link error can
1146 * occur if the linker determines that every path through the
1147 * shader consumes multiple aliased attributes, but
1148 * implementations are not required to generate an error in this
1151 * These two paragraphs are either somewhat contradictory, or I don't
1152 * fully understand one or both of them.
1154 /* FINISHME: The code as currently written does not support attribute
1155 * FINISHME: location aliasing (see comment above).
1157 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
1158 const unsigned slots
= count_attribute_slots(var
->type
);
1160 /* Mask representing the contiguous slots that will be used by this
1163 const unsigned use_mask
= (1 << slots
) - 1;
1165 /* Generate a link error if the set of bits requested for this
1166 * attribute overlaps any previously allocated bits.
1168 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1169 linker_error_printf(prog
,
1170 "insufficient contiguous attribute locations "
1171 "available for vertex shader input `%s'",
1176 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
1177 used_locations
|= (use_mask
<< attr
);
1181 /* Temporary storage for the set of attributes that need locations assigned.
1187 /* Used below in the call to qsort. */
1188 static int compare(const void *a
, const void *b
)
1190 const temp_attr
*const l
= (const temp_attr
*) a
;
1191 const temp_attr
*const r
= (const temp_attr
*) b
;
1193 /* Reversed because we want a descending order sort below. */
1194 return r
->slots
- l
->slots
;
1198 unsigned num_attr
= 0;
1200 foreach_list(node
, sh
->ir
) {
1201 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1203 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1206 if (var
->explicit_location
) {
1207 const unsigned slots
= count_attribute_slots(var
->type
);
1208 const unsigned use_mask
= (1 << slots
) - 1;
1209 const int attr
= var
->location
- VERT_ATTRIB_GENERIC0
;
1211 if ((var
->location
>= (int)(max_attribute_index
+ VERT_ATTRIB_GENERIC0
))
1212 || (var
->location
< 0)) {
1213 linker_error_printf(prog
,
1214 "invalid explicit location %d specified for "
1216 (var
->location
< 0) ? var
->location
: attr
,
1219 } else if (var
->location
>= VERT_ATTRIB_GENERIC0
) {
1220 used_locations
|= (use_mask
<< attr
);
1224 /* The location was explicitly assigned, nothing to do here.
1226 if (var
->location
!= -1)
1229 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
1230 to_assign
[num_attr
].var
= var
;
1234 /* If all of the attributes were assigned locations by the application (or
1235 * are built-in attributes with fixed locations), return early. This should
1236 * be the common case.
1241 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1243 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1244 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1245 * to prevent it from being automatically allocated below.
1247 find_deref_visitor
find("gl_Vertex");
1249 if (find
.variable_found())
1250 used_locations
|= (1 << 0);
1252 for (unsigned i
= 0; i
< num_attr
; i
++) {
1253 /* Mask representing the contiguous slots that will be used by this
1256 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1258 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1261 linker_error_printf(prog
,
1262 "insufficient contiguous attribute locations "
1263 "available for vertex shader input `%s'",
1264 to_assign
[i
].var
->name
);
1268 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1269 used_locations
|= (use_mask
<< location
);
1277 * Demote shader outputs that are not read to being just plain global variables
1280 demote_unread_shader_outputs(gl_shader
*sh
)
1282 foreach_list(node
, sh
->ir
) {
1283 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1285 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1288 /* An 'out' variable is only really a shader output if its value is read
1289 * by the following stage.
1291 if (var
->location
== -1) {
1292 var
->mode
= ir_var_auto
;
1299 assign_varying_locations(struct gl_shader_program
*prog
,
1300 gl_shader
*producer
, gl_shader
*consumer
)
1302 /* FINISHME: Set dynamically when geometry shader support is added. */
1303 unsigned output_index
= VERT_RESULT_VAR0
;
1304 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1306 /* Operate in a total of three passes.
1308 * 1. Assign locations for any matching inputs and outputs.
1310 * 2. Mark output variables in the producer that do not have locations as
1311 * not being outputs. This lets the optimizer eliminate them.
1313 * 3. Mark input variables in the consumer that do not have locations as
1314 * not being inputs. This lets the optimizer eliminate them.
1317 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1318 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1320 foreach_list(node
, producer
->ir
) {
1321 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1323 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1324 || (output_var
->location
!= -1))
1327 ir_variable
*const input_var
=
1328 consumer
->symbols
->get_variable(output_var
->name
);
1330 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1333 assert(input_var
->location
== -1);
1335 output_var
->location
= output_index
;
1336 input_var
->location
= input_index
;
1338 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1339 assert(!output_var
->type
->is_record());
1341 if (output_var
->type
->is_array()) {
1342 const unsigned slots
= output_var
->type
->length
1343 * output_var
->type
->fields
.array
->matrix_columns
;
1345 output_index
+= slots
;
1346 input_index
+= slots
;
1348 const unsigned slots
= output_var
->type
->matrix_columns
;
1350 output_index
+= slots
;
1351 input_index
+= slots
;
1355 demote_unread_shader_outputs(producer
);
1357 foreach_list(node
, consumer
->ir
) {
1358 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1360 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1363 if (var
->location
== -1) {
1364 if (prog
->Version
<= 120) {
1365 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1367 * Only those varying variables used (i.e. read) in
1368 * the fragment shader executable must be written to
1369 * by the vertex shader executable; declaring
1370 * superfluous varying variables in a vertex shader is
1373 * We interpret this text as meaning that the VS must
1374 * write the variable for the FS to read it. See
1375 * "glsl1-varying read but not written" in piglit.
1378 linker_error_printf(prog
, "fragment shader varying %s not written "
1379 "by vertex shader\n.", var
->name
);
1380 prog
->LinkStatus
= false;
1383 /* An 'in' variable is only really a shader input if its
1384 * value is written by the previous stage.
1386 var
->mode
= ir_var_auto
;
1393 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1395 prog
->LinkStatus
= false;
1396 prog
->Validated
= false;
1397 prog
->_Used
= false;
1399 if (prog
->InfoLog
!= NULL
)
1400 talloc_free(prog
->InfoLog
);
1402 prog
->InfoLog
= talloc_strdup(NULL
, "");
1404 /* Separate the shaders into groups based on their type.
1406 struct gl_shader
**vert_shader_list
;
1407 unsigned num_vert_shaders
= 0;
1408 struct gl_shader
**frag_shader_list
;
1409 unsigned num_frag_shaders
= 0;
1411 vert_shader_list
= (struct gl_shader
**)
1412 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1413 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1415 unsigned min_version
= UINT_MAX
;
1416 unsigned max_version
= 0;
1417 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1418 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1419 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1421 switch (prog
->Shaders
[i
]->Type
) {
1422 case GL_VERTEX_SHADER
:
1423 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1426 case GL_FRAGMENT_SHADER
:
1427 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1430 case GL_GEOMETRY_SHADER
:
1431 /* FINISHME: Support geometry shaders. */
1432 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1437 /* Previous to GLSL version 1.30, different compilation units could mix and
1438 * match shading language versions. With GLSL 1.30 and later, the versions
1439 * of all shaders must match.
1441 assert(min_version
>= 100);
1442 assert(max_version
<= 130);
1443 if ((max_version
>= 130 || min_version
== 100)
1444 && min_version
!= max_version
) {
1445 linker_error_printf(prog
, "all shaders must use same shading "
1446 "language version\n");
1450 prog
->Version
= max_version
;
1452 for (unsigned int i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1453 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1456 /* Link all shaders for a particular stage and validate the result.
1458 prog
->_NumLinkedShaders
= 0;
1459 if (num_vert_shaders
> 0) {
1460 gl_shader
*const sh
=
1461 link_intrastage_shaders(ctx
, prog
, vert_shader_list
, num_vert_shaders
);
1466 if (!validate_vertex_shader_executable(prog
, sh
))
1469 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1470 prog
->_NumLinkedShaders
++;
1473 if (num_frag_shaders
> 0) {
1474 gl_shader
*const sh
=
1475 link_intrastage_shaders(ctx
, prog
, frag_shader_list
, num_frag_shaders
);
1480 if (!validate_fragment_shader_executable(prog
, sh
))
1483 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1484 prog
->_NumLinkedShaders
++;
1487 /* Here begins the inter-stage linking phase. Some initial validation is
1488 * performed, then locations are assigned for uniforms, attributes, and
1491 if (cross_validate_uniforms(prog
)) {
1492 /* Validate the inputs of each stage with the output of the preceeding
1495 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++) {
1496 if (!cross_validate_outputs_to_inputs(prog
,
1497 prog
->_LinkedShaders
[i
- 1],
1498 prog
->_LinkedShaders
[i
]))
1502 prog
->LinkStatus
= true;
1505 /* Do common optimization before assigning storage for attributes,
1506 * uniforms, and varyings. Later optimization could possibly make
1507 * some of that unused.
1509 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1510 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, 32))
1514 update_array_sizes(prog
);
1516 assign_uniform_locations(prog
);
1518 if (prog
->_NumLinkedShaders
&& prog
->_LinkedShaders
[0]->Type
== GL_VERTEX_SHADER
) {
1519 /* FINISHME: The value of the max_attribute_index parameter is
1520 * FINISHME: implementation dependent based on the value of
1521 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1522 * FINISHME: at least 16, so hardcode 16 for now.
1524 if (!assign_attribute_locations(prog
, 16)) {
1525 prog
->LinkStatus
= false;
1529 if (prog
->_NumLinkedShaders
== 1)
1530 demote_unread_shader_outputs(prog
->_LinkedShaders
[0]);
1533 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++)
1534 assign_varying_locations(prog
,
1535 prog
->_LinkedShaders
[i
- 1],
1536 prog
->_LinkedShaders
[i
]);
1538 /* FINISHME: Assign fragment shader output locations. */
1541 free(vert_shader_list
);