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"
75 #include "program/prog_instruction.h"
77 #include "link_varyings.h"
78 #include "ir_optimization.h"
79 #include "ir_rvalue_visitor.h"
80 #include "ir_uniform.h"
82 #include "main/shaderobj.h"
83 #include "main/enums.h"
89 * Visitor that determines whether or not a variable is ever written.
91 class find_assignment_visitor
: public ir_hierarchical_visitor
{
93 find_assignment_visitor(const char *name
)
94 : name(name
), found(false)
99 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
101 ir_variable
*const var
= ir
->lhs
->variable_referenced();
103 if (strcmp(name
, var
->name
) == 0) {
108 return visit_continue_with_parent
;
111 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
113 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
114 actual_node
, &ir
->actual_parameters
) {
115 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
116 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
118 if (sig_param
->data
.mode
== ir_var_function_out
||
119 sig_param
->data
.mode
== ir_var_function_inout
) {
120 ir_variable
*var
= param_rval
->variable_referenced();
121 if (var
&& strcmp(name
, var
->name
) == 0) {
128 if (ir
->return_deref
!= NULL
) {
129 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
131 if (strcmp(name
, var
->name
) == 0) {
137 return visit_continue_with_parent
;
140 bool variable_found()
146 const char *name
; /**< Find writes to a variable with this name. */
147 bool found
; /**< Was a write to the variable found? */
152 * Visitor that determines whether or not a variable is ever read.
154 class find_deref_visitor
: public ir_hierarchical_visitor
{
156 find_deref_visitor(const char *name
)
157 : name(name
), found(false)
162 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
164 if (strcmp(this->name
, ir
->var
->name
) == 0) {
169 return visit_continue
;
172 bool variable_found() const
178 const char *name
; /**< Find writes to a variable with this name. */
179 bool found
; /**< Was a write to the variable found? */
183 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
185 unsigned num_vertices
;
186 gl_shader_program
*prog
;
188 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
190 this->num_vertices
= num_vertices
;
194 virtual ~geom_array_resize_visitor()
199 virtual ir_visitor_status
visit(ir_variable
*var
)
201 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
202 return visit_continue
;
204 unsigned size
= var
->type
->length
;
206 /* Generate a link error if the shader has declared this array with an
209 if (!var
->data
.implicit_sized_array
&&
210 size
&& size
!= this->num_vertices
) {
211 linker_error(this->prog
, "size of array %s declared as %u, "
212 "but number of input vertices is %u\n",
213 var
->name
, size
, this->num_vertices
);
214 return visit_continue
;
217 /* Generate a link error if the shader attempts to access an input
218 * array using an index too large for its actual size assigned at link
221 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
222 linker_error(this->prog
, "geometry shader accesses element %i of "
223 "%s, but only %i input vertices\n",
224 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
225 return visit_continue
;
228 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
230 var
->data
.max_array_access
= this->num_vertices
- 1;
232 return visit_continue
;
235 /* Dereferences of input variables need to be updated so that their type
236 * matches the newly assigned type of the variable they are accessing. */
237 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
239 ir
->type
= ir
->var
->type
;
240 return visit_continue
;
243 /* Dereferences of 2D input arrays need to be updated so that their type
244 * matches the newly assigned type of the array they are accessing. */
245 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
247 const glsl_type
*const vt
= ir
->array
->type
;
249 ir
->type
= vt
->fields
.array
;
250 return visit_continue
;
254 class tess_eval_array_resize_visitor
: public ir_hierarchical_visitor
{
256 unsigned num_vertices
;
257 gl_shader_program
*prog
;
259 tess_eval_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
261 this->num_vertices
= num_vertices
;
265 virtual ~tess_eval_array_resize_visitor()
270 virtual ir_visitor_status
visit(ir_variable
*var
)
272 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
|| var
->data
.patch
)
273 return visit_continue
;
275 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
277 var
->data
.max_array_access
= this->num_vertices
- 1;
279 return visit_continue
;
282 /* Dereferences of input variables need to be updated so that their type
283 * matches the newly assigned type of the variable they are accessing. */
284 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
286 ir
->type
= ir
->var
->type
;
287 return visit_continue
;
290 /* Dereferences of 2D input arrays need to be updated so that their type
291 * matches the newly assigned type of the array they are accessing. */
292 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
294 const glsl_type
*const vt
= ir
->array
->type
;
296 ir
->type
= vt
->fields
.array
;
297 return visit_continue
;
301 class barrier_use_visitor
: public ir_hierarchical_visitor
{
303 barrier_use_visitor(gl_shader_program
*prog
)
304 : prog(prog
), in_main(false), after_return(false), control_flow(0)
308 virtual ~barrier_use_visitor()
313 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
315 if (strcmp(ir
->name
, "main") == 0)
318 return visit_continue
;
321 virtual ir_visitor_status
visit_leave(ir_function
*)
324 after_return
= false;
325 return visit_continue
;
328 virtual ir_visitor_status
visit_leave(ir_return
*)
331 return visit_continue
;
334 virtual ir_visitor_status
visit_enter(ir_if
*)
337 return visit_continue
;
340 virtual ir_visitor_status
visit_leave(ir_if
*)
343 return visit_continue
;
346 virtual ir_visitor_status
visit_enter(ir_loop
*)
349 return visit_continue
;
352 virtual ir_visitor_status
visit_leave(ir_loop
*)
355 return visit_continue
;
358 /* FINISHME: `switch` is not expressed at the IR level -- it's already
359 * been lowered to a mess of `if`s. We'll correctly disallow any use of
360 * barrier() in a conditional path within the switch, but not in a path
361 * which is always hit.
364 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
366 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
367 /* Use of barrier(); determine if it is legal: */
369 linker_error(prog
, "Builtin barrier() may only be used in main");
374 linker_error(prog
, "Builtin barrier() may not be used after return");
378 if (control_flow
!= 0) {
379 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
383 return visit_continue
;
387 gl_shader_program
*prog
;
388 bool in_main
, after_return
;
393 * Visitor that determines the highest stream id to which a (geometry) shader
394 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
396 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
398 find_emit_vertex_visitor(int max_allowed
)
399 : max_stream_allowed(max_allowed
),
400 invalid_stream_id(0),
401 invalid_stream_id_from_emit_vertex(false),
402 end_primitive_found(false),
403 uses_non_zero_stream(false)
408 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
410 int stream_id
= ir
->stream_id();
413 invalid_stream_id
= stream_id
;
414 invalid_stream_id_from_emit_vertex
= true;
418 if (stream_id
> max_stream_allowed
) {
419 invalid_stream_id
= stream_id
;
420 invalid_stream_id_from_emit_vertex
= true;
425 uses_non_zero_stream
= true;
427 return visit_continue
;
430 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
432 end_primitive_found
= true;
434 int stream_id
= ir
->stream_id();
437 invalid_stream_id
= stream_id
;
438 invalid_stream_id_from_emit_vertex
= false;
442 if (stream_id
> max_stream_allowed
) {
443 invalid_stream_id
= stream_id
;
444 invalid_stream_id_from_emit_vertex
= false;
449 uses_non_zero_stream
= true;
451 return visit_continue
;
456 return invalid_stream_id
!= 0;
459 const char *error_func()
461 return invalid_stream_id_from_emit_vertex
?
462 "EmitStreamVertex" : "EndStreamPrimitive";
467 return invalid_stream_id
;
472 return uses_non_zero_stream
;
475 bool uses_end_primitive()
477 return end_primitive_found
;
481 int max_stream_allowed
;
482 int invalid_stream_id
;
483 bool invalid_stream_id_from_emit_vertex
;
484 bool end_primitive_found
;
485 bool uses_non_zero_stream
;
488 /* Class that finds array derefs and check if indexes are dynamic. */
489 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
492 dynamic_sampler_array_indexing_visitor() :
493 dynamic_sampler_array_indexing(false)
497 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
499 if (!ir
->variable_referenced())
500 return visit_continue
;
502 if (!ir
->variable_referenced()->type
->contains_sampler())
503 return visit_continue
;
505 if (!ir
->array_index
->constant_expression_value()) {
506 dynamic_sampler_array_indexing
= true;
509 return visit_continue
;
512 bool uses_dynamic_sampler_array_indexing()
514 return dynamic_sampler_array_indexing
;
518 bool dynamic_sampler_array_indexing
;
521 } /* anonymous namespace */
524 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
528 ralloc_strcat(&prog
->InfoLog
, "error: ");
530 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
533 prog
->LinkStatus
= false;
538 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
542 ralloc_strcat(&prog
->InfoLog
, "warning: ");
544 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
551 * Given a string identifying a program resource, break it into a base name
552 * and an optional array index in square brackets.
554 * If an array index is present, \c out_base_name_end is set to point to the
555 * "[" that precedes the array index, and the array index itself is returned
558 * If no array index is present (or if the array index is negative or
559 * mal-formed), \c out_base_name_end, is set to point to the null terminator
560 * at the end of the input string, and -1 is returned.
562 * Only the final array index is parsed; if the string contains other array
563 * indices (or structure field accesses), they are left in the base name.
565 * No attempt is made to check that the base name is properly formed;
566 * typically the caller will look up the base name in a hash table, so
567 * ill-formed base names simply turn into hash table lookup failures.
570 parse_program_resource_name(const GLchar
*name
,
571 const GLchar
**out_base_name_end
)
573 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
575 * "When an integer array element or block instance number is part of
576 * the name string, it will be specified in decimal form without a "+"
577 * or "-" sign or any extra leading zeroes. Additionally, the name
578 * string will not include white space anywhere in the string."
581 const size_t len
= strlen(name
);
582 *out_base_name_end
= name
+ len
;
584 if (len
== 0 || name
[len
-1] != ']')
587 /* Walk backwards over the string looking for a non-digit character. This
588 * had better be the opening bracket for an array index.
590 * Initially, i specifies the location of the ']'. Since the string may
591 * contain only the ']' charcater, walk backwards very carefully.
594 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
597 if ((i
== 0) || name
[i
-1] != '[')
600 long array_index
= strtol(&name
[i
], NULL
, 10);
604 /* Check for leading zero */
605 if (name
[i
] == '0' && name
[i
+1] != ']')
608 *out_base_name_end
= name
+ (i
- 1);
614 link_invalidate_variable_locations(exec_list
*ir
)
616 foreach_in_list(ir_instruction
, node
, ir
) {
617 ir_variable
*const var
= node
->as_variable();
622 /* Only assign locations for variables that lack an explicit location.
623 * Explicit locations are set for all built-in variables, generic vertex
624 * shader inputs (via layout(location=...)), and generic fragment shader
625 * outputs (also via layout(location=...)).
627 if (!var
->data
.explicit_location
) {
628 var
->data
.location
= -1;
629 var
->data
.location_frac
= 0;
632 /* ir_variable::is_unmatched_generic_inout is used by the linker while
633 * connecting outputs from one stage to inputs of the next stage.
635 if (var
->data
.explicit_location
&&
636 var
->data
.location
< VARYING_SLOT_VAR0
) {
637 var
->data
.is_unmatched_generic_inout
= 0;
639 var
->data
.is_unmatched_generic_inout
= 1;
646 * Set clip_distance_array_size based and cull_distance_array_size on the given
649 * Also check for errors based on incorrect usage of gl_ClipVertex and
650 * gl_ClipDistance and gl_CullDistance.
651 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
652 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
654 * Return false if an error was reported.
657 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
658 struct gl_linked_shader
*shader
,
659 struct gl_context
*ctx
,
660 GLuint
*clip_distance_array_size
,
661 GLuint
*cull_distance_array_size
)
663 *clip_distance_array_size
= 0;
664 *cull_distance_array_size
= 0;
666 if (prog
->Version
>= (prog
->IsES
? 300 : 130)) {
667 /* From section 7.1 (Vertex Shader Special Variables) of the
670 * "It is an error for a shader to statically write both
671 * gl_ClipVertex and gl_ClipDistance."
673 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
674 * gl_ClipVertex nor gl_ClipDistance. However with
675 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
677 find_assignment_visitor
clip_distance("gl_ClipDistance");
678 find_assignment_visitor
cull_distance("gl_CullDistance");
680 clip_distance
.run(shader
->ir
);
681 cull_distance
.run(shader
->ir
);
683 /* From the ARB_cull_distance spec:
685 * It is a compile-time or link-time error for the set of shaders forming
686 * a program to statically read or write both gl_ClipVertex and either
687 * gl_ClipDistance or gl_CullDistance.
689 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
693 find_assignment_visitor
clip_vertex("gl_ClipVertex");
695 clip_vertex
.run(shader
->ir
);
697 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
698 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
699 "and `gl_ClipDistance'\n",
700 _mesa_shader_stage_to_string(shader
->Stage
));
703 if (clip_vertex
.variable_found() && cull_distance
.variable_found()) {
704 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
705 "and `gl_CullDistance'\n",
706 _mesa_shader_stage_to_string(shader
->Stage
));
711 if (clip_distance
.variable_found()) {
712 ir_variable
*clip_distance_var
=
713 shader
->symbols
->get_variable("gl_ClipDistance");
714 assert(clip_distance_var
);
715 *clip_distance_array_size
= clip_distance_var
->type
->length
;
717 if (cull_distance
.variable_found()) {
718 ir_variable
*cull_distance_var
=
719 shader
->symbols
->get_variable("gl_CullDistance");
720 assert(cull_distance_var
);
721 *cull_distance_array_size
= cull_distance_var
->type
->length
;
723 /* From the ARB_cull_distance spec:
725 * It is a compile-time or link-time error for the set of shaders forming
726 * a program to have the sum of the sizes of the gl_ClipDistance and
727 * gl_CullDistance arrays to be larger than
728 * gl_MaxCombinedClipAndCullDistances.
730 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
731 ctx
->Const
.MaxClipPlanes
) {
732 linker_error(prog
, "%s shader: the combined size of "
733 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
735 "gl_MaxCombinedClipAndCullDistances (%u)",
736 _mesa_shader_stage_to_string(shader
->Stage
),
737 ctx
->Const
.MaxClipPlanes
);
744 * Verify that a vertex shader executable meets all semantic requirements.
746 * Also sets prog->Vert.ClipDistanceArraySize and
747 * prog->Vert.CullDistanceArraySize as a side effect.
749 * \param shader Vertex shader executable to be verified
752 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
753 struct gl_linked_shader
*shader
,
754 struct gl_context
*ctx
)
759 /* From the GLSL 1.10 spec, page 48:
761 * "The variable gl_Position is available only in the vertex
762 * language and is intended for writing the homogeneous vertex
763 * position. All executions of a well-formed vertex shader
764 * executable must write a value into this variable. [...] The
765 * variable gl_Position is available only in the vertex
766 * language and is intended for writing the homogeneous vertex
767 * position. All executions of a well-formed vertex shader
768 * executable must write a value into this variable."
770 * while in GLSL 1.40 this text is changed to:
772 * "The variable gl_Position is available only in the vertex
773 * language and is intended for writing the homogeneous vertex
774 * position. It can be written at any time during shader
775 * execution. It may also be read back by a vertex shader
776 * after being written. This value will be used by primitive
777 * assembly, clipping, culling, and other fixed functionality
778 * operations, if present, that operate on primitives after
779 * vertex processing has occurred. Its value is undefined if
780 * the vertex shader executable does not write gl_Position."
782 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
783 * gl_Position is not an error.
785 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
786 find_assignment_visitor
find("gl_Position");
787 find
.run(shader
->ir
);
788 if (!find
.variable_found()) {
791 "vertex shader does not write to `gl_Position'."
792 "It's value is undefined. \n");
795 "vertex shader does not write to `gl_Position'. \n");
801 analyze_clip_cull_usage(prog
, shader
, ctx
,
802 &prog
->Vert
.ClipDistanceArraySize
,
803 &prog
->Vert
.CullDistanceArraySize
);
807 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
808 struct gl_linked_shader
*shader
,
809 struct gl_context
*ctx
)
814 analyze_clip_cull_usage(prog
, shader
, ctx
,
815 &prog
->TessEval
.ClipDistanceArraySize
,
816 &prog
->TessEval
.CullDistanceArraySize
);
821 * Verify that a fragment shader executable meets all semantic requirements
823 * \param shader Fragment shader executable to be verified
826 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
827 struct gl_linked_shader
*shader
)
832 find_assignment_visitor
frag_color("gl_FragColor");
833 find_assignment_visitor
frag_data("gl_FragData");
835 frag_color
.run(shader
->ir
);
836 frag_data
.run(shader
->ir
);
838 if (frag_color
.variable_found() && frag_data
.variable_found()) {
839 linker_error(prog
, "fragment shader writes to both "
840 "`gl_FragColor' and `gl_FragData'\n");
845 * Verify that a geometry shader executable meets all semantic requirements
847 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize and
848 * prog->Geom.CullDistanceArraySize as a side effect.
850 * \param shader Geometry shader executable to be verified
853 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
854 struct gl_linked_shader
*shader
,
855 struct gl_context
*ctx
)
860 unsigned num_vertices
= vertices_per_prim(shader
->Geom
.InputType
);
861 prog
->Geom
.VerticesIn
= num_vertices
;
863 analyze_clip_cull_usage(prog
, shader
, ctx
,
864 &prog
->Geom
.ClipDistanceArraySize
,
865 &prog
->Geom
.CullDistanceArraySize
);
869 * Check if geometry shaders emit to non-zero streams and do corresponding
873 validate_geometry_shader_emissions(struct gl_context
*ctx
,
874 struct gl_shader_program
*prog
)
876 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
879 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
880 emit_vertex
.run(sh
->ir
);
881 if (emit_vertex
.error()) {
882 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
883 "stream parameter are in the range [0, %d].\n",
884 emit_vertex
.error_func(),
885 emit_vertex
.error_stream(),
886 ctx
->Const
.MaxVertexStreams
- 1);
888 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
889 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
891 /* From the ARB_gpu_shader5 spec:
893 * "Multiple vertex streams are supported only if the output primitive
894 * type is declared to be "points". A program will fail to link if it
895 * contains a geometry shader calling EmitStreamVertex() or
896 * EndStreamPrimitive() if its output primitive type is not "points".
898 * However, in the same spec:
900 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
901 * with <stream> set to zero."
905 * "The function EndPrimitive() is equivalent to calling
906 * EndStreamPrimitive() with <stream> set to zero."
908 * Since we can call EmitVertex() and EndPrimitive() when we output
909 * primitives other than points, calling EmitStreamVertex(0) or
910 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
911 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
912 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
915 if (prog
->Geom
.UsesStreams
&& sh
->Geom
.OutputType
!= GL_POINTS
) {
916 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
917 "with n>0 requires point output\n");
923 validate_intrastage_arrays(struct gl_shader_program
*prog
,
924 ir_variable
*const var
,
925 ir_variable
*const existing
)
927 /* Consider the types to be "the same" if both types are arrays
928 * of the same type and one of the arrays is implicitly sized.
929 * In addition, set the type of the linked variable to the
930 * explicitly sized array.
932 if (var
->type
->is_array() && existing
->type
->is_array()) {
933 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
934 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
935 if (var
->type
->length
!= 0) {
936 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
937 linker_error(prog
, "%s `%s' declared as type "
938 "`%s' but outermost dimension has an index"
941 var
->name
, var
->type
->name
,
942 existing
->data
.max_array_access
);
944 existing
->type
= var
->type
;
946 } else if (existing
->type
->length
!= 0) {
947 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
948 !existing
->data
.from_ssbo_unsized_array
) {
949 linker_error(prog
, "%s `%s' declared as type "
950 "`%s' but outermost dimension has an index"
953 var
->name
, existing
->type
->name
,
954 var
->data
.max_array_access
);
959 /* The arrays of structs could have different glsl_type pointers but
960 * they are actually the same type. Use record_compare() to check that.
962 if (existing
->type
->fields
.array
->is_record() &&
963 var
->type
->fields
.array
->is_record() &&
964 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
973 * Perform validation of global variables used across multiple shaders
976 cross_validate_globals(struct gl_shader_program
*prog
,
977 struct exec_list
*ir
, glsl_symbol_table
*variables
,
980 foreach_in_list(ir_instruction
, node
, ir
) {
981 ir_variable
*const var
= node
->as_variable();
986 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
989 /* don't cross validate subroutine uniforms */
990 if (var
->type
->contains_subroutine())
993 /* Don't cross validate temporaries that are at global scope. These
994 * will eventually get pulled into the shaders 'main'.
996 if (var
->data
.mode
== ir_var_temporary
)
999 /* If a global with this name has already been seen, verify that the
1000 * new instance has the same type. In addition, if the globals have
1001 * initializers, the values of the initializers must be the same.
1003 ir_variable
*const existing
= variables
->get_variable(var
->name
);
1004 if (existing
!= NULL
) {
1005 /* Check if types match. Interface blocks have some special
1006 * rules so we handle those elsewhere.
1008 if (var
->type
!= existing
->type
&&
1009 !var
->is_interface_instance()) {
1010 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
1011 if (var
->type
->is_record() && existing
->type
->is_record()
1012 && existing
->type
->record_compare(var
->type
)) {
1013 existing
->type
= var
->type
;
1015 /* If it is an unsized array in a Shader Storage Block,
1016 * two different shaders can access to different elements.
1017 * Because of that, they might be converted to different
1018 * sized arrays, then check that they are compatible but
1019 * ignore the array size.
1021 if (!(var
->data
.mode
== ir_var_shader_storage
&&
1022 var
->data
.from_ssbo_unsized_array
&&
1023 existing
->data
.mode
== ir_var_shader_storage
&&
1024 existing
->data
.from_ssbo_unsized_array
&&
1025 var
->type
->gl_type
== existing
->type
->gl_type
)) {
1026 linker_error(prog
, "%s `%s' declared as type "
1027 "`%s' and type `%s'\n",
1029 var
->name
, var
->type
->name
,
1030 existing
->type
->name
);
1037 if (var
->data
.explicit_location
) {
1038 if (existing
->data
.explicit_location
1039 && (var
->data
.location
!= existing
->data
.location
)) {
1040 linker_error(prog
, "explicit locations for %s "
1041 "`%s' have differing values\n",
1042 mode_string(var
), var
->name
);
1046 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
1047 linker_error(prog
, "explicit components for %s `%s' have "
1048 "differing values\n", mode_string(var
), var
->name
);
1052 existing
->data
.location
= var
->data
.location
;
1053 existing
->data
.explicit_location
= true;
1055 /* Check if uniform with implicit location was marked explicit
1056 * by earlier shader stage. If so, mark it explicit in this stage
1057 * too to make sure later processing does not treat it as
1060 if (existing
->data
.explicit_location
) {
1061 var
->data
.location
= existing
->data
.location
;
1062 var
->data
.explicit_location
= true;
1066 /* From the GLSL 4.20 specification:
1067 * "A link error will result if two compilation units in a program
1068 * specify different integer-constant bindings for the same
1069 * opaque-uniform name. However, it is not an error to specify a
1070 * binding on some but not all declarations for the same name"
1072 if (var
->data
.explicit_binding
) {
1073 if (existing
->data
.explicit_binding
&&
1074 var
->data
.binding
!= existing
->data
.binding
) {
1075 linker_error(prog
, "explicit bindings for %s "
1076 "`%s' have differing values\n",
1077 mode_string(var
), var
->name
);
1081 existing
->data
.binding
= var
->data
.binding
;
1082 existing
->data
.explicit_binding
= true;
1085 if (var
->type
->contains_atomic() &&
1086 var
->data
.offset
!= existing
->data
.offset
) {
1087 linker_error(prog
, "offset specifications for %s "
1088 "`%s' have differing values\n",
1089 mode_string(var
), var
->name
);
1093 /* Validate layout qualifiers for gl_FragDepth.
1095 * From the AMD/ARB_conservative_depth specs:
1097 * "If gl_FragDepth is redeclared in any fragment shader in a
1098 * program, it must be redeclared in all fragment shaders in
1099 * that program that have static assignments to
1100 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1101 * fragment shaders in a single program must have the same set
1104 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1105 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1106 bool layout_differs
=
1107 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1109 if (layout_declared
&& layout_differs
) {
1111 "All redeclarations of gl_FragDepth in all "
1112 "fragment shaders in a single program must have "
1113 "the same set of qualifiers.\n");
1116 if (var
->data
.used
&& layout_differs
) {
1118 "If gl_FragDepth is redeclared with a layout "
1119 "qualifier in any fragment shader, it must be "
1120 "redeclared with the same layout qualifier in "
1121 "all fragment shaders that have assignments to "
1126 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1128 * "If a shared global has multiple initializers, the
1129 * initializers must all be constant expressions, and they
1130 * must all have the same value. Otherwise, a link error will
1131 * result. (A shared global having only one initializer does
1132 * not require that initializer to be a constant expression.)"
1134 * Previous to 4.20 the GLSL spec simply said that initializers
1135 * must have the same value. In this case of non-constant
1136 * initializers, this was impossible to determine. As a result,
1137 * no vendor actually implemented that behavior. The 4.20
1138 * behavior matches the implemented behavior of at least one other
1139 * vendor, so we'll implement that for all GLSL versions.
1141 if (var
->constant_initializer
!= NULL
) {
1142 if (existing
->constant_initializer
!= NULL
) {
1143 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1144 linker_error(prog
, "initializers for %s "
1145 "`%s' have differing values\n",
1146 mode_string(var
), var
->name
);
1150 /* If the first-seen instance of a particular uniform did
1151 * not have an initializer but a later instance does,
1152 * replace the former with the later.
1154 variables
->replace_variable(existing
->name
, var
);
1158 if (var
->data
.has_initializer
) {
1159 if (existing
->data
.has_initializer
1160 && (var
->constant_initializer
== NULL
1161 || existing
->constant_initializer
== NULL
)) {
1163 "shared global variable `%s' has multiple "
1164 "non-constant initializers.\n",
1170 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1171 linker_error(prog
, "declarations for %s `%s' have "
1172 "mismatching invariant qualifiers\n",
1173 mode_string(var
), var
->name
);
1176 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1177 linker_error(prog
, "declarations for %s `%s' have "
1178 "mismatching centroid qualifiers\n",
1179 mode_string(var
), var
->name
);
1182 if (existing
->data
.sample
!= var
->data
.sample
) {
1183 linker_error(prog
, "declarations for %s `%s` have "
1184 "mismatching sample qualifiers\n",
1185 mode_string(var
), var
->name
);
1188 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1189 linker_error(prog
, "declarations for %s `%s` have "
1190 "mismatching image format qualifiers\n",
1191 mode_string(var
), var
->name
);
1195 variables
->add_variable(var
);
1201 * Perform validation of uniforms used across multiple shader stages
1204 cross_validate_uniforms(struct gl_shader_program
*prog
)
1206 glsl_symbol_table variables
;
1207 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1208 if (prog
->_LinkedShaders
[i
] == NULL
)
1211 cross_validate_globals(prog
, prog
->_LinkedShaders
[i
]->ir
, &variables
,
1217 * Accumulates the array of buffer blocks and checks that all definitions of
1218 * blocks agree on their contents.
1221 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1224 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1225 struct gl_uniform_block
*blks
= NULL
;
1226 unsigned *num_blks
= validate_ssbo
? &prog
->NumShaderStorageBlocks
:
1227 &prog
->NumUniformBlocks
;
1229 unsigned max_num_buffer_blocks
= 0;
1230 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1231 if (prog
->_LinkedShaders
[i
]) {
1232 if (validate_ssbo
) {
1233 max_num_buffer_blocks
+=
1234 prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1236 max_num_buffer_blocks
+=
1237 prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1242 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1243 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1245 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1246 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1247 InterfaceBlockStageIndex
[i
][j
] = -1;
1252 unsigned sh_num_blocks
;
1253 struct gl_uniform_block
**sh_blks
;
1254 if (validate_ssbo
) {
1255 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1256 sh_blks
= sh
->ShaderStorageBlocks
;
1258 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1259 sh_blks
= sh
->UniformBlocks
;
1262 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1263 int index
= link_cross_validate_uniform_block(prog
, &blks
, num_blks
,
1267 linker_error(prog
, "buffer block `%s' has mismatching "
1268 "definitions\n", sh_blks
[j
]->Name
);
1270 for (unsigned k
= 0; k
<= i
; k
++) {
1271 delete[] InterfaceBlockStageIndex
[k
];
1276 InterfaceBlockStageIndex
[i
][index
] = j
;
1280 /* Update per stage block pointers to point to the program list.
1281 * FIXME: We should be able to free the per stage blocks here.
1283 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1284 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1285 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1287 if (stage_index
!= -1) {
1288 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1290 blks
[j
].stageref
|= (1 << i
);
1292 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1293 sh
->ShaderStorageBlocks
: sh
->UniformBlocks
;
1295 sh_blks
[stage_index
] = &blks
[j
];
1300 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1301 delete[] InterfaceBlockStageIndex
[i
];
1305 prog
->ShaderStorageBlocks
= blks
;
1307 prog
->UniformBlocks
= blks
;
1314 * Populates a shaders symbol table with all global declarations
1317 populate_symbol_table(gl_linked_shader
*sh
)
1319 sh
->symbols
= new(sh
) glsl_symbol_table
;
1321 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1325 if ((func
= inst
->as_function()) != NULL
) {
1326 sh
->symbols
->add_function(func
);
1327 } else if ((var
= inst
->as_variable()) != NULL
) {
1328 if (var
->data
.mode
!= ir_var_temporary
)
1329 sh
->symbols
->add_variable(var
);
1336 * Remap variables referenced in an instruction tree
1338 * This is used when instruction trees are cloned from one shader and placed in
1339 * another. These trees will contain references to \c ir_variable nodes that
1340 * do not exist in the target shader. This function finds these \c ir_variable
1341 * references and replaces the references with matching variables in the target
1344 * If there is no matching variable in the target shader, a clone of the
1345 * \c ir_variable is made and added to the target shader. The new variable is
1346 * added to \b both the instruction stream and the symbol table.
1348 * \param inst IR tree that is to be processed.
1349 * \param symbols Symbol table containing global scope symbols in the
1351 * \param instructions Instruction stream where new variable declarations
1355 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1358 class remap_visitor
: public ir_hierarchical_visitor
{
1360 remap_visitor(struct gl_linked_shader
*target
,
1363 this->target
= target
;
1364 this->symbols
= target
->symbols
;
1365 this->instructions
= target
->ir
;
1366 this->temps
= temps
;
1369 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1371 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1372 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1374 assert(var
!= NULL
);
1376 return visit_continue
;
1379 ir_variable
*const existing
=
1380 this->symbols
->get_variable(ir
->var
->name
);
1381 if (existing
!= NULL
)
1384 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1386 this->symbols
->add_variable(copy
);
1387 this->instructions
->push_head(copy
);
1391 return visit_continue
;
1395 struct gl_linked_shader
*target
;
1396 glsl_symbol_table
*symbols
;
1397 exec_list
*instructions
;
1401 remap_visitor
v(target
, temps
);
1408 * Move non-declarations from one instruction stream to another
1410 * The intended usage pattern of this function is to pass the pointer to the
1411 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1412 * pointer) for \c last and \c false for \c make_copies on the first
1413 * call. Successive calls pass the return value of the previous call for
1414 * \c last and \c true for \c make_copies.
1416 * \param instructions Source instruction stream
1417 * \param last Instruction after which new instructions should be
1418 * inserted in the target instruction stream
1419 * \param make_copies Flag selecting whether instructions in \c instructions
1420 * should be copied (via \c ir_instruction::clone) into the
1421 * target list or moved.
1424 * The new "last" instruction in the target instruction stream. This pointer
1425 * is suitable for use as the \c last parameter of a later call to this
1429 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1430 bool make_copies
, gl_linked_shader
*target
)
1432 hash_table
*temps
= NULL
;
1435 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1436 hash_table_pointer_compare
);
1438 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1439 if (inst
->as_function())
1442 ir_variable
*var
= inst
->as_variable();
1443 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1446 assert(inst
->as_assignment()
1448 || inst
->as_if() /* for initializers with the ?: operator */
1449 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1452 inst
= inst
->clone(target
, NULL
);
1455 hash_table_insert(temps
, inst
, var
);
1457 remap_variables(inst
, target
, temps
);
1462 last
->insert_after(inst
);
1467 hash_table_dtor(temps
);
1474 * This class is only used in link_intrastage_shaders() below but declaring
1475 * it inside that function leads to compiler warnings with some versions of
1478 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1480 array_sizing_visitor()
1481 : mem_ctx(ralloc_context(NULL
)),
1482 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1483 hash_table_pointer_compare
))
1487 ~array_sizing_visitor()
1489 hash_table_dtor(this->unnamed_interfaces
);
1490 ralloc_free(this->mem_ctx
);
1493 virtual ir_visitor_status
visit(ir_variable
*var
)
1495 const glsl_type
*type_without_array
;
1496 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1497 fixup_type(&var
->type
, var
->data
.max_array_access
,
1498 var
->data
.from_ssbo_unsized_array
,
1499 &implicit_sized_array
);
1500 var
->data
.implicit_sized_array
= implicit_sized_array
;
1501 type_without_array
= var
->type
->without_array();
1502 if (var
->type
->is_interface()) {
1503 if (interface_contains_unsized_arrays(var
->type
)) {
1504 const glsl_type
*new_type
=
1505 resize_interface_members(var
->type
,
1506 var
->get_max_ifc_array_access(),
1507 var
->is_in_shader_storage_block());
1508 var
->type
= new_type
;
1509 var
->change_interface_type(new_type
);
1511 } else if (type_without_array
->is_interface()) {
1512 if (interface_contains_unsized_arrays(type_without_array
)) {
1513 const glsl_type
*new_type
=
1514 resize_interface_members(type_without_array
,
1515 var
->get_max_ifc_array_access(),
1516 var
->is_in_shader_storage_block());
1517 var
->change_interface_type(new_type
);
1518 var
->type
= update_interface_members_array(var
->type
, new_type
);
1520 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1521 /* Store a pointer to the variable in the unnamed_interfaces
1524 ir_variable
**interface_vars
= (ir_variable
**)
1525 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1526 if (interface_vars
== NULL
) {
1527 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1529 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1532 unsigned index
= ifc_type
->field_index(var
->name
);
1533 assert(index
< ifc_type
->length
);
1534 assert(interface_vars
[index
] == NULL
);
1535 interface_vars
[index
] = var
;
1537 return visit_continue
;
1541 * For each unnamed interface block that was discovered while running the
1542 * visitor, adjust the interface type to reflect the newly assigned array
1543 * sizes, and fix up the ir_variable nodes to point to the new interface
1546 void fixup_unnamed_interface_types()
1548 hash_table_call_foreach(this->unnamed_interfaces
,
1549 fixup_unnamed_interface_type
, NULL
);
1554 * If the type pointed to by \c type represents an unsized array, replace
1555 * it with a sized array whose size is determined by max_array_access.
1557 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1558 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1560 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1561 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1562 max_array_access
+ 1);
1563 *implicit_sized
= true;
1564 assert(*type
!= NULL
);
1568 static const glsl_type
*
1569 update_interface_members_array(const glsl_type
*type
,
1570 const glsl_type
*new_interface_type
)
1572 const glsl_type
*element_type
= type
->fields
.array
;
1573 if (element_type
->is_array()) {
1574 const glsl_type
*new_array_type
=
1575 update_interface_members_array(element_type
, new_interface_type
);
1576 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1578 return glsl_type::get_array_instance(new_interface_type
,
1584 * Determine whether the given interface type contains unsized arrays (if
1585 * it doesn't, array_sizing_visitor doesn't need to process it).
1587 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1589 for (unsigned i
= 0; i
< type
->length
; i
++) {
1590 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1591 if (elem_type
->is_unsized_array())
1598 * Create a new interface type based on the given type, with unsized arrays
1599 * replaced by sized arrays whose size is determined by
1600 * max_ifc_array_access.
1602 static const glsl_type
*
1603 resize_interface_members(const glsl_type
*type
,
1604 const int *max_ifc_array_access
,
1607 unsigned num_fields
= type
->length
;
1608 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1609 memcpy(fields
, type
->fields
.structure
,
1610 num_fields
* sizeof(*fields
));
1611 for (unsigned i
= 0; i
< num_fields
; i
++) {
1612 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1613 /* If SSBO last member is unsized array, we don't replace it by a sized
1616 if (is_ssbo
&& i
== (num_fields
- 1))
1617 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1618 true, &implicit_sized_array
);
1620 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1621 false, &implicit_sized_array
);
1622 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1624 glsl_interface_packing packing
=
1625 (glsl_interface_packing
) type
->interface_packing
;
1626 const glsl_type
*new_ifc_type
=
1627 glsl_type::get_interface_instance(fields
, num_fields
,
1628 packing
, type
->name
);
1630 return new_ifc_type
;
1633 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1636 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1637 ir_variable
**interface_vars
= (ir_variable
**) data
;
1638 unsigned num_fields
= ifc_type
->length
;
1639 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1640 memcpy(fields
, ifc_type
->fields
.structure
,
1641 num_fields
* sizeof(*fields
));
1642 bool interface_type_changed
= false;
1643 for (unsigned i
= 0; i
< num_fields
; i
++) {
1644 if (interface_vars
[i
] != NULL
&&
1645 fields
[i
].type
!= interface_vars
[i
]->type
) {
1646 fields
[i
].type
= interface_vars
[i
]->type
;
1647 interface_type_changed
= true;
1650 if (!interface_type_changed
) {
1654 glsl_interface_packing packing
=
1655 (glsl_interface_packing
) ifc_type
->interface_packing
;
1656 const glsl_type
*new_ifc_type
=
1657 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1660 for (unsigned i
= 0; i
< num_fields
; i
++) {
1661 if (interface_vars
[i
] != NULL
)
1662 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1667 * Memory context used to allocate the data in \c unnamed_interfaces.
1672 * Hash table from const glsl_type * to an array of ir_variable *'s
1673 * pointing to the ir_variables constituting each unnamed interface block.
1675 hash_table
*unnamed_interfaces
;
1679 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1683 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1684 struct gl_shader_program
*prog
,
1685 struct gl_linked_shader
*linked_shader
,
1686 struct gl_shader
**shader_list
,
1687 unsigned num_shaders
)
1689 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1690 linked_shader
->TransformFeedback
.BufferStride
[i
] = 0;
1693 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1694 struct gl_shader
*shader
= shader_list
[i
];
1696 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1697 if (shader
->TransformFeedback
.BufferStride
[j
]) {
1698 if (linked_shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1699 shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1700 linked_shader
->TransformFeedback
.BufferStride
[j
] !=
1701 shader
->TransformFeedback
.BufferStride
[j
]) {
1703 "intrastage shaders defined with conflicting "
1704 "xfb_stride for buffer %d (%d and %d)\n", j
,
1705 linked_shader
->TransformFeedback
.BufferStride
[j
],
1706 shader
->TransformFeedback
.BufferStride
[j
]);
1710 if (shader
->TransformFeedback
.BufferStride
[j
])
1711 linked_shader
->TransformFeedback
.BufferStride
[j
] =
1712 shader
->TransformFeedback
.BufferStride
[j
];
1717 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1718 if (linked_shader
->TransformFeedback
.BufferStride
[j
]) {
1719 prog
->TransformFeedback
.BufferStride
[j
] =
1720 linked_shader
->TransformFeedback
.BufferStride
[j
];
1722 /* We will validate doubles at a later stage */
1723 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1724 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1725 "multiple of 4 or if its applied to a type that is "
1726 "or contains a double a multiple of 8.",
1727 prog
->TransformFeedback
.BufferStride
[j
]);
1731 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1732 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1734 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1735 "limit has been exceeded.");
1743 * Performs the cross-validation of tessellation control shader vertices and
1744 * layout qualifiers for the attached tessellation control shaders,
1745 * and propagates them to the linked TCS and linked shader program.
1748 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1749 struct gl_linked_shader
*linked_shader
,
1750 struct gl_shader
**shader_list
,
1751 unsigned num_shaders
)
1753 linked_shader
->TessCtrl
.VerticesOut
= 0;
1755 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1758 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1760 * "All tessellation control shader layout declarations in a program
1761 * must specify the same output patch vertex count. There must be at
1762 * least one layout qualifier specifying an output patch vertex count
1763 * in any program containing tessellation control shaders; however,
1764 * such a declaration is not required in all tessellation control
1768 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1769 struct gl_shader
*shader
= shader_list
[i
];
1771 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1772 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1773 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1774 linker_error(prog
, "tessellation control shader defined with "
1775 "conflicting output vertex count (%d and %d)\n",
1776 linked_shader
->TessCtrl
.VerticesOut
,
1777 shader
->TessCtrl
.VerticesOut
);
1780 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1784 /* Just do the intrastage -> interstage propagation right now,
1785 * since we already know we're in the right type of shader program
1788 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1789 linker_error(prog
, "tessellation control shader didn't declare "
1790 "vertices out layout qualifier\n");
1797 * Performs the cross-validation of tessellation evaluation shader
1798 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1799 * for the attached tessellation evaluation shaders, and propagates them
1800 * to the linked TES and linked shader program.
1803 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1804 struct gl_linked_shader
*linked_shader
,
1805 struct gl_shader
**shader_list
,
1806 unsigned num_shaders
)
1808 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1809 linked_shader
->TessEval
.Spacing
= 0;
1810 linked_shader
->TessEval
.VertexOrder
= 0;
1811 linked_shader
->TessEval
.PointMode
= -1;
1813 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1816 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1818 * "At least one tessellation evaluation shader (compilation unit) in
1819 * a program must declare a primitive mode in its input layout.
1820 * Declaration vertex spacing, ordering, and point mode identifiers is
1821 * optional. It is not required that all tessellation evaluation
1822 * shaders in a program declare a primitive mode. If spacing or
1823 * vertex ordering declarations are omitted, the tessellation
1824 * primitive generator will use equal spacing or counter-clockwise
1825 * vertex ordering, respectively. If a point mode declaration is
1826 * omitted, the tessellation primitive generator will produce lines or
1827 * triangles according to the primitive mode."
1830 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1831 struct gl_shader
*shader
= shader_list
[i
];
1833 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1834 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1835 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1836 linker_error(prog
, "tessellation evaluation shader defined with "
1837 "conflicting input primitive modes.\n");
1840 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1843 if (shader
->TessEval
.Spacing
!= 0) {
1844 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1845 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1846 linker_error(prog
, "tessellation evaluation shader defined with "
1847 "conflicting vertex spacing.\n");
1850 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1853 if (shader
->TessEval
.VertexOrder
!= 0) {
1854 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1855 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1856 linker_error(prog
, "tessellation evaluation shader defined with "
1857 "conflicting ordering.\n");
1860 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1863 if (shader
->TessEval
.PointMode
!= -1) {
1864 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1865 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1866 linker_error(prog
, "tessellation evaluation shader defined with "
1867 "conflicting point modes.\n");
1870 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1875 /* Just do the intrastage -> interstage propagation right now,
1876 * since we already know we're in the right type of shader program
1879 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1881 "tessellation evaluation shader didn't declare input "
1882 "primitive modes.\n");
1886 if (linked_shader
->TessEval
.Spacing
== 0)
1887 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1889 if (linked_shader
->TessEval
.VertexOrder
== 0)
1890 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1892 if (linked_shader
->TessEval
.PointMode
== -1)
1893 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1898 * Performs the cross-validation of layout qualifiers specified in
1899 * redeclaration of gl_FragCoord for the attached fragment shaders,
1900 * and propagates them to the linked FS and linked shader program.
1903 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1904 struct gl_linked_shader
*linked_shader
,
1905 struct gl_shader
**shader_list
,
1906 unsigned num_shaders
)
1908 linked_shader
->redeclares_gl_fragcoord
= false;
1909 linked_shader
->uses_gl_fragcoord
= false;
1910 linked_shader
->origin_upper_left
= false;
1911 linked_shader
->pixel_center_integer
= false;
1913 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1914 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1917 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1918 struct gl_shader
*shader
= shader_list
[i
];
1919 /* From the GLSL 1.50 spec, page 39:
1921 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1922 * it must be redeclared in all the fragment shaders in that program
1923 * that have a static use gl_FragCoord."
1925 if ((linked_shader
->redeclares_gl_fragcoord
1926 && !shader
->redeclares_gl_fragcoord
1927 && shader
->uses_gl_fragcoord
)
1928 || (shader
->redeclares_gl_fragcoord
1929 && !linked_shader
->redeclares_gl_fragcoord
1930 && linked_shader
->uses_gl_fragcoord
)) {
1931 linker_error(prog
, "fragment shader defined with conflicting "
1932 "layout qualifiers for gl_FragCoord\n");
1935 /* From the GLSL 1.50 spec, page 39:
1937 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1938 * single program must have the same set of qualifiers."
1940 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1941 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1942 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1943 linker_error(prog
, "fragment shader defined with conflicting "
1944 "layout qualifiers for gl_FragCoord\n");
1947 /* Update the linked shader state. Note that uses_gl_fragcoord should
1948 * accumulate the results. The other values should replace. If there
1949 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1950 * are already known to be the same.
1952 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1953 linked_shader
->redeclares_gl_fragcoord
=
1954 shader
->redeclares_gl_fragcoord
;
1955 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1956 || shader
->uses_gl_fragcoord
;
1957 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1958 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1961 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1966 * Performs the cross-validation of geometry shader max_vertices and
1967 * primitive type layout qualifiers for the attached geometry shaders,
1968 * and propagates them to the linked GS and linked shader program.
1971 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1972 struct gl_linked_shader
*linked_shader
,
1973 struct gl_shader
**shader_list
,
1974 unsigned num_shaders
)
1976 linked_shader
->Geom
.VerticesOut
= -1;
1977 linked_shader
->Geom
.Invocations
= 0;
1978 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1979 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1981 /* No in/out qualifiers defined for anything but GLSL 1.50+
1982 * geometry shaders so far.
1984 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1987 /* From the GLSL 1.50 spec, page 46:
1989 * "All geometry shader output layout declarations in a program
1990 * must declare the same layout and same value for
1991 * max_vertices. There must be at least one geometry output
1992 * layout declaration somewhere in a program, but not all
1993 * geometry shaders (compilation units) are required to
1997 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1998 struct gl_shader
*shader
= shader_list
[i
];
2000 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
2001 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
2002 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
2003 linker_error(prog
, "geometry shader defined with conflicting "
2007 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
2010 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
2011 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
2012 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
2013 linker_error(prog
, "geometry shader defined with conflicting "
2017 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
2020 if (shader
->Geom
.VerticesOut
!= -1) {
2021 if (linked_shader
->Geom
.VerticesOut
!= -1 &&
2022 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
2023 linker_error(prog
, "geometry shader defined with conflicting "
2024 "output vertex count (%d and %d)\n",
2025 linked_shader
->Geom
.VerticesOut
,
2026 shader
->Geom
.VerticesOut
);
2029 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
2032 if (shader
->Geom
.Invocations
!= 0) {
2033 if (linked_shader
->Geom
.Invocations
!= 0 &&
2034 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
2035 linker_error(prog
, "geometry shader defined with conflicting "
2036 "invocation count (%d and %d)\n",
2037 linked_shader
->Geom
.Invocations
,
2038 shader
->Geom
.Invocations
);
2041 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
2045 /* Just do the intrastage -> interstage propagation right now,
2046 * since we already know we're in the right type of shader program
2049 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
2051 "geometry shader didn't declare primitive input type\n");
2055 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
2057 "geometry shader didn't declare primitive output type\n");
2061 if (linked_shader
->Geom
.VerticesOut
== -1) {
2063 "geometry shader didn't declare max_vertices\n");
2067 if (linked_shader
->Geom
.Invocations
== 0)
2068 linked_shader
->Geom
.Invocations
= 1;
2073 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2074 * qualifiers for the attached compute shaders, and propagate them to the
2075 * linked CS and linked shader program.
2078 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2079 struct gl_linked_shader
*linked_shader
,
2080 struct gl_shader
**shader_list
,
2081 unsigned num_shaders
)
2083 for (int i
= 0; i
< 3; i
++)
2084 linked_shader
->Comp
.LocalSize
[i
] = 0;
2086 /* This function is called for all shader stages, but it only has an effect
2087 * for compute shaders.
2089 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2092 /* From the ARB_compute_shader spec, in the section describing local size
2095 * If multiple compute shaders attached to a single program object
2096 * declare local work-group size, the declarations must be identical;
2097 * otherwise a link-time error results. Furthermore, if a program
2098 * object contains any compute shaders, at least one must contain an
2099 * input layout qualifier specifying the local work sizes of the
2100 * program, or a link-time error will occur.
2102 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2103 struct gl_shader
*shader
= shader_list
[sh
];
2105 if (shader
->Comp
.LocalSize
[0] != 0) {
2106 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
2107 for (int i
= 0; i
< 3; i
++) {
2108 if (linked_shader
->Comp
.LocalSize
[i
] !=
2109 shader
->Comp
.LocalSize
[i
]) {
2110 linker_error(prog
, "compute shader defined with conflicting "
2116 for (int i
= 0; i
< 3; i
++)
2117 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
2121 /* Just do the intrastage -> interstage propagation right now,
2122 * since we already know we're in the right type of shader program
2125 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
2126 linker_error(prog
, "compute shader didn't declare local size\n");
2129 for (int i
= 0; i
< 3; i
++)
2130 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
2135 * Combine a group of shaders for a single stage to generate a linked shader
2138 * If this function is supplied a single shader, it is cloned, and the new
2139 * shader is returned.
2141 static struct gl_linked_shader
*
2142 link_intrastage_shaders(void *mem_ctx
,
2143 struct gl_context
*ctx
,
2144 struct gl_shader_program
*prog
,
2145 struct gl_shader
**shader_list
,
2146 unsigned num_shaders
)
2148 struct gl_uniform_block
*ubo_blocks
= NULL
;
2149 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2150 unsigned num_ubo_blocks
= 0;
2151 unsigned num_ssbo_blocks
= 0;
2153 /* Check that global variables defined in multiple shaders are consistent.
2155 glsl_symbol_table variables
;
2156 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2157 if (shader_list
[i
] == NULL
)
2159 cross_validate_globals(prog
, shader_list
[i
]->ir
, &variables
, false);
2162 if (!prog
->LinkStatus
)
2165 /* Check that interface blocks defined in multiple shaders are consistent.
2167 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2169 if (!prog
->LinkStatus
)
2172 /* Check that there is only a single definition of each function signature
2173 * across all shaders.
2175 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2176 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2177 ir_function
*const f
= node
->as_function();
2182 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2183 ir_function
*const other
=
2184 shader_list
[j
]->symbols
->get_function(f
->name
);
2186 /* If the other shader has no function (and therefore no function
2187 * signatures) with the same name, skip to the next shader.
2192 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2193 if (!sig
->is_defined
|| sig
->is_builtin())
2196 ir_function_signature
*other_sig
=
2197 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2199 if ((other_sig
!= NULL
) && other_sig
->is_defined
2200 && !other_sig
->is_builtin()) {
2201 linker_error(prog
, "function `%s' is multiply defined\n",
2210 /* Find the shader that defines main, and make a clone of it.
2212 * Starting with the clone, search for undefined references. If one is
2213 * found, find the shader that defines it. Clone the reference and add
2214 * it to the shader. Repeat until there are no undefined references or
2215 * until a reference cannot be resolved.
2217 gl_shader
*main
= NULL
;
2218 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2219 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2220 main
= shader_list
[i
];
2226 linker_error(prog
, "%s shader lacks `main'\n",
2227 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2231 gl_linked_shader
*linked
= ctx
->Driver
.NewShader(shader_list
[0]->Stage
);
2232 linked
->ir
= new(linked
) exec_list
;
2233 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2235 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2236 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2237 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2238 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2239 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2240 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2243 populate_symbol_table(linked
);
2245 /* The pointer to the main function in the final linked shader (i.e., the
2246 * copy of the original shader that contained the main function).
2248 ir_function_signature
*const main_sig
=
2249 _mesa_get_main_function_signature(linked
->symbols
);
2251 /* Move any instructions other than variable declarations or function
2252 * declarations into main.
2254 exec_node
*insertion_point
=
2255 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2258 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2259 if (shader_list
[i
] == main
)
2262 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2263 insertion_point
, true, linked
);
2266 /* Check if any shader needs built-in functions. */
2267 bool need_builtins
= false;
2268 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2269 if (shader_list
[i
]->uses_builtin_functions
) {
2270 need_builtins
= true;
2276 if (need_builtins
) {
2277 /* Make a temporary array one larger than shader_list, which will hold
2278 * the built-in function shader as well.
2280 gl_shader
**linking_shaders
= (gl_shader
**)
2281 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2283 ok
= linking_shaders
!= NULL
;
2286 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2287 _mesa_glsl_initialize_builtin_functions();
2288 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2290 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2292 free(linking_shaders
);
2294 _mesa_error_no_memory(__func__
);
2297 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2302 _mesa_delete_linked_shader(ctx
, linked
);
2306 /* Make a pass over all variable declarations to ensure that arrays with
2307 * unspecified sizes have a size specified. The size is inferred from the
2308 * max_array_access field.
2310 array_sizing_visitor v
;
2312 v
.fixup_unnamed_interface_types();
2314 /* Link up uniform blocks defined within this stage. */
2315 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2316 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2318 if (!prog
->LinkStatus
) {
2319 _mesa_delete_linked_shader(ctx
, linked
);
2323 /* Copy ubo blocks to linked shader list */
2324 linked
->UniformBlocks
=
2325 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2326 ralloc_steal(linked
, ubo_blocks
);
2327 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2328 linked
->UniformBlocks
[i
] = &ubo_blocks
[i
];
2330 linked
->NumUniformBlocks
= num_ubo_blocks
;
2332 /* Copy ssbo blocks to linked shader list */
2333 linked
->ShaderStorageBlocks
=
2334 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2335 ralloc_steal(linked
, ssbo_blocks
);
2336 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2337 linked
->ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2339 linked
->NumShaderStorageBlocks
= num_ssbo_blocks
;
2341 /* At this point linked should contain all of the linked IR, so
2342 * validate it to make sure nothing went wrong.
2344 validate_ir_tree(linked
->ir
);
2346 /* Set the size of geometry shader input arrays */
2347 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2348 unsigned num_vertices
= vertices_per_prim(linked
->Geom
.InputType
);
2349 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2350 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2351 ir
->accept(&input_resize_visitor
);
2355 if (ctx
->Const
.VertexID_is_zero_based
)
2356 lower_vertex_id(linked
);
2358 /* Validate correct usage of barrier() in the tess control shader */
2359 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2360 barrier_use_visitor
visitor(prog
);
2361 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2362 ir
->accept(&visitor
);
2370 * Update the sizes of linked shader uniform arrays to the maximum
2373 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2375 * If one or more elements of an array are active,
2376 * GetActiveUniform will return the name of the array in name,
2377 * subject to the restrictions listed above. The type of the array
2378 * is returned in type. The size parameter contains the highest
2379 * array element index used, plus one. The compiler or linker
2380 * determines the highest index used. There will be only one
2381 * active uniform reported by the GL per uniform array.
2385 update_array_sizes(struct gl_shader_program
*prog
)
2387 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2388 if (prog
->_LinkedShaders
[i
] == NULL
)
2391 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2392 ir_variable
*const var
= node
->as_variable();
2394 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2395 !var
->type
->is_array())
2398 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2399 * will not be eliminated. Since we always do std140, just
2400 * don't resize arrays in UBOs.
2402 * Atomic counters are supposed to get deterministic
2403 * locations assigned based on the declaration ordering and
2404 * sizes, array compaction would mess that up.
2406 * Subroutine uniforms are not removed.
2408 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2409 var
->type
->contains_subroutine() || var
->constant_initializer
)
2412 int size
= var
->data
.max_array_access
;
2413 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2414 if (prog
->_LinkedShaders
[j
] == NULL
)
2417 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2418 ir_variable
*other_var
= node2
->as_variable();
2422 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2423 other_var
->data
.max_array_access
> size
) {
2424 size
= other_var
->data
.max_array_access
;
2429 if (size
+ 1 != (int)var
->type
->length
) {
2430 /* If this is a built-in uniform (i.e., it's backed by some
2431 * fixed-function state), adjust the number of state slots to
2432 * match the new array size. The number of slots per array entry
2433 * is not known. It seems safe to assume that the total number of
2434 * slots is an integer multiple of the number of array elements.
2435 * Determine the number of slots per array element by dividing by
2436 * the old (total) size.
2438 const unsigned num_slots
= var
->get_num_state_slots();
2439 if (num_slots
> 0) {
2440 var
->set_num_state_slots((size
+ 1)
2441 * (num_slots
/ var
->type
->length
));
2444 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2446 /* FINISHME: We should update the types of array
2447 * dereferences of this variable now.
2455 * Resize tessellation evaluation per-vertex inputs to the size of
2456 * tessellation control per-vertex outputs.
2459 resize_tes_inputs(struct gl_context
*ctx
,
2460 struct gl_shader_program
*prog
)
2462 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2465 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2466 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2468 /* If no control shader is present, then the TES inputs are statically
2469 * sized to MaxPatchVertices; the actual size of the arrays won't be
2470 * known until draw time.
2472 const int num_vertices
= tcs
2473 ? tcs
->TessCtrl
.VerticesOut
2474 : ctx
->Const
.MaxPatchVertices
;
2476 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2477 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2478 ir
->accept(&input_resize_visitor
);
2481 if (tcs
|| ctx
->Const
.LowerTESPatchVerticesIn
) {
2482 /* Convert the gl_PatchVerticesIn system value into a constant, since
2483 * the value is known at this point.
2485 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2486 ir_variable
*var
= ir
->as_variable();
2487 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2488 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2489 void *mem_ctx
= ralloc_parent(var
);
2490 var
->data
.location
= 0;
2491 var
->data
.explicit_location
= false;
2493 var
->data
.mode
= ir_var_auto
;
2494 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2496 var
->data
.mode
= ir_var_uniform
;
2497 var
->data
.how_declared
= ir_var_hidden
;
2498 var
->allocate_state_slots(1);
2499 ir_state_slot
*slot0
= &var
->get_state_slots()[0];
2500 slot0
->swizzle
= SWIZZLE_XXXX
;
2501 slot0
->tokens
[0] = STATE_INTERNAL
;
2502 slot0
->tokens
[1] = STATE_TES_PATCH_VERTICES_IN
;
2503 for (int i
= 2; i
< STATE_LENGTH
; i
++)
2504 slot0
->tokens
[i
] = 0;
2512 * Find a contiguous set of available bits in a bitmask.
2514 * \param used_mask Bits representing used (1) and unused (0) locations
2515 * \param needed_count Number of contiguous bits needed.
2518 * Base location of the available bits on success or -1 on failure.
2521 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2523 unsigned needed_mask
= (1 << needed_count
) - 1;
2524 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2526 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2527 * cannot optimize possibly infinite loops" for the loop below.
2529 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2532 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2533 if ((needed_mask
& ~used_mask
) == needed_mask
)
2544 * Assign locations for either VS inputs or FS outputs
2546 * \param prog Shader program whose variables need locations assigned
2547 * \param constants Driver specific constant values for the program.
2548 * \param target_index Selector for the program target to receive location
2549 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2550 * \c MESA_SHADER_FRAGMENT.
2553 * If locations are successfully assigned, true is returned. Otherwise an
2554 * error is emitted to the shader link log and false is returned.
2557 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2558 struct gl_constants
*constants
,
2559 unsigned target_index
)
2561 /* Maximum number of generic locations. This corresponds to either the
2562 * maximum number of draw buffers or the maximum number of generic
2565 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2566 constants
->Program
[target_index
].MaxAttribs
:
2567 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2569 /* Mark invalid locations as being used.
2571 unsigned used_locations
= (max_index
>= 32)
2572 ? ~0 : ~((1 << max_index
) - 1);
2573 unsigned double_storage_locations
= 0;
2575 assert((target_index
== MESA_SHADER_VERTEX
)
2576 || (target_index
== MESA_SHADER_FRAGMENT
));
2578 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2582 /* Operate in a total of four passes.
2584 * 1. Invalidate the location assignments for all vertex shader inputs.
2586 * 2. Assign locations for inputs that have user-defined (via
2587 * glBindVertexAttribLocation) locations and outputs that have
2588 * user-defined locations (via glBindFragDataLocation).
2590 * 3. Sort the attributes without assigned locations by number of slots
2591 * required in decreasing order. Fragmentation caused by attribute
2592 * locations assigned by the application may prevent large attributes
2593 * from having enough contiguous space.
2595 * 4. Assign locations to any inputs without assigned locations.
2598 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2599 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2601 const enum ir_variable_mode direction
=
2602 (target_index
== MESA_SHADER_VERTEX
)
2603 ? ir_var_shader_in
: ir_var_shader_out
;
2606 /* Temporary storage for the set of attributes that need locations assigned.
2612 /* Used below in the call to qsort. */
2613 static int compare(const void *a
, const void *b
)
2615 const temp_attr
*const l
= (const temp_attr
*) a
;
2616 const temp_attr
*const r
= (const temp_attr
*) b
;
2618 /* Reversed because we want a descending order sort below. */
2619 return r
->slots
- l
->slots
;
2622 assert(max_index
<= 32);
2624 /* Temporary array for the set of attributes that have locations assigned.
2626 ir_variable
*assigned
[16];
2628 unsigned num_attr
= 0;
2629 unsigned assigned_attr
= 0;
2631 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2632 ir_variable
*const var
= node
->as_variable();
2634 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2637 if (var
->data
.explicit_location
) {
2638 var
->data
.is_unmatched_generic_inout
= 0;
2639 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2640 || (var
->data
.location
< 0)) {
2642 "invalid explicit location %d specified for `%s'\n",
2643 (var
->data
.location
< 0)
2644 ? var
->data
.location
2645 : var
->data
.location
- generic_base
,
2649 } else if (target_index
== MESA_SHADER_VERTEX
) {
2652 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2653 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2654 var
->data
.location
= binding
;
2655 var
->data
.is_unmatched_generic_inout
= 0;
2657 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2661 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2662 assert(binding
>= FRAG_RESULT_DATA0
);
2663 var
->data
.location
= binding
;
2664 var
->data
.is_unmatched_generic_inout
= 0;
2666 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2667 var
->data
.index
= index
;
2672 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2674 * "Output binding assignments will cause LinkProgram to fail:
2676 * If the program has an active output assigned to a location greater
2677 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2678 * an active output assigned an index greater than or equal to one;"
2680 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2681 var
->data
.location
- generic_base
>=
2682 (int) constants
->MaxDualSourceDrawBuffers
) {
2684 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2685 "with index %u for %s\n",
2686 var
->data
.location
- generic_base
, var
->data
.index
,
2691 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2693 /* If the variable is not a built-in and has a location statically
2694 * assigned in the shader (presumably via a layout qualifier), make sure
2695 * that it doesn't collide with other assigned locations. Otherwise,
2696 * add it to the list of variables that need linker-assigned locations.
2698 if (var
->data
.location
!= -1) {
2699 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2700 /* From page 61 of the OpenGL 4.0 spec:
2702 * "LinkProgram will fail if the attribute bindings assigned
2703 * by BindAttribLocation do not leave not enough space to
2704 * assign a location for an active matrix attribute or an
2705 * active attribute array, both of which require multiple
2706 * contiguous generic attributes."
2708 * I think above text prohibits the aliasing of explicit and
2709 * automatic assignments. But, aliasing is allowed in manual
2710 * assignments of attribute locations. See below comments for
2713 * From OpenGL 4.0 spec, page 61:
2715 * "It is possible for an application to bind more than one
2716 * attribute name to the same location. This is referred to as
2717 * aliasing. This will only work if only one of the aliased
2718 * attributes is active in the executable program, or if no
2719 * path through the shader consumes more than one attribute of
2720 * a set of attributes aliased to the same location. A link
2721 * error can occur if the linker determines that every path
2722 * through the shader consumes multiple aliased attributes,
2723 * but implementations are not required to generate an error
2726 * From GLSL 4.30 spec, page 54:
2728 * "A program will fail to link if any two non-vertex shader
2729 * input variables are assigned to the same location. For
2730 * vertex shaders, multiple input variables may be assigned
2731 * to the same location using either layout qualifiers or via
2732 * the OpenGL API. However, such aliasing is intended only to
2733 * support vertex shaders where each execution path accesses
2734 * at most one input per each location. Implementations are
2735 * permitted, but not required, to generate link-time errors
2736 * if they detect that every path through the vertex shader
2737 * executable accesses multiple inputs assigned to any single
2738 * location. For all shader types, a program will fail to link
2739 * if explicit location assignments leave the linker unable
2740 * to find space for other variables without explicit
2743 * From OpenGL ES 3.0 spec, page 56:
2745 * "Binding more than one attribute name to the same location
2746 * is referred to as aliasing, and is not permitted in OpenGL
2747 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2748 * fail when this condition exists. However, aliasing is
2749 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2750 * This will only work if only one of the aliased attributes
2751 * is active in the executable program, or if no path through
2752 * the shader consumes more than one attribute of a set of
2753 * attributes aliased to the same location. A link error can
2754 * occur if the linker determines that every path through the
2755 * shader consumes multiple aliased attributes, but implemen-
2756 * tations are not required to generate an error in this case."
2758 * After looking at above references from OpenGL, OpenGL ES and
2759 * GLSL specifications, we allow aliasing of vertex input variables
2760 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2762 * NOTE: This is not required by the spec but its worth mentioning
2763 * here that we're not doing anything to make sure that no path
2764 * through the vertex shader executable accesses multiple inputs
2765 * assigned to any single location.
2768 /* Mask representing the contiguous slots that will be used by
2771 const unsigned attr
= var
->data
.location
- generic_base
;
2772 const unsigned use_mask
= (1 << slots
) - 1;
2773 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2774 ? "vertex shader input" : "fragment shader output";
2776 /* Generate a link error if the requested locations for this
2777 * attribute exceed the maximum allowed attribute location.
2779 if (attr
+ slots
> max_index
) {
2781 "insufficient contiguous locations "
2782 "available for %s `%s' %d %d %d\n", string
,
2783 var
->name
, used_locations
, use_mask
, attr
);
2787 /* Generate a link error if the set of bits requested for this
2788 * attribute overlaps any previously allocated bits.
2790 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2791 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2792 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2795 * "Additionally, for fragment shader outputs, if two
2796 * variables are placed within the same location, they
2797 * must have the same underlying type (floating-point or
2798 * integer). No component aliasing of output variables or
2799 * members is allowed.
2801 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2802 unsigned assigned_slots
=
2803 assigned
[i
]->type
->count_attribute_slots(false);
2804 unsigned assig_attr
=
2805 assigned
[i
]->data
.location
- generic_base
;
2806 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2808 if ((assigned_use_mask
<< assig_attr
) &
2809 (use_mask
<< attr
)) {
2811 const glsl_type
*assigned_type
=
2812 assigned
[i
]->type
->without_array();
2813 const glsl_type
*type
= var
->type
->without_array();
2814 if (assigned_type
->base_type
!= type
->base_type
) {
2815 linker_error(prog
, "types do not match for aliased"
2816 " %ss %s and %s\n", string
,
2817 assigned
[i
]->name
, var
->name
);
2821 unsigned assigned_component_mask
=
2822 ((1 << assigned_type
->vector_elements
) - 1) <<
2823 assigned
[i
]->data
.location_frac
;
2824 unsigned component_mask
=
2825 ((1 << type
->vector_elements
) - 1) <<
2826 var
->data
.location_frac
;
2827 if (assigned_component_mask
& component_mask
) {
2828 linker_error(prog
, "overlapping component is "
2829 "assigned to %ss %s and %s "
2831 string
, assigned
[i
]->name
, var
->name
,
2832 var
->data
.location_frac
);
2837 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2838 (prog
->IsES
&& prog
->Version
>= 300)) {
2839 linker_error(prog
, "overlapping location is assigned "
2840 "to %s `%s' %d %d %d\n", string
, var
->name
,
2841 used_locations
, use_mask
, attr
);
2844 linker_warning(prog
, "overlapping location is assigned "
2845 "to %s `%s' %d %d %d\n", string
, var
->name
,
2846 used_locations
, use_mask
, attr
);
2850 used_locations
|= (use_mask
<< attr
);
2852 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2854 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2855 * active attribute variables may fail to link, unless
2856 * device-dependent optimizations are able to make the program
2857 * fit within available hardware resources. For the purposes
2858 * of this test, attribute variables of the type dvec3, dvec4,
2859 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2860 * count as consuming twice as many attributes as equivalent
2861 * single-precision types. While these types use the same number
2862 * of generic attributes as their single-precision equivalents,
2863 * implementations are permitted to consume two single-precision
2864 * vectors of internal storage for each three- or four-component
2865 * double-precision vector."
2867 * Mark this attribute slot as taking up twice as much space
2868 * so we can count it properly against limits. According to
2869 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2870 * is optional behavior, but it seems preferable.
2872 if (var
->type
->without_array()->is_dual_slot())
2873 double_storage_locations
|= (use_mask
<< attr
);
2876 assigned
[assigned_attr
] = var
;
2882 if (num_attr
>= max_index
) {
2883 linker_error(prog
, "too many %s (max %u)",
2884 target_index
== MESA_SHADER_VERTEX
?
2885 "vertex shader inputs" : "fragment shader outputs",
2889 to_assign
[num_attr
].slots
= slots
;
2890 to_assign
[num_attr
].var
= var
;
2894 if (target_index
== MESA_SHADER_VERTEX
) {
2895 unsigned total_attribs_size
=
2896 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2897 _mesa_bitcount(double_storage_locations
);
2898 if (total_attribs_size
> max_index
) {
2900 "attempt to use %d vertex attribute slots only %d available ",
2901 total_attribs_size
, max_index
);
2906 /* If all of the attributes were assigned locations by the application (or
2907 * are built-in attributes with fixed locations), return early. This should
2908 * be the common case.
2913 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2915 if (target_index
== MESA_SHADER_VERTEX
) {
2916 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2917 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2918 * reserved to prevent it from being automatically allocated below.
2920 find_deref_visitor
find("gl_Vertex");
2922 if (find
.variable_found())
2923 used_locations
|= (1 << 0);
2926 for (unsigned i
= 0; i
< num_attr
; i
++) {
2927 /* Mask representing the contiguous slots that will be used by this
2930 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2932 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2935 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2936 ? "vertex shader input" : "fragment shader output";
2939 "insufficient contiguous locations "
2940 "available for %s `%s'\n",
2941 string
, to_assign
[i
].var
->name
);
2945 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2946 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2947 used_locations
|= (use_mask
<< location
);
2949 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
2950 double_storage_locations
|= (use_mask
<< location
);
2953 /* Now that we have all the locations, from the GL 4.5 core spec, section
2954 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
2955 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
2956 * as equivalent single-precision types.
2958 if (target_index
== MESA_SHADER_VERTEX
) {
2959 unsigned total_attribs_size
=
2960 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2961 _mesa_bitcount(double_storage_locations
);
2962 if (total_attribs_size
> max_index
) {
2964 "attempt to use %d vertex attribute slots only %d available ",
2965 total_attribs_size
, max_index
);
2974 * Match explicit locations of outputs to inputs and deactivate the
2975 * unmatch flag if found so we don't optimise them away.
2978 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
2979 gl_linked_shader
*consumer
)
2981 glsl_symbol_table parameters
;
2982 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
2985 /* Find all shader outputs in the "producer" stage.
2987 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2988 ir_variable
*const var
= node
->as_variable();
2990 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2993 if (var
->data
.explicit_location
&&
2994 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2995 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2996 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
2997 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3001 /* Match inputs to outputs */
3002 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3003 ir_variable
*const input
= node
->as_variable();
3005 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3008 ir_variable
*output
= NULL
;
3009 if (input
->data
.explicit_location
3010 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3011 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3012 [input
->data
.location_frac
];
3014 if (output
!= NULL
){
3015 input
->data
.is_unmatched_generic_inout
= 0;
3016 output
->data
.is_unmatched_generic_inout
= 0;
3023 * Store the gl_FragDepth layout in the gl_shader_program struct.
3026 store_fragdepth_layout(struct gl_shader_program
*prog
)
3028 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3032 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3034 /* We don't look up the gl_FragDepth symbol directly because if
3035 * gl_FragDepth is not used in the shader, it's removed from the IR.
3036 * However, the symbol won't be removed from the symbol table.
3038 * We're only interested in the cases where the variable is NOT removed
3041 foreach_in_list(ir_instruction
, node
, ir
) {
3042 ir_variable
*const var
= node
->as_variable();
3044 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3048 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3049 switch (var
->data
.depth_layout
) {
3050 case ir_depth_layout_none
:
3051 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3053 case ir_depth_layout_any
:
3054 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3056 case ir_depth_layout_greater
:
3057 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3059 case ir_depth_layout_less
:
3060 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3062 case ir_depth_layout_unchanged
:
3063 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3074 * Validate the resources used by a program versus the implementation limits
3077 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3079 unsigned total_uniform_blocks
= 0;
3080 unsigned total_shader_storage_blocks
= 0;
3082 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3083 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3088 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3089 linker_error(prog
, "Too many %s shader texture samplers\n",
3090 _mesa_shader_stage_to_string(i
));
3093 if (sh
->num_uniform_components
>
3094 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3095 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3096 linker_warning(prog
, "Too many %s shader default uniform block "
3097 "components, but the driver will try to optimize "
3098 "them out; this is non-portable out-of-spec "
3100 _mesa_shader_stage_to_string(i
));
3102 linker_error(prog
, "Too many %s shader default uniform block "
3104 _mesa_shader_stage_to_string(i
));
3108 if (sh
->num_combined_uniform_components
>
3109 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3110 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3111 linker_warning(prog
, "Too many %s shader uniform components, "
3112 "but the driver will try to optimize them out; "
3113 "this is non-portable out-of-spec behavior\n",
3114 _mesa_shader_stage_to_string(i
));
3116 linker_error(prog
, "Too many %s shader uniform components\n",
3117 _mesa_shader_stage_to_string(i
));
3121 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3122 total_uniform_blocks
+= sh
->NumUniformBlocks
;
3124 const unsigned max_uniform_blocks
=
3125 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3126 if (max_uniform_blocks
< sh
->NumUniformBlocks
) {
3127 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3128 _mesa_shader_stage_to_string(i
), sh
->NumUniformBlocks
,
3129 max_uniform_blocks
);
3132 const unsigned max_shader_storage_blocks
=
3133 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3134 if (max_shader_storage_blocks
< sh
->NumShaderStorageBlocks
) {
3135 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3136 _mesa_shader_stage_to_string(i
),
3137 sh
->NumShaderStorageBlocks
, max_shader_storage_blocks
);
3141 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3142 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3143 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3146 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3147 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3148 total_shader_storage_blocks
,
3149 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3152 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
3153 if (prog
->UniformBlocks
[i
].UniformBufferSize
>
3154 ctx
->Const
.MaxUniformBlockSize
) {
3155 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3156 prog
->UniformBlocks
[i
].Name
,
3157 prog
->UniformBlocks
[i
].UniformBufferSize
,
3158 ctx
->Const
.MaxUniformBlockSize
);
3162 for (unsigned i
= 0; i
< prog
->NumShaderStorageBlocks
; i
++) {
3163 if (prog
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3164 ctx
->Const
.MaxShaderStorageBlockSize
) {
3165 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3166 prog
->ShaderStorageBlocks
[i
].Name
,
3167 prog
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3168 ctx
->Const
.MaxShaderStorageBlockSize
);
3174 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3176 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3177 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3182 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3183 if (sh
->SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3186 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3191 sh
->NumSubroutineUniforms
++;
3193 if (sh
->NumSubroutineFunctions
== 0) {
3194 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3197 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3198 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3199 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3200 if (fn
->types
[k
] == uni
->type
) {
3206 uni
->num_compatible_subroutines
= count
;
3212 check_subroutine_resources(struct gl_shader_program
*prog
)
3214 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3215 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3218 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3219 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3220 _mesa_shader_stage_to_string(i
));
3225 * Validate shader image resources.
3228 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3230 unsigned total_image_units
= 0;
3231 unsigned fragment_outputs
= 0;
3232 unsigned total_shader_storage_blocks
= 0;
3234 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3237 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3238 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3241 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3242 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3243 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3244 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3246 total_image_units
+= sh
->NumImages
;
3247 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3249 if (i
== MESA_SHADER_FRAGMENT
) {
3250 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3251 ir_variable
*var
= node
->as_variable();
3252 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3253 /* since there are no double fs outputs - pass false */
3254 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3260 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3261 linker_error(prog
, "Too many combined image uniforms\n");
3263 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3264 ctx
->Const
.MaxCombinedShaderOutputResources
)
3265 linker_error(prog
, "Too many combined image uniforms, shader storage "
3266 " buffers and fragment outputs\n");
3271 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3272 * for a variable, checks for overlaps between other uniforms using explicit
3276 reserve_explicit_locations(struct gl_shader_program
*prog
,
3277 string_to_uint_map
*map
, ir_variable
*var
)
3279 unsigned slots
= var
->type
->uniform_locations();
3280 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3281 unsigned return_value
= slots
;
3283 /* Resize remap table if locations do not fit in the current one. */
3284 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3285 prog
->UniformRemapTable
=
3286 reralloc(prog
, prog
->UniformRemapTable
,
3287 gl_uniform_storage
*,
3290 if (!prog
->UniformRemapTable
) {
3291 linker_error(prog
, "Out of memory during linking.\n");
3295 /* Initialize allocated space. */
3296 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3297 prog
->UniformRemapTable
[i
] = NULL
;
3299 prog
->NumUniformRemapTable
= max_loc
+ 1;
3302 for (unsigned i
= 0; i
< slots
; i
++) {
3303 unsigned loc
= var
->data
.location
+ i
;
3305 /* Check if location is already used. */
3306 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3308 /* Possibly same uniform from a different stage, this is ok. */
3310 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3315 /* ARB_explicit_uniform_location specification states:
3317 * "No two default-block uniform variables in the program can have
3318 * the same location, even if they are unused, otherwise a compiler
3319 * or linker error will be generated."
3322 "location qualifier for uniform %s overlaps "
3323 "previously used location\n",
3328 /* Initialize location as inactive before optimization
3329 * rounds and location assignment.
3331 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3334 /* Note, base location used for arrays. */
3335 map
->put(var
->data
.location
, var
->name
);
3337 return return_value
;
3341 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3342 struct gl_linked_shader
*sh
,
3345 unsigned slots
= var
->type
->uniform_locations();
3346 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3348 /* Resize remap table if locations do not fit in the current one. */
3349 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3350 sh
->SubroutineUniformRemapTable
=
3351 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3352 gl_uniform_storage
*,
3355 if (!sh
->SubroutineUniformRemapTable
) {
3356 linker_error(prog
, "Out of memory during linking.\n");
3360 /* Initialize allocated space. */
3361 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3362 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3364 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3367 for (unsigned i
= 0; i
< slots
; i
++) {
3368 unsigned loc
= var
->data
.location
+ i
;
3370 /* Check if location is already used. */
3371 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3373 /* ARB_explicit_uniform_location specification states:
3374 * "No two subroutine uniform variables can have the same location
3375 * in the same shader stage, otherwise a compiler or linker error
3376 * will be generated."
3379 "location qualifier for uniform %s overlaps "
3380 "previously used location\n",
3385 /* Initialize location as inactive before optimization
3386 * rounds and location assignment.
3388 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3394 * Check and reserve all explicit uniform locations, called before
3395 * any optimizations happen to handle also inactive uniforms and
3396 * inactive array elements that may get trimmed away.
3399 check_explicit_uniform_locations(struct gl_context
*ctx
,
3400 struct gl_shader_program
*prog
)
3402 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3405 /* This map is used to detect if overlapping explicit locations
3406 * occur with the same uniform (from different stage) or a different one.
3408 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3411 linker_error(prog
, "Out of memory during linking.\n");
3415 unsigned entries_total
= 0;
3416 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3417 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3422 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3423 ir_variable
*var
= node
->as_variable();
3424 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3427 if (var
->data
.explicit_location
) {
3429 if (var
->type
->without_array()->is_subroutine())
3430 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3432 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3436 entries_total
+= slots
;
3447 struct empty_uniform_block
*current_block
= NULL
;
3449 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3450 /* We found empty space in UniformRemapTable. */
3451 if (prog
->UniformRemapTable
[i
] == NULL
) {
3452 /* We've found the beginning of a new continous block of empty slots */
3453 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3454 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3455 current_block
->start
= i
;
3456 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3457 ¤t_block
->link
);
3460 /* The current block continues, so we simply increment its slots */
3461 current_block
->slots
++;
3466 return entries_total
;
3470 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3471 GLenum type
, const char *name
)
3473 bool found_interface
= false;
3474 unsigned block_name_len
= 0;
3475 const char *block_name_dot
= strchr(name
, '.');
3477 /* These rules only apply to buffer variables. So we return
3478 * true for the rest of types.
3480 if (type
!= GL_BUFFER_VARIABLE
)
3483 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
3484 const char *block_name
= shProg
->ShaderStorageBlocks
[i
].Name
;
3485 block_name_len
= strlen(block_name
);
3487 const char *block_square_bracket
= strchr(block_name
, '[');
3488 if (block_square_bracket
) {
3489 /* The block is part of an array of named interfaces,
3490 * for the name comparison we ignore the "[x]" part.
3492 block_name_len
-= strlen(block_square_bracket
);
3495 if (block_name_dot
) {
3496 /* Check if the variable name starts with the interface
3497 * name. The interface name (if present) should have the
3498 * length than the interface block name we are comparing to.
3500 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3501 if (len
!= block_name_len
)
3505 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3506 found_interface
= true;
3511 /* We remove the interface name from the buffer variable name,
3512 * including the dot that follows it.
3514 if (found_interface
)
3515 name
= name
+ block_name_len
+ 1;
3517 /* The ARB_program_interface_query spec says:
3519 * "For an active shader storage block member declared as an array, an
3520 * entry will be generated only for the first array element, regardless
3521 * of its type. For arrays of aggregate types, the enumeration rules
3522 * are applied recursively for the single enumerated array element."
3524 const char *struct_first_dot
= strchr(name
, '.');
3525 const char *first_square_bracket
= strchr(name
, '[');
3527 /* The buffer variable is on top level and it is not an array */
3528 if (!first_square_bracket
) {
3530 /* The shader storage block member is a struct, then generate the entry */
3531 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3534 /* Shader storage block member is an array, only generate an entry for the
3535 * first array element.
3537 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3545 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3546 const void *data
, uint8_t stages
)
3550 /* If resource already exists, do not add it again. */
3551 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3552 if (prog
->ProgramResourceList
[i
].Data
== data
)
3555 prog
->ProgramResourceList
=
3557 prog
->ProgramResourceList
,
3558 gl_program_resource
,
3559 prog
->NumProgramResourceList
+ 1);
3561 if (!prog
->ProgramResourceList
) {
3562 linker_error(prog
, "Out of memory during linking.\n");
3566 struct gl_program_resource
*res
=
3567 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3571 res
->StageReferences
= stages
;
3573 prog
->NumProgramResourceList
++;
3578 /* Function checks if a variable var is a packed varying and
3579 * if given name is part of packed varying's list.
3581 * If a variable is a packed varying, it has a name like
3582 * 'packed:a,b,c' where a, b and c are separate variables.
3585 included_in_packed_varying(ir_variable
*var
, const char *name
)
3587 if (strncmp(var
->name
, "packed:", 7) != 0)
3590 char *list
= strdup(var
->name
+ 7);
3595 char *token
= strtok_r(list
, ",", &saveptr
);
3597 if (strcmp(token
, name
) == 0) {
3601 token
= strtok_r(NULL
, ",", &saveptr
);
3608 * Function builds a stage reference bitmask from variable name.
3611 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3616 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3617 * used for reference mask in gl_program_resource will need to be changed.
3619 assert(MESA_SHADER_STAGES
< 8);
3621 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3622 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3626 /* Shader symbol table may contain variables that have
3627 * been optimized away. Search IR for the variable instead.
3629 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3630 ir_variable
*var
= node
->as_variable();
3632 unsigned baselen
= strlen(var
->name
);
3634 if (included_in_packed_varying(var
, name
)) {
3639 /* Type needs to match if specified, otherwise we might
3640 * pick a variable with same name but different interface.
3642 if (var
->data
.mode
!= mode
)
3645 if (strncmp(var
->name
, name
, baselen
) == 0) {
3646 /* Check for exact name matches but also check for arrays and
3649 if (name
[baselen
] == '\0' ||
3650 name
[baselen
] == '[' ||
3651 name
[baselen
] == '.') {
3663 * Create gl_shader_variable from ir_variable class.
3665 static gl_shader_variable
*
3666 create_shader_variable(struct gl_shader_program
*shProg
,
3667 const ir_variable
*in
,
3668 const char *name
, const glsl_type
*type
,
3669 bool use_implicit_location
, int location
,
3670 const glsl_type
*outermost_struct_type
)
3672 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3676 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3677 * expect to see gl_VertexID in the program resource list. Pretend.
3679 if (in
->data
.mode
== ir_var_system_value
&&
3680 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3681 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3683 out
->name
= ralloc_strdup(shProg
, name
);
3689 /* The ARB_program_interface_query spec says:
3691 * "Not all active variables are assigned valid locations; the
3692 * following variables will have an effective location of -1:
3694 * * uniforms declared as atomic counters;
3696 * * members of a uniform block;
3698 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3700 * * inputs or outputs not declared with a "location" layout
3701 * qualifier, except for vertex shader inputs and fragment shader
3704 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3705 is_gl_identifier(in
->name
) ||
3706 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3709 out
->location
= location
;
3713 out
->outermost_struct_type
= outermost_struct_type
;
3714 out
->interface_type
= in
->get_interface_type();
3715 out
->component
= in
->data
.location_frac
;
3716 out
->index
= in
->data
.index
;
3717 out
->patch
= in
->data
.patch
;
3718 out
->mode
= in
->data
.mode
;
3719 out
->interpolation
= in
->data
.interpolation
;
3720 out
->explicit_location
= in
->data
.explicit_location
;
3721 out
->precision
= in
->data
.precision
;
3727 add_shader_variable(struct gl_shader_program
*shProg
, unsigned stage_mask
,
3728 GLenum programInterface
, ir_variable
*var
,
3729 const char *name
, const glsl_type
*type
,
3730 bool use_implicit_location
, int location
,
3731 const glsl_type
*outermost_struct_type
= NULL
)
3733 const bool is_vertex_input
=
3734 programInterface
== GL_PROGRAM_INPUT
&&
3735 stage_mask
== MESA_SHADER_VERTEX
;
3737 switch (type
->base_type
) {
3738 case GLSL_TYPE_STRUCT
: {
3739 /* The ARB_program_interface_query spec says:
3741 * "For an active variable declared as a structure, a separate entry
3742 * will be generated for each active structure member. The name of
3743 * each entry is formed by concatenating the name of the structure,
3744 * the "." character, and the name of the structure member. If a
3745 * structure member to enumerate is itself a structure or array,
3746 * these enumeration rules are applied recursively."
3748 if (outermost_struct_type
== NULL
)
3749 outermost_struct_type
= type
;
3751 unsigned field_location
= location
;
3752 for (unsigned i
= 0; i
< type
->length
; i
++) {
3753 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3754 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3755 if (!add_shader_variable(shProg
, stage_mask
, programInterface
,
3756 var
, field_name
, field
->type
,
3757 use_implicit_location
, field_location
,
3758 outermost_struct_type
))
3762 field
->type
->count_attribute_slots(is_vertex_input
);
3768 /* Issue #16 of the ARB_program_interface_query spec says:
3770 * "* If a variable is a member of an interface block without an
3771 * instance name, it is enumerated using just the variable name.
3773 * * If a variable is a member of an interface block with an instance
3774 * name, it is enumerated as "BlockName.Member", where "BlockName" is
3775 * the name of the interface block (not the instance name) and
3776 * "Member" is the name of the variable."
3778 const char *prefixed_name
= (var
->data
.from_named_ifc_block
&&
3779 !is_gl_identifier(var
->name
))
3780 ? ralloc_asprintf(shProg
, "%s.%s", var
->get_interface_type()->name
,
3784 /* The ARB_program_interface_query spec says:
3786 * "For an active variable declared as a single instance of a basic
3787 * type, a single entry will be generated, using the variable name
3788 * from the shader source."
3790 gl_shader_variable
*sha_v
=
3791 create_shader_variable(shProg
, var
, prefixed_name
, type
,
3792 use_implicit_location
, location
,
3793 outermost_struct_type
);
3797 return add_program_resource(shProg
, programInterface
, sha_v
, stage_mask
);
3803 add_interface_variables(struct gl_shader_program
*shProg
,
3804 unsigned stage
, GLenum programInterface
)
3806 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3808 foreach_in_list(ir_instruction
, node
, ir
) {
3809 ir_variable
*var
= node
->as_variable();
3811 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3816 switch (var
->data
.mode
) {
3817 case ir_var_system_value
:
3818 case ir_var_shader_in
:
3819 if (programInterface
!= GL_PROGRAM_INPUT
)
3821 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3822 : int(VARYING_SLOT_VAR0
);
3824 case ir_var_shader_out
:
3825 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3827 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3828 : int(VARYING_SLOT_VAR0
);
3834 /* Skip packed varyings, packed varyings are handled separately
3835 * by add_packed_varyings.
3837 if (strncmp(var
->name
, "packed:", 7) == 0)
3840 /* Skip fragdata arrays, these are handled separately
3841 * by add_fragdata_arrays.
3843 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3846 const bool vs_input_or_fs_output
=
3847 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3848 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3850 if (!add_shader_variable(shProg
, 1 << stage
, programInterface
,
3851 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3852 var
->data
.location
- loc_bias
))
3859 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
, GLenum type
)
3861 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3864 if (!sh
|| !sh
->packed_varyings
)
3867 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3868 ir_variable
*var
= node
->as_variable();
3870 switch (var
->data
.mode
) {
3871 case ir_var_shader_in
:
3872 iface
= GL_PROGRAM_INPUT
;
3874 case ir_var_shader_out
:
3875 iface
= GL_PROGRAM_OUTPUT
;
3878 unreachable("unexpected type");
3881 if (type
== iface
) {
3882 const int stage_mask
=
3883 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3884 if (!add_shader_variable(shProg
, stage_mask
,
3885 iface
, var
, var
->name
, var
->type
, false,
3886 var
->data
.location
- VARYING_SLOT_VAR0
))
3895 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3897 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3899 if (!sh
|| !sh
->fragdata_arrays
)
3902 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3903 ir_variable
*var
= node
->as_variable();
3905 assert(var
->data
.mode
== ir_var_shader_out
);
3907 if (!add_shader_variable(shProg
,
3908 1 << MESA_SHADER_FRAGMENT
,
3909 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3910 true, var
->data
.location
- FRAG_RESULT_DATA0
))
3918 get_top_level_name(const char *name
)
3920 const char *first_dot
= strchr(name
, '.');
3921 const char *first_square_bracket
= strchr(name
, '[');
3924 /* The ARB_program_interface_query spec says:
3926 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3927 * the number of active array elements of the top-level shader storage
3928 * block member containing to the active variable is written to
3929 * <params>. If the top-level block member is not declared as an
3930 * array, the value one is written to <params>. If the top-level block
3931 * member is an array with no declared size, the value zero is written
3935 /* The buffer variable is on top level.*/
3936 if (!first_square_bracket
&& !first_dot
)
3937 name_size
= strlen(name
);
3938 else if ((!first_square_bracket
||
3939 (first_dot
&& first_dot
< first_square_bracket
)))
3940 name_size
= first_dot
- name
;
3942 name_size
= first_square_bracket
- name
;
3944 return strndup(name
, name_size
);
3948 get_var_name(const char *name
)
3950 const char *first_dot
= strchr(name
, '.');
3953 return strdup(name
);
3955 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3959 is_top_level_shader_storage_block_member(const char* name
,
3960 const char* interface_name
,
3961 const char* field_name
)
3963 bool result
= false;
3965 /* If the given variable is already a top-level shader storage
3966 * block member, then return array_size = 1.
3967 * We could have two possibilities: if we have an instanced
3968 * shader storage block or not instanced.
3970 * For the first, we check create a name as it was in top level and
3971 * compare it with the real name. If they are the same, then
3972 * the variable is already at top-level.
3974 * Full instanced name is: interface name + '.' + var name +
3977 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3978 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3979 if (!full_instanced_name
) {
3980 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3984 snprintf(full_instanced_name
, name_length
, "%s.%s",
3985 interface_name
, field_name
);
3987 /* Check if its top-level shader storage block member of an
3988 * instanced interface block, or of a unnamed interface block.
3990 if (strcmp(name
, full_instanced_name
) == 0 ||
3991 strcmp(name
, field_name
) == 0)
3994 free(full_instanced_name
);
3999 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4000 char *interface_name
, char *var_name
)
4002 /* The ARB_program_interface_query spec says:
4004 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4005 * the number of active array elements of the top-level shader storage
4006 * block member containing to the active variable is written to
4007 * <params>. If the top-level block member is not declared as an
4008 * array, the value one is written to <params>. If the top-level block
4009 * member is an array with no declared size, the value zero is written
4012 if (is_top_level_shader_storage_block_member(uni
->name
,
4016 else if (field
->type
->is_unsized_array())
4018 else if (field
->type
->is_array())
4019 return field
->type
->length
;
4025 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
4026 const glsl_struct_field
*field
, char *interface_name
,
4029 /* The ARB_program_interface_query spec says:
4031 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4032 * identifying the stride between array elements of the top-level
4033 * shader storage block member containing the active variable is
4034 * written to <params>. For top-level block members declared as
4035 * arrays, the value written is the difference, in basic machine units,
4036 * between the offsets of the active variable for consecutive elements
4037 * in the top-level array. For top-level block members not declared as
4038 * an array, zero is written to <params>."
4040 if (field
->type
->is_array()) {
4041 const enum glsl_matrix_layout matrix_layout
=
4042 glsl_matrix_layout(field
->matrix_layout
);
4043 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4044 const glsl_type
*array_type
= field
->type
->fields
.array
;
4046 if (is_top_level_shader_storage_block_member(uni
->name
,
4051 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
4052 if (array_type
->is_record() || array_type
->is_array())
4053 return glsl_align(array_type
->std140_size(row_major
), 16);
4055 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4057 return array_type
->std430_array_stride(row_major
);
4064 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
4065 struct gl_uniform_storage
*uni
)
4067 int block_index
= uni
->block_index
;
4068 int array_size
= -1;
4069 int array_stride
= -1;
4070 char *var_name
= get_top_level_name(uni
->name
);
4071 char *interface_name
=
4072 get_top_level_name(uni
->is_shader_storage
?
4073 shProg
->ShaderStorageBlocks
[block_index
].Name
:
4074 shProg
->UniformBlocks
[block_index
].Name
);
4076 if (strcmp(var_name
, interface_name
) == 0) {
4077 /* Deal with instanced array of SSBOs */
4078 char *temp_name
= get_var_name(uni
->name
);
4080 linker_error(shProg
, "Out of memory during linking.\n");
4081 goto write_top_level_array_size_and_stride
;
4084 var_name
= get_top_level_name(temp_name
);
4087 linker_error(shProg
, "Out of memory during linking.\n");
4088 goto write_top_level_array_size_and_stride
;
4092 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
4093 if (shProg
->Shaders
[i
] == NULL
)
4096 const gl_shader
*stage
= shProg
->Shaders
[i
];
4097 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
4098 ir_variable
*var
= node
->as_variable();
4099 if (!var
|| !var
->get_interface_type() ||
4100 var
->data
.mode
!= ir_var_shader_storage
)
4103 const glsl_type
*interface
= var
->get_interface_type();
4105 if (strcmp(interface_name
, interface
->name
) != 0)
4108 for (unsigned i
= 0; i
< interface
->length
; i
++) {
4109 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
4110 if (strcmp(field
->name
, var_name
) != 0)
4113 array_stride
= get_array_stride(uni
, interface
, field
,
4114 interface_name
, var_name
);
4115 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4116 goto write_top_level_array_size_and_stride
;
4120 write_top_level_array_size_and_stride
:
4121 free(interface_name
);
4123 uni
->top_level_array_stride
= array_stride
;
4124 uni
->top_level_array_size
= array_size
;
4128 * Builds up a list of program resources that point to existing
4132 build_program_resource_list(struct gl_context
*ctx
,
4133 struct gl_shader_program
*shProg
)
4135 /* Rebuild resource list. */
4136 if (shProg
->ProgramResourceList
) {
4137 ralloc_free(shProg
->ProgramResourceList
);
4138 shProg
->ProgramResourceList
= NULL
;
4139 shProg
->NumProgramResourceList
= 0;
4142 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4144 /* Determine first input and final output stage. These are used to
4145 * detect which variables should be enumerated in the resource list
4146 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4148 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4149 if (!shProg
->_LinkedShaders
[i
])
4151 if (input_stage
== MESA_SHADER_STAGES
)
4156 /* Empty shader, no resources. */
4157 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4160 /* Program interface needs to expose varyings in case of SSO. */
4161 if (shProg
->SeparateShader
) {
4162 if (!add_packed_varyings(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4165 if (!add_packed_varyings(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4169 if (!add_fragdata_arrays(shProg
))
4172 /* Add inputs and outputs to the resource list. */
4173 if (!add_interface_variables(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4176 if (!add_interface_variables(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4179 /* Add transform feedback varyings. */
4180 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
4181 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
4182 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
4183 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
4189 /* Add transform feedback buffers. */
4190 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4191 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
4192 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
4193 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_BUFFER
,
4194 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
4200 /* Add uniforms from uniform storage. */
4201 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4202 /* Do not add uniforms internally used by Mesa. */
4203 if (shProg
->UniformStorage
[i
].hidden
)
4207 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
4210 /* Add stagereferences for uniforms in a uniform block. */
4211 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
4212 int block_index
= shProg
->UniformStorage
[i
].block_index
;
4213 if (block_index
!= -1) {
4214 stageref
|= is_shader_storage
?
4215 shProg
->ShaderStorageBlocks
[block_index
].stageref
:
4216 shProg
->UniformBlocks
[block_index
].stageref
;
4219 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4220 if (!should_add_buffer_variable(shProg
, type
,
4221 shProg
->UniformStorage
[i
].name
))
4224 if (is_shader_storage
) {
4225 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
4228 if (!add_program_resource(shProg
, type
,
4229 &shProg
->UniformStorage
[i
], stageref
))
4233 /* Add program uniform blocks. */
4234 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
4235 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
4236 &shProg
->UniformBlocks
[i
], 0))
4240 /* Add program shader storage blocks. */
4241 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
4242 if (!add_program_resource(shProg
, GL_SHADER_STORAGE_BLOCK
,
4243 &shProg
->ShaderStorageBlocks
[i
], 0))
4247 /* Add atomic counter buffers. */
4248 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
4249 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
4250 &shProg
->AtomicBuffers
[i
], 0))
4254 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4256 if (!shProg
->UniformStorage
[i
].hidden
)
4259 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4260 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4261 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4264 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4265 /* add shader subroutines */
4266 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
4271 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4272 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4278 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4279 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4280 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
4287 * This check is done to make sure we allow only constant expression
4288 * indexing and "constant-index-expression" (indexing with an expression
4289 * that includes loop induction variable).
4292 validate_sampler_array_indexing(struct gl_context
*ctx
,
4293 struct gl_shader_program
*prog
)
4295 dynamic_sampler_array_indexing_visitor v
;
4296 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4297 if (prog
->_LinkedShaders
[i
] == NULL
)
4300 bool no_dynamic_indexing
=
4301 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4303 /* Search for array derefs in shader. */
4304 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4305 if (v
.uses_dynamic_sampler_array_indexing()) {
4306 const char *msg
= "sampler arrays indexed with non-constant "
4307 "expressions is forbidden in GLSL %s %u";
4308 /* Backend has indicated that it has no dynamic indexing support. */
4309 if (no_dynamic_indexing
) {
4310 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4313 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4321 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4323 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4324 gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
4329 sh
->MaxSubroutineFunctionIndex
= 0;
4330 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4331 ir_function
*fn
= node
->as_function();
4335 if (fn
->is_subroutine
)
4336 sh
->NumSubroutineUniformTypes
++;
4338 if (!fn
->num_subroutine_types
)
4341 /* these should have been calculated earlier. */
4342 assert(fn
->subroutine_index
!= -1);
4343 if (sh
->NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4344 linker_error(prog
, "Too many subroutine functions declared.\n");
4347 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4348 struct gl_subroutine_function
,
4349 sh
->NumSubroutineFunctions
+ 1);
4350 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4351 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4352 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4353 ralloc_array(sh
, const struct glsl_type
*,
4354 fn
->num_subroutine_types
);
4356 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4359 * "Each subroutine with an index qualifier in the shader must be
4360 * given a unique index, otherwise a compile or link error will be
4363 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4364 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4365 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4366 linker_error(prog
, "each subroutine index qualifier in the "
4367 "shader must be unique\n");
4371 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4372 fn
->subroutine_index
;
4374 if (fn
->subroutine_index
> (int)sh
->MaxSubroutineFunctionIndex
)
4375 sh
->MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4377 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4378 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4379 sh
->NumSubroutineFunctions
++;
4385 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4387 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4389 foreach_in_list(ir_instruction
, node
, ir
) {
4390 ir_variable
*const var
= node
->as_variable();
4392 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4395 /* Don't set always active on builtins that haven't been redeclared */
4396 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4399 var
->data
.always_active_io
= true;
4404 * When separate shader programs are enabled, only input/outputs between
4405 * the stages of a multi-stage separate program can be safely removed
4406 * from the shader interface. Other inputs/outputs must remain active.
4409 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4411 unsigned first
, last
;
4412 assert(prog
->SeparateShader
);
4414 first
= MESA_SHADER_STAGES
;
4417 /* Determine first and last stage. Excluding the compute stage */
4418 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4419 if (!prog
->_LinkedShaders
[i
])
4421 if (first
== MESA_SHADER_STAGES
)
4426 if (first
== MESA_SHADER_STAGES
)
4429 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4430 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4434 if (first
== last
) {
4435 /* For a single shader program only allow inputs to the vertex shader
4436 * and outputs from the fragment shader to be removed.
4438 if (stage
!= MESA_SHADER_VERTEX
)
4439 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4440 if (stage
!= MESA_SHADER_FRAGMENT
)
4441 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4443 /* For multi-stage separate shader programs only allow inputs and
4444 * outputs between the shader stages to be removed as well as inputs
4445 * to the vertex shader and outputs from the fragment shader.
4447 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4448 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4449 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4450 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4456 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4458 prog
->LinkStatus
= true; /* All error paths will set this to false */
4459 prog
->Validated
= false;
4460 prog
->_Used
= false;
4462 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4464 * "Linking can fail for a variety of reasons as specified in the
4465 * OpenGL Shading Language Specification, as well as any of the
4466 * following reasons:
4468 * - No shader objects are attached to program."
4470 * The Compatibility Profile specification does not list the error. In
4471 * Compatibility Profile missing shader stages are replaced by
4472 * fixed-function. This applies to the case where all stages are
4475 if (prog
->NumShaders
== 0) {
4476 if (ctx
->API
!= API_OPENGL_COMPAT
)
4477 linker_error(prog
, "no shaders attached to the program\n");
4481 unsigned num_tfeedback_decls
= 0;
4482 unsigned int num_explicit_uniform_locs
= 0;
4483 bool has_xfb_qualifiers
= false;
4484 char **varying_names
= NULL
;
4485 tfeedback_decl
*tfeedback_decls
= NULL
;
4487 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4489 prog
->ARB_fragment_coord_conventions_enable
= false;
4491 /* Separate the shaders into groups based on their type.
4493 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4494 unsigned num_shaders
[MESA_SHADER_STAGES
];
4496 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4497 shader_list
[i
] = (struct gl_shader
**)
4498 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4502 unsigned min_version
= UINT_MAX
;
4503 unsigned max_version
= 0;
4504 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4505 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4506 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4508 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4509 linker_error(prog
, "all shaders must use same shading "
4510 "language version\n");
4514 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4515 prog
->ARB_fragment_coord_conventions_enable
= true;
4518 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4519 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4520 num_shaders
[shader_type
]++;
4523 /* In desktop GLSL, different shader versions may be linked together. In
4524 * GLSL ES, all shader versions must be the same.
4526 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4527 linker_error(prog
, "all shaders must use same shading "
4528 "language version\n");
4532 prog
->Version
= max_version
;
4533 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4535 /* Some shaders have to be linked with some other shaders present.
4537 if (!prog
->SeparateShader
) {
4538 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4539 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4540 linker_error(prog
, "Geometry shader must be linked with "
4544 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4545 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4546 linker_error(prog
, "Tessellation evaluation shader must be linked "
4547 "with vertex shader\n");
4550 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4551 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4552 linker_error(prog
, "Tessellation control shader must be linked with "
4557 /* The spec is self-contradictory here. It allows linking without a tess
4558 * eval shader, but that can only be used with transform feedback and
4559 * rasterization disabled. However, transform feedback isn't allowed
4560 * with GL_PATCHES, so it can't be used.
4562 * More investigation showed that the idea of transform feedback after
4563 * a tess control shader was dropped, because some hw vendors couldn't
4564 * support tessellation without a tess eval shader, but the linker
4565 * section wasn't updated to reflect that.
4567 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4570 * Do what's reasonable and always require a tess eval shader if a tess
4571 * control shader is present.
4573 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4574 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4575 linker_error(prog
, "Tessellation control shader must be linked with "
4576 "tessellation evaluation shader\n");
4581 /* Compute shaders have additional restrictions. */
4582 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4583 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4584 linker_error(prog
, "Compute shaders may not be linked with any other "
4585 "type of shader\n");
4588 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4589 if (prog
->_LinkedShaders
[i
] != NULL
) {
4590 _mesa_delete_linked_shader(ctx
, prog
->_LinkedShaders
[i
]);
4593 prog
->_LinkedShaders
[i
] = NULL
;
4596 /* Link all shaders for a particular stage and validate the result.
4598 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4599 if (num_shaders
[stage
] > 0) {
4600 gl_linked_shader
*const sh
=
4601 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4602 num_shaders
[stage
]);
4604 if (!prog
->LinkStatus
) {
4606 _mesa_delete_linked_shader(ctx
, sh
);
4611 case MESA_SHADER_VERTEX
:
4612 validate_vertex_shader_executable(prog
, sh
, ctx
);
4614 case MESA_SHADER_TESS_CTRL
:
4615 /* nothing to be done */
4617 case MESA_SHADER_TESS_EVAL
:
4618 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4620 case MESA_SHADER_GEOMETRY
:
4621 validate_geometry_shader_executable(prog
, sh
, ctx
);
4623 case MESA_SHADER_FRAGMENT
:
4624 validate_fragment_shader_executable(prog
, sh
);
4627 if (!prog
->LinkStatus
) {
4629 _mesa_delete_linked_shader(ctx
, sh
);
4633 prog
->_LinkedShaders
[stage
] = sh
;
4637 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0) {
4638 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4639 prog
->LastCullDistanceArraySize
= prog
->Geom
.CullDistanceArraySize
;
4640 } else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0) {
4641 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4642 prog
->LastCullDistanceArraySize
= prog
->TessEval
.CullDistanceArraySize
;
4643 } else if (num_shaders
[MESA_SHADER_VERTEX
] > 0) {
4644 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4645 prog
->LastCullDistanceArraySize
= prog
->Vert
.CullDistanceArraySize
;
4647 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4648 prog
->LastCullDistanceArraySize
= 0; /* Not used */
4651 /* Here begins the inter-stage linking phase. Some initial validation is
4652 * performed, then locations are assigned for uniforms, attributes, and
4655 cross_validate_uniforms(prog
);
4656 if (!prog
->LinkStatus
)
4659 unsigned first
, last
, prev
;
4661 first
= MESA_SHADER_STAGES
;
4664 /* Determine first and last stage. */
4665 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4666 if (!prog
->_LinkedShaders
[i
])
4668 if (first
== MESA_SHADER_STAGES
)
4673 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4674 link_assign_subroutine_types(prog
);
4676 if (!prog
->LinkStatus
)
4679 resize_tes_inputs(ctx
, prog
);
4681 /* Validate the inputs of each stage with the output of the preceding
4685 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4686 if (prog
->_LinkedShaders
[i
] == NULL
)
4689 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4690 prog
->_LinkedShaders
[i
]);
4691 if (!prog
->LinkStatus
)
4694 cross_validate_outputs_to_inputs(prog
,
4695 prog
->_LinkedShaders
[prev
],
4696 prog
->_LinkedShaders
[i
]);
4697 if (!prog
->LinkStatus
)
4703 /* Cross-validate uniform blocks between shader stages */
4704 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4705 if (!prog
->LinkStatus
)
4708 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4709 if (prog
->_LinkedShaders
[i
] != NULL
)
4710 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4713 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4714 * it before optimization because we want most of the checks to get
4715 * dropped thanks to constant propagation.
4717 * This rule also applies to GLSL ES 3.00.
4719 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4720 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4722 lower_discard_flow(sh
->ir
);
4726 if (prog
->SeparateShader
)
4727 disable_varying_optimizations_for_sso(prog
);
4730 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4734 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4737 /* Do common optimization before assigning storage for attributes,
4738 * uniforms, and varyings. Later optimization could possibly make
4739 * some of that unused.
4741 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4742 if (prog
->_LinkedShaders
[i
] == NULL
)
4745 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4746 if (!prog
->LinkStatus
)
4749 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4750 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4753 if (ctx
->Const
.LowerTessLevel
) {
4754 lower_tess_level(prog
->_LinkedShaders
[i
]);
4757 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4758 &ctx
->Const
.ShaderCompilerOptions
[i
],
4759 ctx
->Const
.NativeIntegers
))
4762 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4763 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
4766 /* Validation for special cases where we allow sampler array indexing
4767 * with loop induction variable. This check emits a warning or error
4768 * depending if backend can handle dynamic indexing.
4770 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4771 (prog
->IsES
&& prog
->Version
< 300)) {
4772 if (!validate_sampler_array_indexing(ctx
, prog
))
4776 /* Check and validate stream emissions in geometry shaders */
4777 validate_geometry_shader_emissions(ctx
, prog
);
4779 /* Mark all generic shader inputs and outputs as unpaired. */
4780 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4781 if (prog
->_LinkedShaders
[i
] != NULL
) {
4782 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4787 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4788 if (prog
->_LinkedShaders
[i
] == NULL
)
4791 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4792 prog
->_LinkedShaders
[i
]);
4796 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4797 MESA_SHADER_VERTEX
)) {
4801 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4802 MESA_SHADER_FRAGMENT
)) {
4806 /* From the ARB_enhanced_layouts spec:
4808 * "If the shader used to record output variables for transform feedback
4809 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4810 * qualifiers, the values specified by TransformFeedbackVaryings are
4811 * ignored, and the set of variables captured for transform feedback is
4812 * instead derived from the specified layout qualifiers."
4814 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4815 /* Find last stage before fragment shader */
4816 if (prog
->_LinkedShaders
[i
]) {
4817 has_xfb_qualifiers
=
4818 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4819 &num_tfeedback_decls
,
4825 if (!has_xfb_qualifiers
) {
4826 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4827 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4830 if (num_tfeedback_decls
!= 0) {
4831 /* From GL_EXT_transform_feedback:
4832 * A program will fail to link if:
4834 * * the <count> specified by TransformFeedbackVaryingsEXT is
4835 * non-zero, but the program object has no vertex or geometry
4838 if (first
>= MESA_SHADER_FRAGMENT
) {
4839 linker_error(prog
, "Transform feedback varyings specified, but "
4840 "no vertex, tessellation, or geometry shader is "
4845 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4846 num_tfeedback_decls
);
4847 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4848 varying_names
, tfeedback_decls
))
4852 /* If there is no fragment shader we need to set transform feedback.
4854 * For SSO we also need to assign output locations. We assign them here
4855 * because we need to do it for both single stage programs and multi stage
4858 if (last
< MESA_SHADER_FRAGMENT
&&
4859 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4860 const uint64_t reserved_out_slots
=
4861 reserved_varying_slot(prog
->_LinkedShaders
[last
], ir_var_shader_out
);
4862 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4863 prog
->_LinkedShaders
[last
], NULL
,
4864 num_tfeedback_decls
, tfeedback_decls
,
4865 reserved_out_slots
))
4869 if (last
<= MESA_SHADER_FRAGMENT
) {
4870 /* Remove unused varyings from the first/last stage unless SSO */
4871 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4872 prog
->_LinkedShaders
[first
],
4874 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4875 prog
->_LinkedShaders
[last
],
4878 /* If the program is made up of only a single stage */
4879 if (first
== last
) {
4881 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[last
];
4882 if (prog
->SeparateShader
) {
4883 const uint64_t reserved_slots
=
4884 reserved_varying_slot(sh
, ir_var_shader_in
);
4886 /* Assign input locations for SSO, output locations are already
4889 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4890 NULL
/* producer */,
4892 0 /* num_tfeedback_decls */,
4893 NULL
/* tfeedback_decls */,
4898 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4899 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4902 /* Linking the stages in the opposite order (from fragment to vertex)
4903 * ensures that inter-shader outputs written to in an earlier stage
4904 * are eliminated if they are (transitively) not used in a later
4908 for (int i
= next
- 1; i
>= 0; i
--) {
4909 if (prog
->_LinkedShaders
[i
] == NULL
&& i
!= 0)
4912 gl_linked_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4913 gl_linked_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4915 const uint64_t reserved_out_slots
=
4916 reserved_varying_slot(sh_i
, ir_var_shader_out
);
4917 const uint64_t reserved_in_slots
=
4918 reserved_varying_slot(sh_next
, ir_var_shader_in
);
4920 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4921 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4923 reserved_out_slots
| reserved_in_slots
))
4926 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4927 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4930 /* This must be done after all dead varyings are eliminated. */
4932 unsigned slots_used
= _mesa_bitcount_64(reserved_out_slots
);
4933 if (!check_against_output_limit(ctx
, prog
, sh_i
, slots_used
)) {
4938 unsigned slots_used
= _mesa_bitcount_64(reserved_in_slots
);
4939 if (!check_against_input_limit(ctx
, prog
, sh_next
, slots_used
))
4947 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4948 has_xfb_qualifiers
))
4951 update_array_sizes(prog
);
4952 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4953 num_explicit_uniform_locs
,
4954 ctx
->Const
.MaxUserAssignableUniformLocations
);
4955 link_assign_atomic_counter_resources(ctx
, prog
);
4956 store_fragdepth_layout(prog
);
4958 link_calculate_subroutine_compat(prog
);
4959 check_resources(ctx
, prog
);
4960 check_subroutine_resources(prog
);
4961 check_image_resources(ctx
, prog
);
4962 link_check_atomic_counter_resources(ctx
, prog
);
4964 if (!prog
->LinkStatus
)
4967 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4968 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4969 * anything about shader linking when one of the shaders (vertex or
4970 * fragment shader) is absent. So, the extension shouldn't change the
4971 * behavior specified in GLSL specification.
4973 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4974 * "Linking can fail for a variety of reasons as specified in the
4975 * OpenGL ES Shading Language Specification, as well as any of the
4976 * following reasons:
4980 * * program contains objects to form either a vertex shader or
4981 * fragment shader, and program is not separable, and does not
4982 * contain objects to form both a vertex shader and fragment
4985 * However, the only scenario in 3.1+ where we don't require them both is
4986 * when we have a compute shader. For example:
4988 * - No shaders is a link error.
4989 * - Geom or Tess without a Vertex shader is a link error which means we
4990 * always require a Vertex shader and hence a Fragment shader.
4991 * - Finally a Compute shader linked with any other stage is a link error.
4993 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4994 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4995 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4996 linker_error(prog
, "program lacks a vertex shader\n");
4997 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4998 linker_error(prog
, "program lacks a fragment shader\n");
5002 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5003 if (prog
->_LinkedShaders
[i
] == NULL
)
5006 const struct gl_shader_compiler_options
*options
=
5007 &ctx
->Const
.ShaderCompilerOptions
[i
];
5009 if (options
->LowerBufferInterfaceBlocks
)
5010 lower_ubo_reference(prog
->_LinkedShaders
[i
],
5011 options
->ClampBlockIndicesToArrayBounds
);
5013 if (options
->LowerShaderSharedVariables
)
5014 lower_shared_reference(prog
->_LinkedShaders
[i
],
5015 &prog
->Comp
.SharedSize
);
5017 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
5018 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
5022 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5023 free(shader_list
[i
]);
5024 if (prog
->_LinkedShaders
[i
] == NULL
)
5027 /* Do a final validation step to make sure that the IR wasn't
5028 * invalidated by any modifications performed after intrastage linking.
5030 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5032 /* Retain any live IR, but trash the rest. */
5033 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5035 /* The symbol table in the linked shaders may contain references to
5036 * variables that were removed (e.g., unused uniforms). Since it may
5037 * contain junk, there is no possible valid use. Delete it and set the
5040 delete prog
->_LinkedShaders
[i
]->symbols
;
5041 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5044 ralloc_free(mem_ctx
);