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
*)
323 after_return
= false;
324 return visit_continue
;
327 virtual ir_visitor_status
visit_leave(ir_return
*)
330 return visit_continue
;
333 virtual ir_visitor_status
visit_enter(ir_if
*)
336 return visit_continue
;
339 virtual ir_visitor_status
visit_leave(ir_if
*)
342 return visit_continue
;
345 virtual ir_visitor_status
visit_enter(ir_loop
*)
348 return visit_continue
;
351 virtual ir_visitor_status
visit_leave(ir_loop
*)
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 if ((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 !existing
->data
.from_ssbo_unsized_array
) {
897 linker_error(prog
, "%s `%s' declared as type "
898 "`%s' but outermost dimension has an index"
901 var
->name
, existing
->type
->name
,
902 var
->data
.max_array_access
);
907 /* The arrays of structs could have different glsl_type pointers but
908 * they are actually the same type. Use record_compare() to check that.
910 if (existing
->type
->fields
.array
->is_record() &&
911 var
->type
->fields
.array
->is_record() &&
912 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
921 * Perform validation of global variables used across multiple shaders
924 cross_validate_globals(struct gl_shader_program
*prog
,
925 struct gl_shader
**shader_list
,
926 unsigned num_shaders
,
929 /* Examine all of the uniforms in all of the shaders and cross validate
932 glsl_symbol_table variables
;
933 for (unsigned i
= 0; i
< num_shaders
; i
++) {
934 if (shader_list
[i
] == NULL
)
937 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
938 ir_variable
*const var
= node
->as_variable();
943 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
946 /* don't cross validate subroutine uniforms */
947 if (var
->type
->contains_subroutine())
950 /* Don't cross validate temporaries that are at global scope. These
951 * will eventually get pulled into the shaders 'main'.
953 if (var
->data
.mode
== ir_var_temporary
)
956 /* If a global with this name has already been seen, verify that the
957 * new instance has the same type. In addition, if the globals have
958 * initializers, the values of the initializers must be the same.
960 ir_variable
*const existing
= variables
.get_variable(var
->name
);
961 if (existing
!= NULL
) {
962 /* Check if types match. Interface blocks have some special
963 * rules so we handle those elsewhere.
965 if (var
->type
!= existing
->type
&&
966 !var
->is_interface_instance()) {
967 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
968 if (var
->type
->is_record() && existing
->type
->is_record()
969 && existing
->type
->record_compare(var
->type
)) {
970 existing
->type
= var
->type
;
972 /* If it is an unsized array in a Shader Storage Block,
973 * two different shaders can access to different elements.
974 * Because of that, they might be converted to different
975 * sized arrays, then check that they are compatible but
976 * ignore the array size.
978 if (!(var
->data
.mode
== ir_var_shader_storage
&&
979 var
->data
.from_ssbo_unsized_array
&&
980 existing
->data
.mode
== ir_var_shader_storage
&&
981 existing
->data
.from_ssbo_unsized_array
&&
982 var
->type
->gl_type
== existing
->type
->gl_type
)) {
983 linker_error(prog
, "%s `%s' declared as type "
984 "`%s' and type `%s'\n",
986 var
->name
, var
->type
->name
,
987 existing
->type
->name
);
994 if (var
->data
.explicit_location
) {
995 if (existing
->data
.explicit_location
996 && (var
->data
.location
!= existing
->data
.location
)) {
997 linker_error(prog
, "explicit locations for %s "
998 "`%s' have differing values\n",
999 mode_string(var
), var
->name
);
1003 existing
->data
.location
= var
->data
.location
;
1004 existing
->data
.explicit_location
= true;
1007 /* From the GLSL 4.20 specification:
1008 * "A link error will result if two compilation units in a program
1009 * specify different integer-constant bindings for the same
1010 * opaque-uniform name. However, it is not an error to specify a
1011 * binding on some but not all declarations for the same name"
1013 if (var
->data
.explicit_binding
) {
1014 if (existing
->data
.explicit_binding
&&
1015 var
->data
.binding
!= existing
->data
.binding
) {
1016 linker_error(prog
, "explicit bindings for %s "
1017 "`%s' have differing values\n",
1018 mode_string(var
), var
->name
);
1022 existing
->data
.binding
= var
->data
.binding
;
1023 existing
->data
.explicit_binding
= true;
1026 if (var
->type
->contains_atomic() &&
1027 var
->data
.atomic
.offset
!= existing
->data
.atomic
.offset
) {
1028 linker_error(prog
, "offset specifications for %s "
1029 "`%s' have differing values\n",
1030 mode_string(var
), var
->name
);
1034 /* Validate layout qualifiers for gl_FragDepth.
1036 * From the AMD/ARB_conservative_depth specs:
1038 * "If gl_FragDepth is redeclared in any fragment shader in a
1039 * program, it must be redeclared in all fragment shaders in
1040 * that program that have static assignments to
1041 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1042 * fragment shaders in a single program must have the same set
1045 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1046 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1047 bool layout_differs
=
1048 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1050 if (layout_declared
&& layout_differs
) {
1052 "All redeclarations of gl_FragDepth in all "
1053 "fragment shaders in a single program must have "
1054 "the same set of qualifiers.\n");
1057 if (var
->data
.used
&& layout_differs
) {
1059 "If gl_FragDepth is redeclared with a layout "
1060 "qualifier in any fragment shader, it must be "
1061 "redeclared with the same layout qualifier in "
1062 "all fragment shaders that have assignments to "
1067 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1069 * "If a shared global has multiple initializers, the
1070 * initializers must all be constant expressions, and they
1071 * must all have the same value. Otherwise, a link error will
1072 * result. (A shared global having only one initializer does
1073 * not require that initializer to be a constant expression.)"
1075 * Previous to 4.20 the GLSL spec simply said that initializers
1076 * must have the same value. In this case of non-constant
1077 * initializers, this was impossible to determine. As a result,
1078 * no vendor actually implemented that behavior. The 4.20
1079 * behavior matches the implemented behavior of at least one other
1080 * vendor, so we'll implement that for all GLSL versions.
1082 if (var
->constant_initializer
!= NULL
) {
1083 if (existing
->constant_initializer
!= NULL
) {
1084 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1085 linker_error(prog
, "initializers for %s "
1086 "`%s' have differing values\n",
1087 mode_string(var
), var
->name
);
1091 /* If the first-seen instance of a particular uniform did not
1092 * have an initializer but a later instance does, copy the
1093 * initializer to the version stored in the symbol table.
1095 /* FINISHME: This is wrong. The constant_value field should
1096 * FINISHME: not be modified! Imagine a case where a shader
1097 * FINISHME: without an initializer is linked in two different
1098 * FINISHME: programs with shaders that have differing
1099 * FINISHME: initializers. Linking with the first will
1100 * FINISHME: modify the shader, and linking with the second
1101 * FINISHME: will fail.
1103 existing
->constant_initializer
=
1104 var
->constant_initializer
->clone(ralloc_parent(existing
),
1109 if (var
->data
.has_initializer
) {
1110 if (existing
->data
.has_initializer
1111 && (var
->constant_initializer
== NULL
1112 || existing
->constant_initializer
== NULL
)) {
1114 "shared global variable `%s' has multiple "
1115 "non-constant initializers.\n",
1120 /* Some instance had an initializer, so keep track of that. In
1121 * this location, all sorts of initializers (constant or
1122 * otherwise) will propagate the existence to the variable
1123 * stored in the symbol table.
1125 existing
->data
.has_initializer
= true;
1128 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1129 linker_error(prog
, "declarations for %s `%s' have "
1130 "mismatching invariant qualifiers\n",
1131 mode_string(var
), var
->name
);
1134 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1135 linker_error(prog
, "declarations for %s `%s' have "
1136 "mismatching centroid qualifiers\n",
1137 mode_string(var
), var
->name
);
1140 if (existing
->data
.sample
!= var
->data
.sample
) {
1141 linker_error(prog
, "declarations for %s `%s` have "
1142 "mismatching sample qualifiers\n",
1143 mode_string(var
), var
->name
);
1147 variables
.add_variable(var
);
1154 * Perform validation of uniforms used across multiple shader stages
1157 cross_validate_uniforms(struct gl_shader_program
*prog
)
1159 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1160 MESA_SHADER_STAGES
, true);
1164 * Accumulates the array of prog->UniformBlocks and checks that all
1165 * definitons of blocks agree on their contents.
1168 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
1170 unsigned max_num_uniform_blocks
= 0;
1171 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1172 if (prog
->_LinkedShaders
[i
])
1173 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1176 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1177 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1179 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
1180 max_num_uniform_blocks
);
1181 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
1182 prog
->UniformBlockStageIndex
[i
][j
] = -1;
1187 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
1188 int index
= link_cross_validate_uniform_block(prog
,
1189 &prog
->UniformBlocks
,
1190 &prog
->NumBufferInterfaceBlocks
,
1191 &sh
->UniformBlocks
[j
]);
1194 linker_error(prog
, "uniform block `%s' has mismatching definitions\n",
1195 sh
->UniformBlocks
[j
].Name
);
1199 prog
->UniformBlockStageIndex
[i
][index
] = j
;
1208 * Populates a shaders symbol table with all global declarations
1211 populate_symbol_table(gl_shader
*sh
)
1213 sh
->symbols
= new(sh
) glsl_symbol_table
;
1215 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1219 if ((func
= inst
->as_function()) != NULL
) {
1220 sh
->symbols
->add_function(func
);
1221 } else if ((var
= inst
->as_variable()) != NULL
) {
1222 if (var
->data
.mode
!= ir_var_temporary
)
1223 sh
->symbols
->add_variable(var
);
1230 * Remap variables referenced in an instruction tree
1232 * This is used when instruction trees are cloned from one shader and placed in
1233 * another. These trees will contain references to \c ir_variable nodes that
1234 * do not exist in the target shader. This function finds these \c ir_variable
1235 * references and replaces the references with matching variables in the target
1238 * If there is no matching variable in the target shader, a clone of the
1239 * \c ir_variable is made and added to the target shader. The new variable is
1240 * added to \b both the instruction stream and the symbol table.
1242 * \param inst IR tree that is to be processed.
1243 * \param symbols Symbol table containing global scope symbols in the
1245 * \param instructions Instruction stream where new variable declarations
1249 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1252 class remap_visitor
: public ir_hierarchical_visitor
{
1254 remap_visitor(struct gl_shader
*target
,
1257 this->target
= target
;
1258 this->symbols
= target
->symbols
;
1259 this->instructions
= target
->ir
;
1260 this->temps
= temps
;
1263 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1265 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1266 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1268 assert(var
!= NULL
);
1270 return visit_continue
;
1273 ir_variable
*const existing
=
1274 this->symbols
->get_variable(ir
->var
->name
);
1275 if (existing
!= NULL
)
1278 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1280 this->symbols
->add_variable(copy
);
1281 this->instructions
->push_head(copy
);
1285 return visit_continue
;
1289 struct gl_shader
*target
;
1290 glsl_symbol_table
*symbols
;
1291 exec_list
*instructions
;
1295 remap_visitor
v(target
, temps
);
1302 * Move non-declarations from one instruction stream to another
1304 * The intended usage pattern of this function is to pass the pointer to the
1305 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1306 * pointer) for \c last and \c false for \c make_copies on the first
1307 * call. Successive calls pass the return value of the previous call for
1308 * \c last and \c true for \c make_copies.
1310 * \param instructions Source instruction stream
1311 * \param last Instruction after which new instructions should be
1312 * inserted in the target instruction stream
1313 * \param make_copies Flag selecting whether instructions in \c instructions
1314 * should be copied (via \c ir_instruction::clone) into the
1315 * target list or moved.
1318 * The new "last" instruction in the target instruction stream. This pointer
1319 * is suitable for use as the \c last parameter of a later call to this
1323 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1324 bool make_copies
, gl_shader
*target
)
1326 hash_table
*temps
= NULL
;
1329 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1330 hash_table_pointer_compare
);
1332 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1333 if (inst
->as_function())
1336 ir_variable
*var
= inst
->as_variable();
1337 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1340 assert(inst
->as_assignment()
1342 || inst
->as_if() /* for initializers with the ?: operator */
1343 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1346 inst
= inst
->clone(target
, NULL
);
1349 hash_table_insert(temps
, inst
, var
);
1351 remap_variables(inst
, target
, temps
);
1356 last
->insert_after(inst
);
1361 hash_table_dtor(temps
);
1368 * This class is only used in link_intrastage_shaders() below but declaring
1369 * it inside that function leads to compiler warnings with some versions of
1372 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1374 array_sizing_visitor()
1375 : mem_ctx(ralloc_context(NULL
)),
1376 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1377 hash_table_pointer_compare
))
1381 ~array_sizing_visitor()
1383 hash_table_dtor(this->unnamed_interfaces
);
1384 ralloc_free(this->mem_ctx
);
1387 virtual ir_visitor_status
visit(ir_variable
*var
)
1389 fixup_type(&var
->type
, var
->data
.max_array_access
,
1390 var
->data
.from_ssbo_unsized_array
);
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
->is_in_shader_storage_block());
1397 var
->type
= new_type
;
1398 var
->change_interface_type(new_type
);
1400 } else if (var
->type
->is_array() &&
1401 var
->type
->fields
.array
->is_interface()) {
1402 if (interface_contains_unsized_arrays(var
->type
->fields
.array
)) {
1403 const glsl_type
*new_type
=
1404 resize_interface_members(var
->type
->fields
.array
,
1405 var
->get_max_ifc_array_access(),
1406 var
->is_in_shader_storage_block());
1407 var
->change_interface_type(new_type
);
1408 var
->type
= update_interface_members_array(var
->type
, new_type
);
1410 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1411 /* Store a pointer to the variable in the unnamed_interfaces
1414 ir_variable
**interface_vars
= (ir_variable
**)
1415 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1416 if (interface_vars
== NULL
) {
1417 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1419 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1422 unsigned index
= ifc_type
->field_index(var
->name
);
1423 assert(index
< ifc_type
->length
);
1424 assert(interface_vars
[index
] == NULL
);
1425 interface_vars
[index
] = var
;
1427 return visit_continue
;
1431 * For each unnamed interface block that was discovered while running the
1432 * visitor, adjust the interface type to reflect the newly assigned array
1433 * sizes, and fix up the ir_variable nodes to point to the new interface
1436 void fixup_unnamed_interface_types()
1438 hash_table_call_foreach(this->unnamed_interfaces
,
1439 fixup_unnamed_interface_type
, NULL
);
1444 * If the type pointed to by \c type represents an unsized array, replace
1445 * it with a sized array whose size is determined by max_array_access.
1447 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1448 bool from_ssbo_unsized_array
)
1450 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1451 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1452 max_array_access
+ 1);
1453 assert(*type
!= NULL
);
1457 static const glsl_type
*
1458 update_interface_members_array(const glsl_type
*type
,
1459 const glsl_type
*new_interface_type
)
1461 const glsl_type
*element_type
= type
->fields
.array
;
1462 if (element_type
->is_array()) {
1463 const glsl_type
*new_array_type
=
1464 update_interface_members_array(element_type
, new_interface_type
);
1465 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1467 return glsl_type::get_array_instance(new_interface_type
,
1473 * Determine whether the given interface type contains unsized arrays (if
1474 * it doesn't, array_sizing_visitor doesn't need to process it).
1476 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1478 for (unsigned i
= 0; i
< type
->length
; i
++) {
1479 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1480 if (elem_type
->is_unsized_array())
1487 * Create a new interface type based on the given type, with unsized arrays
1488 * replaced by sized arrays whose size is determined by
1489 * max_ifc_array_access.
1491 static const glsl_type
*
1492 resize_interface_members(const glsl_type
*type
,
1493 const unsigned *max_ifc_array_access
,
1496 unsigned num_fields
= type
->length
;
1497 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1498 memcpy(fields
, type
->fields
.structure
,
1499 num_fields
* sizeof(*fields
));
1500 for (unsigned i
= 0; i
< num_fields
; i
++) {
1501 /* If SSBO last member is unsized array, we don't replace it by a sized
1504 if (is_ssbo
&& i
== (num_fields
- 1))
1505 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1508 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1511 glsl_interface_packing packing
=
1512 (glsl_interface_packing
) type
->interface_packing
;
1513 const glsl_type
*new_ifc_type
=
1514 glsl_type::get_interface_instance(fields
, num_fields
,
1515 packing
, type
->name
);
1517 return new_ifc_type
;
1520 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1523 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1524 ir_variable
**interface_vars
= (ir_variable
**) data
;
1525 unsigned num_fields
= ifc_type
->length
;
1526 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1527 memcpy(fields
, ifc_type
->fields
.structure
,
1528 num_fields
* sizeof(*fields
));
1529 bool interface_type_changed
= false;
1530 for (unsigned i
= 0; i
< num_fields
; i
++) {
1531 if (interface_vars
[i
] != NULL
&&
1532 fields
[i
].type
!= interface_vars
[i
]->type
) {
1533 fields
[i
].type
= interface_vars
[i
]->type
;
1534 interface_type_changed
= true;
1537 if (!interface_type_changed
) {
1541 glsl_interface_packing packing
=
1542 (glsl_interface_packing
) ifc_type
->interface_packing
;
1543 const glsl_type
*new_ifc_type
=
1544 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1547 for (unsigned i
= 0; i
< num_fields
; i
++) {
1548 if (interface_vars
[i
] != NULL
)
1549 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1554 * Memory context used to allocate the data in \c unnamed_interfaces.
1559 * Hash table from const glsl_type * to an array of ir_variable *'s
1560 * pointing to the ir_variables constituting each unnamed interface block.
1562 hash_table
*unnamed_interfaces
;
1567 * Performs the cross-validation of tessellation control shader vertices and
1568 * layout qualifiers for the attached tessellation control shaders,
1569 * and propagates them to the linked TCS and linked shader program.
1572 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1573 struct gl_shader
*linked_shader
,
1574 struct gl_shader
**shader_list
,
1575 unsigned num_shaders
)
1577 linked_shader
->TessCtrl
.VerticesOut
= 0;
1579 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1582 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1584 * "All tessellation control shader layout declarations in a program
1585 * must specify the same output patch vertex count. There must be at
1586 * least one layout qualifier specifying an output patch vertex count
1587 * in any program containing tessellation control shaders; however,
1588 * such a declaration is not required in all tessellation control
1592 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1593 struct gl_shader
*shader
= shader_list
[i
];
1595 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1596 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1597 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1598 linker_error(prog
, "tessellation control shader defined with "
1599 "conflicting output vertex count (%d and %d)\n",
1600 linked_shader
->TessCtrl
.VerticesOut
,
1601 shader
->TessCtrl
.VerticesOut
);
1604 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1608 /* Just do the intrastage -> interstage propagation right now,
1609 * since we already know we're in the right type of shader program
1612 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1613 linker_error(prog
, "tessellation control shader didn't declare "
1614 "vertices out layout qualifier\n");
1617 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1622 * Performs the cross-validation of tessellation evaluation shader
1623 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1624 * for the attached tessellation evaluation shaders, and propagates them
1625 * to the linked TES and linked shader program.
1628 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1629 struct gl_shader
*linked_shader
,
1630 struct gl_shader
**shader_list
,
1631 unsigned num_shaders
)
1633 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1634 linked_shader
->TessEval
.Spacing
= 0;
1635 linked_shader
->TessEval
.VertexOrder
= 0;
1636 linked_shader
->TessEval
.PointMode
= -1;
1638 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1641 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1643 * "At least one tessellation evaluation shader (compilation unit) in
1644 * a program must declare a primitive mode in its input layout.
1645 * Declaration vertex spacing, ordering, and point mode identifiers is
1646 * optional. It is not required that all tessellation evaluation
1647 * shaders in a program declare a primitive mode. If spacing or
1648 * vertex ordering declarations are omitted, the tessellation
1649 * primitive generator will use equal spacing or counter-clockwise
1650 * vertex ordering, respectively. If a point mode declaration is
1651 * omitted, the tessellation primitive generator will produce lines or
1652 * triangles according to the primitive mode."
1655 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1656 struct gl_shader
*shader
= shader_list
[i
];
1658 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1659 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1660 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1661 linker_error(prog
, "tessellation evaluation shader defined with "
1662 "conflicting input primitive modes.\n");
1665 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1668 if (shader
->TessEval
.Spacing
!= 0) {
1669 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1670 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1671 linker_error(prog
, "tessellation evaluation shader defined with "
1672 "conflicting vertex spacing.\n");
1675 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1678 if (shader
->TessEval
.VertexOrder
!= 0) {
1679 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1680 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1681 linker_error(prog
, "tessellation evaluation shader defined with "
1682 "conflicting ordering.\n");
1685 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1688 if (shader
->TessEval
.PointMode
!= -1) {
1689 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1690 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1691 linker_error(prog
, "tessellation evaluation shader defined with "
1692 "conflicting point modes.\n");
1695 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1700 /* Just do the intrastage -> interstage propagation right now,
1701 * since we already know we're in the right type of shader program
1704 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1706 "tessellation evaluation shader didn't declare input "
1707 "primitive modes.\n");
1710 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1712 if (linked_shader
->TessEval
.Spacing
== 0)
1713 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1714 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1716 if (linked_shader
->TessEval
.VertexOrder
== 0)
1717 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1718 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1720 if (linked_shader
->TessEval
.PointMode
== -1)
1721 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1722 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1727 * Performs the cross-validation of layout qualifiers specified in
1728 * redeclaration of gl_FragCoord for the attached fragment shaders,
1729 * and propagates them to the linked FS and linked shader program.
1732 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1733 struct gl_shader
*linked_shader
,
1734 struct gl_shader
**shader_list
,
1735 unsigned num_shaders
)
1737 linked_shader
->redeclares_gl_fragcoord
= false;
1738 linked_shader
->uses_gl_fragcoord
= false;
1739 linked_shader
->origin_upper_left
= false;
1740 linked_shader
->pixel_center_integer
= false;
1742 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1743 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1746 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1747 struct gl_shader
*shader
= shader_list
[i
];
1748 /* From the GLSL 1.50 spec, page 39:
1750 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1751 * it must be redeclared in all the fragment shaders in that program
1752 * that have a static use gl_FragCoord."
1754 if ((linked_shader
->redeclares_gl_fragcoord
1755 && !shader
->redeclares_gl_fragcoord
1756 && shader
->uses_gl_fragcoord
)
1757 || (shader
->redeclares_gl_fragcoord
1758 && !linked_shader
->redeclares_gl_fragcoord
1759 && linked_shader
->uses_gl_fragcoord
)) {
1760 linker_error(prog
, "fragment shader defined with conflicting "
1761 "layout qualifiers for gl_FragCoord\n");
1764 /* From the GLSL 1.50 spec, page 39:
1766 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1767 * single program must have the same set of qualifiers."
1769 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1770 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1771 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1772 linker_error(prog
, "fragment shader defined with conflicting "
1773 "layout qualifiers for gl_FragCoord\n");
1776 /* Update the linked shader state. Note that uses_gl_fragcoord should
1777 * accumulate the results. The other values should replace. If there
1778 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1779 * are already known to be the same.
1781 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1782 linked_shader
->redeclares_gl_fragcoord
=
1783 shader
->redeclares_gl_fragcoord
;
1784 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1785 || shader
->uses_gl_fragcoord
;
1786 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1787 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1790 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1795 * Performs the cross-validation of geometry shader max_vertices and
1796 * primitive type layout qualifiers for the attached geometry shaders,
1797 * and propagates them to the linked GS and linked shader program.
1800 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1801 struct gl_shader
*linked_shader
,
1802 struct gl_shader
**shader_list
,
1803 unsigned num_shaders
)
1805 linked_shader
->Geom
.VerticesOut
= 0;
1806 linked_shader
->Geom
.Invocations
= 0;
1807 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1808 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1810 /* No in/out qualifiers defined for anything but GLSL 1.50+
1811 * geometry shaders so far.
1813 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1816 /* From the GLSL 1.50 spec, page 46:
1818 * "All geometry shader output layout declarations in a program
1819 * must declare the same layout and same value for
1820 * max_vertices. There must be at least one geometry output
1821 * layout declaration somewhere in a program, but not all
1822 * geometry shaders (compilation units) are required to
1826 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1827 struct gl_shader
*shader
= shader_list
[i
];
1829 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1830 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1831 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1832 linker_error(prog
, "geometry shader defined with conflicting "
1836 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1839 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1840 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1841 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1842 linker_error(prog
, "geometry shader defined with conflicting "
1846 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1849 if (shader
->Geom
.VerticesOut
!= 0) {
1850 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1851 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1852 linker_error(prog
, "geometry shader defined with conflicting "
1853 "output vertex count (%d and %d)\n",
1854 linked_shader
->Geom
.VerticesOut
,
1855 shader
->Geom
.VerticesOut
);
1858 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1861 if (shader
->Geom
.Invocations
!= 0) {
1862 if (linked_shader
->Geom
.Invocations
!= 0 &&
1863 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1864 linker_error(prog
, "geometry shader defined with conflicting "
1865 "invocation count (%d and %d)\n",
1866 linked_shader
->Geom
.Invocations
,
1867 shader
->Geom
.Invocations
);
1870 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1874 /* Just do the intrastage -> interstage propagation right now,
1875 * since we already know we're in the right type of shader program
1878 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1880 "geometry shader didn't declare primitive input type\n");
1883 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1885 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1887 "geometry shader didn't declare primitive output type\n");
1890 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1892 if (linked_shader
->Geom
.VerticesOut
== 0) {
1894 "geometry shader didn't declare max_vertices\n");
1897 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1899 if (linked_shader
->Geom
.Invocations
== 0)
1900 linked_shader
->Geom
.Invocations
= 1;
1902 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1907 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1908 * qualifiers for the attached compute shaders, and propagate them to the
1909 * linked CS and linked shader program.
1912 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1913 struct gl_shader
*linked_shader
,
1914 struct gl_shader
**shader_list
,
1915 unsigned num_shaders
)
1917 for (int i
= 0; i
< 3; i
++)
1918 linked_shader
->Comp
.LocalSize
[i
] = 0;
1920 /* This function is called for all shader stages, but it only has an effect
1921 * for compute shaders.
1923 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
1926 /* From the ARB_compute_shader spec, in the section describing local size
1929 * If multiple compute shaders attached to a single program object
1930 * declare local work-group size, the declarations must be identical;
1931 * otherwise a link-time error results. Furthermore, if a program
1932 * object contains any compute shaders, at least one must contain an
1933 * input layout qualifier specifying the local work sizes of the
1934 * program, or a link-time error will occur.
1936 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
1937 struct gl_shader
*shader
= shader_list
[sh
];
1939 if (shader
->Comp
.LocalSize
[0] != 0) {
1940 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
1941 for (int i
= 0; i
< 3; i
++) {
1942 if (linked_shader
->Comp
.LocalSize
[i
] !=
1943 shader
->Comp
.LocalSize
[i
]) {
1944 linker_error(prog
, "compute shader defined with conflicting "
1950 for (int i
= 0; i
< 3; i
++)
1951 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
1955 /* Just do the intrastage -> interstage propagation right now,
1956 * since we already know we're in the right type of shader program
1959 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
1960 linker_error(prog
, "compute shader didn't declare local size\n");
1963 for (int i
= 0; i
< 3; i
++)
1964 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
1969 * Combine a group of shaders for a single stage to generate a linked shader
1972 * If this function is supplied a single shader, it is cloned, and the new
1973 * shader is returned.
1975 static struct gl_shader
*
1976 link_intrastage_shaders(void *mem_ctx
,
1977 struct gl_context
*ctx
,
1978 struct gl_shader_program
*prog
,
1979 struct gl_shader
**shader_list
,
1980 unsigned num_shaders
)
1982 struct gl_uniform_block
*uniform_blocks
= NULL
;
1984 /* Check that global variables defined in multiple shaders are consistent.
1986 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1987 if (!prog
->LinkStatus
)
1990 /* Check that interface blocks defined in multiple shaders are consistent.
1992 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1994 if (!prog
->LinkStatus
)
1997 /* Link up uniform blocks defined within this stage. */
1998 const unsigned num_uniform_blocks
=
1999 link_uniform_blocks(mem_ctx
, ctx
, prog
, shader_list
, num_shaders
,
2001 if (!prog
->LinkStatus
)
2004 /* Check that there is only a single definition of each function signature
2005 * across all shaders.
2007 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2008 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2009 ir_function
*const f
= node
->as_function();
2014 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2015 ir_function
*const other
=
2016 shader_list
[j
]->symbols
->get_function(f
->name
);
2018 /* If the other shader has no function (and therefore no function
2019 * signatures) with the same name, skip to the next shader.
2024 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2025 if (!sig
->is_defined
|| sig
->is_builtin())
2028 ir_function_signature
*other_sig
=
2029 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2031 if ((other_sig
!= NULL
) && other_sig
->is_defined
2032 && !other_sig
->is_builtin()) {
2033 linker_error(prog
, "function `%s' is multiply defined\n",
2042 /* Find the shader that defines main, and make a clone of it.
2044 * Starting with the clone, search for undefined references. If one is
2045 * found, find the shader that defines it. Clone the reference and add
2046 * it to the shader. Repeat until there are no undefined references or
2047 * until a reference cannot be resolved.
2049 gl_shader
*main
= NULL
;
2050 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2051 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2052 main
= shader_list
[i
];
2058 linker_error(prog
, "%s shader lacks `main'\n",
2059 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2063 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2064 linked
->ir
= new(linked
) exec_list
;
2065 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2067 linked
->UniformBlocks
= uniform_blocks
;
2068 linked
->NumUniformBlocks
= num_uniform_blocks
;
2069 ralloc_steal(linked
, linked
->UniformBlocks
);
2071 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2072 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2073 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2074 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2075 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2077 populate_symbol_table(linked
);
2079 /* The pointer to the main function in the final linked shader (i.e., the
2080 * copy of the original shader that contained the main function).
2082 ir_function_signature
*const main_sig
=
2083 _mesa_get_main_function_signature(linked
);
2085 /* Move any instructions other than variable declarations or function
2086 * declarations into main.
2088 exec_node
*insertion_point
=
2089 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2092 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2093 if (shader_list
[i
] == main
)
2096 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2097 insertion_point
, true, linked
);
2100 /* Check if any shader needs built-in functions. */
2101 bool need_builtins
= false;
2102 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2103 if (shader_list
[i
]->uses_builtin_functions
) {
2104 need_builtins
= true;
2110 if (need_builtins
) {
2111 /* Make a temporary array one larger than shader_list, which will hold
2112 * the built-in function shader as well.
2114 gl_shader
**linking_shaders
= (gl_shader
**)
2115 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2117 ok
= linking_shaders
!= NULL
;
2120 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2121 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2123 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2125 free(linking_shaders
);
2127 _mesa_error_no_memory(__func__
);
2130 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2135 ctx
->Driver
.DeleteShader(ctx
, linked
);
2139 /* At this point linked should contain all of the linked IR, so
2140 * validate it to make sure nothing went wrong.
2142 validate_ir_tree(linked
->ir
);
2144 /* Set the size of geometry shader input arrays */
2145 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2146 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2147 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2148 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2149 ir
->accept(&input_resize_visitor
);
2153 if (ctx
->Const
.VertexID_is_zero_based
)
2154 lower_vertex_id(linked
);
2156 /* Validate correct usage of barrier() in the tess control shader */
2157 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2158 barrier_use_visitor
visitor(prog
);
2159 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2160 ir
->accept(&visitor
);
2164 /* Make a pass over all variable declarations to ensure that arrays with
2165 * unspecified sizes have a size specified. The size is inferred from the
2166 * max_array_access field.
2168 array_sizing_visitor v
;
2170 v
.fixup_unnamed_interface_types();
2176 * Update the sizes of linked shader uniform arrays to the maximum
2179 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2181 * If one or more elements of an array are active,
2182 * GetActiveUniform will return the name of the array in name,
2183 * subject to the restrictions listed above. The type of the array
2184 * is returned in type. The size parameter contains the highest
2185 * array element index used, plus one. The compiler or linker
2186 * determines the highest index used. There will be only one
2187 * active uniform reported by the GL per uniform array.
2191 update_array_sizes(struct gl_shader_program
*prog
)
2193 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2194 if (prog
->_LinkedShaders
[i
] == NULL
)
2197 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2198 ir_variable
*const var
= node
->as_variable();
2200 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2201 !var
->type
->is_array())
2204 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2205 * will not be eliminated. Since we always do std140, just
2206 * don't resize arrays in UBOs.
2208 * Atomic counters are supposed to get deterministic
2209 * locations assigned based on the declaration ordering and
2210 * sizes, array compaction would mess that up.
2212 * Subroutine uniforms are not removed.
2214 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2215 var
->type
->contains_subroutine())
2218 unsigned int size
= var
->data
.max_array_access
;
2219 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2220 if (prog
->_LinkedShaders
[j
] == NULL
)
2223 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2224 ir_variable
*other_var
= node2
->as_variable();
2228 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2229 other_var
->data
.max_array_access
> size
) {
2230 size
= other_var
->data
.max_array_access
;
2235 if (size
+ 1 != var
->type
->length
) {
2236 /* If this is a built-in uniform (i.e., it's backed by some
2237 * fixed-function state), adjust the number of state slots to
2238 * match the new array size. The number of slots per array entry
2239 * is not known. It seems safe to assume that the total number of
2240 * slots is an integer multiple of the number of array elements.
2241 * Determine the number of slots per array element by dividing by
2242 * the old (total) size.
2244 const unsigned num_slots
= var
->get_num_state_slots();
2245 if (num_slots
> 0) {
2246 var
->set_num_state_slots((size
+ 1)
2247 * (num_slots
/ var
->type
->length
));
2250 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2252 /* FINISHME: We should update the types of array
2253 * dereferences of this variable now.
2261 * Resize tessellation evaluation per-vertex inputs to the size of
2262 * tessellation control per-vertex outputs.
2265 resize_tes_inputs(struct gl_context
*ctx
,
2266 struct gl_shader_program
*prog
)
2268 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2271 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2272 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2274 /* If no control shader is present, then the TES inputs are statically
2275 * sized to MaxPatchVertices; the actual size of the arrays won't be
2276 * known until draw time.
2278 const int num_vertices
= tcs
2279 ? tcs
->TessCtrl
.VerticesOut
2280 : ctx
->Const
.MaxPatchVertices
;
2282 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2283 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2284 ir
->accept(&input_resize_visitor
);
2289 * Find a contiguous set of available bits in a bitmask.
2291 * \param used_mask Bits representing used (1) and unused (0) locations
2292 * \param needed_count Number of contiguous bits needed.
2295 * Base location of the available bits on success or -1 on failure.
2298 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2300 unsigned needed_mask
= (1 << needed_count
) - 1;
2301 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2303 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2304 * cannot optimize possibly infinite loops" for the loop below.
2306 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2309 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2310 if ((needed_mask
& ~used_mask
) == needed_mask
)
2321 * Assign locations for either VS inputs or FS outputs
2323 * \param prog Shader program whose variables need locations assigned
2324 * \param constants Driver specific constant values for the program.
2325 * \param target_index Selector for the program target to receive location
2326 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2327 * \c MESA_SHADER_FRAGMENT.
2330 * If locations are successfully assigned, true is returned. Otherwise an
2331 * error is emitted to the shader link log and false is returned.
2334 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2335 struct gl_constants
*constants
,
2336 unsigned target_index
)
2338 /* Maximum number of generic locations. This corresponds to either the
2339 * maximum number of draw buffers or the maximum number of generic
2342 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2343 constants
->Program
[target_index
].MaxAttribs
:
2344 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2346 /* Mark invalid locations as being used.
2348 unsigned used_locations
= (max_index
>= 32)
2349 ? ~0 : ~((1 << max_index
) - 1);
2350 unsigned double_storage_locations
= 0;
2352 assert((target_index
== MESA_SHADER_VERTEX
)
2353 || (target_index
== MESA_SHADER_FRAGMENT
));
2355 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2359 /* Operate in a total of four passes.
2361 * 1. Invalidate the location assignments for all vertex shader inputs.
2363 * 2. Assign locations for inputs that have user-defined (via
2364 * glBindVertexAttribLocation) locations and outputs that have
2365 * user-defined locations (via glBindFragDataLocation).
2367 * 3. Sort the attributes without assigned locations by number of slots
2368 * required in decreasing order. Fragmentation caused by attribute
2369 * locations assigned by the application may prevent large attributes
2370 * from having enough contiguous space.
2372 * 4. Assign locations to any inputs without assigned locations.
2375 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2376 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2378 const enum ir_variable_mode direction
=
2379 (target_index
== MESA_SHADER_VERTEX
)
2380 ? ir_var_shader_in
: ir_var_shader_out
;
2383 /* Temporary storage for the set of attributes that need locations assigned.
2389 /* Used below in the call to qsort. */
2390 static int compare(const void *a
, const void *b
)
2392 const temp_attr
*const l
= (const temp_attr
*) a
;
2393 const temp_attr
*const r
= (const temp_attr
*) b
;
2395 /* Reversed because we want a descending order sort below. */
2396 return r
->slots
- l
->slots
;
2400 unsigned num_attr
= 0;
2402 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2403 ir_variable
*const var
= node
->as_variable();
2405 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2408 if (var
->data
.explicit_location
) {
2409 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2410 || (var
->data
.location
< 0)) {
2412 "invalid explicit location %d specified for `%s'\n",
2413 (var
->data
.location
< 0)
2414 ? var
->data
.location
2415 : var
->data
.location
- generic_base
,
2419 } else if (target_index
== MESA_SHADER_VERTEX
) {
2422 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2423 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2424 var
->data
.location
= binding
;
2425 var
->data
.is_unmatched_generic_inout
= 0;
2427 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2431 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2432 assert(binding
>= FRAG_RESULT_DATA0
);
2433 var
->data
.location
= binding
;
2434 var
->data
.is_unmatched_generic_inout
= 0;
2436 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2437 var
->data
.index
= index
;
2442 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2444 * "Output binding assignments will cause LinkProgram to fail:
2446 * If the program has an active output assigned to a location greater
2447 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2448 * an active output assigned an index greater than or equal to one;"
2450 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2451 var
->data
.location
- generic_base
>=
2452 (int) constants
->MaxDualSourceDrawBuffers
) {
2454 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2455 "with index %u for %s\n",
2456 var
->data
.location
- generic_base
, var
->data
.index
,
2461 const unsigned slots
= var
->type
->count_attribute_slots();
2463 /* If the variable is not a built-in and has a location statically
2464 * assigned in the shader (presumably via a layout qualifier), make sure
2465 * that it doesn't collide with other assigned locations. Otherwise,
2466 * add it to the list of variables that need linker-assigned locations.
2468 if (var
->data
.location
!= -1) {
2469 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2470 /* From page 61 of the OpenGL 4.0 spec:
2472 * "LinkProgram will fail if the attribute bindings assigned
2473 * by BindAttribLocation do not leave not enough space to
2474 * assign a location for an active matrix attribute or an
2475 * active attribute array, both of which require multiple
2476 * contiguous generic attributes."
2478 * I think above text prohibits the aliasing of explicit and
2479 * automatic assignments. But, aliasing is allowed in manual
2480 * assignments of attribute locations. See below comments for
2483 * From OpenGL 4.0 spec, page 61:
2485 * "It is possible for an application to bind more than one
2486 * attribute name to the same location. This is referred to as
2487 * aliasing. This will only work if only one of the aliased
2488 * attributes is active in the executable program, or if no
2489 * path through the shader consumes more than one attribute of
2490 * a set of attributes aliased to the same location. A link
2491 * error can occur if the linker determines that every path
2492 * through the shader consumes multiple aliased attributes,
2493 * but implementations are not required to generate an error
2496 * From GLSL 4.30 spec, page 54:
2498 * "A program will fail to link if any two non-vertex shader
2499 * input variables are assigned to the same location. For
2500 * vertex shaders, multiple input variables may be assigned
2501 * to the same location using either layout qualifiers or via
2502 * the OpenGL API. However, such aliasing is intended only to
2503 * support vertex shaders where each execution path accesses
2504 * at most one input per each location. Implementations are
2505 * permitted, but not required, to generate link-time errors
2506 * if they detect that every path through the vertex shader
2507 * executable accesses multiple inputs assigned to any single
2508 * location. For all shader types, a program will fail to link
2509 * if explicit location assignments leave the linker unable
2510 * to find space for other variables without explicit
2513 * From OpenGL ES 3.0 spec, page 56:
2515 * "Binding more than one attribute name to the same location
2516 * is referred to as aliasing, and is not permitted in OpenGL
2517 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2518 * fail when this condition exists. However, aliasing is
2519 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2520 * This will only work if only one of the aliased attributes
2521 * is active in the executable program, or if no path through
2522 * the shader consumes more than one attribute of a set of
2523 * attributes aliased to the same location. A link error can
2524 * occur if the linker determines that every path through the
2525 * shader consumes multiple aliased attributes, but implemen-
2526 * tations are not required to generate an error in this case."
2528 * After looking at above references from OpenGL, OpenGL ES and
2529 * GLSL specifications, we allow aliasing of vertex input variables
2530 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2532 * NOTE: This is not required by the spec but its worth mentioning
2533 * here that we're not doing anything to make sure that no path
2534 * through the vertex shader executable accesses multiple inputs
2535 * assigned to any single location.
2538 /* Mask representing the contiguous slots that will be used by
2541 const unsigned attr
= var
->data
.location
- generic_base
;
2542 const unsigned use_mask
= (1 << slots
) - 1;
2543 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2544 ? "vertex shader input" : "fragment shader output";
2546 /* Generate a link error if the requested locations for this
2547 * attribute exceed the maximum allowed attribute location.
2549 if (attr
+ slots
> max_index
) {
2551 "insufficient contiguous locations "
2552 "available for %s `%s' %d %d %d\n", string
,
2553 var
->name
, used_locations
, use_mask
, attr
);
2557 /* Generate a link error if the set of bits requested for this
2558 * attribute overlaps any previously allocated bits.
2560 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2561 if (target_index
== MESA_SHADER_FRAGMENT
||
2562 (prog
->IsES
&& prog
->Version
>= 300)) {
2564 "overlapping location is assigned "
2565 "to %s `%s' %d %d %d\n", string
,
2566 var
->name
, used_locations
, use_mask
, attr
);
2569 linker_warning(prog
,
2570 "overlapping location is assigned "
2571 "to %s `%s' %d %d %d\n", string
,
2572 var
->name
, used_locations
, use_mask
, attr
);
2576 used_locations
|= (use_mask
<< attr
);
2578 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2580 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2581 * active attribute variables may fail to link, unless
2582 * device-dependent optimizations are able to make the program
2583 * fit within available hardware resources. For the purposes
2584 * of this test, attribute variables of the type dvec3, dvec4,
2585 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2586 * count as consuming twice as many attributes as equivalent
2587 * single-precision types. While these types use the same number
2588 * of generic attributes as their single-precision equivalents,
2589 * implementations are permitted to consume two single-precision
2590 * vectors of internal storage for each three- or four-component
2591 * double-precision vector."
2593 * Mark this attribute slot as taking up twice as much space
2594 * so we can count it properly against limits. According to
2595 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2596 * is optional behavior, but it seems preferable.
2598 const glsl_type
*type
= var
->type
->without_array();
2599 if (type
== glsl_type::dvec3_type
||
2600 type
== glsl_type::dvec4_type
||
2601 type
== glsl_type::dmat2x3_type
||
2602 type
== glsl_type::dmat2x4_type
||
2603 type
== glsl_type::dmat3_type
||
2604 type
== glsl_type::dmat3x4_type
||
2605 type
== glsl_type::dmat4x3_type
||
2606 type
== glsl_type::dmat4_type
) {
2607 double_storage_locations
|= (use_mask
<< attr
);
2614 to_assign
[num_attr
].slots
= slots
;
2615 to_assign
[num_attr
].var
= var
;
2619 if (target_index
== MESA_SHADER_VERTEX
) {
2620 unsigned total_attribs_size
=
2621 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2622 _mesa_bitcount(double_storage_locations
);
2623 if (total_attribs_size
> max_index
) {
2625 "attempt to use %d vertex attribute slots only %d available ",
2626 total_attribs_size
, max_index
);
2631 /* If all of the attributes were assigned locations by the application (or
2632 * are built-in attributes with fixed locations), return early. This should
2633 * be the common case.
2638 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2640 if (target_index
== MESA_SHADER_VERTEX
) {
2641 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2642 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2643 * reserved to prevent it from being automatically allocated below.
2645 find_deref_visitor
find("gl_Vertex");
2647 if (find
.variable_found())
2648 used_locations
|= (1 << 0);
2651 for (unsigned i
= 0; i
< num_attr
; i
++) {
2652 /* Mask representing the contiguous slots that will be used by this
2655 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2657 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2660 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2661 ? "vertex shader input" : "fragment shader output";
2664 "insufficient contiguous locations "
2665 "available for %s `%s'\n",
2666 string
, to_assign
[i
].var
->name
);
2670 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2671 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2672 used_locations
|= (use_mask
<< location
);
2680 * Demote shader inputs and outputs that are not used in other stages
2683 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
2685 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2686 ir_variable
*const var
= node
->as_variable();
2688 if ((var
== NULL
) || (var
->data
.mode
!= int(mode
)))
2691 /* A shader 'in' or 'out' variable is only really an input or output if
2692 * its value is used by other shader stages. This will cause the variable
2693 * to have a location assigned.
2695 if (var
->data
.is_unmatched_generic_inout
) {
2696 assert(var
->data
.mode
!= ir_var_temporary
);
2697 var
->data
.mode
= ir_var_auto
;
2704 * Store the gl_FragDepth layout in the gl_shader_program struct.
2707 store_fragdepth_layout(struct gl_shader_program
*prog
)
2709 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2713 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2715 /* We don't look up the gl_FragDepth symbol directly because if
2716 * gl_FragDepth is not used in the shader, it's removed from the IR.
2717 * However, the symbol won't be removed from the symbol table.
2719 * We're only interested in the cases where the variable is NOT removed
2722 foreach_in_list(ir_instruction
, node
, ir
) {
2723 ir_variable
*const var
= node
->as_variable();
2725 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2729 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2730 switch (var
->data
.depth_layout
) {
2731 case ir_depth_layout_none
:
2732 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2734 case ir_depth_layout_any
:
2735 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2737 case ir_depth_layout_greater
:
2738 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2740 case ir_depth_layout_less
:
2741 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2743 case ir_depth_layout_unchanged
:
2744 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2755 * Validate the resources used by a program versus the implementation limits
2758 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2760 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2761 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2766 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2767 linker_error(prog
, "Too many %s shader texture samplers\n",
2768 _mesa_shader_stage_to_string(i
));
2771 if (sh
->num_uniform_components
>
2772 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2773 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2774 linker_warning(prog
, "Too many %s shader default uniform block "
2775 "components, but the driver will try to optimize "
2776 "them out; this is non-portable out-of-spec "
2778 _mesa_shader_stage_to_string(i
));
2780 linker_error(prog
, "Too many %s shader default uniform block "
2782 _mesa_shader_stage_to_string(i
));
2786 if (sh
->num_combined_uniform_components
>
2787 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2788 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2789 linker_warning(prog
, "Too many %s shader uniform components, "
2790 "but the driver will try to optimize them out; "
2791 "this is non-portable out-of-spec behavior\n",
2792 _mesa_shader_stage_to_string(i
));
2794 linker_error(prog
, "Too many %s shader uniform components\n",
2795 _mesa_shader_stage_to_string(i
));
2800 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2801 unsigned total_uniform_blocks
= 0;
2802 unsigned shader_blocks
[MESA_SHADER_STAGES
] = {0};
2803 unsigned total_shader_storage_blocks
= 0;
2805 for (unsigned i
= 0; i
< prog
->NumBufferInterfaceBlocks
; i
++) {
2806 /* Don't check SSBOs for Uniform Block Size */
2807 if (!prog
->UniformBlocks
[i
].IsShaderStorage
&&
2808 prog
->UniformBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxUniformBlockSize
) {
2809 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
2810 prog
->UniformBlocks
[i
].Name
,
2811 prog
->UniformBlocks
[i
].UniformBufferSize
,
2812 ctx
->Const
.MaxUniformBlockSize
);
2815 if (prog
->UniformBlocks
[i
].IsShaderStorage
&&
2816 prog
->UniformBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxShaderStorageBlockSize
) {
2817 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
2818 prog
->UniformBlocks
[i
].Name
,
2819 prog
->UniformBlocks
[i
].UniformBufferSize
,
2820 ctx
->Const
.MaxShaderStorageBlockSize
);
2823 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2824 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2825 struct gl_shader
*sh
= prog
->_LinkedShaders
[j
];
2826 int stage_index
= prog
->UniformBlockStageIndex
[j
][i
];
2827 if (sh
&& sh
->UniformBlocks
[stage_index
].IsShaderStorage
) {
2829 total_shader_storage_blocks
++;
2832 total_uniform_blocks
++;
2837 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2838 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2839 total_uniform_blocks
,
2840 ctx
->Const
.MaxCombinedUniformBlocks
);
2842 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2843 const unsigned max_uniform_blocks
=
2844 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2845 if (blocks
[i
] > max_uniform_blocks
) {
2846 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2847 _mesa_shader_stage_to_string(i
),
2849 max_uniform_blocks
);
2855 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
2856 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
2857 total_shader_storage_blocks
,
2858 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
2860 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2861 const unsigned max_shader_storage_blocks
=
2862 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
2863 if (shader_blocks
[i
] > max_shader_storage_blocks
) {
2864 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2865 _mesa_shader_stage_to_string(i
),
2867 max_shader_storage_blocks
);
2876 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
2878 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2879 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2884 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
2885 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
2891 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
2892 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
2893 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
2894 if (fn
->types
[k
] == uni
->type
) {
2900 uni
->num_compatible_subroutines
= count
;
2906 check_subroutine_resources(struct gl_shader_program
*prog
)
2908 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2909 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2912 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
2913 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
2914 _mesa_shader_stage_to_string(i
));
2919 * Validate shader image resources.
2922 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2924 unsigned total_image_units
= 0;
2925 unsigned fragment_outputs
= 0;
2926 unsigned total_shader_storage_blocks
= 0;
2928 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
2931 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2932 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2935 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
2936 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
2937 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
2938 ctx
->Const
.Program
[i
].MaxImageUniforms
);
2940 total_image_units
+= sh
->NumImages
;
2942 for (unsigned j
= 0; j
< prog
->NumBufferInterfaceBlocks
; j
++) {
2943 int stage_index
= prog
->UniformBlockStageIndex
[i
][j
];
2944 if (stage_index
!= -1 && sh
->UniformBlocks
[stage_index
].IsShaderStorage
)
2945 total_shader_storage_blocks
++;
2948 if (i
== MESA_SHADER_FRAGMENT
) {
2949 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2950 ir_variable
*var
= node
->as_variable();
2951 if (var
&& var
->data
.mode
== ir_var_shader_out
)
2952 fragment_outputs
+= var
->type
->count_attribute_slots();
2958 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
2959 linker_error(prog
, "Too many combined image uniforms\n");
2961 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
2962 ctx
->Const
.MaxCombinedShaderOutputResources
)
2963 linker_error(prog
, "Too many combined image uniforms, shader storage "
2964 " buffers and fragment outputs\n");
2969 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2970 * for a variable, checks for overlaps between other uniforms using explicit
2974 reserve_explicit_locations(struct gl_shader_program
*prog
,
2975 string_to_uint_map
*map
, ir_variable
*var
)
2977 unsigned slots
= var
->type
->uniform_locations();
2978 unsigned max_loc
= var
->data
.location
+ slots
- 1;
2980 /* Resize remap table if locations do not fit in the current one. */
2981 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
2982 prog
->UniformRemapTable
=
2983 reralloc(prog
, prog
->UniformRemapTable
,
2984 gl_uniform_storage
*,
2987 if (!prog
->UniformRemapTable
) {
2988 linker_error(prog
, "Out of memory during linking.\n");
2992 /* Initialize allocated space. */
2993 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
2994 prog
->UniformRemapTable
[i
] = NULL
;
2996 prog
->NumUniformRemapTable
= max_loc
+ 1;
2999 for (unsigned i
= 0; i
< slots
; i
++) {
3000 unsigned loc
= var
->data
.location
+ i
;
3002 /* Check if location is already used. */
3003 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3005 /* Possibly same uniform from a different stage, this is ok. */
3007 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
)
3010 /* ARB_explicit_uniform_location specification states:
3012 * "No two default-block uniform variables in the program can have
3013 * the same location, even if they are unused, otherwise a compiler
3014 * or linker error will be generated."
3017 "location qualifier for uniform %s overlaps "
3018 "previously used location\n",
3023 /* Initialize location as inactive before optimization
3024 * rounds and location assignment.
3026 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3029 /* Note, base location used for arrays. */
3030 map
->put(var
->data
.location
, var
->name
);
3036 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3037 struct gl_shader
*sh
,
3040 unsigned slots
= var
->type
->uniform_locations();
3041 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3043 /* Resize remap table if locations do not fit in the current one. */
3044 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3045 sh
->SubroutineUniformRemapTable
=
3046 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3047 gl_uniform_storage
*,
3050 if (!sh
->SubroutineUniformRemapTable
) {
3051 linker_error(prog
, "Out of memory during linking.\n");
3055 /* Initialize allocated space. */
3056 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3057 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3059 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3062 for (unsigned i
= 0; i
< slots
; i
++) {
3063 unsigned loc
= var
->data
.location
+ i
;
3065 /* Check if location is already used. */
3066 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3068 /* ARB_explicit_uniform_location specification states:
3069 * "No two subroutine uniform variables can have the same location
3070 * in the same shader stage, otherwise a compiler or linker error
3071 * will be generated."
3074 "location qualifier for uniform %s overlaps "
3075 "previously used location\n",
3080 /* Initialize location as inactive before optimization
3081 * rounds and location assignment.
3083 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3089 * Check and reserve all explicit uniform locations, called before
3090 * any optimizations happen to handle also inactive uniforms and
3091 * inactive array elements that may get trimmed away.
3094 check_explicit_uniform_locations(struct gl_context
*ctx
,
3095 struct gl_shader_program
*prog
)
3097 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3100 /* This map is used to detect if overlapping explicit locations
3101 * occur with the same uniform (from different stage) or a different one.
3103 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3106 linker_error(prog
, "Out of memory during linking.\n");
3110 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3111 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3116 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3117 ir_variable
*var
= node
->as_variable();
3118 if (var
&& (var
->data
.mode
== ir_var_uniform
|| var
->data
.mode
== ir_var_shader_storage
) &&
3119 var
->data
.explicit_location
) {
3121 if (var
->type
->is_subroutine())
3122 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3124 ret
= reserve_explicit_locations(prog
, uniform_map
, var
);
3137 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3138 const void *data
, uint8_t stages
)
3142 /* If resource already exists, do not add it again. */
3143 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3144 if (prog
->ProgramResourceList
[i
].Data
== data
)
3147 prog
->ProgramResourceList
=
3149 prog
->ProgramResourceList
,
3150 gl_program_resource
,
3151 prog
->NumProgramResourceList
+ 1);
3153 if (!prog
->ProgramResourceList
) {
3154 linker_error(prog
, "Out of memory during linking.\n");
3158 struct gl_program_resource
*res
=
3159 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3163 res
->StageReferences
= stages
;
3165 prog
->NumProgramResourceList
++;
3170 /* Function checks if a variable var is a packed varying and
3171 * if given name is part of packed varying's list.
3173 * If a variable is a packed varying, it has a name like
3174 * 'packed:a,b,c' where a, b and c are separate variables.
3177 included_in_packed_varying(ir_variable
*var
, const char *name
)
3179 if (strncmp(var
->name
, "packed:", 7) != 0)
3182 char *list
= strdup(var
->name
+ 7);
3187 char *token
= strtok_r(list
, ",", &saveptr
);
3189 if (strcmp(token
, name
) == 0) {
3193 token
= strtok_r(NULL
, ",", &saveptr
);
3200 * Function builds a stage reference bitmask from variable name.
3203 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3208 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3209 * used for reference mask in gl_program_resource will need to be changed.
3211 assert(MESA_SHADER_STAGES
< 8);
3213 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3214 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3218 /* Shader symbol table may contain variables that have
3219 * been optimized away. Search IR for the variable instead.
3221 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3222 ir_variable
*var
= node
->as_variable();
3224 unsigned baselen
= strlen(var
->name
);
3226 if (included_in_packed_varying(var
, name
)) {
3231 /* Type needs to match if specified, otherwise we might
3232 * pick a variable with same name but different interface.
3234 if (var
->data
.mode
!= mode
)
3237 if (strncmp(var
->name
, name
, baselen
) == 0) {
3238 /* Check for exact name matches but also check for arrays and
3241 if (name
[baselen
] == '\0' ||
3242 name
[baselen
] == '[' ||
3243 name
[baselen
] == '.') {
3255 add_interface_variables(struct gl_shader_program
*shProg
,
3256 exec_list
*ir
, GLenum programInterface
)
3258 foreach_in_list(ir_instruction
, node
, ir
) {
3259 ir_variable
*var
= node
->as_variable();
3265 switch (var
->data
.mode
) {
3266 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3267 * "For GetActiveAttrib, all active vertex shader input variables
3268 * are enumerated, including the special built-in inputs gl_VertexID
3269 * and gl_InstanceID."
3271 case ir_var_system_value
:
3272 if (var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID
&&
3273 var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
&&
3274 var
->data
.location
!= SYSTEM_VALUE_INSTANCE_ID
)
3276 /* Mark special built-in inputs referenced by the vertex stage so
3277 * that they are considered active by the shader queries.
3279 mask
= (1 << (MESA_SHADER_VERTEX
));
3281 case ir_var_shader_in
:
3282 if (programInterface
!= GL_PROGRAM_INPUT
)
3285 case ir_var_shader_out
:
3286 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3293 /* Skip packed varyings, packed varyings are handled separately
3294 * by add_packed_varyings.
3296 if (strncmp(var
->name
, "packed:", 7) == 0)
3299 if (!add_program_resource(shProg
, programInterface
, var
,
3300 build_stageref(shProg
, var
->name
,
3301 var
->data
.mode
) | mask
))
3308 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
)
3310 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3313 if (!sh
|| !sh
->packed_varyings
)
3316 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3317 ir_variable
*var
= node
->as_variable();
3319 switch (var
->data
.mode
) {
3320 case ir_var_shader_in
:
3321 iface
= GL_PROGRAM_INPUT
;
3323 case ir_var_shader_out
:
3324 iface
= GL_PROGRAM_OUTPUT
;
3327 unreachable("unexpected type");
3329 if (!add_program_resource(shProg
, iface
, var
,
3330 build_stageref(shProg
, var
->name
,
3339 * Builds up a list of program resources that point to existing
3343 build_program_resource_list(struct gl_shader_program
*shProg
)
3345 /* Rebuild resource list. */
3346 if (shProg
->ProgramResourceList
) {
3347 ralloc_free(shProg
->ProgramResourceList
);
3348 shProg
->ProgramResourceList
= NULL
;
3349 shProg
->NumProgramResourceList
= 0;
3352 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3354 /* Determine first input and final output stage. These are used to
3355 * detect which variables should be enumerated in the resource list
3356 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3358 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3359 if (!shProg
->_LinkedShaders
[i
])
3361 if (input_stage
== MESA_SHADER_STAGES
)
3366 /* Empty shader, no resources. */
3367 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3370 if (!add_packed_varyings(shProg
, input_stage
))
3372 if (!add_packed_varyings(shProg
, output_stage
))
3375 /* Add inputs and outputs to the resource list. */
3376 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[input_stage
]->ir
,
3380 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[output_stage
]->ir
,
3384 /* Add transform feedback varyings. */
3385 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3386 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3387 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3388 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
3394 /* Add uniforms from uniform storage. */
3395 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3396 /* Do not add uniforms internally used by Mesa. */
3397 if (shProg
->UniformStorage
[i
].hidden
)
3401 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
3404 /* Add stagereferences for uniforms in a uniform block. */
3405 int block_index
= shProg
->UniformStorage
[i
].block_index
;
3406 if (block_index
!= -1) {
3407 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
3408 if (shProg
->UniformBlockStageIndex
[j
][block_index
] != -1)
3409 stageref
|= (1 << j
);
3413 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
3414 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
3415 if (!add_program_resource(shProg
, type
,
3416 &shProg
->UniformStorage
[i
], stageref
))
3420 /* Add program uniform blocks and shader storage blocks. */
3421 for (unsigned i
= 0; i
< shProg
->NumBufferInterfaceBlocks
; i
++) {
3422 bool is_shader_storage
= shProg
->UniformBlocks
[i
].IsShaderStorage
;
3423 GLenum type
= is_shader_storage
? GL_SHADER_STORAGE_BLOCK
: GL_UNIFORM_BLOCK
;
3424 if (!add_program_resource(shProg
, type
,
3425 &shProg
->UniformBlocks
[i
], 0))
3429 /* Add atomic counter buffers. */
3430 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
3431 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
3432 &shProg
->AtomicBuffers
[i
], 0))
3436 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3438 if (!shProg
->UniformStorage
[i
].hidden
)
3441 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
3442 if (!shProg
->UniformStorage
[i
].subroutine
[j
].active
)
3445 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
3446 /* add shader subroutines */
3447 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
3452 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3453 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3459 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
3460 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
3461 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
3466 /* TODO - following extensions will require more resource types:
3468 * GL_ARB_shader_storage_buffer_object
3473 * This check is done to make sure we allow only constant expression
3474 * indexing and "constant-index-expression" (indexing with an expression
3475 * that includes loop induction variable).
3478 validate_sampler_array_indexing(struct gl_context
*ctx
,
3479 struct gl_shader_program
*prog
)
3481 dynamic_sampler_array_indexing_visitor v
;
3482 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3483 if (prog
->_LinkedShaders
[i
] == NULL
)
3486 bool no_dynamic_indexing
=
3487 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
3489 /* Search for array derefs in shader. */
3490 v
.run(prog
->_LinkedShaders
[i
]->ir
);
3491 if (v
.uses_dynamic_sampler_array_indexing()) {
3492 const char *msg
= "sampler arrays indexed with non-constant "
3493 "expressions is forbidden in GLSL %s %u";
3494 /* Backend has indicated that it has no dynamic indexing support. */
3495 if (no_dynamic_indexing
) {
3496 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3499 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3507 link_assign_subroutine_types(struct gl_shader_program
*prog
)
3509 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3510 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3515 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3516 ir_function
*fn
= node
->as_function();
3520 if (fn
->is_subroutine
)
3521 sh
->NumSubroutineUniformTypes
++;
3523 if (!fn
->num_subroutine_types
)
3526 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
3527 struct gl_subroutine_function
,
3528 sh
->NumSubroutineFunctions
+ 1);
3529 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
3530 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
3531 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
3532 ralloc_array(sh
, const struct glsl_type
*,
3533 fn
->num_subroutine_types
);
3534 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
3535 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
3536 sh
->NumSubroutineFunctions
++;
3542 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3544 tfeedback_decl
*tfeedback_decls
= NULL
;
3545 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
3547 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
3549 prog
->LinkStatus
= true; /* All error paths will set this to false */
3550 prog
->Validated
= false;
3551 prog
->_Used
= false;
3553 prog
->ARB_fragment_coord_conventions_enable
= false;
3555 /* Separate the shaders into groups based on their type.
3557 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
3558 unsigned num_shaders
[MESA_SHADER_STAGES
];
3560 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3561 shader_list
[i
] = (struct gl_shader
**)
3562 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
3566 unsigned min_version
= UINT_MAX
;
3567 unsigned max_version
= 0;
3568 const bool is_es_prog
=
3569 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
3570 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
3571 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
3572 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
3574 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
3575 linker_error(prog
, "all shaders must use same shading "
3576 "language version\n");
3580 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
3581 prog
->ARB_fragment_coord_conventions_enable
= true;
3584 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
3585 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
3586 num_shaders
[shader_type
]++;
3589 /* In desktop GLSL, different shader versions may be linked together. In
3590 * GLSL ES, all shader versions must be the same.
3592 if (is_es_prog
&& min_version
!= max_version
) {
3593 linker_error(prog
, "all shaders must use same shading "
3594 "language version\n");
3598 prog
->Version
= max_version
;
3599 prog
->IsES
= is_es_prog
;
3601 /* From OpenGL 4.5 Core specification (7.3 Program Objects):
3602 * "Linking can fail for a variety of reasons as specified in the OpenGL
3603 * Shading Language Specification, as well as any of the following
3606 * * No shader objects are attached to program.
3610 * Same rule applies for OpenGL ES >= 3.1.
3613 if (prog
->NumShaders
== 0 &&
3614 ((ctx
->API
== API_OPENGL_CORE
&& ctx
->Version
>= 45) ||
3615 (ctx
->API
== API_OPENGLES2
&& ctx
->Version
>= 31))) {
3616 linker_error(prog
, "No shader objects are attached to program.\n");
3620 /* Some shaders have to be linked with some other shaders present.
3622 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
3623 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3624 !prog
->SeparateShader
) {
3625 linker_error(prog
, "Geometry shader must be linked with "
3629 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
3630 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3631 !prog
->SeparateShader
) {
3632 linker_error(prog
, "Tessellation evaluation shader must be linked with "
3636 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3637 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3638 !prog
->SeparateShader
) {
3639 linker_error(prog
, "Tessellation control shader must be linked with "
3644 /* The spec is self-contradictory here. It allows linking without a tess
3645 * eval shader, but that can only be used with transform feedback and
3646 * rasterization disabled. However, transform feedback isn't allowed
3647 * with GL_PATCHES, so it can't be used.
3649 * More investigation showed that the idea of transform feedback after
3650 * a tess control shader was dropped, because some hw vendors couldn't
3651 * support tessellation without a tess eval shader, but the linker section
3652 * wasn't updated to reflect that.
3654 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
3657 * Do what's reasonable and always require a tess eval shader if a tess
3658 * control shader is present.
3660 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3661 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0 &&
3662 !prog
->SeparateShader
) {
3663 linker_error(prog
, "Tessellation control shader must be linked with "
3664 "tessellation evaluation shader\n");
3668 /* Compute shaders have additional restrictions. */
3669 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
3670 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
3671 linker_error(prog
, "Compute shaders may not be linked with any other "
3672 "type of shader\n");
3675 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3676 if (prog
->_LinkedShaders
[i
] != NULL
)
3677 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
3679 prog
->_LinkedShaders
[i
] = NULL
;
3682 /* Link all shaders for a particular stage and validate the result.
3684 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
3685 if (num_shaders
[stage
] > 0) {
3686 gl_shader
*const sh
=
3687 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
3688 num_shaders
[stage
]);
3690 if (!prog
->LinkStatus
) {
3692 ctx
->Driver
.DeleteShader(ctx
, sh
);
3697 case MESA_SHADER_VERTEX
:
3698 validate_vertex_shader_executable(prog
, sh
);
3700 case MESA_SHADER_TESS_CTRL
:
3701 /* nothing to be done */
3703 case MESA_SHADER_TESS_EVAL
:
3704 validate_tess_eval_shader_executable(prog
, sh
);
3706 case MESA_SHADER_GEOMETRY
:
3707 validate_geometry_shader_executable(prog
, sh
);
3709 case MESA_SHADER_FRAGMENT
:
3710 validate_fragment_shader_executable(prog
, sh
);
3713 if (!prog
->LinkStatus
) {
3715 ctx
->Driver
.DeleteShader(ctx
, sh
);
3719 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
3723 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
3724 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
3725 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
3726 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
3727 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
3728 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
3730 prog
->LastClipDistanceArraySize
= 0; /* Not used */
3732 /* Here begins the inter-stage linking phase. Some initial validation is
3733 * performed, then locations are assigned for uniforms, attributes, and
3736 cross_validate_uniforms(prog
);
3737 if (!prog
->LinkStatus
)
3742 for (prev
= 0; prev
<= MESA_SHADER_FRAGMENT
; prev
++) {
3743 if (prog
->_LinkedShaders
[prev
] != NULL
)
3747 check_explicit_uniform_locations(ctx
, prog
);
3748 link_assign_subroutine_types(prog
);
3750 if (!prog
->LinkStatus
)
3753 resize_tes_inputs(ctx
, prog
);
3755 /* Validate the inputs of each stage with the output of the preceding
3758 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3759 if (prog
->_LinkedShaders
[i
] == NULL
)
3762 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
3763 prog
->_LinkedShaders
[i
]);
3764 if (!prog
->LinkStatus
)
3767 cross_validate_outputs_to_inputs(prog
,
3768 prog
->_LinkedShaders
[prev
],
3769 prog
->_LinkedShaders
[i
]);
3770 if (!prog
->LinkStatus
)
3776 /* Cross-validate uniform blocks between shader stages */
3777 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
3778 MESA_SHADER_STAGES
);
3779 if (!prog
->LinkStatus
)
3782 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3783 if (prog
->_LinkedShaders
[i
] != NULL
)
3784 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
3787 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
3788 * it before optimization because we want most of the checks to get
3789 * dropped thanks to constant propagation.
3791 * This rule also applies to GLSL ES 3.00.
3793 if (max_version
>= (is_es_prog
? 300 : 130)) {
3794 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3796 lower_discard_flow(sh
->ir
);
3800 if (!interstage_cross_validate_uniform_blocks(prog
))
3803 /* Do common optimization before assigning storage for attributes,
3804 * uniforms, and varyings. Later optimization could possibly make
3805 * some of that unused.
3807 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3808 if (prog
->_LinkedShaders
[i
] == NULL
)
3811 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
3812 if (!prog
->LinkStatus
)
3815 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerClipDistance
) {
3816 lower_clip_distance(prog
->_LinkedShaders
[i
]);
3819 if (ctx
->Const
.LowerTessLevel
) {
3820 lower_tess_level(prog
->_LinkedShaders
[i
]);
3823 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
3824 &ctx
->Const
.ShaderCompilerOptions
[i
],
3825 ctx
->Const
.NativeIntegers
))
3828 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
3831 /* Validation for special cases where we allow sampler array indexing
3832 * with loop induction variable. This check emits a warning or error
3833 * depending if backend can handle dynamic indexing.
3835 if ((!prog
->IsES
&& prog
->Version
< 130) ||
3836 (prog
->IsES
&& prog
->Version
< 300)) {
3837 if (!validate_sampler_array_indexing(ctx
, prog
))
3841 /* Check and validate stream emissions in geometry shaders */
3842 validate_geometry_shader_emissions(ctx
, prog
);
3844 /* Mark all generic shader inputs and outputs as unpaired. */
3845 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3846 if (prog
->_LinkedShaders
[i
] != NULL
) {
3847 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
3851 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
3852 MESA_SHADER_VERTEX
)) {
3856 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
3857 MESA_SHADER_FRAGMENT
)) {
3861 unsigned first
, last
;
3863 first
= MESA_SHADER_STAGES
;
3866 /* Determine first and last stage. */
3867 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3868 if (!prog
->_LinkedShaders
[i
])
3870 if (first
== MESA_SHADER_STAGES
)
3875 if (num_tfeedback_decls
!= 0) {
3876 /* From GL_EXT_transform_feedback:
3877 * A program will fail to link if:
3879 * * the <count> specified by TransformFeedbackVaryingsEXT is
3880 * non-zero, but the program object has no vertex or geometry
3883 if (first
== MESA_SHADER_FRAGMENT
) {
3884 linker_error(prog
, "Transform feedback varyings specified, but "
3885 "no vertex or geometry shader is present.\n");
3889 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
3890 prog
->TransformFeedback
.NumVarying
);
3891 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
3892 prog
->TransformFeedback
.VaryingNames
,
3897 /* Linking the stages in the opposite order (from fragment to vertex)
3898 * ensures that inter-shader outputs written to in an earlier stage are
3899 * eliminated if they are (transitively) not used in a later stage.
3903 if (first
< MESA_SHADER_FRAGMENT
) {
3904 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
3906 if (first
== MESA_SHADER_GEOMETRY
) {
3907 /* There was no vertex shader, but we still have to assign varying
3908 * locations for use by geometry shader inputs in SSO.
3910 * If the shader is not separable (i.e., prog->SeparateShader is
3911 * false), linking will have already failed when first is
3912 * MESA_SHADER_GEOMETRY.
3914 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3915 NULL
, prog
->_LinkedShaders
[first
],
3916 num_tfeedback_decls
, tfeedback_decls
))
3920 if (last
!= MESA_SHADER_FRAGMENT
&&
3921 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
3922 /* There was no fragment shader, but we still have to assign varying
3923 * locations for use by transform feedback.
3925 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3927 num_tfeedback_decls
, tfeedback_decls
))
3931 do_dead_builtin_varyings(ctx
, sh
, NULL
,
3932 num_tfeedback_decls
, tfeedback_decls
);
3934 if (!prog
->SeparateShader
)
3935 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
3937 /* Eliminate code that is now dead due to unused outputs being demoted.
3939 while (do_dead_code(sh
->ir
, false))
3942 else if (first
== MESA_SHADER_FRAGMENT
) {
3943 /* If the program only contains a fragment shader...
3945 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
3947 do_dead_builtin_varyings(ctx
, NULL
, sh
,
3948 num_tfeedback_decls
, tfeedback_decls
);
3950 if (prog
->SeparateShader
) {
3951 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3952 NULL
/* producer */,
3954 0 /* num_tfeedback_decls */,
3955 NULL
/* tfeedback_decls */))
3958 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
3960 while (do_dead_code(sh
->ir
, false))
3965 for (int i
= next
- 1; i
>= 0; i
--) {
3966 if (prog
->_LinkedShaders
[i
] == NULL
)
3969 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
3970 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
3972 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
3973 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3977 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
3978 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3981 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
3982 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
3984 /* Eliminate code that is now dead due to unused outputs being demoted.
3986 while (do_dead_code(sh_i
->ir
, false))
3988 while (do_dead_code(sh_next
->ir
, false))
3991 /* This must be done after all dead varyings are eliminated. */
3992 if (!check_against_output_limit(ctx
, prog
, sh_i
))
3994 if (!check_against_input_limit(ctx
, prog
, sh_next
))
4000 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
4003 update_array_sizes(prog
);
4004 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
);
4005 link_assign_atomic_counter_resources(ctx
, prog
);
4006 store_fragdepth_layout(prog
);
4008 link_calculate_subroutine_compat(prog
);
4009 check_resources(ctx
, prog
);
4010 check_subroutine_resources(prog
);
4011 check_image_resources(ctx
, prog
);
4012 link_check_atomic_counter_resources(ctx
, prog
);
4014 if (!prog
->LinkStatus
)
4017 /* OpenGL ES requires that a vertex shader and a fragment shader both be
4018 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
4019 * anything about shader linking when one of the shaders (vertex or
4020 * fragment shader) is absent. So, the extension shouldn't change the
4021 * behavior specified in GLSL specification.
4023 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
) {
4024 /* With ES < 3.1 one needs to have always vertex + fragment shader. */
4025 if (ctx
->Version
< 31) {
4026 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4027 linker_error(prog
, "program lacks a vertex shader\n");
4028 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4029 linker_error(prog
, "program lacks a fragment shader\n");
4032 /* From OpenGL ES 3.1 specification (7.3 Program Objects):
4033 * "Linking can fail for a variety of reasons as specified in the
4034 * OpenGL ES Shading Language Specification, as well as any of the
4035 * following reasons:
4039 * * program contains objects to form either a vertex shader or
4040 * fragment shader, and program is not separable, and does not
4041 * contain objects to form both a vertex shader and fragment
4044 if (!!prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] ^
4045 !!prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]) {
4046 linker_error(prog
, "Program needs to contain both vertex and "
4047 "fragment shaders.\n");
4052 /* FINISHME: Assign fragment shader output locations. */
4055 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4056 free(shader_list
[i
]);
4057 if (prog
->_LinkedShaders
[i
] == NULL
)
4060 /* Do a final validation step to make sure that the IR wasn't
4061 * invalidated by any modifications performed after intrastage linking.
4063 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4065 /* Retain any live IR, but trash the rest. */
4066 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4068 /* The symbol table in the linked shaders may contain references to
4069 * variables that were removed (e.g., unused uniforms). Since it may
4070 * contain junk, there is no possible valid use. Delete it and set the
4073 delete prog
->_LinkedShaders
[i
]->symbols
;
4074 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4077 ralloc_free(mem_ctx
);