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 "util/strndup.h"
69 #include "main/core.h"
70 #include "glsl_symbol_table.h"
71 #include "glsl_parser_extras.h"
74 #include "program/hash_table.h"
76 #include "link_varyings.h"
77 #include "ir_optimization.h"
78 #include "ir_rvalue_visitor.h"
79 #include "ir_uniform.h"
81 #include "main/shaderobj.h"
82 #include "main/enums.h"
88 * Visitor that determines whether or not a variable is ever written.
90 class find_assignment_visitor
: public ir_hierarchical_visitor
{
92 find_assignment_visitor(const char *name
)
93 : name(name
), found(false)
98 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
100 ir_variable
*const var
= ir
->lhs
->variable_referenced();
102 if (strcmp(name
, var
->name
) == 0) {
107 return visit_continue_with_parent
;
110 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
112 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
113 actual_node
, &ir
->actual_parameters
) {
114 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
115 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
117 if (sig_param
->data
.mode
== ir_var_function_out
||
118 sig_param
->data
.mode
== ir_var_function_inout
) {
119 ir_variable
*var
= param_rval
->variable_referenced();
120 if (var
&& strcmp(name
, var
->name
) == 0) {
127 if (ir
->return_deref
!= NULL
) {
128 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
130 if (strcmp(name
, var
->name
) == 0) {
136 return visit_continue_with_parent
;
139 bool variable_found()
145 const char *name
; /**< Find writes to a variable with this name. */
146 bool found
; /**< Was a write to the variable found? */
151 * Visitor that determines whether or not a variable is ever read.
153 class find_deref_visitor
: public ir_hierarchical_visitor
{
155 find_deref_visitor(const char *name
)
156 : name(name
), found(false)
161 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
163 if (strcmp(this->name
, ir
->var
->name
) == 0) {
168 return visit_continue
;
171 bool variable_found() const
177 const char *name
; /**< Find writes to a variable with this name. */
178 bool found
; /**< Was a write to the variable found? */
182 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
184 unsigned num_vertices
;
185 gl_shader_program
*prog
;
187 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
189 this->num_vertices
= num_vertices
;
193 virtual ~geom_array_resize_visitor()
198 virtual ir_visitor_status
visit(ir_variable
*var
)
200 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
201 return visit_continue
;
203 unsigned size
= var
->type
->length
;
205 /* Generate a link error if the shader has declared this array with an
208 if (!var
->data
.implicit_sized_array
&&
209 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
>= (int)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 if (var
->data
.explicit_location
&&
635 var
->data
.location
< VARYING_SLOT_VAR0
) {
636 var
->data
.is_unmatched_generic_inout
= 0;
638 var
->data
.is_unmatched_generic_inout
= 1;
645 * Set clip_distance_array_size based and cull_distance_array_size on the given
648 * Also check for errors based on incorrect usage of gl_ClipVertex and
649 * gl_ClipDistance and gl_CullDistance.
650 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
651 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
653 * Return false if an error was reported.
656 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
657 struct gl_shader
*shader
,
658 struct gl_context
*ctx
,
659 GLuint
*clip_distance_array_size
,
660 GLuint
*cull_distance_array_size
)
662 *clip_distance_array_size
= 0;
663 *cull_distance_array_size
= 0;
665 if (prog
->Version
>= (prog
->IsES
? 300 : 130)) {
666 /* From section 7.1 (Vertex Shader Special Variables) of the
669 * "It is an error for a shader to statically write both
670 * gl_ClipVertex and gl_ClipDistance."
672 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
673 * gl_ClipVertex nor gl_ClipDistance. However with
674 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
676 find_assignment_visitor
clip_distance("gl_ClipDistance");
677 find_assignment_visitor
cull_distance("gl_CullDistance");
679 clip_distance
.run(shader
->ir
);
680 cull_distance
.run(shader
->ir
);
682 /* From the ARB_cull_distance spec:
684 * It is a compile-time or link-time error for the set of shaders forming
685 * a program to statically read or write both gl_ClipVertex and either
686 * gl_ClipDistance or gl_CullDistance.
688 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
692 find_assignment_visitor
clip_vertex("gl_ClipVertex");
694 clip_vertex
.run(shader
->ir
);
696 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
697 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
698 "and `gl_ClipDistance'\n",
699 _mesa_shader_stage_to_string(shader
->Stage
));
702 if (clip_vertex
.variable_found() && cull_distance
.variable_found()) {
703 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
704 "and `gl_CullDistance'\n",
705 _mesa_shader_stage_to_string(shader
->Stage
));
710 if (clip_distance
.variable_found()) {
711 ir_variable
*clip_distance_var
=
712 shader
->symbols
->get_variable("gl_ClipDistance");
713 assert(clip_distance_var
);
714 *clip_distance_array_size
= clip_distance_var
->type
->length
;
716 if (cull_distance
.variable_found()) {
717 ir_variable
*cull_distance_var
=
718 shader
->symbols
->get_variable("gl_CullDistance");
719 assert(cull_distance_var
);
720 *cull_distance_array_size
= cull_distance_var
->type
->length
;
722 /* From the ARB_cull_distance spec:
724 * It is a compile-time or link-time error for the set of shaders forming
725 * a program to have the sum of the sizes of the gl_ClipDistance and
726 * gl_CullDistance arrays to be larger than
727 * gl_MaxCombinedClipAndCullDistances.
729 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
730 ctx
->Const
.MaxClipPlanes
) {
731 linker_error(prog
, "%s shader: the combined size of "
732 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
734 "gl_MaxCombinedClipAndCullDistances (%u)",
735 _mesa_shader_stage_to_string(shader
->Stage
),
736 ctx
->Const
.MaxClipPlanes
);
743 * Verify that a vertex shader executable meets all semantic requirements.
745 * Also sets prog->Vert.ClipDistanceArraySize and
746 * prog->Vert.CullDistanceArraySize as a side effect.
748 * \param shader Vertex shader executable to be verified
751 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
752 struct gl_shader
*shader
,
753 struct gl_context
*ctx
)
758 /* From the GLSL 1.10 spec, page 48:
760 * "The variable gl_Position is available only in the vertex
761 * language and is intended for writing the homogeneous vertex
762 * position. All executions of a well-formed vertex shader
763 * executable must write a value into this variable. [...] The
764 * variable gl_Position is available only in the vertex
765 * language and is intended for writing the homogeneous vertex
766 * position. All executions of a well-formed vertex shader
767 * executable must write a value into this variable."
769 * while in GLSL 1.40 this text is changed to:
771 * "The variable gl_Position is available only in the vertex
772 * language and is intended for writing the homogeneous vertex
773 * position. It can be written at any time during shader
774 * execution. It may also be read back by a vertex shader
775 * after being written. This value will be used by primitive
776 * assembly, clipping, culling, and other fixed functionality
777 * operations, if present, that operate on primitives after
778 * vertex processing has occurred. Its value is undefined if
779 * the vertex shader executable does not write gl_Position."
781 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
782 * gl_Position is not an error.
784 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
785 find_assignment_visitor
find("gl_Position");
786 find
.run(shader
->ir
);
787 if (!find
.variable_found()) {
790 "vertex shader does not write to `gl_Position'."
791 "It's value is undefined. \n");
794 "vertex shader does not write to `gl_Position'. \n");
800 analyze_clip_cull_usage(prog
, shader
, ctx
,
801 &prog
->Vert
.ClipDistanceArraySize
,
802 &prog
->Vert
.CullDistanceArraySize
);
806 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
807 struct gl_shader
*shader
,
808 struct gl_context
*ctx
)
813 analyze_clip_cull_usage(prog
, shader
, ctx
,
814 &prog
->TessEval
.ClipDistanceArraySize
,
815 &prog
->TessEval
.CullDistanceArraySize
);
820 * Verify that a fragment shader executable meets all semantic requirements
822 * \param shader Fragment shader executable to be verified
825 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
826 struct gl_shader
*shader
)
831 find_assignment_visitor
frag_color("gl_FragColor");
832 find_assignment_visitor
frag_data("gl_FragData");
834 frag_color
.run(shader
->ir
);
835 frag_data
.run(shader
->ir
);
837 if (frag_color
.variable_found() && frag_data
.variable_found()) {
838 linker_error(prog
, "fragment shader writes to both "
839 "`gl_FragColor' and `gl_FragData'\n");
844 * Verify that a geometry shader executable meets all semantic requirements
846 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize and
847 * prog->Geom.CullDistanceArraySize as a side effect.
849 * \param shader Geometry shader executable to be verified
852 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
853 struct gl_shader
*shader
,
854 struct gl_context
*ctx
)
859 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
860 prog
->Geom
.VerticesIn
= num_vertices
;
862 analyze_clip_cull_usage(prog
, shader
, ctx
,
863 &prog
->Geom
.ClipDistanceArraySize
,
864 &prog
->Geom
.CullDistanceArraySize
);
868 * Check if geometry shaders emit to non-zero streams and do corresponding
872 validate_geometry_shader_emissions(struct gl_context
*ctx
,
873 struct gl_shader_program
*prog
)
875 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
876 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
877 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
878 if (emit_vertex
.error()) {
879 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
880 "stream parameter are in the range [0, %d].\n",
881 emit_vertex
.error_func(),
882 emit_vertex
.error_stream(),
883 ctx
->Const
.MaxVertexStreams
- 1);
885 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
886 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
888 /* From the ARB_gpu_shader5 spec:
890 * "Multiple vertex streams are supported only if the output primitive
891 * type is declared to be "points". A program will fail to link if it
892 * contains a geometry shader calling EmitStreamVertex() or
893 * EndStreamPrimitive() if its output primitive type is not "points".
895 * However, in the same spec:
897 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
898 * with <stream> set to zero."
902 * "The function EndPrimitive() is equivalent to calling
903 * EndStreamPrimitive() with <stream> set to zero."
905 * Since we can call EmitVertex() and EndPrimitive() when we output
906 * primitives other than points, calling EmitStreamVertex(0) or
907 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
908 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
909 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
912 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
913 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
914 "with n>0 requires point output\n");
920 validate_intrastage_arrays(struct gl_shader_program
*prog
,
921 ir_variable
*const var
,
922 ir_variable
*const existing
)
924 /* Consider the types to be "the same" if both types are arrays
925 * of the same type and one of the arrays is implicitly sized.
926 * In addition, set the type of the linked variable to the
927 * explicitly sized array.
929 if (var
->type
->is_array() && existing
->type
->is_array()) {
930 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
931 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
932 if (var
->type
->length
!= 0) {
933 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
934 linker_error(prog
, "%s `%s' declared as type "
935 "`%s' but outermost dimension has an index"
938 var
->name
, var
->type
->name
,
939 existing
->data
.max_array_access
);
941 existing
->type
= var
->type
;
943 } else if (existing
->type
->length
!= 0) {
944 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
945 !existing
->data
.from_ssbo_unsized_array
) {
946 linker_error(prog
, "%s `%s' declared as type "
947 "`%s' but outermost dimension has an index"
950 var
->name
, existing
->type
->name
,
951 var
->data
.max_array_access
);
956 /* The arrays of structs could have different glsl_type pointers but
957 * they are actually the same type. Use record_compare() to check that.
959 if (existing
->type
->fields
.array
->is_record() &&
960 var
->type
->fields
.array
->is_record() &&
961 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
970 * Perform validation of global variables used across multiple shaders
973 cross_validate_globals(struct gl_shader_program
*prog
,
974 struct gl_shader
**shader_list
,
975 unsigned num_shaders
,
978 /* Examine all of the uniforms in all of the shaders and cross validate
981 glsl_symbol_table variables
;
982 for (unsigned i
= 0; i
< num_shaders
; i
++) {
983 if (shader_list
[i
] == NULL
)
986 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
987 ir_variable
*const var
= node
->as_variable();
992 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
995 /* don't cross validate subroutine uniforms */
996 if (var
->type
->contains_subroutine())
999 /* Don't cross validate temporaries that are at global scope. These
1000 * will eventually get pulled into the shaders 'main'.
1002 if (var
->data
.mode
== ir_var_temporary
)
1005 /* If a global with this name has already been seen, verify that the
1006 * new instance has the same type. In addition, if the globals have
1007 * initializers, the values of the initializers must be the same.
1009 ir_variable
*const existing
= variables
.get_variable(var
->name
);
1010 if (existing
!= NULL
) {
1011 /* Check if types match. Interface blocks have some special
1012 * rules so we handle those elsewhere.
1014 if (var
->type
!= existing
->type
&&
1015 !var
->is_interface_instance()) {
1016 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
1017 if (var
->type
->is_record() && existing
->type
->is_record()
1018 && existing
->type
->record_compare(var
->type
)) {
1019 existing
->type
= var
->type
;
1021 /* If it is an unsized array in a Shader Storage Block,
1022 * two different shaders can access to different elements.
1023 * Because of that, they might be converted to different
1024 * sized arrays, then check that they are compatible but
1025 * ignore the array size.
1027 if (!(var
->data
.mode
== ir_var_shader_storage
&&
1028 var
->data
.from_ssbo_unsized_array
&&
1029 existing
->data
.mode
== ir_var_shader_storage
&&
1030 existing
->data
.from_ssbo_unsized_array
&&
1031 var
->type
->gl_type
== existing
->type
->gl_type
)) {
1032 linker_error(prog
, "%s `%s' declared as type "
1033 "`%s' and type `%s'\n",
1035 var
->name
, var
->type
->name
,
1036 existing
->type
->name
);
1043 if (var
->data
.explicit_location
) {
1044 if (existing
->data
.explicit_location
1045 && (var
->data
.location
!= existing
->data
.location
)) {
1046 linker_error(prog
, "explicit locations for %s "
1047 "`%s' have differing values\n",
1048 mode_string(var
), var
->name
);
1052 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
1053 linker_error(prog
, "explicit components for %s "
1054 "`%s' have differing values\n",
1055 mode_string(var
), var
->name
);
1059 existing
->data
.location
= var
->data
.location
;
1060 existing
->data
.explicit_location
= true;
1062 /* Check if uniform with implicit location was marked explicit
1063 * by earlier shader stage. If so, mark it explicit in this stage
1064 * too to make sure later processing does not treat it as
1067 if (existing
->data
.explicit_location
) {
1068 var
->data
.location
= existing
->data
.location
;
1069 var
->data
.explicit_location
= true;
1073 /* From the GLSL 4.20 specification:
1074 * "A link error will result if two compilation units in a program
1075 * specify different integer-constant bindings for the same
1076 * opaque-uniform name. However, it is not an error to specify a
1077 * binding on some but not all declarations for the same name"
1079 if (var
->data
.explicit_binding
) {
1080 if (existing
->data
.explicit_binding
&&
1081 var
->data
.binding
!= existing
->data
.binding
) {
1082 linker_error(prog
, "explicit bindings for %s "
1083 "`%s' have differing values\n",
1084 mode_string(var
), var
->name
);
1088 existing
->data
.binding
= var
->data
.binding
;
1089 existing
->data
.explicit_binding
= true;
1092 if (var
->type
->contains_atomic() &&
1093 var
->data
.offset
!= existing
->data
.offset
) {
1094 linker_error(prog
, "offset specifications for %s "
1095 "`%s' have differing values\n",
1096 mode_string(var
), var
->name
);
1100 /* Validate layout qualifiers for gl_FragDepth.
1102 * From the AMD/ARB_conservative_depth specs:
1104 * "If gl_FragDepth is redeclared in any fragment shader in a
1105 * program, it must be redeclared in all fragment shaders in
1106 * that program that have static assignments to
1107 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1108 * fragment shaders in a single program must have the same set
1111 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1112 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1113 bool layout_differs
=
1114 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1116 if (layout_declared
&& layout_differs
) {
1118 "All redeclarations of gl_FragDepth in all "
1119 "fragment shaders in a single program must have "
1120 "the same set of qualifiers.\n");
1123 if (var
->data
.used
&& layout_differs
) {
1125 "If gl_FragDepth is redeclared with a layout "
1126 "qualifier in any fragment shader, it must be "
1127 "redeclared with the same layout qualifier in "
1128 "all fragment shaders that have assignments to "
1133 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1135 * "If a shared global has multiple initializers, the
1136 * initializers must all be constant expressions, and they
1137 * must all have the same value. Otherwise, a link error will
1138 * result. (A shared global having only one initializer does
1139 * not require that initializer to be a constant expression.)"
1141 * Previous to 4.20 the GLSL spec simply said that initializers
1142 * must have the same value. In this case of non-constant
1143 * initializers, this was impossible to determine. As a result,
1144 * no vendor actually implemented that behavior. The 4.20
1145 * behavior matches the implemented behavior of at least one other
1146 * vendor, so we'll implement that for all GLSL versions.
1148 if (var
->constant_initializer
!= NULL
) {
1149 if (existing
->constant_initializer
!= NULL
) {
1150 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1151 linker_error(prog
, "initializers for %s "
1152 "`%s' have differing values\n",
1153 mode_string(var
), var
->name
);
1157 /* If the first-seen instance of a particular uniform did
1158 * not have an initializer but a later instance does,
1159 * replace the former with the later.
1161 variables
.replace_variable(existing
->name
, var
);
1165 if (var
->data
.has_initializer
) {
1166 if (existing
->data
.has_initializer
1167 && (var
->constant_initializer
== NULL
1168 || existing
->constant_initializer
== NULL
)) {
1170 "shared global variable `%s' has multiple "
1171 "non-constant initializers.\n",
1177 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1178 linker_error(prog
, "declarations for %s `%s' have "
1179 "mismatching invariant qualifiers\n",
1180 mode_string(var
), var
->name
);
1183 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1184 linker_error(prog
, "declarations for %s `%s' have "
1185 "mismatching centroid qualifiers\n",
1186 mode_string(var
), var
->name
);
1189 if (existing
->data
.sample
!= var
->data
.sample
) {
1190 linker_error(prog
, "declarations for %s `%s` have "
1191 "mismatching sample qualifiers\n",
1192 mode_string(var
), var
->name
);
1195 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1196 linker_error(prog
, "declarations for %s `%s` have "
1197 "mismatching image format qualifiers\n",
1198 mode_string(var
), var
->name
);
1202 variables
.add_variable(var
);
1209 * Perform validation of uniforms used across multiple shader stages
1212 cross_validate_uniforms(struct gl_shader_program
*prog
)
1214 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1215 MESA_SHADER_STAGES
, true);
1219 * Accumulates the array of buffer blocks and checks that all definitions of
1220 * blocks agree on their contents.
1223 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1226 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1227 struct gl_uniform_block
*blks
= NULL
;
1228 unsigned *num_blks
= validate_ssbo
? &prog
->NumShaderStorageBlocks
:
1229 &prog
->NumUniformBlocks
;
1231 unsigned max_num_buffer_blocks
= 0;
1232 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1233 if (prog
->_LinkedShaders
[i
]) {
1234 if (validate_ssbo
) {
1235 max_num_buffer_blocks
+=
1236 prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1238 max_num_buffer_blocks
+=
1239 prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1244 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1245 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1247 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1248 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1249 InterfaceBlockStageIndex
[i
][j
] = -1;
1254 unsigned sh_num_blocks
;
1255 struct gl_uniform_block
**sh_blks
;
1256 if (validate_ssbo
) {
1257 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1258 sh_blks
= sh
->ShaderStorageBlocks
;
1260 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1261 sh_blks
= sh
->UniformBlocks
;
1264 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1265 int index
= link_cross_validate_uniform_block(prog
, &blks
, num_blks
,
1269 linker_error(prog
, "buffer block `%s' has mismatching "
1270 "definitions\n", sh_blks
[j
]->Name
);
1272 for (unsigned k
= 0; k
<= i
; k
++) {
1273 delete[] InterfaceBlockStageIndex
[k
];
1278 InterfaceBlockStageIndex
[i
][index
] = j
;
1282 /* Update per stage block pointers to point to the program list.
1283 * FIXME: We should be able to free the per stage blocks here.
1285 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1286 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1287 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1289 if (stage_index
!= -1) {
1290 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1292 blks
[j
].stageref
|= (1 << i
);
1294 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1295 sh
->ShaderStorageBlocks
: sh
->UniformBlocks
;
1297 sh_blks
[stage_index
] = &blks
[j
];
1302 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1303 delete[] InterfaceBlockStageIndex
[i
];
1307 prog
->ShaderStorageBlocks
= blks
;
1309 prog
->UniformBlocks
= blks
;
1316 * Populates a shaders symbol table with all global declarations
1319 populate_symbol_table(gl_shader
*sh
)
1321 sh
->symbols
= new(sh
) glsl_symbol_table
;
1323 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1327 if ((func
= inst
->as_function()) != NULL
) {
1328 sh
->symbols
->add_function(func
);
1329 } else if ((var
= inst
->as_variable()) != NULL
) {
1330 if (var
->data
.mode
!= ir_var_temporary
)
1331 sh
->symbols
->add_variable(var
);
1338 * Remap variables referenced in an instruction tree
1340 * This is used when instruction trees are cloned from one shader and placed in
1341 * another. These trees will contain references to \c ir_variable nodes that
1342 * do not exist in the target shader. This function finds these \c ir_variable
1343 * references and replaces the references with matching variables in the target
1346 * If there is no matching variable in the target shader, a clone of the
1347 * \c ir_variable is made and added to the target shader. The new variable is
1348 * added to \b both the instruction stream and the symbol table.
1350 * \param inst IR tree that is to be processed.
1351 * \param symbols Symbol table containing global scope symbols in the
1353 * \param instructions Instruction stream where new variable declarations
1357 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1360 class remap_visitor
: public ir_hierarchical_visitor
{
1362 remap_visitor(struct gl_shader
*target
,
1365 this->target
= target
;
1366 this->symbols
= target
->symbols
;
1367 this->instructions
= target
->ir
;
1368 this->temps
= temps
;
1371 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1373 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1374 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1376 assert(var
!= NULL
);
1378 return visit_continue
;
1381 ir_variable
*const existing
=
1382 this->symbols
->get_variable(ir
->var
->name
);
1383 if (existing
!= NULL
)
1386 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1388 this->symbols
->add_variable(copy
);
1389 this->instructions
->push_head(copy
);
1393 return visit_continue
;
1397 struct gl_shader
*target
;
1398 glsl_symbol_table
*symbols
;
1399 exec_list
*instructions
;
1403 remap_visitor
v(target
, temps
);
1410 * Move non-declarations from one instruction stream to another
1412 * The intended usage pattern of this function is to pass the pointer to the
1413 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1414 * pointer) for \c last and \c false for \c make_copies on the first
1415 * call. Successive calls pass the return value of the previous call for
1416 * \c last and \c true for \c make_copies.
1418 * \param instructions Source instruction stream
1419 * \param last Instruction after which new instructions should be
1420 * inserted in the target instruction stream
1421 * \param make_copies Flag selecting whether instructions in \c instructions
1422 * should be copied (via \c ir_instruction::clone) into the
1423 * target list or moved.
1426 * The new "last" instruction in the target instruction stream. This pointer
1427 * is suitable for use as the \c last parameter of a later call to this
1431 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1432 bool make_copies
, gl_shader
*target
)
1434 hash_table
*temps
= NULL
;
1437 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1438 hash_table_pointer_compare
);
1440 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1441 if (inst
->as_function())
1444 ir_variable
*var
= inst
->as_variable();
1445 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1448 assert(inst
->as_assignment()
1450 || inst
->as_if() /* for initializers with the ?: operator */
1451 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1454 inst
= inst
->clone(target
, NULL
);
1457 hash_table_insert(temps
, inst
, var
);
1459 remap_variables(inst
, target
, temps
);
1464 last
->insert_after(inst
);
1469 hash_table_dtor(temps
);
1476 * This class is only used in link_intrastage_shaders() below but declaring
1477 * it inside that function leads to compiler warnings with some versions of
1480 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1482 array_sizing_visitor()
1483 : mem_ctx(ralloc_context(NULL
)),
1484 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1485 hash_table_pointer_compare
))
1489 ~array_sizing_visitor()
1491 hash_table_dtor(this->unnamed_interfaces
);
1492 ralloc_free(this->mem_ctx
);
1495 virtual ir_visitor_status
visit(ir_variable
*var
)
1497 const glsl_type
*type_without_array
;
1498 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1499 fixup_type(&var
->type
, var
->data
.max_array_access
,
1500 var
->data
.from_ssbo_unsized_array
,
1501 &implicit_sized_array
);
1502 var
->data
.implicit_sized_array
= implicit_sized_array
;
1503 type_without_array
= var
->type
->without_array();
1504 if (var
->type
->is_interface()) {
1505 if (interface_contains_unsized_arrays(var
->type
)) {
1506 const glsl_type
*new_type
=
1507 resize_interface_members(var
->type
,
1508 var
->get_max_ifc_array_access(),
1509 var
->is_in_shader_storage_block());
1510 var
->type
= new_type
;
1511 var
->change_interface_type(new_type
);
1513 } else if (type_without_array
->is_interface()) {
1514 if (interface_contains_unsized_arrays(type_without_array
)) {
1515 const glsl_type
*new_type
=
1516 resize_interface_members(type_without_array
,
1517 var
->get_max_ifc_array_access(),
1518 var
->is_in_shader_storage_block());
1519 var
->change_interface_type(new_type
);
1520 var
->type
= update_interface_members_array(var
->type
, new_type
);
1522 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1523 /* Store a pointer to the variable in the unnamed_interfaces
1526 ir_variable
**interface_vars
= (ir_variable
**)
1527 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1528 if (interface_vars
== NULL
) {
1529 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1531 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1534 unsigned index
= ifc_type
->field_index(var
->name
);
1535 assert(index
< ifc_type
->length
);
1536 assert(interface_vars
[index
] == NULL
);
1537 interface_vars
[index
] = var
;
1539 return visit_continue
;
1543 * For each unnamed interface block that was discovered while running the
1544 * visitor, adjust the interface type to reflect the newly assigned array
1545 * sizes, and fix up the ir_variable nodes to point to the new interface
1548 void fixup_unnamed_interface_types()
1550 hash_table_call_foreach(this->unnamed_interfaces
,
1551 fixup_unnamed_interface_type
, NULL
);
1556 * If the type pointed to by \c type represents an unsized array, replace
1557 * it with a sized array whose size is determined by max_array_access.
1559 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1560 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1562 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1563 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1564 max_array_access
+ 1);
1565 *implicit_sized
= true;
1566 assert(*type
!= NULL
);
1570 static const glsl_type
*
1571 update_interface_members_array(const glsl_type
*type
,
1572 const glsl_type
*new_interface_type
)
1574 const glsl_type
*element_type
= type
->fields
.array
;
1575 if (element_type
->is_array()) {
1576 const glsl_type
*new_array_type
=
1577 update_interface_members_array(element_type
, new_interface_type
);
1578 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1580 return glsl_type::get_array_instance(new_interface_type
,
1586 * Determine whether the given interface type contains unsized arrays (if
1587 * it doesn't, array_sizing_visitor doesn't need to process it).
1589 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1591 for (unsigned i
= 0; i
< type
->length
; i
++) {
1592 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1593 if (elem_type
->is_unsized_array())
1600 * Create a new interface type based on the given type, with unsized arrays
1601 * replaced by sized arrays whose size is determined by
1602 * max_ifc_array_access.
1604 static const glsl_type
*
1605 resize_interface_members(const glsl_type
*type
,
1606 const int *max_ifc_array_access
,
1609 unsigned num_fields
= type
->length
;
1610 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1611 memcpy(fields
, type
->fields
.structure
,
1612 num_fields
* sizeof(*fields
));
1613 for (unsigned i
= 0; i
< num_fields
; i
++) {
1614 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1615 /* If SSBO last member is unsized array, we don't replace it by a sized
1618 if (is_ssbo
&& i
== (num_fields
- 1))
1619 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1620 true, &implicit_sized_array
);
1622 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1623 false, &implicit_sized_array
);
1624 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1626 glsl_interface_packing packing
=
1627 (glsl_interface_packing
) type
->interface_packing
;
1628 const glsl_type
*new_ifc_type
=
1629 glsl_type::get_interface_instance(fields
, num_fields
,
1630 packing
, type
->name
);
1632 return new_ifc_type
;
1635 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1638 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1639 ir_variable
**interface_vars
= (ir_variable
**) data
;
1640 unsigned num_fields
= ifc_type
->length
;
1641 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1642 memcpy(fields
, ifc_type
->fields
.structure
,
1643 num_fields
* sizeof(*fields
));
1644 bool interface_type_changed
= false;
1645 for (unsigned i
= 0; i
< num_fields
; i
++) {
1646 if (interface_vars
[i
] != NULL
&&
1647 fields
[i
].type
!= interface_vars
[i
]->type
) {
1648 fields
[i
].type
= interface_vars
[i
]->type
;
1649 interface_type_changed
= true;
1652 if (!interface_type_changed
) {
1656 glsl_interface_packing packing
=
1657 (glsl_interface_packing
) ifc_type
->interface_packing
;
1658 const glsl_type
*new_ifc_type
=
1659 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1662 for (unsigned i
= 0; i
< num_fields
; i
++) {
1663 if (interface_vars
[i
] != NULL
)
1664 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1669 * Memory context used to allocate the data in \c unnamed_interfaces.
1674 * Hash table from const glsl_type * to an array of ir_variable *'s
1675 * pointing to the ir_variables constituting each unnamed interface block.
1677 hash_table
*unnamed_interfaces
;
1681 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1685 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1686 struct gl_shader_program
*prog
,
1687 struct gl_shader
*linked_shader
,
1688 struct gl_shader
**shader_list
,
1689 unsigned num_shaders
)
1691 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1692 linked_shader
->TransformFeedback
.BufferStride
[i
] = 0;
1695 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1696 struct gl_shader
*shader
= shader_list
[i
];
1698 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1699 if (shader
->TransformFeedback
.BufferStride
[j
]) {
1700 if (linked_shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1701 shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1702 linked_shader
->TransformFeedback
.BufferStride
[j
] !=
1703 shader
->TransformFeedback
.BufferStride
[j
]) {
1705 "intrastage shaders defined with conflicting "
1706 "xfb_stride for buffer %d (%d and %d)\n", j
,
1707 linked_shader
->TransformFeedback
.BufferStride
[j
],
1708 shader
->TransformFeedback
.BufferStride
[j
]);
1712 if (shader
->TransformFeedback
.BufferStride
[j
])
1713 linked_shader
->TransformFeedback
.BufferStride
[j
] =
1714 shader
->TransformFeedback
.BufferStride
[j
];
1719 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1720 if (linked_shader
->TransformFeedback
.BufferStride
[j
]) {
1721 prog
->TransformFeedback
.BufferStride
[j
] =
1722 linked_shader
->TransformFeedback
.BufferStride
[j
];
1724 /* We will validate doubles at a later stage */
1725 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1726 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1727 "multiple of 4 or if its applied to a type that is "
1728 "or contains a double a multiple of 8.",
1729 prog
->TransformFeedback
.BufferStride
[j
]);
1733 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1734 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1736 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1737 "limit has been exceeded.");
1745 * Performs the cross-validation of tessellation control shader vertices and
1746 * layout qualifiers for the attached tessellation control shaders,
1747 * and propagates them to the linked TCS and linked shader program.
1750 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1751 struct gl_shader
*linked_shader
,
1752 struct gl_shader
**shader_list
,
1753 unsigned num_shaders
)
1755 linked_shader
->TessCtrl
.VerticesOut
= 0;
1757 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1760 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1762 * "All tessellation control shader layout declarations in a program
1763 * must specify the same output patch vertex count. There must be at
1764 * least one layout qualifier specifying an output patch vertex count
1765 * in any program containing tessellation control shaders; however,
1766 * such a declaration is not required in all tessellation control
1770 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1771 struct gl_shader
*shader
= shader_list
[i
];
1773 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1774 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1775 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1776 linker_error(prog
, "tessellation control shader defined with "
1777 "conflicting output vertex count (%d and %d)\n",
1778 linked_shader
->TessCtrl
.VerticesOut
,
1779 shader
->TessCtrl
.VerticesOut
);
1782 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1786 /* Just do the intrastage -> interstage propagation right now,
1787 * since we already know we're in the right type of shader program
1790 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1791 linker_error(prog
, "tessellation control shader didn't declare "
1792 "vertices out layout qualifier\n");
1795 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1800 * Performs the cross-validation of tessellation evaluation shader
1801 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1802 * for the attached tessellation evaluation shaders, and propagates them
1803 * to the linked TES and linked shader program.
1806 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1807 struct gl_shader
*linked_shader
,
1808 struct gl_shader
**shader_list
,
1809 unsigned num_shaders
)
1811 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1812 linked_shader
->TessEval
.Spacing
= 0;
1813 linked_shader
->TessEval
.VertexOrder
= 0;
1814 linked_shader
->TessEval
.PointMode
= -1;
1816 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1819 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1821 * "At least one tessellation evaluation shader (compilation unit) in
1822 * a program must declare a primitive mode in its input layout.
1823 * Declaration vertex spacing, ordering, and point mode identifiers is
1824 * optional. It is not required that all tessellation evaluation
1825 * shaders in a program declare a primitive mode. If spacing or
1826 * vertex ordering declarations are omitted, the tessellation
1827 * primitive generator will use equal spacing or counter-clockwise
1828 * vertex ordering, respectively. If a point mode declaration is
1829 * omitted, the tessellation primitive generator will produce lines or
1830 * triangles according to the primitive mode."
1833 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1834 struct gl_shader
*shader
= shader_list
[i
];
1836 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1837 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1838 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1839 linker_error(prog
, "tessellation evaluation shader defined with "
1840 "conflicting input primitive modes.\n");
1843 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1846 if (shader
->TessEval
.Spacing
!= 0) {
1847 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1848 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1849 linker_error(prog
, "tessellation evaluation shader defined with "
1850 "conflicting vertex spacing.\n");
1853 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1856 if (shader
->TessEval
.VertexOrder
!= 0) {
1857 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1858 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1859 linker_error(prog
, "tessellation evaluation shader defined with "
1860 "conflicting ordering.\n");
1863 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1866 if (shader
->TessEval
.PointMode
!= -1) {
1867 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1868 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1869 linker_error(prog
, "tessellation evaluation shader defined with "
1870 "conflicting point modes.\n");
1873 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1878 /* Just do the intrastage -> interstage propagation right now,
1879 * since we already know we're in the right type of shader program
1882 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1884 "tessellation evaluation shader didn't declare input "
1885 "primitive modes.\n");
1888 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1890 if (linked_shader
->TessEval
.Spacing
== 0)
1891 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1892 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1894 if (linked_shader
->TessEval
.VertexOrder
== 0)
1895 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1896 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1898 if (linked_shader
->TessEval
.PointMode
== -1)
1899 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1900 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1905 * Performs the cross-validation of layout qualifiers specified in
1906 * redeclaration of gl_FragCoord for the attached fragment shaders,
1907 * and propagates them to the linked FS and linked shader program.
1910 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1911 struct gl_shader
*linked_shader
,
1912 struct gl_shader
**shader_list
,
1913 unsigned num_shaders
)
1915 linked_shader
->redeclares_gl_fragcoord
= false;
1916 linked_shader
->uses_gl_fragcoord
= false;
1917 linked_shader
->origin_upper_left
= false;
1918 linked_shader
->pixel_center_integer
= false;
1920 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1921 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1924 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1925 struct gl_shader
*shader
= shader_list
[i
];
1926 /* From the GLSL 1.50 spec, page 39:
1928 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1929 * it must be redeclared in all the fragment shaders in that program
1930 * that have a static use gl_FragCoord."
1932 if ((linked_shader
->redeclares_gl_fragcoord
1933 && !shader
->redeclares_gl_fragcoord
1934 && shader
->uses_gl_fragcoord
)
1935 || (shader
->redeclares_gl_fragcoord
1936 && !linked_shader
->redeclares_gl_fragcoord
1937 && linked_shader
->uses_gl_fragcoord
)) {
1938 linker_error(prog
, "fragment shader defined with conflicting "
1939 "layout qualifiers for gl_FragCoord\n");
1942 /* From the GLSL 1.50 spec, page 39:
1944 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1945 * single program must have the same set of qualifiers."
1947 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1948 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1949 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1950 linker_error(prog
, "fragment shader defined with conflicting "
1951 "layout qualifiers for gl_FragCoord\n");
1954 /* Update the linked shader state. Note that uses_gl_fragcoord should
1955 * accumulate the results. The other values should replace. If there
1956 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1957 * are already known to be the same.
1959 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1960 linked_shader
->redeclares_gl_fragcoord
=
1961 shader
->redeclares_gl_fragcoord
;
1962 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1963 || shader
->uses_gl_fragcoord
;
1964 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1965 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1968 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1973 * Performs the cross-validation of geometry shader max_vertices and
1974 * primitive type layout qualifiers for the attached geometry shaders,
1975 * and propagates them to the linked GS and linked shader program.
1978 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1979 struct gl_shader
*linked_shader
,
1980 struct gl_shader
**shader_list
,
1981 unsigned num_shaders
)
1983 linked_shader
->Geom
.VerticesOut
= -1;
1984 linked_shader
->Geom
.Invocations
= 0;
1985 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1986 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1988 /* No in/out qualifiers defined for anything but GLSL 1.50+
1989 * geometry shaders so far.
1991 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1994 /* From the GLSL 1.50 spec, page 46:
1996 * "All geometry shader output layout declarations in a program
1997 * must declare the same layout and same value for
1998 * max_vertices. There must be at least one geometry output
1999 * layout declaration somewhere in a program, but not all
2000 * geometry shaders (compilation units) are required to
2004 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2005 struct gl_shader
*shader
= shader_list
[i
];
2007 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
2008 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
2009 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
2010 linker_error(prog
, "geometry shader defined with conflicting "
2014 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
2017 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
2018 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
2019 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
2020 linker_error(prog
, "geometry shader defined with conflicting "
2024 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
2027 if (shader
->Geom
.VerticesOut
!= -1) {
2028 if (linked_shader
->Geom
.VerticesOut
!= -1 &&
2029 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
2030 linker_error(prog
, "geometry shader defined with conflicting "
2031 "output vertex count (%d and %d)\n",
2032 linked_shader
->Geom
.VerticesOut
,
2033 shader
->Geom
.VerticesOut
);
2036 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
2039 if (shader
->Geom
.Invocations
!= 0) {
2040 if (linked_shader
->Geom
.Invocations
!= 0 &&
2041 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
2042 linker_error(prog
, "geometry shader defined with conflicting "
2043 "invocation count (%d and %d)\n",
2044 linked_shader
->Geom
.Invocations
,
2045 shader
->Geom
.Invocations
);
2048 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
2052 /* Just do the intrastage -> interstage propagation right now,
2053 * since we already know we're in the right type of shader program
2056 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
2058 "geometry shader didn't declare primitive input type\n");
2061 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
2063 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
2065 "geometry shader didn't declare primitive output type\n");
2068 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
2070 if (linked_shader
->Geom
.VerticesOut
== -1) {
2072 "geometry shader didn't declare max_vertices\n");
2075 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
2077 if (linked_shader
->Geom
.Invocations
== 0)
2078 linked_shader
->Geom
.Invocations
= 1;
2080 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
2085 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2086 * qualifiers for the attached compute shaders, and propagate them to the
2087 * linked CS and linked shader program.
2090 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2091 struct gl_shader
*linked_shader
,
2092 struct gl_shader
**shader_list
,
2093 unsigned num_shaders
)
2095 for (int i
= 0; i
< 3; i
++)
2096 linked_shader
->Comp
.LocalSize
[i
] = 0;
2098 /* This function is called for all shader stages, but it only has an effect
2099 * for compute shaders.
2101 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2104 /* From the ARB_compute_shader spec, in the section describing local size
2107 * If multiple compute shaders attached to a single program object
2108 * declare local work-group size, the declarations must be identical;
2109 * otherwise a link-time error results. Furthermore, if a program
2110 * object contains any compute shaders, at least one must contain an
2111 * input layout qualifier specifying the local work sizes of the
2112 * program, or a link-time error will occur.
2114 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2115 struct gl_shader
*shader
= shader_list
[sh
];
2117 if (shader
->Comp
.LocalSize
[0] != 0) {
2118 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
2119 for (int i
= 0; i
< 3; i
++) {
2120 if (linked_shader
->Comp
.LocalSize
[i
] !=
2121 shader
->Comp
.LocalSize
[i
]) {
2122 linker_error(prog
, "compute shader defined with conflicting "
2128 for (int i
= 0; i
< 3; i
++)
2129 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
2133 /* Just do the intrastage -> interstage propagation right now,
2134 * since we already know we're in the right type of shader program
2137 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
2138 linker_error(prog
, "compute shader didn't declare local size\n");
2141 for (int i
= 0; i
< 3; i
++)
2142 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
2147 * Combine a group of shaders for a single stage to generate a linked shader
2150 * If this function is supplied a single shader, it is cloned, and the new
2151 * shader is returned.
2153 static struct gl_shader
*
2154 link_intrastage_shaders(void *mem_ctx
,
2155 struct gl_context
*ctx
,
2156 struct gl_shader_program
*prog
,
2157 struct gl_shader
**shader_list
,
2158 unsigned num_shaders
)
2160 struct gl_uniform_block
*ubo_blocks
= NULL
;
2161 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2162 unsigned num_ubo_blocks
= 0;
2163 unsigned num_ssbo_blocks
= 0;
2165 /* Check that global variables defined in multiple shaders are consistent.
2167 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
2168 if (!prog
->LinkStatus
)
2171 /* Check that interface blocks defined in multiple shaders are consistent.
2173 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2175 if (!prog
->LinkStatus
)
2178 /* Check that there is only a single definition of each function signature
2179 * across all shaders.
2181 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2182 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2183 ir_function
*const f
= node
->as_function();
2188 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2189 ir_function
*const other
=
2190 shader_list
[j
]->symbols
->get_function(f
->name
);
2192 /* If the other shader has no function (and therefore no function
2193 * signatures) with the same name, skip to the next shader.
2198 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2199 if (!sig
->is_defined
|| sig
->is_builtin())
2202 ir_function_signature
*other_sig
=
2203 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2205 if ((other_sig
!= NULL
) && other_sig
->is_defined
2206 && !other_sig
->is_builtin()) {
2207 linker_error(prog
, "function `%s' is multiply defined\n",
2216 /* Find the shader that defines main, and make a clone of it.
2218 * Starting with the clone, search for undefined references. If one is
2219 * found, find the shader that defines it. Clone the reference and add
2220 * it to the shader. Repeat until there are no undefined references or
2221 * until a reference cannot be resolved.
2223 gl_shader
*main
= NULL
;
2224 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2225 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2226 main
= shader_list
[i
];
2232 linker_error(prog
, "%s shader lacks `main'\n",
2233 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2237 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2238 linked
->ir
= new(linked
) exec_list
;
2239 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2241 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2242 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2243 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2244 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2245 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2246 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2249 populate_symbol_table(linked
);
2251 /* The pointer to the main function in the final linked shader (i.e., the
2252 * copy of the original shader that contained the main function).
2254 ir_function_signature
*const main_sig
=
2255 _mesa_get_main_function_signature(linked
);
2257 /* Move any instructions other than variable declarations or function
2258 * declarations into main.
2260 exec_node
*insertion_point
=
2261 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2264 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2265 if (shader_list
[i
] == main
)
2268 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2269 insertion_point
, true, linked
);
2272 /* Check if any shader needs built-in functions. */
2273 bool need_builtins
= false;
2274 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2275 if (shader_list
[i
]->uses_builtin_functions
) {
2276 need_builtins
= true;
2282 if (need_builtins
) {
2283 /* Make a temporary array one larger than shader_list, which will hold
2284 * the built-in function shader as well.
2286 gl_shader
**linking_shaders
= (gl_shader
**)
2287 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2289 ok
= linking_shaders
!= NULL
;
2292 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2293 _mesa_glsl_initialize_builtin_functions();
2294 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2296 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2298 free(linking_shaders
);
2300 _mesa_error_no_memory(__func__
);
2303 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2308 _mesa_delete_shader(ctx
, linked
);
2312 /* Make a pass over all variable declarations to ensure that arrays with
2313 * unspecified sizes have a size specified. The size is inferred from the
2314 * max_array_access field.
2316 array_sizing_visitor v
;
2318 v
.fixup_unnamed_interface_types();
2320 /* Link up uniform blocks defined within this stage. */
2321 link_uniform_blocks(mem_ctx
, ctx
, prog
, &linked
, 1,
2322 &ubo_blocks
, &num_ubo_blocks
, &ssbo_blocks
,
2325 if (!prog
->LinkStatus
) {
2326 _mesa_delete_shader(ctx
, linked
);
2330 /* Copy ubo blocks to linked shader list */
2331 linked
->UniformBlocks
=
2332 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2333 ralloc_steal(linked
, ubo_blocks
);
2334 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2335 linked
->UniformBlocks
[i
] = &ubo_blocks
[i
];
2337 linked
->NumUniformBlocks
= num_ubo_blocks
;
2339 /* Copy ssbo blocks to linked shader list */
2340 linked
->ShaderStorageBlocks
=
2341 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2342 ralloc_steal(linked
, ssbo_blocks
);
2343 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2344 linked
->ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2346 linked
->NumShaderStorageBlocks
= num_ssbo_blocks
;
2348 /* At this point linked should contain all of the linked IR, so
2349 * validate it to make sure nothing went wrong.
2351 validate_ir_tree(linked
->ir
);
2353 /* Set the size of geometry shader input arrays */
2354 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2355 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2356 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2357 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2358 ir
->accept(&input_resize_visitor
);
2362 if (ctx
->Const
.VertexID_is_zero_based
)
2363 lower_vertex_id(linked
);
2365 /* Validate correct usage of barrier() in the tess control shader */
2366 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2367 barrier_use_visitor
visitor(prog
);
2368 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2369 ir
->accept(&visitor
);
2377 * Update the sizes of linked shader uniform arrays to the maximum
2380 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2382 * If one or more elements of an array are active,
2383 * GetActiveUniform will return the name of the array in name,
2384 * subject to the restrictions listed above. The type of the array
2385 * is returned in type. The size parameter contains the highest
2386 * array element index used, plus one. The compiler or linker
2387 * determines the highest index used. There will be only one
2388 * active uniform reported by the GL per uniform array.
2392 update_array_sizes(struct gl_shader_program
*prog
)
2394 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2395 if (prog
->_LinkedShaders
[i
] == NULL
)
2398 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2399 ir_variable
*const var
= node
->as_variable();
2401 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2402 !var
->type
->is_array())
2405 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2406 * will not be eliminated. Since we always do std140, just
2407 * don't resize arrays in UBOs.
2409 * Atomic counters are supposed to get deterministic
2410 * locations assigned based on the declaration ordering and
2411 * sizes, array compaction would mess that up.
2413 * Subroutine uniforms are not removed.
2415 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2416 var
->type
->contains_subroutine() || var
->constant_initializer
)
2419 int size
= var
->data
.max_array_access
;
2420 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2421 if (prog
->_LinkedShaders
[j
] == NULL
)
2424 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2425 ir_variable
*other_var
= node2
->as_variable();
2429 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2430 other_var
->data
.max_array_access
> size
) {
2431 size
= other_var
->data
.max_array_access
;
2436 if (size
+ 1 != (int)var
->type
->length
) {
2437 /* If this is a built-in uniform (i.e., it's backed by some
2438 * fixed-function state), adjust the number of state slots to
2439 * match the new array size. The number of slots per array entry
2440 * is not known. It seems safe to assume that the total number of
2441 * slots is an integer multiple of the number of array elements.
2442 * Determine the number of slots per array element by dividing by
2443 * the old (total) size.
2445 const unsigned num_slots
= var
->get_num_state_slots();
2446 if (num_slots
> 0) {
2447 var
->set_num_state_slots((size
+ 1)
2448 * (num_slots
/ var
->type
->length
));
2451 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2453 /* FINISHME: We should update the types of array
2454 * dereferences of this variable now.
2462 * Resize tessellation evaluation per-vertex inputs to the size of
2463 * tessellation control per-vertex outputs.
2466 resize_tes_inputs(struct gl_context
*ctx
,
2467 struct gl_shader_program
*prog
)
2469 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2472 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2473 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2475 /* If no control shader is present, then the TES inputs are statically
2476 * sized to MaxPatchVertices; the actual size of the arrays won't be
2477 * known until draw time.
2479 const int num_vertices
= tcs
2480 ? tcs
->TessCtrl
.VerticesOut
2481 : ctx
->Const
.MaxPatchVertices
;
2483 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2484 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2485 ir
->accept(&input_resize_visitor
);
2489 /* Convert the gl_PatchVerticesIn system value into a constant, since
2490 * the value is known at this point.
2492 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2493 ir_variable
*var
= ir
->as_variable();
2494 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2495 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2496 void *mem_ctx
= ralloc_parent(var
);
2497 var
->data
.mode
= ir_var_auto
;
2498 var
->data
.location
= 0;
2499 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2506 * Find a contiguous set of available bits in a bitmask.
2508 * \param used_mask Bits representing used (1) and unused (0) locations
2509 * \param needed_count Number of contiguous bits needed.
2512 * Base location of the available bits on success or -1 on failure.
2515 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2517 unsigned needed_mask
= (1 << needed_count
) - 1;
2518 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2520 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2521 * cannot optimize possibly infinite loops" for the loop below.
2523 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2526 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2527 if ((needed_mask
& ~used_mask
) == needed_mask
)
2538 * Assign locations for either VS inputs or FS outputs
2540 * \param prog Shader program whose variables need locations assigned
2541 * \param constants Driver specific constant values for the program.
2542 * \param target_index Selector for the program target to receive location
2543 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2544 * \c MESA_SHADER_FRAGMENT.
2547 * If locations are successfully assigned, true is returned. Otherwise an
2548 * error is emitted to the shader link log and false is returned.
2551 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2552 struct gl_constants
*constants
,
2553 unsigned target_index
)
2555 /* Maximum number of generic locations. This corresponds to either the
2556 * maximum number of draw buffers or the maximum number of generic
2559 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2560 constants
->Program
[target_index
].MaxAttribs
:
2561 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2563 /* Mark invalid locations as being used.
2565 unsigned used_locations
= (max_index
>= 32)
2566 ? ~0 : ~((1 << max_index
) - 1);
2567 unsigned double_storage_locations
= 0;
2569 assert((target_index
== MESA_SHADER_VERTEX
)
2570 || (target_index
== MESA_SHADER_FRAGMENT
));
2572 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2576 /* Operate in a total of four passes.
2578 * 1. Invalidate the location assignments for all vertex shader inputs.
2580 * 2. Assign locations for inputs that have user-defined (via
2581 * glBindVertexAttribLocation) locations and outputs that have
2582 * user-defined locations (via glBindFragDataLocation).
2584 * 3. Sort the attributes without assigned locations by number of slots
2585 * required in decreasing order. Fragmentation caused by attribute
2586 * locations assigned by the application may prevent large attributes
2587 * from having enough contiguous space.
2589 * 4. Assign locations to any inputs without assigned locations.
2592 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2593 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2595 const enum ir_variable_mode direction
=
2596 (target_index
== MESA_SHADER_VERTEX
)
2597 ? ir_var_shader_in
: ir_var_shader_out
;
2600 /* Temporary storage for the set of attributes that need locations assigned.
2606 /* Used below in the call to qsort. */
2607 static int compare(const void *a
, const void *b
)
2609 const temp_attr
*const l
= (const temp_attr
*) a
;
2610 const temp_attr
*const r
= (const temp_attr
*) b
;
2612 /* Reversed because we want a descending order sort below. */
2613 return r
->slots
- l
->slots
;
2616 assert(max_index
<= 32);
2618 /* Temporary array for the set of attributes that have locations assigned.
2620 ir_variable
*assigned
[16];
2622 unsigned num_attr
= 0;
2623 unsigned assigned_attr
= 0;
2625 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2626 ir_variable
*const var
= node
->as_variable();
2628 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2631 if (var
->data
.explicit_location
) {
2632 var
->data
.is_unmatched_generic_inout
= 0;
2633 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2634 || (var
->data
.location
< 0)) {
2636 "invalid explicit location %d specified for `%s'\n",
2637 (var
->data
.location
< 0)
2638 ? var
->data
.location
2639 : var
->data
.location
- generic_base
,
2643 } else if (target_index
== MESA_SHADER_VERTEX
) {
2646 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2647 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2648 var
->data
.location
= binding
;
2649 var
->data
.is_unmatched_generic_inout
= 0;
2651 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2655 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2656 assert(binding
>= FRAG_RESULT_DATA0
);
2657 var
->data
.location
= binding
;
2658 var
->data
.is_unmatched_generic_inout
= 0;
2660 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2661 var
->data
.index
= index
;
2666 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2668 * "Output binding assignments will cause LinkProgram to fail:
2670 * If the program has an active output assigned to a location greater
2671 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2672 * an active output assigned an index greater than or equal to one;"
2674 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2675 var
->data
.location
- generic_base
>=
2676 (int) constants
->MaxDualSourceDrawBuffers
) {
2678 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2679 "with index %u for %s\n",
2680 var
->data
.location
- generic_base
, var
->data
.index
,
2685 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2687 /* If the variable is not a built-in and has a location statically
2688 * assigned in the shader (presumably via a layout qualifier), make sure
2689 * that it doesn't collide with other assigned locations. Otherwise,
2690 * add it to the list of variables that need linker-assigned locations.
2692 if (var
->data
.location
!= -1) {
2693 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2694 /* From page 61 of the OpenGL 4.0 spec:
2696 * "LinkProgram will fail if the attribute bindings assigned
2697 * by BindAttribLocation do not leave not enough space to
2698 * assign a location for an active matrix attribute or an
2699 * active attribute array, both of which require multiple
2700 * contiguous generic attributes."
2702 * I think above text prohibits the aliasing of explicit and
2703 * automatic assignments. But, aliasing is allowed in manual
2704 * assignments of attribute locations. See below comments for
2707 * From OpenGL 4.0 spec, page 61:
2709 * "It is possible for an application to bind more than one
2710 * attribute name to the same location. This is referred to as
2711 * aliasing. This will only work if only one of the aliased
2712 * attributes is active in the executable program, or if no
2713 * path through the shader consumes more than one attribute of
2714 * a set of attributes aliased to the same location. A link
2715 * error can occur if the linker determines that every path
2716 * through the shader consumes multiple aliased attributes,
2717 * but implementations are not required to generate an error
2720 * From GLSL 4.30 spec, page 54:
2722 * "A program will fail to link if any two non-vertex shader
2723 * input variables are assigned to the same location. For
2724 * vertex shaders, multiple input variables may be assigned
2725 * to the same location using either layout qualifiers or via
2726 * the OpenGL API. However, such aliasing is intended only to
2727 * support vertex shaders where each execution path accesses
2728 * at most one input per each location. Implementations are
2729 * permitted, but not required, to generate link-time errors
2730 * if they detect that every path through the vertex shader
2731 * executable accesses multiple inputs assigned to any single
2732 * location. For all shader types, a program will fail to link
2733 * if explicit location assignments leave the linker unable
2734 * to find space for other variables without explicit
2737 * From OpenGL ES 3.0 spec, page 56:
2739 * "Binding more than one attribute name to the same location
2740 * is referred to as aliasing, and is not permitted in OpenGL
2741 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2742 * fail when this condition exists. However, aliasing is
2743 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2744 * This will only work if only one of the aliased attributes
2745 * is active in the executable program, or if no path through
2746 * the shader consumes more than one attribute of a set of
2747 * attributes aliased to the same location. A link error can
2748 * occur if the linker determines that every path through the
2749 * shader consumes multiple aliased attributes, but implemen-
2750 * tations are not required to generate an error in this case."
2752 * After looking at above references from OpenGL, OpenGL ES and
2753 * GLSL specifications, we allow aliasing of vertex input variables
2754 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2756 * NOTE: This is not required by the spec but its worth mentioning
2757 * here that we're not doing anything to make sure that no path
2758 * through the vertex shader executable accesses multiple inputs
2759 * assigned to any single location.
2762 /* Mask representing the contiguous slots that will be used by
2765 const unsigned attr
= var
->data
.location
- generic_base
;
2766 const unsigned use_mask
= (1 << slots
) - 1;
2767 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2768 ? "vertex shader input" : "fragment shader output";
2770 /* Generate a link error if the requested locations for this
2771 * attribute exceed the maximum allowed attribute location.
2773 if (attr
+ slots
> max_index
) {
2775 "insufficient contiguous locations "
2776 "available for %s `%s' %d %d %d\n", string
,
2777 var
->name
, used_locations
, use_mask
, attr
);
2781 /* Generate a link error if the set of bits requested for this
2782 * attribute overlaps any previously allocated bits.
2784 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2785 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2786 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2789 * "Additionally, for fragment shader outputs, if two
2790 * variables are placed within the same location, they
2791 * must have the same underlying type (floating-point or
2792 * integer). No component aliasing of output variables or
2793 * members is allowed.
2795 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2796 unsigned assigned_slots
=
2797 assigned
[i
]->type
->count_attribute_slots(false);
2798 unsigned assig_attr
=
2799 assigned
[i
]->data
.location
- generic_base
;
2800 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2802 if ((assigned_use_mask
<< assig_attr
) &
2803 (use_mask
<< attr
)) {
2805 const glsl_type
*assigned_type
=
2806 assigned
[i
]->type
->without_array();
2807 const glsl_type
*type
= var
->type
->without_array();
2808 if (assigned_type
->base_type
!= type
->base_type
) {
2809 linker_error(prog
, "types do not match for aliased"
2810 " %ss %s and %s\n", string
,
2811 assigned
[i
]->name
, var
->name
);
2815 unsigned assigned_component_mask
=
2816 ((1 << assigned_type
->vector_elements
) - 1) <<
2817 assigned
[i
]->data
.location_frac
;
2818 unsigned component_mask
=
2819 ((1 << type
->vector_elements
) - 1) <<
2820 var
->data
.location_frac
;
2821 if (assigned_component_mask
& component_mask
) {
2822 linker_error(prog
, "overlapping component is "
2823 "assigned to %ss %s and %s "
2825 string
, assigned
[i
]->name
, var
->name
,
2826 var
->data
.location_frac
);
2831 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2832 (prog
->IsES
&& prog
->Version
>= 300)) {
2833 linker_error(prog
, "overlapping location is assigned "
2834 "to %s `%s' %d %d %d\n", string
, var
->name
,
2835 used_locations
, use_mask
, attr
);
2838 linker_warning(prog
, "overlapping location is assigned "
2839 "to %s `%s' %d %d %d\n", string
, var
->name
,
2840 used_locations
, use_mask
, attr
);
2844 used_locations
|= (use_mask
<< attr
);
2846 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2848 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2849 * active attribute variables may fail to link, unless
2850 * device-dependent optimizations are able to make the program
2851 * fit within available hardware resources. For the purposes
2852 * of this test, attribute variables of the type dvec3, dvec4,
2853 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2854 * count as consuming twice as many attributes as equivalent
2855 * single-precision types. While these types use the same number
2856 * of generic attributes as their single-precision equivalents,
2857 * implementations are permitted to consume two single-precision
2858 * vectors of internal storage for each three- or four-component
2859 * double-precision vector."
2861 * Mark this attribute slot as taking up twice as much space
2862 * so we can count it properly against limits. According to
2863 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2864 * is optional behavior, but it seems preferable.
2866 if (var
->type
->without_array()->is_dual_slot())
2867 double_storage_locations
|= (use_mask
<< attr
);
2870 assigned
[assigned_attr
] = var
;
2876 if (num_attr
>= max_index
) {
2877 linker_error(prog
, "too many %s (max %u)",
2878 target_index
== MESA_SHADER_VERTEX
?
2879 "vertex shader inputs" : "fragment shader outputs",
2883 to_assign
[num_attr
].slots
= slots
;
2884 to_assign
[num_attr
].var
= var
;
2888 if (target_index
== MESA_SHADER_VERTEX
) {
2889 unsigned total_attribs_size
=
2890 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2891 _mesa_bitcount(double_storage_locations
);
2892 if (total_attribs_size
> max_index
) {
2894 "attempt to use %d vertex attribute slots only %d available ",
2895 total_attribs_size
, max_index
);
2900 /* If all of the attributes were assigned locations by the application (or
2901 * are built-in attributes with fixed locations), return early. This should
2902 * be the common case.
2907 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2909 if (target_index
== MESA_SHADER_VERTEX
) {
2910 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2911 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2912 * reserved to prevent it from being automatically allocated below.
2914 find_deref_visitor
find("gl_Vertex");
2916 if (find
.variable_found())
2917 used_locations
|= (1 << 0);
2920 for (unsigned i
= 0; i
< num_attr
; i
++) {
2921 /* Mask representing the contiguous slots that will be used by this
2924 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2926 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2929 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2930 ? "vertex shader input" : "fragment shader output";
2933 "insufficient contiguous locations "
2934 "available for %s `%s'\n",
2935 string
, to_assign
[i
].var
->name
);
2939 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2940 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2941 used_locations
|= (use_mask
<< location
);
2943 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
2944 double_storage_locations
|= (use_mask
<< location
);
2947 /* Now that we have all the locations, from the GL 4.5 core spec, section
2948 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
2949 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
2950 * as equivalent single-precision types.
2952 if (target_index
== MESA_SHADER_VERTEX
) {
2953 unsigned total_attribs_size
=
2954 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2955 _mesa_bitcount(double_storage_locations
);
2956 if (total_attribs_size
> max_index
) {
2958 "attempt to use %d vertex attribute slots only %d available ",
2959 total_attribs_size
, max_index
);
2968 * Match explicit locations of outputs to inputs and deactivate the
2969 * unmatch flag if found so we don't optimise them away.
2972 match_explicit_outputs_to_inputs(gl_shader
*producer
,
2973 gl_shader
*consumer
)
2975 glsl_symbol_table parameters
;
2976 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
2979 /* Find all shader outputs in the "producer" stage.
2981 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2982 ir_variable
*const var
= node
->as_variable();
2984 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2987 if (var
->data
.explicit_location
&&
2988 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2989 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2990 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
2991 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
2995 /* Match inputs to outputs */
2996 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
2997 ir_variable
*const input
= node
->as_variable();
2999 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3002 ir_variable
*output
= NULL
;
3003 if (input
->data
.explicit_location
3004 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3005 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3006 [input
->data
.location_frac
];
3008 if (output
!= NULL
){
3009 input
->data
.is_unmatched_generic_inout
= 0;
3010 output
->data
.is_unmatched_generic_inout
= 0;
3017 * Store the gl_FragDepth layout in the gl_shader_program struct.
3020 store_fragdepth_layout(struct gl_shader_program
*prog
)
3022 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3026 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3028 /* We don't look up the gl_FragDepth symbol directly because if
3029 * gl_FragDepth is not used in the shader, it's removed from the IR.
3030 * However, the symbol won't be removed from the symbol table.
3032 * We're only interested in the cases where the variable is NOT removed
3035 foreach_in_list(ir_instruction
, node
, ir
) {
3036 ir_variable
*const var
= node
->as_variable();
3038 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3042 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3043 switch (var
->data
.depth_layout
) {
3044 case ir_depth_layout_none
:
3045 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3047 case ir_depth_layout_any
:
3048 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3050 case ir_depth_layout_greater
:
3051 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3053 case ir_depth_layout_less
:
3054 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3056 case ir_depth_layout_unchanged
:
3057 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3068 * Validate the resources used by a program versus the implementation limits
3071 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3073 unsigned total_uniform_blocks
= 0;
3074 unsigned total_shader_storage_blocks
= 0;
3076 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3077 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3082 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3083 linker_error(prog
, "Too many %s shader texture samplers\n",
3084 _mesa_shader_stage_to_string(i
));
3087 if (sh
->num_uniform_components
>
3088 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3089 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3090 linker_warning(prog
, "Too many %s shader default uniform block "
3091 "components, but the driver will try to optimize "
3092 "them out; this is non-portable out-of-spec "
3094 _mesa_shader_stage_to_string(i
));
3096 linker_error(prog
, "Too many %s shader default uniform block "
3098 _mesa_shader_stage_to_string(i
));
3102 if (sh
->num_combined_uniform_components
>
3103 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3104 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3105 linker_warning(prog
, "Too many %s shader uniform components, "
3106 "but the driver will try to optimize them out; "
3107 "this is non-portable out-of-spec behavior\n",
3108 _mesa_shader_stage_to_string(i
));
3110 linker_error(prog
, "Too many %s shader uniform components\n",
3111 _mesa_shader_stage_to_string(i
));
3115 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3116 total_uniform_blocks
+= sh
->NumUniformBlocks
;
3118 const unsigned max_uniform_blocks
=
3119 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3120 if (max_uniform_blocks
< sh
->NumUniformBlocks
) {
3121 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3122 _mesa_shader_stage_to_string(i
), sh
->NumUniformBlocks
,
3123 max_uniform_blocks
);
3126 const unsigned max_shader_storage_blocks
=
3127 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3128 if (max_shader_storage_blocks
< sh
->NumShaderStorageBlocks
) {
3129 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3130 _mesa_shader_stage_to_string(i
),
3131 sh
->NumShaderStorageBlocks
, max_shader_storage_blocks
);
3135 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3136 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3137 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3140 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3141 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3142 total_shader_storage_blocks
,
3143 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3146 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
3147 if (prog
->UniformBlocks
[i
].UniformBufferSize
>
3148 ctx
->Const
.MaxUniformBlockSize
) {
3149 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3150 prog
->UniformBlocks
[i
].Name
,
3151 prog
->UniformBlocks
[i
].UniformBufferSize
,
3152 ctx
->Const
.MaxUniformBlockSize
);
3156 for (unsigned i
= 0; i
< prog
->NumShaderStorageBlocks
; i
++) {
3157 if (prog
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3158 ctx
->Const
.MaxShaderStorageBlockSize
) {
3159 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3160 prog
->ShaderStorageBlocks
[i
].Name
,
3161 prog
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3162 ctx
->Const
.MaxShaderStorageBlockSize
);
3168 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3170 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3171 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3176 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3177 if (sh
->SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3180 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3185 sh
->NumSubroutineUniforms
++;
3187 if (sh
->NumSubroutineFunctions
== 0) {
3188 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3191 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3192 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3193 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3194 if (fn
->types
[k
] == uni
->type
) {
3200 uni
->num_compatible_subroutines
= count
;
3206 check_subroutine_resources(struct gl_shader_program
*prog
)
3208 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3209 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3212 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3213 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3214 _mesa_shader_stage_to_string(i
));
3219 * Validate shader image resources.
3222 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3224 unsigned total_image_units
= 0;
3225 unsigned fragment_outputs
= 0;
3226 unsigned total_shader_storage_blocks
= 0;
3228 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3231 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3232 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3235 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3236 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3237 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3238 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3240 total_image_units
+= sh
->NumImages
;
3241 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3243 if (i
== MESA_SHADER_FRAGMENT
) {
3244 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3245 ir_variable
*var
= node
->as_variable();
3246 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3247 /* since there are no double fs outputs - pass false */
3248 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3254 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3255 linker_error(prog
, "Too many combined image uniforms\n");
3257 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3258 ctx
->Const
.MaxCombinedShaderOutputResources
)
3259 linker_error(prog
, "Too many combined image uniforms, shader storage "
3260 " buffers and fragment outputs\n");
3265 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3266 * for a variable, checks for overlaps between other uniforms using explicit
3270 reserve_explicit_locations(struct gl_shader_program
*prog
,
3271 string_to_uint_map
*map
, ir_variable
*var
)
3273 unsigned slots
= var
->type
->uniform_locations();
3274 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3275 unsigned return_value
= slots
;
3277 /* Resize remap table if locations do not fit in the current one. */
3278 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3279 prog
->UniformRemapTable
=
3280 reralloc(prog
, prog
->UniformRemapTable
,
3281 gl_uniform_storage
*,
3284 if (!prog
->UniformRemapTable
) {
3285 linker_error(prog
, "Out of memory during linking.\n");
3289 /* Initialize allocated space. */
3290 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3291 prog
->UniformRemapTable
[i
] = NULL
;
3293 prog
->NumUniformRemapTable
= max_loc
+ 1;
3296 for (unsigned i
= 0; i
< slots
; i
++) {
3297 unsigned loc
= var
->data
.location
+ i
;
3299 /* Check if location is already used. */
3300 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3302 /* Possibly same uniform from a different stage, this is ok. */
3304 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3309 /* ARB_explicit_uniform_location specification states:
3311 * "No two default-block uniform variables in the program can have
3312 * the same location, even if they are unused, otherwise a compiler
3313 * or linker error will be generated."
3316 "location qualifier for uniform %s overlaps "
3317 "previously used location\n",
3322 /* Initialize location as inactive before optimization
3323 * rounds and location assignment.
3325 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3328 /* Note, base location used for arrays. */
3329 map
->put(var
->data
.location
, var
->name
);
3331 return return_value
;
3335 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3336 struct gl_shader
*sh
,
3339 unsigned slots
= var
->type
->uniform_locations();
3340 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3342 /* Resize remap table if locations do not fit in the current one. */
3343 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3344 sh
->SubroutineUniformRemapTable
=
3345 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3346 gl_uniform_storage
*,
3349 if (!sh
->SubroutineUniformRemapTable
) {
3350 linker_error(prog
, "Out of memory during linking.\n");
3354 /* Initialize allocated space. */
3355 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3356 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3358 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3361 for (unsigned i
= 0; i
< slots
; i
++) {
3362 unsigned loc
= var
->data
.location
+ i
;
3364 /* Check if location is already used. */
3365 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3367 /* ARB_explicit_uniform_location specification states:
3368 * "No two subroutine uniform variables can have the same location
3369 * in the same shader stage, otherwise a compiler or linker error
3370 * will be generated."
3373 "location qualifier for uniform %s overlaps "
3374 "previously used location\n",
3379 /* Initialize location as inactive before optimization
3380 * rounds and location assignment.
3382 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3388 * Check and reserve all explicit uniform locations, called before
3389 * any optimizations happen to handle also inactive uniforms and
3390 * inactive array elements that may get trimmed away.
3393 check_explicit_uniform_locations(struct gl_context
*ctx
,
3394 struct gl_shader_program
*prog
)
3396 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3399 /* This map is used to detect if overlapping explicit locations
3400 * occur with the same uniform (from different stage) or a different one.
3402 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3405 linker_error(prog
, "Out of memory during linking.\n");
3409 unsigned entries_total
= 0;
3410 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3411 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3416 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3417 ir_variable
*var
= node
->as_variable();
3418 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3421 if (var
->data
.explicit_location
) {
3423 if (var
->type
->without_array()->is_subroutine())
3424 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3426 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3430 entries_total
+= slots
;
3441 struct empty_uniform_block
*current_block
= NULL
;
3443 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3444 /* We found empty space in UniformRemapTable. */
3445 if (prog
->UniformRemapTable
[i
] == NULL
) {
3446 /* We've found the beginning of a new continous block of empty slots */
3447 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3448 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3449 current_block
->start
= i
;
3450 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3451 ¤t_block
->link
);
3454 /* The current block continues, so we simply increment its slots */
3455 current_block
->slots
++;
3460 return entries_total
;
3464 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3465 GLenum type
, const char *name
)
3467 bool found_interface
= false;
3468 unsigned block_name_len
= 0;
3469 const char *block_name_dot
= strchr(name
, '.');
3471 /* These rules only apply to buffer variables. So we return
3472 * true for the rest of types.
3474 if (type
!= GL_BUFFER_VARIABLE
)
3477 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
3478 const char *block_name
= shProg
->ShaderStorageBlocks
[i
].Name
;
3479 block_name_len
= strlen(block_name
);
3481 const char *block_square_bracket
= strchr(block_name
, '[');
3482 if (block_square_bracket
) {
3483 /* The block is part of an array of named interfaces,
3484 * for the name comparison we ignore the "[x]" part.
3486 block_name_len
-= strlen(block_square_bracket
);
3489 if (block_name_dot
) {
3490 /* Check if the variable name starts with the interface
3491 * name. The interface name (if present) should have the
3492 * length than the interface block name we are comparing to.
3494 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3495 if (len
!= block_name_len
)
3499 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3500 found_interface
= true;
3505 /* We remove the interface name from the buffer variable name,
3506 * including the dot that follows it.
3508 if (found_interface
)
3509 name
= name
+ block_name_len
+ 1;
3511 /* The ARB_program_interface_query spec says:
3513 * "For an active shader storage block member declared as an array, an
3514 * entry will be generated only for the first array element, regardless
3515 * of its type. For arrays of aggregate types, the enumeration rules
3516 * are applied recursively for the single enumerated array element."
3518 const char *struct_first_dot
= strchr(name
, '.');
3519 const char *first_square_bracket
= strchr(name
, '[');
3521 /* The buffer variable is on top level and it is not an array */
3522 if (!first_square_bracket
) {
3524 /* The shader storage block member is a struct, then generate the entry */
3525 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3528 /* Shader storage block member is an array, only generate an entry for the
3529 * first array element.
3531 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3539 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3540 const void *data
, uint8_t stages
)
3544 /* If resource already exists, do not add it again. */
3545 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3546 if (prog
->ProgramResourceList
[i
].Data
== data
)
3549 prog
->ProgramResourceList
=
3551 prog
->ProgramResourceList
,
3552 gl_program_resource
,
3553 prog
->NumProgramResourceList
+ 1);
3555 if (!prog
->ProgramResourceList
) {
3556 linker_error(prog
, "Out of memory during linking.\n");
3560 struct gl_program_resource
*res
=
3561 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3565 res
->StageReferences
= stages
;
3567 prog
->NumProgramResourceList
++;
3572 /* Function checks if a variable var is a packed varying and
3573 * if given name is part of packed varying's list.
3575 * If a variable is a packed varying, it has a name like
3576 * 'packed:a,b,c' where a, b and c are separate variables.
3579 included_in_packed_varying(ir_variable
*var
, const char *name
)
3581 if (strncmp(var
->name
, "packed:", 7) != 0)
3584 char *list
= strdup(var
->name
+ 7);
3589 char *token
= strtok_r(list
, ",", &saveptr
);
3591 if (strcmp(token
, name
) == 0) {
3595 token
= strtok_r(NULL
, ",", &saveptr
);
3602 * Function builds a stage reference bitmask from variable name.
3605 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3610 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3611 * used for reference mask in gl_program_resource will need to be changed.
3613 assert(MESA_SHADER_STAGES
< 8);
3615 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3616 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3620 /* Shader symbol table may contain variables that have
3621 * been optimized away. Search IR for the variable instead.
3623 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3624 ir_variable
*var
= node
->as_variable();
3626 unsigned baselen
= strlen(var
->name
);
3628 if (included_in_packed_varying(var
, name
)) {
3633 /* Type needs to match if specified, otherwise we might
3634 * pick a variable with same name but different interface.
3636 if (var
->data
.mode
!= mode
)
3639 if (strncmp(var
->name
, name
, baselen
) == 0) {
3640 /* Check for exact name matches but also check for arrays and
3643 if (name
[baselen
] == '\0' ||
3644 name
[baselen
] == '[' ||
3645 name
[baselen
] == '.') {
3657 * Create gl_shader_variable from ir_variable class.
3659 static gl_shader_variable
*
3660 create_shader_variable(struct gl_shader_program
*shProg
,
3661 const ir_variable
*in
,
3662 const char *name
, const glsl_type
*type
,
3663 bool use_implicit_location
, int location
,
3664 const glsl_type
*outermost_struct_type
)
3666 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3670 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3671 * expect to see gl_VertexID in the program resource list. Pretend.
3673 if (in
->data
.mode
== ir_var_system_value
&&
3674 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3675 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3677 out
->name
= ralloc_strdup(shProg
, name
);
3683 /* The ARB_program_interface_query spec says:
3685 * "Not all active variables are assigned valid locations; the
3686 * following variables will have an effective location of -1:
3688 * * uniforms declared as atomic counters;
3690 * * members of a uniform block;
3692 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3694 * * inputs or outputs not declared with a "location" layout
3695 * qualifier, except for vertex shader inputs and fragment shader
3698 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3699 is_gl_identifier(in
->name
) ||
3700 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3703 out
->location
= location
;
3707 out
->outermost_struct_type
= outermost_struct_type
;
3708 out
->interface_type
= in
->get_interface_type();
3709 out
->component
= in
->data
.location_frac
;
3710 out
->index
= in
->data
.index
;
3711 out
->patch
= in
->data
.patch
;
3712 out
->mode
= in
->data
.mode
;
3713 out
->interpolation
= in
->data
.interpolation
;
3714 out
->explicit_location
= in
->data
.explicit_location
;
3715 out
->precision
= in
->data
.precision
;
3721 add_shader_variable(struct gl_shader_program
*shProg
, unsigned stage_mask
,
3722 GLenum programInterface
, ir_variable
*var
,
3723 const char *name
, const glsl_type
*type
,
3724 bool use_implicit_location
, int location
,
3725 const glsl_type
*outermost_struct_type
= NULL
)
3727 const bool is_vertex_input
=
3728 programInterface
== GL_PROGRAM_INPUT
&&
3729 stage_mask
== MESA_SHADER_VERTEX
;
3731 switch (type
->base_type
) {
3732 case GLSL_TYPE_STRUCT
: {
3733 /* The ARB_program_interface_query spec says:
3735 * "For an active variable declared as a structure, a separate entry
3736 * will be generated for each active structure member. The name of
3737 * each entry is formed by concatenating the name of the structure,
3738 * the "." character, and the name of the structure member. If a
3739 * structure member to enumerate is itself a structure or array,
3740 * these enumeration rules are applied recursively."
3742 if (outermost_struct_type
== NULL
)
3743 outermost_struct_type
= type
;
3745 unsigned field_location
= location
;
3746 for (unsigned i
= 0; i
< type
->length
; i
++) {
3747 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3748 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3749 if (!add_shader_variable(shProg
, stage_mask
, programInterface
,
3750 var
, field_name
, field
->type
,
3751 use_implicit_location
, field_location
,
3752 outermost_struct_type
))
3756 field
->type
->count_attribute_slots(is_vertex_input
);
3762 /* Issue #16 of the ARB_program_interface_query spec says:
3764 * "* If a variable is a member of an interface block without an
3765 * instance name, it is enumerated using just the variable name.
3767 * * If a variable is a member of an interface block with an instance
3768 * name, it is enumerated as "BlockName.Member", where "BlockName" is
3769 * the name of the interface block (not the instance name) and
3770 * "Member" is the name of the variable."
3772 const char *prefixed_name
= (var
->data
.from_named_ifc_block
&&
3773 !is_gl_identifier(var
->name
))
3774 ? ralloc_asprintf(shProg
, "%s.%s", var
->get_interface_type()->name
,
3778 /* The ARB_program_interface_query spec says:
3780 * "For an active variable declared as a single instance of a basic
3781 * type, a single entry will be generated, using the variable name
3782 * from the shader source."
3784 gl_shader_variable
*sha_v
=
3785 create_shader_variable(shProg
, var
, prefixed_name
, type
,
3786 use_implicit_location
, location
,
3787 outermost_struct_type
);
3791 return add_program_resource(shProg
, programInterface
, sha_v
, stage_mask
);
3797 add_interface_variables(struct gl_shader_program
*shProg
,
3798 unsigned stage
, GLenum programInterface
)
3800 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3802 foreach_in_list(ir_instruction
, node
, ir
) {
3803 ir_variable
*var
= node
->as_variable();
3805 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3810 switch (var
->data
.mode
) {
3811 case ir_var_system_value
:
3812 case ir_var_shader_in
:
3813 if (programInterface
!= GL_PROGRAM_INPUT
)
3815 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3816 : int(VARYING_SLOT_VAR0
);
3818 case ir_var_shader_out
:
3819 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3821 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3822 : int(VARYING_SLOT_VAR0
);
3828 /* Skip packed varyings, packed varyings are handled separately
3829 * by add_packed_varyings.
3831 if (strncmp(var
->name
, "packed:", 7) == 0)
3834 /* Skip fragdata arrays, these are handled separately
3835 * by add_fragdata_arrays.
3837 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3840 const bool vs_input_or_fs_output
=
3841 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3842 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3844 if (!add_shader_variable(shProg
, 1 << stage
, programInterface
,
3845 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3846 var
->data
.location
- loc_bias
))
3853 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
, GLenum type
)
3855 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3858 if (!sh
|| !sh
->packed_varyings
)
3861 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3862 ir_variable
*var
= node
->as_variable();
3864 switch (var
->data
.mode
) {
3865 case ir_var_shader_in
:
3866 iface
= GL_PROGRAM_INPUT
;
3868 case ir_var_shader_out
:
3869 iface
= GL_PROGRAM_OUTPUT
;
3872 unreachable("unexpected type");
3875 if (type
== iface
) {
3876 const int stage_mask
=
3877 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3878 if (!add_shader_variable(shProg
, stage_mask
,
3879 iface
, var
, var
->name
, var
->type
, false,
3880 var
->data
.location
- VARYING_SLOT_VAR0
))
3889 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3891 struct gl_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3893 if (!sh
|| !sh
->fragdata_arrays
)
3896 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3897 ir_variable
*var
= node
->as_variable();
3899 assert(var
->data
.mode
== ir_var_shader_out
);
3901 if (!add_shader_variable(shProg
,
3902 1 << MESA_SHADER_FRAGMENT
,
3903 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3904 true, var
->data
.location
- FRAG_RESULT_DATA0
))
3912 get_top_level_name(const char *name
)
3914 const char *first_dot
= strchr(name
, '.');
3915 const char *first_square_bracket
= strchr(name
, '[');
3918 /* The ARB_program_interface_query spec says:
3920 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3921 * the number of active array elements of the top-level shader storage
3922 * block member containing to the active variable is written to
3923 * <params>. If the top-level block member is not declared as an
3924 * array, the value one is written to <params>. If the top-level block
3925 * member is an array with no declared size, the value zero is written
3929 /* The buffer variable is on top level.*/
3930 if (!first_square_bracket
&& !first_dot
)
3931 name_size
= strlen(name
);
3932 else if ((!first_square_bracket
||
3933 (first_dot
&& first_dot
< first_square_bracket
)))
3934 name_size
= first_dot
- name
;
3936 name_size
= first_square_bracket
- name
;
3938 return strndup(name
, name_size
);
3942 get_var_name(const char *name
)
3944 const char *first_dot
= strchr(name
, '.');
3947 return strdup(name
);
3949 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3953 is_top_level_shader_storage_block_member(const char* name
,
3954 const char* interface_name
,
3955 const char* field_name
)
3957 bool result
= false;
3959 /* If the given variable is already a top-level shader storage
3960 * block member, then return array_size = 1.
3961 * We could have two possibilities: if we have an instanced
3962 * shader storage block or not instanced.
3964 * For the first, we check create a name as it was in top level and
3965 * compare it with the real name. If they are the same, then
3966 * the variable is already at top-level.
3968 * Full instanced name is: interface name + '.' + var name +
3971 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3972 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3973 if (!full_instanced_name
) {
3974 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3978 snprintf(full_instanced_name
, name_length
, "%s.%s",
3979 interface_name
, field_name
);
3981 /* Check if its top-level shader storage block member of an
3982 * instanced interface block, or of a unnamed interface block.
3984 if (strcmp(name
, full_instanced_name
) == 0 ||
3985 strcmp(name
, field_name
) == 0)
3988 free(full_instanced_name
);
3993 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
3994 char *interface_name
, char *var_name
)
3996 /* The ARB_program_interface_query spec says:
3998 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3999 * the number of active array elements of the top-level shader storage
4000 * block member containing to the active variable is written to
4001 * <params>. If the top-level block member is not declared as an
4002 * array, the value one is written to <params>. If the top-level block
4003 * member is an array with no declared size, the value zero is written
4006 if (is_top_level_shader_storage_block_member(uni
->name
,
4010 else if (field
->type
->is_unsized_array())
4012 else if (field
->type
->is_array())
4013 return field
->type
->length
;
4019 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
4020 const glsl_struct_field
*field
, char *interface_name
,
4023 /* The ARB_program_interface_query spec says:
4025 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4026 * identifying the stride between array elements of the top-level
4027 * shader storage block member containing the active variable is
4028 * written to <params>. For top-level block members declared as
4029 * arrays, the value written is the difference, in basic machine units,
4030 * between the offsets of the active variable for consecutive elements
4031 * in the top-level array. For top-level block members not declared as
4032 * an array, zero is written to <params>."
4034 if (field
->type
->is_array()) {
4035 const enum glsl_matrix_layout matrix_layout
=
4036 glsl_matrix_layout(field
->matrix_layout
);
4037 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4038 const glsl_type
*array_type
= field
->type
->fields
.array
;
4040 if (is_top_level_shader_storage_block_member(uni
->name
,
4045 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
4046 if (array_type
->is_record() || array_type
->is_array())
4047 return glsl_align(array_type
->std140_size(row_major
), 16);
4049 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4051 return array_type
->std430_array_stride(row_major
);
4058 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
4059 struct gl_uniform_storage
*uni
)
4061 int block_index
= uni
->block_index
;
4062 int array_size
= -1;
4063 int array_stride
= -1;
4064 char *var_name
= get_top_level_name(uni
->name
);
4065 char *interface_name
=
4066 get_top_level_name(uni
->is_shader_storage
?
4067 shProg
->ShaderStorageBlocks
[block_index
].Name
:
4068 shProg
->UniformBlocks
[block_index
].Name
);
4070 if (strcmp(var_name
, interface_name
) == 0) {
4071 /* Deal with instanced array of SSBOs */
4072 char *temp_name
= get_var_name(uni
->name
);
4074 linker_error(shProg
, "Out of memory during linking.\n");
4075 goto write_top_level_array_size_and_stride
;
4078 var_name
= get_top_level_name(temp_name
);
4081 linker_error(shProg
, "Out of memory during linking.\n");
4082 goto write_top_level_array_size_and_stride
;
4086 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
4087 if (shProg
->Shaders
[i
] == NULL
)
4090 const gl_shader
*stage
= shProg
->Shaders
[i
];
4091 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
4092 ir_variable
*var
= node
->as_variable();
4093 if (!var
|| !var
->get_interface_type() ||
4094 var
->data
.mode
!= ir_var_shader_storage
)
4097 const glsl_type
*interface
= var
->get_interface_type();
4099 if (strcmp(interface_name
, interface
->name
) != 0)
4102 for (unsigned i
= 0; i
< interface
->length
; i
++) {
4103 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
4104 if (strcmp(field
->name
, var_name
) != 0)
4107 array_stride
= get_array_stride(uni
, interface
, field
,
4108 interface_name
, var_name
);
4109 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4110 goto write_top_level_array_size_and_stride
;
4114 write_top_level_array_size_and_stride
:
4115 free(interface_name
);
4117 uni
->top_level_array_stride
= array_stride
;
4118 uni
->top_level_array_size
= array_size
;
4122 * Builds up a list of program resources that point to existing
4126 build_program_resource_list(struct gl_context
*ctx
,
4127 struct gl_shader_program
*shProg
)
4129 /* Rebuild resource list. */
4130 if (shProg
->ProgramResourceList
) {
4131 ralloc_free(shProg
->ProgramResourceList
);
4132 shProg
->ProgramResourceList
= NULL
;
4133 shProg
->NumProgramResourceList
= 0;
4136 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4138 /* Determine first input and final output stage. These are used to
4139 * detect which variables should be enumerated in the resource list
4140 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4142 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4143 if (!shProg
->_LinkedShaders
[i
])
4145 if (input_stage
== MESA_SHADER_STAGES
)
4150 /* Empty shader, no resources. */
4151 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4154 /* Program interface needs to expose varyings in case of SSO. */
4155 if (shProg
->SeparateShader
) {
4156 if (!add_packed_varyings(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4159 if (!add_packed_varyings(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4163 if (!add_fragdata_arrays(shProg
))
4166 /* Add inputs and outputs to the resource list. */
4167 if (!add_interface_variables(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4170 if (!add_interface_variables(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4173 /* Add transform feedback varyings. */
4174 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
4175 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
4176 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
4177 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
4183 /* Add transform feedback buffers. */
4184 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4185 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
4186 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
4187 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_BUFFER
,
4188 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
4194 /* Add uniforms from uniform storage. */
4195 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4196 /* Do not add uniforms internally used by Mesa. */
4197 if (shProg
->UniformStorage
[i
].hidden
)
4201 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
4204 /* Add stagereferences for uniforms in a uniform block. */
4205 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
4206 int block_index
= shProg
->UniformStorage
[i
].block_index
;
4207 if (block_index
!= -1) {
4208 stageref
|= is_shader_storage
?
4209 shProg
->ShaderStorageBlocks
[block_index
].stageref
:
4210 shProg
->UniformBlocks
[block_index
].stageref
;
4213 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4214 if (!should_add_buffer_variable(shProg
, type
,
4215 shProg
->UniformStorage
[i
].name
))
4218 if (is_shader_storage
) {
4219 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
4222 if (!add_program_resource(shProg
, type
,
4223 &shProg
->UniformStorage
[i
], stageref
))
4227 /* Add program uniform blocks. */
4228 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
4229 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
4230 &shProg
->UniformBlocks
[i
], 0))
4234 /* Add program shader storage blocks. */
4235 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
4236 if (!add_program_resource(shProg
, GL_SHADER_STORAGE_BLOCK
,
4237 &shProg
->ShaderStorageBlocks
[i
], 0))
4241 /* Add atomic counter buffers. */
4242 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
4243 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
4244 &shProg
->AtomicBuffers
[i
], 0))
4248 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4250 if (!shProg
->UniformStorage
[i
].hidden
)
4253 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4254 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4255 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4258 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4259 /* add shader subroutines */
4260 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
4265 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4266 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
4272 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4273 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4274 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
4281 * This check is done to make sure we allow only constant expression
4282 * indexing and "constant-index-expression" (indexing with an expression
4283 * that includes loop induction variable).
4286 validate_sampler_array_indexing(struct gl_context
*ctx
,
4287 struct gl_shader_program
*prog
)
4289 dynamic_sampler_array_indexing_visitor v
;
4290 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4291 if (prog
->_LinkedShaders
[i
] == NULL
)
4294 bool no_dynamic_indexing
=
4295 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4297 /* Search for array derefs in shader. */
4298 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4299 if (v
.uses_dynamic_sampler_array_indexing()) {
4300 const char *msg
= "sampler arrays indexed with non-constant "
4301 "expressions is forbidden in GLSL %s %u";
4302 /* Backend has indicated that it has no dynamic indexing support. */
4303 if (no_dynamic_indexing
) {
4304 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4307 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4315 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4317 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4318 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4323 sh
->MaxSubroutineFunctionIndex
= 0;
4324 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4325 ir_function
*fn
= node
->as_function();
4329 if (fn
->is_subroutine
)
4330 sh
->NumSubroutineUniformTypes
++;
4332 if (!fn
->num_subroutine_types
)
4335 /* these should have been calculated earlier. */
4336 assert(fn
->subroutine_index
!= -1);
4337 if (sh
->NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4338 linker_error(prog
, "Too many subroutine functions declared.\n");
4341 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4342 struct gl_subroutine_function
,
4343 sh
->NumSubroutineFunctions
+ 1);
4344 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4345 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4346 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4347 ralloc_array(sh
, const struct glsl_type
*,
4348 fn
->num_subroutine_types
);
4350 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4353 * "Each subroutine with an index qualifier in the shader must be
4354 * given a unique index, otherwise a compile or link error will be
4357 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4358 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4359 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4360 linker_error(prog
, "each subroutine index qualifier in the "
4361 "shader must be unique\n");
4365 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4366 fn
->subroutine_index
;
4368 if (fn
->subroutine_index
> (int)sh
->MaxSubroutineFunctionIndex
)
4369 sh
->MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4371 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4372 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4373 sh
->NumSubroutineFunctions
++;
4379 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4381 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4383 foreach_in_list(ir_instruction
, node
, ir
) {
4384 ir_variable
*const var
= node
->as_variable();
4386 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4389 /* Don't set always active on builtins that haven't been redeclared */
4390 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4393 var
->data
.always_active_io
= true;
4398 * When separate shader programs are enabled, only input/outputs between
4399 * the stages of a multi-stage separate program can be safely removed
4400 * from the shader interface. Other inputs/outputs must remain active.
4403 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4405 unsigned first
, last
;
4406 assert(prog
->SeparateShader
);
4408 first
= MESA_SHADER_STAGES
;
4411 /* Determine first and last stage. Excluding the compute stage */
4412 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4413 if (!prog
->_LinkedShaders
[i
])
4415 if (first
== MESA_SHADER_STAGES
)
4420 if (first
== MESA_SHADER_STAGES
)
4423 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4424 gl_shader
*sh
= prog
->_LinkedShaders
[stage
];
4428 if (first
== last
) {
4429 /* For a single shader program only allow inputs to the vertex shader
4430 * and outputs from the fragment shader to be removed.
4432 if (stage
!= MESA_SHADER_VERTEX
)
4433 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4434 if (stage
!= MESA_SHADER_FRAGMENT
)
4435 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4437 /* For multi-stage separate shader programs only allow inputs and
4438 * outputs between the shader stages to be removed as well as inputs
4439 * to the vertex shader and outputs from the fragment shader.
4441 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4442 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4443 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4444 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4450 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4452 prog
->LinkStatus
= true; /* All error paths will set this to false */
4453 prog
->Validated
= false;
4454 prog
->_Used
= false;
4456 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4458 * "Linking can fail for a variety of reasons as specified in the
4459 * OpenGL Shading Language Specification, as well as any of the
4460 * following reasons:
4462 * - No shader objects are attached to program."
4464 * The Compatibility Profile specification does not list the error. In
4465 * Compatibility Profile missing shader stages are replaced by
4466 * fixed-function. This applies to the case where all stages are
4469 if (prog
->NumShaders
== 0) {
4470 if (ctx
->API
!= API_OPENGL_COMPAT
)
4471 linker_error(prog
, "no shaders attached to the program\n");
4475 unsigned num_tfeedback_decls
= 0;
4476 unsigned int num_explicit_uniform_locs
= 0;
4477 bool has_xfb_qualifiers
= false;
4478 char **varying_names
= NULL
;
4479 tfeedback_decl
*tfeedback_decls
= NULL
;
4481 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4483 prog
->ARB_fragment_coord_conventions_enable
= false;
4485 /* Separate the shaders into groups based on their type.
4487 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4488 unsigned num_shaders
[MESA_SHADER_STAGES
];
4490 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4491 shader_list
[i
] = (struct gl_shader
**)
4492 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4496 unsigned min_version
= UINT_MAX
;
4497 unsigned max_version
= 0;
4498 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4499 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4500 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4502 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4503 linker_error(prog
, "all shaders must use same shading "
4504 "language version\n");
4508 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4509 prog
->ARB_fragment_coord_conventions_enable
= true;
4512 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4513 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4514 num_shaders
[shader_type
]++;
4517 /* In desktop GLSL, different shader versions may be linked together. In
4518 * GLSL ES, all shader versions must be the same.
4520 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4521 linker_error(prog
, "all shaders must use same shading "
4522 "language version\n");
4526 prog
->Version
= max_version
;
4527 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4529 /* Some shaders have to be linked with some other shaders present.
4531 if (!prog
->SeparateShader
) {
4532 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4533 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4534 linker_error(prog
, "Geometry shader must be linked with "
4538 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4539 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4540 linker_error(prog
, "Tessellation evaluation shader must be linked "
4541 "with vertex shader\n");
4544 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4545 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4546 linker_error(prog
, "Tessellation control shader must be linked with "
4551 /* The spec is self-contradictory here. It allows linking without a tess
4552 * eval shader, but that can only be used with transform feedback and
4553 * rasterization disabled. However, transform feedback isn't allowed
4554 * with GL_PATCHES, so it can't be used.
4556 * More investigation showed that the idea of transform feedback after
4557 * a tess control shader was dropped, because some hw vendors couldn't
4558 * support tessellation without a tess eval shader, but the linker
4559 * section wasn't updated to reflect that.
4561 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4564 * Do what's reasonable and always require a tess eval shader if a tess
4565 * control shader is present.
4567 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4568 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4569 linker_error(prog
, "Tessellation control shader must be linked with "
4570 "tessellation evaluation shader\n");
4575 /* Compute shaders have additional restrictions. */
4576 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4577 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4578 linker_error(prog
, "Compute shaders may not be linked with any other "
4579 "type of shader\n");
4582 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4583 if (prog
->_LinkedShaders
[i
] != NULL
)
4584 _mesa_delete_shader(ctx
, prog
->_LinkedShaders
[i
]);
4586 prog
->_LinkedShaders
[i
] = NULL
;
4589 /* Link all shaders for a particular stage and validate the result.
4591 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4592 if (num_shaders
[stage
] > 0) {
4593 gl_shader
*const sh
=
4594 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4595 num_shaders
[stage
]);
4597 if (!prog
->LinkStatus
) {
4599 _mesa_delete_shader(ctx
, sh
);
4604 case MESA_SHADER_VERTEX
:
4605 validate_vertex_shader_executable(prog
, sh
, ctx
);
4607 case MESA_SHADER_TESS_CTRL
:
4608 /* nothing to be done */
4610 case MESA_SHADER_TESS_EVAL
:
4611 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4613 case MESA_SHADER_GEOMETRY
:
4614 validate_geometry_shader_executable(prog
, sh
, ctx
);
4616 case MESA_SHADER_FRAGMENT
:
4617 validate_fragment_shader_executable(prog
, sh
);
4620 if (!prog
->LinkStatus
) {
4622 _mesa_delete_shader(ctx
, sh
);
4626 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
4630 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0) {
4631 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4632 prog
->LastCullDistanceArraySize
= prog
->Geom
.CullDistanceArraySize
;
4633 } else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0) {
4634 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4635 prog
->LastCullDistanceArraySize
= prog
->TessEval
.CullDistanceArraySize
;
4636 } else if (num_shaders
[MESA_SHADER_VERTEX
] > 0) {
4637 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4638 prog
->LastCullDistanceArraySize
= prog
->Vert
.CullDistanceArraySize
;
4640 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4641 prog
->LastCullDistanceArraySize
= 0; /* Not used */
4644 /* Here begins the inter-stage linking phase. Some initial validation is
4645 * performed, then locations are assigned for uniforms, attributes, and
4648 cross_validate_uniforms(prog
);
4649 if (!prog
->LinkStatus
)
4652 unsigned first
, last
, prev
;
4654 first
= MESA_SHADER_STAGES
;
4657 /* Determine first and last stage. */
4658 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4659 if (!prog
->_LinkedShaders
[i
])
4661 if (first
== MESA_SHADER_STAGES
)
4666 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4667 link_assign_subroutine_types(prog
);
4669 if (!prog
->LinkStatus
)
4672 resize_tes_inputs(ctx
, prog
);
4674 /* Validate the inputs of each stage with the output of the preceding
4678 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4679 if (prog
->_LinkedShaders
[i
] == NULL
)
4682 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4683 prog
->_LinkedShaders
[i
]);
4684 if (!prog
->LinkStatus
)
4687 cross_validate_outputs_to_inputs(prog
,
4688 prog
->_LinkedShaders
[prev
],
4689 prog
->_LinkedShaders
[i
]);
4690 if (!prog
->LinkStatus
)
4696 /* Cross-validate uniform blocks between shader stages */
4697 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
4698 MESA_SHADER_STAGES
);
4699 if (!prog
->LinkStatus
)
4702 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4703 if (prog
->_LinkedShaders
[i
] != NULL
)
4704 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4707 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4708 * it before optimization because we want most of the checks to get
4709 * dropped thanks to constant propagation.
4711 * This rule also applies to GLSL ES 3.00.
4713 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4714 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4716 lower_discard_flow(sh
->ir
);
4720 if (prog
->SeparateShader
)
4721 disable_varying_optimizations_for_sso(prog
);
4724 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4728 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4731 /* Do common optimization before assigning storage for attributes,
4732 * uniforms, and varyings. Later optimization could possibly make
4733 * some of that unused.
4735 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4736 if (prog
->_LinkedShaders
[i
] == NULL
)
4739 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4740 if (!prog
->LinkStatus
)
4743 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4744 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4747 if (ctx
->Const
.LowerTessLevel
) {
4748 lower_tess_level(prog
->_LinkedShaders
[i
]);
4751 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4752 &ctx
->Const
.ShaderCompilerOptions
[i
],
4753 ctx
->Const
.NativeIntegers
))
4756 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4759 /* Validation for special cases where we allow sampler array indexing
4760 * with loop induction variable. This check emits a warning or error
4761 * depending if backend can handle dynamic indexing.
4763 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4764 (prog
->IsES
&& prog
->Version
< 300)) {
4765 if (!validate_sampler_array_indexing(ctx
, prog
))
4769 /* Check and validate stream emissions in geometry shaders */
4770 validate_geometry_shader_emissions(ctx
, prog
);
4772 /* Mark all generic shader inputs and outputs as unpaired. */
4773 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4774 if (prog
->_LinkedShaders
[i
] != NULL
) {
4775 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4780 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4781 if (prog
->_LinkedShaders
[i
] == NULL
)
4784 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4785 prog
->_LinkedShaders
[i
]);
4789 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4790 MESA_SHADER_VERTEX
)) {
4794 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4795 MESA_SHADER_FRAGMENT
)) {
4799 /* From the ARB_enhanced_layouts spec:
4801 * "If the shader used to record output variables for transform feedback
4802 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4803 * qualifiers, the values specified by TransformFeedbackVaryings are
4804 * ignored, and the set of variables captured for transform feedback is
4805 * instead derived from the specified layout qualifiers."
4807 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4808 /* Find last stage before fragment shader */
4809 if (prog
->_LinkedShaders
[i
]) {
4810 has_xfb_qualifiers
=
4811 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4812 &num_tfeedback_decls
,
4818 if (!has_xfb_qualifiers
) {
4819 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4820 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4823 if (num_tfeedback_decls
!= 0) {
4824 /* From GL_EXT_transform_feedback:
4825 * A program will fail to link if:
4827 * * the <count> specified by TransformFeedbackVaryingsEXT is
4828 * non-zero, but the program object has no vertex or geometry
4831 if (first
>= MESA_SHADER_FRAGMENT
) {
4832 linker_error(prog
, "Transform feedback varyings specified, but "
4833 "no vertex, tessellation, or geometry shader is "
4838 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4839 num_tfeedback_decls
);
4840 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4841 varying_names
, tfeedback_decls
))
4845 /* If there is no fragment shader we need to set transform feedback.
4847 * For SSO we also need to assign output locations. We assign them here
4848 * because we need to do it for both single stage programs and multi stage
4851 if (last
< MESA_SHADER_FRAGMENT
&&
4852 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4853 const uint64_t reserved_out_slots
=
4854 reserved_varying_slot(prog
->_LinkedShaders
[last
], ir_var_shader_out
);
4855 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4856 prog
->_LinkedShaders
[last
], NULL
,
4857 num_tfeedback_decls
, tfeedback_decls
,
4858 reserved_out_slots
))
4862 if (last
<= MESA_SHADER_FRAGMENT
) {
4863 /* Remove unused varyings from the first/last stage unless SSO */
4864 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4865 prog
->_LinkedShaders
[first
],
4867 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4868 prog
->_LinkedShaders
[last
],
4871 /* If the program is made up of only a single stage */
4872 if (first
== last
) {
4874 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
4875 if (prog
->SeparateShader
) {
4876 const uint64_t reserved_slots
=
4877 reserved_varying_slot(sh
, ir_var_shader_in
);
4879 /* Assign input locations for SSO, output locations are already
4882 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4883 NULL
/* producer */,
4885 0 /* num_tfeedback_decls */,
4886 NULL
/* tfeedback_decls */,
4891 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4892 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4895 /* Linking the stages in the opposite order (from fragment to vertex)
4896 * ensures that inter-shader outputs written to in an earlier stage
4897 * are eliminated if they are (transitively) not used in a later
4901 for (int i
= next
- 1; i
>= 0; i
--) {
4902 if (prog
->_LinkedShaders
[i
] == NULL
&& i
!= 0)
4905 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4906 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4908 const uint64_t reserved_out_slots
=
4909 reserved_varying_slot(sh_i
, ir_var_shader_out
);
4910 const uint64_t reserved_in_slots
=
4911 reserved_varying_slot(sh_next
, ir_var_shader_in
);
4913 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4914 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4916 reserved_out_slots
| reserved_in_slots
))
4919 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4920 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4923 /* This must be done after all dead varyings are eliminated. */
4925 unsigned slots_used
= _mesa_bitcount_64(reserved_out_slots
);
4926 if (!check_against_output_limit(ctx
, prog
, sh_i
, slots_used
)) {
4931 unsigned slots_used
= _mesa_bitcount_64(reserved_in_slots
);
4932 if (!check_against_input_limit(ctx
, prog
, sh_next
, slots_used
))
4940 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4941 has_xfb_qualifiers
))
4944 update_array_sizes(prog
);
4945 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4946 num_explicit_uniform_locs
,
4947 ctx
->Const
.MaxUserAssignableUniformLocations
);
4948 link_assign_atomic_counter_resources(ctx
, prog
);
4949 store_fragdepth_layout(prog
);
4951 link_calculate_subroutine_compat(prog
);
4952 check_resources(ctx
, prog
);
4953 check_subroutine_resources(prog
);
4954 check_image_resources(ctx
, prog
);
4955 link_check_atomic_counter_resources(ctx
, prog
);
4957 if (!prog
->LinkStatus
)
4960 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4961 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4962 * anything about shader linking when one of the shaders (vertex or
4963 * fragment shader) is absent. So, the extension shouldn't change the
4964 * behavior specified in GLSL specification.
4966 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4967 * "Linking can fail for a variety of reasons as specified in the
4968 * OpenGL ES Shading Language Specification, as well as any of the
4969 * following reasons:
4973 * * program contains objects to form either a vertex shader or
4974 * fragment shader, and program is not separable, and does not
4975 * contain objects to form both a vertex shader and fragment
4978 * However, the only scenario in 3.1+ where we don't require them both is
4979 * when we have a compute shader. For example:
4981 * - No shaders is a link error.
4982 * - Geom or Tess without a Vertex shader is a link error which means we
4983 * always require a Vertex shader and hence a Fragment shader.
4984 * - Finally a Compute shader linked with any other stage is a link error.
4986 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4987 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4988 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4989 linker_error(prog
, "program lacks a vertex shader\n");
4990 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4991 linker_error(prog
, "program lacks a fragment shader\n");
4995 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4996 if (prog
->_LinkedShaders
[i
] == NULL
)
4999 const struct gl_shader_compiler_options
*options
=
5000 &ctx
->Const
.ShaderCompilerOptions
[i
];
5002 if (options
->LowerBufferInterfaceBlocks
)
5003 lower_ubo_reference(prog
->_LinkedShaders
[i
],
5004 options
->ClampBlockIndicesToArrayBounds
);
5006 if (options
->LowerShaderSharedVariables
)
5007 lower_shared_reference(prog
->_LinkedShaders
[i
],
5008 &prog
->Comp
.SharedSize
);
5010 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
5011 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
5015 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5016 free(shader_list
[i
]);
5017 if (prog
->_LinkedShaders
[i
] == NULL
)
5020 /* Do a final validation step to make sure that the IR wasn't
5021 * invalidated by any modifications performed after intrastage linking.
5023 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5025 /* Retain any live IR, but trash the rest. */
5026 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5028 /* The symbol table in the linked shaders may contain references to
5029 * variables that were removed (e.g., unused uniforms). Since it may
5030 * contain junk, there is no possible valid use. Delete it and set the
5033 delete prog
->_LinkedShaders
[i
]->symbols
;
5034 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5037 ralloc_free(mem_ctx
);