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>
68 #include "main/core.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
73 #include "program/hash_table.h"
75 #include "link_varyings.h"
76 #include "ir_optimization.h"
77 #include "ir_rvalue_visitor.h"
78 #include "ir_uniform.h"
80 #include "main/shaderobj.h"
81 #include "main/enums.h"
84 void linker_error(gl_shader_program
*, const char *, ...);
89 * Visitor that determines whether or not a variable is ever written.
91 class find_assignment_visitor
: public ir_hierarchical_visitor
{
93 find_assignment_visitor(const char *name
)
94 : name(name
), found(false)
99 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
101 ir_variable
*const var
= ir
->lhs
->variable_referenced();
103 if (strcmp(name
, var
->name
) == 0) {
108 return visit_continue_with_parent
;
111 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
113 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
114 actual_node
, &ir
->actual_parameters
) {
115 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
116 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
118 if (sig_param
->data
.mode
== ir_var_function_out
||
119 sig_param
->data
.mode
== ir_var_function_inout
) {
120 ir_variable
*var
= param_rval
->variable_referenced();
121 if (var
&& strcmp(name
, var
->name
) == 0) {
128 if (ir
->return_deref
!= NULL
) {
129 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
131 if (strcmp(name
, var
->name
) == 0) {
137 return visit_continue_with_parent
;
140 bool variable_found()
146 const char *name
; /**< Find writes to a variable with this name. */
147 bool found
; /**< Was a write to the variable found? */
152 * Visitor that determines whether or not a variable is ever read.
154 class find_deref_visitor
: public ir_hierarchical_visitor
{
156 find_deref_visitor(const char *name
)
157 : name(name
), found(false)
162 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
164 if (strcmp(this->name
, ir
->var
->name
) == 0) {
169 return visit_continue
;
172 bool variable_found() const
178 const char *name
; /**< Find writes to a variable with this name. */
179 bool found
; /**< Was a write to the variable found? */
183 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
185 unsigned num_vertices
;
186 gl_shader_program
*prog
;
188 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
190 this->num_vertices
= num_vertices
;
194 virtual ~geom_array_resize_visitor()
199 virtual ir_visitor_status
visit(ir_variable
*var
)
201 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
202 return visit_continue
;
204 unsigned size
= var
->type
->length
;
206 /* Generate a link error if the shader has declared this array with an
209 if (size
&& size
!= this->num_vertices
) {
210 linker_error(this->prog
, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var
->name
, size
, this->num_vertices
);
213 return visit_continue
;
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
220 if (var
->data
.max_array_access
>= this->num_vertices
) {
221 linker_error(this->prog
, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
223 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
224 return visit_continue
;
227 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
229 var
->data
.max_array_access
= this->num_vertices
- 1;
231 return visit_continue
;
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
238 ir
->type
= ir
->var
->type
;
239 return visit_continue
;
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
246 const glsl_type
*const vt
= ir
->array
->type
;
248 ir
->type
= vt
->fields
.array
;
249 return visit_continue
;
253 class tess_eval_array_resize_visitor
: public ir_hierarchical_visitor
{
255 unsigned num_vertices
;
256 gl_shader_program
*prog
;
258 tess_eval_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
260 this->num_vertices
= num_vertices
;
264 virtual ~tess_eval_array_resize_visitor()
269 virtual ir_visitor_status
visit(ir_variable
*var
)
271 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
|| var
->data
.patch
)
272 return visit_continue
;
274 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
276 var
->data
.max_array_access
= this->num_vertices
- 1;
278 return visit_continue
;
281 /* Dereferences of input variables need to be updated so that their type
282 * matches the newly assigned type of the variable they are accessing. */
283 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
285 ir
->type
= ir
->var
->type
;
286 return visit_continue
;
289 /* Dereferences of 2D input arrays need to be updated so that their type
290 * matches the newly assigned type of the array they are accessing. */
291 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
293 const glsl_type
*const vt
= ir
->array
->type
;
295 ir
->type
= vt
->fields
.array
;
296 return visit_continue
;
300 class barrier_use_visitor
: public ir_hierarchical_visitor
{
302 barrier_use_visitor(gl_shader_program
*prog
)
303 : prog(prog
), in_main(false), after_return(false), control_flow(0)
307 virtual ~barrier_use_visitor()
312 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
314 if (strcmp(ir
->name
, "main") == 0)
317 return visit_continue
;
320 virtual ir_visitor_status
visit_leave(ir_function
*ir
)
323 after_return
= false;
324 return visit_continue
;
327 virtual ir_visitor_status
visit_leave(ir_return
*ir
)
330 return visit_continue
;
333 virtual ir_visitor_status
visit_enter(ir_if
*ir
)
336 return visit_continue
;
339 virtual ir_visitor_status
visit_leave(ir_if
*ir
)
342 return visit_continue
;
345 virtual ir_visitor_status
visit_enter(ir_loop
*ir
)
348 return visit_continue
;
351 virtual ir_visitor_status
visit_leave(ir_loop
*ir
)
354 return visit_continue
;
357 /* FINISHME: `switch` is not expressed at the IR level -- it's already
358 * been lowered to a mess of `if`s. We'll correctly disallow any use of
359 * barrier() in a conditional path within the switch, but not in a path
360 * which is always hit.
363 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
365 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
366 /* Use of barrier(); determine if it is legal: */
368 linker_error(prog
, "Builtin barrier() may only be used in main");
373 linker_error(prog
, "Builtin barrier() may not be used after return");
377 if (control_flow
!= 0) {
378 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
382 return visit_continue
;
386 gl_shader_program
*prog
;
387 bool in_main
, after_return
;
392 * Visitor that determines the highest stream id to which a (geometry) shader
393 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
395 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
397 find_emit_vertex_visitor(int max_allowed
)
398 : max_stream_allowed(max_allowed
),
399 invalid_stream_id(0),
400 invalid_stream_id_from_emit_vertex(false),
401 end_primitive_found(false),
402 uses_non_zero_stream(false)
407 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
409 int stream_id
= ir
->stream_id();
412 invalid_stream_id
= stream_id
;
413 invalid_stream_id_from_emit_vertex
= true;
417 if (stream_id
> max_stream_allowed
) {
418 invalid_stream_id
= stream_id
;
419 invalid_stream_id_from_emit_vertex
= true;
424 uses_non_zero_stream
= true;
426 return visit_continue
;
429 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
431 end_primitive_found
= true;
433 int stream_id
= ir
->stream_id();
436 invalid_stream_id
= stream_id
;
437 invalid_stream_id_from_emit_vertex
= false;
441 if (stream_id
> max_stream_allowed
) {
442 invalid_stream_id
= stream_id
;
443 invalid_stream_id_from_emit_vertex
= false;
448 uses_non_zero_stream
= true;
450 return visit_continue
;
455 return invalid_stream_id
!= 0;
458 const char *error_func()
460 return invalid_stream_id_from_emit_vertex
?
461 "EmitStreamVertex" : "EndStreamPrimitive";
466 return invalid_stream_id
;
471 return uses_non_zero_stream
;
474 bool uses_end_primitive()
476 return end_primitive_found
;
480 int max_stream_allowed
;
481 int invalid_stream_id
;
482 bool invalid_stream_id_from_emit_vertex
;
483 bool end_primitive_found
;
484 bool uses_non_zero_stream
;
487 /* Class that finds array derefs and check if indexes are dynamic. */
488 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
491 dynamic_sampler_array_indexing_visitor() :
492 dynamic_sampler_array_indexing(false)
496 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
498 if (!ir
->variable_referenced())
499 return visit_continue
;
501 if (!ir
->variable_referenced()->type
->contains_sampler())
502 return visit_continue
;
504 if (!ir
->array_index
->constant_expression_value()) {
505 dynamic_sampler_array_indexing
= true;
508 return visit_continue
;
511 bool uses_dynamic_sampler_array_indexing()
513 return dynamic_sampler_array_indexing
;
517 bool dynamic_sampler_array_indexing
;
520 } /* anonymous namespace */
523 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
527 ralloc_strcat(&prog
->InfoLog
, "error: ");
529 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
532 prog
->LinkStatus
= false;
537 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
541 ralloc_strcat(&prog
->InfoLog
, "warning: ");
543 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
550 * Given a string identifying a program resource, break it into a base name
551 * and an optional array index in square brackets.
553 * If an array index is present, \c out_base_name_end is set to point to the
554 * "[" that precedes the array index, and the array index itself is returned
557 * If no array index is present (or if the array index is negative or
558 * mal-formed), \c out_base_name_end, is set to point to the null terminator
559 * at the end of the input string, and -1 is returned.
561 * Only the final array index is parsed; if the string contains other array
562 * indices (or structure field accesses), they are left in the base name.
564 * No attempt is made to check that the base name is properly formed;
565 * typically the caller will look up the base name in a hash table, so
566 * ill-formed base names simply turn into hash table lookup failures.
569 parse_program_resource_name(const GLchar
*name
,
570 const GLchar
**out_base_name_end
)
572 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
574 * "When an integer array element or block instance number is part of
575 * the name string, it will be specified in decimal form without a "+"
576 * or "-" sign or any extra leading zeroes. Additionally, the name
577 * string will not include white space anywhere in the string."
580 const size_t len
= strlen(name
);
581 *out_base_name_end
= name
+ len
;
583 if (len
== 0 || name
[len
-1] != ']')
586 /* Walk backwards over the string looking for a non-digit character. This
587 * had better be the opening bracket for an array index.
589 * Initially, i specifies the location of the ']'. Since the string may
590 * contain only the ']' charcater, walk backwards very carefully.
593 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
596 if ((i
== 0) || name
[i
-1] != '[')
599 long array_index
= strtol(&name
[i
], NULL
, 10);
603 /* Check for leading zero */
604 if (name
[i
] == '0' && name
[i
+1] != ']')
607 *out_base_name_end
= name
+ (i
- 1);
613 link_invalidate_variable_locations(exec_list
*ir
)
615 foreach_in_list(ir_instruction
, node
, ir
) {
616 ir_variable
*const var
= node
->as_variable();
621 /* Only assign locations for variables that lack an explicit location.
622 * Explicit locations are set for all built-in variables, generic vertex
623 * shader inputs (via layout(location=...)), and generic fragment shader
624 * outputs (also via layout(location=...)).
626 if (!var
->data
.explicit_location
) {
627 var
->data
.location
= -1;
628 var
->data
.location_frac
= 0;
631 /* ir_variable::is_unmatched_generic_inout is used by the linker while
632 * connecting outputs from one stage to inputs of the next stage.
634 * There are two implicit assumptions here. First, we assume that any
635 * built-in variable (i.e., non-generic in or out) will have
636 * explicit_location set. Second, we assume that any generic in or out
637 * will not have explicit_location set.
639 * This second assumption will only be valid until
640 * GL_ARB_separate_shader_objects is supported. When that extension is
641 * implemented, this function will need some modifications.
643 if (!var
->data
.explicit_location
) {
644 var
->data
.is_unmatched_generic_inout
= 1;
646 var
->data
.is_unmatched_generic_inout
= 0;
653 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
655 * Also check for errors based on incorrect usage of gl_ClipVertex and
658 * Return false if an error was reported.
661 analyze_clip_usage(struct gl_shader_program
*prog
,
662 struct gl_shader
*shader
, GLboolean
*UsesClipDistance
,
663 GLuint
*ClipDistanceArraySize
)
665 *ClipDistanceArraySize
= 0;
667 if (!prog
->IsES
&& prog
->Version
>= 130) {
668 /* From section 7.1 (Vertex Shader Special Variables) of the
671 * "It is an error for a shader to statically write both
672 * gl_ClipVertex and gl_ClipDistance."
674 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
675 * gl_ClipVertex nor gl_ClipDistance.
677 find_assignment_visitor
clip_vertex("gl_ClipVertex");
678 find_assignment_visitor
clip_distance("gl_ClipDistance");
680 clip_vertex
.run(shader
->ir
);
681 clip_distance
.run(shader
->ir
);
682 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
683 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
684 "and `gl_ClipDistance'\n",
685 _mesa_shader_stage_to_string(shader
->Stage
));
688 *UsesClipDistance
= clip_distance
.variable_found();
689 ir_variable
*clip_distance_var
=
690 shader
->symbols
->get_variable("gl_ClipDistance");
691 if (clip_distance_var
)
692 *ClipDistanceArraySize
= clip_distance_var
->type
->length
;
694 *UsesClipDistance
= false;
700 * Verify that a vertex shader executable meets all semantic requirements.
702 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
705 * \param shader Vertex shader executable to be verified
708 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
709 struct gl_shader
*shader
)
714 /* From the GLSL 1.10 spec, page 48:
716 * "The variable gl_Position is available only in the vertex
717 * language and is intended for writing the homogeneous vertex
718 * position. All executions of a well-formed vertex shader
719 * executable must write a value into this variable. [...] The
720 * variable gl_Position is available only in the vertex
721 * language and is intended for writing the homogeneous vertex
722 * position. All executions of a well-formed vertex shader
723 * executable must write a value into this variable."
725 * while in GLSL 1.40 this text is changed to:
727 * "The variable gl_Position is available only in the vertex
728 * language and is intended for writing the homogeneous vertex
729 * position. It can be written at any time during shader
730 * execution. It may also be read back by a vertex shader
731 * after being written. This value will be used by primitive
732 * assembly, clipping, culling, and other fixed functionality
733 * operations, if present, that operate on primitives after
734 * vertex processing has occurred. Its value is undefined if
735 * the vertex shader executable does not write gl_Position."
737 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
738 * gl_Position is not an error.
740 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
741 find_assignment_visitor
find("gl_Position");
742 find
.run(shader
->ir
);
743 if (!find
.variable_found()) {
746 "vertex shader does not write to `gl_Position'."
747 "It's value is undefined. \n");
750 "vertex shader does not write to `gl_Position'. \n");
756 analyze_clip_usage(prog
, shader
, &prog
->Vert
.UsesClipDistance
,
757 &prog
->Vert
.ClipDistanceArraySize
);
761 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
762 struct gl_shader
*shader
)
767 analyze_clip_usage(prog
, shader
, &prog
->TessEval
.UsesClipDistance
,
768 &prog
->TessEval
.ClipDistanceArraySize
);
773 * Verify that a fragment shader executable meets all semantic requirements
775 * \param shader Fragment shader executable to be verified
778 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
779 struct gl_shader
*shader
)
784 find_assignment_visitor
frag_color("gl_FragColor");
785 find_assignment_visitor
frag_data("gl_FragData");
787 frag_color
.run(shader
->ir
);
788 frag_data
.run(shader
->ir
);
790 if (frag_color
.variable_found() && frag_data
.variable_found()) {
791 linker_error(prog
, "fragment shader writes to both "
792 "`gl_FragColor' and `gl_FragData'\n");
797 * Verify that a geometry shader executable meets all semantic requirements
799 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
800 * prog->Geom.ClipDistanceArraySize as a side effect.
802 * \param shader Geometry shader executable to be verified
805 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
806 struct gl_shader
*shader
)
811 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
812 prog
->Geom
.VerticesIn
= num_vertices
;
814 analyze_clip_usage(prog
, shader
, &prog
->Geom
.UsesClipDistance
,
815 &prog
->Geom
.ClipDistanceArraySize
);
819 * Check if geometry shaders emit to non-zero streams and do corresponding
823 validate_geometry_shader_emissions(struct gl_context
*ctx
,
824 struct gl_shader_program
*prog
)
826 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
827 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
828 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
829 if (emit_vertex
.error()) {
830 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
831 "stream parameter are in the range [0, %d].\n",
832 emit_vertex
.error_func(),
833 emit_vertex
.error_stream(),
834 ctx
->Const
.MaxVertexStreams
- 1);
836 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
837 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
839 /* From the ARB_gpu_shader5 spec:
841 * "Multiple vertex streams are supported only if the output primitive
842 * type is declared to be "points". A program will fail to link if it
843 * contains a geometry shader calling EmitStreamVertex() or
844 * EndStreamPrimitive() if its output primitive type is not "points".
846 * However, in the same spec:
848 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
849 * with <stream> set to zero."
853 * "The function EndPrimitive() is equivalent to calling
854 * EndStreamPrimitive() with <stream> set to zero."
856 * Since we can call EmitVertex() and EndPrimitive() when we output
857 * primitives other than points, calling EmitStreamVertex(0) or
858 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
859 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
860 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
863 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
864 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
865 "with n>0 requires point output\n");
871 validate_intrastage_arrays(struct gl_shader_program
*prog
,
872 ir_variable
*const var
,
873 ir_variable
*const existing
)
875 /* Consider the types to be "the same" if both types are arrays
876 * of the same type and one of the arrays is implicitly sized.
877 * In addition, set the type of the linked variable to the
878 * explicitly sized array.
880 if (var
->type
->is_array() && existing
->type
->is_array() &&
881 (var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
882 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
883 if (var
->type
->length
!= 0) {
884 if (var
->type
->length
<= existing
->data
.max_array_access
) {
885 linker_error(prog
, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
889 var
->name
, var
->type
->name
,
890 existing
->data
.max_array_access
);
892 existing
->type
= var
->type
;
894 } else if (existing
->type
->length
!= 0) {
895 if(existing
->type
->length
<= var
->data
.max_array_access
) {
896 linker_error(prog
, "%s `%s' declared as type "
897 "`%s' but outermost dimension has an index"
900 var
->name
, existing
->type
->name
,
901 var
->data
.max_array_access
);
911 * Perform validation of global variables used across multiple shaders
914 cross_validate_globals(struct gl_shader_program
*prog
,
915 struct gl_shader
**shader_list
,
916 unsigned num_shaders
,
919 /* Examine all of the uniforms in all of the shaders and cross validate
922 glsl_symbol_table variables
;
923 for (unsigned i
= 0; i
< num_shaders
; i
++) {
924 if (shader_list
[i
] == NULL
)
927 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
928 ir_variable
*const var
= node
->as_variable();
933 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
936 /* Don't cross validate temporaries that are at global scope. These
937 * will eventually get pulled into the shaders 'main'.
939 if (var
->data
.mode
== ir_var_temporary
)
942 /* If a global with this name has already been seen, verify that the
943 * new instance has the same type. In addition, if the globals have
944 * initializers, the values of the initializers must be the same.
946 ir_variable
*const existing
= variables
.get_variable(var
->name
);
947 if (existing
!= NULL
) {
948 /* Check if types match. Interface blocks have some special
949 * rules so we handle those elsewhere.
951 if (var
->type
!= existing
->type
&&
952 !var
->is_interface_instance()) {
953 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
954 if (var
->type
->is_record() && existing
->type
->is_record()
955 && existing
->type
->record_compare(var
->type
)) {
956 existing
->type
= var
->type
;
958 linker_error(prog
, "%s `%s' declared as type "
959 "`%s' and type `%s'\n",
961 var
->name
, var
->type
->name
,
962 existing
->type
->name
);
968 if (var
->data
.explicit_location
) {
969 if (existing
->data
.explicit_location
970 && (var
->data
.location
!= existing
->data
.location
)) {
971 linker_error(prog
, "explicit locations for %s "
972 "`%s' have differing values\n",
973 mode_string(var
), var
->name
);
977 existing
->data
.location
= var
->data
.location
;
978 existing
->data
.explicit_location
= true;
981 /* From the GLSL 4.20 specification:
982 * "A link error will result if two compilation units in a program
983 * specify different integer-constant bindings for the same
984 * opaque-uniform name. However, it is not an error to specify a
985 * binding on some but not all declarations for the same name"
987 if (var
->data
.explicit_binding
) {
988 if (existing
->data
.explicit_binding
&&
989 var
->data
.binding
!= existing
->data
.binding
) {
990 linker_error(prog
, "explicit bindings for %s "
991 "`%s' have differing values\n",
992 mode_string(var
), var
->name
);
996 existing
->data
.binding
= var
->data
.binding
;
997 existing
->data
.explicit_binding
= true;
1000 if (var
->type
->contains_atomic() &&
1001 var
->data
.atomic
.offset
!= existing
->data
.atomic
.offset
) {
1002 linker_error(prog
, "offset specifications for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var
), var
->name
);
1008 /* Validate layout qualifiers for gl_FragDepth.
1010 * From the AMD/ARB_conservative_depth specs:
1012 * "If gl_FragDepth is redeclared in any fragment shader in a
1013 * program, it must be redeclared in all fragment shaders in
1014 * that program that have static assignments to
1015 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1016 * fragment shaders in a single program must have the same set
1019 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1020 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1021 bool layout_differs
=
1022 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1024 if (layout_declared
&& layout_differs
) {
1026 "All redeclarations of gl_FragDepth in all "
1027 "fragment shaders in a single program must have "
1028 "the same set of qualifiers.\n");
1031 if (var
->data
.used
&& layout_differs
) {
1033 "If gl_FragDepth is redeclared with a layout "
1034 "qualifier in any fragment shader, it must be "
1035 "redeclared with the same layout qualifier in "
1036 "all fragment shaders that have assignments to "
1041 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1043 * "If a shared global has multiple initializers, the
1044 * initializers must all be constant expressions, and they
1045 * must all have the same value. Otherwise, a link error will
1046 * result. (A shared global having only one initializer does
1047 * not require that initializer to be a constant expression.)"
1049 * Previous to 4.20 the GLSL spec simply said that initializers
1050 * must have the same value. In this case of non-constant
1051 * initializers, this was impossible to determine. As a result,
1052 * no vendor actually implemented that behavior. The 4.20
1053 * behavior matches the implemented behavior of at least one other
1054 * vendor, so we'll implement that for all GLSL versions.
1056 if (var
->constant_initializer
!= NULL
) {
1057 if (existing
->constant_initializer
!= NULL
) {
1058 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1059 linker_error(prog
, "initializers for %s "
1060 "`%s' have differing values\n",
1061 mode_string(var
), var
->name
);
1065 /* If the first-seen instance of a particular uniform did not
1066 * have an initializer but a later instance does, copy the
1067 * initializer to the version stored in the symbol table.
1069 /* FINISHME: This is wrong. The constant_value field should
1070 * FINISHME: not be modified! Imagine a case where a shader
1071 * FINISHME: without an initializer is linked in two different
1072 * FINISHME: programs with shaders that have differing
1073 * FINISHME: initializers. Linking with the first will
1074 * FINISHME: modify the shader, and linking with the second
1075 * FINISHME: will fail.
1077 existing
->constant_initializer
=
1078 var
->constant_initializer
->clone(ralloc_parent(existing
),
1083 if (var
->data
.has_initializer
) {
1084 if (existing
->data
.has_initializer
1085 && (var
->constant_initializer
== NULL
1086 || existing
->constant_initializer
== NULL
)) {
1088 "shared global variable `%s' has multiple "
1089 "non-constant initializers.\n",
1094 /* Some instance had an initializer, so keep track of that. In
1095 * this location, all sorts of initializers (constant or
1096 * otherwise) will propagate the existence to the variable
1097 * stored in the symbol table.
1099 existing
->data
.has_initializer
= true;
1102 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1103 linker_error(prog
, "declarations for %s `%s' have "
1104 "mismatching invariant qualifiers\n",
1105 mode_string(var
), var
->name
);
1108 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1109 linker_error(prog
, "declarations for %s `%s' have "
1110 "mismatching centroid qualifiers\n",
1111 mode_string(var
), var
->name
);
1114 if (existing
->data
.sample
!= var
->data
.sample
) {
1115 linker_error(prog
, "declarations for %s `%s` have "
1116 "mismatching sample qualifiers\n",
1117 mode_string(var
), var
->name
);
1121 variables
.add_variable(var
);
1128 * Perform validation of uniforms used across multiple shader stages
1131 cross_validate_uniforms(struct gl_shader_program
*prog
)
1133 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1134 MESA_SHADER_STAGES
, true);
1138 * Accumulates the array of prog->UniformBlocks and checks that all
1139 * definitons of blocks agree on their contents.
1142 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
1144 unsigned max_num_uniform_blocks
= 0;
1145 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1146 if (prog
->_LinkedShaders
[i
])
1147 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1150 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1151 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1153 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
1154 max_num_uniform_blocks
);
1155 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
1156 prog
->UniformBlockStageIndex
[i
][j
] = -1;
1161 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
1162 int index
= link_cross_validate_uniform_block(prog
,
1163 &prog
->UniformBlocks
,
1164 &prog
->NumUniformBlocks
,
1165 &sh
->UniformBlocks
[j
]);
1168 linker_error(prog
, "uniform block `%s' has mismatching definitions\n",
1169 sh
->UniformBlocks
[j
].Name
);
1173 prog
->UniformBlockStageIndex
[i
][index
] = j
;
1182 * Populates a shaders symbol table with all global declarations
1185 populate_symbol_table(gl_shader
*sh
)
1187 sh
->symbols
= new(sh
) glsl_symbol_table
;
1189 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1193 if ((func
= inst
->as_function()) != NULL
) {
1194 sh
->symbols
->add_function(func
);
1195 } else if ((var
= inst
->as_variable()) != NULL
) {
1196 if (var
->data
.mode
!= ir_var_temporary
)
1197 sh
->symbols
->add_variable(var
);
1204 * Remap variables referenced in an instruction tree
1206 * This is used when instruction trees are cloned from one shader and placed in
1207 * another. These trees will contain references to \c ir_variable nodes that
1208 * do not exist in the target shader. This function finds these \c ir_variable
1209 * references and replaces the references with matching variables in the target
1212 * If there is no matching variable in the target shader, a clone of the
1213 * \c ir_variable is made and added to the target shader. The new variable is
1214 * added to \b both the instruction stream and the symbol table.
1216 * \param inst IR tree that is to be processed.
1217 * \param symbols Symbol table containing global scope symbols in the
1219 * \param instructions Instruction stream where new variable declarations
1223 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1226 class remap_visitor
: public ir_hierarchical_visitor
{
1228 remap_visitor(struct gl_shader
*target
,
1231 this->target
= target
;
1232 this->symbols
= target
->symbols
;
1233 this->instructions
= target
->ir
;
1234 this->temps
= temps
;
1237 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1239 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1240 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1242 assert(var
!= NULL
);
1244 return visit_continue
;
1247 ir_variable
*const existing
=
1248 this->symbols
->get_variable(ir
->var
->name
);
1249 if (existing
!= NULL
)
1252 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1254 this->symbols
->add_variable(copy
);
1255 this->instructions
->push_head(copy
);
1259 return visit_continue
;
1263 struct gl_shader
*target
;
1264 glsl_symbol_table
*symbols
;
1265 exec_list
*instructions
;
1269 remap_visitor
v(target
, temps
);
1276 * Move non-declarations from one instruction stream to another
1278 * The intended usage pattern of this function is to pass the pointer to the
1279 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1280 * pointer) for \c last and \c false for \c make_copies on the first
1281 * call. Successive calls pass the return value of the previous call for
1282 * \c last and \c true for \c make_copies.
1284 * \param instructions Source instruction stream
1285 * \param last Instruction after which new instructions should be
1286 * inserted in the target instruction stream
1287 * \param make_copies Flag selecting whether instructions in \c instructions
1288 * should be copied (via \c ir_instruction::clone) into the
1289 * target list or moved.
1292 * The new "last" instruction in the target instruction stream. This pointer
1293 * is suitable for use as the \c last parameter of a later call to this
1297 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1298 bool make_copies
, gl_shader
*target
)
1300 hash_table
*temps
= NULL
;
1303 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1304 hash_table_pointer_compare
);
1306 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1307 if (inst
->as_function())
1310 ir_variable
*var
= inst
->as_variable();
1311 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1314 assert(inst
->as_assignment()
1316 || inst
->as_if() /* for initializers with the ?: operator */
1317 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1320 inst
= inst
->clone(target
, NULL
);
1323 hash_table_insert(temps
, inst
, var
);
1325 remap_variables(inst
, target
, temps
);
1330 last
->insert_after(inst
);
1335 hash_table_dtor(temps
);
1341 * Get the function signature for main from a shader
1343 ir_function_signature
*
1344 link_get_main_function_signature(gl_shader
*sh
)
1346 ir_function
*const f
= sh
->symbols
->get_function("main");
1348 exec_list void_parameters
;
1350 /* Look for the 'void main()' signature and ensure that it's defined.
1351 * This keeps the linker from accidentally pick a shader that just
1352 * contains a prototype for main.
1354 * We don't have to check for multiple definitions of main (in multiple
1355 * shaders) because that would have already been caught above.
1357 ir_function_signature
*sig
=
1358 f
->matching_signature(NULL
, &void_parameters
, false);
1359 if ((sig
!= NULL
) && sig
->is_defined
) {
1369 * This class is only used in link_intrastage_shaders() below but declaring
1370 * it inside that function leads to compiler warnings with some versions of
1373 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1375 array_sizing_visitor()
1376 : mem_ctx(ralloc_context(NULL
)),
1377 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1378 hash_table_pointer_compare
))
1382 ~array_sizing_visitor()
1384 hash_table_dtor(this->unnamed_interfaces
);
1385 ralloc_free(this->mem_ctx
);
1388 virtual ir_visitor_status
visit(ir_variable
*var
)
1390 fixup_type(&var
->type
, var
->data
.max_array_access
);
1391 if (var
->type
->is_interface()) {
1392 if (interface_contains_unsized_arrays(var
->type
)) {
1393 const glsl_type
*new_type
=
1394 resize_interface_members(var
->type
,
1395 var
->get_max_ifc_array_access());
1396 var
->type
= new_type
;
1397 var
->change_interface_type(new_type
);
1399 } else if (var
->type
->is_array() &&
1400 var
->type
->fields
.array
->is_interface()) {
1401 if (interface_contains_unsized_arrays(var
->type
->fields
.array
)) {
1402 const glsl_type
*new_type
=
1403 resize_interface_members(var
->type
->fields
.array
,
1404 var
->get_max_ifc_array_access());
1405 var
->change_interface_type(new_type
);
1406 var
->type
= update_interface_members_array(var
->type
, new_type
);
1408 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1409 /* Store a pointer to the variable in the unnamed_interfaces
1412 ir_variable
**interface_vars
= (ir_variable
**)
1413 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1414 if (interface_vars
== NULL
) {
1415 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1417 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1420 unsigned index
= ifc_type
->field_index(var
->name
);
1421 assert(index
< ifc_type
->length
);
1422 assert(interface_vars
[index
] == NULL
);
1423 interface_vars
[index
] = var
;
1425 return visit_continue
;
1429 * For each unnamed interface block that was discovered while running the
1430 * visitor, adjust the interface type to reflect the newly assigned array
1431 * sizes, and fix up the ir_variable nodes to point to the new interface
1434 void fixup_unnamed_interface_types()
1436 hash_table_call_foreach(this->unnamed_interfaces
,
1437 fixup_unnamed_interface_type
, NULL
);
1442 * If the type pointed to by \c type represents an unsized array, replace
1443 * it with a sized array whose size is determined by max_array_access.
1445 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
)
1447 if ((*type
)->is_unsized_array()) {
1448 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1449 max_array_access
+ 1);
1450 assert(*type
!= NULL
);
1454 static const glsl_type
*
1455 update_interface_members_array(const glsl_type
*type
,
1456 const glsl_type
*new_interface_type
)
1458 const glsl_type
*element_type
= type
->fields
.array
;
1459 if (element_type
->is_array()) {
1460 const glsl_type
*new_array_type
=
1461 update_interface_members_array(element_type
, new_interface_type
);
1462 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1464 return glsl_type::get_array_instance(new_interface_type
,
1470 * Determine whether the given interface type contains unsized arrays (if
1471 * it doesn't, array_sizing_visitor doesn't need to process it).
1473 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1475 for (unsigned i
= 0; i
< type
->length
; i
++) {
1476 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1477 if (elem_type
->is_unsized_array())
1484 * Create a new interface type based on the given type, with unsized arrays
1485 * replaced by sized arrays whose size is determined by
1486 * max_ifc_array_access.
1488 static const glsl_type
*
1489 resize_interface_members(const glsl_type
*type
,
1490 const unsigned *max_ifc_array_access
)
1492 unsigned num_fields
= type
->length
;
1493 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1494 memcpy(fields
, type
->fields
.structure
,
1495 num_fields
* sizeof(*fields
));
1496 for (unsigned i
= 0; i
< num_fields
; i
++) {
1497 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
]);
1499 glsl_interface_packing packing
=
1500 (glsl_interface_packing
) type
->interface_packing
;
1501 const glsl_type
*new_ifc_type
=
1502 glsl_type::get_interface_instance(fields
, num_fields
,
1503 packing
, type
->name
);
1505 return new_ifc_type
;
1508 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1511 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1512 ir_variable
**interface_vars
= (ir_variable
**) data
;
1513 unsigned num_fields
= ifc_type
->length
;
1514 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1515 memcpy(fields
, ifc_type
->fields
.structure
,
1516 num_fields
* sizeof(*fields
));
1517 bool interface_type_changed
= false;
1518 for (unsigned i
= 0; i
< num_fields
; i
++) {
1519 if (interface_vars
[i
] != NULL
&&
1520 fields
[i
].type
!= interface_vars
[i
]->type
) {
1521 fields
[i
].type
= interface_vars
[i
]->type
;
1522 interface_type_changed
= true;
1525 if (!interface_type_changed
) {
1529 glsl_interface_packing packing
=
1530 (glsl_interface_packing
) ifc_type
->interface_packing
;
1531 const glsl_type
*new_ifc_type
=
1532 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1535 for (unsigned i
= 0; i
< num_fields
; i
++) {
1536 if (interface_vars
[i
] != NULL
)
1537 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1542 * Memory context used to allocate the data in \c unnamed_interfaces.
1547 * Hash table from const glsl_type * to an array of ir_variable *'s
1548 * pointing to the ir_variables constituting each unnamed interface block.
1550 hash_table
*unnamed_interfaces
;
1555 * Performs the cross-validation of tessellation control shader vertices and
1556 * layout qualifiers for the attached tessellation control shaders,
1557 * and propagates them to the linked TCS and linked shader program.
1560 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1561 struct gl_shader
*linked_shader
,
1562 struct gl_shader
**shader_list
,
1563 unsigned num_shaders
)
1565 linked_shader
->TessCtrl
.VerticesOut
= 0;
1567 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1570 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1572 * "All tessellation control shader layout declarations in a program
1573 * must specify the same output patch vertex count. There must be at
1574 * least one layout qualifier specifying an output patch vertex count
1575 * in any program containing tessellation control shaders; however,
1576 * such a declaration is not required in all tessellation control
1580 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1581 struct gl_shader
*shader
= shader_list
[i
];
1583 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1584 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1585 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1586 linker_error(prog
, "tessellation control shader defined with "
1587 "conflicting output vertex count (%d and %d)\n",
1588 linked_shader
->TessCtrl
.VerticesOut
,
1589 shader
->TessCtrl
.VerticesOut
);
1592 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1596 /* Just do the intrastage -> interstage propagation right now,
1597 * since we already know we're in the right type of shader program
1600 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1601 linker_error(prog
, "tessellation control shader didn't declare "
1602 "vertices out layout qualifier\n");
1605 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1610 * Performs the cross-validation of tessellation evaluation shader
1611 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1612 * for the attached tessellation evaluation shaders, and propagates them
1613 * to the linked TES and linked shader program.
1616 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1617 struct gl_shader
*linked_shader
,
1618 struct gl_shader
**shader_list
,
1619 unsigned num_shaders
)
1621 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1622 linked_shader
->TessEval
.Spacing
= 0;
1623 linked_shader
->TessEval
.VertexOrder
= 0;
1624 linked_shader
->TessEval
.PointMode
= -1;
1626 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1629 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1631 * "At least one tessellation evaluation shader (compilation unit) in
1632 * a program must declare a primitive mode in its input layout.
1633 * Declaration vertex spacing, ordering, and point mode identifiers is
1634 * optional. It is not required that all tessellation evaluation
1635 * shaders in a program declare a primitive mode. If spacing or
1636 * vertex ordering declarations are omitted, the tessellation
1637 * primitive generator will use equal spacing or counter-clockwise
1638 * vertex ordering, respectively. If a point mode declaration is
1639 * omitted, the tessellation primitive generator will produce lines or
1640 * triangles according to the primitive mode."
1643 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1644 struct gl_shader
*shader
= shader_list
[i
];
1646 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1647 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1648 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1649 linker_error(prog
, "tessellation evaluation shader defined with "
1650 "conflicting input primitive modes.\n");
1653 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1656 if (shader
->TessEval
.Spacing
!= 0) {
1657 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1658 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1659 linker_error(prog
, "tessellation evaluation shader defined with "
1660 "conflicting vertex spacing.\n");
1663 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1666 if (shader
->TessEval
.VertexOrder
!= 0) {
1667 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1668 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1669 linker_error(prog
, "tessellation evaluation shader defined with "
1670 "conflicting ordering.\n");
1673 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1676 if (shader
->TessEval
.PointMode
!= -1) {
1677 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1678 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1679 linker_error(prog
, "tessellation evaluation shader defined with "
1680 "conflicting point modes.\n");
1683 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1688 /* Just do the intrastage -> interstage propagation right now,
1689 * since we already know we're in the right type of shader program
1692 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1694 "tessellation evaluation shader didn't declare input "
1695 "primitive modes.\n");
1698 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1700 if (linked_shader
->TessEval
.Spacing
== 0)
1701 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1702 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1704 if (linked_shader
->TessEval
.VertexOrder
== 0)
1705 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1706 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1708 if (linked_shader
->TessEval
.PointMode
== -1)
1709 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1710 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1715 * Performs the cross-validation of layout qualifiers specified in
1716 * redeclaration of gl_FragCoord for the attached fragment shaders,
1717 * and propagates them to the linked FS and linked shader program.
1720 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1721 struct gl_shader
*linked_shader
,
1722 struct gl_shader
**shader_list
,
1723 unsigned num_shaders
)
1725 linked_shader
->redeclares_gl_fragcoord
= false;
1726 linked_shader
->uses_gl_fragcoord
= false;
1727 linked_shader
->origin_upper_left
= false;
1728 linked_shader
->pixel_center_integer
= false;
1730 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1731 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1734 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1735 struct gl_shader
*shader
= shader_list
[i
];
1736 /* From the GLSL 1.50 spec, page 39:
1738 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1739 * it must be redeclared in all the fragment shaders in that program
1740 * that have a static use gl_FragCoord."
1742 if ((linked_shader
->redeclares_gl_fragcoord
1743 && !shader
->redeclares_gl_fragcoord
1744 && shader
->uses_gl_fragcoord
)
1745 || (shader
->redeclares_gl_fragcoord
1746 && !linked_shader
->redeclares_gl_fragcoord
1747 && linked_shader
->uses_gl_fragcoord
)) {
1748 linker_error(prog
, "fragment shader defined with conflicting "
1749 "layout qualifiers for gl_FragCoord\n");
1752 /* From the GLSL 1.50 spec, page 39:
1754 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1755 * single program must have the same set of qualifiers."
1757 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1758 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1759 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1760 linker_error(prog
, "fragment shader defined with conflicting "
1761 "layout qualifiers for gl_FragCoord\n");
1764 /* Update the linked shader state. Note that uses_gl_fragcoord should
1765 * accumulate the results. The other values should replace. If there
1766 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1767 * are already known to be the same.
1769 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1770 linked_shader
->redeclares_gl_fragcoord
=
1771 shader
->redeclares_gl_fragcoord
;
1772 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1773 || shader
->uses_gl_fragcoord
;
1774 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1775 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1778 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1783 * Performs the cross-validation of geometry shader max_vertices and
1784 * primitive type layout qualifiers for the attached geometry shaders,
1785 * and propagates them to the linked GS and linked shader program.
1788 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1789 struct gl_shader
*linked_shader
,
1790 struct gl_shader
**shader_list
,
1791 unsigned num_shaders
)
1793 linked_shader
->Geom
.VerticesOut
= 0;
1794 linked_shader
->Geom
.Invocations
= 0;
1795 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1796 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1798 /* No in/out qualifiers defined for anything but GLSL 1.50+
1799 * geometry shaders so far.
1801 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1804 /* From the GLSL 1.50 spec, page 46:
1806 * "All geometry shader output layout declarations in a program
1807 * must declare the same layout and same value for
1808 * max_vertices. There must be at least one geometry output
1809 * layout declaration somewhere in a program, but not all
1810 * geometry shaders (compilation units) are required to
1814 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1815 struct gl_shader
*shader
= shader_list
[i
];
1817 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1818 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1819 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1820 linker_error(prog
, "geometry shader defined with conflicting "
1824 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1827 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1828 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1829 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1830 linker_error(prog
, "geometry shader defined with conflicting "
1834 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1837 if (shader
->Geom
.VerticesOut
!= 0) {
1838 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1839 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1840 linker_error(prog
, "geometry shader defined with conflicting "
1841 "output vertex count (%d and %d)\n",
1842 linked_shader
->Geom
.VerticesOut
,
1843 shader
->Geom
.VerticesOut
);
1846 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1849 if (shader
->Geom
.Invocations
!= 0) {
1850 if (linked_shader
->Geom
.Invocations
!= 0 &&
1851 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1852 linker_error(prog
, "geometry shader defined with conflicting "
1853 "invocation count (%d and %d)\n",
1854 linked_shader
->Geom
.Invocations
,
1855 shader
->Geom
.Invocations
);
1858 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1862 /* Just do the intrastage -> interstage propagation right now,
1863 * since we already know we're in the right type of shader program
1866 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1868 "geometry shader didn't declare primitive input type\n");
1871 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1873 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1875 "geometry shader didn't declare primitive output type\n");
1878 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1880 if (linked_shader
->Geom
.VerticesOut
== 0) {
1882 "geometry shader didn't declare max_vertices\n");
1885 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1887 if (linked_shader
->Geom
.Invocations
== 0)
1888 linked_shader
->Geom
.Invocations
= 1;
1890 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1895 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1896 * qualifiers for the attached compute shaders, and propagate them to the
1897 * linked CS and linked shader program.
1900 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1901 struct gl_shader
*linked_shader
,
1902 struct gl_shader
**shader_list
,
1903 unsigned num_shaders
)
1905 for (int i
= 0; i
< 3; i
++)
1906 linked_shader
->Comp
.LocalSize
[i
] = 0;
1908 /* This function is called for all shader stages, but it only has an effect
1909 * for compute shaders.
1911 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
1914 /* From the ARB_compute_shader spec, in the section describing local size
1917 * If multiple compute shaders attached to a single program object
1918 * declare local work-group size, the declarations must be identical;
1919 * otherwise a link-time error results. Furthermore, if a program
1920 * object contains any compute shaders, at least one must contain an
1921 * input layout qualifier specifying the local work sizes of the
1922 * program, or a link-time error will occur.
1924 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
1925 struct gl_shader
*shader
= shader_list
[sh
];
1927 if (shader
->Comp
.LocalSize
[0] != 0) {
1928 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
1929 for (int i
= 0; i
< 3; i
++) {
1930 if (linked_shader
->Comp
.LocalSize
[i
] !=
1931 shader
->Comp
.LocalSize
[i
]) {
1932 linker_error(prog
, "compute shader defined with conflicting "
1938 for (int i
= 0; i
< 3; i
++)
1939 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
1943 /* Just do the intrastage -> interstage propagation right now,
1944 * since we already know we're in the right type of shader program
1947 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
1948 linker_error(prog
, "compute shader didn't declare local size\n");
1951 for (int i
= 0; i
< 3; i
++)
1952 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
1957 * Combine a group of shaders for a single stage to generate a linked shader
1960 * If this function is supplied a single shader, it is cloned, and the new
1961 * shader is returned.
1963 static struct gl_shader
*
1964 link_intrastage_shaders(void *mem_ctx
,
1965 struct gl_context
*ctx
,
1966 struct gl_shader_program
*prog
,
1967 struct gl_shader
**shader_list
,
1968 unsigned num_shaders
)
1970 struct gl_uniform_block
*uniform_blocks
= NULL
;
1972 /* Check that global variables defined in multiple shaders are consistent.
1974 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1975 if (!prog
->LinkStatus
)
1978 /* Check that interface blocks defined in multiple shaders are consistent.
1980 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1982 if (!prog
->LinkStatus
)
1985 /* Link up uniform blocks defined within this stage. */
1986 const unsigned num_uniform_blocks
=
1987 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
1989 if (!prog
->LinkStatus
)
1992 /* Check that there is only a single definition of each function signature
1993 * across all shaders.
1995 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1996 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
1997 ir_function
*const f
= node
->as_function();
2002 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2003 ir_function
*const other
=
2004 shader_list
[j
]->symbols
->get_function(f
->name
);
2006 /* If the other shader has no function (and therefore no function
2007 * signatures) with the same name, skip to the next shader.
2012 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2013 if (!sig
->is_defined
|| sig
->is_builtin())
2016 ir_function_signature
*other_sig
=
2017 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2019 if ((other_sig
!= NULL
) && other_sig
->is_defined
2020 && !other_sig
->is_builtin()) {
2021 linker_error(prog
, "function `%s' is multiply defined\n",
2030 /* Find the shader that defines main, and make a clone of it.
2032 * Starting with the clone, search for undefined references. If one is
2033 * found, find the shader that defines it. Clone the reference and add
2034 * it to the shader. Repeat until there are no undefined references or
2035 * until a reference cannot be resolved.
2037 gl_shader
*main
= NULL
;
2038 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2039 if (link_get_main_function_signature(shader_list
[i
]) != NULL
) {
2040 main
= shader_list
[i
];
2046 linker_error(prog
, "%s shader lacks `main'\n",
2047 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2051 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2052 linked
->ir
= new(linked
) exec_list
;
2053 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2055 linked
->UniformBlocks
= uniform_blocks
;
2056 linked
->NumUniformBlocks
= num_uniform_blocks
;
2057 ralloc_steal(linked
, linked
->UniformBlocks
);
2059 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2060 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2061 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2062 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2063 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2065 populate_symbol_table(linked
);
2067 /* The pointer to the main function in the final linked shader (i.e., the
2068 * copy of the original shader that contained the main function).
2070 ir_function_signature
*const main_sig
=
2071 link_get_main_function_signature(linked
);
2073 /* Move any instructions other than variable declarations or function
2074 * declarations into main.
2076 exec_node
*insertion_point
=
2077 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2080 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2081 if (shader_list
[i
] == main
)
2084 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2085 insertion_point
, true, linked
);
2088 /* Check if any shader needs built-in functions. */
2089 bool need_builtins
= false;
2090 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2091 if (shader_list
[i
]->uses_builtin_functions
) {
2092 need_builtins
= true;
2098 if (need_builtins
) {
2099 /* Make a temporary array one larger than shader_list, which will hold
2100 * the built-in function shader as well.
2102 gl_shader
**linking_shaders
= (gl_shader
**)
2103 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2105 ok
= linking_shaders
!= NULL
;
2108 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2109 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2111 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2113 free(linking_shaders
);
2115 _mesa_error_no_memory(__func__
);
2118 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2123 ctx
->Driver
.DeleteShader(ctx
, linked
);
2127 /* At this point linked should contain all of the linked IR, so
2128 * validate it to make sure nothing went wrong.
2130 validate_ir_tree(linked
->ir
);
2132 /* Set the size of geometry shader input arrays */
2133 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2134 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2135 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2136 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2137 ir
->accept(&input_resize_visitor
);
2141 if (ctx
->Const
.VertexID_is_zero_based
)
2142 lower_vertex_id(linked
);
2144 /* Validate correct usage of barrier() in the tess control shader */
2145 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2146 barrier_use_visitor
visitor(prog
);
2147 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2148 ir
->accept(&visitor
);
2152 /* Make a pass over all variable declarations to ensure that arrays with
2153 * unspecified sizes have a size specified. The size is inferred from the
2154 * max_array_access field.
2156 array_sizing_visitor v
;
2158 v
.fixup_unnamed_interface_types();
2164 * Update the sizes of linked shader uniform arrays to the maximum
2167 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2169 * If one or more elements of an array are active,
2170 * GetActiveUniform will return the name of the array in name,
2171 * subject to the restrictions listed above. The type of the array
2172 * is returned in type. The size parameter contains the highest
2173 * array element index used, plus one. The compiler or linker
2174 * determines the highest index used. There will be only one
2175 * active uniform reported by the GL per uniform array.
2179 update_array_sizes(struct gl_shader_program
*prog
)
2181 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2182 if (prog
->_LinkedShaders
[i
] == NULL
)
2185 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2186 ir_variable
*const var
= node
->as_variable();
2188 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2189 !var
->type
->is_array())
2192 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2193 * will not be eliminated. Since we always do std140, just
2194 * don't resize arrays in UBOs.
2196 * Atomic counters are supposed to get deterministic
2197 * locations assigned based on the declaration ordering and
2198 * sizes, array compaction would mess that up.
2200 if (var
->is_in_buffer_block() || var
->type
->contains_atomic())
2203 unsigned int size
= var
->data
.max_array_access
;
2204 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2205 if (prog
->_LinkedShaders
[j
] == NULL
)
2208 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2209 ir_variable
*other_var
= node2
->as_variable();
2213 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2214 other_var
->data
.max_array_access
> size
) {
2215 size
= other_var
->data
.max_array_access
;
2220 if (size
+ 1 != var
->type
->length
) {
2221 /* If this is a built-in uniform (i.e., it's backed by some
2222 * fixed-function state), adjust the number of state slots to
2223 * match the new array size. The number of slots per array entry
2224 * is not known. It seems safe to assume that the total number of
2225 * slots is an integer multiple of the number of array elements.
2226 * Determine the number of slots per array element by dividing by
2227 * the old (total) size.
2229 const unsigned num_slots
= var
->get_num_state_slots();
2230 if (num_slots
> 0) {
2231 var
->set_num_state_slots((size
+ 1)
2232 * (num_slots
/ var
->type
->length
));
2235 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2237 /* FINISHME: We should update the types of array
2238 * dereferences of this variable now.
2246 * Resize tessellation evaluation per-vertex inputs to the size of
2247 * tessellation control per-vertex outputs.
2250 resize_tes_inputs(struct gl_context
*ctx
,
2251 struct gl_shader_program
*prog
)
2253 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2256 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2257 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2259 /* If no control shader is present, then the TES inputs are statically
2260 * sized to MaxPatchVertices; the actual size of the arrays won't be
2261 * known until draw time.
2263 const int num_vertices
= tcs
2264 ? tcs
->TessCtrl
.VerticesOut
2265 : ctx
->Const
.MaxPatchVertices
;
2267 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2268 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2269 ir
->accept(&input_resize_visitor
);
2274 * Find a contiguous set of available bits in a bitmask.
2276 * \param used_mask Bits representing used (1) and unused (0) locations
2277 * \param needed_count Number of contiguous bits needed.
2280 * Base location of the available bits on success or -1 on failure.
2283 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2285 unsigned needed_mask
= (1 << needed_count
) - 1;
2286 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2288 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2289 * cannot optimize possibly infinite loops" for the loop below.
2291 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2294 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2295 if ((needed_mask
& ~used_mask
) == needed_mask
)
2306 * Assign locations for either VS inputs or FS outputs
2308 * \param prog Shader program whose variables need locations assigned
2309 * \param target_index Selector for the program target to receive location
2310 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2311 * \c MESA_SHADER_FRAGMENT.
2312 * \param max_index Maximum number of generic locations. This corresponds
2313 * to either the maximum number of draw buffers or the
2314 * maximum number of generic attributes.
2317 * If locations are successfully assigned, true is returned. Otherwise an
2318 * error is emitted to the shader link log and false is returned.
2321 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2322 unsigned target_index
,
2325 /* Mark invalid locations as being used.
2327 unsigned used_locations
= (max_index
>= 32)
2328 ? ~0 : ~((1 << max_index
) - 1);
2330 assert((target_index
== MESA_SHADER_VERTEX
)
2331 || (target_index
== MESA_SHADER_FRAGMENT
));
2333 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2337 /* Operate in a total of four passes.
2339 * 1. Invalidate the location assignments for all vertex shader inputs.
2341 * 2. Assign locations for inputs that have user-defined (via
2342 * glBindVertexAttribLocation) locations and outputs that have
2343 * user-defined locations (via glBindFragDataLocation).
2345 * 3. Sort the attributes without assigned locations by number of slots
2346 * required in decreasing order. Fragmentation caused by attribute
2347 * locations assigned by the application may prevent large attributes
2348 * from having enough contiguous space.
2350 * 4. Assign locations to any inputs without assigned locations.
2353 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2354 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2356 const enum ir_variable_mode direction
=
2357 (target_index
== MESA_SHADER_VERTEX
)
2358 ? ir_var_shader_in
: ir_var_shader_out
;
2361 /* Temporary storage for the set of attributes that need locations assigned.
2367 /* Used below in the call to qsort. */
2368 static int compare(const void *a
, const void *b
)
2370 const temp_attr
*const l
= (const temp_attr
*) a
;
2371 const temp_attr
*const r
= (const temp_attr
*) b
;
2373 /* Reversed because we want a descending order sort below. */
2374 return r
->slots
- l
->slots
;
2378 unsigned num_attr
= 0;
2379 unsigned total_attribs_size
= 0;
2381 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2382 ir_variable
*const var
= node
->as_variable();
2384 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2387 if (var
->data
.explicit_location
) {
2388 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2389 || (var
->data
.location
< 0)) {
2391 "invalid explicit location %d specified for `%s'\n",
2392 (var
->data
.location
< 0)
2393 ? var
->data
.location
2394 : var
->data
.location
- generic_base
,
2398 } else if (target_index
== MESA_SHADER_VERTEX
) {
2401 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2402 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2403 var
->data
.location
= binding
;
2404 var
->data
.is_unmatched_generic_inout
= 0;
2406 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2410 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2411 assert(binding
>= FRAG_RESULT_DATA0
);
2412 var
->data
.location
= binding
;
2413 var
->data
.is_unmatched_generic_inout
= 0;
2415 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2416 var
->data
.index
= index
;
2421 const unsigned slots
= var
->type
->count_attribute_slots();
2423 /* From GL4.5 core spec, section 11.1.1 (Vertex Attributes):
2425 * "A program with more than the value of MAX_VERTEX_ATTRIBS active
2426 * attribute variables may fail to link, unless device-dependent
2427 * optimizations are able to make the program fit within available
2428 * hardware resources. For the purposes of this test, attribute variables
2429 * of the type dvec3, dvec4, dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3,
2430 * and dmat4 may count as consuming twice as many attributes as equivalent
2431 * single-precision types. While these types use the same number of
2432 * generic attributes as their single-precision equivalents,
2433 * implementations are permitted to consume two single-precision vectors
2434 * of internal storage for each three- or four-component double-precision
2436 * Until someone has a good reason in Mesa, enforce that now.
2438 if (target_index
== MESA_SHADER_VERTEX
) {
2439 total_attribs_size
+= slots
;
2440 if (var
->type
->without_array() == glsl_type::dvec3_type
||
2441 var
->type
->without_array() == glsl_type::dvec4_type
||
2442 var
->type
->without_array() == glsl_type::dmat2x3_type
||
2443 var
->type
->without_array() == glsl_type::dmat2x4_type
||
2444 var
->type
->without_array() == glsl_type::dmat3_type
||
2445 var
->type
->without_array() == glsl_type::dmat3x4_type
||
2446 var
->type
->without_array() == glsl_type::dmat4x3_type
||
2447 var
->type
->without_array() == glsl_type::dmat4_type
)
2448 total_attribs_size
+= slots
;
2451 /* If the variable is not a built-in and has a location statically
2452 * assigned in the shader (presumably via a layout qualifier), make sure
2453 * that it doesn't collide with other assigned locations. Otherwise,
2454 * add it to the list of variables that need linker-assigned locations.
2456 if (var
->data
.location
!= -1) {
2457 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2458 /* From page 61 of the OpenGL 4.0 spec:
2460 * "LinkProgram will fail if the attribute bindings assigned
2461 * by BindAttribLocation do not leave not enough space to
2462 * assign a location for an active matrix attribute or an
2463 * active attribute array, both of which require multiple
2464 * contiguous generic attributes."
2466 * I think above text prohibits the aliasing of explicit and
2467 * automatic assignments. But, aliasing is allowed in manual
2468 * assignments of attribute locations. See below comments for
2471 * From OpenGL 4.0 spec, page 61:
2473 * "It is possible for an application to bind more than one
2474 * attribute name to the same location. This is referred to as
2475 * aliasing. This will only work if only one of the aliased
2476 * attributes is active in the executable program, or if no
2477 * path through the shader consumes more than one attribute of
2478 * a set of attributes aliased to the same location. A link
2479 * error can occur if the linker determines that every path
2480 * through the shader consumes multiple aliased attributes,
2481 * but implementations are not required to generate an error
2484 * From GLSL 4.30 spec, page 54:
2486 * "A program will fail to link if any two non-vertex shader
2487 * input variables are assigned to the same location. For
2488 * vertex shaders, multiple input variables may be assigned
2489 * to the same location using either layout qualifiers or via
2490 * the OpenGL API. However, such aliasing is intended only to
2491 * support vertex shaders where each execution path accesses
2492 * at most one input per each location. Implementations are
2493 * permitted, but not required, to generate link-time errors
2494 * if they detect that every path through the vertex shader
2495 * executable accesses multiple inputs assigned to any single
2496 * location. For all shader types, a program will fail to link
2497 * if explicit location assignments leave the linker unable
2498 * to find space for other variables without explicit
2501 * From OpenGL ES 3.0 spec, page 56:
2503 * "Binding more than one attribute name to the same location
2504 * is referred to as aliasing, and is not permitted in OpenGL
2505 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2506 * fail when this condition exists. However, aliasing is
2507 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2508 * This will only work if only one of the aliased attributes
2509 * is active in the executable program, or if no path through
2510 * the shader consumes more than one attribute of a set of
2511 * attributes aliased to the same location. A link error can
2512 * occur if the linker determines that every path through the
2513 * shader consumes multiple aliased attributes, but implemen-
2514 * tations are not required to generate an error in this case."
2516 * After looking at above references from OpenGL, OpenGL ES and
2517 * GLSL specifications, we allow aliasing of vertex input variables
2518 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2520 * NOTE: This is not required by the spec but its worth mentioning
2521 * here that we're not doing anything to make sure that no path
2522 * through the vertex shader executable accesses multiple inputs
2523 * assigned to any single location.
2526 /* Mask representing the contiguous slots that will be used by
2529 const unsigned attr
= var
->data
.location
- generic_base
;
2530 const unsigned use_mask
= (1 << slots
) - 1;
2531 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2532 ? "vertex shader input" : "fragment shader output";
2534 /* Generate a link error if the requested locations for this
2535 * attribute exceed the maximum allowed attribute location.
2537 if (attr
+ slots
> max_index
) {
2539 "insufficient contiguous locations "
2540 "available for %s `%s' %d %d %d\n", string
,
2541 var
->name
, used_locations
, use_mask
, attr
);
2545 /* Generate a link error if the set of bits requested for this
2546 * attribute overlaps any previously allocated bits.
2548 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2549 if (target_index
== MESA_SHADER_FRAGMENT
||
2550 (prog
->IsES
&& prog
->Version
>= 300)) {
2552 "overlapping location is assigned "
2553 "to %s `%s' %d %d %d\n", string
,
2554 var
->name
, used_locations
, use_mask
, attr
);
2557 linker_warning(prog
,
2558 "overlapping location is assigned "
2559 "to %s `%s' %d %d %d\n", string
,
2560 var
->name
, used_locations
, use_mask
, attr
);
2564 used_locations
|= (use_mask
<< attr
);
2570 to_assign
[num_attr
].slots
= slots
;
2571 to_assign
[num_attr
].var
= var
;
2575 if (target_index
== MESA_SHADER_VERTEX
) {
2576 if (total_attribs_size
> max_index
) {
2578 "attempt to use %d vertex attribute slots only %d available ",
2579 total_attribs_size
, max_index
);
2584 /* If all of the attributes were assigned locations by the application (or
2585 * are built-in attributes with fixed locations), return early. This should
2586 * be the common case.
2591 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2593 if (target_index
== MESA_SHADER_VERTEX
) {
2594 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2595 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2596 * reserved to prevent it from being automatically allocated below.
2598 find_deref_visitor
find("gl_Vertex");
2600 if (find
.variable_found())
2601 used_locations
|= (1 << 0);
2604 for (unsigned i
= 0; i
< num_attr
; i
++) {
2605 /* Mask representing the contiguous slots that will be used by this
2608 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2610 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2613 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2614 ? "vertex shader input" : "fragment shader output";
2617 "insufficient contiguous locations "
2618 "available for %s `%s'\n",
2619 string
, to_assign
[i
].var
->name
);
2623 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2624 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2625 used_locations
|= (use_mask
<< location
);
2633 * Demote shader inputs and outputs that are not used in other stages
2636 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
2638 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2639 ir_variable
*const var
= node
->as_variable();
2641 if ((var
== NULL
) || (var
->data
.mode
!= int(mode
)))
2644 /* A shader 'in' or 'out' variable is only really an input or output if
2645 * its value is used by other shader stages. This will cause the variable
2646 * to have a location assigned.
2648 if (var
->data
.is_unmatched_generic_inout
) {
2649 assert(var
->data
.mode
!= ir_var_temporary
);
2650 var
->data
.mode
= ir_var_auto
;
2657 * Store the gl_FragDepth layout in the gl_shader_program struct.
2660 store_fragdepth_layout(struct gl_shader_program
*prog
)
2662 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2666 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2668 /* We don't look up the gl_FragDepth symbol directly because if
2669 * gl_FragDepth is not used in the shader, it's removed from the IR.
2670 * However, the symbol won't be removed from the symbol table.
2672 * We're only interested in the cases where the variable is NOT removed
2675 foreach_in_list(ir_instruction
, node
, ir
) {
2676 ir_variable
*const var
= node
->as_variable();
2678 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2682 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2683 switch (var
->data
.depth_layout
) {
2684 case ir_depth_layout_none
:
2685 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2687 case ir_depth_layout_any
:
2688 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2690 case ir_depth_layout_greater
:
2691 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2693 case ir_depth_layout_less
:
2694 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2696 case ir_depth_layout_unchanged
:
2697 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2708 * Validate the resources used by a program versus the implementation limits
2711 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2713 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2714 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2719 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2720 linker_error(prog
, "Too many %s shader texture samplers\n",
2721 _mesa_shader_stage_to_string(i
));
2724 if (sh
->num_uniform_components
>
2725 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2726 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2727 linker_warning(prog
, "Too many %s shader default uniform block "
2728 "components, but the driver will try to optimize "
2729 "them out; this is non-portable out-of-spec "
2731 _mesa_shader_stage_to_string(i
));
2733 linker_error(prog
, "Too many %s shader default uniform block "
2735 _mesa_shader_stage_to_string(i
));
2739 if (sh
->num_combined_uniform_components
>
2740 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2741 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2742 linker_warning(prog
, "Too many %s shader uniform components, "
2743 "but the driver will try to optimize them out; "
2744 "this is non-portable out-of-spec behavior\n",
2745 _mesa_shader_stage_to_string(i
));
2747 linker_error(prog
, "Too many %s shader uniform components\n",
2748 _mesa_shader_stage_to_string(i
));
2753 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2754 unsigned total_uniform_blocks
= 0;
2756 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
2757 if (prog
->UniformBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxUniformBlockSize
) {
2758 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
2759 prog
->UniformBlocks
[i
].Name
,
2760 prog
->UniformBlocks
[i
].UniformBufferSize
,
2761 ctx
->Const
.MaxUniformBlockSize
);
2764 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2765 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2767 total_uniform_blocks
++;
2771 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2772 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2773 prog
->NumUniformBlocks
,
2774 ctx
->Const
.MaxCombinedUniformBlocks
);
2776 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2777 const unsigned max_uniform_blocks
=
2778 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2779 if (blocks
[i
] > max_uniform_blocks
) {
2780 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2781 _mesa_shader_stage_to_string(i
),
2783 max_uniform_blocks
);
2792 * Validate shader image resources.
2795 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2797 unsigned total_image_units
= 0;
2798 unsigned fragment_outputs
= 0;
2800 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
2803 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2804 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2807 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
2808 linker_error(prog
, "Too many %s shader image uniforms\n",
2809 _mesa_shader_stage_to_string(i
));
2811 total_image_units
+= sh
->NumImages
;
2813 if (i
== MESA_SHADER_FRAGMENT
) {
2814 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2815 ir_variable
*var
= node
->as_variable();
2816 if (var
&& var
->data
.mode
== ir_var_shader_out
)
2817 fragment_outputs
+= var
->type
->count_attribute_slots();
2823 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
2824 linker_error(prog
, "Too many combined image uniforms\n");
2826 if (total_image_units
+ fragment_outputs
>
2827 ctx
->Const
.MaxCombinedImageUnitsAndFragmentOutputs
)
2828 linker_error(prog
, "Too many combined image uniforms and fragment outputs\n");
2833 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2834 * for a variable, checks for overlaps between other uniforms using explicit
2838 reserve_explicit_locations(struct gl_shader_program
*prog
,
2839 string_to_uint_map
*map
, ir_variable
*var
)
2841 unsigned slots
= var
->type
->uniform_locations();
2842 unsigned max_loc
= var
->data
.location
+ slots
- 1;
2844 /* Resize remap table if locations do not fit in the current one. */
2845 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
2846 prog
->UniformRemapTable
=
2847 reralloc(prog
, prog
->UniformRemapTable
,
2848 gl_uniform_storage
*,
2851 if (!prog
->UniformRemapTable
) {
2852 linker_error(prog
, "Out of memory during linking.\n");
2856 /* Initialize allocated space. */
2857 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
2858 prog
->UniformRemapTable
[i
] = NULL
;
2860 prog
->NumUniformRemapTable
= max_loc
+ 1;
2863 for (unsigned i
= 0; i
< slots
; i
++) {
2864 unsigned loc
= var
->data
.location
+ i
;
2866 /* Check if location is already used. */
2867 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
2869 /* Possibly same uniform from a different stage, this is ok. */
2871 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
)
2874 /* ARB_explicit_uniform_location specification states:
2876 * "No two default-block uniform variables in the program can have
2877 * the same location, even if they are unused, otherwise a compiler
2878 * or linker error will be generated."
2881 "location qualifier for uniform %s overlaps "
2882 "previously used location\n",
2887 /* Initialize location as inactive before optimization
2888 * rounds and location assignment.
2890 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
2893 /* Note, base location used for arrays. */
2894 map
->put(var
->data
.location
, var
->name
);
2900 * Check and reserve all explicit uniform locations, called before
2901 * any optimizations happen to handle also inactive uniforms and
2902 * inactive array elements that may get trimmed away.
2905 check_explicit_uniform_locations(struct gl_context
*ctx
,
2906 struct gl_shader_program
*prog
)
2908 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
2911 /* This map is used to detect if overlapping explicit locations
2912 * occur with the same uniform (from different stage) or a different one.
2914 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
2917 linker_error(prog
, "Out of memory during linking.\n");
2921 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2922 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2927 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2928 ir_variable
*var
= node
->as_variable();
2929 if (var
&& (var
->data
.mode
== ir_var_uniform
|| var
->data
.mode
== ir_var_shader_storage
) &&
2930 var
->data
.explicit_location
) {
2931 if (!reserve_explicit_locations(prog
, uniform_map
, var
)) {
2943 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
2944 const void *data
, uint8_t stages
)
2948 /* If resource already exists, do not add it again. */
2949 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
2950 if (prog
->ProgramResourceList
[i
].Data
== data
)
2953 prog
->ProgramResourceList
=
2955 prog
->ProgramResourceList
,
2956 gl_program_resource
,
2957 prog
->NumProgramResourceList
+ 1);
2959 if (!prog
->ProgramResourceList
) {
2960 linker_error(prog
, "Out of memory during linking.\n");
2964 struct gl_program_resource
*res
=
2965 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
2969 res
->StageReferences
= stages
;
2971 prog
->NumProgramResourceList
++;
2977 * Function builds a stage reference bitmask from variable name.
2980 build_stageref(struct gl_shader_program
*shProg
, const char *name
)
2984 /* Note, that we assume MAX 8 stages, if there will be more stages, type
2985 * used for reference mask in gl_program_resource will need to be changed.
2987 assert(MESA_SHADER_STAGES
< 8);
2989 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2990 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
2994 /* Shader symbol table may contain variables that have
2995 * been optimized away. Search IR for the variable instead.
2997 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2998 ir_variable
*var
= node
->as_variable();
2999 if (var
&& strcmp(var
->name
, name
) == 0) {
3009 add_interface_variables(struct gl_shader_program
*shProg
,
3010 struct gl_shader
*sh
, GLenum programInterface
)
3012 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3013 ir_variable
*var
= node
->as_variable();
3019 switch (var
->data
.mode
) {
3020 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3021 * "For GetActiveAttrib, all active vertex shader input variables
3022 * are enumerated, including the special built-in inputs gl_VertexID
3023 * and gl_InstanceID."
3025 case ir_var_system_value
:
3026 if (var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID
&&
3027 var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
&&
3028 var
->data
.location
!= SYSTEM_VALUE_INSTANCE_ID
)
3030 /* Mark special built-in inputs referenced by the vertex stage so
3031 * that they are considered active by the shader queries.
3033 mask
= (1 << (MESA_SHADER_VERTEX
));
3035 case ir_var_shader_in
:
3036 if (programInterface
!= GL_PROGRAM_INPUT
)
3039 case ir_var_shader_out
:
3040 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3047 if (!add_program_resource(shProg
, programInterface
, var
,
3048 build_stageref(shProg
, var
->name
) | mask
))
3055 * Builds up a list of program resources that point to existing
3059 build_program_resource_list(struct gl_context
*ctx
,
3060 struct gl_shader_program
*shProg
)
3062 /* Rebuild resource list. */
3063 if (shProg
->ProgramResourceList
) {
3064 ralloc_free(shProg
->ProgramResourceList
);
3065 shProg
->ProgramResourceList
= NULL
;
3066 shProg
->NumProgramResourceList
= 0;
3069 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3071 /* Determine first input and final output stage. These are used to
3072 * detect which variables should be enumerated in the resource list
3073 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3075 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3076 if (!shProg
->_LinkedShaders
[i
])
3078 if (input_stage
== MESA_SHADER_STAGES
)
3083 /* Empty shader, no resources. */
3084 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3087 /* Add inputs and outputs to the resource list. */
3088 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[input_stage
],
3092 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[output_stage
],
3096 /* Add transform feedback varyings. */
3097 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3098 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3100 build_stageref(shProg
,
3101 shProg
->LinkedTransformFeedback
.Varyings
[i
].Name
);
3102 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3103 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
3109 /* Add uniforms from uniform storage. */
3110 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3111 /* Do not add uniforms internally used by Mesa. */
3112 if (shProg
->UniformStorage
[i
].hidden
)
3116 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
);
3118 /* Add stagereferences for uniforms in a uniform block. */
3119 int block_index
= shProg
->UniformStorage
[i
].block_index
;
3120 if (block_index
!= -1) {
3121 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
3122 if (shProg
->UniformBlockStageIndex
[j
][block_index
] != -1)
3123 stageref
|= (1 << j
);
3127 if (!add_program_resource(shProg
, GL_UNIFORM
,
3128 &shProg
->UniformStorage
[i
], stageref
))
3132 /* Add program uniform blocks. */
3133 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
3134 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
3135 &shProg
->UniformBlocks
[i
], 0))
3139 /* Add atomic counter buffers. */
3140 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
3141 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
3142 &shProg
->AtomicBuffers
[i
], 0))
3146 /* TODO - following extensions will require more resource types:
3148 * GL_ARB_shader_storage_buffer_object
3149 * GL_ARB_shader_subroutine
3154 * This check is done to make sure we allow only constant expression
3155 * indexing and "constant-index-expression" (indexing with an expression
3156 * that includes loop induction variable).
3159 validate_sampler_array_indexing(struct gl_context
*ctx
,
3160 struct gl_shader_program
*prog
)
3162 dynamic_sampler_array_indexing_visitor v
;
3163 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3164 if (prog
->_LinkedShaders
[i
] == NULL
)
3167 bool no_dynamic_indexing
=
3168 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
3170 /* Search for array derefs in shader. */
3171 v
.run(prog
->_LinkedShaders
[i
]->ir
);
3172 if (v
.uses_dynamic_sampler_array_indexing()) {
3173 const char *msg
= "sampler arrays indexed with non-constant "
3174 "expressions is forbidden in GLSL %s %u";
3175 /* Backend has indicated that it has no dynamic indexing support. */
3176 if (no_dynamic_indexing
) {
3177 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3180 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3189 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3191 tfeedback_decl
*tfeedback_decls
= NULL
;
3192 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
3194 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
3196 prog
->LinkStatus
= true; /* All error paths will set this to false */
3197 prog
->Validated
= false;
3198 prog
->_Used
= false;
3200 prog
->ARB_fragment_coord_conventions_enable
= false;
3202 /* Separate the shaders into groups based on their type.
3204 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
3205 unsigned num_shaders
[MESA_SHADER_STAGES
];
3207 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3208 shader_list
[i
] = (struct gl_shader
**)
3209 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
3213 unsigned min_version
= UINT_MAX
;
3214 unsigned max_version
= 0;
3215 const bool is_es_prog
=
3216 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
3217 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
3218 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
3219 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
3221 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
3222 linker_error(prog
, "all shaders must use same shading "
3223 "language version\n");
3227 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
3228 prog
->ARB_fragment_coord_conventions_enable
= true;
3231 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
3232 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
3233 num_shaders
[shader_type
]++;
3236 /* In desktop GLSL, different shader versions may be linked together. In
3237 * GLSL ES, all shader versions must be the same.
3239 if (is_es_prog
&& min_version
!= max_version
) {
3240 linker_error(prog
, "all shaders must use same shading "
3241 "language version\n");
3245 prog
->Version
= max_version
;
3246 prog
->IsES
= is_es_prog
;
3248 /* Some shaders have to be linked with some other shaders present.
3250 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
3251 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3252 !prog
->SeparateShader
) {
3253 linker_error(prog
, "Geometry shader must be linked with "
3257 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
3258 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3259 !prog
->SeparateShader
) {
3260 linker_error(prog
, "Tessellation evaluation shader must be linked with "
3264 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3265 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3266 !prog
->SeparateShader
) {
3267 linker_error(prog
, "Tessellation control shader must be linked with "
3272 /* The spec is self-contradictory here. It allows linking without a tess
3273 * eval shader, but that can only be used with transform feedback and
3274 * rasterization disabled. However, transform feedback isn't allowed
3275 * with GL_PATCHES, so it can't be used.
3277 * More investigation showed that the idea of transform feedback after
3278 * a tess control shader was dropped, because some hw vendors couldn't
3279 * support tessellation without a tess eval shader, but the linker section
3280 * wasn't updated to reflect that.
3282 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
3285 * Do what's reasonable and always require a tess eval shader if a tess
3286 * control shader is present.
3288 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3289 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0 &&
3290 !prog
->SeparateShader
) {
3291 linker_error(prog
, "Tessellation control shader must be linked with "
3292 "tessellation evaluation shader\n");
3296 /* Compute shaders have additional restrictions. */
3297 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
3298 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
3299 linker_error(prog
, "Compute shaders may not be linked with any other "
3300 "type of shader\n");
3303 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3304 if (prog
->_LinkedShaders
[i
] != NULL
)
3305 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
3307 prog
->_LinkedShaders
[i
] = NULL
;
3310 /* Link all shaders for a particular stage and validate the result.
3312 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
3313 if (num_shaders
[stage
] > 0) {
3314 gl_shader
*const sh
=
3315 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
3316 num_shaders
[stage
]);
3318 if (!prog
->LinkStatus
) {
3320 ctx
->Driver
.DeleteShader(ctx
, sh
);
3325 case MESA_SHADER_VERTEX
:
3326 validate_vertex_shader_executable(prog
, sh
);
3328 case MESA_SHADER_TESS_CTRL
:
3329 /* nothing to be done */
3331 case MESA_SHADER_TESS_EVAL
:
3332 validate_tess_eval_shader_executable(prog
, sh
);
3334 case MESA_SHADER_GEOMETRY
:
3335 validate_geometry_shader_executable(prog
, sh
);
3337 case MESA_SHADER_FRAGMENT
:
3338 validate_fragment_shader_executable(prog
, sh
);
3341 if (!prog
->LinkStatus
) {
3343 ctx
->Driver
.DeleteShader(ctx
, sh
);
3347 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
3351 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
3352 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
3353 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
3354 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
3355 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
3356 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
3358 prog
->LastClipDistanceArraySize
= 0; /* Not used */
3360 /* Here begins the inter-stage linking phase. Some initial validation is
3361 * performed, then locations are assigned for uniforms, attributes, and
3364 cross_validate_uniforms(prog
);
3365 if (!prog
->LinkStatus
)
3370 for (prev
= 0; prev
<= MESA_SHADER_FRAGMENT
; prev
++) {
3371 if (prog
->_LinkedShaders
[prev
] != NULL
)
3375 check_explicit_uniform_locations(ctx
, prog
);
3376 if (!prog
->LinkStatus
)
3379 resize_tes_inputs(ctx
, prog
);
3381 /* Validate the inputs of each stage with the output of the preceding
3384 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3385 if (prog
->_LinkedShaders
[i
] == NULL
)
3388 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
3389 prog
->_LinkedShaders
[i
]);
3390 if (!prog
->LinkStatus
)
3393 cross_validate_outputs_to_inputs(prog
,
3394 prog
->_LinkedShaders
[prev
],
3395 prog
->_LinkedShaders
[i
]);
3396 if (!prog
->LinkStatus
)
3402 /* Cross-validate uniform blocks between shader stages */
3403 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
3404 MESA_SHADER_STAGES
);
3405 if (!prog
->LinkStatus
)
3408 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3409 if (prog
->_LinkedShaders
[i
] != NULL
)
3410 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
3413 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
3414 * it before optimization because we want most of the checks to get
3415 * dropped thanks to constant propagation.
3417 * This rule also applies to GLSL ES 3.00.
3419 if (max_version
>= (is_es_prog
? 300 : 130)) {
3420 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3422 lower_discard_flow(sh
->ir
);
3426 if (!interstage_cross_validate_uniform_blocks(prog
))
3429 /* Do common optimization before assigning storage for attributes,
3430 * uniforms, and varyings. Later optimization could possibly make
3431 * some of that unused.
3433 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3434 if (prog
->_LinkedShaders
[i
] == NULL
)
3437 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
3438 if (!prog
->LinkStatus
)
3441 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerClipDistance
) {
3442 lower_clip_distance(prog
->_LinkedShaders
[i
]);
3445 if (ctx
->Const
.LowerTessLevel
) {
3446 lower_tess_level(prog
->_LinkedShaders
[i
]);
3449 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
3450 &ctx
->Const
.ShaderCompilerOptions
[i
],
3451 ctx
->Const
.NativeIntegers
))
3454 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
3457 /* Validation for special cases where we allow sampler array indexing
3458 * with loop induction variable. This check emits a warning or error
3459 * depending if backend can handle dynamic indexing.
3461 if ((!prog
->IsES
&& prog
->Version
< 130) ||
3462 (prog
->IsES
&& prog
->Version
< 300)) {
3463 if (!validate_sampler_array_indexing(ctx
, prog
))
3467 /* Check and validate stream emissions in geometry shaders */
3468 validate_geometry_shader_emissions(ctx
, prog
);
3470 /* Mark all generic shader inputs and outputs as unpaired. */
3471 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3472 if (prog
->_LinkedShaders
[i
] != NULL
) {
3473 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
3477 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
,
3478 ctx
->Const
.Program
[MESA_SHADER_VERTEX
].MaxAttribs
)) {
3482 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
3486 unsigned first
, last
;
3488 first
= MESA_SHADER_STAGES
;
3491 /* Determine first and last stage. */
3492 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3493 if (!prog
->_LinkedShaders
[i
])
3495 if (first
== MESA_SHADER_STAGES
)
3500 if (num_tfeedback_decls
!= 0) {
3501 /* From GL_EXT_transform_feedback:
3502 * A program will fail to link if:
3504 * * the <count> specified by TransformFeedbackVaryingsEXT is
3505 * non-zero, but the program object has no vertex or geometry
3508 if (first
== MESA_SHADER_FRAGMENT
) {
3509 linker_error(prog
, "Transform feedback varyings specified, but "
3510 "no vertex or geometry shader is present.\n");
3514 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
3515 prog
->TransformFeedback
.NumVarying
);
3516 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
3517 prog
->TransformFeedback
.VaryingNames
,
3522 /* Linking the stages in the opposite order (from fragment to vertex)
3523 * ensures that inter-shader outputs written to in an earlier stage are
3524 * eliminated if they are (transitively) not used in a later stage.
3528 if (first
< MESA_SHADER_FRAGMENT
) {
3529 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
3531 if (first
== MESA_SHADER_GEOMETRY
) {
3532 /* There was no vertex shader, but we still have to assign varying
3533 * locations for use by geometry shader inputs in SSO.
3535 * If the shader is not separable (i.e., prog->SeparateShader is
3536 * false), linking will have already failed when first is
3537 * MESA_SHADER_GEOMETRY.
3539 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3540 NULL
, prog
->_LinkedShaders
[first
],
3541 num_tfeedback_decls
, tfeedback_decls
))
3545 if (last
!= MESA_SHADER_FRAGMENT
&&
3546 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
3547 /* There was no fragment shader, but we still have to assign varying
3548 * locations for use by transform feedback.
3550 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3552 num_tfeedback_decls
, tfeedback_decls
))
3556 do_dead_builtin_varyings(ctx
, sh
, NULL
,
3557 num_tfeedback_decls
, tfeedback_decls
);
3559 if (!prog
->SeparateShader
)
3560 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
3562 /* Eliminate code that is now dead due to unused outputs being demoted.
3564 while (do_dead_code(sh
->ir
, false))
3567 else if (first
== MESA_SHADER_FRAGMENT
) {
3568 /* If the program only contains a fragment shader...
3570 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
3572 do_dead_builtin_varyings(ctx
, NULL
, sh
,
3573 num_tfeedback_decls
, tfeedback_decls
);
3575 if (prog
->SeparateShader
) {
3576 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3577 NULL
/* producer */,
3579 0 /* num_tfeedback_decls */,
3580 NULL
/* tfeedback_decls */))
3583 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
3585 while (do_dead_code(sh
->ir
, false))
3590 for (int i
= next
- 1; i
>= 0; i
--) {
3591 if (prog
->_LinkedShaders
[i
] == NULL
)
3594 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
3595 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
3597 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
3598 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3602 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
3603 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3606 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
3607 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
3609 /* Eliminate code that is now dead due to unused outputs being demoted.
3611 while (do_dead_code(sh_i
->ir
, false))
3613 while (do_dead_code(sh_next
->ir
, false))
3616 /* This must be done after all dead varyings are eliminated. */
3617 if (!check_against_output_limit(ctx
, prog
, sh_i
))
3619 if (!check_against_input_limit(ctx
, prog
, sh_next
))
3625 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
3628 update_array_sizes(prog
);
3629 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
);
3630 link_assign_atomic_counter_resources(ctx
, prog
);
3631 store_fragdepth_layout(prog
);
3633 check_resources(ctx
, prog
);
3634 check_image_resources(ctx
, prog
);
3635 link_check_atomic_counter_resources(ctx
, prog
);
3637 if (!prog
->LinkStatus
)
3640 /* OpenGL ES requires that a vertex shader and a fragment shader both be
3641 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
3642 * anything about shader linking when one of the shaders (vertex or
3643 * fragment shader) is absent. So, the extension shouldn't change the
3644 * behavior specified in GLSL specification.
3646 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
) {
3647 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
3648 linker_error(prog
, "program lacks a vertex shader\n");
3649 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3650 linker_error(prog
, "program lacks a fragment shader\n");
3654 /* FINISHME: Assign fragment shader output locations. */
3657 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3658 free(shader_list
[i
]);
3659 if (prog
->_LinkedShaders
[i
] == NULL
)
3662 /* Do a final validation step to make sure that the IR wasn't
3663 * invalidated by any modifications performed after intrastage linking.
3665 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
3667 /* Retain any live IR, but trash the rest. */
3668 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
3670 /* The symbol table in the linked shaders may contain references to
3671 * variables that were removed (e.g., unused uniforms). Since it may
3672 * contain junk, there is no possible valid use. Delete it and set the
3675 delete prog
->_LinkedShaders
[i
]->symbols
;
3676 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
3679 ralloc_free(mem_ctx
);