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 "glsl_symbol_table.h"
80 #include "hash_table.h"
81 #include "shader_api.h"
85 * Visitor that determines whether or not a variable is ever written.
87 class find_assignment_visitor
: public ir_hierarchical_visitor
{
89 find_assignment_visitor(const char *name
)
90 : name(name
), found(false)
95 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
97 ir_variable
*const var
= ir
->lhs
->variable_referenced();
99 if (strcmp(name
, var
->name
) == 0) {
104 return visit_continue_with_parent
;
107 bool variable_found()
113 const char *name
; /**< Find writes to a variable with this name. */
114 bool found
; /**< Was a write to the variable found? */
119 linker_error_printf(gl_shader_program
*prog
, const char *fmt
, ...)
123 prog
->InfoLog
= talloc_strdup_append(prog
->InfoLog
, "error: ");
125 prog
->InfoLog
= talloc_vasprintf_append(prog
->InfoLog
, fmt
, ap
);
131 invalidate_variable_locations(gl_shader
*sh
, enum ir_variable_mode mode
,
134 foreach_list(node
, sh
->ir
) {
135 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
137 if ((var
== NULL
) || (var
->mode
!= (unsigned) mode
))
140 /* Only assign locations for generic attributes / varyings / etc.
142 if (var
->location
>= generic_base
)
149 * Determine the number of attribute slots required for a particular type
151 * This code is here because it implements the language rules of a specific
152 * GLSL version. Since it's a property of the language and not a property of
153 * types in general, it doesn't really belong in glsl_type.
156 count_attribute_slots(const glsl_type
*t
)
158 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
160 * "A scalar input counts the same amount against this limit as a vec4,
161 * so applications may want to consider packing groups of four
162 * unrelated float inputs together into a vector to better utilize the
163 * capabilities of the underlying hardware. A matrix input will use up
164 * multiple locations. The number of locations used will equal the
165 * number of columns in the matrix."
167 * The spec does not explicitly say how arrays are counted. However, it
168 * should be safe to assume the total number of slots consumed by an array
169 * is the number of entries in the array multiplied by the number of slots
170 * consumed by a single element of the array.
174 return t
->array_size() * count_attribute_slots(t
->element_type());
177 return t
->matrix_columns
;
184 * Verify that a vertex shader executable meets all semantic requirements
186 * \param shader Vertex shader executable to be verified
189 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
190 struct gl_shader
*shader
)
195 if (!shader
->symbols
->get_function("main")) {
196 linker_error_printf(prog
, "vertex shader lacks `main'\n");
200 find_assignment_visitor
find("gl_Position");
201 find
.run(shader
->ir
);
202 if (!find
.variable_found()) {
203 linker_error_printf(prog
,
204 "vertex shader does not write to `gl_Position'\n");
213 * Verify that a fragment shader executable meets all semantic requirements
215 * \param shader Fragment shader executable to be verified
218 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
219 struct gl_shader
*shader
)
224 if (!shader
->symbols
->get_function("main")) {
225 linker_error_printf(prog
, "fragment shader lacks `main'\n");
229 find_assignment_visitor
frag_color("gl_FragColor");
230 find_assignment_visitor
frag_data("gl_FragData");
232 frag_color
.run(shader
->ir
);
233 frag_data
.run(shader
->ir
);
235 if (frag_color
.variable_found() && frag_data
.variable_found()) {
236 linker_error_printf(prog
, "fragment shader writes to both "
237 "`gl_FragColor' and `gl_FragData'\n");
246 * Generate a string describing the mode of a variable
249 mode_string(const ir_variable
*var
)
253 return (var
->read_only
) ? "global constant" : "global variable";
255 case ir_var_uniform
: return "uniform";
256 case ir_var_in
: return "shader input";
257 case ir_var_out
: return "shader output";
258 case ir_var_inout
: return "shader inout";
260 assert(!"Should not get here.");
261 return "invalid variable";
267 * Perform validation of global variables used across multiple shaders
270 cross_validate_globals(struct gl_shader_program
*prog
,
271 struct gl_shader
**shader_list
,
272 unsigned num_shaders
,
275 /* Examine all of the uniforms in all of the shaders and cross validate
278 glsl_symbol_table variables
;
279 for (unsigned i
= 0; i
< num_shaders
; i
++) {
280 foreach_list(node
, shader_list
[i
]->ir
) {
281 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
286 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
289 /* If a global with this name has already been seen, verify that the
290 * new instance has the same type. In addition, if the globals have
291 * initializers, the values of the initializers must be the same.
293 ir_variable
*const existing
= variables
.get_variable(var
->name
);
294 if (existing
!= NULL
) {
295 if (var
->type
!= existing
->type
) {
296 linker_error_printf(prog
, "%s `%s' declared as type "
297 "`%s' and type `%s'\n",
299 var
->name
, var
->type
->name
,
300 existing
->type
->name
);
304 /* FINISHME: Handle non-constant initializers.
306 if (var
->constant_value
!= NULL
) {
307 if (existing
->constant_value
!= NULL
) {
308 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
309 linker_error_printf(prog
, "initializers for %s "
310 "`%s' have differing values\n",
311 mode_string(var
), var
->name
);
315 /* If the first-seen instance of a particular uniform did not
316 * have an initializer but a later instance does, copy the
317 * initializer to the version stored in the symbol table.
319 /* FINISHME: This is wrong. The constant_value field should
320 * FINISHME: not be modified! Imagine a case where a shader
321 * FINISHME: without an initializer is linked in two different
322 * FINISHME: programs with shaders that have differing
323 * FINISHME: initializers. Linking with the first will
324 * FINISHME: modify the shader, and linking with the second
325 * FINISHME: will fail.
327 existing
->constant_value
= var
->constant_value
->clone(NULL
);
330 variables
.add_variable(var
->name
, var
);
339 * Perform validation of uniforms used across multiple shader stages
342 cross_validate_uniforms(struct gl_shader_program
*prog
)
344 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
345 prog
->_NumLinkedShaders
, true);
350 * Validate that outputs from one stage match inputs of another
353 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
354 gl_shader
*producer
, gl_shader
*consumer
)
356 glsl_symbol_table parameters
;
357 /* FINISHME: Figure these out dynamically. */
358 const char *const producer_stage
= "vertex";
359 const char *const consumer_stage
= "fragment";
361 /* Find all shader outputs in the "producer" stage.
363 foreach_list(node
, producer
->ir
) {
364 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
366 /* FINISHME: For geometry shaders, this should also look for inout
367 * FINISHME: variables.
369 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
372 parameters
.add_variable(var
->name
, var
);
376 /* Find all shader inputs in the "consumer" stage. Any variables that have
377 * matching outputs already in the symbol table must have the same type and
380 foreach_list(node
, consumer
->ir
) {
381 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
383 /* FINISHME: For geometry shaders, this should also look for inout
384 * FINISHME: variables.
386 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
389 ir_variable
*const output
= parameters
.get_variable(input
->name
);
390 if (output
!= NULL
) {
391 /* Check that the types match between stages.
393 if (input
->type
!= output
->type
) {
394 linker_error_printf(prog
,
395 "%s shader output `%s' delcared as "
396 "type `%s', but %s shader input declared "
398 producer_stage
, output
->name
,
400 consumer_stage
, input
->type
->name
);
404 /* Check that all of the qualifiers match between stages.
406 if (input
->centroid
!= output
->centroid
) {
407 linker_error_printf(prog
,
408 "%s shader output `%s' %s centroid qualifier, "
409 "but %s shader input %s centroid qualifier\n",
412 (output
->centroid
) ? "has" : "lacks",
414 (input
->centroid
) ? "has" : "lacks");
418 if (input
->invariant
!= output
->invariant
) {
419 linker_error_printf(prog
,
420 "%s shader output `%s' %s invariant qualifier, "
421 "but %s shader input %s invariant qualifier\n",
424 (output
->invariant
) ? "has" : "lacks",
426 (input
->invariant
) ? "has" : "lacks");
430 if (input
->interpolation
!= output
->interpolation
) {
431 linker_error_printf(prog
,
432 "%s shader output `%s' specifies %s "
433 "interpolation qualifier, "
434 "but %s shader input specifies %s "
435 "interpolation qualifier\n",
438 output
->interpolation_string(),
440 input
->interpolation_string());
451 * Populates a shaders symbol table with all global declarations
454 populate_symbol_table(gl_shader
*sh
)
456 sh
->symbols
= new(sh
) glsl_symbol_table
;
458 foreach_list(node
, sh
->ir
) {
459 ir_instruction
*const inst
= (ir_instruction
*) node
;
463 if ((func
= inst
->as_function()) != NULL
) {
464 sh
->symbols
->add_function(func
->name
, func
);
465 } else if ((var
= inst
->as_variable()) != NULL
) {
466 sh
->symbols
->add_variable(var
->name
, var
);
473 * Remap variables referenced in an instruction tree
475 * This is used when instruction trees are cloned from one shader and placed in
476 * another. These trees will contain references to \c ir_variable nodes that
477 * do not exist in the target shader. This function finds these \c ir_variable
478 * references and replaces the references with matching variables in the target
481 * If there is no matching variable in the target shader, a clone of the
482 * \c ir_variable is made and added to the target shader. The new variable is
483 * added to \b both the instruction stream and the symbol table.
485 * \param inst IR tree that is to be processed.
486 * \param symbols Symbol table containing global scope symbols in the
488 * \param instructions Instruction stream where new variable declarations
492 remap_variables(ir_instruction
*inst
, glsl_symbol_table
*symbols
,
493 exec_list
*instructions
)
495 class remap_visitor
: public ir_hierarchical_visitor
{
497 remap_visitor(glsl_symbol_table
*symbols
, exec_list
*instructions
)
499 this->symbols
= symbols
;
500 this->instructions
= instructions
;
503 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
505 ir_variable
*const existing
=
506 this->symbols
->get_variable(ir
->var
->name
);
507 if (existing
!= NULL
)
510 ir_variable
*copy
= ir
->var
->clone(NULL
);
512 this->symbols
->add_variable(copy
->name
, copy
);
513 this->instructions
->push_head(copy
);
516 return visit_continue
;
520 glsl_symbol_table
*symbols
;
521 exec_list
*instructions
;
524 remap_visitor
v(symbols
, instructions
);
531 * Move non-declarations from one instruction stream to another
533 * The intended usage pattern of this function is to pass the pointer to the
534 * head sentinal of a list (i.e., a pointer to the list cast to an \c exec_node
535 * pointer) for \c last and \c false for \c make_copies on the first
536 * call. Successive calls pass the return value of the previous call for
537 * \c last and \c true for \c make_copies.
539 * \param instructions Source instruction stream
540 * \param last Instruction after which new instructions should be
541 * inserted in the target instruction stream
542 * \param make_copies Flag selecting whether instructions in \c instructions
543 * should be copied (via \c ir_instruction::clone) into the
544 * target list or moved.
547 * The new "last" instruction in the target instruction stream. This pointer
548 * is suitable for use as the \c last parameter of a later call to this
552 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
553 bool make_copies
, gl_shader
*target
)
555 foreach_list_safe(node
, instructions
) {
556 ir_instruction
*inst
= (ir_instruction
*) node
;
558 if (inst
->as_variable() || inst
->as_function())
561 assert(inst
->as_assignment());
564 inst
= inst
->clone(NULL
);
565 remap_variables(inst
, target
->symbols
, target
->ir
);
570 last
->insert_after(inst
);
578 * Get the function signature for main from a shader
580 static ir_function_signature
*
581 get_main_function_signature(gl_shader
*sh
)
583 ir_function
*const f
= sh
->symbols
->get_function("main");
585 exec_list void_parameters
;
587 /* Look for the 'void main()' signature and ensure that it's defined.
588 * This keeps the linker from accidentally pick a shader that just
589 * contains a prototype for main.
591 * We don't have to check for multiple definitions of main (in multiple
592 * shaders) because that would have already been caught above.
594 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
595 if ((sig
!= NULL
) && sig
->is_defined
) {
605 * Combine a group of shaders for a single stage to generate a linked shader
608 * If this function is supplied a single shader, it is cloned, and the new
609 * shader is returned.
611 static struct gl_shader
*
612 link_intrastage_shaders(struct gl_shader_program
*prog
,
613 struct gl_shader
**shader_list
,
614 unsigned num_shaders
)
616 /* Check that global variables defined in multiple shaders are consistent.
618 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
621 /* Check that there is only a single definition of each function signature
622 * across all shaders.
624 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
625 foreach_list(node
, shader_list
[i
]->ir
) {
626 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
631 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
632 ir_function
*const other
=
633 shader_list
[j
]->symbols
->get_function(f
->name
);
635 /* If the other shader has no function (and therefore no function
636 * signatures) with the same name, skip to the next shader.
641 foreach_iter (exec_list_iterator
, iter
, *f
) {
642 ir_function_signature
*sig
=
643 (ir_function_signature
*) iter
.get();
645 if (!sig
->is_defined
|| sig
->is_built_in
)
648 ir_function_signature
*other_sig
=
649 other
->exact_matching_signature(& sig
->parameters
);
651 if ((other_sig
!= NULL
) && other_sig
->is_defined
652 && !other_sig
->is_built_in
) {
653 linker_error_printf(prog
,
654 "function `%s' is multiply defined",
663 /* Find the shader that defines main, and make a clone of it.
665 * Starting with the clone, search for undefined references. If one is
666 * found, find the shader that defines it. Clone the reference and add
667 * it to the shader. Repeat until there are no undefined references or
668 * until a reference cannot be resolved.
670 gl_shader
*main
= NULL
;
671 for (unsigned i
= 0; i
< num_shaders
; i
++) {
672 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
673 main
= shader_list
[i
];
679 linker_error_printf(prog
, "%s shader lacks `main'\n",
680 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
681 ? "vertex" : "fragment");
685 gl_shader
*const linked
= _mesa_new_shader(NULL
, 0, main
->Type
);
686 linked
->ir
= new(linked
) exec_list
;
687 clone_ir_list(linked
->ir
, main
->ir
);
689 populate_symbol_table(linked
);
691 /* The a pointer to the main function in the final linked shader (i.e., the
692 * copy of the original shader that contained the main function).
694 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
696 /* Move any instructions other than variable declarations or function
697 * declarations into main.
699 exec_node
*insertion_point
=
700 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
703 for (unsigned i
= 0; i
< num_shaders
; i
++) {
704 if (shader_list
[i
] == main
)
707 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
708 insertion_point
, true, linked
);
711 /* Resolve initializers for global variables in the linked shader.
713 link_function_calls(prog
, linked
, shader_list
, num_shaders
);
719 struct uniform_node
{
721 struct gl_uniform
*u
;
726 assign_uniform_locations(struct gl_shader_program
*prog
)
730 unsigned total_uniforms
= 0;
731 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
732 hash_table_string_compare
);
734 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
735 unsigned next_position
= 0;
737 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
738 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
740 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
743 const unsigned vec4_slots
= (var
->component_slots() + 3) / 4;
744 assert(vec4_slots
!= 0);
746 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, var
->name
);
748 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
749 n
->u
= (gl_uniform
*) calloc(vec4_slots
, sizeof(struct gl_uniform
));
750 n
->slots
= vec4_slots
;
752 n
->u
[0].Name
= strdup(var
->name
);
753 for (unsigned j
= 1; j
< vec4_slots
; j
++)
754 n
->u
[j
].Name
= n
->u
[0].Name
;
756 hash_table_insert(ht
, n
, n
->u
[0].Name
);
757 uniforms
.push_tail(& n
->link
);
758 total_uniforms
+= vec4_slots
;
761 if (var
->constant_value
!= NULL
)
762 for (unsigned j
= 0; j
< vec4_slots
; j
++)
763 n
->u
[j
].Initialized
= true;
765 var
->location
= next_position
;
767 for (unsigned j
= 0; j
< vec4_slots
; j
++) {
768 switch (prog
->_LinkedShaders
[i
]->Type
) {
769 case GL_VERTEX_SHADER
:
770 n
->u
[j
].VertPos
= next_position
;
772 case GL_FRAGMENT_SHADER
:
773 n
->u
[j
].FragPos
= next_position
;
775 case GL_GEOMETRY_SHADER
:
776 /* FINISHME: Support geometry shaders. */
777 assert(prog
->_LinkedShaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
786 gl_uniform_list
*ul
= (gl_uniform_list
*)
787 calloc(1, sizeof(gl_uniform_list
));
789 ul
->Size
= total_uniforms
;
790 ul
->NumUniforms
= total_uniforms
;
791 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
795 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
796 ; node
->link
.next
!= NULL
798 next
= (uniform_node
*) node
->link
.next
;
801 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
) * node
->slots
);
815 * Find a contiguous set of available bits in a bitmask
817 * \param used_mask Bits representing used (1) and unused (0) locations
818 * \param needed_count Number of contiguous bits needed.
821 * Base location of the available bits on success or -1 on failure.
824 find_available_slots(unsigned used_mask
, unsigned needed_count
)
826 unsigned needed_mask
= (1 << needed_count
) - 1;
827 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
829 /* The comparison to 32 is redundant, but without it GCC emits "warning:
830 * cannot optimize possibly infinite loops" for the loop below.
832 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
835 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
836 if ((needed_mask
& ~used_mask
) == needed_mask
)
847 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
849 /* Mark invalid attribute locations as being used.
851 unsigned used_locations
= (max_attribute_index
>= 32)
852 ? ~0 : ~((1 << max_attribute_index
) - 1);
854 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
855 assert(sh
->Type
== GL_VERTEX_SHADER
);
857 /* Operate in a total of four passes.
859 * 1. Invalidate the location assignments for all vertex shader inputs.
861 * 2. Assign locations for inputs that have user-defined (via
862 * glBindVertexAttribLocation) locatoins.
864 * 3. Sort the attributes without assigned locations by number of slots
865 * required in decreasing order. Fragmentation caused by attribute
866 * locations assigned by the application may prevent large attributes
867 * from having enough contiguous space.
869 * 4. Assign locations to any inputs without assigned locations.
872 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
874 if (prog
->Attributes
!= NULL
) {
875 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
876 ir_variable
*const var
=
877 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
879 /* Note: attributes that occupy multiple slots, such as arrays or
880 * matrices, may appear in the attrib array multiple times.
882 if ((var
== NULL
) || (var
->location
!= -1))
885 /* From page 61 of the OpenGL 4.0 spec:
887 * "LinkProgram will fail if the attribute bindings assigned by
888 * BindAttribLocation do not leave not enough space to assign a
889 * location for an active matrix attribute or an active attribute
890 * array, both of which require multiple contiguous generic
893 * Previous versions of the spec contain similar language but omit the
894 * bit about attribute arrays.
896 * Page 61 of the OpenGL 4.0 spec also says:
898 * "It is possible for an application to bind more than one
899 * attribute name to the same location. This is referred to as
900 * aliasing. This will only work if only one of the aliased
901 * attributes is active in the executable program, or if no path
902 * through the shader consumes more than one attribute of a set
903 * of attributes aliased to the same location. A link error can
904 * occur if the linker determines that every path through the
905 * shader consumes multiple aliased attributes, but
906 * implementations are not required to generate an error in this
909 * These two paragraphs are either somewhat contradictory, or I don't
910 * fully understand one or both of them.
912 /* FINISHME: The code as currently written does not support attribute
913 * FINISHME: location aliasing (see comment above).
915 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
916 const unsigned slots
= count_attribute_slots(var
->type
);
918 /* Mask representing the contiguous slots that will be used by this
921 const unsigned use_mask
= (1 << slots
) - 1;
923 /* Generate a link error if the set of bits requested for this
924 * attribute overlaps any previously allocated bits.
926 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
927 linker_error_printf(prog
,
928 "insufficient contiguous attribute locations "
929 "available for vertex shader input `%s'",
934 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
935 used_locations
|= (use_mask
<< attr
);
939 /* Temporary storage for the set of attributes that need locations assigned.
945 /* Used below in the call to qsort. */
946 static int compare(const void *a
, const void *b
)
948 const temp_attr
*const l
= (const temp_attr
*) a
;
949 const temp_attr
*const r
= (const temp_attr
*) b
;
951 /* Reversed because we want a descending order sort below. */
952 return r
->slots
- l
->slots
;
956 unsigned num_attr
= 0;
958 foreach_list(node
, sh
->ir
) {
959 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
961 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
964 /* The location was explicitly assigned, nothing to do here.
966 if (var
->location
!= -1)
969 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
970 to_assign
[num_attr
].var
= var
;
974 /* If all of the attributes were assigned locations by the application (or
975 * are built-in attributes with fixed locations), return early. This should
976 * be the common case.
981 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
983 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
984 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
985 * to prevent it from being automatically allocated below.
987 used_locations
|= (1 << 0);
989 for (unsigned i
= 0; i
< num_attr
; i
++) {
990 /* Mask representing the contiguous slots that will be used by this
993 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
995 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
998 linker_error_printf(prog
,
999 "insufficient contiguous attribute locations "
1000 "available for vertex shader input `%s'",
1001 to_assign
[i
].var
->name
);
1005 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1006 used_locations
|= (use_mask
<< location
);
1014 assign_varying_locations(gl_shader
*producer
, gl_shader
*consumer
)
1016 /* FINISHME: Set dynamically when geometry shader support is added. */
1017 unsigned output_index
= VERT_RESULT_VAR0
;
1018 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1020 /* Operate in a total of three passes.
1022 * 1. Assign locations for any matching inputs and outputs.
1024 * 2. Mark output variables in the producer that do not have locations as
1025 * not being outputs. This lets the optimizer eliminate them.
1027 * 3. Mark input variables in the consumer that do not have locations as
1028 * not being inputs. This lets the optimizer eliminate them.
1031 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1032 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1034 foreach_list(node
, producer
->ir
) {
1035 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1037 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1038 || (output_var
->location
!= -1))
1041 ir_variable
*const input_var
=
1042 consumer
->symbols
->get_variable(output_var
->name
);
1044 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1047 assert(input_var
->location
== -1);
1049 /* FINISHME: Location assignment will need some changes when arrays,
1050 * FINISHME: matrices, and structures are allowed as shader inputs /
1051 * FINISHME: outputs.
1053 output_var
->location
= output_index
;
1054 input_var
->location
= input_index
;
1060 foreach_list(node
, producer
->ir
) {
1061 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1063 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1066 /* An 'out' variable is only really a shader output if its value is read
1067 * by the following stage.
1069 if (var
->location
== -1) {
1070 var
->shader_out
= false;
1071 var
->mode
= ir_var_auto
;
1075 foreach_list(node
, consumer
->ir
) {
1076 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1078 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1081 /* An 'in' variable is only really a shader input if its value is written
1082 * by the previous stage.
1084 var
->shader_in
= (var
->location
!= -1);
1090 link_shaders(struct gl_shader_program
*prog
)
1092 prog
->LinkStatus
= false;
1093 prog
->Validated
= false;
1094 prog
->_Used
= false;
1096 if (prog
->InfoLog
!= NULL
)
1097 talloc_free(prog
->InfoLog
);
1099 prog
->InfoLog
= talloc_strdup(NULL
, "");
1101 /* Separate the shaders into groups based on their type.
1103 struct gl_shader
**vert_shader_list
;
1104 unsigned num_vert_shaders
= 0;
1105 struct gl_shader
**frag_shader_list
;
1106 unsigned num_frag_shaders
= 0;
1108 vert_shader_list
= (struct gl_shader
**)
1109 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1110 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1112 unsigned min_version
= UINT_MAX
;
1113 unsigned max_version
= 0;
1114 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1115 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1116 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1118 switch (prog
->Shaders
[i
]->Type
) {
1119 case GL_VERTEX_SHADER
:
1120 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1123 case GL_FRAGMENT_SHADER
:
1124 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1127 case GL_GEOMETRY_SHADER
:
1128 /* FINISHME: Support geometry shaders. */
1129 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1134 /* Previous to GLSL version 1.30, different compilation units could mix and
1135 * match shading language versions. With GLSL 1.30 and later, the versions
1136 * of all shaders must match.
1138 assert(min_version
>= 110);
1139 assert(max_version
<= 130);
1140 if ((max_version
>= 130) && (min_version
!= max_version
)) {
1141 linker_error_printf(prog
, "all shaders must use same shading "
1142 "language version\n");
1146 prog
->Version
= max_version
;
1148 /* FINISHME: Implement intra-stage linking. */
1149 prog
->_NumLinkedShaders
= 0;
1150 if (num_vert_shaders
> 0) {
1151 gl_shader
*const sh
=
1152 link_intrastage_shaders(prog
, vert_shader_list
, num_vert_shaders
);
1157 if (!validate_vertex_shader_executable(prog
, sh
))
1160 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1161 prog
->_NumLinkedShaders
++;
1164 if (num_frag_shaders
> 0) {
1165 gl_shader
*const sh
=
1166 link_intrastage_shaders(prog
, frag_shader_list
, num_frag_shaders
);
1171 if (!validate_fragment_shader_executable(prog
, sh
))
1174 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1175 prog
->_NumLinkedShaders
++;
1178 /* Here begins the inter-stage linking phase. Some initial validation is
1179 * performed, then locations are assigned for uniforms, attributes, and
1182 if (cross_validate_uniforms(prog
)) {
1183 /* Validate the inputs of each stage with the output of the preceeding
1186 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++) {
1187 if (!cross_validate_outputs_to_inputs(prog
,
1188 prog
->_LinkedShaders
[i
- 1],
1189 prog
->_LinkedShaders
[i
]))
1193 prog
->LinkStatus
= true;
1196 /* FINISHME: Perform whole-program optimization here. */
1198 assign_uniform_locations(prog
);
1200 if (prog
->_LinkedShaders
[0]->Type
== GL_VERTEX_SHADER
)
1201 /* FINISHME: The value of the max_attribute_index parameter is
1202 * FINISHME: implementation dependent based on the value of
1203 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1204 * FINISHME: at least 16, so hardcode 16 for now.
1206 if (!assign_attribute_locations(prog
, 16))
1209 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++)
1210 assign_varying_locations(prog
->_LinkedShaders
[i
- 1],
1211 prog
->_LinkedShaders
[i
]);
1213 /* FINISHME: Assign fragment shader output locations. */
1216 free(vert_shader_list
);