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
;
366 linker_error_printf(prog
, "%s `%s' declared as type "
367 "`%s' and type `%s'\n",
369 var
->name
, var
->type
->name
,
370 existing
->type
->name
);
375 if (var
->explicit_location
) {
376 if (existing
->explicit_location
377 && (var
->location
!= existing
->location
)) {
378 linker_error_printf(prog
, "explicit locations for %s "
379 "`%s' have differing values\n",
380 mode_string(var
), var
->name
);
384 existing
->location
= var
->location
;
385 existing
->explicit_location
= true;
388 /* FINISHME: Handle non-constant initializers.
390 if (var
->constant_value
!= NULL
) {
391 if (existing
->constant_value
!= NULL
) {
392 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
393 linker_error_printf(prog
, "initializers for %s "
394 "`%s' have differing values\n",
395 mode_string(var
), var
->name
);
399 /* If the first-seen instance of a particular uniform did not
400 * have an initializer but a later instance does, copy the
401 * initializer to the version stored in the symbol table.
403 /* FINISHME: This is wrong. The constant_value field should
404 * FINISHME: not be modified! Imagine a case where a shader
405 * FINISHME: without an initializer is linked in two different
406 * FINISHME: programs with shaders that have differing
407 * FINISHME: initializers. Linking with the first will
408 * FINISHME: modify the shader, and linking with the second
409 * FINISHME: will fail.
411 existing
->constant_value
=
412 var
->constant_value
->clone(talloc_parent(existing
), NULL
);
415 variables
.add_variable(var
->name
, var
);
424 * Perform validation of uniforms used across multiple shader stages
427 cross_validate_uniforms(struct gl_shader_program
*prog
)
429 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
430 MESA_SHADER_TYPES
, true);
435 * Validate that outputs from one stage match inputs of another
438 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
439 gl_shader
*producer
, gl_shader
*consumer
)
441 glsl_symbol_table parameters
;
442 /* FINISHME: Figure these out dynamically. */
443 const char *const producer_stage
= "vertex";
444 const char *const consumer_stage
= "fragment";
446 /* Find all shader outputs in the "producer" stage.
448 foreach_list(node
, producer
->ir
) {
449 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
451 /* FINISHME: For geometry shaders, this should also look for inout
452 * FINISHME: variables.
454 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
457 parameters
.add_variable(var
->name
, var
);
461 /* Find all shader inputs in the "consumer" stage. Any variables that have
462 * matching outputs already in the symbol table must have the same type and
465 foreach_list(node
, consumer
->ir
) {
466 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
468 /* FINISHME: For geometry shaders, this should also look for inout
469 * FINISHME: variables.
471 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
474 ir_variable
*const output
= parameters
.get_variable(input
->name
);
475 if (output
!= NULL
) {
476 /* Check that the types match between stages.
478 if (input
->type
!= output
->type
) {
479 linker_error_printf(prog
,
480 "%s shader output `%s' declared as "
481 "type `%s', but %s shader input declared "
483 producer_stage
, output
->name
,
485 consumer_stage
, input
->type
->name
);
489 /* Check that all of the qualifiers match between stages.
491 if (input
->centroid
!= output
->centroid
) {
492 linker_error_printf(prog
,
493 "%s shader output `%s' %s centroid qualifier, "
494 "but %s shader input %s centroid qualifier\n",
497 (output
->centroid
) ? "has" : "lacks",
499 (input
->centroid
) ? "has" : "lacks");
503 if (input
->invariant
!= output
->invariant
) {
504 linker_error_printf(prog
,
505 "%s shader output `%s' %s invariant qualifier, "
506 "but %s shader input %s invariant qualifier\n",
509 (output
->invariant
) ? "has" : "lacks",
511 (input
->invariant
) ? "has" : "lacks");
515 if (input
->interpolation
!= output
->interpolation
) {
516 linker_error_printf(prog
,
517 "%s shader output `%s' specifies %s "
518 "interpolation qualifier, "
519 "but %s shader input specifies %s "
520 "interpolation qualifier\n",
523 output
->interpolation_string(),
525 input
->interpolation_string());
536 * Populates a shaders symbol table with all global declarations
539 populate_symbol_table(gl_shader
*sh
)
541 sh
->symbols
= new(sh
) glsl_symbol_table
;
543 foreach_list(node
, sh
->ir
) {
544 ir_instruction
*const inst
= (ir_instruction
*) node
;
548 if ((func
= inst
->as_function()) != NULL
) {
549 sh
->symbols
->add_function(func
->name
, func
);
550 } else if ((var
= inst
->as_variable()) != NULL
) {
551 sh
->symbols
->add_variable(var
->name
, var
);
558 * Remap variables referenced in an instruction tree
560 * This is used when instruction trees are cloned from one shader and placed in
561 * another. These trees will contain references to \c ir_variable nodes that
562 * do not exist in the target shader. This function finds these \c ir_variable
563 * references and replaces the references with matching variables in the target
566 * If there is no matching variable in the target shader, a clone of the
567 * \c ir_variable is made and added to the target shader. The new variable is
568 * added to \b both the instruction stream and the symbol table.
570 * \param inst IR tree that is to be processed.
571 * \param symbols Symbol table containing global scope symbols in the
573 * \param instructions Instruction stream where new variable declarations
577 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
580 class remap_visitor
: public ir_hierarchical_visitor
{
582 remap_visitor(struct gl_shader
*target
,
585 this->target
= target
;
586 this->symbols
= target
->symbols
;
587 this->instructions
= target
->ir
;
591 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
593 if (ir
->var
->mode
== ir_var_temporary
) {
594 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
598 return visit_continue
;
601 ir_variable
*const existing
=
602 this->symbols
->get_variable(ir
->var
->name
);
603 if (existing
!= NULL
)
606 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
608 this->symbols
->add_variable(copy
->name
, copy
);
609 this->instructions
->push_head(copy
);
613 return visit_continue
;
617 struct gl_shader
*target
;
618 glsl_symbol_table
*symbols
;
619 exec_list
*instructions
;
623 remap_visitor
v(target
, temps
);
630 * Move non-declarations from one instruction stream to another
632 * The intended usage pattern of this function is to pass the pointer to the
633 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
634 * pointer) for \c last and \c false for \c make_copies on the first
635 * call. Successive calls pass the return value of the previous call for
636 * \c last and \c true for \c make_copies.
638 * \param instructions Source instruction stream
639 * \param last Instruction after which new instructions should be
640 * inserted in the target instruction stream
641 * \param make_copies Flag selecting whether instructions in \c instructions
642 * should be copied (via \c ir_instruction::clone) into the
643 * target list or moved.
646 * The new "last" instruction in the target instruction stream. This pointer
647 * is suitable for use as the \c last parameter of a later call to this
651 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
652 bool make_copies
, gl_shader
*target
)
654 hash_table
*temps
= NULL
;
657 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
658 hash_table_pointer_compare
);
660 foreach_list_safe(node
, instructions
) {
661 ir_instruction
*inst
= (ir_instruction
*) node
;
663 if (inst
->as_function())
666 ir_variable
*var
= inst
->as_variable();
667 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
670 assert(inst
->as_assignment()
671 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
674 inst
= inst
->clone(target
, NULL
);
677 hash_table_insert(temps
, inst
, var
);
679 remap_variables(inst
, target
, temps
);
684 last
->insert_after(inst
);
689 hash_table_dtor(temps
);
695 * Get the function signature for main from a shader
697 static ir_function_signature
*
698 get_main_function_signature(gl_shader
*sh
)
700 ir_function
*const f
= sh
->symbols
->get_function("main");
702 exec_list void_parameters
;
704 /* Look for the 'void main()' signature and ensure that it's defined.
705 * This keeps the linker from accidentally pick a shader that just
706 * contains a prototype for main.
708 * We don't have to check for multiple definitions of main (in multiple
709 * shaders) because that would have already been caught above.
711 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
712 if ((sig
!= NULL
) && sig
->is_defined
) {
722 * Combine a group of shaders for a single stage to generate a linked shader
725 * If this function is supplied a single shader, it is cloned, and the new
726 * shader is returned.
728 static struct gl_shader
*
729 link_intrastage_shaders(struct gl_context
*ctx
,
730 struct gl_shader_program
*prog
,
731 struct gl_shader
**shader_list
,
732 unsigned num_shaders
)
734 /* Check that global variables defined in multiple shaders are consistent.
736 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
739 /* Check that there is only a single definition of each function signature
740 * across all shaders.
742 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
743 foreach_list(node
, shader_list
[i
]->ir
) {
744 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
749 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
750 ir_function
*const other
=
751 shader_list
[j
]->symbols
->get_function(f
->name
);
753 /* If the other shader has no function (and therefore no function
754 * signatures) with the same name, skip to the next shader.
759 foreach_iter (exec_list_iterator
, iter
, *f
) {
760 ir_function_signature
*sig
=
761 (ir_function_signature
*) iter
.get();
763 if (!sig
->is_defined
|| sig
->is_builtin
)
766 ir_function_signature
*other_sig
=
767 other
->exact_matching_signature(& sig
->parameters
);
769 if ((other_sig
!= NULL
) && other_sig
->is_defined
770 && !other_sig
->is_builtin
) {
771 linker_error_printf(prog
,
772 "function `%s' is multiply defined",
781 /* Find the shader that defines main, and make a clone of it.
783 * Starting with the clone, search for undefined references. If one is
784 * found, find the shader that defines it. Clone the reference and add
785 * it to the shader. Repeat until there are no undefined references or
786 * until a reference cannot be resolved.
788 gl_shader
*main
= NULL
;
789 for (unsigned i
= 0; i
< num_shaders
; i
++) {
790 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
791 main
= shader_list
[i
];
797 linker_error_printf(prog
, "%s shader lacks `main'\n",
798 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
799 ? "vertex" : "fragment");
803 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
804 linked
->ir
= new(linked
) exec_list
;
805 clone_ir_list(linked
, linked
->ir
, main
->ir
);
807 populate_symbol_table(linked
);
809 /* The a pointer to the main function in the final linked shader (i.e., the
810 * copy of the original shader that contained the main function).
812 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
814 /* Move any instructions other than variable declarations or function
815 * declarations into main.
817 exec_node
*insertion_point
=
818 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
821 for (unsigned i
= 0; i
< num_shaders
; i
++) {
822 if (shader_list
[i
] == main
)
825 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
826 insertion_point
, true, linked
);
829 /* Resolve initializers for global variables in the linked shader.
831 unsigned num_linking_shaders
= num_shaders
;
832 for (unsigned i
= 0; i
< num_shaders
; i
++)
833 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
835 gl_shader
**linking_shaders
=
836 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
838 memcpy(linking_shaders
, shader_list
,
839 sizeof(linking_shaders
[0]) * num_shaders
);
841 unsigned idx
= num_shaders
;
842 for (unsigned i
= 0; i
< num_shaders
; i
++) {
843 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
844 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
845 idx
+= shader_list
[i
]->num_builtins_to_link
;
848 assert(idx
== num_linking_shaders
);
850 if (!link_function_calls(prog
, linked
, linking_shaders
,
851 num_linking_shaders
)) {
852 ctx
->Driver
.DeleteShader(ctx
, linked
);
856 free(linking_shaders
);
862 struct uniform_node
{
864 struct gl_uniform
*u
;
869 * Update the sizes of linked shader uniform arrays to the maximum
872 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
874 * If one or more elements of an array are active,
875 * GetActiveUniform will return the name of the array in name,
876 * subject to the restrictions listed above. The type of the array
877 * is returned in type. The size parameter contains the highest
878 * array element index used, plus one. The compiler or linker
879 * determines the highest index used. There will be only one
880 * active uniform reported by the GL per uniform array.
884 update_array_sizes(struct gl_shader_program
*prog
)
886 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
887 if (prog
->_LinkedShaders
[i
] == NULL
)
890 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
891 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
893 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
894 var
->mode
!= ir_var_in
&&
895 var
->mode
!= ir_var_out
) ||
896 !var
->type
->is_array())
899 unsigned int size
= var
->max_array_access
;
900 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
901 if (prog
->_LinkedShaders
[j
] == NULL
)
904 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
905 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
909 if (strcmp(var
->name
, other_var
->name
) == 0 &&
910 other_var
->max_array_access
> size
) {
911 size
= other_var
->max_array_access
;
916 if (size
+ 1 != var
->type
->fields
.array
->length
) {
917 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
919 /* FINISHME: We should update the types of array
920 * dereferences of this variable now.
928 add_uniform(void *mem_ctx
, exec_list
*uniforms
, struct hash_table
*ht
,
929 const char *name
, const glsl_type
*type
, GLenum shader_type
,
930 unsigned *next_shader_pos
, unsigned *total_uniforms
)
932 if (type
->is_record()) {
933 for (unsigned int i
= 0; i
< type
->length
; i
++) {
934 const glsl_type
*field_type
= type
->fields
.structure
[i
].type
;
935 char *field_name
= talloc_asprintf(mem_ctx
, "%s.%s", name
,
936 type
->fields
.structure
[i
].name
);
938 add_uniform(mem_ctx
, uniforms
, ht
, field_name
, field_type
,
939 shader_type
, next_shader_pos
, total_uniforms
);
942 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, name
);
943 unsigned int vec4_slots
;
944 const glsl_type
*array_elem_type
= NULL
;
946 if (type
->is_array()) {
947 array_elem_type
= type
->fields
.array
;
948 /* Array of structures. */
949 if (array_elem_type
->is_record()) {
950 for (unsigned int i
= 0; i
< type
->length
; i
++) {
951 char *elem_name
= talloc_asprintf(mem_ctx
, "%s[%d]", name
, i
);
952 add_uniform(mem_ctx
, uniforms
, ht
, elem_name
, array_elem_type
,
953 shader_type
, next_shader_pos
, total_uniforms
);
959 /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
960 * vectors to vec4 slots.
962 if (type
->is_array()) {
963 if (array_elem_type
->is_sampler())
964 vec4_slots
= type
->length
;
966 vec4_slots
= type
->length
* array_elem_type
->matrix_columns
;
967 } else if (type
->is_sampler()) {
970 vec4_slots
= type
->matrix_columns
;
974 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
975 n
->u
= (gl_uniform
*) calloc(1, sizeof(struct gl_uniform
));
976 n
->slots
= vec4_slots
;
978 n
->u
->Name
= strdup(name
);
985 hash_table_insert(ht
, n
, name
);
986 uniforms
->push_tail(& n
->link
);
989 switch (shader_type
) {
990 case GL_VERTEX_SHADER
:
991 n
->u
->VertPos
= *next_shader_pos
;
993 case GL_FRAGMENT_SHADER
:
994 n
->u
->FragPos
= *next_shader_pos
;
996 case GL_GEOMETRY_SHADER
:
997 n
->u
->GeomPos
= *next_shader_pos
;
1001 (*next_shader_pos
) += vec4_slots
;
1006 assign_uniform_locations(struct gl_shader_program
*prog
)
1010 unsigned total_uniforms
= 0;
1011 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
1012 hash_table_string_compare
);
1013 void *mem_ctx
= talloc_new(NULL
);
1015 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1016 if (prog
->_LinkedShaders
[i
] == NULL
)
1019 unsigned next_position
= 0;
1021 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1022 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1024 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
1027 if (strncmp(var
->name
, "gl_", 3) == 0) {
1028 /* At the moment, we don't allocate uniform locations for
1029 * builtin uniforms. It's permitted by spec, and we'll
1030 * likely switch to doing that at some point, but not yet.
1035 var
->location
= next_position
;
1036 add_uniform(mem_ctx
, &uniforms
, ht
, var
->name
, var
->type
,
1037 prog
->_LinkedShaders
[i
]->Type
,
1038 &next_position
, &total_uniforms
);
1042 talloc_free(mem_ctx
);
1044 gl_uniform_list
*ul
= (gl_uniform_list
*)
1045 calloc(1, sizeof(gl_uniform_list
));
1047 ul
->Size
= total_uniforms
;
1048 ul
->NumUniforms
= total_uniforms
;
1049 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
1053 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
1054 ; node
->link
.next
!= NULL
1056 next
= (uniform_node
*) node
->link
.next
;
1058 node
->link
.remove();
1059 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
));
1066 hash_table_dtor(ht
);
1068 prog
->Uniforms
= ul
;
1073 * Find a contiguous set of available bits in a bitmask
1075 * \param used_mask Bits representing used (1) and unused (0) locations
1076 * \param needed_count Number of contiguous bits needed.
1079 * Base location of the available bits on success or -1 on failure.
1082 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1084 unsigned needed_mask
= (1 << needed_count
) - 1;
1085 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1087 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1088 * cannot optimize possibly infinite loops" for the loop below.
1090 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1093 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1094 if ((needed_mask
& ~used_mask
) == needed_mask
)
1105 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
1107 /* Mark invalid attribute locations as being used.
1109 unsigned used_locations
= (max_attribute_index
>= 32)
1110 ? ~0 : ~((1 << max_attribute_index
) - 1);
1112 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
1113 assert(sh
->Type
== GL_VERTEX_SHADER
);
1115 /* Operate in a total of four passes.
1117 * 1. Invalidate the location assignments for all vertex shader inputs.
1119 * 2. Assign locations for inputs that have user-defined (via
1120 * glBindVertexAttribLocation) locatoins.
1122 * 3. Sort the attributes without assigned locations by number of slots
1123 * required in decreasing order. Fragmentation caused by attribute
1124 * locations assigned by the application may prevent large attributes
1125 * from having enough contiguous space.
1127 * 4. Assign locations to any inputs without assigned locations.
1130 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
1132 if (prog
->Attributes
!= NULL
) {
1133 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
1134 ir_variable
*const var
=
1135 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
1137 /* Note: attributes that occupy multiple slots, such as arrays or
1138 * matrices, may appear in the attrib array multiple times.
1140 if ((var
== NULL
) || (var
->location
!= -1))
1143 /* From page 61 of the OpenGL 4.0 spec:
1145 * "LinkProgram will fail if the attribute bindings assigned by
1146 * BindAttribLocation do not leave not enough space to assign a
1147 * location for an active matrix attribute or an active attribute
1148 * array, both of which require multiple contiguous generic
1151 * Previous versions of the spec contain similar language but omit the
1152 * bit about attribute arrays.
1154 * Page 61 of the OpenGL 4.0 spec also says:
1156 * "It is possible for an application to bind more than one
1157 * attribute name to the same location. This is referred to as
1158 * aliasing. This will only work if only one of the aliased
1159 * attributes is active in the executable program, or if no path
1160 * through the shader consumes more than one attribute of a set
1161 * of attributes aliased to the same location. A link error can
1162 * occur if the linker determines that every path through the
1163 * shader consumes multiple aliased attributes, but
1164 * implementations are not required to generate an error in this
1167 * These two paragraphs are either somewhat contradictory, or I don't
1168 * fully understand one or both of them.
1170 /* FINISHME: The code as currently written does not support attribute
1171 * FINISHME: location aliasing (see comment above).
1173 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
1174 const unsigned slots
= count_attribute_slots(var
->type
);
1176 /* Mask representing the contiguous slots that will be used by this
1179 const unsigned use_mask
= (1 << slots
) - 1;
1181 /* Generate a link error if the set of bits requested for this
1182 * attribute overlaps any previously allocated bits.
1184 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1185 linker_error_printf(prog
,
1186 "insufficient contiguous attribute locations "
1187 "available for vertex shader input `%s'",
1192 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
1193 used_locations
|= (use_mask
<< attr
);
1197 /* Temporary storage for the set of attributes that need locations assigned.
1203 /* Used below in the call to qsort. */
1204 static int compare(const void *a
, const void *b
)
1206 const temp_attr
*const l
= (const temp_attr
*) a
;
1207 const temp_attr
*const r
= (const temp_attr
*) b
;
1209 /* Reversed because we want a descending order sort below. */
1210 return r
->slots
- l
->slots
;
1214 unsigned num_attr
= 0;
1216 foreach_list(node
, sh
->ir
) {
1217 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1219 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1222 if (var
->explicit_location
) {
1223 const unsigned slots
= count_attribute_slots(var
->type
);
1224 const unsigned use_mask
= (1 << slots
) - 1;
1225 const int attr
= var
->location
- VERT_ATTRIB_GENERIC0
;
1227 if ((var
->location
>= (int)(max_attribute_index
+ VERT_ATTRIB_GENERIC0
))
1228 || (var
->location
< 0)) {
1229 linker_error_printf(prog
,
1230 "invalid explicit location %d specified for "
1232 (var
->location
< 0) ? var
->location
: attr
,
1235 } else if (var
->location
>= VERT_ATTRIB_GENERIC0
) {
1236 used_locations
|= (use_mask
<< attr
);
1240 /* The location was explicitly assigned, nothing to do here.
1242 if (var
->location
!= -1)
1245 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
1246 to_assign
[num_attr
].var
= var
;
1250 /* If all of the attributes were assigned locations by the application (or
1251 * are built-in attributes with fixed locations), return early. This should
1252 * be the common case.
1257 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1259 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1260 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1261 * to prevent it from being automatically allocated below.
1263 find_deref_visitor
find("gl_Vertex");
1265 if (find
.variable_found())
1266 used_locations
|= (1 << 0);
1268 for (unsigned i
= 0; i
< num_attr
; i
++) {
1269 /* Mask representing the contiguous slots that will be used by this
1272 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1274 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1277 linker_error_printf(prog
,
1278 "insufficient contiguous attribute locations "
1279 "available for vertex shader input `%s'",
1280 to_assign
[i
].var
->name
);
1284 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1285 used_locations
|= (use_mask
<< location
);
1293 * Demote shader outputs that are not read to being just plain global variables
1296 demote_unread_shader_outputs(gl_shader
*sh
)
1298 foreach_list(node
, sh
->ir
) {
1299 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1301 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1304 /* An 'out' variable is only really a shader output if its value is read
1305 * by the following stage.
1307 if (var
->location
== -1) {
1308 var
->mode
= ir_var_auto
;
1315 assign_varying_locations(struct gl_shader_program
*prog
,
1316 gl_shader
*producer
, gl_shader
*consumer
)
1318 /* FINISHME: Set dynamically when geometry shader support is added. */
1319 unsigned output_index
= VERT_RESULT_VAR0
;
1320 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1322 /* Operate in a total of three passes.
1324 * 1. Assign locations for any matching inputs and outputs.
1326 * 2. Mark output variables in the producer that do not have locations as
1327 * not being outputs. This lets the optimizer eliminate them.
1329 * 3. Mark input variables in the consumer that do not have locations as
1330 * not being inputs. This lets the optimizer eliminate them.
1333 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1334 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1336 foreach_list(node
, producer
->ir
) {
1337 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1339 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1340 || (output_var
->location
!= -1))
1343 ir_variable
*const input_var
=
1344 consumer
->symbols
->get_variable(output_var
->name
);
1346 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1349 assert(input_var
->location
== -1);
1351 output_var
->location
= output_index
;
1352 input_var
->location
= input_index
;
1354 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1355 assert(!output_var
->type
->is_record());
1357 if (output_var
->type
->is_array()) {
1358 const unsigned slots
= output_var
->type
->length
1359 * output_var
->type
->fields
.array
->matrix_columns
;
1361 output_index
+= slots
;
1362 input_index
+= slots
;
1364 const unsigned slots
= output_var
->type
->matrix_columns
;
1366 output_index
+= slots
;
1367 input_index
+= slots
;
1371 demote_unread_shader_outputs(producer
);
1373 foreach_list(node
, consumer
->ir
) {
1374 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1376 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1379 if (var
->location
== -1) {
1380 if (prog
->Version
<= 120) {
1381 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1383 * Only those varying variables used (i.e. read) in
1384 * the fragment shader executable must be written to
1385 * by the vertex shader executable; declaring
1386 * superfluous varying variables in a vertex shader is
1389 * We interpret this text as meaning that the VS must
1390 * write the variable for the FS to read it. See
1391 * "glsl1-varying read but not written" in piglit.
1394 linker_error_printf(prog
, "fragment shader varying %s not written "
1395 "by vertex shader\n.", var
->name
);
1396 prog
->LinkStatus
= false;
1399 /* An 'in' variable is only really a shader input if its
1400 * value is written by the previous stage.
1402 var
->mode
= ir_var_auto
;
1409 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1411 prog
->LinkStatus
= false;
1412 prog
->Validated
= false;
1413 prog
->_Used
= false;
1415 if (prog
->InfoLog
!= NULL
)
1416 talloc_free(prog
->InfoLog
);
1418 prog
->InfoLog
= talloc_strdup(NULL
, "");
1420 /* Separate the shaders into groups based on their type.
1422 struct gl_shader
**vert_shader_list
;
1423 unsigned num_vert_shaders
= 0;
1424 struct gl_shader
**frag_shader_list
;
1425 unsigned num_frag_shaders
= 0;
1427 vert_shader_list
= (struct gl_shader
**)
1428 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1429 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1431 unsigned min_version
= UINT_MAX
;
1432 unsigned max_version
= 0;
1433 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1434 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1435 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1437 switch (prog
->Shaders
[i
]->Type
) {
1438 case GL_VERTEX_SHADER
:
1439 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1442 case GL_FRAGMENT_SHADER
:
1443 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1446 case GL_GEOMETRY_SHADER
:
1447 /* FINISHME: Support geometry shaders. */
1448 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1453 /* Previous to GLSL version 1.30, different compilation units could mix and
1454 * match shading language versions. With GLSL 1.30 and later, the versions
1455 * of all shaders must match.
1457 assert(min_version
>= 100);
1458 assert(max_version
<= 130);
1459 if ((max_version
>= 130 || min_version
== 100)
1460 && min_version
!= max_version
) {
1461 linker_error_printf(prog
, "all shaders must use same shading "
1462 "language version\n");
1466 prog
->Version
= max_version
;
1468 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1469 if (prog
->_LinkedShaders
[i
] != NULL
)
1470 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1472 prog
->_LinkedShaders
[i
] = NULL
;
1475 /* Link all shaders for a particular stage and validate the result.
1477 if (num_vert_shaders
> 0) {
1478 gl_shader
*const sh
=
1479 link_intrastage_shaders(ctx
, prog
, vert_shader_list
, num_vert_shaders
);
1484 if (!validate_vertex_shader_executable(prog
, sh
))
1487 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1491 if (num_frag_shaders
> 0) {
1492 gl_shader
*const sh
=
1493 link_intrastage_shaders(ctx
, prog
, frag_shader_list
, num_frag_shaders
);
1498 if (!validate_fragment_shader_executable(prog
, sh
))
1501 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1505 /* Here begins the inter-stage linking phase. Some initial validation is
1506 * performed, then locations are assigned for uniforms, attributes, and
1509 if (cross_validate_uniforms(prog
)) {
1512 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1513 if (prog
->_LinkedShaders
[prev
] != NULL
)
1517 /* Validate the inputs of each stage with the output of the preceeding
1520 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1521 if (prog
->_LinkedShaders
[i
] == NULL
)
1524 if (!cross_validate_outputs_to_inputs(prog
,
1525 prog
->_LinkedShaders
[prev
],
1526 prog
->_LinkedShaders
[i
]))
1532 prog
->LinkStatus
= true;
1535 /* Do common optimization before assigning storage for attributes,
1536 * uniforms, and varyings. Later optimization could possibly make
1537 * some of that unused.
1539 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1540 if (prog
->_LinkedShaders
[i
] == NULL
)
1543 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, 32))
1547 update_array_sizes(prog
);
1549 assign_uniform_locations(prog
);
1551 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
1552 /* FINISHME: The value of the max_attribute_index parameter is
1553 * FINISHME: implementation dependent based on the value of
1554 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1555 * FINISHME: at least 16, so hardcode 16 for now.
1557 if (!assign_attribute_locations(prog
, 16)) {
1558 prog
->LinkStatus
= false;
1562 if ((prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] == NULL
)
1563 && (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
))
1564 demote_unread_shader_outputs(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
]);
1568 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1569 if (prog
->_LinkedShaders
[prev
] != NULL
)
1573 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1574 if (prog
->_LinkedShaders
[i
] == NULL
)
1577 assign_varying_locations(prog
,
1578 prog
->_LinkedShaders
[prev
],
1579 prog
->_LinkedShaders
[i
]);
1583 /* FINISHME: Assign fragment shader output locations. */
1586 free(vert_shader_list
);