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 linker_error_printf(gl_shader_program
*prog
, const char *fmt
, ...)
124 prog
->InfoLog
= talloc_strdup_append(prog
->InfoLog
, "error: ");
126 prog
->InfoLog
= talloc_vasprintf_append(prog
->InfoLog
, fmt
, ap
);
132 invalidate_variable_locations(gl_shader
*sh
, enum ir_variable_mode mode
,
135 foreach_list(node
, sh
->ir
) {
136 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
138 if ((var
== NULL
) || (var
->mode
!= (unsigned) mode
))
141 /* Only assign locations for generic attributes / varyings / etc.
143 if (var
->location
>= generic_base
)
150 * Determine the number of attribute slots required for a particular type
152 * This code is here because it implements the language rules of a specific
153 * GLSL version. Since it's a property of the language and not a property of
154 * types in general, it doesn't really belong in glsl_type.
157 count_attribute_slots(const glsl_type
*t
)
159 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
161 * "A scalar input counts the same amount against this limit as a vec4,
162 * so applications may want to consider packing groups of four
163 * unrelated float inputs together into a vector to better utilize the
164 * capabilities of the underlying hardware. A matrix input will use up
165 * multiple locations. The number of locations used will equal the
166 * number of columns in the matrix."
168 * The spec does not explicitly say how arrays are counted. However, it
169 * should be safe to assume the total number of slots consumed by an array
170 * is the number of entries in the array multiplied by the number of slots
171 * consumed by a single element of the array.
175 return t
->array_size() * count_attribute_slots(t
->element_type());
178 return t
->matrix_columns
;
185 * Verify that a vertex shader executable meets all semantic requirements
187 * \param shader Vertex shader executable to be verified
190 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
191 struct gl_shader
*shader
)
196 find_assignment_visitor
find("gl_Position");
197 find
.run(shader
->ir
);
198 if (!find
.variable_found()) {
199 linker_error_printf(prog
,
200 "vertex shader does not write to `gl_Position'\n");
209 * Verify that a fragment shader executable meets all semantic requirements
211 * \param shader Fragment shader executable to be verified
214 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
215 struct gl_shader
*shader
)
220 find_assignment_visitor
frag_color("gl_FragColor");
221 find_assignment_visitor
frag_data("gl_FragData");
223 frag_color
.run(shader
->ir
);
224 frag_data
.run(shader
->ir
);
226 if (frag_color
.variable_found() && frag_data
.variable_found()) {
227 linker_error_printf(prog
, "fragment shader writes to both "
228 "`gl_FragColor' and `gl_FragData'\n");
237 * Generate a string describing the mode of a variable
240 mode_string(const ir_variable
*var
)
244 return (var
->read_only
) ? "global constant" : "global variable";
246 case ir_var_uniform
: return "uniform";
247 case ir_var_in
: return "shader input";
248 case ir_var_out
: return "shader output";
249 case ir_var_inout
: return "shader inout";
251 case ir_var_temporary
:
253 assert(!"Should not get here.");
254 return "invalid variable";
260 * Perform validation of global variables used across multiple shaders
263 cross_validate_globals(struct gl_shader_program
*prog
,
264 struct gl_shader
**shader_list
,
265 unsigned num_shaders
,
268 /* Examine all of the uniforms in all of the shaders and cross validate
271 glsl_symbol_table variables
;
272 for (unsigned i
= 0; i
< num_shaders
; i
++) {
273 foreach_list(node
, shader_list
[i
]->ir
) {
274 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
279 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
282 /* Don't cross validate temporaries that are at global scope. These
283 * will eventually get pulled into the shaders 'main'.
285 if (var
->mode
== ir_var_temporary
)
288 /* If a global with this name has already been seen, verify that the
289 * new instance has the same type. In addition, if the globals have
290 * initializers, the values of the initializers must be the same.
292 ir_variable
*const existing
= variables
.get_variable(var
->name
);
293 if (existing
!= NULL
) {
294 if (var
->type
!= existing
->type
) {
295 linker_error_printf(prog
, "%s `%s' declared as type "
296 "`%s' and type `%s'\n",
298 var
->name
, var
->type
->name
,
299 existing
->type
->name
);
303 /* FINISHME: Handle non-constant initializers.
305 if (var
->constant_value
!= NULL
) {
306 if (existing
->constant_value
!= NULL
) {
307 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
308 linker_error_printf(prog
, "initializers for %s "
309 "`%s' have differing values\n",
310 mode_string(var
), var
->name
);
314 /* If the first-seen instance of a particular uniform did not
315 * have an initializer but a later instance does, copy the
316 * initializer to the version stored in the symbol table.
318 /* FINISHME: This is wrong. The constant_value field should
319 * FINISHME: not be modified! Imagine a case where a shader
320 * FINISHME: without an initializer is linked in two different
321 * FINISHME: programs with shaders that have differing
322 * FINISHME: initializers. Linking with the first will
323 * FINISHME: modify the shader, and linking with the second
324 * FINISHME: will fail.
326 existing
->constant_value
=
327 var
->constant_value
->clone(talloc_parent(existing
), 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
, struct gl_shader
*target
,
495 class remap_visitor
: public ir_hierarchical_visitor
{
497 remap_visitor(struct gl_shader
*target
,
500 this->target
= target
;
501 this->symbols
= target
->symbols
;
502 this->instructions
= target
->ir
;
506 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
508 if (ir
->var
->mode
== ir_var_temporary
) {
509 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
513 return visit_continue
;
516 ir_variable
*const existing
=
517 this->symbols
->get_variable(ir
->var
->name
);
518 if (existing
!= NULL
)
521 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
523 this->symbols
->add_variable(copy
->name
, copy
);
524 this->instructions
->push_head(copy
);
528 return visit_continue
;
532 struct gl_shader
*target
;
533 glsl_symbol_table
*symbols
;
534 exec_list
*instructions
;
538 remap_visitor
v(target
, temps
);
545 * Move non-declarations from one instruction stream to another
547 * The intended usage pattern of this function is to pass the pointer to the
548 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
549 * pointer) for \c last and \c false for \c make_copies on the first
550 * call. Successive calls pass the return value of the previous call for
551 * \c last and \c true for \c make_copies.
553 * \param instructions Source instruction stream
554 * \param last Instruction after which new instructions should be
555 * inserted in the target instruction stream
556 * \param make_copies Flag selecting whether instructions in \c instructions
557 * should be copied (via \c ir_instruction::clone) into the
558 * target list or moved.
561 * The new "last" instruction in the target instruction stream. This pointer
562 * is suitable for use as the \c last parameter of a later call to this
566 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
567 bool make_copies
, gl_shader
*target
)
569 hash_table
*temps
= NULL
;
572 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
573 hash_table_pointer_compare
);
575 foreach_list_safe(node
, instructions
) {
576 ir_instruction
*inst
= (ir_instruction
*) node
;
578 if (inst
->as_function())
581 ir_variable
*var
= inst
->as_variable();
582 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
585 assert(inst
->as_assignment()
586 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
589 inst
= inst
->clone(target
, NULL
);
592 hash_table_insert(temps
, inst
, var
);
594 remap_variables(inst
, target
, temps
);
599 last
->insert_after(inst
);
604 hash_table_dtor(temps
);
610 * Get the function signature for main from a shader
612 static ir_function_signature
*
613 get_main_function_signature(gl_shader
*sh
)
615 ir_function
*const f
= sh
->symbols
->get_function("main");
617 exec_list void_parameters
;
619 /* Look for the 'void main()' signature and ensure that it's defined.
620 * This keeps the linker from accidentally pick a shader that just
621 * contains a prototype for main.
623 * We don't have to check for multiple definitions of main (in multiple
624 * shaders) because that would have already been caught above.
626 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
627 if ((sig
!= NULL
) && sig
->is_defined
) {
637 * Combine a group of shaders for a single stage to generate a linked shader
640 * If this function is supplied a single shader, it is cloned, and the new
641 * shader is returned.
643 static struct gl_shader
*
644 link_intrastage_shaders(struct gl_shader_program
*prog
,
645 struct gl_shader
**shader_list
,
646 unsigned num_shaders
)
648 /* Check that global variables defined in multiple shaders are consistent.
650 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
653 /* Check that there is only a single definition of each function signature
654 * across all shaders.
656 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
657 foreach_list(node
, shader_list
[i
]->ir
) {
658 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
663 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
664 ir_function
*const other
=
665 shader_list
[j
]->symbols
->get_function(f
->name
);
667 /* If the other shader has no function (and therefore no function
668 * signatures) with the same name, skip to the next shader.
673 foreach_iter (exec_list_iterator
, iter
, *f
) {
674 ir_function_signature
*sig
=
675 (ir_function_signature
*) iter
.get();
677 if (!sig
->is_defined
|| sig
->is_built_in
)
680 ir_function_signature
*other_sig
=
681 other
->exact_matching_signature(& sig
->parameters
);
683 if ((other_sig
!= NULL
) && other_sig
->is_defined
684 && !other_sig
->is_built_in
) {
685 linker_error_printf(prog
,
686 "function `%s' is multiply defined",
695 /* Find the shader that defines main, and make a clone of it.
697 * Starting with the clone, search for undefined references. If one is
698 * found, find the shader that defines it. Clone the reference and add
699 * it to the shader. Repeat until there are no undefined references or
700 * until a reference cannot be resolved.
702 gl_shader
*main
= NULL
;
703 for (unsigned i
= 0; i
< num_shaders
; i
++) {
704 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
705 main
= shader_list
[i
];
711 linker_error_printf(prog
, "%s shader lacks `main'\n",
712 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
713 ? "vertex" : "fragment");
717 gl_shader
*const linked
= _mesa_new_shader(NULL
, 0, main
->Type
);
718 linked
->ir
= new(linked
) exec_list
;
719 clone_ir_list(linked
, linked
->ir
, main
->ir
);
721 populate_symbol_table(linked
);
723 /* The a pointer to the main function in the final linked shader (i.e., the
724 * copy of the original shader that contained the main function).
726 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
728 /* Move any instructions other than variable declarations or function
729 * declarations into main.
731 exec_node
*insertion_point
=
732 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
735 for (unsigned i
= 0; i
< num_shaders
; i
++) {
736 if (shader_list
[i
] == main
)
739 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
740 insertion_point
, true, linked
);
743 /* Resolve initializers for global variables in the linked shader.
745 unsigned num_linking_shaders
= num_shaders
;
746 for (unsigned i
= 0; i
< num_shaders
; i
++)
747 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
749 gl_shader
**linking_shaders
=
750 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
752 memcpy(linking_shaders
, shader_list
,
753 sizeof(linking_shaders
[0]) * num_shaders
);
755 unsigned idx
= num_shaders
;
756 for (unsigned i
= 0; i
< num_shaders
; i
++) {
757 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
758 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
759 idx
+= shader_list
[i
]->num_builtins_to_link
;
762 assert(idx
== num_linking_shaders
);
764 link_function_calls(prog
, linked
, linking_shaders
, num_linking_shaders
);
766 free(linking_shaders
);
772 struct uniform_node
{
774 struct gl_uniform
*u
;
779 assign_uniform_locations(struct gl_shader_program
*prog
)
783 unsigned total_uniforms
= 0;
784 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
785 hash_table_string_compare
);
787 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
788 unsigned next_position
= 0;
790 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
791 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
793 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
796 const unsigned vec4_slots
= (var
->component_slots() + 3) / 4;
797 if (vec4_slots
== 0) {
798 /* If we've got a sampler or an aggregate of them, the size can
799 * end up zero. Don't allocate any space.
804 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, var
->name
);
806 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
807 n
->u
= (gl_uniform
*) calloc(vec4_slots
, sizeof(struct gl_uniform
));
808 n
->slots
= vec4_slots
;
810 n
->u
[0].Name
= strdup(var
->name
);
811 for (unsigned j
= 1; j
< vec4_slots
; j
++)
812 n
->u
[j
].Name
= n
->u
[0].Name
;
814 hash_table_insert(ht
, n
, n
->u
[0].Name
);
815 uniforms
.push_tail(& n
->link
);
816 total_uniforms
+= vec4_slots
;
819 if (var
->constant_value
!= NULL
)
820 for (unsigned j
= 0; j
< vec4_slots
; j
++)
821 n
->u
[j
].Initialized
= true;
823 var
->location
= next_position
;
825 for (unsigned j
= 0; j
< vec4_slots
; j
++) {
826 switch (prog
->_LinkedShaders
[i
]->Type
) {
827 case GL_VERTEX_SHADER
:
828 n
->u
[j
].VertPos
= next_position
;
830 case GL_FRAGMENT_SHADER
:
831 n
->u
[j
].FragPos
= next_position
;
833 case GL_GEOMETRY_SHADER
:
834 /* FINISHME: Support geometry shaders. */
835 assert(prog
->_LinkedShaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
844 gl_uniform_list
*ul
= (gl_uniform_list
*)
845 calloc(1, sizeof(gl_uniform_list
));
847 ul
->Size
= total_uniforms
;
848 ul
->NumUniforms
= total_uniforms
;
849 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
853 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
854 ; node
->link
.next
!= NULL
856 next
= (uniform_node
*) node
->link
.next
;
859 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
) * node
->slots
);
873 * Find a contiguous set of available bits in a bitmask
875 * \param used_mask Bits representing used (1) and unused (0) locations
876 * \param needed_count Number of contiguous bits needed.
879 * Base location of the available bits on success or -1 on failure.
882 find_available_slots(unsigned used_mask
, unsigned needed_count
)
884 unsigned needed_mask
= (1 << needed_count
) - 1;
885 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
887 /* The comparison to 32 is redundant, but without it GCC emits "warning:
888 * cannot optimize possibly infinite loops" for the loop below.
890 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
893 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
894 if ((needed_mask
& ~used_mask
) == needed_mask
)
905 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
907 /* Mark invalid attribute locations as being used.
909 unsigned used_locations
= (max_attribute_index
>= 32)
910 ? ~0 : ~((1 << max_attribute_index
) - 1);
912 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
913 assert(sh
->Type
== GL_VERTEX_SHADER
);
915 /* Operate in a total of four passes.
917 * 1. Invalidate the location assignments for all vertex shader inputs.
919 * 2. Assign locations for inputs that have user-defined (via
920 * glBindVertexAttribLocation) locatoins.
922 * 3. Sort the attributes without assigned locations by number of slots
923 * required in decreasing order. Fragmentation caused by attribute
924 * locations assigned by the application may prevent large attributes
925 * from having enough contiguous space.
927 * 4. Assign locations to any inputs without assigned locations.
930 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
932 if (prog
->Attributes
!= NULL
) {
933 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
934 ir_variable
*const var
=
935 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
937 /* Note: attributes that occupy multiple slots, such as arrays or
938 * matrices, may appear in the attrib array multiple times.
940 if ((var
== NULL
) || (var
->location
!= -1))
943 /* From page 61 of the OpenGL 4.0 spec:
945 * "LinkProgram will fail if the attribute bindings assigned by
946 * BindAttribLocation do not leave not enough space to assign a
947 * location for an active matrix attribute or an active attribute
948 * array, both of which require multiple contiguous generic
951 * Previous versions of the spec contain similar language but omit the
952 * bit about attribute arrays.
954 * Page 61 of the OpenGL 4.0 spec also says:
956 * "It is possible for an application to bind more than one
957 * attribute name to the same location. This is referred to as
958 * aliasing. This will only work if only one of the aliased
959 * attributes is active in the executable program, or if no path
960 * through the shader consumes more than one attribute of a set
961 * of attributes aliased to the same location. A link error can
962 * occur if the linker determines that every path through the
963 * shader consumes multiple aliased attributes, but
964 * implementations are not required to generate an error in this
967 * These two paragraphs are either somewhat contradictory, or I don't
968 * fully understand one or both of them.
970 /* FINISHME: The code as currently written does not support attribute
971 * FINISHME: location aliasing (see comment above).
973 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
974 const unsigned slots
= count_attribute_slots(var
->type
);
976 /* Mask representing the contiguous slots that will be used by this
979 const unsigned use_mask
= (1 << slots
) - 1;
981 /* Generate a link error if the set of bits requested for this
982 * attribute overlaps any previously allocated bits.
984 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
985 linker_error_printf(prog
,
986 "insufficient contiguous attribute locations "
987 "available for vertex shader input `%s'",
992 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
993 used_locations
|= (use_mask
<< attr
);
997 /* Temporary storage for the set of attributes that need locations assigned.
1003 /* Used below in the call to qsort. */
1004 static int compare(const void *a
, const void *b
)
1006 const temp_attr
*const l
= (const temp_attr
*) a
;
1007 const temp_attr
*const r
= (const temp_attr
*) b
;
1009 /* Reversed because we want a descending order sort below. */
1010 return r
->slots
- l
->slots
;
1014 unsigned num_attr
= 0;
1016 foreach_list(node
, sh
->ir
) {
1017 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1019 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1022 /* The location was explicitly assigned, nothing to do here.
1024 if (var
->location
!= -1)
1027 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
1028 to_assign
[num_attr
].var
= var
;
1032 /* If all of the attributes were assigned locations by the application (or
1033 * are built-in attributes with fixed locations), return early. This should
1034 * be the common case.
1039 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1041 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1042 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1043 * to prevent it from being automatically allocated below.
1045 used_locations
|= (1 << 0);
1047 for (unsigned i
= 0; i
< num_attr
; i
++) {
1048 /* Mask representing the contiguous slots that will be used by this
1051 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1053 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1056 linker_error_printf(prog
,
1057 "insufficient contiguous attribute locations "
1058 "available for vertex shader input `%s'",
1059 to_assign
[i
].var
->name
);
1063 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1064 used_locations
|= (use_mask
<< location
);
1072 assign_varying_locations(struct gl_shader_program
*prog
,
1073 gl_shader
*producer
, gl_shader
*consumer
)
1075 /* FINISHME: Set dynamically when geometry shader support is added. */
1076 unsigned output_index
= VERT_RESULT_VAR0
;
1077 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1079 /* Operate in a total of three passes.
1081 * 1. Assign locations for any matching inputs and outputs.
1083 * 2. Mark output variables in the producer that do not have locations as
1084 * not being outputs. This lets the optimizer eliminate them.
1086 * 3. Mark input variables in the consumer that do not have locations as
1087 * not being inputs. This lets the optimizer eliminate them.
1090 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1091 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1093 foreach_list(node
, producer
->ir
) {
1094 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1096 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1097 || (output_var
->location
!= -1))
1100 ir_variable
*const input_var
=
1101 consumer
->symbols
->get_variable(output_var
->name
);
1103 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1106 assert(input_var
->location
== -1);
1108 /* FINISHME: Location assignment will need some changes when arrays,
1109 * FINISHME: matrices, and structures are allowed as shader inputs /
1110 * FINISHME: outputs.
1112 output_var
->location
= output_index
;
1113 input_var
->location
= input_index
;
1119 foreach_list(node
, producer
->ir
) {
1120 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1122 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1125 /* An 'out' variable is only really a shader output if its value is read
1126 * by the following stage.
1128 if (var
->location
== -1) {
1129 var
->mode
= ir_var_auto
;
1133 foreach_list(node
, consumer
->ir
) {
1134 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1136 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1139 if (var
->location
== -1) {
1140 if (prog
->Version
<= 120) {
1141 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1143 * Only those varying variables used (i.e. read) in
1144 * the fragment shader executable must be written to
1145 * by the vertex shader executable; declaring
1146 * superfluous varying variables in a vertex shader is
1149 * We interpret this text as meaning that the VS must
1150 * write the variable for the FS to read it. See
1151 * "glsl1-varying read but not written" in piglit.
1154 linker_error_printf(prog
, "fragment shader varying %s not written "
1155 "by vertex shader\n.", var
->name
);
1156 prog
->LinkStatus
= false;
1159 /* An 'in' variable is only really a shader input if its
1160 * value is written by the previous stage.
1162 var
->mode
= ir_var_auto
;
1169 link_shaders(struct gl_shader_program
*prog
)
1171 prog
->LinkStatus
= false;
1172 prog
->Validated
= false;
1173 prog
->_Used
= false;
1175 if (prog
->InfoLog
!= NULL
)
1176 talloc_free(prog
->InfoLog
);
1178 prog
->InfoLog
= talloc_strdup(NULL
, "");
1180 /* Separate the shaders into groups based on their type.
1182 struct gl_shader
**vert_shader_list
;
1183 unsigned num_vert_shaders
= 0;
1184 struct gl_shader
**frag_shader_list
;
1185 unsigned num_frag_shaders
= 0;
1187 vert_shader_list
= (struct gl_shader
**)
1188 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1189 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1191 unsigned min_version
= UINT_MAX
;
1192 unsigned max_version
= 0;
1193 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1194 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1195 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1197 switch (prog
->Shaders
[i
]->Type
) {
1198 case GL_VERTEX_SHADER
:
1199 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1202 case GL_FRAGMENT_SHADER
:
1203 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1206 case GL_GEOMETRY_SHADER
:
1207 /* FINISHME: Support geometry shaders. */
1208 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1213 /* Previous to GLSL version 1.30, different compilation units could mix and
1214 * match shading language versions. With GLSL 1.30 and later, the versions
1215 * of all shaders must match.
1217 assert(min_version
>= 110);
1218 assert(max_version
<= 130);
1219 if ((max_version
>= 130) && (min_version
!= max_version
)) {
1220 linker_error_printf(prog
, "all shaders must use same shading "
1221 "language version\n");
1225 prog
->Version
= max_version
;
1227 /* Link all shaders for a particular stage and validate the result.
1229 prog
->_NumLinkedShaders
= 0;
1230 if (num_vert_shaders
> 0) {
1231 gl_shader
*const sh
=
1232 link_intrastage_shaders(prog
, vert_shader_list
, num_vert_shaders
);
1237 if (!validate_vertex_shader_executable(prog
, sh
))
1240 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1241 prog
->_NumLinkedShaders
++;
1244 if (num_frag_shaders
> 0) {
1245 gl_shader
*const sh
=
1246 link_intrastage_shaders(prog
, frag_shader_list
, num_frag_shaders
);
1251 if (!validate_fragment_shader_executable(prog
, sh
))
1254 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1255 prog
->_NumLinkedShaders
++;
1258 /* Here begins the inter-stage linking phase. Some initial validation is
1259 * performed, then locations are assigned for uniforms, attributes, and
1262 if (cross_validate_uniforms(prog
)) {
1263 /* Validate the inputs of each stage with the output of the preceeding
1266 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++) {
1267 if (!cross_validate_outputs_to_inputs(prog
,
1268 prog
->_LinkedShaders
[i
- 1],
1269 prog
->_LinkedShaders
[i
]))
1273 prog
->LinkStatus
= true;
1276 /* FINISHME: Perform whole-program optimization here. */
1277 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1278 /* Optimization passes */
1280 exec_list
*ir
= prog
->_LinkedShaders
[i
]->ir
;
1283 do_mat_op_to_vec(ir
);
1284 do_mod_to_fract(ir
);
1285 do_div_to_mul_rcp(ir
);
1286 do_explog_to_explog2(ir
);
1287 do_sub_to_add_neg(ir
);
1292 progress
= do_function_inlining(ir
) || progress
;
1293 progress
= do_dead_functions(ir
) || progress
;
1294 progress
= do_structure_splitting(ir
) || progress
;
1295 progress
= do_if_simplification(ir
) || progress
;
1296 progress
= do_copy_propagation(ir
) || progress
;
1297 progress
= do_dead_code_local(ir
) || progress
;
1298 progress
= do_dead_code(ir
) || progress
;
1299 progress
= do_tree_grafting(ir
) || progress
;
1300 progress
= do_constant_propagation(ir
) || progress
;
1301 progress
= do_constant_variable(ir
) || progress
;
1302 progress
= do_constant_folding(ir
) || progress
;
1303 progress
= do_algebraic(ir
) || progress
;
1304 progress
= do_if_return(ir
) || progress
;
1306 if (ctx
->Shader
.EmitNoIfs
)
1307 progress
= do_if_to_cond_assign(ir
) || progress
;
1310 progress
= do_vec_index_to_swizzle(ir
) || progress
;
1311 /* Do this one after the previous to let the easier pass handle
1312 * constant vector indexing.
1314 progress
= do_vec_index_to_cond_assign(ir
) || progress
;
1316 progress
= do_swizzle_swizzle(ir
) || progress
;
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
);