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/mtypes.h"
76 #include "main/macros.h"
77 #include "main/shaderobj.h"
78 #include "glsl_symbol_table.h"
81 #include "program/hash_table.h"
83 #include "ir_optimization.h"
86 * Visitor that determines whether or not a variable is ever written.
88 class find_assignment_visitor
: public ir_hierarchical_visitor
{
90 find_assignment_visitor(const char *name
)
91 : name(name
), found(false)
96 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
98 ir_variable
*const var
= ir
->lhs
->variable_referenced();
100 if (strcmp(name
, var
->name
) == 0) {
105 return visit_continue_with_parent
;
108 bool variable_found()
114 const char *name
; /**< Find writes to a variable with this name. */
115 bool found
; /**< Was a write to the variable found? */
120 * Visitor that determines whether or not a variable is ever read.
122 class find_deref_visitor
: public ir_hierarchical_visitor
{
124 find_deref_visitor(const char *name
)
125 : name(name
), found(false)
130 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
132 if (strcmp(this->name
, ir
->var
->name
) == 0) {
137 return visit_continue
;
140 bool variable_found() const
146 const char *name
; /**< Find writes to a variable with this name. */
147 bool found
; /**< Was a write to the variable found? */
152 linker_error_printf(gl_shader_program
*prog
, const char *fmt
, ...)
156 prog
->InfoLog
= talloc_strdup_append(prog
->InfoLog
, "error: ");
158 prog
->InfoLog
= talloc_vasprintf_append(prog
->InfoLog
, fmt
, ap
);
164 invalidate_variable_locations(gl_shader
*sh
, enum ir_variable_mode mode
,
167 foreach_list(node
, sh
->ir
) {
168 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
170 if ((var
== NULL
) || (var
->mode
!= (unsigned) mode
))
173 /* Only assign locations for generic attributes / varyings / etc.
175 if (var
->location
>= generic_base
)
182 * Determine the number of attribute slots required for a particular type
184 * This code is here because it implements the language rules of a specific
185 * GLSL version. Since it's a property of the language and not a property of
186 * types in general, it doesn't really belong in glsl_type.
189 count_attribute_slots(const glsl_type
*t
)
191 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
193 * "A scalar input counts the same amount against this limit as a vec4,
194 * so applications may want to consider packing groups of four
195 * unrelated float inputs together into a vector to better utilize the
196 * capabilities of the underlying hardware. A matrix input will use up
197 * multiple locations. The number of locations used will equal the
198 * number of columns in the matrix."
200 * The spec does not explicitly say how arrays are counted. However, it
201 * should be safe to assume the total number of slots consumed by an array
202 * is the number of entries in the array multiplied by the number of slots
203 * consumed by a single element of the array.
207 return t
->array_size() * count_attribute_slots(t
->element_type());
210 return t
->matrix_columns
;
217 * Verify that a vertex shader executable meets all semantic requirements
219 * \param shader Vertex shader executable to be verified
222 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
223 struct gl_shader
*shader
)
228 find_assignment_visitor
find("gl_Position");
229 find
.run(shader
->ir
);
230 if (!find
.variable_found()) {
231 linker_error_printf(prog
,
232 "vertex shader does not write to `gl_Position'\n");
241 * Verify that a fragment shader executable meets all semantic requirements
243 * \param shader Fragment shader executable to be verified
246 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
247 struct gl_shader
*shader
)
252 find_assignment_visitor
frag_color("gl_FragColor");
253 find_assignment_visitor
frag_data("gl_FragData");
255 frag_color
.run(shader
->ir
);
256 frag_data
.run(shader
->ir
);
258 if (frag_color
.variable_found() && frag_data
.variable_found()) {
259 linker_error_printf(prog
, "fragment shader writes to both "
260 "`gl_FragColor' and `gl_FragData'\n");
269 * Generate a string describing the mode of a variable
272 mode_string(const ir_variable
*var
)
276 return (var
->read_only
) ? "global constant" : "global variable";
278 case ir_var_uniform
: return "uniform";
279 case ir_var_in
: return "shader input";
280 case ir_var_out
: return "shader output";
281 case ir_var_inout
: return "shader inout";
283 case ir_var_temporary
:
285 assert(!"Should not get here.");
286 return "invalid variable";
292 * Perform validation of global variables used across multiple shaders
295 cross_validate_globals(struct gl_shader_program
*prog
,
296 struct gl_shader
**shader_list
,
297 unsigned num_shaders
,
300 /* Examine all of the uniforms in all of the shaders and cross validate
303 glsl_symbol_table variables
;
304 for (unsigned i
= 0; i
< num_shaders
; i
++) {
305 foreach_list(node
, shader_list
[i
]->ir
) {
306 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
311 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
314 /* Don't cross validate temporaries that are at global scope. These
315 * will eventually get pulled into the shaders 'main'.
317 if (var
->mode
== ir_var_temporary
)
320 /* If a global with this name has already been seen, verify that the
321 * new instance has the same type. In addition, if the globals have
322 * initializers, the values of the initializers must be the same.
324 ir_variable
*const existing
= variables
.get_variable(var
->name
);
325 if (existing
!= NULL
) {
326 if (var
->type
!= existing
->type
) {
327 linker_error_printf(prog
, "%s `%s' declared as type "
328 "`%s' and type `%s'\n",
330 var
->name
, var
->type
->name
,
331 existing
->type
->name
);
335 /* FINISHME: Handle non-constant initializers.
337 if (var
->constant_value
!= NULL
) {
338 if (existing
->constant_value
!= NULL
) {
339 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
340 linker_error_printf(prog
, "initializers for %s "
341 "`%s' have differing values\n",
342 mode_string(var
), var
->name
);
346 /* If the first-seen instance of a particular uniform did not
347 * have an initializer but a later instance does, copy the
348 * initializer to the version stored in the symbol table.
350 /* FINISHME: This is wrong. The constant_value field should
351 * FINISHME: not be modified! Imagine a case where a shader
352 * FINISHME: without an initializer is linked in two different
353 * FINISHME: programs with shaders that have differing
354 * FINISHME: initializers. Linking with the first will
355 * FINISHME: modify the shader, and linking with the second
356 * FINISHME: will fail.
358 existing
->constant_value
=
359 var
->constant_value
->clone(talloc_parent(existing
), NULL
);
362 variables
.add_variable(var
->name
, var
);
371 * Perform validation of uniforms used across multiple shader stages
374 cross_validate_uniforms(struct gl_shader_program
*prog
)
376 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
377 prog
->_NumLinkedShaders
, true);
382 * Validate that outputs from one stage match inputs of another
385 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
386 gl_shader
*producer
, gl_shader
*consumer
)
388 glsl_symbol_table parameters
;
389 /* FINISHME: Figure these out dynamically. */
390 const char *const producer_stage
= "vertex";
391 const char *const consumer_stage
= "fragment";
393 /* Find all shader outputs in the "producer" stage.
395 foreach_list(node
, producer
->ir
) {
396 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
398 /* FINISHME: For geometry shaders, this should also look for inout
399 * FINISHME: variables.
401 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
404 parameters
.add_variable(var
->name
, var
);
408 /* Find all shader inputs in the "consumer" stage. Any variables that have
409 * matching outputs already in the symbol table must have the same type and
412 foreach_list(node
, consumer
->ir
) {
413 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
415 /* FINISHME: For geometry shaders, this should also look for inout
416 * FINISHME: variables.
418 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
421 ir_variable
*const output
= parameters
.get_variable(input
->name
);
422 if (output
!= NULL
) {
423 /* Check that the types match between stages.
425 if (input
->type
!= output
->type
) {
426 linker_error_printf(prog
,
427 "%s shader output `%s' delcared as "
428 "type `%s', but %s shader input declared "
430 producer_stage
, output
->name
,
432 consumer_stage
, input
->type
->name
);
436 /* Check that all of the qualifiers match between stages.
438 if (input
->centroid
!= output
->centroid
) {
439 linker_error_printf(prog
,
440 "%s shader output `%s' %s centroid qualifier, "
441 "but %s shader input %s centroid qualifier\n",
444 (output
->centroid
) ? "has" : "lacks",
446 (input
->centroid
) ? "has" : "lacks");
450 if (input
->invariant
!= output
->invariant
) {
451 linker_error_printf(prog
,
452 "%s shader output `%s' %s invariant qualifier, "
453 "but %s shader input %s invariant qualifier\n",
456 (output
->invariant
) ? "has" : "lacks",
458 (input
->invariant
) ? "has" : "lacks");
462 if (input
->interpolation
!= output
->interpolation
) {
463 linker_error_printf(prog
,
464 "%s shader output `%s' specifies %s "
465 "interpolation qualifier, "
466 "but %s shader input specifies %s "
467 "interpolation qualifier\n",
470 output
->interpolation_string(),
472 input
->interpolation_string());
483 * Populates a shaders symbol table with all global declarations
486 populate_symbol_table(gl_shader
*sh
)
488 sh
->symbols
= new(sh
) glsl_symbol_table
;
490 foreach_list(node
, sh
->ir
) {
491 ir_instruction
*const inst
= (ir_instruction
*) node
;
495 if ((func
= inst
->as_function()) != NULL
) {
496 sh
->symbols
->add_function(func
->name
, func
);
497 } else if ((var
= inst
->as_variable()) != NULL
) {
498 sh
->symbols
->add_variable(var
->name
, var
);
505 * Remap variables referenced in an instruction tree
507 * This is used when instruction trees are cloned from one shader and placed in
508 * another. These trees will contain references to \c ir_variable nodes that
509 * do not exist in the target shader. This function finds these \c ir_variable
510 * references and replaces the references with matching variables in the target
513 * If there is no matching variable in the target shader, a clone of the
514 * \c ir_variable is made and added to the target shader. The new variable is
515 * added to \b both the instruction stream and the symbol table.
517 * \param inst IR tree that is to be processed.
518 * \param symbols Symbol table containing global scope symbols in the
520 * \param instructions Instruction stream where new variable declarations
524 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
527 class remap_visitor
: public ir_hierarchical_visitor
{
529 remap_visitor(struct gl_shader
*target
,
532 this->target
= target
;
533 this->symbols
= target
->symbols
;
534 this->instructions
= target
->ir
;
538 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
540 if (ir
->var
->mode
== ir_var_temporary
) {
541 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
545 return visit_continue
;
548 ir_variable
*const existing
=
549 this->symbols
->get_variable(ir
->var
->name
);
550 if (existing
!= NULL
)
553 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
555 this->symbols
->add_variable(copy
->name
, copy
);
556 this->instructions
->push_head(copy
);
560 return visit_continue
;
564 struct gl_shader
*target
;
565 glsl_symbol_table
*symbols
;
566 exec_list
*instructions
;
570 remap_visitor
v(target
, temps
);
577 * Move non-declarations from one instruction stream to another
579 * The intended usage pattern of this function is to pass the pointer to the
580 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
581 * pointer) for \c last and \c false for \c make_copies on the first
582 * call. Successive calls pass the return value of the previous call for
583 * \c last and \c true for \c make_copies.
585 * \param instructions Source instruction stream
586 * \param last Instruction after which new instructions should be
587 * inserted in the target instruction stream
588 * \param make_copies Flag selecting whether instructions in \c instructions
589 * should be copied (via \c ir_instruction::clone) into the
590 * target list or moved.
593 * The new "last" instruction in the target instruction stream. This pointer
594 * is suitable for use as the \c last parameter of a later call to this
598 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
599 bool make_copies
, gl_shader
*target
)
601 hash_table
*temps
= NULL
;
604 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
605 hash_table_pointer_compare
);
607 foreach_list_safe(node
, instructions
) {
608 ir_instruction
*inst
= (ir_instruction
*) node
;
610 if (inst
->as_function())
613 ir_variable
*var
= inst
->as_variable();
614 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
617 assert(inst
->as_assignment()
618 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
621 inst
= inst
->clone(target
, NULL
);
624 hash_table_insert(temps
, inst
, var
);
626 remap_variables(inst
, target
, temps
);
631 last
->insert_after(inst
);
636 hash_table_dtor(temps
);
642 * Get the function signature for main from a shader
644 static ir_function_signature
*
645 get_main_function_signature(gl_shader
*sh
)
647 ir_function
*const f
= sh
->symbols
->get_function("main");
649 exec_list void_parameters
;
651 /* Look for the 'void main()' signature and ensure that it's defined.
652 * This keeps the linker from accidentally pick a shader that just
653 * contains a prototype for main.
655 * We don't have to check for multiple definitions of main (in multiple
656 * shaders) because that would have already been caught above.
658 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
659 if ((sig
!= NULL
) && sig
->is_defined
) {
669 * Combine a group of shaders for a single stage to generate a linked shader
672 * If this function is supplied a single shader, it is cloned, and the new
673 * shader is returned.
675 static struct gl_shader
*
676 link_intrastage_shaders(struct gl_shader_program
*prog
,
677 struct gl_shader
**shader_list
,
678 unsigned num_shaders
)
680 /* Check that global variables defined in multiple shaders are consistent.
682 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
685 /* Check that there is only a single definition of each function signature
686 * across all shaders.
688 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
689 foreach_list(node
, shader_list
[i
]->ir
) {
690 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
695 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
696 ir_function
*const other
=
697 shader_list
[j
]->symbols
->get_function(f
->name
);
699 /* If the other shader has no function (and therefore no function
700 * signatures) with the same name, skip to the next shader.
705 foreach_iter (exec_list_iterator
, iter
, *f
) {
706 ir_function_signature
*sig
=
707 (ir_function_signature
*) iter
.get();
709 if (!sig
->is_defined
|| sig
->is_built_in
)
712 ir_function_signature
*other_sig
=
713 other
->exact_matching_signature(& sig
->parameters
);
715 if ((other_sig
!= NULL
) && other_sig
->is_defined
716 && !other_sig
->is_built_in
) {
717 linker_error_printf(prog
,
718 "function `%s' is multiply defined",
727 /* Find the shader that defines main, and make a clone of it.
729 * Starting with the clone, search for undefined references. If one is
730 * found, find the shader that defines it. Clone the reference and add
731 * it to the shader. Repeat until there are no undefined references or
732 * until a reference cannot be resolved.
734 gl_shader
*main
= NULL
;
735 for (unsigned i
= 0; i
< num_shaders
; i
++) {
736 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
737 main
= shader_list
[i
];
743 linker_error_printf(prog
, "%s shader lacks `main'\n",
744 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
745 ? "vertex" : "fragment");
749 gl_shader
*const linked
= _mesa_new_shader(NULL
, 0, main
->Type
);
750 linked
->ir
= new(linked
) exec_list
;
751 clone_ir_list(linked
, linked
->ir
, main
->ir
);
753 populate_symbol_table(linked
);
755 /* The a pointer to the main function in the final linked shader (i.e., the
756 * copy of the original shader that contained the main function).
758 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
760 /* Move any instructions other than variable declarations or function
761 * declarations into main.
763 exec_node
*insertion_point
=
764 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
767 for (unsigned i
= 0; i
< num_shaders
; i
++) {
768 if (shader_list
[i
] == main
)
771 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
772 insertion_point
, true, linked
);
775 /* Resolve initializers for global variables in the linked shader.
777 unsigned num_linking_shaders
= num_shaders
;
778 for (unsigned i
= 0; i
< num_shaders
; i
++)
779 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
781 gl_shader
**linking_shaders
=
782 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
784 memcpy(linking_shaders
, shader_list
,
785 sizeof(linking_shaders
[0]) * num_shaders
);
787 unsigned idx
= num_shaders
;
788 for (unsigned i
= 0; i
< num_shaders
; i
++) {
789 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
790 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
791 idx
+= shader_list
[i
]->num_builtins_to_link
;
794 assert(idx
== num_linking_shaders
);
796 link_function_calls(prog
, linked
, linking_shaders
, num_linking_shaders
);
798 free(linking_shaders
);
804 struct uniform_node
{
806 struct gl_uniform
*u
;
811 assign_uniform_locations(struct gl_shader_program
*prog
)
815 unsigned total_uniforms
= 0;
816 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
817 hash_table_string_compare
);
819 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
820 unsigned next_position
= 0;
822 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
823 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
825 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
828 const unsigned vec4_slots
= (var
->component_slots() + 3) / 4;
829 if (vec4_slots
== 0) {
830 /* If we've got a sampler or an aggregate of them, the size can
831 * end up zero. Don't allocate any space.
836 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, var
->name
);
838 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
839 n
->u
= (gl_uniform
*) calloc(vec4_slots
, sizeof(struct gl_uniform
));
840 n
->slots
= vec4_slots
;
842 n
->u
[0].Name
= strdup(var
->name
);
843 for (unsigned j
= 1; j
< vec4_slots
; j
++)
844 n
->u
[j
].Name
= n
->u
[0].Name
;
846 hash_table_insert(ht
, n
, n
->u
[0].Name
);
847 uniforms
.push_tail(& n
->link
);
848 total_uniforms
+= vec4_slots
;
851 if (var
->constant_value
!= NULL
)
852 for (unsigned j
= 0; j
< vec4_slots
; j
++)
853 n
->u
[j
].Initialized
= true;
855 var
->location
= next_position
;
857 for (unsigned j
= 0; j
< vec4_slots
; j
++) {
858 switch (prog
->_LinkedShaders
[i
]->Type
) {
859 case GL_VERTEX_SHADER
:
860 n
->u
[j
].VertPos
= next_position
;
862 case GL_FRAGMENT_SHADER
:
863 n
->u
[j
].FragPos
= next_position
;
865 case GL_GEOMETRY_SHADER
:
866 /* FINISHME: Support geometry shaders. */
867 assert(prog
->_LinkedShaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
876 gl_uniform_list
*ul
= (gl_uniform_list
*)
877 calloc(1, sizeof(gl_uniform_list
));
879 ul
->Size
= total_uniforms
;
880 ul
->NumUniforms
= total_uniforms
;
881 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
885 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
886 ; node
->link
.next
!= NULL
888 next
= (uniform_node
*) node
->link
.next
;
891 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
) * node
->slots
);
905 * Find a contiguous set of available bits in a bitmask
907 * \param used_mask Bits representing used (1) and unused (0) locations
908 * \param needed_count Number of contiguous bits needed.
911 * Base location of the available bits on success or -1 on failure.
914 find_available_slots(unsigned used_mask
, unsigned needed_count
)
916 unsigned needed_mask
= (1 << needed_count
) - 1;
917 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
919 /* The comparison to 32 is redundant, but without it GCC emits "warning:
920 * cannot optimize possibly infinite loops" for the loop below.
922 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
925 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
926 if ((needed_mask
& ~used_mask
) == needed_mask
)
937 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
939 /* Mark invalid attribute locations as being used.
941 unsigned used_locations
= (max_attribute_index
>= 32)
942 ? ~0 : ~((1 << max_attribute_index
) - 1);
944 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
945 assert(sh
->Type
== GL_VERTEX_SHADER
);
947 /* Operate in a total of four passes.
949 * 1. Invalidate the location assignments for all vertex shader inputs.
951 * 2. Assign locations for inputs that have user-defined (via
952 * glBindVertexAttribLocation) locatoins.
954 * 3. Sort the attributes without assigned locations by number of slots
955 * required in decreasing order. Fragmentation caused by attribute
956 * locations assigned by the application may prevent large attributes
957 * from having enough contiguous space.
959 * 4. Assign locations to any inputs without assigned locations.
962 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
964 if (prog
->Attributes
!= NULL
) {
965 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
966 ir_variable
*const var
=
967 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
969 /* Note: attributes that occupy multiple slots, such as arrays or
970 * matrices, may appear in the attrib array multiple times.
972 if ((var
== NULL
) || (var
->location
!= -1))
975 /* From page 61 of the OpenGL 4.0 spec:
977 * "LinkProgram will fail if the attribute bindings assigned by
978 * BindAttribLocation do not leave not enough space to assign a
979 * location for an active matrix attribute or an active attribute
980 * array, both of which require multiple contiguous generic
983 * Previous versions of the spec contain similar language but omit the
984 * bit about attribute arrays.
986 * Page 61 of the OpenGL 4.0 spec also says:
988 * "It is possible for an application to bind more than one
989 * attribute name to the same location. This is referred to as
990 * aliasing. This will only work if only one of the aliased
991 * attributes is active in the executable program, or if no path
992 * through the shader consumes more than one attribute of a set
993 * of attributes aliased to the same location. A link error can
994 * occur if the linker determines that every path through the
995 * shader consumes multiple aliased attributes, but
996 * implementations are not required to generate an error in this
999 * These two paragraphs are either somewhat contradictory, or I don't
1000 * fully understand one or both of them.
1002 /* FINISHME: The code as currently written does not support attribute
1003 * FINISHME: location aliasing (see comment above).
1005 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
1006 const unsigned slots
= count_attribute_slots(var
->type
);
1008 /* Mask representing the contiguous slots that will be used by this
1011 const unsigned use_mask
= (1 << slots
) - 1;
1013 /* Generate a link error if the set of bits requested for this
1014 * attribute overlaps any previously allocated bits.
1016 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1017 linker_error_printf(prog
,
1018 "insufficient contiguous attribute locations "
1019 "available for vertex shader input `%s'",
1024 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
1025 used_locations
|= (use_mask
<< attr
);
1029 /* Temporary storage for the set of attributes that need locations assigned.
1035 /* Used below in the call to qsort. */
1036 static int compare(const void *a
, const void *b
)
1038 const temp_attr
*const l
= (const temp_attr
*) a
;
1039 const temp_attr
*const r
= (const temp_attr
*) b
;
1041 /* Reversed because we want a descending order sort below. */
1042 return r
->slots
- l
->slots
;
1046 unsigned num_attr
= 0;
1048 foreach_list(node
, sh
->ir
) {
1049 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1051 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1054 /* The location was explicitly assigned, nothing to do here.
1056 if (var
->location
!= -1)
1059 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
1060 to_assign
[num_attr
].var
= var
;
1064 /* If all of the attributes were assigned locations by the application (or
1065 * are built-in attributes with fixed locations), return early. This should
1066 * be the common case.
1071 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1073 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1074 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1075 * to prevent it from being automatically allocated below.
1077 find_deref_visitor
find("gl_Vertex");
1079 if (find
.variable_found())
1080 used_locations
|= (1 << 0);
1082 for (unsigned i
= 0; i
< num_attr
; i
++) {
1083 /* Mask representing the contiguous slots that will be used by this
1086 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1088 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1091 linker_error_printf(prog
,
1092 "insufficient contiguous attribute locations "
1093 "available for vertex shader input `%s'",
1094 to_assign
[i
].var
->name
);
1098 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1099 used_locations
|= (use_mask
<< location
);
1107 assign_varying_locations(struct gl_shader_program
*prog
,
1108 gl_shader
*producer
, gl_shader
*consumer
)
1110 /* FINISHME: Set dynamically when geometry shader support is added. */
1111 unsigned output_index
= VERT_RESULT_VAR0
;
1112 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1114 /* Operate in a total of three passes.
1116 * 1. Assign locations for any matching inputs and outputs.
1118 * 2. Mark output variables in the producer that do not have locations as
1119 * not being outputs. This lets the optimizer eliminate them.
1121 * 3. Mark input variables in the consumer that do not have locations as
1122 * not being inputs. This lets the optimizer eliminate them.
1125 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1126 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1128 foreach_list(node
, producer
->ir
) {
1129 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1131 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1132 || (output_var
->location
!= -1))
1135 ir_variable
*const input_var
=
1136 consumer
->symbols
->get_variable(output_var
->name
);
1138 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1141 assert(input_var
->location
== -1);
1143 /* FINISHME: Location assignment will need some changes when arrays,
1144 * FINISHME: matrices, and structures are allowed as shader inputs /
1145 * FINISHME: outputs.
1147 output_var
->location
= output_index
;
1148 input_var
->location
= input_index
;
1154 foreach_list(node
, producer
->ir
) {
1155 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1157 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1160 /* An 'out' variable is only really a shader output if its value is read
1161 * by the following stage.
1163 if (var
->location
== -1) {
1164 var
->mode
= ir_var_auto
;
1168 foreach_list(node
, consumer
->ir
) {
1169 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1171 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1174 if (var
->location
== -1) {
1175 if (prog
->Version
<= 120) {
1176 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1178 * Only those varying variables used (i.e. read) in
1179 * the fragment shader executable must be written to
1180 * by the vertex shader executable; declaring
1181 * superfluous varying variables in a vertex shader is
1184 * We interpret this text as meaning that the VS must
1185 * write the variable for the FS to read it. See
1186 * "glsl1-varying read but not written" in piglit.
1189 linker_error_printf(prog
, "fragment shader varying %s not written "
1190 "by vertex shader\n.", var
->name
);
1191 prog
->LinkStatus
= false;
1194 /* An 'in' variable is only really a shader input if its
1195 * value is written by the previous stage.
1197 var
->mode
= ir_var_auto
;
1204 link_shaders(struct gl_shader_program
*prog
)
1206 prog
->LinkStatus
= false;
1207 prog
->Validated
= false;
1208 prog
->_Used
= false;
1210 if (prog
->InfoLog
!= NULL
)
1211 talloc_free(prog
->InfoLog
);
1213 prog
->InfoLog
= talloc_strdup(NULL
, "");
1215 /* Separate the shaders into groups based on their type.
1217 struct gl_shader
**vert_shader_list
;
1218 unsigned num_vert_shaders
= 0;
1219 struct gl_shader
**frag_shader_list
;
1220 unsigned num_frag_shaders
= 0;
1222 vert_shader_list
= (struct gl_shader
**)
1223 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1224 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1226 unsigned min_version
= UINT_MAX
;
1227 unsigned max_version
= 0;
1228 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1229 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1230 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1232 switch (prog
->Shaders
[i
]->Type
) {
1233 case GL_VERTEX_SHADER
:
1234 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1237 case GL_FRAGMENT_SHADER
:
1238 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1241 case GL_GEOMETRY_SHADER
:
1242 /* FINISHME: Support geometry shaders. */
1243 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1248 /* Previous to GLSL version 1.30, different compilation units could mix and
1249 * match shading language versions. With GLSL 1.30 and later, the versions
1250 * of all shaders must match.
1252 assert(min_version
>= 110);
1253 assert(max_version
<= 130);
1254 if ((max_version
>= 130) && (min_version
!= max_version
)) {
1255 linker_error_printf(prog
, "all shaders must use same shading "
1256 "language version\n");
1260 prog
->Version
= max_version
;
1262 /* Link all shaders for a particular stage and validate the result.
1264 prog
->_NumLinkedShaders
= 0;
1265 if (num_vert_shaders
> 0) {
1266 gl_shader
*const sh
=
1267 link_intrastage_shaders(prog
, vert_shader_list
, num_vert_shaders
);
1272 if (!validate_vertex_shader_executable(prog
, sh
))
1275 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1276 prog
->_NumLinkedShaders
++;
1279 if (num_frag_shaders
> 0) {
1280 gl_shader
*const sh
=
1281 link_intrastage_shaders(prog
, frag_shader_list
, num_frag_shaders
);
1286 if (!validate_fragment_shader_executable(prog
, sh
))
1289 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1290 prog
->_NumLinkedShaders
++;
1293 /* Here begins the inter-stage linking phase. Some initial validation is
1294 * performed, then locations are assigned for uniforms, attributes, and
1297 if (cross_validate_uniforms(prog
)) {
1298 /* Validate the inputs of each stage with the output of the preceeding
1301 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++) {
1302 if (!cross_validate_outputs_to_inputs(prog
,
1303 prog
->_LinkedShaders
[i
- 1],
1304 prog
->_LinkedShaders
[i
]))
1308 prog
->LinkStatus
= true;
1311 /* Do common optimization before assigning storage for attributes,
1312 * uniforms, and varyings. Later optimization could possibly make
1313 * some of that unused.
1315 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1316 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true))
1320 assign_uniform_locations(prog
);
1322 if (prog
->_LinkedShaders
[0]->Type
== GL_VERTEX_SHADER
)
1323 /* FINISHME: The value of the max_attribute_index parameter is
1324 * FINISHME: implementation dependent based on the value of
1325 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1326 * FINISHME: at least 16, so hardcode 16 for now.
1328 if (!assign_attribute_locations(prog
, 16))
1331 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++)
1332 assign_varying_locations(prog
,
1333 prog
->_LinkedShaders
[i
- 1],
1334 prog
->_LinkedShaders
[i
]);
1336 /* FINISHME: Assign fragment shader output locations. */
1339 free(vert_shader_list
);