2 * Copyright © 2010 Intel Corporation
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
26 * GLSL linker implementation
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
35 * - Undefined references in each shader are resolve to definitions in
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
64 * \author Ian Romanick <ian.d.romanick@intel.com>
68 #include "main/core.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
73 #include "program/hash_table.h"
75 #include "link_varyings.h"
76 #include "ir_optimization.h"
77 #include "ir_rvalue_visitor.h"
78 #include "ir_uniform.h"
80 #include "main/shaderobj.h"
81 #include "main/enums.h"
84 void linker_error(gl_shader_program
*, const char *, ...);
89 * Visitor that determines whether or not a variable is ever written.
91 class find_assignment_visitor
: public ir_hierarchical_visitor
{
93 find_assignment_visitor(const char *name
)
94 : name(name
), found(false)
99 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
101 ir_variable
*const var
= ir
->lhs
->variable_referenced();
103 if (strcmp(name
, var
->name
) == 0) {
108 return visit_continue_with_parent
;
111 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
113 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
114 actual_node
, &ir
->actual_parameters
) {
115 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
116 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
118 if (sig_param
->data
.mode
== ir_var_function_out
||
119 sig_param
->data
.mode
== ir_var_function_inout
) {
120 ir_variable
*var
= param_rval
->variable_referenced();
121 if (var
&& strcmp(name
, var
->name
) == 0) {
128 if (ir
->return_deref
!= NULL
) {
129 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
131 if (strcmp(name
, var
->name
) == 0) {
137 return visit_continue_with_parent
;
140 bool variable_found()
146 const char *name
; /**< Find writes to a variable with this name. */
147 bool found
; /**< Was a write to the variable found? */
152 * Visitor that determines whether or not a variable is ever read.
154 class find_deref_visitor
: public ir_hierarchical_visitor
{
156 find_deref_visitor(const char *name
)
157 : name(name
), found(false)
162 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
164 if (strcmp(this->name
, ir
->var
->name
) == 0) {
169 return visit_continue
;
172 bool variable_found() const
178 const char *name
; /**< Find writes to a variable with this name. */
179 bool found
; /**< Was a write to the variable found? */
183 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
185 unsigned num_vertices
;
186 gl_shader_program
*prog
;
188 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
190 this->num_vertices
= num_vertices
;
194 virtual ~geom_array_resize_visitor()
199 virtual ir_visitor_status
visit(ir_variable
*var
)
201 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
202 return visit_continue
;
204 unsigned size
= var
->type
->length
;
206 /* Generate a link error if the shader has declared this array with an
209 if (size
&& size
!= this->num_vertices
) {
210 linker_error(this->prog
, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var
->name
, size
, this->num_vertices
);
213 return visit_continue
;
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
220 if (var
->data
.max_array_access
>= this->num_vertices
) {
221 linker_error(this->prog
, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
223 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
224 return visit_continue
;
227 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
229 var
->data
.max_array_access
= this->num_vertices
- 1;
231 return visit_continue
;
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
238 ir
->type
= ir
->var
->type
;
239 return visit_continue
;
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
246 const glsl_type
*const vt
= ir
->array
->type
;
248 ir
->type
= vt
->fields
.array
;
249 return visit_continue
;
253 class tess_eval_array_resize_visitor
: public ir_hierarchical_visitor
{
255 unsigned num_vertices
;
256 gl_shader_program
*prog
;
258 tess_eval_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
260 this->num_vertices
= num_vertices
;
264 virtual ~tess_eval_array_resize_visitor()
269 virtual ir_visitor_status
visit(ir_variable
*var
)
271 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
|| var
->data
.patch
)
272 return visit_continue
;
274 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
276 var
->data
.max_array_access
= this->num_vertices
- 1;
278 return visit_continue
;
281 /* Dereferences of input variables need to be updated so that their type
282 * matches the newly assigned type of the variable they are accessing. */
283 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
285 ir
->type
= ir
->var
->type
;
286 return visit_continue
;
289 /* Dereferences of 2D input arrays need to be updated so that their type
290 * matches the newly assigned type of the array they are accessing. */
291 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
293 const glsl_type
*const vt
= ir
->array
->type
;
295 ir
->type
= vt
->fields
.array
;
296 return visit_continue
;
300 class barrier_use_visitor
: public ir_hierarchical_visitor
{
302 barrier_use_visitor(gl_shader_program
*prog
)
303 : prog(prog
), in_main(false), after_return(false), control_flow(0)
307 virtual ~barrier_use_visitor()
312 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
314 if (strcmp(ir
->name
, "main") == 0)
317 return visit_continue
;
320 virtual ir_visitor_status
visit_leave(ir_function
*)
323 after_return
= false;
324 return visit_continue
;
327 virtual ir_visitor_status
visit_leave(ir_return
*)
330 return visit_continue
;
333 virtual ir_visitor_status
visit_enter(ir_if
*)
336 return visit_continue
;
339 virtual ir_visitor_status
visit_leave(ir_if
*)
342 return visit_continue
;
345 virtual ir_visitor_status
visit_enter(ir_loop
*)
348 return visit_continue
;
351 virtual ir_visitor_status
visit_leave(ir_loop
*)
354 return visit_continue
;
357 /* FINISHME: `switch` is not expressed at the IR level -- it's already
358 * been lowered to a mess of `if`s. We'll correctly disallow any use of
359 * barrier() in a conditional path within the switch, but not in a path
360 * which is always hit.
363 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
365 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
366 /* Use of barrier(); determine if it is legal: */
368 linker_error(prog
, "Builtin barrier() may only be used in main");
373 linker_error(prog
, "Builtin barrier() may not be used after return");
377 if (control_flow
!= 0) {
378 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
382 return visit_continue
;
386 gl_shader_program
*prog
;
387 bool in_main
, after_return
;
392 * Visitor that determines the highest stream id to which a (geometry) shader
393 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
395 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
397 find_emit_vertex_visitor(int max_allowed
)
398 : max_stream_allowed(max_allowed
),
399 invalid_stream_id(0),
400 invalid_stream_id_from_emit_vertex(false),
401 end_primitive_found(false),
402 uses_non_zero_stream(false)
407 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
409 int stream_id
= ir
->stream_id();
412 invalid_stream_id
= stream_id
;
413 invalid_stream_id_from_emit_vertex
= true;
417 if (stream_id
> max_stream_allowed
) {
418 invalid_stream_id
= stream_id
;
419 invalid_stream_id_from_emit_vertex
= true;
424 uses_non_zero_stream
= true;
426 return visit_continue
;
429 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
431 end_primitive_found
= true;
433 int stream_id
= ir
->stream_id();
436 invalid_stream_id
= stream_id
;
437 invalid_stream_id_from_emit_vertex
= false;
441 if (stream_id
> max_stream_allowed
) {
442 invalid_stream_id
= stream_id
;
443 invalid_stream_id_from_emit_vertex
= false;
448 uses_non_zero_stream
= true;
450 return visit_continue
;
455 return invalid_stream_id
!= 0;
458 const char *error_func()
460 return invalid_stream_id_from_emit_vertex
?
461 "EmitStreamVertex" : "EndStreamPrimitive";
466 return invalid_stream_id
;
471 return uses_non_zero_stream
;
474 bool uses_end_primitive()
476 return end_primitive_found
;
480 int max_stream_allowed
;
481 int invalid_stream_id
;
482 bool invalid_stream_id_from_emit_vertex
;
483 bool end_primitive_found
;
484 bool uses_non_zero_stream
;
487 /* Class that finds array derefs and check if indexes are dynamic. */
488 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
491 dynamic_sampler_array_indexing_visitor() :
492 dynamic_sampler_array_indexing(false)
496 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
498 if (!ir
->variable_referenced())
499 return visit_continue
;
501 if (!ir
->variable_referenced()->type
->contains_sampler())
502 return visit_continue
;
504 if (!ir
->array_index
->constant_expression_value()) {
505 dynamic_sampler_array_indexing
= true;
508 return visit_continue
;
511 bool uses_dynamic_sampler_array_indexing()
513 return dynamic_sampler_array_indexing
;
517 bool dynamic_sampler_array_indexing
;
520 } /* anonymous namespace */
523 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
527 ralloc_strcat(&prog
->InfoLog
, "error: ");
529 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
532 prog
->LinkStatus
= false;
537 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
541 ralloc_strcat(&prog
->InfoLog
, "warning: ");
543 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
550 * Given a string identifying a program resource, break it into a base name
551 * and an optional array index in square brackets.
553 * If an array index is present, \c out_base_name_end is set to point to the
554 * "[" that precedes the array index, and the array index itself is returned
557 * If no array index is present (or if the array index is negative or
558 * mal-formed), \c out_base_name_end, is set to point to the null terminator
559 * at the end of the input string, and -1 is returned.
561 * Only the final array index is parsed; if the string contains other array
562 * indices (or structure field accesses), they are left in the base name.
564 * No attempt is made to check that the base name is properly formed;
565 * typically the caller will look up the base name in a hash table, so
566 * ill-formed base names simply turn into hash table lookup failures.
569 parse_program_resource_name(const GLchar
*name
,
570 const GLchar
**out_base_name_end
)
572 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
574 * "When an integer array element or block instance number is part of
575 * the name string, it will be specified in decimal form without a "+"
576 * or "-" sign or any extra leading zeroes. Additionally, the name
577 * string will not include white space anywhere in the string."
580 const size_t len
= strlen(name
);
581 *out_base_name_end
= name
+ len
;
583 if (len
== 0 || name
[len
-1] != ']')
586 /* Walk backwards over the string looking for a non-digit character. This
587 * had better be the opening bracket for an array index.
589 * Initially, i specifies the location of the ']'. Since the string may
590 * contain only the ']' charcater, walk backwards very carefully.
593 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
596 if ((i
== 0) || name
[i
-1] != '[')
599 long array_index
= strtol(&name
[i
], NULL
, 10);
603 /* Check for leading zero */
604 if (name
[i
] == '0' && name
[i
+1] != ']')
607 *out_base_name_end
= name
+ (i
- 1);
613 link_invalidate_variable_locations(exec_list
*ir
)
615 foreach_in_list(ir_instruction
, node
, ir
) {
616 ir_variable
*const var
= node
->as_variable();
621 /* Only assign locations for variables that lack an explicit location.
622 * Explicit locations are set for all built-in variables, generic vertex
623 * shader inputs (via layout(location=...)), and generic fragment shader
624 * outputs (also via layout(location=...)).
626 if (!var
->data
.explicit_location
) {
627 var
->data
.location
= -1;
628 var
->data
.location_frac
= 0;
631 /* ir_variable::is_unmatched_generic_inout is used by the linker while
632 * connecting outputs from one stage to inputs of the next stage.
634 * There are two implicit assumptions here. First, we assume that any
635 * built-in variable (i.e., non-generic in or out) will have
636 * explicit_location set. Second, we assume that any generic in or out
637 * will not have explicit_location set.
639 * This second assumption will only be valid until
640 * GL_ARB_separate_shader_objects is supported. When that extension is
641 * implemented, this function will need some modifications.
643 if (!var
->data
.explicit_location
) {
644 var
->data
.is_unmatched_generic_inout
= 1;
646 var
->data
.is_unmatched_generic_inout
= 0;
653 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
655 * Also check for errors based on incorrect usage of gl_ClipVertex and
658 * Return false if an error was reported.
661 analyze_clip_usage(struct gl_shader_program
*prog
,
662 struct gl_shader
*shader
, GLboolean
*UsesClipDistance
,
663 GLuint
*ClipDistanceArraySize
)
665 *ClipDistanceArraySize
= 0;
667 if (!prog
->IsES
&& prog
->Version
>= 130) {
668 /* From section 7.1 (Vertex Shader Special Variables) of the
671 * "It is an error for a shader to statically write both
672 * gl_ClipVertex and gl_ClipDistance."
674 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
675 * gl_ClipVertex nor gl_ClipDistance.
677 find_assignment_visitor
clip_vertex("gl_ClipVertex");
678 find_assignment_visitor
clip_distance("gl_ClipDistance");
680 clip_vertex
.run(shader
->ir
);
681 clip_distance
.run(shader
->ir
);
682 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
683 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
684 "and `gl_ClipDistance'\n",
685 _mesa_shader_stage_to_string(shader
->Stage
));
688 *UsesClipDistance
= clip_distance
.variable_found();
689 ir_variable
*clip_distance_var
=
690 shader
->symbols
->get_variable("gl_ClipDistance");
691 if (clip_distance_var
)
692 *ClipDistanceArraySize
= clip_distance_var
->type
->length
;
694 *UsesClipDistance
= false;
700 * Verify that a vertex shader executable meets all semantic requirements.
702 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
705 * \param shader Vertex shader executable to be verified
708 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
709 struct gl_shader
*shader
)
714 /* From the GLSL 1.10 spec, page 48:
716 * "The variable gl_Position is available only in the vertex
717 * language and is intended for writing the homogeneous vertex
718 * position. All executions of a well-formed vertex shader
719 * executable must write a value into this variable. [...] The
720 * variable gl_Position is available only in the vertex
721 * language and is intended for writing the homogeneous vertex
722 * position. All executions of a well-formed vertex shader
723 * executable must write a value into this variable."
725 * while in GLSL 1.40 this text is changed to:
727 * "The variable gl_Position is available only in the vertex
728 * language and is intended for writing the homogeneous vertex
729 * position. It can be written at any time during shader
730 * execution. It may also be read back by a vertex shader
731 * after being written. This value will be used by primitive
732 * assembly, clipping, culling, and other fixed functionality
733 * operations, if present, that operate on primitives after
734 * vertex processing has occurred. Its value is undefined if
735 * the vertex shader executable does not write gl_Position."
737 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
738 * gl_Position is not an error.
740 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
741 find_assignment_visitor
find("gl_Position");
742 find
.run(shader
->ir
);
743 if (!find
.variable_found()) {
746 "vertex shader does not write to `gl_Position'."
747 "It's value is undefined. \n");
750 "vertex shader does not write to `gl_Position'. \n");
756 analyze_clip_usage(prog
, shader
, &prog
->Vert
.UsesClipDistance
,
757 &prog
->Vert
.ClipDistanceArraySize
);
761 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
762 struct gl_shader
*shader
)
767 analyze_clip_usage(prog
, shader
, &prog
->TessEval
.UsesClipDistance
,
768 &prog
->TessEval
.ClipDistanceArraySize
);
773 * Verify that a fragment shader executable meets all semantic requirements
775 * \param shader Fragment shader executable to be verified
778 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
779 struct gl_shader
*shader
)
784 find_assignment_visitor
frag_color("gl_FragColor");
785 find_assignment_visitor
frag_data("gl_FragData");
787 frag_color
.run(shader
->ir
);
788 frag_data
.run(shader
->ir
);
790 if (frag_color
.variable_found() && frag_data
.variable_found()) {
791 linker_error(prog
, "fragment shader writes to both "
792 "`gl_FragColor' and `gl_FragData'\n");
797 * Verify that a geometry shader executable meets all semantic requirements
799 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
800 * prog->Geom.ClipDistanceArraySize as a side effect.
802 * \param shader Geometry shader executable to be verified
805 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
806 struct gl_shader
*shader
)
811 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
812 prog
->Geom
.VerticesIn
= num_vertices
;
814 analyze_clip_usage(prog
, shader
, &prog
->Geom
.UsesClipDistance
,
815 &prog
->Geom
.ClipDistanceArraySize
);
819 * Check if geometry shaders emit to non-zero streams and do corresponding
823 validate_geometry_shader_emissions(struct gl_context
*ctx
,
824 struct gl_shader_program
*prog
)
826 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
827 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
828 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
829 if (emit_vertex
.error()) {
830 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
831 "stream parameter are in the range [0, %d].\n",
832 emit_vertex
.error_func(),
833 emit_vertex
.error_stream(),
834 ctx
->Const
.MaxVertexStreams
- 1);
836 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
837 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
839 /* From the ARB_gpu_shader5 spec:
841 * "Multiple vertex streams are supported only if the output primitive
842 * type is declared to be "points". A program will fail to link if it
843 * contains a geometry shader calling EmitStreamVertex() or
844 * EndStreamPrimitive() if its output primitive type is not "points".
846 * However, in the same spec:
848 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
849 * with <stream> set to zero."
853 * "The function EndPrimitive() is equivalent to calling
854 * EndStreamPrimitive() with <stream> set to zero."
856 * Since we can call EmitVertex() and EndPrimitive() when we output
857 * primitives other than points, calling EmitStreamVertex(0) or
858 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
859 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
860 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
863 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
864 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
865 "with n>0 requires point output\n");
871 validate_intrastage_arrays(struct gl_shader_program
*prog
,
872 ir_variable
*const var
,
873 ir_variable
*const existing
)
875 /* Consider the types to be "the same" if both types are arrays
876 * of the same type and one of the arrays is implicitly sized.
877 * In addition, set the type of the linked variable to the
878 * explicitly sized array.
880 if (var
->type
->is_array() && existing
->type
->is_array() &&
881 (var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
882 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
883 if (var
->type
->length
!= 0) {
884 if (var
->type
->length
<= existing
->data
.max_array_access
) {
885 linker_error(prog
, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
889 var
->name
, var
->type
->name
,
890 existing
->data
.max_array_access
);
892 existing
->type
= var
->type
;
894 } else if (existing
->type
->length
!= 0) {
895 if(existing
->type
->length
<= var
->data
.max_array_access
) {
896 linker_error(prog
, "%s `%s' declared as type "
897 "`%s' but outermost dimension has an index"
900 var
->name
, existing
->type
->name
,
901 var
->data
.max_array_access
);
911 * Perform validation of global variables used across multiple shaders
914 cross_validate_globals(struct gl_shader_program
*prog
,
915 struct gl_shader
**shader_list
,
916 unsigned num_shaders
,
919 /* Examine all of the uniforms in all of the shaders and cross validate
922 glsl_symbol_table variables
;
923 for (unsigned i
= 0; i
< num_shaders
; i
++) {
924 if (shader_list
[i
] == NULL
)
927 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
928 ir_variable
*const var
= node
->as_variable();
933 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
936 /* don't cross validate subroutine uniforms */
937 if (var
->type
->contains_subroutine())
940 /* Don't cross validate temporaries that are at global scope. These
941 * will eventually get pulled into the shaders 'main'.
943 if (var
->data
.mode
== ir_var_temporary
)
946 /* If a global with this name has already been seen, verify that the
947 * new instance has the same type. In addition, if the globals have
948 * initializers, the values of the initializers must be the same.
950 ir_variable
*const existing
= variables
.get_variable(var
->name
);
951 if (existing
!= NULL
) {
952 /* Check if types match. Interface blocks have some special
953 * rules so we handle those elsewhere.
955 if (var
->type
!= existing
->type
&&
956 !var
->is_interface_instance()) {
957 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
958 if (var
->type
->is_record() && existing
->type
->is_record()
959 && existing
->type
->record_compare(var
->type
)) {
960 existing
->type
= var
->type
;
962 linker_error(prog
, "%s `%s' declared as type "
963 "`%s' and type `%s'\n",
965 var
->name
, var
->type
->name
,
966 existing
->type
->name
);
972 if (var
->data
.explicit_location
) {
973 if (existing
->data
.explicit_location
974 && (var
->data
.location
!= existing
->data
.location
)) {
975 linker_error(prog
, "explicit locations for %s "
976 "`%s' have differing values\n",
977 mode_string(var
), var
->name
);
981 existing
->data
.location
= var
->data
.location
;
982 existing
->data
.explicit_location
= true;
985 /* From the GLSL 4.20 specification:
986 * "A link error will result if two compilation units in a program
987 * specify different integer-constant bindings for the same
988 * opaque-uniform name. However, it is not an error to specify a
989 * binding on some but not all declarations for the same name"
991 if (var
->data
.explicit_binding
) {
992 if (existing
->data
.explicit_binding
&&
993 var
->data
.binding
!= existing
->data
.binding
) {
994 linker_error(prog
, "explicit bindings for %s "
995 "`%s' have differing values\n",
996 mode_string(var
), var
->name
);
1000 existing
->data
.binding
= var
->data
.binding
;
1001 existing
->data
.explicit_binding
= true;
1004 if (var
->type
->contains_atomic() &&
1005 var
->data
.atomic
.offset
!= existing
->data
.atomic
.offset
) {
1006 linker_error(prog
, "offset specifications for %s "
1007 "`%s' have differing values\n",
1008 mode_string(var
), var
->name
);
1012 /* Validate layout qualifiers for gl_FragDepth.
1014 * From the AMD/ARB_conservative_depth specs:
1016 * "If gl_FragDepth is redeclared in any fragment shader in a
1017 * program, it must be redeclared in all fragment shaders in
1018 * that program that have static assignments to
1019 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1020 * fragment shaders in a single program must have the same set
1023 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1024 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1025 bool layout_differs
=
1026 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1028 if (layout_declared
&& layout_differs
) {
1030 "All redeclarations of gl_FragDepth in all "
1031 "fragment shaders in a single program must have "
1032 "the same set of qualifiers.\n");
1035 if (var
->data
.used
&& layout_differs
) {
1037 "If gl_FragDepth is redeclared with a layout "
1038 "qualifier in any fragment shader, it must be "
1039 "redeclared with the same layout qualifier in "
1040 "all fragment shaders that have assignments to "
1045 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1047 * "If a shared global has multiple initializers, the
1048 * initializers must all be constant expressions, and they
1049 * must all have the same value. Otherwise, a link error will
1050 * result. (A shared global having only one initializer does
1051 * not require that initializer to be a constant expression.)"
1053 * Previous to 4.20 the GLSL spec simply said that initializers
1054 * must have the same value. In this case of non-constant
1055 * initializers, this was impossible to determine. As a result,
1056 * no vendor actually implemented that behavior. The 4.20
1057 * behavior matches the implemented behavior of at least one other
1058 * vendor, so we'll implement that for all GLSL versions.
1060 if (var
->constant_initializer
!= NULL
) {
1061 if (existing
->constant_initializer
!= NULL
) {
1062 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1063 linker_error(prog
, "initializers for %s "
1064 "`%s' have differing values\n",
1065 mode_string(var
), var
->name
);
1069 /* If the first-seen instance of a particular uniform did not
1070 * have an initializer but a later instance does, copy the
1071 * initializer to the version stored in the symbol table.
1073 /* FINISHME: This is wrong. The constant_value field should
1074 * FINISHME: not be modified! Imagine a case where a shader
1075 * FINISHME: without an initializer is linked in two different
1076 * FINISHME: programs with shaders that have differing
1077 * FINISHME: initializers. Linking with the first will
1078 * FINISHME: modify the shader, and linking with the second
1079 * FINISHME: will fail.
1081 existing
->constant_initializer
=
1082 var
->constant_initializer
->clone(ralloc_parent(existing
),
1087 if (var
->data
.has_initializer
) {
1088 if (existing
->data
.has_initializer
1089 && (var
->constant_initializer
== NULL
1090 || existing
->constant_initializer
== NULL
)) {
1092 "shared global variable `%s' has multiple "
1093 "non-constant initializers.\n",
1098 /* Some instance had an initializer, so keep track of that. In
1099 * this location, all sorts of initializers (constant or
1100 * otherwise) will propagate the existence to the variable
1101 * stored in the symbol table.
1103 existing
->data
.has_initializer
= true;
1106 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1107 linker_error(prog
, "declarations for %s `%s' have "
1108 "mismatching invariant qualifiers\n",
1109 mode_string(var
), var
->name
);
1112 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1113 linker_error(prog
, "declarations for %s `%s' have "
1114 "mismatching centroid qualifiers\n",
1115 mode_string(var
), var
->name
);
1118 if (existing
->data
.sample
!= var
->data
.sample
) {
1119 linker_error(prog
, "declarations for %s `%s` have "
1120 "mismatching sample qualifiers\n",
1121 mode_string(var
), var
->name
);
1125 variables
.add_variable(var
);
1132 * Perform validation of uniforms used across multiple shader stages
1135 cross_validate_uniforms(struct gl_shader_program
*prog
)
1137 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1138 MESA_SHADER_STAGES
, true);
1142 * Accumulates the array of prog->UniformBlocks and checks that all
1143 * definitons of blocks agree on their contents.
1146 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
1148 unsigned max_num_uniform_blocks
= 0;
1149 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1150 if (prog
->_LinkedShaders
[i
])
1151 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1154 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1155 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1157 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
1158 max_num_uniform_blocks
);
1159 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
1160 prog
->UniformBlockStageIndex
[i
][j
] = -1;
1165 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
1166 int index
= link_cross_validate_uniform_block(prog
,
1167 &prog
->UniformBlocks
,
1168 &prog
->NumUniformBlocks
,
1169 &sh
->UniformBlocks
[j
]);
1172 linker_error(prog
, "uniform block `%s' has mismatching definitions\n",
1173 sh
->UniformBlocks
[j
].Name
);
1177 prog
->UniformBlockStageIndex
[i
][index
] = j
;
1186 * Populates a shaders symbol table with all global declarations
1189 populate_symbol_table(gl_shader
*sh
)
1191 sh
->symbols
= new(sh
) glsl_symbol_table
;
1193 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1197 if ((func
= inst
->as_function()) != NULL
) {
1198 sh
->symbols
->add_function(func
);
1199 } else if ((var
= inst
->as_variable()) != NULL
) {
1200 if (var
->data
.mode
!= ir_var_temporary
)
1201 sh
->symbols
->add_variable(var
);
1208 * Remap variables referenced in an instruction tree
1210 * This is used when instruction trees are cloned from one shader and placed in
1211 * another. These trees will contain references to \c ir_variable nodes that
1212 * do not exist in the target shader. This function finds these \c ir_variable
1213 * references and replaces the references with matching variables in the target
1216 * If there is no matching variable in the target shader, a clone of the
1217 * \c ir_variable is made and added to the target shader. The new variable is
1218 * added to \b both the instruction stream and the symbol table.
1220 * \param inst IR tree that is to be processed.
1221 * \param symbols Symbol table containing global scope symbols in the
1223 * \param instructions Instruction stream where new variable declarations
1227 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1230 class remap_visitor
: public ir_hierarchical_visitor
{
1232 remap_visitor(struct gl_shader
*target
,
1235 this->target
= target
;
1236 this->symbols
= target
->symbols
;
1237 this->instructions
= target
->ir
;
1238 this->temps
= temps
;
1241 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1243 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1244 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1246 assert(var
!= NULL
);
1248 return visit_continue
;
1251 ir_variable
*const existing
=
1252 this->symbols
->get_variable(ir
->var
->name
);
1253 if (existing
!= NULL
)
1256 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1258 this->symbols
->add_variable(copy
);
1259 this->instructions
->push_head(copy
);
1263 return visit_continue
;
1267 struct gl_shader
*target
;
1268 glsl_symbol_table
*symbols
;
1269 exec_list
*instructions
;
1273 remap_visitor
v(target
, temps
);
1280 * Move non-declarations from one instruction stream to another
1282 * The intended usage pattern of this function is to pass the pointer to the
1283 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1284 * pointer) for \c last and \c false for \c make_copies on the first
1285 * call. Successive calls pass the return value of the previous call for
1286 * \c last and \c true for \c make_copies.
1288 * \param instructions Source instruction stream
1289 * \param last Instruction after which new instructions should be
1290 * inserted in the target instruction stream
1291 * \param make_copies Flag selecting whether instructions in \c instructions
1292 * should be copied (via \c ir_instruction::clone) into the
1293 * target list or moved.
1296 * The new "last" instruction in the target instruction stream. This pointer
1297 * is suitable for use as the \c last parameter of a later call to this
1301 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1302 bool make_copies
, gl_shader
*target
)
1304 hash_table
*temps
= NULL
;
1307 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1308 hash_table_pointer_compare
);
1310 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1311 if (inst
->as_function())
1314 ir_variable
*var
= inst
->as_variable();
1315 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1318 assert(inst
->as_assignment()
1320 || inst
->as_if() /* for initializers with the ?: operator */
1321 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1324 inst
= inst
->clone(target
, NULL
);
1327 hash_table_insert(temps
, inst
, var
);
1329 remap_variables(inst
, target
, temps
);
1334 last
->insert_after(inst
);
1339 hash_table_dtor(temps
);
1345 * Get the function signature for main from a shader
1347 ir_function_signature
*
1348 link_get_main_function_signature(gl_shader
*sh
)
1350 ir_function
*const f
= sh
->symbols
->get_function("main");
1352 exec_list void_parameters
;
1354 /* Look for the 'void main()' signature and ensure that it's defined.
1355 * This keeps the linker from accidentally pick a shader that just
1356 * contains a prototype for main.
1358 * We don't have to check for multiple definitions of main (in multiple
1359 * shaders) because that would have already been caught above.
1361 ir_function_signature
*sig
=
1362 f
->matching_signature(NULL
, &void_parameters
, false);
1363 if ((sig
!= NULL
) && sig
->is_defined
) {
1373 * This class is only used in link_intrastage_shaders() below but declaring
1374 * it inside that function leads to compiler warnings with some versions of
1377 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1379 array_sizing_visitor()
1380 : mem_ctx(ralloc_context(NULL
)),
1381 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1382 hash_table_pointer_compare
))
1386 ~array_sizing_visitor()
1388 hash_table_dtor(this->unnamed_interfaces
);
1389 ralloc_free(this->mem_ctx
);
1392 virtual ir_visitor_status
visit(ir_variable
*var
)
1394 fixup_type(&var
->type
, var
->data
.max_array_access
);
1395 if (var
->type
->is_interface()) {
1396 if (interface_contains_unsized_arrays(var
->type
)) {
1397 const glsl_type
*new_type
=
1398 resize_interface_members(var
->type
,
1399 var
->get_max_ifc_array_access());
1400 var
->type
= new_type
;
1401 var
->change_interface_type(new_type
);
1403 } else if (var
->type
->is_array() &&
1404 var
->type
->fields
.array
->is_interface()) {
1405 if (interface_contains_unsized_arrays(var
->type
->fields
.array
)) {
1406 const glsl_type
*new_type
=
1407 resize_interface_members(var
->type
->fields
.array
,
1408 var
->get_max_ifc_array_access());
1409 var
->change_interface_type(new_type
);
1410 var
->type
= update_interface_members_array(var
->type
, new_type
);
1412 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1413 /* Store a pointer to the variable in the unnamed_interfaces
1416 ir_variable
**interface_vars
= (ir_variable
**)
1417 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1418 if (interface_vars
== NULL
) {
1419 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1421 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1424 unsigned index
= ifc_type
->field_index(var
->name
);
1425 assert(index
< ifc_type
->length
);
1426 assert(interface_vars
[index
] == NULL
);
1427 interface_vars
[index
] = var
;
1429 return visit_continue
;
1433 * For each unnamed interface block that was discovered while running the
1434 * visitor, adjust the interface type to reflect the newly assigned array
1435 * sizes, and fix up the ir_variable nodes to point to the new interface
1438 void fixup_unnamed_interface_types()
1440 hash_table_call_foreach(this->unnamed_interfaces
,
1441 fixup_unnamed_interface_type
, NULL
);
1446 * If the type pointed to by \c type represents an unsized array, replace
1447 * it with a sized array whose size is determined by max_array_access.
1449 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
)
1451 if ((*type
)->is_unsized_array()) {
1452 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1453 max_array_access
+ 1);
1454 assert(*type
!= NULL
);
1458 static const glsl_type
*
1459 update_interface_members_array(const glsl_type
*type
,
1460 const glsl_type
*new_interface_type
)
1462 const glsl_type
*element_type
= type
->fields
.array
;
1463 if (element_type
->is_array()) {
1464 const glsl_type
*new_array_type
=
1465 update_interface_members_array(element_type
, new_interface_type
);
1466 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1468 return glsl_type::get_array_instance(new_interface_type
,
1474 * Determine whether the given interface type contains unsized arrays (if
1475 * it doesn't, array_sizing_visitor doesn't need to process it).
1477 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1479 for (unsigned i
= 0; i
< type
->length
; i
++) {
1480 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1481 if (elem_type
->is_unsized_array())
1488 * Create a new interface type based on the given type, with unsized arrays
1489 * replaced by sized arrays whose size is determined by
1490 * max_ifc_array_access.
1492 static const glsl_type
*
1493 resize_interface_members(const glsl_type
*type
,
1494 const unsigned *max_ifc_array_access
)
1496 unsigned num_fields
= type
->length
;
1497 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1498 memcpy(fields
, type
->fields
.structure
,
1499 num_fields
* sizeof(*fields
));
1500 for (unsigned i
= 0; i
< num_fields
; i
++) {
1501 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
]);
1503 glsl_interface_packing packing
=
1504 (glsl_interface_packing
) type
->interface_packing
;
1505 const glsl_type
*new_ifc_type
=
1506 glsl_type::get_interface_instance(fields
, num_fields
,
1507 packing
, type
->name
);
1509 return new_ifc_type
;
1512 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1515 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1516 ir_variable
**interface_vars
= (ir_variable
**) data
;
1517 unsigned num_fields
= ifc_type
->length
;
1518 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1519 memcpy(fields
, ifc_type
->fields
.structure
,
1520 num_fields
* sizeof(*fields
));
1521 bool interface_type_changed
= false;
1522 for (unsigned i
= 0; i
< num_fields
; i
++) {
1523 if (interface_vars
[i
] != NULL
&&
1524 fields
[i
].type
!= interface_vars
[i
]->type
) {
1525 fields
[i
].type
= interface_vars
[i
]->type
;
1526 interface_type_changed
= true;
1529 if (!interface_type_changed
) {
1533 glsl_interface_packing packing
=
1534 (glsl_interface_packing
) ifc_type
->interface_packing
;
1535 const glsl_type
*new_ifc_type
=
1536 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1539 for (unsigned i
= 0; i
< num_fields
; i
++) {
1540 if (interface_vars
[i
] != NULL
)
1541 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1546 * Memory context used to allocate the data in \c unnamed_interfaces.
1551 * Hash table from const glsl_type * to an array of ir_variable *'s
1552 * pointing to the ir_variables constituting each unnamed interface block.
1554 hash_table
*unnamed_interfaces
;
1559 * Performs the cross-validation of tessellation control shader vertices and
1560 * layout qualifiers for the attached tessellation control shaders,
1561 * and propagates them to the linked TCS and linked shader program.
1564 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1565 struct gl_shader
*linked_shader
,
1566 struct gl_shader
**shader_list
,
1567 unsigned num_shaders
)
1569 linked_shader
->TessCtrl
.VerticesOut
= 0;
1571 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1574 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1576 * "All tessellation control shader layout declarations in a program
1577 * must specify the same output patch vertex count. There must be at
1578 * least one layout qualifier specifying an output patch vertex count
1579 * in any program containing tessellation control shaders; however,
1580 * such a declaration is not required in all tessellation control
1584 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1585 struct gl_shader
*shader
= shader_list
[i
];
1587 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1588 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1589 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1590 linker_error(prog
, "tessellation control shader defined with "
1591 "conflicting output vertex count (%d and %d)\n",
1592 linked_shader
->TessCtrl
.VerticesOut
,
1593 shader
->TessCtrl
.VerticesOut
);
1596 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1600 /* Just do the intrastage -> interstage propagation right now,
1601 * since we already know we're in the right type of shader program
1604 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1605 linker_error(prog
, "tessellation control shader didn't declare "
1606 "vertices out layout qualifier\n");
1609 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1614 * Performs the cross-validation of tessellation evaluation shader
1615 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1616 * for the attached tessellation evaluation shaders, and propagates them
1617 * to the linked TES and linked shader program.
1620 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1621 struct gl_shader
*linked_shader
,
1622 struct gl_shader
**shader_list
,
1623 unsigned num_shaders
)
1625 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1626 linked_shader
->TessEval
.Spacing
= 0;
1627 linked_shader
->TessEval
.VertexOrder
= 0;
1628 linked_shader
->TessEval
.PointMode
= -1;
1630 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1633 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1635 * "At least one tessellation evaluation shader (compilation unit) in
1636 * a program must declare a primitive mode in its input layout.
1637 * Declaration vertex spacing, ordering, and point mode identifiers is
1638 * optional. It is not required that all tessellation evaluation
1639 * shaders in a program declare a primitive mode. If spacing or
1640 * vertex ordering declarations are omitted, the tessellation
1641 * primitive generator will use equal spacing or counter-clockwise
1642 * vertex ordering, respectively. If a point mode declaration is
1643 * omitted, the tessellation primitive generator will produce lines or
1644 * triangles according to the primitive mode."
1647 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1648 struct gl_shader
*shader
= shader_list
[i
];
1650 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1651 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1652 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1653 linker_error(prog
, "tessellation evaluation shader defined with "
1654 "conflicting input primitive modes.\n");
1657 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1660 if (shader
->TessEval
.Spacing
!= 0) {
1661 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1662 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1663 linker_error(prog
, "tessellation evaluation shader defined with "
1664 "conflicting vertex spacing.\n");
1667 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1670 if (shader
->TessEval
.VertexOrder
!= 0) {
1671 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1672 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1673 linker_error(prog
, "tessellation evaluation shader defined with "
1674 "conflicting ordering.\n");
1677 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1680 if (shader
->TessEval
.PointMode
!= -1) {
1681 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1682 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1683 linker_error(prog
, "tessellation evaluation shader defined with "
1684 "conflicting point modes.\n");
1687 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1692 /* Just do the intrastage -> interstage propagation right now,
1693 * since we already know we're in the right type of shader program
1696 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1698 "tessellation evaluation shader didn't declare input "
1699 "primitive modes.\n");
1702 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1704 if (linked_shader
->TessEval
.Spacing
== 0)
1705 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1706 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1708 if (linked_shader
->TessEval
.VertexOrder
== 0)
1709 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1710 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1712 if (linked_shader
->TessEval
.PointMode
== -1)
1713 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1714 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1719 * Performs the cross-validation of layout qualifiers specified in
1720 * redeclaration of gl_FragCoord for the attached fragment shaders,
1721 * and propagates them to the linked FS and linked shader program.
1724 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1725 struct gl_shader
*linked_shader
,
1726 struct gl_shader
**shader_list
,
1727 unsigned num_shaders
)
1729 linked_shader
->redeclares_gl_fragcoord
= false;
1730 linked_shader
->uses_gl_fragcoord
= false;
1731 linked_shader
->origin_upper_left
= false;
1732 linked_shader
->pixel_center_integer
= false;
1734 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1735 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1738 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1739 struct gl_shader
*shader
= shader_list
[i
];
1740 /* From the GLSL 1.50 spec, page 39:
1742 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1743 * it must be redeclared in all the fragment shaders in that program
1744 * that have a static use gl_FragCoord."
1746 if ((linked_shader
->redeclares_gl_fragcoord
1747 && !shader
->redeclares_gl_fragcoord
1748 && shader
->uses_gl_fragcoord
)
1749 || (shader
->redeclares_gl_fragcoord
1750 && !linked_shader
->redeclares_gl_fragcoord
1751 && linked_shader
->uses_gl_fragcoord
)) {
1752 linker_error(prog
, "fragment shader defined with conflicting "
1753 "layout qualifiers for gl_FragCoord\n");
1756 /* From the GLSL 1.50 spec, page 39:
1758 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1759 * single program must have the same set of qualifiers."
1761 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1762 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1763 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1764 linker_error(prog
, "fragment shader defined with conflicting "
1765 "layout qualifiers for gl_FragCoord\n");
1768 /* Update the linked shader state. Note that uses_gl_fragcoord should
1769 * accumulate the results. The other values should replace. If there
1770 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1771 * are already known to be the same.
1773 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1774 linked_shader
->redeclares_gl_fragcoord
=
1775 shader
->redeclares_gl_fragcoord
;
1776 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1777 || shader
->uses_gl_fragcoord
;
1778 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1779 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1782 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1787 * Performs the cross-validation of geometry shader max_vertices and
1788 * primitive type layout qualifiers for the attached geometry shaders,
1789 * and propagates them to the linked GS and linked shader program.
1792 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1793 struct gl_shader
*linked_shader
,
1794 struct gl_shader
**shader_list
,
1795 unsigned num_shaders
)
1797 linked_shader
->Geom
.VerticesOut
= 0;
1798 linked_shader
->Geom
.Invocations
= 0;
1799 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1800 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1802 /* No in/out qualifiers defined for anything but GLSL 1.50+
1803 * geometry shaders so far.
1805 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1808 /* From the GLSL 1.50 spec, page 46:
1810 * "All geometry shader output layout declarations in a program
1811 * must declare the same layout and same value for
1812 * max_vertices. There must be at least one geometry output
1813 * layout declaration somewhere in a program, but not all
1814 * geometry shaders (compilation units) are required to
1818 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1819 struct gl_shader
*shader
= shader_list
[i
];
1821 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1822 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1823 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1824 linker_error(prog
, "geometry shader defined with conflicting "
1828 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1831 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1832 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1833 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1834 linker_error(prog
, "geometry shader defined with conflicting "
1838 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1841 if (shader
->Geom
.VerticesOut
!= 0) {
1842 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1843 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1844 linker_error(prog
, "geometry shader defined with conflicting "
1845 "output vertex count (%d and %d)\n",
1846 linked_shader
->Geom
.VerticesOut
,
1847 shader
->Geom
.VerticesOut
);
1850 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1853 if (shader
->Geom
.Invocations
!= 0) {
1854 if (linked_shader
->Geom
.Invocations
!= 0 &&
1855 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1856 linker_error(prog
, "geometry shader defined with conflicting "
1857 "invocation count (%d and %d)\n",
1858 linked_shader
->Geom
.Invocations
,
1859 shader
->Geom
.Invocations
);
1862 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1866 /* Just do the intrastage -> interstage propagation right now,
1867 * since we already know we're in the right type of shader program
1870 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1872 "geometry shader didn't declare primitive input type\n");
1875 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1877 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1879 "geometry shader didn't declare primitive output type\n");
1882 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1884 if (linked_shader
->Geom
.VerticesOut
== 0) {
1886 "geometry shader didn't declare max_vertices\n");
1889 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1891 if (linked_shader
->Geom
.Invocations
== 0)
1892 linked_shader
->Geom
.Invocations
= 1;
1894 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1899 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1900 * qualifiers for the attached compute shaders, and propagate them to the
1901 * linked CS and linked shader program.
1904 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1905 struct gl_shader
*linked_shader
,
1906 struct gl_shader
**shader_list
,
1907 unsigned num_shaders
)
1909 for (int i
= 0; i
< 3; i
++)
1910 linked_shader
->Comp
.LocalSize
[i
] = 0;
1912 /* This function is called for all shader stages, but it only has an effect
1913 * for compute shaders.
1915 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
1918 /* From the ARB_compute_shader spec, in the section describing local size
1921 * If multiple compute shaders attached to a single program object
1922 * declare local work-group size, the declarations must be identical;
1923 * otherwise a link-time error results. Furthermore, if a program
1924 * object contains any compute shaders, at least one must contain an
1925 * input layout qualifier specifying the local work sizes of the
1926 * program, or a link-time error will occur.
1928 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
1929 struct gl_shader
*shader
= shader_list
[sh
];
1931 if (shader
->Comp
.LocalSize
[0] != 0) {
1932 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
1933 for (int i
= 0; i
< 3; i
++) {
1934 if (linked_shader
->Comp
.LocalSize
[i
] !=
1935 shader
->Comp
.LocalSize
[i
]) {
1936 linker_error(prog
, "compute shader defined with conflicting "
1942 for (int i
= 0; i
< 3; i
++)
1943 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
1947 /* Just do the intrastage -> interstage propagation right now,
1948 * since we already know we're in the right type of shader program
1951 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
1952 linker_error(prog
, "compute shader didn't declare local size\n");
1955 for (int i
= 0; i
< 3; i
++)
1956 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
1961 * Combine a group of shaders for a single stage to generate a linked shader
1964 * If this function is supplied a single shader, it is cloned, and the new
1965 * shader is returned.
1967 static struct gl_shader
*
1968 link_intrastage_shaders(void *mem_ctx
,
1969 struct gl_context
*ctx
,
1970 struct gl_shader_program
*prog
,
1971 struct gl_shader
**shader_list
,
1972 unsigned num_shaders
)
1974 struct gl_uniform_block
*uniform_blocks
= NULL
;
1976 /* Check that global variables defined in multiple shaders are consistent.
1978 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1979 if (!prog
->LinkStatus
)
1982 /* Check that interface blocks defined in multiple shaders are consistent.
1984 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1986 if (!prog
->LinkStatus
)
1989 /* Link up uniform blocks defined within this stage. */
1990 const unsigned num_uniform_blocks
=
1991 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
1993 if (!prog
->LinkStatus
)
1996 /* Check that there is only a single definition of each function signature
1997 * across all shaders.
1999 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2000 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2001 ir_function
*const f
= node
->as_function();
2006 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2007 ir_function
*const other
=
2008 shader_list
[j
]->symbols
->get_function(f
->name
);
2010 /* If the other shader has no function (and therefore no function
2011 * signatures) with the same name, skip to the next shader.
2016 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2017 if (!sig
->is_defined
|| sig
->is_builtin())
2020 ir_function_signature
*other_sig
=
2021 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2023 if ((other_sig
!= NULL
) && other_sig
->is_defined
2024 && !other_sig
->is_builtin()) {
2025 linker_error(prog
, "function `%s' is multiply defined\n",
2034 /* Find the shader that defines main, and make a clone of it.
2036 * Starting with the clone, search for undefined references. If one is
2037 * found, find the shader that defines it. Clone the reference and add
2038 * it to the shader. Repeat until there are no undefined references or
2039 * until a reference cannot be resolved.
2041 gl_shader
*main
= NULL
;
2042 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2043 if (link_get_main_function_signature(shader_list
[i
]) != NULL
) {
2044 main
= shader_list
[i
];
2050 linker_error(prog
, "%s shader lacks `main'\n",
2051 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2055 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2056 linked
->ir
= new(linked
) exec_list
;
2057 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2059 linked
->UniformBlocks
= uniform_blocks
;
2060 linked
->NumUniformBlocks
= num_uniform_blocks
;
2061 ralloc_steal(linked
, linked
->UniformBlocks
);
2063 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2064 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2065 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2066 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2067 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2069 populate_symbol_table(linked
);
2071 /* The pointer to the main function in the final linked shader (i.e., the
2072 * copy of the original shader that contained the main function).
2074 ir_function_signature
*const main_sig
=
2075 link_get_main_function_signature(linked
);
2077 /* Move any instructions other than variable declarations or function
2078 * declarations into main.
2080 exec_node
*insertion_point
=
2081 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2084 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2085 if (shader_list
[i
] == main
)
2088 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2089 insertion_point
, true, linked
);
2092 /* Check if any shader needs built-in functions. */
2093 bool need_builtins
= false;
2094 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2095 if (shader_list
[i
]->uses_builtin_functions
) {
2096 need_builtins
= true;
2102 if (need_builtins
) {
2103 /* Make a temporary array one larger than shader_list, which will hold
2104 * the built-in function shader as well.
2106 gl_shader
**linking_shaders
= (gl_shader
**)
2107 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2109 ok
= linking_shaders
!= NULL
;
2112 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2113 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2115 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2117 free(linking_shaders
);
2119 _mesa_error_no_memory(__func__
);
2122 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2127 ctx
->Driver
.DeleteShader(ctx
, linked
);
2131 /* At this point linked should contain all of the linked IR, so
2132 * validate it to make sure nothing went wrong.
2134 validate_ir_tree(linked
->ir
);
2136 /* Set the size of geometry shader input arrays */
2137 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2138 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2139 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2140 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2141 ir
->accept(&input_resize_visitor
);
2145 if (ctx
->Const
.VertexID_is_zero_based
)
2146 lower_vertex_id(linked
);
2148 /* Validate correct usage of barrier() in the tess control shader */
2149 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2150 barrier_use_visitor
visitor(prog
);
2151 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2152 ir
->accept(&visitor
);
2156 /* Make a pass over all variable declarations to ensure that arrays with
2157 * unspecified sizes have a size specified. The size is inferred from the
2158 * max_array_access field.
2160 array_sizing_visitor v
;
2162 v
.fixup_unnamed_interface_types();
2168 * Update the sizes of linked shader uniform arrays to the maximum
2171 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2173 * If one or more elements of an array are active,
2174 * GetActiveUniform will return the name of the array in name,
2175 * subject to the restrictions listed above. The type of the array
2176 * is returned in type. The size parameter contains the highest
2177 * array element index used, plus one. The compiler or linker
2178 * determines the highest index used. There will be only one
2179 * active uniform reported by the GL per uniform array.
2183 update_array_sizes(struct gl_shader_program
*prog
)
2185 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2186 if (prog
->_LinkedShaders
[i
] == NULL
)
2189 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2190 ir_variable
*const var
= node
->as_variable();
2192 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2193 !var
->type
->is_array())
2196 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2197 * will not be eliminated. Since we always do std140, just
2198 * don't resize arrays in UBOs.
2200 * Atomic counters are supposed to get deterministic
2201 * locations assigned based on the declaration ordering and
2202 * sizes, array compaction would mess that up.
2204 * Subroutine uniforms are not removed.
2206 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2207 var
->type
->contains_subroutine())
2210 unsigned int size
= var
->data
.max_array_access
;
2211 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2212 if (prog
->_LinkedShaders
[j
] == NULL
)
2215 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2216 ir_variable
*other_var
= node2
->as_variable();
2220 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2221 other_var
->data
.max_array_access
> size
) {
2222 size
= other_var
->data
.max_array_access
;
2227 if (size
+ 1 != var
->type
->length
) {
2228 /* If this is a built-in uniform (i.e., it's backed by some
2229 * fixed-function state), adjust the number of state slots to
2230 * match the new array size. The number of slots per array entry
2231 * is not known. It seems safe to assume that the total number of
2232 * slots is an integer multiple of the number of array elements.
2233 * Determine the number of slots per array element by dividing by
2234 * the old (total) size.
2236 const unsigned num_slots
= var
->get_num_state_slots();
2237 if (num_slots
> 0) {
2238 var
->set_num_state_slots((size
+ 1)
2239 * (num_slots
/ var
->type
->length
));
2242 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2244 /* FINISHME: We should update the types of array
2245 * dereferences of this variable now.
2253 * Resize tessellation evaluation per-vertex inputs to the size of
2254 * tessellation control per-vertex outputs.
2257 resize_tes_inputs(struct gl_context
*ctx
,
2258 struct gl_shader_program
*prog
)
2260 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2263 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2264 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2266 /* If no control shader is present, then the TES inputs are statically
2267 * sized to MaxPatchVertices; the actual size of the arrays won't be
2268 * known until draw time.
2270 const int num_vertices
= tcs
2271 ? tcs
->TessCtrl
.VerticesOut
2272 : ctx
->Const
.MaxPatchVertices
;
2274 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2275 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2276 ir
->accept(&input_resize_visitor
);
2281 * Find a contiguous set of available bits in a bitmask.
2283 * \param used_mask Bits representing used (1) and unused (0) locations
2284 * \param needed_count Number of contiguous bits needed.
2287 * Base location of the available bits on success or -1 on failure.
2290 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2292 unsigned needed_mask
= (1 << needed_count
) - 1;
2293 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2295 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2296 * cannot optimize possibly infinite loops" for the loop below.
2298 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2301 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2302 if ((needed_mask
& ~used_mask
) == needed_mask
)
2313 * Assign locations for either VS inputs or FS outputs
2315 * \param prog Shader program whose variables need locations assigned
2316 * \param constants Driver specific constant values for the program.
2317 * \param target_index Selector for the program target to receive location
2318 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2319 * \c MESA_SHADER_FRAGMENT.
2322 * If locations are successfully assigned, true is returned. Otherwise an
2323 * error is emitted to the shader link log and false is returned.
2326 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2327 struct gl_constants
*constants
,
2328 unsigned target_index
)
2330 /* Maximum number of generic locations. This corresponds to either the
2331 * maximum number of draw buffers or the maximum number of generic
2334 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2335 constants
->Program
[target_index
].MaxAttribs
:
2336 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2338 /* Mark invalid locations as being used.
2340 unsigned used_locations
= (max_index
>= 32)
2341 ? ~0 : ~((1 << max_index
) - 1);
2342 unsigned double_storage_locations
= 0;
2344 assert((target_index
== MESA_SHADER_VERTEX
)
2345 || (target_index
== MESA_SHADER_FRAGMENT
));
2347 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2351 /* Operate in a total of four passes.
2353 * 1. Invalidate the location assignments for all vertex shader inputs.
2355 * 2. Assign locations for inputs that have user-defined (via
2356 * glBindVertexAttribLocation) locations and outputs that have
2357 * user-defined locations (via glBindFragDataLocation).
2359 * 3. Sort the attributes without assigned locations by number of slots
2360 * required in decreasing order. Fragmentation caused by attribute
2361 * locations assigned by the application may prevent large attributes
2362 * from having enough contiguous space.
2364 * 4. Assign locations to any inputs without assigned locations.
2367 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2368 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2370 const enum ir_variable_mode direction
=
2371 (target_index
== MESA_SHADER_VERTEX
)
2372 ? ir_var_shader_in
: ir_var_shader_out
;
2375 /* Temporary storage for the set of attributes that need locations assigned.
2381 /* Used below in the call to qsort. */
2382 static int compare(const void *a
, const void *b
)
2384 const temp_attr
*const l
= (const temp_attr
*) a
;
2385 const temp_attr
*const r
= (const temp_attr
*) b
;
2387 /* Reversed because we want a descending order sort below. */
2388 return r
->slots
- l
->slots
;
2392 unsigned num_attr
= 0;
2394 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2395 ir_variable
*const var
= node
->as_variable();
2397 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2400 if (var
->data
.explicit_location
) {
2401 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2402 || (var
->data
.location
< 0)) {
2404 "invalid explicit location %d specified for `%s'\n",
2405 (var
->data
.location
< 0)
2406 ? var
->data
.location
2407 : var
->data
.location
- generic_base
,
2411 } else if (target_index
== MESA_SHADER_VERTEX
) {
2414 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2415 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2416 var
->data
.location
= binding
;
2417 var
->data
.is_unmatched_generic_inout
= 0;
2419 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2423 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2424 assert(binding
>= FRAG_RESULT_DATA0
);
2425 var
->data
.location
= binding
;
2426 var
->data
.is_unmatched_generic_inout
= 0;
2428 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2429 var
->data
.index
= index
;
2434 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2436 * "Output binding assignments will cause LinkProgram to fail:
2438 * If the program has an active output assigned to a location greater
2439 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2440 * an active output assigned an index greater than or equal to one;"
2442 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2443 var
->data
.location
- generic_base
>=
2444 (int) constants
->MaxDualSourceDrawBuffers
) {
2446 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2447 "with index %u for %s\n",
2448 var
->data
.location
- generic_base
, var
->data
.index
,
2453 const unsigned slots
= var
->type
->count_attribute_slots();
2455 /* If the variable is not a built-in and has a location statically
2456 * assigned in the shader (presumably via a layout qualifier), make sure
2457 * that it doesn't collide with other assigned locations. Otherwise,
2458 * add it to the list of variables that need linker-assigned locations.
2460 if (var
->data
.location
!= -1) {
2461 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2462 /* From page 61 of the OpenGL 4.0 spec:
2464 * "LinkProgram will fail if the attribute bindings assigned
2465 * by BindAttribLocation do not leave not enough space to
2466 * assign a location for an active matrix attribute or an
2467 * active attribute array, both of which require multiple
2468 * contiguous generic attributes."
2470 * I think above text prohibits the aliasing of explicit and
2471 * automatic assignments. But, aliasing is allowed in manual
2472 * assignments of attribute locations. See below comments for
2475 * From OpenGL 4.0 spec, page 61:
2477 * "It is possible for an application to bind more than one
2478 * attribute name to the same location. This is referred to as
2479 * aliasing. This will only work if only one of the aliased
2480 * attributes is active in the executable program, or if no
2481 * path through the shader consumes more than one attribute of
2482 * a set of attributes aliased to the same location. A link
2483 * error can occur if the linker determines that every path
2484 * through the shader consumes multiple aliased attributes,
2485 * but implementations are not required to generate an error
2488 * From GLSL 4.30 spec, page 54:
2490 * "A program will fail to link if any two non-vertex shader
2491 * input variables are assigned to the same location. For
2492 * vertex shaders, multiple input variables may be assigned
2493 * to the same location using either layout qualifiers or via
2494 * the OpenGL API. However, such aliasing is intended only to
2495 * support vertex shaders where each execution path accesses
2496 * at most one input per each location. Implementations are
2497 * permitted, but not required, to generate link-time errors
2498 * if they detect that every path through the vertex shader
2499 * executable accesses multiple inputs assigned to any single
2500 * location. For all shader types, a program will fail to link
2501 * if explicit location assignments leave the linker unable
2502 * to find space for other variables without explicit
2505 * From OpenGL ES 3.0 spec, page 56:
2507 * "Binding more than one attribute name to the same location
2508 * is referred to as aliasing, and is not permitted in OpenGL
2509 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2510 * fail when this condition exists. However, aliasing is
2511 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2512 * This will only work if only one of the aliased attributes
2513 * is active in the executable program, or if no path through
2514 * the shader consumes more than one attribute of a set of
2515 * attributes aliased to the same location. A link error can
2516 * occur if the linker determines that every path through the
2517 * shader consumes multiple aliased attributes, but implemen-
2518 * tations are not required to generate an error in this case."
2520 * After looking at above references from OpenGL, OpenGL ES and
2521 * GLSL specifications, we allow aliasing of vertex input variables
2522 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2524 * NOTE: This is not required by the spec but its worth mentioning
2525 * here that we're not doing anything to make sure that no path
2526 * through the vertex shader executable accesses multiple inputs
2527 * assigned to any single location.
2530 /* Mask representing the contiguous slots that will be used by
2533 const unsigned attr
= var
->data
.location
- generic_base
;
2534 const unsigned use_mask
= (1 << slots
) - 1;
2535 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2536 ? "vertex shader input" : "fragment shader output";
2538 /* Generate a link error if the requested locations for this
2539 * attribute exceed the maximum allowed attribute location.
2541 if (attr
+ slots
> max_index
) {
2543 "insufficient contiguous locations "
2544 "available for %s `%s' %d %d %d\n", string
,
2545 var
->name
, used_locations
, use_mask
, attr
);
2549 /* Generate a link error if the set of bits requested for this
2550 * attribute overlaps any previously allocated bits.
2552 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2553 if (target_index
== MESA_SHADER_FRAGMENT
||
2554 (prog
->IsES
&& prog
->Version
>= 300)) {
2556 "overlapping location is assigned "
2557 "to %s `%s' %d %d %d\n", string
,
2558 var
->name
, used_locations
, use_mask
, attr
);
2561 linker_warning(prog
,
2562 "overlapping location is assigned "
2563 "to %s `%s' %d %d %d\n", string
,
2564 var
->name
, used_locations
, use_mask
, attr
);
2568 used_locations
|= (use_mask
<< attr
);
2570 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2572 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2573 * active attribute variables may fail to link, unless
2574 * device-dependent optimizations are able to make the program
2575 * fit within available hardware resources. For the purposes
2576 * of this test, attribute variables of the type dvec3, dvec4,
2577 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2578 * count as consuming twice as many attributes as equivalent
2579 * single-precision types. While these types use the same number
2580 * of generic attributes as their single-precision equivalents,
2581 * implementations are permitted to consume two single-precision
2582 * vectors of internal storage for each three- or four-component
2583 * double-precision vector."
2585 * Mark this attribute slot as taking up twice as much space
2586 * so we can count it properly against limits. According to
2587 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2588 * is optional behavior, but it seems preferable.
2590 const glsl_type
*type
= var
->type
->without_array();
2591 if (type
== glsl_type::dvec3_type
||
2592 type
== glsl_type::dvec4_type
||
2593 type
== glsl_type::dmat2x3_type
||
2594 type
== glsl_type::dmat2x4_type
||
2595 type
== glsl_type::dmat3_type
||
2596 type
== glsl_type::dmat3x4_type
||
2597 type
== glsl_type::dmat4x3_type
||
2598 type
== glsl_type::dmat4_type
) {
2599 double_storage_locations
|= (use_mask
<< attr
);
2606 to_assign
[num_attr
].slots
= slots
;
2607 to_assign
[num_attr
].var
= var
;
2611 if (target_index
== MESA_SHADER_VERTEX
) {
2612 unsigned total_attribs_size
=
2613 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2614 _mesa_bitcount(double_storage_locations
);
2615 if (total_attribs_size
> max_index
) {
2617 "attempt to use %d vertex attribute slots only %d available ",
2618 total_attribs_size
, max_index
);
2623 /* If all of the attributes were assigned locations by the application (or
2624 * are built-in attributes with fixed locations), return early. This should
2625 * be the common case.
2630 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2632 if (target_index
== MESA_SHADER_VERTEX
) {
2633 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2634 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2635 * reserved to prevent it from being automatically allocated below.
2637 find_deref_visitor
find("gl_Vertex");
2639 if (find
.variable_found())
2640 used_locations
|= (1 << 0);
2643 for (unsigned i
= 0; i
< num_attr
; i
++) {
2644 /* Mask representing the contiguous slots that will be used by this
2647 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2649 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2652 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2653 ? "vertex shader input" : "fragment shader output";
2656 "insufficient contiguous locations "
2657 "available for %s `%s'\n",
2658 string
, to_assign
[i
].var
->name
);
2662 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2663 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2664 used_locations
|= (use_mask
<< location
);
2672 * Demote shader inputs and outputs that are not used in other stages
2675 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
2677 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2678 ir_variable
*const var
= node
->as_variable();
2680 if ((var
== NULL
) || (var
->data
.mode
!= int(mode
)))
2683 /* A shader 'in' or 'out' variable is only really an input or output if
2684 * its value is used by other shader stages. This will cause the variable
2685 * to have a location assigned.
2687 if (var
->data
.is_unmatched_generic_inout
) {
2688 assert(var
->data
.mode
!= ir_var_temporary
);
2689 var
->data
.mode
= ir_var_auto
;
2696 * Store the gl_FragDepth layout in the gl_shader_program struct.
2699 store_fragdepth_layout(struct gl_shader_program
*prog
)
2701 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2705 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2707 /* We don't look up the gl_FragDepth symbol directly because if
2708 * gl_FragDepth is not used in the shader, it's removed from the IR.
2709 * However, the symbol won't be removed from the symbol table.
2711 * We're only interested in the cases where the variable is NOT removed
2714 foreach_in_list(ir_instruction
, node
, ir
) {
2715 ir_variable
*const var
= node
->as_variable();
2717 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2721 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2722 switch (var
->data
.depth_layout
) {
2723 case ir_depth_layout_none
:
2724 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2726 case ir_depth_layout_any
:
2727 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2729 case ir_depth_layout_greater
:
2730 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2732 case ir_depth_layout_less
:
2733 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2735 case ir_depth_layout_unchanged
:
2736 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2747 * Validate the resources used by a program versus the implementation limits
2750 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2752 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2753 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2758 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2759 linker_error(prog
, "Too many %s shader texture samplers\n",
2760 _mesa_shader_stage_to_string(i
));
2763 if (sh
->num_uniform_components
>
2764 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2765 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2766 linker_warning(prog
, "Too many %s shader default uniform block "
2767 "components, but the driver will try to optimize "
2768 "them out; this is non-portable out-of-spec "
2770 _mesa_shader_stage_to_string(i
));
2772 linker_error(prog
, "Too many %s shader default uniform block "
2774 _mesa_shader_stage_to_string(i
));
2778 if (sh
->num_combined_uniform_components
>
2779 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2780 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2781 linker_warning(prog
, "Too many %s shader uniform components, "
2782 "but the driver will try to optimize them out; "
2783 "this is non-portable out-of-spec behavior\n",
2784 _mesa_shader_stage_to_string(i
));
2786 linker_error(prog
, "Too many %s shader uniform components\n",
2787 _mesa_shader_stage_to_string(i
));
2792 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2793 unsigned total_uniform_blocks
= 0;
2795 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
2796 if (prog
->UniformBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxUniformBlockSize
) {
2797 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
2798 prog
->UniformBlocks
[i
].Name
,
2799 prog
->UniformBlocks
[i
].UniformBufferSize
,
2800 ctx
->Const
.MaxUniformBlockSize
);
2803 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2804 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2806 total_uniform_blocks
++;
2810 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2811 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2812 prog
->NumUniformBlocks
,
2813 ctx
->Const
.MaxCombinedUniformBlocks
);
2815 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2816 const unsigned max_uniform_blocks
=
2817 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2818 if (blocks
[i
] > max_uniform_blocks
) {
2819 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2820 _mesa_shader_stage_to_string(i
),
2822 max_uniform_blocks
);
2831 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
2833 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2834 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2839 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
2840 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
2846 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
2847 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
2848 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
2849 if (fn
->types
[k
] == uni
->type
) {
2855 uni
->num_compatible_subroutines
= count
;
2861 check_subroutine_resources(struct gl_shader_program
*prog
)
2863 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2864 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2867 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
2868 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
2869 _mesa_shader_stage_to_string(i
));
2874 * Validate shader image resources.
2877 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2879 unsigned total_image_units
= 0;
2880 unsigned fragment_outputs
= 0;
2882 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
2885 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2886 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2889 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
2890 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
2891 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
2892 ctx
->Const
.Program
[i
].MaxImageUniforms
);
2894 total_image_units
+= sh
->NumImages
;
2896 if (i
== MESA_SHADER_FRAGMENT
) {
2897 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2898 ir_variable
*var
= node
->as_variable();
2899 if (var
&& var
->data
.mode
== ir_var_shader_out
)
2900 fragment_outputs
+= var
->type
->count_attribute_slots();
2906 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
2907 linker_error(prog
, "Too many combined image uniforms\n");
2909 if (total_image_units
+ fragment_outputs
>
2910 ctx
->Const
.MaxCombinedShaderOutputResources
)
2911 linker_error(prog
, "Too many combined image uniforms and fragment outputs\n");
2916 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2917 * for a variable, checks for overlaps between other uniforms using explicit
2921 reserve_explicit_locations(struct gl_shader_program
*prog
,
2922 string_to_uint_map
*map
, ir_variable
*var
)
2924 unsigned slots
= var
->type
->uniform_locations();
2925 unsigned max_loc
= var
->data
.location
+ slots
- 1;
2927 /* Resize remap table if locations do not fit in the current one. */
2928 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
2929 prog
->UniformRemapTable
=
2930 reralloc(prog
, prog
->UniformRemapTable
,
2931 gl_uniform_storage
*,
2934 if (!prog
->UniformRemapTable
) {
2935 linker_error(prog
, "Out of memory during linking.\n");
2939 /* Initialize allocated space. */
2940 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
2941 prog
->UniformRemapTable
[i
] = NULL
;
2943 prog
->NumUniformRemapTable
= max_loc
+ 1;
2946 for (unsigned i
= 0; i
< slots
; i
++) {
2947 unsigned loc
= var
->data
.location
+ i
;
2949 /* Check if location is already used. */
2950 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
2952 /* Possibly same uniform from a different stage, this is ok. */
2954 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
)
2957 /* ARB_explicit_uniform_location specification states:
2959 * "No two default-block uniform variables in the program can have
2960 * the same location, even if they are unused, otherwise a compiler
2961 * or linker error will be generated."
2964 "location qualifier for uniform %s overlaps "
2965 "previously used location\n",
2970 /* Initialize location as inactive before optimization
2971 * rounds and location assignment.
2973 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
2976 /* Note, base location used for arrays. */
2977 map
->put(var
->data
.location
, var
->name
);
2983 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
2984 struct gl_shader
*sh
,
2987 unsigned slots
= var
->type
->uniform_locations();
2988 unsigned max_loc
= var
->data
.location
+ slots
- 1;
2990 /* Resize remap table if locations do not fit in the current one. */
2991 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
2992 sh
->SubroutineUniformRemapTable
=
2993 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
2994 gl_uniform_storage
*,
2997 if (!sh
->SubroutineUniformRemapTable
) {
2998 linker_error(prog
, "Out of memory during linking.\n");
3002 /* Initialize allocated space. */
3003 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3004 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3006 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3009 for (unsigned i
= 0; i
< slots
; i
++) {
3010 unsigned loc
= var
->data
.location
+ i
;
3012 /* Check if location is already used. */
3013 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3015 /* ARB_explicit_uniform_location specification states:
3016 * "No two subroutine uniform variables can have the same location
3017 * in the same shader stage, otherwise a compiler or linker error
3018 * will be generated."
3021 "location qualifier for uniform %s overlaps "
3022 "previously used location\n",
3027 /* Initialize location as inactive before optimization
3028 * rounds and location assignment.
3030 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3036 * Check and reserve all explicit uniform locations, called before
3037 * any optimizations happen to handle also inactive uniforms and
3038 * inactive array elements that may get trimmed away.
3041 check_explicit_uniform_locations(struct gl_context
*ctx
,
3042 struct gl_shader_program
*prog
)
3044 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3047 /* This map is used to detect if overlapping explicit locations
3048 * occur with the same uniform (from different stage) or a different one.
3050 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3053 linker_error(prog
, "Out of memory during linking.\n");
3057 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3058 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3063 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3064 ir_variable
*var
= node
->as_variable();
3065 if (var
&& (var
->data
.mode
== ir_var_uniform
|| var
->data
.mode
== ir_var_shader_storage
) &&
3066 var
->data
.explicit_location
) {
3068 if (var
->type
->is_subroutine())
3069 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3071 ret
= reserve_explicit_locations(prog
, uniform_map
, var
);
3084 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3085 const void *data
, uint8_t stages
)
3089 /* If resource already exists, do not add it again. */
3090 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3091 if (prog
->ProgramResourceList
[i
].Data
== data
)
3094 prog
->ProgramResourceList
=
3096 prog
->ProgramResourceList
,
3097 gl_program_resource
,
3098 prog
->NumProgramResourceList
+ 1);
3100 if (!prog
->ProgramResourceList
) {
3101 linker_error(prog
, "Out of memory during linking.\n");
3105 struct gl_program_resource
*res
=
3106 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3110 res
->StageReferences
= stages
;
3112 prog
->NumProgramResourceList
++;
3118 * Function builds a stage reference bitmask from variable name.
3121 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3126 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3127 * used for reference mask in gl_program_resource will need to be changed.
3129 assert(MESA_SHADER_STAGES
< 8);
3131 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3132 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3136 /* Shader symbol table may contain variables that have
3137 * been optimized away. Search IR for the variable instead.
3139 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3140 ir_variable
*var
= node
->as_variable();
3142 unsigned baselen
= strlen(var
->name
);
3144 /* Type needs to match if specified, otherwise we might
3145 * pick a variable with same name but different interface.
3147 if (var
->data
.mode
!= mode
)
3150 if (strncmp(var
->name
, name
, baselen
) == 0) {
3151 /* Check for exact name matches but also check for arrays and
3154 if (name
[baselen
] == '\0' ||
3155 name
[baselen
] == '[' ||
3156 name
[baselen
] == '.') {
3168 add_interface_variables(struct gl_shader_program
*shProg
,
3169 struct gl_shader
*sh
, GLenum programInterface
)
3171 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3172 ir_variable
*var
= node
->as_variable();
3178 switch (var
->data
.mode
) {
3179 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3180 * "For GetActiveAttrib, all active vertex shader input variables
3181 * are enumerated, including the special built-in inputs gl_VertexID
3182 * and gl_InstanceID."
3184 case ir_var_system_value
:
3185 if (var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID
&&
3186 var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
&&
3187 var
->data
.location
!= SYSTEM_VALUE_INSTANCE_ID
)
3189 /* Mark special built-in inputs referenced by the vertex stage so
3190 * that they are considered active by the shader queries.
3192 mask
= (1 << (MESA_SHADER_VERTEX
));
3194 case ir_var_shader_in
:
3195 if (programInterface
!= GL_PROGRAM_INPUT
)
3198 case ir_var_shader_out
:
3199 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3206 if (!add_program_resource(shProg
, programInterface
, var
,
3207 build_stageref(shProg
, var
->name
,
3208 var
->data
.mode
) | mask
))
3215 * Builds up a list of program resources that point to existing
3219 build_program_resource_list(struct gl_shader_program
*shProg
)
3221 /* Rebuild resource list. */
3222 if (shProg
->ProgramResourceList
) {
3223 ralloc_free(shProg
->ProgramResourceList
);
3224 shProg
->ProgramResourceList
= NULL
;
3225 shProg
->NumProgramResourceList
= 0;
3228 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3230 /* Determine first input and final output stage. These are used to
3231 * detect which variables should be enumerated in the resource list
3232 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3234 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3235 if (!shProg
->_LinkedShaders
[i
])
3237 if (input_stage
== MESA_SHADER_STAGES
)
3242 /* Empty shader, no resources. */
3243 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3246 /* Add inputs and outputs to the resource list. */
3247 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[input_stage
],
3251 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[output_stage
],
3255 /* Add transform feedback varyings. */
3256 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3257 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3258 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3259 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
3265 /* Add uniforms from uniform storage. */
3266 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3267 /* Do not add uniforms internally used by Mesa. */
3268 if (shProg
->UniformStorage
[i
].hidden
)
3272 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
3275 /* Add stagereferences for uniforms in a uniform block. */
3276 int block_index
= shProg
->UniformStorage
[i
].block_index
;
3277 if (block_index
!= -1) {
3278 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
3279 if (shProg
->UniformBlockStageIndex
[j
][block_index
] != -1)
3280 stageref
|= (1 << j
);
3284 if (!add_program_resource(shProg
, GL_UNIFORM
,
3285 &shProg
->UniformStorage
[i
], stageref
))
3289 /* Add program uniform blocks. */
3290 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
3291 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
3292 &shProg
->UniformBlocks
[i
], 0))
3296 /* Add atomic counter buffers. */
3297 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
3298 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
3299 &shProg
->AtomicBuffers
[i
], 0))
3303 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3305 if (!shProg
->UniformStorage
[i
].hidden
)
3308 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
3309 if (!shProg
->UniformStorage
[i
].subroutine
[j
].active
)
3312 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
3313 /* add shader subroutines */
3314 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
3319 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3320 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3326 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
3327 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
3328 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
3333 /* TODO - following extensions will require more resource types:
3335 * GL_ARB_shader_storage_buffer_object
3340 * This check is done to make sure we allow only constant expression
3341 * indexing and "constant-index-expression" (indexing with an expression
3342 * that includes loop induction variable).
3345 validate_sampler_array_indexing(struct gl_context
*ctx
,
3346 struct gl_shader_program
*prog
)
3348 dynamic_sampler_array_indexing_visitor v
;
3349 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3350 if (prog
->_LinkedShaders
[i
] == NULL
)
3353 bool no_dynamic_indexing
=
3354 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
3356 /* Search for array derefs in shader. */
3357 v
.run(prog
->_LinkedShaders
[i
]->ir
);
3358 if (v
.uses_dynamic_sampler_array_indexing()) {
3359 const char *msg
= "sampler arrays indexed with non-constant "
3360 "expressions is forbidden in GLSL %s %u";
3361 /* Backend has indicated that it has no dynamic indexing support. */
3362 if (no_dynamic_indexing
) {
3363 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3366 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3374 link_assign_subroutine_types(struct gl_shader_program
*prog
)
3376 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3377 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3382 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3383 ir_function
*fn
= node
->as_function();
3387 if (fn
->is_subroutine
)
3388 sh
->NumSubroutineUniformTypes
++;
3390 if (!fn
->num_subroutine_types
)
3393 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
3394 struct gl_subroutine_function
,
3395 sh
->NumSubroutineFunctions
+ 1);
3396 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
3397 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
3398 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
3399 ralloc_array(sh
, const struct glsl_type
*,
3400 fn
->num_subroutine_types
);
3401 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
3402 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
3403 sh
->NumSubroutineFunctions
++;
3409 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3411 tfeedback_decl
*tfeedback_decls
= NULL
;
3412 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
3414 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
3416 prog
->LinkStatus
= true; /* All error paths will set this to false */
3417 prog
->Validated
= false;
3418 prog
->_Used
= false;
3420 prog
->ARB_fragment_coord_conventions_enable
= false;
3422 /* Separate the shaders into groups based on their type.
3424 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
3425 unsigned num_shaders
[MESA_SHADER_STAGES
];
3427 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3428 shader_list
[i
] = (struct gl_shader
**)
3429 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
3433 unsigned min_version
= UINT_MAX
;
3434 unsigned max_version
= 0;
3435 const bool is_es_prog
=
3436 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
3437 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
3438 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
3439 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
3441 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
3442 linker_error(prog
, "all shaders must use same shading "
3443 "language version\n");
3447 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
3448 prog
->ARB_fragment_coord_conventions_enable
= true;
3451 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
3452 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
3453 num_shaders
[shader_type
]++;
3456 /* In desktop GLSL, different shader versions may be linked together. In
3457 * GLSL ES, all shader versions must be the same.
3459 if (is_es_prog
&& min_version
!= max_version
) {
3460 linker_error(prog
, "all shaders must use same shading "
3461 "language version\n");
3465 prog
->Version
= max_version
;
3466 prog
->IsES
= is_es_prog
;
3468 /* From OpenGL 4.5 Core specification (7.3 Program Objects):
3469 * "Linking can fail for a variety of reasons as specified in the OpenGL
3470 * Shading Language Specification, as well as any of the following
3473 * * No shader objects are attached to program.
3477 * Same rule applies for OpenGL ES >= 3.1.
3480 if (prog
->NumShaders
== 0 &&
3481 ((ctx
->API
== API_OPENGL_CORE
&& ctx
->Version
>= 45) ||
3482 (ctx
->API
== API_OPENGLES2
&& ctx
->Version
>= 31))) {
3483 linker_error(prog
, "No shader objects are attached to program.\n");
3487 /* Some shaders have to be linked with some other shaders present.
3489 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
3490 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3491 !prog
->SeparateShader
) {
3492 linker_error(prog
, "Geometry shader must be linked with "
3496 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
3497 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3498 !prog
->SeparateShader
) {
3499 linker_error(prog
, "Tessellation evaluation shader must be linked with "
3503 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3504 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
3505 !prog
->SeparateShader
) {
3506 linker_error(prog
, "Tessellation control shader must be linked with "
3511 /* The spec is self-contradictory here. It allows linking without a tess
3512 * eval shader, but that can only be used with transform feedback and
3513 * rasterization disabled. However, transform feedback isn't allowed
3514 * with GL_PATCHES, so it can't be used.
3516 * More investigation showed that the idea of transform feedback after
3517 * a tess control shader was dropped, because some hw vendors couldn't
3518 * support tessellation without a tess eval shader, but the linker section
3519 * wasn't updated to reflect that.
3521 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
3524 * Do what's reasonable and always require a tess eval shader if a tess
3525 * control shader is present.
3527 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
3528 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0 &&
3529 !prog
->SeparateShader
) {
3530 linker_error(prog
, "Tessellation control shader must be linked with "
3531 "tessellation evaluation shader\n");
3535 /* Compute shaders have additional restrictions. */
3536 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
3537 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
3538 linker_error(prog
, "Compute shaders may not be linked with any other "
3539 "type of shader\n");
3542 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3543 if (prog
->_LinkedShaders
[i
] != NULL
)
3544 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
3546 prog
->_LinkedShaders
[i
] = NULL
;
3549 /* Link all shaders for a particular stage and validate the result.
3551 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
3552 if (num_shaders
[stage
] > 0) {
3553 gl_shader
*const sh
=
3554 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
3555 num_shaders
[stage
]);
3557 if (!prog
->LinkStatus
) {
3559 ctx
->Driver
.DeleteShader(ctx
, sh
);
3564 case MESA_SHADER_VERTEX
:
3565 validate_vertex_shader_executable(prog
, sh
);
3567 case MESA_SHADER_TESS_CTRL
:
3568 /* nothing to be done */
3570 case MESA_SHADER_TESS_EVAL
:
3571 validate_tess_eval_shader_executable(prog
, sh
);
3573 case MESA_SHADER_GEOMETRY
:
3574 validate_geometry_shader_executable(prog
, sh
);
3576 case MESA_SHADER_FRAGMENT
:
3577 validate_fragment_shader_executable(prog
, sh
);
3580 if (!prog
->LinkStatus
) {
3582 ctx
->Driver
.DeleteShader(ctx
, sh
);
3586 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
3590 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
3591 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
3592 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
3593 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
3594 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
3595 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
3597 prog
->LastClipDistanceArraySize
= 0; /* Not used */
3599 /* Here begins the inter-stage linking phase. Some initial validation is
3600 * performed, then locations are assigned for uniforms, attributes, and
3603 cross_validate_uniforms(prog
);
3604 if (!prog
->LinkStatus
)
3609 for (prev
= 0; prev
<= MESA_SHADER_FRAGMENT
; prev
++) {
3610 if (prog
->_LinkedShaders
[prev
] != NULL
)
3614 check_explicit_uniform_locations(ctx
, prog
);
3615 link_assign_subroutine_types(prog
);
3617 if (!prog
->LinkStatus
)
3620 resize_tes_inputs(ctx
, prog
);
3622 /* Validate the inputs of each stage with the output of the preceding
3625 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3626 if (prog
->_LinkedShaders
[i
] == NULL
)
3629 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
3630 prog
->_LinkedShaders
[i
]);
3631 if (!prog
->LinkStatus
)
3634 cross_validate_outputs_to_inputs(prog
,
3635 prog
->_LinkedShaders
[prev
],
3636 prog
->_LinkedShaders
[i
]);
3637 if (!prog
->LinkStatus
)
3643 /* Cross-validate uniform blocks between shader stages */
3644 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
3645 MESA_SHADER_STAGES
);
3646 if (!prog
->LinkStatus
)
3649 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3650 if (prog
->_LinkedShaders
[i
] != NULL
)
3651 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
3654 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
3655 * it before optimization because we want most of the checks to get
3656 * dropped thanks to constant propagation.
3658 * This rule also applies to GLSL ES 3.00.
3660 if (max_version
>= (is_es_prog
? 300 : 130)) {
3661 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3663 lower_discard_flow(sh
->ir
);
3667 if (!interstage_cross_validate_uniform_blocks(prog
))
3670 /* Do common optimization before assigning storage for attributes,
3671 * uniforms, and varyings. Later optimization could possibly make
3672 * some of that unused.
3674 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3675 if (prog
->_LinkedShaders
[i
] == NULL
)
3678 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
3679 if (!prog
->LinkStatus
)
3682 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerClipDistance
) {
3683 lower_clip_distance(prog
->_LinkedShaders
[i
]);
3686 if (ctx
->Const
.LowerTessLevel
) {
3687 lower_tess_level(prog
->_LinkedShaders
[i
]);
3690 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
3691 &ctx
->Const
.ShaderCompilerOptions
[i
],
3692 ctx
->Const
.NativeIntegers
))
3695 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
3698 /* Validation for special cases where we allow sampler array indexing
3699 * with loop induction variable. This check emits a warning or error
3700 * depending if backend can handle dynamic indexing.
3702 if ((!prog
->IsES
&& prog
->Version
< 130) ||
3703 (prog
->IsES
&& prog
->Version
< 300)) {
3704 if (!validate_sampler_array_indexing(ctx
, prog
))
3708 /* Check and validate stream emissions in geometry shaders */
3709 validate_geometry_shader_emissions(ctx
, prog
);
3711 /* Mark all generic shader inputs and outputs as unpaired. */
3712 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
3713 if (prog
->_LinkedShaders
[i
] != NULL
) {
3714 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
3718 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
3719 MESA_SHADER_VERTEX
)) {
3723 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
3724 MESA_SHADER_FRAGMENT
)) {
3728 unsigned first
, last
;
3730 first
= MESA_SHADER_STAGES
;
3733 /* Determine first and last stage. */
3734 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3735 if (!prog
->_LinkedShaders
[i
])
3737 if (first
== MESA_SHADER_STAGES
)
3742 if (num_tfeedback_decls
!= 0) {
3743 /* From GL_EXT_transform_feedback:
3744 * A program will fail to link if:
3746 * * the <count> specified by TransformFeedbackVaryingsEXT is
3747 * non-zero, but the program object has no vertex or geometry
3750 if (first
== MESA_SHADER_FRAGMENT
) {
3751 linker_error(prog
, "Transform feedback varyings specified, but "
3752 "no vertex or geometry shader is present.\n");
3756 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
3757 prog
->TransformFeedback
.NumVarying
);
3758 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
3759 prog
->TransformFeedback
.VaryingNames
,
3764 /* Linking the stages in the opposite order (from fragment to vertex)
3765 * ensures that inter-shader outputs written to in an earlier stage are
3766 * eliminated if they are (transitively) not used in a later stage.
3770 if (first
< MESA_SHADER_FRAGMENT
) {
3771 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
3773 if (first
== MESA_SHADER_GEOMETRY
) {
3774 /* There was no vertex shader, but we still have to assign varying
3775 * locations for use by geometry shader inputs in SSO.
3777 * If the shader is not separable (i.e., prog->SeparateShader is
3778 * false), linking will have already failed when first is
3779 * MESA_SHADER_GEOMETRY.
3781 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3782 NULL
, prog
->_LinkedShaders
[first
],
3783 num_tfeedback_decls
, tfeedback_decls
))
3787 if (last
!= MESA_SHADER_FRAGMENT
&&
3788 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
3789 /* There was no fragment shader, but we still have to assign varying
3790 * locations for use by transform feedback.
3792 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3794 num_tfeedback_decls
, tfeedback_decls
))
3798 do_dead_builtin_varyings(ctx
, sh
, NULL
,
3799 num_tfeedback_decls
, tfeedback_decls
);
3801 if (!prog
->SeparateShader
)
3802 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
3804 /* Eliminate code that is now dead due to unused outputs being demoted.
3806 while (do_dead_code(sh
->ir
, false))
3809 else if (first
== MESA_SHADER_FRAGMENT
) {
3810 /* If the program only contains a fragment shader...
3812 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
3814 do_dead_builtin_varyings(ctx
, NULL
, sh
,
3815 num_tfeedback_decls
, tfeedback_decls
);
3817 if (prog
->SeparateShader
) {
3818 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
3819 NULL
/* producer */,
3821 0 /* num_tfeedback_decls */,
3822 NULL
/* tfeedback_decls */))
3825 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
3827 while (do_dead_code(sh
->ir
, false))
3832 for (int i
= next
- 1; i
>= 0; i
--) {
3833 if (prog
->_LinkedShaders
[i
] == NULL
)
3836 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
3837 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
3839 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
3840 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3844 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
3845 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
3848 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
3849 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
3851 /* Eliminate code that is now dead due to unused outputs being demoted.
3853 while (do_dead_code(sh_i
->ir
, false))
3855 while (do_dead_code(sh_next
->ir
, false))
3858 /* This must be done after all dead varyings are eliminated. */
3859 if (!check_against_output_limit(ctx
, prog
, sh_i
))
3861 if (!check_against_input_limit(ctx
, prog
, sh_next
))
3867 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
3870 update_array_sizes(prog
);
3871 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
);
3872 link_assign_atomic_counter_resources(ctx
, prog
);
3873 store_fragdepth_layout(prog
);
3875 link_calculate_subroutine_compat(prog
);
3876 check_resources(ctx
, prog
);
3877 check_subroutine_resources(prog
);
3878 check_image_resources(ctx
, prog
);
3879 link_check_atomic_counter_resources(ctx
, prog
);
3881 if (!prog
->LinkStatus
)
3884 /* OpenGL ES requires that a vertex shader and a fragment shader both be
3885 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
3886 * anything about shader linking when one of the shaders (vertex or
3887 * fragment shader) is absent. So, the extension shouldn't change the
3888 * behavior specified in GLSL specification.
3890 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
) {
3891 /* With ES < 3.1 one needs to have always vertex + fragment shader. */
3892 if (ctx
->Version
< 31) {
3893 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
3894 linker_error(prog
, "program lacks a vertex shader\n");
3895 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3896 linker_error(prog
, "program lacks a fragment shader\n");
3899 /* From OpenGL ES 3.1 specification (7.3 Program Objects):
3900 * "Linking can fail for a variety of reasons as specified in the
3901 * OpenGL ES Shading Language Specification, as well as any of the
3902 * following reasons:
3906 * * program contains objects to form either a vertex shader or
3907 * fragment shader, and program is not separable, and does not
3908 * contain objects to form both a vertex shader and fragment
3911 if (!!prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] ^
3912 !!prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]) {
3913 linker_error(prog
, "Program needs to contain both vertex and "
3914 "fragment shaders.\n");
3919 /* FINISHME: Assign fragment shader output locations. */
3922 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3923 free(shader_list
[i
]);
3924 if (prog
->_LinkedShaders
[i
] == NULL
)
3927 /* Do a final validation step to make sure that the IR wasn't
3928 * invalidated by any modifications performed after intrastage linking.
3930 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
3932 /* Retain any live IR, but trash the rest. */
3933 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
3935 /* The symbol table in the linked shaders may contain references to
3936 * variables that were removed (e.g., unused uniforms). Since it may
3937 * contain junk, there is no possible valid use. Delete it and set the
3940 delete prog
->_LinkedShaders
[i
]->symbols
;
3941 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
3944 ralloc_free(mem_ctx
);