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>
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
69 #include "glsl_parser_extras.h"
72 #include "program/hash_table.h"
74 #include "link_varyings.h"
75 #include "ir_optimization.h"
76 #include "ir_rvalue_visitor.h"
79 #include "main/shaderobj.h"
80 #include "main/enums.h"
83 void linker_error(gl_shader_program
*, const char *, ...);
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 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
110 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
111 foreach_iter(exec_list_iterator
, iter
, *ir
) {
112 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
113 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
115 if (sig_param
->mode
== ir_var_function_out
||
116 sig_param
->mode
== ir_var_function_inout
) {
117 ir_variable
*var
= param_rval
->variable_referenced();
118 if (var
&& strcmp(name
, var
->name
) == 0) {
126 if (ir
->return_deref
!= NULL
) {
127 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
129 if (strcmp(name
, var
->name
) == 0) {
135 return visit_continue_with_parent
;
138 bool variable_found()
144 const char *name
; /**< Find writes to a variable with this name. */
145 bool found
; /**< Was a write to the variable found? */
150 * Visitor that determines whether or not a variable is ever read.
152 class find_deref_visitor
: public ir_hierarchical_visitor
{
154 find_deref_visitor(const char *name
)
155 : name(name
), found(false)
160 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
162 if (strcmp(this->name
, ir
->var
->name
) == 0) {
167 return visit_continue
;
170 bool variable_found() const
176 const char *name
; /**< Find writes to a variable with this name. */
177 bool found
; /**< Was a write to the variable found? */
181 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
183 unsigned num_vertices
;
184 gl_shader_program
*prog
;
186 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
188 this->num_vertices
= num_vertices
;
192 virtual ~geom_array_resize_visitor()
197 virtual ir_visitor_status
visit(ir_variable
*var
)
199 if (!var
->type
->is_array() || var
->mode
!= ir_var_shader_in
)
200 return visit_continue
;
202 unsigned size
= var
->type
->length
;
204 /* Generate a link error if the shader has declared this array with an
207 if (size
&& size
!= this->num_vertices
) {
208 linker_error(this->prog
, "size of array %s declared as %u, "
209 "but number of input vertices is %u\n",
210 var
->name
, size
, this->num_vertices
);
211 return visit_continue
;
214 /* Generate a link error if the shader attempts to access an input
215 * array using an index too large for its actual size assigned at link
218 if (var
->max_array_access
>= this->num_vertices
) {
219 linker_error(this->prog
, "geometry shader accesses element %i of "
220 "%s, but only %i input vertices\n",
221 var
->max_array_access
, var
->name
, this->num_vertices
);
222 return visit_continue
;
225 var
->type
= glsl_type::get_array_instance(var
->type
->element_type(),
227 var
->max_array_access
= this->num_vertices
- 1;
229 return visit_continue
;
232 /* Dereferences of input variables need to be updated so that their type
233 * matches the newly assigned type of the variable they are accessing. */
234 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
236 ir
->type
= ir
->var
->type
;
237 return visit_continue
;
240 /* Dereferences of 2D input arrays need to be updated so that their type
241 * matches the newly assigned type of the array they are accessing. */
242 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
244 const glsl_type
*const vt
= ir
->array
->type
;
246 ir
->type
= vt
->element_type();
247 return visit_continue
;
253 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
257 ralloc_strcat(&prog
->InfoLog
, "error: ");
259 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
262 prog
->LinkStatus
= false;
267 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
271 ralloc_strcat(&prog
->InfoLog
, "error: ");
273 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
280 * Given a string identifying a program resource, break it into a base name
281 * and an optional array index in square brackets.
283 * If an array index is present, \c out_base_name_end is set to point to the
284 * "[" that precedes the array index, and the array index itself is returned
287 * If no array index is present (or if the array index is negative or
288 * mal-formed), \c out_base_name_end, is set to point to the null terminator
289 * at the end of the input string, and -1 is returned.
291 * Only the final array index is parsed; if the string contains other array
292 * indices (or structure field accesses), they are left in the base name.
294 * No attempt is made to check that the base name is properly formed;
295 * typically the caller will look up the base name in a hash table, so
296 * ill-formed base names simply turn into hash table lookup failures.
299 parse_program_resource_name(const GLchar
*name
,
300 const GLchar
**out_base_name_end
)
302 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
304 * "When an integer array element or block instance number is part of
305 * the name string, it will be specified in decimal form without a "+"
306 * or "-" sign or any extra leading zeroes. Additionally, the name
307 * string will not include white space anywhere in the string."
310 const size_t len
= strlen(name
);
311 *out_base_name_end
= name
+ len
;
313 if (len
== 0 || name
[len
-1] != ']')
316 /* Walk backwards over the string looking for a non-digit character. This
317 * had better be the opening bracket for an array index.
319 * Initially, i specifies the location of the ']'. Since the string may
320 * contain only the ']' charcater, walk backwards very carefully.
323 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
326 if ((i
== 0) || name
[i
-1] != '[')
329 long array_index
= strtol(&name
[i
], NULL
, 10);
333 *out_base_name_end
= name
+ (i
- 1);
339 link_invalidate_variable_locations(gl_shader
*sh
, int input_base
,
342 foreach_list(node
, sh
->ir
) {
343 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
350 case ir_var_shader_in
:
353 case ir_var_shader_out
:
360 /* Only assign locations for generic attributes / varyings / etc.
362 if ((var
->location
>= base
) && !var
->explicit_location
)
365 if ((var
->location
== -1) && !var
->explicit_location
) {
366 var
->is_unmatched_generic_inout
= 1;
367 var
->location_frac
= 0;
369 var
->is_unmatched_generic_inout
= 0;
376 * Verify that a vertex shader executable meets all semantic requirements.
378 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
381 * \param shader Vertex shader executable to be verified
384 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
385 struct gl_shader
*shader
)
390 /* From the GLSL 1.10 spec, page 48:
392 * "The variable gl_Position is available only in the vertex
393 * language and is intended for writing the homogeneous vertex
394 * position. All executions of a well-formed vertex shader
395 * executable must write a value into this variable. [...] The
396 * variable gl_Position is available only in the vertex
397 * language and is intended for writing the homogeneous vertex
398 * position. All executions of a well-formed vertex shader
399 * executable must write a value into this variable."
401 * while in GLSL 1.40 this text is changed to:
403 * "The variable gl_Position is available only in the vertex
404 * language and is intended for writing the homogeneous vertex
405 * position. It can be written at any time during shader
406 * execution. It may also be read back by a vertex shader
407 * after being written. This value will be used by primitive
408 * assembly, clipping, culling, and other fixed functionality
409 * operations, if present, that operate on primitives after
410 * vertex processing has occurred. Its value is undefined if
411 * the vertex shader executable does not write gl_Position."
413 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
416 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
417 find_assignment_visitor
find("gl_Position");
418 find
.run(shader
->ir
);
419 if (!find
.variable_found()) {
420 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
425 prog
->Vert
.ClipDistanceArraySize
= 0;
427 if (!prog
->IsES
&& prog
->Version
>= 130) {
428 /* From section 7.1 (Vertex Shader Special Variables) of the
431 * "It is an error for a shader to statically write both
432 * gl_ClipVertex and gl_ClipDistance."
434 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
435 * gl_ClipVertex nor gl_ClipDistance.
437 find_assignment_visitor
clip_vertex("gl_ClipVertex");
438 find_assignment_visitor
clip_distance("gl_ClipDistance");
440 clip_vertex
.run(shader
->ir
);
441 clip_distance
.run(shader
->ir
);
442 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
443 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
444 "and `gl_ClipDistance'\n");
447 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
448 ir_variable
*clip_distance_var
=
449 shader
->symbols
->get_variable("gl_ClipDistance");
450 if (clip_distance_var
)
451 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
457 * Verify that a fragment shader executable meets all semantic requirements
459 * \param shader Fragment shader executable to be verified
462 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
463 struct gl_shader
*shader
)
468 find_assignment_visitor
frag_color("gl_FragColor");
469 find_assignment_visitor
frag_data("gl_FragData");
471 frag_color
.run(shader
->ir
);
472 frag_data
.run(shader
->ir
);
474 if (frag_color
.variable_found() && frag_data
.variable_found()) {
475 linker_error(prog
, "fragment shader writes to both "
476 "`gl_FragColor' and `gl_FragData'\n");
481 * Verify that a geometry shader executable meets all semantic requirements
483 * Also sets prog->Geom.VerticesIn as a side effect.
485 * \param shader Geometry shader executable to be verified
488 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
489 struct gl_shader
*shader
)
494 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
495 prog
->Geom
.VerticesIn
= num_vertices
;
500 * Generate a string describing the mode of a variable
503 mode_string(const ir_variable
*var
)
507 return (var
->read_only
) ? "global constant" : "global variable";
509 case ir_var_uniform
: return "uniform";
510 case ir_var_shader_in
: return "shader input";
511 case ir_var_shader_out
: return "shader output";
513 case ir_var_const_in
:
514 case ir_var_temporary
:
516 assert(!"Should not get here.");
517 return "invalid variable";
523 * Perform validation of global variables used across multiple shaders
526 cross_validate_globals(struct gl_shader_program
*prog
,
527 struct gl_shader
**shader_list
,
528 unsigned num_shaders
,
531 /* Examine all of the uniforms in all of the shaders and cross validate
534 glsl_symbol_table variables
;
535 for (unsigned i
= 0; i
< num_shaders
; i
++) {
536 if (shader_list
[i
] == NULL
)
539 foreach_list(node
, shader_list
[i
]->ir
) {
540 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
545 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
548 /* Don't cross validate temporaries that are at global scope. These
549 * will eventually get pulled into the shaders 'main'.
551 if (var
->mode
== ir_var_temporary
)
554 /* If a global with this name has already been seen, verify that the
555 * new instance has the same type. In addition, if the globals have
556 * initializers, the values of the initializers must be the same.
558 ir_variable
*const existing
= variables
.get_variable(var
->name
);
559 if (existing
!= NULL
) {
560 if (var
->type
!= existing
->type
) {
561 /* Consider the types to be "the same" if both types are arrays
562 * of the same type and one of the arrays is implicitly sized.
563 * In addition, set the type of the linked variable to the
564 * explicitly sized array.
566 if (var
->type
->is_array()
567 && existing
->type
->is_array()
568 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
569 && ((var
->type
->length
== 0)
570 || (existing
->type
->length
== 0))) {
571 if (var
->type
->length
!= 0) {
572 existing
->type
= var
->type
;
575 linker_error(prog
, "%s `%s' declared as type "
576 "`%s' and type `%s'\n",
578 var
->name
, var
->type
->name
,
579 existing
->type
->name
);
584 if (var
->explicit_location
) {
585 if (existing
->explicit_location
586 && (var
->location
!= existing
->location
)) {
587 linker_error(prog
, "explicit locations for %s "
588 "`%s' have differing values\n",
589 mode_string(var
), var
->name
);
593 existing
->location
= var
->location
;
594 existing
->explicit_location
= true;
597 /* From the GLSL 4.20 specification:
598 * "A link error will result if two compilation units in a program
599 * specify different integer-constant bindings for the same
600 * opaque-uniform name. However, it is not an error to specify a
601 * binding on some but not all declarations for the same name"
603 if (var
->explicit_binding
) {
604 if (existing
->explicit_binding
&&
605 var
->binding
!= existing
->binding
) {
606 linker_error(prog
, "explicit bindings for %s "
607 "`%s' have differing values\n",
608 mode_string(var
), var
->name
);
612 existing
->binding
= var
->binding
;
613 existing
->explicit_binding
= true;
616 /* Validate layout qualifiers for gl_FragDepth.
618 * From the AMD/ARB_conservative_depth specs:
620 * "If gl_FragDepth is redeclared in any fragment shader in a
621 * program, it must be redeclared in all fragment shaders in
622 * that program that have static assignments to
623 * gl_FragDepth. All redeclarations of gl_FragDepth in all
624 * fragment shaders in a single program must have the same set
627 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
628 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
629 bool layout_differs
=
630 var
->depth_layout
!= existing
->depth_layout
;
632 if (layout_declared
&& layout_differs
) {
634 "All redeclarations of gl_FragDepth in all "
635 "fragment shaders in a single program must have "
636 "the same set of qualifiers.");
639 if (var
->used
&& layout_differs
) {
641 "If gl_FragDepth is redeclared with a layout "
642 "qualifier in any fragment shader, it must be "
643 "redeclared with the same layout qualifier in "
644 "all fragment shaders that have assignments to "
649 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
651 * "If a shared global has multiple initializers, the
652 * initializers must all be constant expressions, and they
653 * must all have the same value. Otherwise, a link error will
654 * result. (A shared global having only one initializer does
655 * not require that initializer to be a constant expression.)"
657 * Previous to 4.20 the GLSL spec simply said that initializers
658 * must have the same value. In this case of non-constant
659 * initializers, this was impossible to determine. As a result,
660 * no vendor actually implemented that behavior. The 4.20
661 * behavior matches the implemented behavior of at least one other
662 * vendor, so we'll implement that for all GLSL versions.
664 if (var
->constant_initializer
!= NULL
) {
665 if (existing
->constant_initializer
!= NULL
) {
666 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
667 linker_error(prog
, "initializers for %s "
668 "`%s' have differing values\n",
669 mode_string(var
), var
->name
);
673 /* If the first-seen instance of a particular uniform did not
674 * have an initializer but a later instance does, copy the
675 * initializer to the version stored in the symbol table.
677 /* FINISHME: This is wrong. The constant_value field should
678 * FINISHME: not be modified! Imagine a case where a shader
679 * FINISHME: without an initializer is linked in two different
680 * FINISHME: programs with shaders that have differing
681 * FINISHME: initializers. Linking with the first will
682 * FINISHME: modify the shader, and linking with the second
683 * FINISHME: will fail.
685 existing
->constant_initializer
=
686 var
->constant_initializer
->clone(ralloc_parent(existing
),
691 if (var
->has_initializer
) {
692 if (existing
->has_initializer
693 && (var
->constant_initializer
== NULL
694 || existing
->constant_initializer
== NULL
)) {
696 "shared global variable `%s' has multiple "
697 "non-constant initializers.\n",
702 /* Some instance had an initializer, so keep track of that. In
703 * this location, all sorts of initializers (constant or
704 * otherwise) will propagate the existence to the variable
705 * stored in the symbol table.
707 existing
->has_initializer
= true;
710 if (existing
->invariant
!= var
->invariant
) {
711 linker_error(prog
, "declarations for %s `%s' have "
712 "mismatching invariant qualifiers\n",
713 mode_string(var
), var
->name
);
716 if (existing
->centroid
!= var
->centroid
) {
717 linker_error(prog
, "declarations for %s `%s' have "
718 "mismatching centroid qualifiers\n",
719 mode_string(var
), var
->name
);
723 variables
.add_variable(var
);
730 * Perform validation of uniforms used across multiple shader stages
733 cross_validate_uniforms(struct gl_shader_program
*prog
)
735 cross_validate_globals(prog
, prog
->_LinkedShaders
,
736 MESA_SHADER_TYPES
, true);
740 * Accumulates the array of prog->UniformBlocks and checks that all
741 * definitons of blocks agree on their contents.
744 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
746 unsigned max_num_uniform_blocks
= 0;
747 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
748 if (prog
->_LinkedShaders
[i
])
749 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
752 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
753 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
755 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
756 max_num_uniform_blocks
);
757 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
758 prog
->UniformBlockStageIndex
[i
][j
] = -1;
763 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
764 int index
= link_cross_validate_uniform_block(prog
,
765 &prog
->UniformBlocks
,
766 &prog
->NumUniformBlocks
,
767 &sh
->UniformBlocks
[j
]);
770 linker_error(prog
, "uniform block `%s' has mismatching definitions",
771 sh
->UniformBlocks
[j
].Name
);
775 prog
->UniformBlockStageIndex
[i
][index
] = j
;
784 * Populates a shaders symbol table with all global declarations
787 populate_symbol_table(gl_shader
*sh
)
789 sh
->symbols
= new(sh
) glsl_symbol_table
;
791 foreach_list(node
, sh
->ir
) {
792 ir_instruction
*const inst
= (ir_instruction
*) node
;
796 if ((func
= inst
->as_function()) != NULL
) {
797 sh
->symbols
->add_function(func
);
798 } else if ((var
= inst
->as_variable()) != NULL
) {
799 sh
->symbols
->add_variable(var
);
806 * Remap variables referenced in an instruction tree
808 * This is used when instruction trees are cloned from one shader and placed in
809 * another. These trees will contain references to \c ir_variable nodes that
810 * do not exist in the target shader. This function finds these \c ir_variable
811 * references and replaces the references with matching variables in the target
814 * If there is no matching variable in the target shader, a clone of the
815 * \c ir_variable is made and added to the target shader. The new variable is
816 * added to \b both the instruction stream and the symbol table.
818 * \param inst IR tree that is to be processed.
819 * \param symbols Symbol table containing global scope symbols in the
821 * \param instructions Instruction stream where new variable declarations
825 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
828 class remap_visitor
: public ir_hierarchical_visitor
{
830 remap_visitor(struct gl_shader
*target
,
833 this->target
= target
;
834 this->symbols
= target
->symbols
;
835 this->instructions
= target
->ir
;
839 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
841 if (ir
->var
->mode
== ir_var_temporary
) {
842 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
846 return visit_continue
;
849 ir_variable
*const existing
=
850 this->symbols
->get_variable(ir
->var
->name
);
851 if (existing
!= NULL
)
854 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
856 this->symbols
->add_variable(copy
);
857 this->instructions
->push_head(copy
);
861 return visit_continue
;
865 struct gl_shader
*target
;
866 glsl_symbol_table
*symbols
;
867 exec_list
*instructions
;
871 remap_visitor
v(target
, temps
);
878 * Move non-declarations from one instruction stream to another
880 * The intended usage pattern of this function is to pass the pointer to the
881 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
882 * pointer) for \c last and \c false for \c make_copies on the first
883 * call. Successive calls pass the return value of the previous call for
884 * \c last and \c true for \c make_copies.
886 * \param instructions Source instruction stream
887 * \param last Instruction after which new instructions should be
888 * inserted in the target instruction stream
889 * \param make_copies Flag selecting whether instructions in \c instructions
890 * should be copied (via \c ir_instruction::clone) into the
891 * target list or moved.
894 * The new "last" instruction in the target instruction stream. This pointer
895 * is suitable for use as the \c last parameter of a later call to this
899 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
900 bool make_copies
, gl_shader
*target
)
902 hash_table
*temps
= NULL
;
905 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
906 hash_table_pointer_compare
);
908 foreach_list_safe(node
, instructions
) {
909 ir_instruction
*inst
= (ir_instruction
*) node
;
911 if (inst
->as_function())
914 ir_variable
*var
= inst
->as_variable();
915 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
918 assert(inst
->as_assignment()
920 || inst
->as_if() /* for initializers with the ?: operator */
921 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
924 inst
= inst
->clone(target
, NULL
);
927 hash_table_insert(temps
, inst
, var
);
929 remap_variables(inst
, target
, temps
);
934 last
->insert_after(inst
);
939 hash_table_dtor(temps
);
945 * Get the function signature for main from a shader
947 static ir_function_signature
*
948 get_main_function_signature(gl_shader
*sh
)
950 ir_function
*const f
= sh
->symbols
->get_function("main");
952 exec_list void_parameters
;
954 /* Look for the 'void main()' signature and ensure that it's defined.
955 * This keeps the linker from accidentally pick a shader that just
956 * contains a prototype for main.
958 * We don't have to check for multiple definitions of main (in multiple
959 * shaders) because that would have already been caught above.
961 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
962 if ((sig
!= NULL
) && sig
->is_defined
) {
972 * This class is only used in link_intrastage_shaders() below but declaring
973 * it inside that function leads to compiler warnings with some versions of
976 class array_sizing_visitor
: public ir_hierarchical_visitor
{
978 virtual ir_visitor_status
visit(ir_variable
*var
)
980 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
981 const glsl_type
*type
=
982 glsl_type::get_array_instance(var
->type
->fields
.array
,
983 var
->max_array_access
+ 1);
984 assert(type
!= NULL
);
987 return visit_continue
;
992 * Performs the cross-validation of geometry shader max_vertices and
993 * primitive type layout qualifiers for the attached geometry shaders,
994 * and propagates them to the linked GS and linked shader program.
997 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
998 struct gl_shader
*linked_shader
,
999 struct gl_shader
**shader_list
,
1000 unsigned num_shaders
)
1002 linked_shader
->Geom
.VerticesOut
= 0;
1003 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1004 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1006 /* No in/out qualifiers defined for anything but GLSL 1.50+
1007 * geometry shaders so far.
1009 if (linked_shader
->Type
!= GL_GEOMETRY_SHADER
|| prog
->Version
< 150)
1012 /* From the GLSL 1.50 spec, page 46:
1014 * "All geometry shader output layout declarations in a program
1015 * must declare the same layout and same value for
1016 * max_vertices. There must be at least one geometry output
1017 * layout declaration somewhere in a program, but not all
1018 * geometry shaders (compilation units) are required to
1022 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1023 struct gl_shader
*shader
= shader_list
[i
];
1025 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1026 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1027 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1028 linker_error(prog
, "geometry shader defined with conflicting "
1032 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1035 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1036 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1037 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1038 linker_error(prog
, "geometry shader defined with conflicting "
1042 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1045 if (shader
->Geom
.VerticesOut
!= 0) {
1046 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1047 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1048 linker_error(prog
, "geometry shader defined with conflicting "
1049 "output vertex count (%d and %d)\n",
1050 linked_shader
->Geom
.VerticesOut
,
1051 shader
->Geom
.VerticesOut
);
1054 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1058 /* Just do the intrastage -> interstage propagation right now,
1059 * since we already know we're in the right type of shader program
1062 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1064 "geometry shader didn't declare primitive input type\n");
1067 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1069 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1071 "geometry shader didn't declare primitive output type\n");
1074 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1076 if (linked_shader
->Geom
.VerticesOut
== 0) {
1078 "geometry shader didn't declare max_vertices\n");
1081 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1085 * Combine a group of shaders for a single stage to generate a linked shader
1088 * If this function is supplied a single shader, it is cloned, and the new
1089 * shader is returned.
1091 static struct gl_shader
*
1092 link_intrastage_shaders(void *mem_ctx
,
1093 struct gl_context
*ctx
,
1094 struct gl_shader_program
*prog
,
1095 struct gl_shader
**shader_list
,
1096 unsigned num_shaders
)
1098 struct gl_uniform_block
*uniform_blocks
= NULL
;
1100 /* Check that global variables defined in multiple shaders are consistent.
1102 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1103 if (!prog
->LinkStatus
)
1106 /* Check that interface blocks defined in multiple shaders are consistent.
1108 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1110 if (!prog
->LinkStatus
)
1113 /* Link up uniform blocks defined within this stage. */
1114 const unsigned num_uniform_blocks
=
1115 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
1118 /* Check that there is only a single definition of each function signature
1119 * across all shaders.
1121 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1122 foreach_list(node
, shader_list
[i
]->ir
) {
1123 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
1128 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
1129 ir_function
*const other
=
1130 shader_list
[j
]->symbols
->get_function(f
->name
);
1132 /* If the other shader has no function (and therefore no function
1133 * signatures) with the same name, skip to the next shader.
1138 foreach_iter (exec_list_iterator
, iter
, *f
) {
1139 ir_function_signature
*sig
=
1140 (ir_function_signature
*) iter
.get();
1142 if (!sig
->is_defined
|| sig
->is_builtin
)
1145 ir_function_signature
*other_sig
=
1146 other
->exact_matching_signature(& sig
->parameters
);
1148 if ((other_sig
!= NULL
) && other_sig
->is_defined
1149 && !other_sig
->is_builtin
) {
1150 linker_error(prog
, "function `%s' is multiply defined",
1159 /* Find the shader that defines main, and make a clone of it.
1161 * Starting with the clone, search for undefined references. If one is
1162 * found, find the shader that defines it. Clone the reference and add
1163 * it to the shader. Repeat until there are no undefined references or
1164 * until a reference cannot be resolved.
1166 gl_shader
*main
= NULL
;
1167 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1168 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1169 main
= shader_list
[i
];
1175 linker_error(prog
, "%s shader lacks `main'\n",
1176 _mesa_glsl_shader_target_name(shader_list
[0]->Type
));
1180 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1181 linked
->ir
= new(linked
) exec_list
;
1182 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1184 linked
->UniformBlocks
= uniform_blocks
;
1185 linked
->NumUniformBlocks
= num_uniform_blocks
;
1186 ralloc_steal(linked
, linked
->UniformBlocks
);
1188 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
1190 populate_symbol_table(linked
);
1192 /* The a pointer to the main function in the final linked shader (i.e., the
1193 * copy of the original shader that contained the main function).
1195 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1197 /* Move any instructions other than variable declarations or function
1198 * declarations into main.
1200 exec_node
*insertion_point
=
1201 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1204 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1205 if (shader_list
[i
] == main
)
1208 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1209 insertion_point
, true, linked
);
1212 /* Resolve initializers for global variables in the linked shader.
1214 unsigned num_linking_shaders
= num_shaders
;
1215 for (unsigned i
= 0; i
< num_shaders
; i
++)
1216 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1218 gl_shader
**linking_shaders
=
1219 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1221 memcpy(linking_shaders
, shader_list
,
1222 sizeof(linking_shaders
[0]) * num_shaders
);
1224 unsigned idx
= num_shaders
;
1225 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1226 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1227 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1228 idx
+= shader_list
[i
]->num_builtins_to_link
;
1231 assert(idx
== num_linking_shaders
);
1233 if (!link_function_calls(prog
, linked
, linking_shaders
,
1234 num_linking_shaders
)) {
1235 ctx
->Driver
.DeleteShader(ctx
, linked
);
1236 free(linking_shaders
);
1240 free(linking_shaders
);
1242 /* At this point linked should contain all of the linked IR, so
1243 * validate it to make sure nothing went wrong.
1245 validate_ir_tree(linked
->ir
);
1247 /* Set the size of geometry shader input arrays */
1248 if (linked
->Type
== GL_GEOMETRY_SHADER
) {
1249 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
1250 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
1251 foreach_iter(exec_list_iterator
, iter
, *linked
->ir
) {
1252 ir_instruction
*ir
= (ir_instruction
*)iter
.get();
1253 ir
->accept(&input_resize_visitor
);
1257 /* Make a pass over all variable declarations to ensure that arrays with
1258 * unspecified sizes have a size specified. The size is inferred from the
1259 * max_array_access field.
1261 array_sizing_visitor v
;
1268 * Update the sizes of linked shader uniform arrays to the maximum
1271 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1273 * If one or more elements of an array are active,
1274 * GetActiveUniform will return the name of the array in name,
1275 * subject to the restrictions listed above. The type of the array
1276 * is returned in type. The size parameter contains the highest
1277 * array element index used, plus one. The compiler or linker
1278 * determines the highest index used. There will be only one
1279 * active uniform reported by the GL per uniform array.
1283 update_array_sizes(struct gl_shader_program
*prog
)
1285 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1286 if (prog
->_LinkedShaders
[i
] == NULL
)
1289 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1290 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1292 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
) ||
1293 !var
->type
->is_array())
1296 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1297 * will not be eliminated. Since we always do std140, just
1298 * don't resize arrays in UBOs.
1300 if (var
->is_in_uniform_block())
1303 unsigned int size
= var
->max_array_access
;
1304 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1305 if (prog
->_LinkedShaders
[j
] == NULL
)
1308 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1309 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1313 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1314 other_var
->max_array_access
> size
) {
1315 size
= other_var
->max_array_access
;
1320 if (size
+ 1 != var
->type
->length
) {
1321 /* If this is a built-in uniform (i.e., it's backed by some
1322 * fixed-function state), adjust the number of state slots to
1323 * match the new array size. The number of slots per array entry
1324 * is not known. It seems safe to assume that the total number of
1325 * slots is an integer multiple of the number of array elements.
1326 * Determine the number of slots per array element by dividing by
1327 * the old (total) size.
1329 if (var
->num_state_slots
> 0) {
1330 var
->num_state_slots
= (size
+ 1)
1331 * (var
->num_state_slots
/ var
->type
->length
);
1334 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1336 /* FINISHME: We should update the types of array
1337 * dereferences of this variable now.
1345 * Find a contiguous set of available bits in a bitmask.
1347 * \param used_mask Bits representing used (1) and unused (0) locations
1348 * \param needed_count Number of contiguous bits needed.
1351 * Base location of the available bits on success or -1 on failure.
1354 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1356 unsigned needed_mask
= (1 << needed_count
) - 1;
1357 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1359 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1360 * cannot optimize possibly infinite loops" for the loop below.
1362 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1365 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1366 if ((needed_mask
& ~used_mask
) == needed_mask
)
1377 * Assign locations for either VS inputs for FS outputs
1379 * \param prog Shader program whose variables need locations assigned
1380 * \param target_index Selector for the program target to receive location
1381 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1382 * \c MESA_SHADER_FRAGMENT.
1383 * \param max_index Maximum number of generic locations. This corresponds
1384 * to either the maximum number of draw buffers or the
1385 * maximum number of generic attributes.
1388 * If locations are successfully assigned, true is returned. Otherwise an
1389 * error is emitted to the shader link log and false is returned.
1392 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1393 unsigned target_index
,
1396 /* Mark invalid locations as being used.
1398 unsigned used_locations
= (max_index
>= 32)
1399 ? ~0 : ~((1 << max_index
) - 1);
1401 assert((target_index
== MESA_SHADER_VERTEX
)
1402 || (target_index
== MESA_SHADER_FRAGMENT
));
1404 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1408 /* Operate in a total of four passes.
1410 * 1. Invalidate the location assignments for all vertex shader inputs.
1412 * 2. Assign locations for inputs that have user-defined (via
1413 * glBindVertexAttribLocation) locations and outputs that have
1414 * user-defined locations (via glBindFragDataLocation).
1416 * 3. Sort the attributes without assigned locations by number of slots
1417 * required in decreasing order. Fragmentation caused by attribute
1418 * locations assigned by the application may prevent large attributes
1419 * from having enough contiguous space.
1421 * 4. Assign locations to any inputs without assigned locations.
1424 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1425 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1427 const enum ir_variable_mode direction
=
1428 (target_index
== MESA_SHADER_VERTEX
)
1429 ? ir_var_shader_in
: ir_var_shader_out
;
1432 /* Temporary storage for the set of attributes that need locations assigned.
1438 /* Used below in the call to qsort. */
1439 static int compare(const void *a
, const void *b
)
1441 const temp_attr
*const l
= (const temp_attr
*) a
;
1442 const temp_attr
*const r
= (const temp_attr
*) b
;
1444 /* Reversed because we want a descending order sort below. */
1445 return r
->slots
- l
->slots
;
1449 unsigned num_attr
= 0;
1451 foreach_list(node
, sh
->ir
) {
1452 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1454 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1457 if (var
->explicit_location
) {
1458 if ((var
->location
>= (int)(max_index
+ generic_base
))
1459 || (var
->location
< 0)) {
1461 "invalid explicit location %d specified for `%s'\n",
1463 ? var
->location
: var
->location
- generic_base
,
1467 } else if (target_index
== MESA_SHADER_VERTEX
) {
1470 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1471 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1472 var
->location
= binding
;
1473 var
->is_unmatched_generic_inout
= 0;
1475 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1479 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1480 assert(binding
>= FRAG_RESULT_DATA0
);
1481 var
->location
= binding
;
1482 var
->is_unmatched_generic_inout
= 0;
1484 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1490 /* If the variable is not a built-in and has a location statically
1491 * assigned in the shader (presumably via a layout qualifier), make sure
1492 * that it doesn't collide with other assigned locations. Otherwise,
1493 * add it to the list of variables that need linker-assigned locations.
1495 const unsigned slots
= var
->type
->count_attribute_slots();
1496 if (var
->location
!= -1) {
1497 if (var
->location
>= generic_base
&& var
->index
< 1) {
1498 /* From page 61 of the OpenGL 4.0 spec:
1500 * "LinkProgram will fail if the attribute bindings assigned
1501 * by BindAttribLocation do not leave not enough space to
1502 * assign a location for an active matrix attribute or an
1503 * active attribute array, both of which require multiple
1504 * contiguous generic attributes."
1506 * Previous versions of the spec contain similar language but omit
1507 * the bit about attribute arrays.
1509 * Page 61 of the OpenGL 4.0 spec also says:
1511 * "It is possible for an application to bind more than one
1512 * attribute name to the same location. This is referred to as
1513 * aliasing. This will only work if only one of the aliased
1514 * attributes is active in the executable program, or if no
1515 * path through the shader consumes more than one attribute of
1516 * a set of attributes aliased to the same location. A link
1517 * error can occur if the linker determines that every path
1518 * through the shader consumes multiple aliased attributes,
1519 * but implementations are not required to generate an error
1522 * These two paragraphs are either somewhat contradictory, or I
1523 * don't fully understand one or both of them.
1525 /* FINISHME: The code as currently written does not support
1526 * FINISHME: attribute location aliasing (see comment above).
1528 /* Mask representing the contiguous slots that will be used by
1531 const unsigned attr
= var
->location
- generic_base
;
1532 const unsigned use_mask
= (1 << slots
) - 1;
1534 /* Generate a link error if the set of bits requested for this
1535 * attribute overlaps any previously allocated bits.
1537 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1538 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1539 ? "vertex shader input" : "fragment shader output";
1541 "insufficient contiguous locations "
1542 "available for %s `%s' %d %d %d", string
,
1543 var
->name
, used_locations
, use_mask
, attr
);
1547 used_locations
|= (use_mask
<< attr
);
1553 to_assign
[num_attr
].slots
= slots
;
1554 to_assign
[num_attr
].var
= var
;
1558 /* If all of the attributes were assigned locations by the application (or
1559 * are built-in attributes with fixed locations), return early. This should
1560 * be the common case.
1565 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1567 if (target_index
== MESA_SHADER_VERTEX
) {
1568 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1569 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1570 * reserved to prevent it from being automatically allocated below.
1572 find_deref_visitor
find("gl_Vertex");
1574 if (find
.variable_found())
1575 used_locations
|= (1 << 0);
1578 for (unsigned i
= 0; i
< num_attr
; i
++) {
1579 /* Mask representing the contiguous slots that will be used by this
1582 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1584 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1587 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1588 ? "vertex shader input" : "fragment shader output";
1591 "insufficient contiguous locations "
1592 "available for %s `%s'",
1593 string
, to_assign
[i
].var
->name
);
1597 to_assign
[i
].var
->location
= generic_base
+ location
;
1598 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1599 used_locations
|= (use_mask
<< location
);
1607 * Demote shader inputs and outputs that are not used in other stages
1610 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1612 foreach_list(node
, sh
->ir
) {
1613 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1615 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1618 /* A shader 'in' or 'out' variable is only really an input or output if
1619 * its value is used by other shader stages. This will cause the variable
1620 * to have a location assigned.
1622 if (var
->is_unmatched_generic_inout
) {
1623 var
->mode
= ir_var_auto
;
1630 * Store the gl_FragDepth layout in the gl_shader_program struct.
1633 store_fragdepth_layout(struct gl_shader_program
*prog
)
1635 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1639 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
1641 /* We don't look up the gl_FragDepth symbol directly because if
1642 * gl_FragDepth is not used in the shader, it's removed from the IR.
1643 * However, the symbol won't be removed from the symbol table.
1645 * We're only interested in the cases where the variable is NOT removed
1648 foreach_list(node
, ir
) {
1649 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1651 if (var
== NULL
|| var
->mode
!= ir_var_shader_out
) {
1655 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1656 switch (var
->depth_layout
) {
1657 case ir_depth_layout_none
:
1658 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
1660 case ir_depth_layout_any
:
1661 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
1663 case ir_depth_layout_greater
:
1664 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
1666 case ir_depth_layout_less
:
1667 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
1669 case ir_depth_layout_unchanged
:
1670 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
1681 * Validate the resources used by a program versus the implementation limits
1684 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1686 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
1687 "vertex", "geometry", "fragment"
1690 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
1691 ctx
->Const
.VertexProgram
.MaxTextureImageUnits
,
1692 ctx
->Const
.GeometryProgram
.MaxTextureImageUnits
,
1693 ctx
->Const
.FragmentProgram
.MaxTextureImageUnits
1696 const unsigned max_default_uniform_components
[MESA_SHADER_TYPES
] = {
1697 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
1698 ctx
->Const
.GeometryProgram
.MaxUniformComponents
,
1699 ctx
->Const
.FragmentProgram
.MaxUniformComponents
1702 const unsigned max_combined_uniform_components
[MESA_SHADER_TYPES
] = {
1703 ctx
->Const
.VertexProgram
.MaxCombinedUniformComponents
,
1704 ctx
->Const
.GeometryProgram
.MaxCombinedUniformComponents
,
1705 ctx
->Const
.FragmentProgram
.MaxCombinedUniformComponents
1708 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
1709 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
1710 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
1711 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
1714 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1715 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1720 if (sh
->num_samplers
> max_samplers
[i
]) {
1721 linker_error(prog
, "Too many %s shader texture samplers",
1725 if (sh
->num_uniform_components
> max_default_uniform_components
[i
]) {
1726 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1727 linker_warning(prog
, "Too many %s shader default uniform block "
1728 "components, but the driver will try to optimize "
1729 "them out; this is non-portable out-of-spec "
1733 linker_error(prog
, "Too many %s shader default uniform block "
1739 if (sh
->num_combined_uniform_components
>
1740 max_combined_uniform_components
[i
]) {
1741 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1742 linker_warning(prog
, "Too many %s shader uniform components, "
1743 "but the driver will try to optimize them out; "
1744 "this is non-portable out-of-spec behavior\n",
1747 linker_error(prog
, "Too many %s shader uniform components",
1753 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
1754 unsigned total_uniform_blocks
= 0;
1756 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
1757 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1758 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
1760 total_uniform_blocks
++;
1764 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
1765 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
1766 prog
->NumUniformBlocks
,
1767 ctx
->Const
.MaxCombinedUniformBlocks
);
1769 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1770 if (blocks
[i
] > max_uniform_blocks
[i
]) {
1771 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
1774 max_uniform_blocks
[i
]);
1783 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1785 tfeedback_decl
*tfeedback_decls
= NULL
;
1786 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
1788 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
1790 prog
->LinkStatus
= true; /* All error paths will set this to false */
1791 prog
->Validated
= false;
1792 prog
->_Used
= false;
1794 ralloc_free(prog
->InfoLog
);
1795 prog
->InfoLog
= ralloc_strdup(NULL
, "");
1797 ralloc_free(prog
->UniformBlocks
);
1798 prog
->UniformBlocks
= NULL
;
1799 prog
->NumUniformBlocks
= 0;
1800 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1801 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
1802 prog
->UniformBlockStageIndex
[i
] = NULL
;
1805 /* Separate the shaders into groups based on their type.
1807 struct gl_shader
**vert_shader_list
;
1808 unsigned num_vert_shaders
= 0;
1809 struct gl_shader
**frag_shader_list
;
1810 unsigned num_frag_shaders
= 0;
1811 struct gl_shader
**geom_shader_list
;
1812 unsigned num_geom_shaders
= 0;
1814 vert_shader_list
= (struct gl_shader
**)
1815 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1816 frag_shader_list
= (struct gl_shader
**)
1817 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1818 geom_shader_list
= (struct gl_shader
**)
1819 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1821 unsigned min_version
= UINT_MAX
;
1822 unsigned max_version
= 0;
1823 const bool is_es_prog
=
1824 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
1825 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1826 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1827 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1829 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
1830 linker_error(prog
, "all shaders must use same shading "
1831 "language version\n");
1835 switch (prog
->Shaders
[i
]->Type
) {
1836 case GL_VERTEX_SHADER
:
1837 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1840 case GL_FRAGMENT_SHADER
:
1841 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1844 case GL_GEOMETRY_SHADER
:
1845 geom_shader_list
[num_geom_shaders
] = prog
->Shaders
[i
];
1851 /* Previous to GLSL version 1.30, different compilation units could mix and
1852 * match shading language versions. With GLSL 1.30 and later, the versions
1853 * of all shaders must match.
1855 * GLSL ES has never allowed mixing of shading language versions.
1857 if ((is_es_prog
|| max_version
>= 130)
1858 && min_version
!= max_version
) {
1859 linker_error(prog
, "all shaders must use same shading "
1860 "language version\n");
1864 prog
->Version
= max_version
;
1865 prog
->IsES
= is_es_prog
;
1867 /* Geometry shaders have to be linked with vertex shaders.
1869 if (num_geom_shaders
> 0 && num_vert_shaders
== 0) {
1870 linker_error(prog
, "Geometry shader must be linked with "
1875 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1876 if (prog
->_LinkedShaders
[i
] != NULL
)
1877 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1879 prog
->_LinkedShaders
[i
] = NULL
;
1882 /* Link all shaders for a particular stage and validate the result.
1884 if (num_vert_shaders
> 0) {
1885 gl_shader
*const sh
=
1886 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
1889 if (!prog
->LinkStatus
)
1892 validate_vertex_shader_executable(prog
, sh
);
1893 if (!prog
->LinkStatus
)
1896 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1900 if (num_frag_shaders
> 0) {
1901 gl_shader
*const sh
=
1902 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
1905 if (!prog
->LinkStatus
)
1908 validate_fragment_shader_executable(prog
, sh
);
1909 if (!prog
->LinkStatus
)
1912 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1916 if (num_geom_shaders
> 0) {
1917 gl_shader
*const sh
=
1918 link_intrastage_shaders(mem_ctx
, ctx
, prog
, geom_shader_list
,
1921 if (!prog
->LinkStatus
)
1924 validate_geometry_shader_executable(prog
, sh
);
1925 if (!prog
->LinkStatus
)
1928 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
],
1932 /* Here begins the inter-stage linking phase. Some initial validation is
1933 * performed, then locations are assigned for uniforms, attributes, and
1936 cross_validate_uniforms(prog
);
1937 if (!prog
->LinkStatus
)
1942 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1943 if (prog
->_LinkedShaders
[prev
] != NULL
)
1947 /* Validate the inputs of each stage with the output of the preceding
1950 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1951 if (prog
->_LinkedShaders
[i
] == NULL
)
1954 validate_interstage_interface_blocks(prog
, prog
->_LinkedShaders
[prev
],
1955 prog
->_LinkedShaders
[i
]);
1956 if (!prog
->LinkStatus
)
1959 cross_validate_outputs_to_inputs(prog
,
1960 prog
->_LinkedShaders
[prev
],
1961 prog
->_LinkedShaders
[i
]);
1962 if (!prog
->LinkStatus
)
1969 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1970 if (prog
->_LinkedShaders
[i
] != NULL
)
1971 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
1974 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1975 * it before optimization because we want most of the checks to get
1976 * dropped thanks to constant propagation.
1978 * This rule also applies to GLSL ES 3.00.
1980 if (max_version
>= (is_es_prog
? 300 : 130)) {
1981 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
1983 lower_discard_flow(sh
->ir
);
1987 if (!interstage_cross_validate_uniform_blocks(prog
))
1990 /* Do common optimization before assigning storage for attributes,
1991 * uniforms, and varyings. Later optimization could possibly make
1992 * some of that unused.
1994 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1995 if (prog
->_LinkedShaders
[i
] == NULL
)
1998 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
1999 if (!prog
->LinkStatus
)
2002 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
2003 lower_clip_distance(prog
->_LinkedShaders
[i
]);
2006 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
2008 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
, &ctx
->ShaderCompilerOptions
[i
]))
2012 /* Mark all generic shader inputs and outputs as unpaired. */
2013 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2014 link_invalidate_variable_locations(
2015 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2016 VERT_ATTRIB_GENERIC0
, VARYING_SLOT_VAR0
);
2018 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
2019 link_invalidate_variable_locations(
2020 prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
],
2021 VARYING_SLOT_VAR0
, VARYING_SLOT_VAR0
);
2023 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2024 link_invalidate_variable_locations(
2025 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2026 VARYING_SLOT_VAR0
, FRAG_RESULT_DATA0
);
2029 /* FINISHME: The value of the max_attribute_index parameter is
2030 * FINISHME: implementation dependent based on the value of
2031 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2032 * FINISHME: at least 16, so hardcode 16 for now.
2034 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
2038 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
2043 for (first
= 0; first
< MESA_SHADER_TYPES
; first
++) {
2044 if (prog
->_LinkedShaders
[first
] != NULL
)
2048 if (num_tfeedback_decls
!= 0) {
2049 /* From GL_EXT_transform_feedback:
2050 * A program will fail to link if:
2052 * * the <count> specified by TransformFeedbackVaryingsEXT is
2053 * non-zero, but the program object has no vertex or geometry
2056 if (first
== MESA_SHADER_FRAGMENT
) {
2057 linker_error(prog
, "Transform feedback varyings specified, but "
2058 "no vertex or geometry shader is present.");
2062 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
2063 prog
->TransformFeedback
.NumVarying
);
2064 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
2065 prog
->TransformFeedback
.VaryingNames
,
2070 /* Linking the stages in the opposite order (from fragment to vertex)
2071 * ensures that inter-shader outputs written to in an earlier stage are
2072 * eliminated if they are (transitively) not used in a later stage.
2075 for (last
= MESA_SHADER_TYPES
-1; last
>= 0; last
--) {
2076 if (prog
->_LinkedShaders
[last
] != NULL
)
2080 if (last
>= 0 && last
< MESA_SHADER_FRAGMENT
) {
2081 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
2083 if (num_tfeedback_decls
!= 0) {
2084 /* There was no fragment shader, but we still have to assign varying
2085 * locations for use by transform feedback.
2087 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
2089 num_tfeedback_decls
, tfeedback_decls
,
2094 do_dead_builtin_varyings(ctx
, sh
, NULL
,
2095 num_tfeedback_decls
, tfeedback_decls
);
2097 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
2099 /* Eliminate code that is now dead due to unused outputs being demoted.
2101 while (do_dead_code(sh
->ir
, false))
2104 else if (first
== MESA_SHADER_FRAGMENT
) {
2105 /* If the program only contains a fragment shader...
2107 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
2109 do_dead_builtin_varyings(ctx
, NULL
, sh
,
2110 num_tfeedback_decls
, tfeedback_decls
);
2112 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
2114 while (do_dead_code(sh
->ir
, false))
2119 for (int i
= next
- 1; i
>= 0; i
--) {
2120 if (prog
->_LinkedShaders
[i
] == NULL
)
2123 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
2124 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
2125 unsigned gs_input_vertices
=
2126 next
== MESA_SHADER_GEOMETRY
? prog
->Geom
.VerticesIn
: 0;
2128 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
2129 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2130 tfeedback_decls
, gs_input_vertices
))
2133 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
2134 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2137 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
2138 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
2140 /* Eliminate code that is now dead due to unused outputs being demoted.
2142 while (do_dead_code(sh_i
->ir
, false))
2144 while (do_dead_code(sh_next
->ir
, false))
2147 /* This must be done after all dead varyings are eliminated. */
2148 if (!check_against_varying_limit(ctx
, prog
, sh_next
))
2154 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
2157 update_array_sizes(prog
);
2158 link_assign_uniform_locations(prog
);
2159 store_fragdepth_layout(prog
);
2161 check_resources(ctx
, prog
);
2162 if (!prog
->LinkStatus
)
2165 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2166 * present in a linked program. By checking prog->IsES, we also
2167 * catch the GL_ARB_ES2_compatibility case.
2169 if (!prog
->InternalSeparateShader
&&
2170 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
2171 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
2172 linker_error(prog
, "program lacks a vertex shader\n");
2173 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2174 linker_error(prog
, "program lacks a fragment shader\n");
2178 /* FINISHME: Assign fragment shader output locations. */
2181 free(vert_shader_list
);
2182 free(frag_shader_list
);
2183 free(geom_shader_list
);
2185 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2186 if (prog
->_LinkedShaders
[i
] == NULL
)
2189 /* Retain any live IR, but trash the rest. */
2190 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
2192 /* The symbol table in the linked shaders may contain references to
2193 * variables that were removed (e.g., unused uniforms). Since it may
2194 * contain junk, there is no possible valid use. Delete it and set the
2197 delete prog
->_LinkedShaders
[i
]->symbols
;
2198 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
2201 ralloc_free(mem_ctx
);