2 * Copyright © 2010 Intel Corporation
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
26 * GLSL linker implementation
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
35 * - Undefined references in each shader are resolve to definitions in
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
64 * \author Ian Romanick <ian.d.romanick@intel.com>
68 #include "util/strndup.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
73 #include "program/prog_instruction.h"
74 #include "program/program.h"
75 #include "util/mesa-sha1.h"
77 #include "string_to_uint_map.h"
79 #include "link_varyings.h"
80 #include "ir_optimization.h"
81 #include "ir_rvalue_visitor.h"
82 #include "ir_uniform.h"
83 #include "builtin_functions.h"
84 #include "shader_cache.h"
86 #include "main/imports.h"
87 #include "main/shaderobj.h"
88 #include "main/enums.h"
89 #include "main/mtypes.h"
94 struct find_variable
{
98 find_variable(const char *name
) : name(name
), found(false) {}
102 * Visitor that determines whether or not a variable is ever written.
104 * Use \ref find_assignments for convenience.
106 class find_assignment_visitor
: public ir_hierarchical_visitor
{
108 find_assignment_visitor(unsigned num_vars
,
109 find_variable
* const *vars
)
110 : num_variables(num_vars
), num_found(0), variables(vars
)
114 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
116 ir_variable
*const var
= ir
->lhs
->variable_referenced();
118 return check_variable_name(var
->name
);
121 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
123 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
124 actual_node
, &ir
->actual_parameters
) {
125 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
126 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
128 if (sig_param
->data
.mode
== ir_var_function_out
||
129 sig_param
->data
.mode
== ir_var_function_inout
) {
130 ir_variable
*var
= param_rval
->variable_referenced();
131 if (var
&& check_variable_name(var
->name
) == visit_stop
)
136 if (ir
->return_deref
!= NULL
) {
137 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
139 if (check_variable_name(var
->name
) == visit_stop
)
143 return visit_continue_with_parent
;
147 ir_visitor_status
check_variable_name(const char *name
)
149 for (unsigned i
= 0; i
< num_variables
; ++i
) {
150 if (strcmp(variables
[i
]->name
, name
) == 0) {
151 if (!variables
[i
]->found
) {
152 variables
[i
]->found
= true;
154 assert(num_found
< num_variables
);
155 if (++num_found
== num_variables
)
162 return visit_continue_with_parent
;
166 unsigned num_variables
; /**< Number of variables to find */
167 unsigned num_found
; /**< Number of variables already found */
168 find_variable
* const *variables
; /**< Variables to find */
172 * Determine whether or not any of NULL-terminated list of variables is ever
176 find_assignments(exec_list
*ir
, find_variable
* const *vars
)
178 unsigned num_variables
= 0;
180 for (find_variable
* const *v
= vars
; *v
; ++v
)
183 find_assignment_visitor
visitor(num_variables
, vars
);
188 * Determine whether or not the given variable is ever written to.
191 find_assignments(exec_list
*ir
, find_variable
*var
)
193 find_assignment_visitor
visitor(1, &var
);
198 * Visitor that determines whether or not a variable is ever read.
200 class find_deref_visitor
: public ir_hierarchical_visitor
{
202 find_deref_visitor(const char *name
)
203 : name(name
), found(false)
208 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
210 if (strcmp(this->name
, ir
->var
->name
) == 0) {
215 return visit_continue
;
218 bool variable_found() const
224 const char *name
; /**< Find writes to a variable with this name. */
225 bool found
; /**< Was a write to the variable found? */
230 * A visitor helper that provides methods for updating the types of
231 * ir_dereferences. Classes that update variable types (say, updating
232 * array sizes) will want to use this so that dereference types stay in sync.
234 class deref_type_updater
: public ir_hierarchical_visitor
{
236 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
238 ir
->type
= ir
->var
->type
;
239 return visit_continue
;
242 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
244 const glsl_type
*const vt
= ir
->array
->type
;
246 ir
->type
= vt
->fields
.array
;
247 return visit_continue
;
250 virtual ir_visitor_status
visit_leave(ir_dereference_record
*ir
)
252 ir
->type
= ir
->record
->type
->fields
.structure
[ir
->field_idx
].type
;
253 return visit_continue
;
258 class array_resize_visitor
: public deref_type_updater
{
260 unsigned num_vertices
;
261 gl_shader_program
*prog
;
262 gl_shader_stage stage
;
264 array_resize_visitor(unsigned num_vertices
,
265 gl_shader_program
*prog
,
266 gl_shader_stage stage
)
268 this->num_vertices
= num_vertices
;
273 virtual ~array_resize_visitor()
278 virtual ir_visitor_status
visit(ir_variable
*var
)
280 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
282 return visit_continue
;
284 unsigned size
= var
->type
->length
;
286 if (stage
== MESA_SHADER_GEOMETRY
) {
287 /* Generate a link error if the shader has declared this array with
290 if (!var
->data
.implicit_sized_array
&&
291 size
&& size
!= this->num_vertices
) {
292 linker_error(this->prog
, "size of array %s declared as %u, "
293 "but number of input vertices is %u\n",
294 var
->name
, size
, this->num_vertices
);
295 return visit_continue
;
298 /* Generate a link error if the shader attempts to access an input
299 * array using an index too large for its actual size assigned at
302 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
303 linker_error(this->prog
, "%s shader accesses element %i of "
304 "%s, but only %i input vertices\n",
305 _mesa_shader_stage_to_string(this->stage
),
306 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
307 return visit_continue
;
311 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
313 var
->data
.max_array_access
= this->num_vertices
- 1;
315 return visit_continue
;
320 * Visitor that determines the highest stream id to which a (geometry) shader
321 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
323 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
325 find_emit_vertex_visitor(int max_allowed
)
326 : max_stream_allowed(max_allowed
),
327 invalid_stream_id(0),
328 invalid_stream_id_from_emit_vertex(false),
329 end_primitive_found(false),
330 uses_non_zero_stream(false)
335 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
337 int stream_id
= ir
->stream_id();
340 invalid_stream_id
= stream_id
;
341 invalid_stream_id_from_emit_vertex
= true;
345 if (stream_id
> max_stream_allowed
) {
346 invalid_stream_id
= stream_id
;
347 invalid_stream_id_from_emit_vertex
= true;
352 uses_non_zero_stream
= true;
354 return visit_continue
;
357 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
359 end_primitive_found
= true;
361 int stream_id
= ir
->stream_id();
364 invalid_stream_id
= stream_id
;
365 invalid_stream_id_from_emit_vertex
= false;
369 if (stream_id
> max_stream_allowed
) {
370 invalid_stream_id
= stream_id
;
371 invalid_stream_id_from_emit_vertex
= false;
376 uses_non_zero_stream
= true;
378 return visit_continue
;
383 return invalid_stream_id
!= 0;
386 const char *error_func()
388 return invalid_stream_id_from_emit_vertex
?
389 "EmitStreamVertex" : "EndStreamPrimitive";
394 return invalid_stream_id
;
399 return uses_non_zero_stream
;
402 bool uses_end_primitive()
404 return end_primitive_found
;
408 int max_stream_allowed
;
409 int invalid_stream_id
;
410 bool invalid_stream_id_from_emit_vertex
;
411 bool end_primitive_found
;
412 bool uses_non_zero_stream
;
415 /* Class that finds array derefs and check if indexes are dynamic. */
416 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
419 dynamic_sampler_array_indexing_visitor() :
420 dynamic_sampler_array_indexing(false)
424 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
426 if (!ir
->variable_referenced())
427 return visit_continue
;
429 if (!ir
->variable_referenced()->type
->contains_sampler())
430 return visit_continue
;
432 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
433 dynamic_sampler_array_indexing
= true;
436 return visit_continue
;
439 bool uses_dynamic_sampler_array_indexing()
441 return dynamic_sampler_array_indexing
;
445 bool dynamic_sampler_array_indexing
;
448 } /* anonymous namespace */
451 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
455 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
457 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
460 prog
->data
->LinkStatus
= LINKING_FAILURE
;
465 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
469 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
471 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
478 * Given a string identifying a program resource, break it into a base name
479 * and an optional array index in square brackets.
481 * If an array index is present, \c out_base_name_end is set to point to the
482 * "[" that precedes the array index, and the array index itself is returned
485 * If no array index is present (or if the array index is negative or
486 * mal-formed), \c out_base_name_end, is set to point to the null terminator
487 * at the end of the input string, and -1 is returned.
489 * Only the final array index is parsed; if the string contains other array
490 * indices (or structure field accesses), they are left in the base name.
492 * No attempt is made to check that the base name is properly formed;
493 * typically the caller will look up the base name in a hash table, so
494 * ill-formed base names simply turn into hash table lookup failures.
497 parse_program_resource_name(const GLchar
*name
,
498 const GLchar
**out_base_name_end
)
500 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
502 * "When an integer array element or block instance number is part of
503 * the name string, it will be specified in decimal form without a "+"
504 * or "-" sign or any extra leading zeroes. Additionally, the name
505 * string will not include white space anywhere in the string."
508 const size_t len
= strlen(name
);
509 *out_base_name_end
= name
+ len
;
511 if (len
== 0 || name
[len
-1] != ']')
514 /* Walk backwards over the string looking for a non-digit character. This
515 * had better be the opening bracket for an array index.
517 * Initially, i specifies the location of the ']'. Since the string may
518 * contain only the ']' charcater, walk backwards very carefully.
521 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
524 if ((i
== 0) || name
[i
-1] != '[')
527 long array_index
= strtol(&name
[i
], NULL
, 10);
531 /* Check for leading zero */
532 if (name
[i
] == '0' && name
[i
+1] != ']')
535 *out_base_name_end
= name
+ (i
- 1);
541 link_invalidate_variable_locations(exec_list
*ir
)
543 foreach_in_list(ir_instruction
, node
, ir
) {
544 ir_variable
*const var
= node
->as_variable();
549 /* Only assign locations for variables that lack an explicit location.
550 * Explicit locations are set for all built-in variables, generic vertex
551 * shader inputs (via layout(location=...)), and generic fragment shader
552 * outputs (also via layout(location=...)).
554 if (!var
->data
.explicit_location
) {
555 var
->data
.location
= -1;
556 var
->data
.location_frac
= 0;
559 /* ir_variable::is_unmatched_generic_inout is used by the linker while
560 * connecting outputs from one stage to inputs of the next stage.
562 if (var
->data
.explicit_location
&&
563 var
->data
.location
< VARYING_SLOT_VAR0
) {
564 var
->data
.is_unmatched_generic_inout
= 0;
566 var
->data
.is_unmatched_generic_inout
= 1;
573 * Set clip_distance_array_size based and cull_distance_array_size on the given
576 * Also check for errors based on incorrect usage of gl_ClipVertex and
577 * gl_ClipDistance and gl_CullDistance.
578 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
579 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
581 * Return false if an error was reported.
584 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
585 struct gl_linked_shader
*shader
,
586 struct gl_context
*ctx
,
587 GLuint
*clip_distance_array_size
,
588 GLuint
*cull_distance_array_size
)
590 *clip_distance_array_size
= 0;
591 *cull_distance_array_size
= 0;
593 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
594 /* From section 7.1 (Vertex Shader Special Variables) of the
597 * "It is an error for a shader to statically write both
598 * gl_ClipVertex and gl_ClipDistance."
600 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
601 * gl_ClipVertex nor gl_ClipDistance. However with
602 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
604 find_variable
gl_ClipDistance("gl_ClipDistance");
605 find_variable
gl_CullDistance("gl_CullDistance");
606 find_variable
gl_ClipVertex("gl_ClipVertex");
607 find_variable
* const variables
[] = {
610 !prog
->IsES
? &gl_ClipVertex
: NULL
,
613 find_assignments(shader
->ir
, variables
);
615 /* From the ARB_cull_distance spec:
617 * It is a compile-time or link-time error for the set of shaders forming
618 * a program to statically read or write both gl_ClipVertex and either
619 * gl_ClipDistance or gl_CullDistance.
621 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
625 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
626 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
627 "and `gl_ClipDistance'\n",
628 _mesa_shader_stage_to_string(shader
->Stage
));
631 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
632 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
633 "and `gl_CullDistance'\n",
634 _mesa_shader_stage_to_string(shader
->Stage
));
639 if (gl_ClipDistance
.found
) {
640 ir_variable
*clip_distance_var
=
641 shader
->symbols
->get_variable("gl_ClipDistance");
642 assert(clip_distance_var
);
643 *clip_distance_array_size
= clip_distance_var
->type
->length
;
645 if (gl_CullDistance
.found
) {
646 ir_variable
*cull_distance_var
=
647 shader
->symbols
->get_variable("gl_CullDistance");
648 assert(cull_distance_var
);
649 *cull_distance_array_size
= cull_distance_var
->type
->length
;
651 /* From the ARB_cull_distance spec:
653 * It is a compile-time or link-time error for the set of shaders forming
654 * a program to have the sum of the sizes of the gl_ClipDistance and
655 * gl_CullDistance arrays to be larger than
656 * gl_MaxCombinedClipAndCullDistances.
658 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
659 ctx
->Const
.MaxClipPlanes
) {
660 linker_error(prog
, "%s shader: the combined size of "
661 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
663 "gl_MaxCombinedClipAndCullDistances (%u)",
664 _mesa_shader_stage_to_string(shader
->Stage
),
665 ctx
->Const
.MaxClipPlanes
);
672 * Verify that a vertex shader executable meets all semantic requirements.
674 * Also sets info.clip_distance_array_size and
675 * info.cull_distance_array_size as a side effect.
677 * \param shader Vertex shader executable to be verified
680 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
681 struct gl_linked_shader
*shader
,
682 struct gl_context
*ctx
)
687 /* From the GLSL 1.10 spec, page 48:
689 * "The variable gl_Position is available only in the vertex
690 * language and is intended for writing the homogeneous vertex
691 * position. All executions of a well-formed vertex shader
692 * executable must write a value into this variable. [...] The
693 * variable gl_Position is available only in the vertex
694 * language and is intended for writing the homogeneous vertex
695 * position. All executions of a well-formed vertex shader
696 * executable must write a value into this variable."
698 * while in GLSL 1.40 this text is changed to:
700 * "The variable gl_Position is available only in the vertex
701 * language and is intended for writing the homogeneous vertex
702 * position. It can be written at any time during shader
703 * execution. It may also be read back by a vertex shader
704 * after being written. This value will be used by primitive
705 * assembly, clipping, culling, and other fixed functionality
706 * operations, if present, that operate on primitives after
707 * vertex processing has occurred. Its value is undefined if
708 * the vertex shader executable does not write gl_Position."
710 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
711 * gl_Position is not an error.
713 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
714 find_variable
gl_Position("gl_Position");
715 find_assignments(shader
->ir
, &gl_Position
);
716 if (!gl_Position
.found
) {
719 "vertex shader does not write to `gl_Position'. "
720 "Its value is undefined. \n");
723 "vertex shader does not write to `gl_Position'. \n");
729 analyze_clip_cull_usage(prog
, shader
, ctx
,
730 &shader
->Program
->info
.clip_distance_array_size
,
731 &shader
->Program
->info
.cull_distance_array_size
);
735 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
736 struct gl_linked_shader
*shader
,
737 struct gl_context
*ctx
)
742 analyze_clip_cull_usage(prog
, shader
, ctx
,
743 &shader
->Program
->info
.clip_distance_array_size
,
744 &shader
->Program
->info
.cull_distance_array_size
);
749 * Verify that a fragment shader executable meets all semantic requirements
751 * \param shader Fragment shader executable to be verified
754 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
755 struct gl_linked_shader
*shader
)
760 find_variable
gl_FragColor("gl_FragColor");
761 find_variable
gl_FragData("gl_FragData");
762 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
763 find_assignments(shader
->ir
, variables
);
765 if (gl_FragColor
.found
&& gl_FragData
.found
) {
766 linker_error(prog
, "fragment shader writes to both "
767 "`gl_FragColor' and `gl_FragData'\n");
772 * Verify that a geometry shader executable meets all semantic requirements
774 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
775 * info.cull_distance_array_size as a side effect.
777 * \param shader Geometry shader executable to be verified
780 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
781 struct gl_linked_shader
*shader
,
782 struct gl_context
*ctx
)
787 unsigned num_vertices
=
788 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
789 prog
->Geom
.VerticesIn
= num_vertices
;
791 analyze_clip_cull_usage(prog
, shader
, ctx
,
792 &shader
->Program
->info
.clip_distance_array_size
,
793 &shader
->Program
->info
.cull_distance_array_size
);
797 * Check if geometry shaders emit to non-zero streams and do corresponding
801 validate_geometry_shader_emissions(struct gl_context
*ctx
,
802 struct gl_shader_program
*prog
)
804 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
807 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
808 emit_vertex
.run(sh
->ir
);
809 if (emit_vertex
.error()) {
810 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
811 "stream parameter are in the range [0, %d].\n",
812 emit_vertex
.error_func(),
813 emit_vertex
.error_stream(),
814 ctx
->Const
.MaxVertexStreams
- 1);
816 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
817 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
819 /* From the ARB_gpu_shader5 spec:
821 * "Multiple vertex streams are supported only if the output primitive
822 * type is declared to be "points". A program will fail to link if it
823 * contains a geometry shader calling EmitStreamVertex() or
824 * EndStreamPrimitive() if its output primitive type is not "points".
826 * However, in the same spec:
828 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
829 * with <stream> set to zero."
833 * "The function EndPrimitive() is equivalent to calling
834 * EndStreamPrimitive() with <stream> set to zero."
836 * Since we can call EmitVertex() and EndPrimitive() when we output
837 * primitives other than points, calling EmitStreamVertex(0) or
838 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
839 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
840 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
843 if (prog
->Geom
.UsesStreams
&&
844 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
845 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
846 "with n>0 requires point output\n");
852 validate_intrastage_arrays(struct gl_shader_program
*prog
,
853 ir_variable
*const var
,
854 ir_variable
*const existing
)
856 /* Consider the types to be "the same" if both types are arrays
857 * of the same type and one of the arrays is implicitly sized.
858 * In addition, set the type of the linked variable to the
859 * explicitly sized array.
861 if (var
->type
->is_array() && existing
->type
->is_array()) {
862 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
863 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
864 if (var
->type
->length
!= 0) {
865 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
866 linker_error(prog
, "%s `%s' declared as type "
867 "`%s' but outermost dimension has an index"
870 var
->name
, var
->type
->name
,
871 existing
->data
.max_array_access
);
873 existing
->type
= var
->type
;
875 } else if (existing
->type
->length
!= 0) {
876 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
877 !existing
->data
.from_ssbo_unsized_array
) {
878 linker_error(prog
, "%s `%s' declared as type "
879 "`%s' but outermost dimension has an index"
882 var
->name
, existing
->type
->name
,
883 var
->data
.max_array_access
);
894 * Perform validation of global variables used across multiple shaders
897 cross_validate_globals(struct gl_shader_program
*prog
,
898 struct exec_list
*ir
, glsl_symbol_table
*variables
,
901 foreach_in_list(ir_instruction
, node
, ir
) {
902 ir_variable
*const var
= node
->as_variable();
907 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
910 /* don't cross validate subroutine uniforms */
911 if (var
->type
->contains_subroutine())
914 /* Don't cross validate interface instances. These are only relevant
915 * inside a shader. The cross validation is done at the Interface Block
918 if (var
->is_interface_instance())
921 /* Don't cross validate temporaries that are at global scope. These
922 * will eventually get pulled into the shaders 'main'.
924 if (var
->data
.mode
== ir_var_temporary
)
927 /* If a global with this name has already been seen, verify that the
928 * new instance has the same type. In addition, if the globals have
929 * initializers, the values of the initializers must be the same.
931 ir_variable
*const existing
= variables
->get_variable(var
->name
);
932 if (existing
!= NULL
) {
933 /* Check if types match. */
934 if (var
->type
!= existing
->type
) {
935 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
936 /* If it is an unsized array in a Shader Storage Block,
937 * two different shaders can access to different elements.
938 * Because of that, they might be converted to different
939 * sized arrays, then check that they are compatible but
940 * ignore the array size.
942 if (!(var
->data
.mode
== ir_var_shader_storage
&&
943 var
->data
.from_ssbo_unsized_array
&&
944 existing
->data
.mode
== ir_var_shader_storage
&&
945 existing
->data
.from_ssbo_unsized_array
&&
946 var
->type
->gl_type
== existing
->type
->gl_type
)) {
947 linker_error(prog
, "%s `%s' declared as type "
948 "`%s' and type `%s'\n",
950 var
->name
, var
->type
->name
,
951 existing
->type
->name
);
957 if (var
->data
.explicit_location
) {
958 if (existing
->data
.explicit_location
959 && (var
->data
.location
!= existing
->data
.location
)) {
960 linker_error(prog
, "explicit locations for %s "
961 "`%s' have differing values\n",
962 mode_string(var
), var
->name
);
966 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
967 linker_error(prog
, "explicit components for %s `%s' have "
968 "differing values\n", mode_string(var
), var
->name
);
972 existing
->data
.location
= var
->data
.location
;
973 existing
->data
.explicit_location
= true;
975 /* Check if uniform with implicit location was marked explicit
976 * by earlier shader stage. If so, mark it explicit in this stage
977 * too to make sure later processing does not treat it as
980 if (existing
->data
.explicit_location
) {
981 var
->data
.location
= existing
->data
.location
;
982 var
->data
.explicit_location
= true;
986 /* From the GLSL 4.20 specification:
987 * "A link error will result if two compilation units in a program
988 * specify different integer-constant bindings for the same
989 * opaque-uniform name. However, it is not an error to specify a
990 * binding on some but not all declarations for the same name"
992 if (var
->data
.explicit_binding
) {
993 if (existing
->data
.explicit_binding
&&
994 var
->data
.binding
!= existing
->data
.binding
) {
995 linker_error(prog
, "explicit bindings for %s "
996 "`%s' have differing values\n",
997 mode_string(var
), var
->name
);
1001 existing
->data
.binding
= var
->data
.binding
;
1002 existing
->data
.explicit_binding
= true;
1005 if (var
->type
->contains_atomic() &&
1006 var
->data
.offset
!= existing
->data
.offset
) {
1007 linker_error(prog
, "offset specifications for %s "
1008 "`%s' have differing values\n",
1009 mode_string(var
), var
->name
);
1013 /* Validate layout qualifiers for gl_FragDepth.
1015 * From the AMD/ARB_conservative_depth specs:
1017 * "If gl_FragDepth is redeclared in any fragment shader in a
1018 * program, it must be redeclared in all fragment shaders in
1019 * that program that have static assignments to
1020 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1021 * fragment shaders in a single program must have the same set
1024 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1025 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1026 bool layout_differs
=
1027 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1029 if (layout_declared
&& layout_differs
) {
1031 "All redeclarations of gl_FragDepth in all "
1032 "fragment shaders in a single program must have "
1033 "the same set of qualifiers.\n");
1036 if (var
->data
.used
&& layout_differs
) {
1038 "If gl_FragDepth is redeclared with a layout "
1039 "qualifier in any fragment shader, it must be "
1040 "redeclared with the same layout qualifier in "
1041 "all fragment shaders that have assignments to "
1046 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1048 * "If a shared global has multiple initializers, the
1049 * initializers must all be constant expressions, and they
1050 * must all have the same value. Otherwise, a link error will
1051 * result. (A shared global having only one initializer does
1052 * not require that initializer to be a constant expression.)"
1054 * Previous to 4.20 the GLSL spec simply said that initializers
1055 * must have the same value. In this case of non-constant
1056 * initializers, this was impossible to determine. As a result,
1057 * no vendor actually implemented that behavior. The 4.20
1058 * behavior matches the implemented behavior of at least one other
1059 * vendor, so we'll implement that for all GLSL versions.
1061 if (var
->constant_initializer
!= NULL
) {
1062 if (existing
->constant_initializer
!= NULL
) {
1063 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1064 linker_error(prog
, "initializers for %s "
1065 "`%s' have differing values\n",
1066 mode_string(var
), var
->name
);
1070 /* If the first-seen instance of a particular uniform did
1071 * not have an initializer but a later instance does,
1072 * replace the former with the later.
1074 variables
->replace_variable(existing
->name
, var
);
1078 if (var
->data
.has_initializer
) {
1079 if (existing
->data
.has_initializer
1080 && (var
->constant_initializer
== NULL
1081 || existing
->constant_initializer
== NULL
)) {
1083 "shared global variable `%s' has multiple "
1084 "non-constant initializers.\n",
1090 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1091 linker_error(prog
, "declarations for %s `%s' have "
1092 "mismatching invariant qualifiers\n",
1093 mode_string(var
), var
->name
);
1096 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1097 linker_error(prog
, "declarations for %s `%s' have "
1098 "mismatching centroid qualifiers\n",
1099 mode_string(var
), var
->name
);
1102 if (existing
->data
.sample
!= var
->data
.sample
) {
1103 linker_error(prog
, "declarations for %s `%s` have "
1104 "mismatching sample qualifiers\n",
1105 mode_string(var
), var
->name
);
1108 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1109 linker_error(prog
, "declarations for %s `%s` have "
1110 "mismatching image format qualifiers\n",
1111 mode_string(var
), var
->name
);
1115 /* Check the precision qualifier matches for uniform variables on
1118 if (prog
->IsES
&& !var
->get_interface_type() &&
1119 existing
->data
.precision
!= var
->data
.precision
) {
1120 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1121 linker_error(prog
, "declarations for %s `%s` have "
1122 "mismatching precision qualifiers\n",
1123 mode_string(var
), var
->name
);
1126 linker_warning(prog
, "declarations for %s `%s` have "
1127 "mismatching precision qualifiers\n",
1128 mode_string(var
), var
->name
);
1132 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1134 * "It is a link-time error if any particular shader interface
1137 * - two different blocks, each having no instance name, and each
1138 * having a member of the same name, or
1140 * - a variable outside a block, and a block with no instance name,
1141 * where the variable has the same name as a member in the block."
1143 const glsl_type
*var_itype
= var
->get_interface_type();
1144 const glsl_type
*existing_itype
= existing
->get_interface_type();
1145 if (var_itype
!= existing_itype
) {
1146 if (!var_itype
|| !existing_itype
) {
1147 linker_error(prog
, "declarations for %s `%s` are inside block "
1148 "`%s` and outside a block",
1149 mode_string(var
), var
->name
,
1150 var_itype
? var_itype
->name
: existing_itype
->name
);
1152 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1153 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1155 mode_string(var
), var
->name
,
1156 existing_itype
->name
,
1162 variables
->add_variable(var
);
1168 * Perform validation of uniforms used across multiple shader stages
1171 cross_validate_uniforms(struct gl_shader_program
*prog
)
1173 glsl_symbol_table variables
;
1174 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1175 if (prog
->_LinkedShaders
[i
] == NULL
)
1178 cross_validate_globals(prog
, prog
->_LinkedShaders
[i
]->ir
, &variables
,
1184 * Accumulates the array of buffer blocks and checks that all definitions of
1185 * blocks agree on their contents.
1188 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1191 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1192 struct gl_uniform_block
*blks
= NULL
;
1193 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1194 &prog
->data
->NumUniformBlocks
;
1196 unsigned max_num_buffer_blocks
= 0;
1197 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1198 if (prog
->_LinkedShaders
[i
]) {
1199 if (validate_ssbo
) {
1200 max_num_buffer_blocks
+=
1201 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1203 max_num_buffer_blocks
+=
1204 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1209 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1210 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1212 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1213 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1214 InterfaceBlockStageIndex
[i
][j
] = -1;
1219 unsigned sh_num_blocks
;
1220 struct gl_uniform_block
**sh_blks
;
1221 if (validate_ssbo
) {
1222 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1223 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1225 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1226 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1229 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1230 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1231 num_blks
, sh_blks
[j
]);
1234 linker_error(prog
, "buffer block `%s' has mismatching "
1235 "definitions\n", sh_blks
[j
]->Name
);
1237 for (unsigned k
= 0; k
<= i
; k
++) {
1238 delete[] InterfaceBlockStageIndex
[k
];
1241 /* Reset the block count. This will help avoid various segfaults
1242 * from api calls that assume the array exists due to the count
1249 InterfaceBlockStageIndex
[i
][index
] = j
;
1253 /* Update per stage block pointers to point to the program list.
1254 * FIXME: We should be able to free the per stage blocks here.
1256 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1257 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1258 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1260 if (stage_index
!= -1) {
1261 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1263 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1264 sh
->Program
->sh
.ShaderStorageBlocks
:
1265 sh
->Program
->sh
.UniformBlocks
;
1267 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1268 sh_blks
[stage_index
] = &blks
[j
];
1273 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1274 delete[] InterfaceBlockStageIndex
[i
];
1278 prog
->data
->ShaderStorageBlocks
= blks
;
1280 prog
->data
->UniformBlocks
= blks
;
1287 * Populates a shaders symbol table with all global declarations
1290 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1292 sh
->symbols
= new(sh
) glsl_symbol_table
;
1294 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1299 * Remap variables referenced in an instruction tree
1301 * This is used when instruction trees are cloned from one shader and placed in
1302 * another. These trees will contain references to \c ir_variable nodes that
1303 * do not exist in the target shader. This function finds these \c ir_variable
1304 * references and replaces the references with matching variables in the target
1307 * If there is no matching variable in the target shader, a clone of the
1308 * \c ir_variable is made and added to the target shader. The new variable is
1309 * added to \b both the instruction stream and the symbol table.
1311 * \param inst IR tree that is to be processed.
1312 * \param symbols Symbol table containing global scope symbols in the
1314 * \param instructions Instruction stream where new variable declarations
1318 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1321 class remap_visitor
: public ir_hierarchical_visitor
{
1323 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1325 this->target
= target
;
1326 this->symbols
= target
->symbols
;
1327 this->instructions
= target
->ir
;
1328 this->temps
= temps
;
1331 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1333 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1334 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1335 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1337 assert(var
!= NULL
);
1339 return visit_continue
;
1342 ir_variable
*const existing
=
1343 this->symbols
->get_variable(ir
->var
->name
);
1344 if (existing
!= NULL
)
1347 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1349 this->symbols
->add_variable(copy
);
1350 this->instructions
->push_head(copy
);
1354 return visit_continue
;
1358 struct gl_linked_shader
*target
;
1359 glsl_symbol_table
*symbols
;
1360 exec_list
*instructions
;
1364 remap_visitor
v(target
, temps
);
1371 * Move non-declarations from one instruction stream to another
1373 * The intended usage pattern of this function is to pass the pointer to the
1374 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1375 * pointer) for \c last and \c false for \c make_copies on the first
1376 * call. Successive calls pass the return value of the previous call for
1377 * \c last and \c true for \c make_copies.
1379 * \param instructions Source instruction stream
1380 * \param last Instruction after which new instructions should be
1381 * inserted in the target instruction stream
1382 * \param make_copies Flag selecting whether instructions in \c instructions
1383 * should be copied (via \c ir_instruction::clone) into the
1384 * target list or moved.
1387 * The new "last" instruction in the target instruction stream. This pointer
1388 * is suitable for use as the \c last parameter of a later call to this
1392 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1393 bool make_copies
, gl_linked_shader
*target
)
1395 hash_table
*temps
= NULL
;
1398 temps
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1399 _mesa_key_pointer_equal
);
1401 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1402 if (inst
->as_function())
1405 ir_variable
*var
= inst
->as_variable();
1406 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1409 assert(inst
->as_assignment()
1411 || inst
->as_if() /* for initializers with the ?: operator */
1412 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1415 inst
= inst
->clone(target
, NULL
);
1418 _mesa_hash_table_insert(temps
, var
, inst
);
1420 remap_variables(inst
, target
, temps
);
1425 last
->insert_after(inst
);
1430 _mesa_hash_table_destroy(temps
, NULL
);
1437 * This class is only used in link_intrastage_shaders() below but declaring
1438 * it inside that function leads to compiler warnings with some versions of
1441 class array_sizing_visitor
: public deref_type_updater
{
1443 array_sizing_visitor()
1444 : mem_ctx(ralloc_context(NULL
)),
1445 unnamed_interfaces(_mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1446 _mesa_key_pointer_equal
))
1450 ~array_sizing_visitor()
1452 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1453 ralloc_free(this->mem_ctx
);
1456 virtual ir_visitor_status
visit(ir_variable
*var
)
1458 const glsl_type
*type_without_array
;
1459 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1460 fixup_type(&var
->type
, var
->data
.max_array_access
,
1461 var
->data
.from_ssbo_unsized_array
,
1462 &implicit_sized_array
);
1463 var
->data
.implicit_sized_array
= implicit_sized_array
;
1464 type_without_array
= var
->type
->without_array();
1465 if (var
->type
->is_interface()) {
1466 if (interface_contains_unsized_arrays(var
->type
)) {
1467 const glsl_type
*new_type
=
1468 resize_interface_members(var
->type
,
1469 var
->get_max_ifc_array_access(),
1470 var
->is_in_shader_storage_block());
1471 var
->type
= new_type
;
1472 var
->change_interface_type(new_type
);
1474 } else if (type_without_array
->is_interface()) {
1475 if (interface_contains_unsized_arrays(type_without_array
)) {
1476 const glsl_type
*new_type
=
1477 resize_interface_members(type_without_array
,
1478 var
->get_max_ifc_array_access(),
1479 var
->is_in_shader_storage_block());
1480 var
->change_interface_type(new_type
);
1481 var
->type
= update_interface_members_array(var
->type
, new_type
);
1483 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1484 /* Store a pointer to the variable in the unnamed_interfaces
1488 _mesa_hash_table_search(this->unnamed_interfaces
,
1491 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1493 if (interface_vars
== NULL
) {
1494 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1496 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1499 unsigned index
= ifc_type
->field_index(var
->name
);
1500 assert(index
< ifc_type
->length
);
1501 assert(interface_vars
[index
] == NULL
);
1502 interface_vars
[index
] = var
;
1504 return visit_continue
;
1508 * For each unnamed interface block that was discovered while running the
1509 * visitor, adjust the interface type to reflect the newly assigned array
1510 * sizes, and fix up the ir_variable nodes to point to the new interface
1513 void fixup_unnamed_interface_types()
1515 hash_table_call_foreach(this->unnamed_interfaces
,
1516 fixup_unnamed_interface_type
, NULL
);
1521 * If the type pointed to by \c type represents an unsized array, replace
1522 * it with a sized array whose size is determined by max_array_access.
1524 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1525 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1527 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1528 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1529 max_array_access
+ 1);
1530 *implicit_sized
= true;
1531 assert(*type
!= NULL
);
1535 static const glsl_type
*
1536 update_interface_members_array(const glsl_type
*type
,
1537 const glsl_type
*new_interface_type
)
1539 const glsl_type
*element_type
= type
->fields
.array
;
1540 if (element_type
->is_array()) {
1541 const glsl_type
*new_array_type
=
1542 update_interface_members_array(element_type
, new_interface_type
);
1543 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1545 return glsl_type::get_array_instance(new_interface_type
,
1551 * Determine whether the given interface type contains unsized arrays (if
1552 * it doesn't, array_sizing_visitor doesn't need to process it).
1554 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1556 for (unsigned i
= 0; i
< type
->length
; i
++) {
1557 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1558 if (elem_type
->is_unsized_array())
1565 * Create a new interface type based on the given type, with unsized arrays
1566 * replaced by sized arrays whose size is determined by
1567 * max_ifc_array_access.
1569 static const glsl_type
*
1570 resize_interface_members(const glsl_type
*type
,
1571 const int *max_ifc_array_access
,
1574 unsigned num_fields
= type
->length
;
1575 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1576 memcpy(fields
, type
->fields
.structure
,
1577 num_fields
* sizeof(*fields
));
1578 for (unsigned i
= 0; i
< num_fields
; i
++) {
1579 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1580 /* If SSBO last member is unsized array, we don't replace it by a sized
1583 if (is_ssbo
&& i
== (num_fields
- 1))
1584 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1585 true, &implicit_sized_array
);
1587 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1588 false, &implicit_sized_array
);
1589 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1591 glsl_interface_packing packing
=
1592 (glsl_interface_packing
) type
->interface_packing
;
1593 bool row_major
= (bool) type
->interface_row_major
;
1594 const glsl_type
*new_ifc_type
=
1595 glsl_type::get_interface_instance(fields
, num_fields
,
1596 packing
, row_major
, type
->name
);
1598 return new_ifc_type
;
1601 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1604 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1605 ir_variable
**interface_vars
= (ir_variable
**) data
;
1606 unsigned num_fields
= ifc_type
->length
;
1607 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1608 memcpy(fields
, ifc_type
->fields
.structure
,
1609 num_fields
* sizeof(*fields
));
1610 bool interface_type_changed
= false;
1611 for (unsigned i
= 0; i
< num_fields
; i
++) {
1612 if (interface_vars
[i
] != NULL
&&
1613 fields
[i
].type
!= interface_vars
[i
]->type
) {
1614 fields
[i
].type
= interface_vars
[i
]->type
;
1615 interface_type_changed
= true;
1618 if (!interface_type_changed
) {
1622 glsl_interface_packing packing
=
1623 (glsl_interface_packing
) ifc_type
->interface_packing
;
1624 bool row_major
= (bool) ifc_type
->interface_row_major
;
1625 const glsl_type
*new_ifc_type
=
1626 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1627 row_major
, ifc_type
->name
);
1629 for (unsigned i
= 0; i
< num_fields
; i
++) {
1630 if (interface_vars
[i
] != NULL
)
1631 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1636 * Memory context used to allocate the data in \c unnamed_interfaces.
1641 * Hash table from const glsl_type * to an array of ir_variable *'s
1642 * pointing to the ir_variables constituting each unnamed interface block.
1644 hash_table
*unnamed_interfaces
;
1648 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1649 struct gl_shader_program
*prog
)
1651 /* We will validate doubles at a later stage */
1652 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1653 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1654 "multiple of 4 or if its applied to a type that is "
1655 "or contains a double a multiple of 8.",
1656 prog
->TransformFeedback
.BufferStride
[idx
]);
1660 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1661 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1662 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1663 "limit has been exceeded.");
1671 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1675 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1676 struct gl_shader_program
*prog
,
1677 struct gl_shader
**shader_list
,
1678 unsigned num_shaders
)
1680 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1681 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1684 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1685 struct gl_shader
*shader
= shader_list
[i
];
1687 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1688 if (shader
->TransformFeedbackBufferStride
[j
]) {
1689 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1690 prog
->TransformFeedback
.BufferStride
[j
] =
1691 shader
->TransformFeedbackBufferStride
[j
];
1692 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1694 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1695 shader
->TransformFeedbackBufferStride
[j
]){
1697 "intrastage shaders defined with conflicting "
1698 "xfb_stride for buffer %d (%d and %d)\n", j
,
1699 prog
->TransformFeedback
.BufferStride
[j
],
1700 shader
->TransformFeedbackBufferStride
[j
]);
1709 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1713 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1714 struct gl_shader
**shader_list
,
1715 unsigned num_shaders
)
1717 bool bindless_sampler
, bindless_image
;
1718 bool bound_sampler
, bound_image
;
1720 bindless_sampler
= bindless_image
= false;
1721 bound_sampler
= bound_image
= false;
1723 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1724 struct gl_shader
*shader
= shader_list
[i
];
1726 if (shader
->bindless_sampler
)
1727 bindless_sampler
= true;
1728 if (shader
->bindless_image
)
1729 bindless_image
= true;
1730 if (shader
->bound_sampler
)
1731 bound_sampler
= true;
1732 if (shader
->bound_image
)
1735 if ((bindless_sampler
&& bound_sampler
) ||
1736 (bindless_image
&& bound_image
)) {
1737 /* From section 4.4.6 of the ARB_bindless_texture spec:
1739 * "If both bindless_sampler and bound_sampler, or bindless_image
1740 * and bound_image, are declared at global scope in any
1741 * compilation unit, a link- time error will be generated."
1743 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1744 "bindless_image and bound_image, can't be declared at "
1751 * Performs the cross-validation of tessellation control shader vertices and
1752 * layout qualifiers for the attached tessellation control shaders,
1753 * and propagates them to the linked TCS and linked shader program.
1756 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1757 struct gl_program
*gl_prog
,
1758 struct gl_shader
**shader_list
,
1759 unsigned num_shaders
)
1761 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1764 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1766 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1768 * "All tessellation control shader layout declarations in a program
1769 * must specify the same output patch vertex count. There must be at
1770 * least one layout qualifier specifying an output patch vertex count
1771 * in any program containing tessellation control shaders; however,
1772 * such a declaration is not required in all tessellation control
1776 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1777 struct gl_shader
*shader
= shader_list
[i
];
1779 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1780 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1781 gl_prog
->info
.tess
.tcs_vertices_out
!=
1782 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1783 linker_error(prog
, "tessellation control shader defined with "
1784 "conflicting output vertex count (%d and %d)\n",
1785 gl_prog
->info
.tess
.tcs_vertices_out
,
1786 shader
->info
.TessCtrl
.VerticesOut
);
1789 gl_prog
->info
.tess
.tcs_vertices_out
=
1790 shader
->info
.TessCtrl
.VerticesOut
;
1794 /* Just do the intrastage -> interstage propagation right now,
1795 * since we already know we're in the right type of shader program
1798 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1799 linker_error(prog
, "tessellation control shader didn't declare "
1800 "vertices out layout qualifier\n");
1807 * Performs the cross-validation of tessellation evaluation shader
1808 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1809 * for the attached tessellation evaluation shaders, and propagates them
1810 * to the linked TES and linked shader program.
1813 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1814 struct gl_program
*gl_prog
,
1815 struct gl_shader
**shader_list
,
1816 unsigned num_shaders
)
1818 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1821 int point_mode
= -1;
1822 unsigned vertex_order
= 0;
1824 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1825 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1827 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1829 * "At least one tessellation evaluation shader (compilation unit) in
1830 * a program must declare a primitive mode in its input layout.
1831 * Declaration vertex spacing, ordering, and point mode identifiers is
1832 * optional. It is not required that all tessellation evaluation
1833 * shaders in a program declare a primitive mode. If spacing or
1834 * vertex ordering declarations are omitted, the tessellation
1835 * primitive generator will use equal spacing or counter-clockwise
1836 * vertex ordering, respectively. If a point mode declaration is
1837 * omitted, the tessellation primitive generator will produce lines or
1838 * triangles according to the primitive mode."
1841 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1842 struct gl_shader
*shader
= shader_list
[i
];
1844 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1845 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1846 gl_prog
->info
.tess
.primitive_mode
!=
1847 shader
->info
.TessEval
.PrimitiveMode
) {
1848 linker_error(prog
, "tessellation evaluation shader defined with "
1849 "conflicting input primitive modes.\n");
1852 gl_prog
->info
.tess
.primitive_mode
=
1853 shader
->info
.TessEval
.PrimitiveMode
;
1856 if (shader
->info
.TessEval
.Spacing
!= 0) {
1857 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1858 shader
->info
.TessEval
.Spacing
) {
1859 linker_error(prog
, "tessellation evaluation shader defined with "
1860 "conflicting vertex spacing.\n");
1863 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1866 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1867 if (vertex_order
!= 0 &&
1868 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1869 linker_error(prog
, "tessellation evaluation shader defined with "
1870 "conflicting ordering.\n");
1873 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1876 if (shader
->info
.TessEval
.PointMode
!= -1) {
1877 if (point_mode
!= -1 &&
1878 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1879 linker_error(prog
, "tessellation evaluation shader defined with "
1880 "conflicting point modes.\n");
1883 point_mode
= shader
->info
.TessEval
.PointMode
;
1888 /* Just do the intrastage -> interstage propagation right now,
1889 * since we already know we're in the right type of shader program
1892 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1894 "tessellation evaluation shader didn't declare input "
1895 "primitive modes.\n");
1899 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1900 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1902 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1903 gl_prog
->info
.tess
.ccw
= true;
1905 gl_prog
->info
.tess
.ccw
= false;
1908 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1909 gl_prog
->info
.tess
.point_mode
= false;
1911 gl_prog
->info
.tess
.point_mode
= true;
1916 * Performs the cross-validation of layout qualifiers specified in
1917 * redeclaration of gl_FragCoord for the attached fragment shaders,
1918 * and propagates them to the linked FS and linked shader program.
1921 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1922 struct gl_linked_shader
*linked_shader
,
1923 struct gl_shader
**shader_list
,
1924 unsigned num_shaders
)
1926 bool redeclares_gl_fragcoord
= false;
1927 bool uses_gl_fragcoord
= false;
1928 bool origin_upper_left
= false;
1929 bool pixel_center_integer
= false;
1931 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1932 (prog
->data
->Version
< 150 &&
1933 !prog
->ARB_fragment_coord_conventions_enable
))
1936 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1937 struct gl_shader
*shader
= shader_list
[i
];
1938 /* From the GLSL 1.50 spec, page 39:
1940 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1941 * it must be redeclared in all the fragment shaders in that program
1942 * that have a static use gl_FragCoord."
1944 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
1945 shader
->uses_gl_fragcoord
)
1946 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
1947 uses_gl_fragcoord
)) {
1948 linker_error(prog
, "fragment shader defined with conflicting "
1949 "layout qualifiers for gl_FragCoord\n");
1952 /* From the GLSL 1.50 spec, page 39:
1954 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1955 * single program must have the same set of qualifiers."
1957 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
1958 (shader
->origin_upper_left
!= origin_upper_left
||
1959 shader
->pixel_center_integer
!= pixel_center_integer
)) {
1960 linker_error(prog
, "fragment shader defined with conflicting "
1961 "layout qualifiers for gl_FragCoord\n");
1964 /* Update the linked shader state. Note that uses_gl_fragcoord should
1965 * accumulate the results. The other values should replace. If there
1966 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1967 * are already known to be the same.
1969 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1970 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
1971 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
1972 origin_upper_left
= shader
->origin_upper_left
;
1973 pixel_center_integer
= shader
->pixel_center_integer
;
1976 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
1977 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
1978 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
1979 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
1980 shader
->PostDepthCoverage
;
1982 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
1987 * Performs the cross-validation of geometry shader max_vertices and
1988 * primitive type layout qualifiers for the attached geometry shaders,
1989 * and propagates them to the linked GS and linked shader program.
1992 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1993 struct gl_program
*gl_prog
,
1994 struct gl_shader
**shader_list
,
1995 unsigned num_shaders
)
1997 /* No in/out qualifiers defined for anything but GLSL 1.50+
1998 * geometry shaders so far.
2000 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2001 prog
->data
->Version
< 150)
2004 int vertices_out
= -1;
2006 gl_prog
->info
.gs
.invocations
= 0;
2007 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2008 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2010 /* From the GLSL 1.50 spec, page 46:
2012 * "All geometry shader output layout declarations in a program
2013 * must declare the same layout and same value for
2014 * max_vertices. There must be at least one geometry output
2015 * layout declaration somewhere in a program, but not all
2016 * geometry shaders (compilation units) are required to
2020 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2021 struct gl_shader
*shader
= shader_list
[i
];
2023 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2024 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2025 gl_prog
->info
.gs
.input_primitive
!=
2026 shader
->info
.Geom
.InputType
) {
2027 linker_error(prog
, "geometry shader defined with conflicting "
2031 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2034 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2035 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2036 gl_prog
->info
.gs
.output_primitive
!=
2037 shader
->info
.Geom
.OutputType
) {
2038 linker_error(prog
, "geometry shader defined with conflicting "
2042 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2045 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2046 if (vertices_out
!= -1 &&
2047 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2048 linker_error(prog
, "geometry shader defined with conflicting "
2049 "output vertex count (%d and %d)\n",
2050 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2053 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2056 if (shader
->info
.Geom
.Invocations
!= 0) {
2057 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2058 gl_prog
->info
.gs
.invocations
!=
2059 (unsigned) shader
->info
.Geom
.Invocations
) {
2060 linker_error(prog
, "geometry shader defined with conflicting "
2061 "invocation count (%d and %d)\n",
2062 gl_prog
->info
.gs
.invocations
,
2063 shader
->info
.Geom
.Invocations
);
2066 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2070 /* Just do the intrastage -> interstage propagation right now,
2071 * since we already know we're in the right type of shader program
2074 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2076 "geometry shader didn't declare primitive input type\n");
2080 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2082 "geometry shader didn't declare primitive output type\n");
2086 if (vertices_out
== -1) {
2088 "geometry shader didn't declare max_vertices\n");
2091 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2094 if (gl_prog
->info
.gs
.invocations
== 0)
2095 gl_prog
->info
.gs
.invocations
= 1;
2100 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2101 * qualifiers for the attached compute shaders, and propagate them to the
2102 * linked CS and linked shader program.
2105 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2106 struct gl_program
*gl_prog
,
2107 struct gl_shader
**shader_list
,
2108 unsigned num_shaders
)
2110 /* This function is called for all shader stages, but it only has an effect
2111 * for compute shaders.
2113 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2116 for (int i
= 0; i
< 3; i
++)
2117 gl_prog
->info
.cs
.local_size
[i
] = 0;
2119 gl_prog
->info
.cs
.local_size_variable
= false;
2121 /* From the ARB_compute_shader spec, in the section describing local size
2124 * If multiple compute shaders attached to a single program object
2125 * declare local work-group size, the declarations must be identical;
2126 * otherwise a link-time error results. Furthermore, if a program
2127 * object contains any compute shaders, at least one must contain an
2128 * input layout qualifier specifying the local work sizes of the
2129 * program, or a link-time error will occur.
2131 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2132 struct gl_shader
*shader
= shader_list
[sh
];
2134 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2135 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2136 for (int i
= 0; i
< 3; i
++) {
2137 if (gl_prog
->info
.cs
.local_size
[i
] !=
2138 shader
->info
.Comp
.LocalSize
[i
]) {
2139 linker_error(prog
, "compute shader defined with conflicting "
2145 for (int i
= 0; i
< 3; i
++) {
2146 gl_prog
->info
.cs
.local_size
[i
] =
2147 shader
->info
.Comp
.LocalSize
[i
];
2149 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2150 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2151 /* The ARB_compute_variable_group_size spec says:
2153 * If one compute shader attached to a program declares a
2154 * variable local group size and a second compute shader
2155 * attached to the same program declares a fixed local group
2156 * size, a link-time error results.
2158 linker_error(prog
, "compute shader defined with both fixed and "
2159 "variable local group size\n");
2162 gl_prog
->info
.cs
.local_size_variable
= true;
2166 /* Just do the intrastage -> interstage propagation right now,
2167 * since we already know we're in the right type of shader program
2170 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2171 !gl_prog
->info
.cs
.local_size_variable
) {
2172 linker_error(prog
, "compute shader must contain a fixed or a variable "
2173 "local group size\n");
2180 * Combine a group of shaders for a single stage to generate a linked shader
2183 * If this function is supplied a single shader, it is cloned, and the new
2184 * shader is returned.
2186 struct gl_linked_shader
*
2187 link_intrastage_shaders(void *mem_ctx
,
2188 struct gl_context
*ctx
,
2189 struct gl_shader_program
*prog
,
2190 struct gl_shader
**shader_list
,
2191 unsigned num_shaders
,
2192 bool allow_missing_main
)
2194 struct gl_uniform_block
*ubo_blocks
= NULL
;
2195 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2196 unsigned num_ubo_blocks
= 0;
2197 unsigned num_ssbo_blocks
= 0;
2199 /* Check that global variables defined in multiple shaders are consistent.
2201 glsl_symbol_table variables
;
2202 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2203 if (shader_list
[i
] == NULL
)
2205 cross_validate_globals(prog
, shader_list
[i
]->ir
, &variables
, false);
2208 if (!prog
->data
->LinkStatus
)
2211 /* Check that interface blocks defined in multiple shaders are consistent.
2213 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2215 if (!prog
->data
->LinkStatus
)
2218 /* Check that there is only a single definition of each function signature
2219 * across all shaders.
2221 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2222 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2223 ir_function
*const f
= node
->as_function();
2228 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2229 ir_function
*const other
=
2230 shader_list
[j
]->symbols
->get_function(f
->name
);
2232 /* If the other shader has no function (and therefore no function
2233 * signatures) with the same name, skip to the next shader.
2238 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2239 if (!sig
->is_defined
)
2242 ir_function_signature
*other_sig
=
2243 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2245 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2246 linker_error(prog
, "function `%s' is multiply defined\n",
2255 /* Find the shader that defines main, and make a clone of it.
2257 * Starting with the clone, search for undefined references. If one is
2258 * found, find the shader that defines it. Clone the reference and add
2259 * it to the shader. Repeat until there are no undefined references or
2260 * until a reference cannot be resolved.
2262 gl_shader
*main
= NULL
;
2263 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2264 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2265 main
= shader_list
[i
];
2270 if (main
== NULL
&& allow_missing_main
)
2271 main
= shader_list
[0];
2274 linker_error(prog
, "%s shader lacks `main'\n",
2275 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2279 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2280 linked
->Stage
= shader_list
[0]->Stage
;
2282 /* Create program and attach it to the linked shader */
2283 struct gl_program
*gl_prog
=
2284 ctx
->Driver
.NewProgram(ctx
,
2285 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2288 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2289 _mesa_delete_linked_shader(ctx
, linked
);
2293 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2295 /* Don't use _mesa_reference_program() just take ownership */
2296 linked
->Program
= gl_prog
;
2298 linked
->ir
= new(linked
) exec_list
;
2299 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2301 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2302 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2303 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2304 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2305 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2307 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2308 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2310 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2312 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2314 /* The pointer to the main function in the final linked shader (i.e., the
2315 * copy of the original shader that contained the main function).
2317 ir_function_signature
*const main_sig
=
2318 _mesa_get_main_function_signature(linked
->symbols
);
2320 /* Move any instructions other than variable declarations or function
2321 * declarations into main.
2323 if (main_sig
!= NULL
) {
2324 exec_node
*insertion_point
=
2325 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2328 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2329 if (shader_list
[i
] == main
)
2332 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2333 insertion_point
, true, linked
);
2337 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2338 _mesa_delete_linked_shader(ctx
, linked
);
2342 /* Make a pass over all variable declarations to ensure that arrays with
2343 * unspecified sizes have a size specified. The size is inferred from the
2344 * max_array_access field.
2346 array_sizing_visitor v
;
2348 v
.fixup_unnamed_interface_types();
2350 /* Link up uniform blocks defined within this stage. */
2351 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2352 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2354 if (!prog
->data
->LinkStatus
) {
2355 _mesa_delete_linked_shader(ctx
, linked
);
2359 /* Copy ubo blocks to linked shader list */
2360 linked
->Program
->sh
.UniformBlocks
=
2361 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2362 ralloc_steal(linked
, ubo_blocks
);
2363 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2364 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2366 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2368 /* Copy ssbo blocks to linked shader list */
2369 linked
->Program
->sh
.ShaderStorageBlocks
=
2370 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2371 ralloc_steal(linked
, ssbo_blocks
);
2372 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2373 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2375 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2377 /* At this point linked should contain all of the linked IR, so
2378 * validate it to make sure nothing went wrong.
2380 validate_ir_tree(linked
->ir
);
2382 /* Set the size of geometry shader input arrays */
2383 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2384 unsigned num_vertices
=
2385 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2386 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2387 MESA_SHADER_GEOMETRY
);
2388 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2389 ir
->accept(&input_resize_visitor
);
2393 if (ctx
->Const
.VertexID_is_zero_based
)
2394 lower_vertex_id(linked
);
2396 if (ctx
->Const
.LowerCsDerivedVariables
)
2397 lower_cs_derived(linked
);
2400 /* Compute the source checksum. */
2401 linked
->SourceChecksum
= 0;
2402 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2403 if (shader_list
[i
] == NULL
)
2405 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2413 * Update the sizes of linked shader uniform arrays to the maximum
2416 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2418 * If one or more elements of an array are active,
2419 * GetActiveUniform will return the name of the array in name,
2420 * subject to the restrictions listed above. The type of the array
2421 * is returned in type. The size parameter contains the highest
2422 * array element index used, plus one. The compiler or linker
2423 * determines the highest index used. There will be only one
2424 * active uniform reported by the GL per uniform array.
2428 update_array_sizes(struct gl_shader_program
*prog
)
2430 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2431 if (prog
->_LinkedShaders
[i
] == NULL
)
2434 bool types_were_updated
= false;
2436 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2437 ir_variable
*const var
= node
->as_variable();
2439 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2440 !var
->type
->is_array())
2443 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2444 * will not be eliminated. Since we always do std140, just
2445 * don't resize arrays in UBOs.
2447 * Atomic counters are supposed to get deterministic
2448 * locations assigned based on the declaration ordering and
2449 * sizes, array compaction would mess that up.
2451 * Subroutine uniforms are not removed.
2453 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2454 var
->type
->contains_subroutine() || var
->constant_initializer
)
2457 int size
= var
->data
.max_array_access
;
2458 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2459 if (prog
->_LinkedShaders
[j
] == NULL
)
2462 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2463 ir_variable
*other_var
= node2
->as_variable();
2467 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2468 other_var
->data
.max_array_access
> size
) {
2469 size
= other_var
->data
.max_array_access
;
2474 if (size
+ 1 != (int)var
->type
->length
) {
2475 /* If this is a built-in uniform (i.e., it's backed by some
2476 * fixed-function state), adjust the number of state slots to
2477 * match the new array size. The number of slots per array entry
2478 * is not known. It seems safe to assume that the total number of
2479 * slots is an integer multiple of the number of array elements.
2480 * Determine the number of slots per array element by dividing by
2481 * the old (total) size.
2483 const unsigned num_slots
= var
->get_num_state_slots();
2484 if (num_slots
> 0) {
2485 var
->set_num_state_slots((size
+ 1)
2486 * (num_slots
/ var
->type
->length
));
2489 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2491 types_were_updated
= true;
2495 /* Update the types of dereferences in case we changed any. */
2496 if (types_were_updated
) {
2497 deref_type_updater v
;
2498 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2504 * Resize tessellation evaluation per-vertex inputs to the size of
2505 * tessellation control per-vertex outputs.
2508 resize_tes_inputs(struct gl_context
*ctx
,
2509 struct gl_shader_program
*prog
)
2511 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2514 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2515 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2517 /* If no control shader is present, then the TES inputs are statically
2518 * sized to MaxPatchVertices; the actual size of the arrays won't be
2519 * known until draw time.
2521 const int num_vertices
= tcs
2522 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2523 : ctx
->Const
.MaxPatchVertices
;
2525 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2526 MESA_SHADER_TESS_EVAL
);
2527 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2528 ir
->accept(&input_resize_visitor
);
2532 /* Convert the gl_PatchVerticesIn system value into a constant, since
2533 * the value is known at this point.
2535 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2536 ir_variable
*var
= ir
->as_variable();
2537 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2538 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2539 void *mem_ctx
= ralloc_parent(var
);
2540 var
->data
.location
= 0;
2541 var
->data
.explicit_location
= false;
2542 var
->data
.mode
= ir_var_auto
;
2543 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2550 * Find a contiguous set of available bits in a bitmask.
2552 * \param used_mask Bits representing used (1) and unused (0) locations
2553 * \param needed_count Number of contiguous bits needed.
2556 * Base location of the available bits on success or -1 on failure.
2559 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2561 unsigned needed_mask
= (1 << needed_count
) - 1;
2562 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2564 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2565 * cannot optimize possibly infinite loops" for the loop below.
2567 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2570 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2571 if ((needed_mask
& ~used_mask
) == needed_mask
)
2581 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2584 * Assign locations for either VS inputs or FS outputs
2586 * \param mem_ctx Temporary ralloc context used for linking
2587 * \param prog Shader program whose variables need locations assigned
2588 * \param constants Driver specific constant values for the program.
2589 * \param target_index Selector for the program target to receive location
2590 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2591 * \c MESA_SHADER_FRAGMENT.
2594 * If locations are successfully assigned, true is returned. Otherwise an
2595 * error is emitted to the shader link log and false is returned.
2598 assign_attribute_or_color_locations(void *mem_ctx
,
2599 gl_shader_program
*prog
,
2600 struct gl_constants
*constants
,
2601 unsigned target_index
)
2603 /* Maximum number of generic locations. This corresponds to either the
2604 * maximum number of draw buffers or the maximum number of generic
2607 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2608 constants
->Program
[target_index
].MaxAttribs
:
2609 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2611 /* Mark invalid locations as being used.
2613 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2614 unsigned double_storage_locations
= 0;
2616 assert((target_index
== MESA_SHADER_VERTEX
)
2617 || (target_index
== MESA_SHADER_FRAGMENT
));
2619 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2623 /* Operate in a total of four passes.
2625 * 1. Invalidate the location assignments for all vertex shader inputs.
2627 * 2. Assign locations for inputs that have user-defined (via
2628 * glBindVertexAttribLocation) locations and outputs that have
2629 * user-defined locations (via glBindFragDataLocation).
2631 * 3. Sort the attributes without assigned locations by number of slots
2632 * required in decreasing order. Fragmentation caused by attribute
2633 * locations assigned by the application may prevent large attributes
2634 * from having enough contiguous space.
2636 * 4. Assign locations to any inputs without assigned locations.
2639 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2640 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2642 const enum ir_variable_mode direction
=
2643 (target_index
== MESA_SHADER_VERTEX
)
2644 ? ir_var_shader_in
: ir_var_shader_out
;
2647 /* Temporary storage for the set of attributes that need locations assigned.
2653 /* Used below in the call to qsort. */
2654 static int compare(const void *a
, const void *b
)
2656 const temp_attr
*const l
= (const temp_attr
*) a
;
2657 const temp_attr
*const r
= (const temp_attr
*) b
;
2659 /* Reversed because we want a descending order sort below. */
2660 return r
->slots
- l
->slots
;
2663 assert(max_index
<= 32);
2665 /* Temporary array for the set of attributes that have locations assigned,
2666 * for the purpose of checking overlapping slots/components of (non-ES)
2667 * fragment shader outputs.
2669 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2670 unsigned assigned_attr
= 0;
2672 unsigned num_attr
= 0;
2674 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2675 ir_variable
*const var
= node
->as_variable();
2677 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2680 if (var
->data
.explicit_location
) {
2681 var
->data
.is_unmatched_generic_inout
= 0;
2682 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2683 || (var
->data
.location
< 0)) {
2685 "invalid explicit location %d specified for `%s'\n",
2686 (var
->data
.location
< 0)
2687 ? var
->data
.location
2688 : var
->data
.location
- generic_base
,
2692 } else if (target_index
== MESA_SHADER_VERTEX
) {
2695 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2696 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2697 var
->data
.location
= binding
;
2698 var
->data
.is_unmatched_generic_inout
= 0;
2700 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2703 const char *name
= var
->name
;
2704 const glsl_type
*type
= var
->type
;
2707 /* Check if there's a binding for the variable name */
2708 if (prog
->FragDataBindings
->get(binding
, name
)) {
2709 assert(binding
>= FRAG_RESULT_DATA0
);
2710 var
->data
.location
= binding
;
2711 var
->data
.is_unmatched_generic_inout
= 0;
2713 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2714 var
->data
.index
= index
;
2719 /* If not, but it's an array type, look for name[0] */
2720 if (type
->is_array()) {
2721 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2722 type
= type
->fields
.array
;
2730 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2733 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2735 * "Output binding assignments will cause LinkProgram to fail:
2737 * If the program has an active output assigned to a location greater
2738 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2739 * an active output assigned an index greater than or equal to one;"
2741 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2742 var
->data
.location
- generic_base
>=
2743 (int) constants
->MaxDualSourceDrawBuffers
) {
2745 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2746 "with index %u for %s\n",
2747 var
->data
.location
- generic_base
, var
->data
.index
,
2752 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2754 /* If the variable is not a built-in and has a location statically
2755 * assigned in the shader (presumably via a layout qualifier), make sure
2756 * that it doesn't collide with other assigned locations. Otherwise,
2757 * add it to the list of variables that need linker-assigned locations.
2759 if (var
->data
.location
!= -1) {
2760 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2761 /* From page 61 of the OpenGL 4.0 spec:
2763 * "LinkProgram will fail if the attribute bindings assigned
2764 * by BindAttribLocation do not leave not enough space to
2765 * assign a location for an active matrix attribute or an
2766 * active attribute array, both of which require multiple
2767 * contiguous generic attributes."
2769 * I think above text prohibits the aliasing of explicit and
2770 * automatic assignments. But, aliasing is allowed in manual
2771 * assignments of attribute locations. See below comments for
2774 * From OpenGL 4.0 spec, page 61:
2776 * "It is possible for an application to bind more than one
2777 * attribute name to the same location. This is referred to as
2778 * aliasing. This will only work if only one of the aliased
2779 * attributes is active in the executable program, or if no
2780 * path through the shader consumes more than one attribute of
2781 * a set of attributes aliased to the same location. A link
2782 * error can occur if the linker determines that every path
2783 * through the shader consumes multiple aliased attributes,
2784 * but implementations are not required to generate an error
2787 * From GLSL 4.30 spec, page 54:
2789 * "A program will fail to link if any two non-vertex shader
2790 * input variables are assigned to the same location. For
2791 * vertex shaders, multiple input variables may be assigned
2792 * to the same location using either layout qualifiers or via
2793 * the OpenGL API. However, such aliasing is intended only to
2794 * support vertex shaders where each execution path accesses
2795 * at most one input per each location. Implementations are
2796 * permitted, but not required, to generate link-time errors
2797 * if they detect that every path through the vertex shader
2798 * executable accesses multiple inputs assigned to any single
2799 * location. For all shader types, a program will fail to link
2800 * if explicit location assignments leave the linker unable
2801 * to find space for other variables without explicit
2804 * From OpenGL ES 3.0 spec, page 56:
2806 * "Binding more than one attribute name to the same location
2807 * is referred to as aliasing, and is not permitted in OpenGL
2808 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2809 * fail when this condition exists. However, aliasing is
2810 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2811 * This will only work if only one of the aliased attributes
2812 * is active in the executable program, or if no path through
2813 * the shader consumes more than one attribute of a set of
2814 * attributes aliased to the same location. A link error can
2815 * occur if the linker determines that every path through the
2816 * shader consumes multiple aliased attributes, but implemen-
2817 * tations are not required to generate an error in this case."
2819 * After looking at above references from OpenGL, OpenGL ES and
2820 * GLSL specifications, we allow aliasing of vertex input variables
2821 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2823 * NOTE: This is not required by the spec but its worth mentioning
2824 * here that we're not doing anything to make sure that no path
2825 * through the vertex shader executable accesses multiple inputs
2826 * assigned to any single location.
2829 /* Mask representing the contiguous slots that will be used by
2832 const unsigned attr
= var
->data
.location
- generic_base
;
2833 const unsigned use_mask
= (1 << slots
) - 1;
2834 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2835 ? "vertex shader input" : "fragment shader output";
2837 /* Generate a link error if the requested locations for this
2838 * attribute exceed the maximum allowed attribute location.
2840 if (attr
+ slots
> max_index
) {
2842 "insufficient contiguous locations "
2843 "available for %s `%s' %d %d %d\n", string
,
2844 var
->name
, used_locations
, use_mask
, attr
);
2848 /* Generate a link error if the set of bits requested for this
2849 * attribute overlaps any previously allocated bits.
2851 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2852 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2853 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2856 * "Additionally, for fragment shader outputs, if two
2857 * variables are placed within the same location, they
2858 * must have the same underlying type (floating-point or
2859 * integer). No component aliasing of output variables or
2860 * members is allowed.
2862 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2863 unsigned assigned_slots
=
2864 assigned
[i
]->type
->count_attribute_slots(false);
2865 unsigned assig_attr
=
2866 assigned
[i
]->data
.location
- generic_base
;
2867 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2869 if ((assigned_use_mask
<< assig_attr
) &
2870 (use_mask
<< attr
)) {
2872 const glsl_type
*assigned_type
=
2873 assigned
[i
]->type
->without_array();
2874 const glsl_type
*type
= var
->type
->without_array();
2875 if (assigned_type
->base_type
!= type
->base_type
) {
2876 linker_error(prog
, "types do not match for aliased"
2877 " %ss %s and %s\n", string
,
2878 assigned
[i
]->name
, var
->name
);
2882 unsigned assigned_component_mask
=
2883 ((1 << assigned_type
->vector_elements
) - 1) <<
2884 assigned
[i
]->data
.location_frac
;
2885 unsigned component_mask
=
2886 ((1 << type
->vector_elements
) - 1) <<
2887 var
->data
.location_frac
;
2888 if (assigned_component_mask
& component_mask
) {
2889 linker_error(prog
, "overlapping component is "
2890 "assigned to %ss %s and %s "
2892 string
, assigned
[i
]->name
, var
->name
,
2893 var
->data
.location_frac
);
2898 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2899 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
2900 linker_error(prog
, "overlapping location is assigned "
2901 "to %s `%s' %d %d %d\n", string
, var
->name
,
2902 used_locations
, use_mask
, attr
);
2905 linker_warning(prog
, "overlapping location is assigned "
2906 "to %s `%s' %d %d %d\n", string
, var
->name
,
2907 used_locations
, use_mask
, attr
);
2911 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2912 /* Only track assigned variables for non-ES fragment shaders
2913 * to avoid overflowing the array.
2915 * At most one variable per fragment output component should
2918 assert(assigned_attr
< ARRAY_SIZE(assigned
));
2919 assigned
[assigned_attr
] = var
;
2923 used_locations
|= (use_mask
<< attr
);
2925 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2927 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2928 * active attribute variables may fail to link, unless
2929 * device-dependent optimizations are able to make the program
2930 * fit within available hardware resources. For the purposes
2931 * of this test, attribute variables of the type dvec3, dvec4,
2932 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2933 * count as consuming twice as many attributes as equivalent
2934 * single-precision types. While these types use the same number
2935 * of generic attributes as their single-precision equivalents,
2936 * implementations are permitted to consume two single-precision
2937 * vectors of internal storage for each three- or four-component
2938 * double-precision vector."
2940 * Mark this attribute slot as taking up twice as much space
2941 * so we can count it properly against limits. According to
2942 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2943 * is optional behavior, but it seems preferable.
2945 if (var
->type
->without_array()->is_dual_slot())
2946 double_storage_locations
|= (use_mask
<< attr
);
2952 if (num_attr
>= max_index
) {
2953 linker_error(prog
, "too many %s (max %u)",
2954 target_index
== MESA_SHADER_VERTEX
?
2955 "vertex shader inputs" : "fragment shader outputs",
2959 to_assign
[num_attr
].slots
= slots
;
2960 to_assign
[num_attr
].var
= var
;
2964 if (target_index
== MESA_SHADER_VERTEX
) {
2965 unsigned total_attribs_size
=
2966 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
2967 _mesa_bitcount(double_storage_locations
);
2968 if (total_attribs_size
> max_index
) {
2970 "attempt to use %d vertex attribute slots only %d available ",
2971 total_attribs_size
, max_index
);
2976 /* If all of the attributes were assigned locations by the application (or
2977 * are built-in attributes with fixed locations), return early. This should
2978 * be the common case.
2983 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2985 if (target_index
== MESA_SHADER_VERTEX
) {
2986 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2987 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2988 * reserved to prevent it from being automatically allocated below.
2990 find_deref_visitor
find("gl_Vertex");
2992 if (find
.variable_found())
2993 used_locations
|= (1 << 0);
2996 for (unsigned i
= 0; i
< num_attr
; i
++) {
2997 /* Mask representing the contiguous slots that will be used by this
3000 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3002 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3005 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3006 ? "vertex shader input" : "fragment shader output";
3009 "insufficient contiguous locations "
3010 "available for %s `%s'\n",
3011 string
, to_assign
[i
].var
->name
);
3015 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3016 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3017 used_locations
|= (use_mask
<< location
);
3019 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3020 double_storage_locations
|= (use_mask
<< location
);
3023 /* Now that we have all the locations, from the GL 4.5 core spec, section
3024 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3025 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3026 * as equivalent single-precision types.
3028 if (target_index
== MESA_SHADER_VERTEX
) {
3029 unsigned total_attribs_size
=
3030 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3031 _mesa_bitcount(double_storage_locations
);
3032 if (total_attribs_size
> max_index
) {
3034 "attempt to use %d vertex attribute slots only %d available ",
3035 total_attribs_size
, max_index
);
3044 * Match explicit locations of outputs to inputs and deactivate the
3045 * unmatch flag if found so we don't optimise them away.
3048 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3049 gl_linked_shader
*consumer
)
3051 glsl_symbol_table parameters
;
3052 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3055 /* Find all shader outputs in the "producer" stage.
3057 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3058 ir_variable
*const var
= node
->as_variable();
3060 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3063 if (var
->data
.explicit_location
&&
3064 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3065 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3066 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3067 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3071 /* Match inputs to outputs */
3072 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3073 ir_variable
*const input
= node
->as_variable();
3075 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3078 ir_variable
*output
= NULL
;
3079 if (input
->data
.explicit_location
3080 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3081 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3082 [input
->data
.location_frac
];
3084 if (output
!= NULL
){
3085 input
->data
.is_unmatched_generic_inout
= 0;
3086 output
->data
.is_unmatched_generic_inout
= 0;
3093 * Store the gl_FragDepth layout in the gl_shader_program struct.
3096 store_fragdepth_layout(struct gl_shader_program
*prog
)
3098 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3102 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3104 /* We don't look up the gl_FragDepth symbol directly because if
3105 * gl_FragDepth is not used in the shader, it's removed from the IR.
3106 * However, the symbol won't be removed from the symbol table.
3108 * We're only interested in the cases where the variable is NOT removed
3111 foreach_in_list(ir_instruction
, node
, ir
) {
3112 ir_variable
*const var
= node
->as_variable();
3114 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3118 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3119 switch (var
->data
.depth_layout
) {
3120 case ir_depth_layout_none
:
3121 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3123 case ir_depth_layout_any
:
3124 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3126 case ir_depth_layout_greater
:
3127 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3129 case ir_depth_layout_less
:
3130 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3132 case ir_depth_layout_unchanged
:
3133 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3144 * Validate the resources used by a program versus the implementation limits
3147 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3149 unsigned total_uniform_blocks
= 0;
3150 unsigned total_shader_storage_blocks
= 0;
3152 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3153 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3158 if (sh
->Program
->info
.num_textures
>
3159 ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3160 linker_error(prog
, "Too many %s shader texture samplers\n",
3161 _mesa_shader_stage_to_string(i
));
3164 if (sh
->num_uniform_components
>
3165 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3166 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3167 linker_warning(prog
, "Too many %s shader default uniform block "
3168 "components, but the driver will try to optimize "
3169 "them out; this is non-portable out-of-spec "
3171 _mesa_shader_stage_to_string(i
));
3173 linker_error(prog
, "Too many %s shader default uniform block "
3175 _mesa_shader_stage_to_string(i
));
3179 if (sh
->num_combined_uniform_components
>
3180 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3181 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3182 linker_warning(prog
, "Too many %s shader uniform components, "
3183 "but the driver will try to optimize them out; "
3184 "this is non-portable out-of-spec behavior\n",
3185 _mesa_shader_stage_to_string(i
));
3187 linker_error(prog
, "Too many %s shader uniform components\n",
3188 _mesa_shader_stage_to_string(i
));
3192 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3193 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3195 const unsigned max_uniform_blocks
=
3196 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3197 if (max_uniform_blocks
< sh
->Program
->info
.num_ubos
) {
3198 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3199 _mesa_shader_stage_to_string(i
),
3200 sh
->Program
->info
.num_ubos
, max_uniform_blocks
);
3203 const unsigned max_shader_storage_blocks
=
3204 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3205 if (max_shader_storage_blocks
< sh
->Program
->info
.num_ssbos
) {
3206 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3207 _mesa_shader_stage_to_string(i
),
3208 sh
->Program
->info
.num_ssbos
, max_shader_storage_blocks
);
3212 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3213 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3214 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3217 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3218 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3219 total_shader_storage_blocks
,
3220 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3223 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3224 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3225 ctx
->Const
.MaxUniformBlockSize
) {
3226 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3227 prog
->data
->UniformBlocks
[i
].Name
,
3228 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3229 ctx
->Const
.MaxUniformBlockSize
);
3233 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3234 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3235 ctx
->Const
.MaxShaderStorageBlockSize
) {
3236 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3237 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3238 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3239 ctx
->Const
.MaxShaderStorageBlockSize
);
3245 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3247 unsigned mask
= prog
->data
->linked_stages
;
3249 const int i
= u_bit_scan(&mask
);
3250 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3252 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3253 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3256 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3262 if (p
->sh
.NumSubroutineFunctions
== 0) {
3263 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3266 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3267 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3268 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3269 if (fn
->types
[k
] == uni
->type
) {
3275 uni
->num_compatible_subroutines
= count
;
3281 check_subroutine_resources(struct gl_shader_program
*prog
)
3283 unsigned mask
= prog
->data
->linked_stages
;
3285 const int i
= u_bit_scan(&mask
);
3286 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3288 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3289 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3290 _mesa_shader_stage_to_string(i
));
3295 * Validate shader image resources.
3298 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3300 unsigned total_image_units
= 0;
3301 unsigned fragment_outputs
= 0;
3302 unsigned total_shader_storage_blocks
= 0;
3304 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3307 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3308 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3311 if (sh
->Program
->info
.num_images
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3312 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3313 _mesa_shader_stage_to_string(i
),
3314 sh
->Program
->info
.num_images
,
3315 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3317 total_image_units
+= sh
->Program
->info
.num_images
;
3318 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3320 if (i
== MESA_SHADER_FRAGMENT
) {
3321 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3322 ir_variable
*var
= node
->as_variable();
3323 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3324 /* since there are no double fs outputs - pass false */
3325 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3331 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3332 linker_error(prog
, "Too many combined image uniforms\n");
3334 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3335 ctx
->Const
.MaxCombinedShaderOutputResources
)
3336 linker_error(prog
, "Too many combined image uniforms, shader storage "
3337 " buffers and fragment outputs\n");
3342 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3343 * for a variable, checks for overlaps between other uniforms using explicit
3347 reserve_explicit_locations(struct gl_shader_program
*prog
,
3348 string_to_uint_map
*map
, ir_variable
*var
)
3350 unsigned slots
= var
->type
->uniform_locations();
3351 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3352 unsigned return_value
= slots
;
3354 /* Resize remap table if locations do not fit in the current one. */
3355 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3356 prog
->UniformRemapTable
=
3357 reralloc(prog
, prog
->UniformRemapTable
,
3358 gl_uniform_storage
*,
3361 if (!prog
->UniformRemapTable
) {
3362 linker_error(prog
, "Out of memory during linking.\n");
3366 /* Initialize allocated space. */
3367 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3368 prog
->UniformRemapTable
[i
] = NULL
;
3370 prog
->NumUniformRemapTable
= max_loc
+ 1;
3373 for (unsigned i
= 0; i
< slots
; i
++) {
3374 unsigned loc
= var
->data
.location
+ i
;
3376 /* Check if location is already used. */
3377 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3379 /* Possibly same uniform from a different stage, this is ok. */
3381 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3386 /* ARB_explicit_uniform_location specification states:
3388 * "No two default-block uniform variables in the program can have
3389 * the same location, even if they are unused, otherwise a compiler
3390 * or linker error will be generated."
3393 "location qualifier for uniform %s overlaps "
3394 "previously used location\n",
3399 /* Initialize location as inactive before optimization
3400 * rounds and location assignment.
3402 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3405 /* Note, base location used for arrays. */
3406 map
->put(var
->data
.location
, var
->name
);
3408 return return_value
;
3412 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3413 struct gl_program
*p
,
3416 unsigned slots
= var
->type
->uniform_locations();
3417 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3419 /* Resize remap table if locations do not fit in the current one. */
3420 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3421 p
->sh
.SubroutineUniformRemapTable
=
3422 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3423 gl_uniform_storage
*,
3426 if (!p
->sh
.SubroutineUniformRemapTable
) {
3427 linker_error(prog
, "Out of memory during linking.\n");
3431 /* Initialize allocated space. */
3432 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3433 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3435 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3438 for (unsigned i
= 0; i
< slots
; i
++) {
3439 unsigned loc
= var
->data
.location
+ i
;
3441 /* Check if location is already used. */
3442 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3444 /* ARB_explicit_uniform_location specification states:
3445 * "No two subroutine uniform variables can have the same location
3446 * in the same shader stage, otherwise a compiler or linker error
3447 * will be generated."
3450 "location qualifier for uniform %s overlaps "
3451 "previously used location\n",
3456 /* Initialize location as inactive before optimization
3457 * rounds and location assignment.
3459 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3465 * Check and reserve all explicit uniform locations, called before
3466 * any optimizations happen to handle also inactive uniforms and
3467 * inactive array elements that may get trimmed away.
3470 check_explicit_uniform_locations(struct gl_context
*ctx
,
3471 struct gl_shader_program
*prog
)
3473 prog
->NumExplicitUniformLocations
= 0;
3475 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3478 /* This map is used to detect if overlapping explicit locations
3479 * occur with the same uniform (from different stage) or a different one.
3481 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3484 linker_error(prog
, "Out of memory during linking.\n");
3488 unsigned entries_total
= 0;
3489 unsigned mask
= prog
->data
->linked_stages
;
3491 const int i
= u_bit_scan(&mask
);
3492 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3494 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3495 ir_variable
*var
= node
->as_variable();
3496 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3499 if (var
->data
.explicit_location
) {
3501 if (var
->type
->without_array()->is_subroutine())
3502 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3504 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3508 entries_total
+= slots
;
3519 struct empty_uniform_block
*current_block
= NULL
;
3521 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3522 /* We found empty space in UniformRemapTable. */
3523 if (prog
->UniformRemapTable
[i
] == NULL
) {
3524 /* We've found the beginning of a new continous block of empty slots */
3525 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3526 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3527 current_block
->start
= i
;
3528 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3529 ¤t_block
->link
);
3532 /* The current block continues, so we simply increment its slots */
3533 current_block
->slots
++;
3538 prog
->NumExplicitUniformLocations
= entries_total
;
3542 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3543 GLenum type
, const char *name
)
3545 bool found_interface
= false;
3546 unsigned block_name_len
= 0;
3547 const char *block_name_dot
= strchr(name
, '.');
3549 /* These rules only apply to buffer variables. So we return
3550 * true for the rest of types.
3552 if (type
!= GL_BUFFER_VARIABLE
)
3555 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
3556 const char *block_name
= shProg
->data
->ShaderStorageBlocks
[i
].Name
;
3557 block_name_len
= strlen(block_name
);
3559 const char *block_square_bracket
= strchr(block_name
, '[');
3560 if (block_square_bracket
) {
3561 /* The block is part of an array of named interfaces,
3562 * for the name comparison we ignore the "[x]" part.
3564 block_name_len
-= strlen(block_square_bracket
);
3567 if (block_name_dot
) {
3568 /* Check if the variable name starts with the interface
3569 * name. The interface name (if present) should have the
3570 * length than the interface block name we are comparing to.
3572 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3573 if (len
!= block_name_len
)
3577 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3578 found_interface
= true;
3583 /* We remove the interface name from the buffer variable name,
3584 * including the dot that follows it.
3586 if (found_interface
)
3587 name
= name
+ block_name_len
+ 1;
3589 /* The ARB_program_interface_query spec says:
3591 * "For an active shader storage block member declared as an array, an
3592 * entry will be generated only for the first array element, regardless
3593 * of its type. For arrays of aggregate types, the enumeration rules
3594 * are applied recursively for the single enumerated array element."
3596 const char *struct_first_dot
= strchr(name
, '.');
3597 const char *first_square_bracket
= strchr(name
, '[');
3599 /* The buffer variable is on top level and it is not an array */
3600 if (!first_square_bracket
) {
3602 /* The shader storage block member is a struct, then generate the entry */
3603 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3606 /* Shader storage block member is an array, only generate an entry for the
3607 * first array element.
3609 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3617 add_program_resource(struct gl_shader_program
*prog
,
3618 struct set
*resource_set
,
3619 GLenum type
, const void *data
, uint8_t stages
)
3623 /* If resource already exists, do not add it again. */
3624 if (_mesa_set_search(resource_set
, data
))
3627 prog
->data
->ProgramResourceList
=
3628 reralloc(prog
->data
,
3629 prog
->data
->ProgramResourceList
,
3630 gl_program_resource
,
3631 prog
->data
->NumProgramResourceList
+ 1);
3633 if (!prog
->data
->ProgramResourceList
) {
3634 linker_error(prog
, "Out of memory during linking.\n");
3638 struct gl_program_resource
*res
=
3639 &prog
->data
->ProgramResourceList
[prog
->data
->NumProgramResourceList
];
3643 res
->StageReferences
= stages
;
3645 prog
->data
->NumProgramResourceList
++;
3647 _mesa_set_add(resource_set
, data
);
3652 /* Function checks if a variable var is a packed varying and
3653 * if given name is part of packed varying's list.
3655 * If a variable is a packed varying, it has a name like
3656 * 'packed:a,b,c' where a, b and c are separate variables.
3659 included_in_packed_varying(ir_variable
*var
, const char *name
)
3661 if (strncmp(var
->name
, "packed:", 7) != 0)
3664 char *list
= strdup(var
->name
+ 7);
3669 char *token
= strtok_r(list
, ",", &saveptr
);
3671 if (strcmp(token
, name
) == 0) {
3675 token
= strtok_r(NULL
, ",", &saveptr
);
3682 * Function builds a stage reference bitmask from variable name.
3685 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3690 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3691 * used for reference mask in gl_program_resource will need to be changed.
3693 assert(MESA_SHADER_STAGES
< 8);
3695 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3696 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3700 /* Shader symbol table may contain variables that have
3701 * been optimized away. Search IR for the variable instead.
3703 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3704 ir_variable
*var
= node
->as_variable();
3706 unsigned baselen
= strlen(var
->name
);
3708 if (included_in_packed_varying(var
, name
)) {
3713 /* Type needs to match if specified, otherwise we might
3714 * pick a variable with same name but different interface.
3716 if (var
->data
.mode
!= mode
)
3719 if (strncmp(var
->name
, name
, baselen
) == 0) {
3720 /* Check for exact name matches but also check for arrays and
3723 if (name
[baselen
] == '\0' ||
3724 name
[baselen
] == '[' ||
3725 name
[baselen
] == '.') {
3737 * Create gl_shader_variable from ir_variable class.
3739 static gl_shader_variable
*
3740 create_shader_variable(struct gl_shader_program
*shProg
,
3741 const ir_variable
*in
,
3742 const char *name
, const glsl_type
*type
,
3743 const glsl_type
*interface_type
,
3744 bool use_implicit_location
, int location
,
3745 const glsl_type
*outermost_struct_type
)
3747 /* Allocate zero-initialized memory to ensure that bitfield padding
3750 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3754 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3755 * expect to see gl_VertexID in the program resource list. Pretend.
3757 if (in
->data
.mode
== ir_var_system_value
&&
3758 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3759 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3760 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3761 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3762 (in
->data
.mode
== ir_var_system_value
&&
3763 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3764 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3765 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3766 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3767 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3768 (in
->data
.mode
== ir_var_system_value
&&
3769 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3770 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3771 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3773 out
->name
= ralloc_strdup(shProg
, name
);
3779 /* The ARB_program_interface_query spec says:
3781 * "Not all active variables are assigned valid locations; the
3782 * following variables will have an effective location of -1:
3784 * * uniforms declared as atomic counters;
3786 * * members of a uniform block;
3788 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3790 * * inputs or outputs not declared with a "location" layout
3791 * qualifier, except for vertex shader inputs and fragment shader
3794 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3795 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3798 out
->location
= location
;
3802 out
->outermost_struct_type
= outermost_struct_type
;
3803 out
->interface_type
= interface_type
;
3804 out
->component
= in
->data
.location_frac
;
3805 out
->index
= in
->data
.index
;
3806 out
->patch
= in
->data
.patch
;
3807 out
->mode
= in
->data
.mode
;
3808 out
->interpolation
= in
->data
.interpolation
;
3809 out
->explicit_location
= in
->data
.explicit_location
;
3810 out
->precision
= in
->data
.precision
;
3816 add_shader_variable(const struct gl_context
*ctx
,
3817 struct gl_shader_program
*shProg
,
3818 struct set
*resource_set
,
3819 unsigned stage_mask
,
3820 GLenum programInterface
, ir_variable
*var
,
3821 const char *name
, const glsl_type
*type
,
3822 bool use_implicit_location
, int location
,
3823 bool inouts_share_location
,
3824 const glsl_type
*outermost_struct_type
= NULL
)
3826 const glsl_type
*interface_type
= var
->get_interface_type();
3828 if (outermost_struct_type
== NULL
) {
3829 if (var
->data
.from_named_ifc_block
) {
3830 const char *interface_name
= interface_type
->name
;
3832 if (interface_type
->is_array()) {
3833 /* Issue #16 of the ARB_program_interface_query spec says:
3835 * "* If a variable is a member of an interface block without an
3836 * instance name, it is enumerated using just the variable name.
3838 * * If a variable is a member of an interface block with an
3839 * instance name, it is enumerated as "BlockName.Member", where
3840 * "BlockName" is the name of the interface block (not the
3841 * instance name) and "Member" is the name of the variable."
3843 * In particular, it indicates that it should be "BlockName",
3844 * not "BlockName[array length]". The conformance suite and
3845 * dEQP both require this behavior.
3847 * Here, we unwrap the extra array level added by named interface
3848 * block array lowering so we have the correct variable type. We
3849 * also unwrap the interface type when constructing the name.
3851 * We leave interface_type the same so that ES 3.x SSO pipeline
3852 * validation can enforce the rules requiring array length to
3853 * match on interface blocks.
3855 type
= type
->fields
.array
;
3857 interface_name
= interface_type
->fields
.array
->name
;
3860 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3864 switch (type
->base_type
) {
3865 case GLSL_TYPE_STRUCT
: {
3866 /* The ARB_program_interface_query spec says:
3868 * "For an active variable declared as a structure, a separate entry
3869 * will be generated for each active structure member. The name of
3870 * each entry is formed by concatenating the name of the structure,
3871 * the "." character, and the name of the structure member. If a
3872 * structure member to enumerate is itself a structure or array,
3873 * these enumeration rules are applied recursively."
3875 if (outermost_struct_type
== NULL
)
3876 outermost_struct_type
= type
;
3878 unsigned field_location
= location
;
3879 for (unsigned i
= 0; i
< type
->length
; i
++) {
3880 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3881 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3882 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3883 stage_mask
, programInterface
,
3884 var
, field_name
, field
->type
,
3885 use_implicit_location
, field_location
,
3886 false, outermost_struct_type
))
3889 field_location
+= field
->type
->count_attribute_slots(false);
3894 case GLSL_TYPE_ARRAY
: {
3895 /* The ARB_program_interface_query spec says:
3897 * "For an active variable declared as an array of basic types, a
3898 * single entry will be generated, with its name string formed by
3899 * concatenating the name of the array and the string "[0]"."
3901 * "For an active variable declared as an array of an aggregate data
3902 * type (structures or arrays), a separate entry will be generated
3903 * for each active array element, unless noted immediately below.
3904 * The name of each entry is formed by concatenating the name of
3905 * the array, the "[" character, an integer identifying the element
3906 * number, and the "]" character. These enumeration rules are
3907 * applied recursively, treating each enumerated array element as a
3908 * separate active variable."
3910 const struct glsl_type
*array_type
= type
->fields
.array
;
3911 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3912 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3913 unsigned elem_location
= location
;
3914 unsigned stride
= inouts_share_location
? 0 :
3915 array_type
->count_attribute_slots(false);
3916 for (unsigned i
= 0; i
< type
->length
; i
++) {
3917 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3918 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3919 stage_mask
, programInterface
,
3920 var
, elem
, array_type
,
3921 use_implicit_location
, elem_location
,
3922 false, outermost_struct_type
))
3924 elem_location
+= stride
;
3932 /* The ARB_program_interface_query spec says:
3934 * "For an active variable declared as a single instance of a basic
3935 * type, a single entry will be generated, using the variable name
3936 * from the shader source."
3938 gl_shader_variable
*sha_v
=
3939 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3940 use_implicit_location
, location
,
3941 outermost_struct_type
);
3945 return add_program_resource(shProg
, resource_set
,
3946 programInterface
, sha_v
, stage_mask
);
3952 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3954 if (!var
->data
.patch
&&
3955 ((var
->data
.mode
== ir_var_shader_out
&&
3956 stage
== MESA_SHADER_TESS_CTRL
) ||
3957 (var
->data
.mode
== ir_var_shader_in
&&
3958 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3959 stage
== MESA_SHADER_GEOMETRY
))))
3966 add_interface_variables(const struct gl_context
*ctx
,
3967 struct gl_shader_program
*shProg
,
3968 struct set
*resource_set
,
3969 unsigned stage
, GLenum programInterface
)
3971 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3973 foreach_in_list(ir_instruction
, node
, ir
) {
3974 ir_variable
*var
= node
->as_variable();
3976 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3981 switch (var
->data
.mode
) {
3982 case ir_var_system_value
:
3983 case ir_var_shader_in
:
3984 if (programInterface
!= GL_PROGRAM_INPUT
)
3986 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3987 : int(VARYING_SLOT_VAR0
);
3989 case ir_var_shader_out
:
3990 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3992 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3993 : int(VARYING_SLOT_VAR0
);
3999 if (var
->data
.patch
)
4000 loc_bias
= int(VARYING_SLOT_PATCH0
);
4002 /* Skip packed varyings, packed varyings are handled separately
4003 * by add_packed_varyings.
4005 if (strncmp(var
->name
, "packed:", 7) == 0)
4008 /* Skip fragdata arrays, these are handled separately
4009 * by add_fragdata_arrays.
4011 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
4014 const bool vs_input_or_fs_output
=
4015 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
4016 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
4018 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4019 1 << stage
, programInterface
,
4020 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
4021 var
->data
.location
- loc_bias
,
4022 inout_has_same_location(var
, stage
)))
4029 add_packed_varyings(const struct gl_context
*ctx
,
4030 struct gl_shader_program
*shProg
,
4031 struct set
*resource_set
,
4032 int stage
, GLenum type
)
4034 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
4037 if (!sh
|| !sh
->packed_varyings
)
4040 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4041 ir_variable
*var
= node
->as_variable();
4043 switch (var
->data
.mode
) {
4044 case ir_var_shader_in
:
4045 iface
= GL_PROGRAM_INPUT
;
4047 case ir_var_shader_out
:
4048 iface
= GL_PROGRAM_OUTPUT
;
4051 unreachable("unexpected type");
4054 if (type
== iface
) {
4055 const int stage_mask
=
4056 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4057 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4059 iface
, var
, var
->name
, var
->type
, false,
4060 var
->data
.location
- VARYING_SLOT_VAR0
,
4061 inout_has_same_location(var
, stage
)))
4070 add_fragdata_arrays(const struct gl_context
*ctx
,
4071 struct gl_shader_program
*shProg
,
4072 struct set
*resource_set
)
4074 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4076 if (!sh
|| !sh
->fragdata_arrays
)
4079 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4080 ir_variable
*var
= node
->as_variable();
4082 assert(var
->data
.mode
== ir_var_shader_out
);
4084 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4085 1 << MESA_SHADER_FRAGMENT
,
4086 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4087 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4096 get_top_level_name(const char *name
)
4098 const char *first_dot
= strchr(name
, '.');
4099 const char *first_square_bracket
= strchr(name
, '[');
4102 /* The ARB_program_interface_query spec says:
4104 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4105 * the number of active array elements of the top-level shader storage
4106 * block member containing to the active variable is written to
4107 * <params>. If the top-level block member is not declared as an
4108 * array, the value one is written to <params>. If the top-level block
4109 * member is an array with no declared size, the value zero is written
4113 /* The buffer variable is on top level.*/
4114 if (!first_square_bracket
&& !first_dot
)
4115 name_size
= strlen(name
);
4116 else if ((!first_square_bracket
||
4117 (first_dot
&& first_dot
< first_square_bracket
)))
4118 name_size
= first_dot
- name
;
4120 name_size
= first_square_bracket
- name
;
4122 return strndup(name
, name_size
);
4126 get_var_name(const char *name
)
4128 const char *first_dot
= strchr(name
, '.');
4131 return strdup(name
);
4133 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4137 is_top_level_shader_storage_block_member(const char* name
,
4138 const char* interface_name
,
4139 const char* field_name
)
4141 bool result
= false;
4143 /* If the given variable is already a top-level shader storage
4144 * block member, then return array_size = 1.
4145 * We could have two possibilities: if we have an instanced
4146 * shader storage block or not instanced.
4148 * For the first, we check create a name as it was in top level and
4149 * compare it with the real name. If they are the same, then
4150 * the variable is already at top-level.
4152 * Full instanced name is: interface name + '.' + var name +
4155 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4156 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4157 if (!full_instanced_name
) {
4158 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4162 snprintf(full_instanced_name
, name_length
, "%s.%s",
4163 interface_name
, field_name
);
4165 /* Check if its top-level shader storage block member of an
4166 * instanced interface block, or of a unnamed interface block.
4168 if (strcmp(name
, full_instanced_name
) == 0 ||
4169 strcmp(name
, field_name
) == 0)
4172 free(full_instanced_name
);
4177 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4178 char *interface_name
, char *var_name
)
4180 /* The ARB_program_interface_query spec says:
4182 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4183 * the number of active array elements of the top-level shader storage
4184 * block member containing to the active variable is written to
4185 * <params>. If the top-level block member is not declared as an
4186 * array, the value one is written to <params>. If the top-level block
4187 * member is an array with no declared size, the value zero is written
4190 if (is_top_level_shader_storage_block_member(uni
->name
,
4194 else if (field
->type
->is_unsized_array())
4196 else if (field
->type
->is_array())
4197 return field
->type
->length
;
4203 get_array_stride(struct gl_context
*ctx
, struct gl_uniform_storage
*uni
,
4204 const glsl_type
*interface
, const glsl_struct_field
*field
,
4205 char *interface_name
, char *var_name
)
4207 /* The ARB_program_interface_query spec says:
4209 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4210 * identifying the stride between array elements of the top-level
4211 * shader storage block member containing the active variable is
4212 * written to <params>. For top-level block members declared as
4213 * arrays, the value written is the difference, in basic machine units,
4214 * between the offsets of the active variable for consecutive elements
4215 * in the top-level array. For top-level block members not declared as
4216 * an array, zero is written to <params>."
4218 if (field
->type
->is_array()) {
4219 const enum glsl_matrix_layout matrix_layout
=
4220 glsl_matrix_layout(field
->matrix_layout
);
4221 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4222 const glsl_type
*array_type
= field
->type
->fields
.array
;
4224 if (is_top_level_shader_storage_block_member(uni
->name
,
4229 if (GLSL_INTERFACE_PACKING_STD140
==
4231 get_internal_ifc_packing(ctx
->Const
.UseSTD430AsDefaultPacking
)) {
4232 if (array_type
->is_record() || array_type
->is_array())
4233 return glsl_align(array_type
->std140_size(row_major
), 16);
4235 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4237 return array_type
->std430_array_stride(row_major
);
4244 calculate_array_size_and_stride(struct gl_context
*ctx
,
4245 struct gl_shader_program
*shProg
,
4246 struct gl_uniform_storage
*uni
)
4248 int block_index
= uni
->block_index
;
4249 int array_size
= -1;
4250 int array_stride
= -1;
4251 char *var_name
= get_top_level_name(uni
->name
);
4252 char *interface_name
=
4253 get_top_level_name(uni
->is_shader_storage
?
4254 shProg
->data
->ShaderStorageBlocks
[block_index
].Name
:
4255 shProg
->data
->UniformBlocks
[block_index
].Name
);
4257 if (strcmp(var_name
, interface_name
) == 0) {
4258 /* Deal with instanced array of SSBOs */
4259 char *temp_name
= get_var_name(uni
->name
);
4261 linker_error(shProg
, "Out of memory during linking.\n");
4262 goto write_top_level_array_size_and_stride
;
4265 var_name
= get_top_level_name(temp_name
);
4268 linker_error(shProg
, "Out of memory during linking.\n");
4269 goto write_top_level_array_size_and_stride
;
4273 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4274 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4278 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4279 ir_variable
*var
= node
->as_variable();
4280 if (!var
|| !var
->get_interface_type() ||
4281 var
->data
.mode
!= ir_var_shader_storage
)
4284 const glsl_type
*interface
= var
->get_interface_type();
4286 if (strcmp(interface_name
, interface
->name
) != 0)
4289 for (unsigned i
= 0; i
< interface
->length
; i
++) {
4290 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
4291 if (strcmp(field
->name
, var_name
) != 0)
4294 array_stride
= get_array_stride(ctx
, uni
, interface
, field
,
4295 interface_name
, var_name
);
4296 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4297 goto write_top_level_array_size_and_stride
;
4301 write_top_level_array_size_and_stride
:
4302 free(interface_name
);
4304 uni
->top_level_array_stride
= array_stride
;
4305 uni
->top_level_array_size
= array_size
;
4309 * Builds up a list of program resources that point to existing
4313 build_program_resource_list(struct gl_context
*ctx
,
4314 struct gl_shader_program
*shProg
)
4316 /* Rebuild resource list. */
4317 if (shProg
->data
->ProgramResourceList
) {
4318 ralloc_free(shProg
->data
->ProgramResourceList
);
4319 shProg
->data
->ProgramResourceList
= NULL
;
4320 shProg
->data
->NumProgramResourceList
= 0;
4323 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4325 /* Determine first input and final output stage. These are used to
4326 * detect which variables should be enumerated in the resource list
4327 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4329 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4330 if (!shProg
->_LinkedShaders
[i
])
4332 if (input_stage
== MESA_SHADER_STAGES
)
4337 /* Empty shader, no resources. */
4338 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4341 struct set
*resource_set
= _mesa_set_create(NULL
,
4343 _mesa_key_pointer_equal
);
4345 /* Program interface needs to expose varyings in case of SSO. */
4346 if (shProg
->SeparateShader
) {
4347 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4348 input_stage
, GL_PROGRAM_INPUT
))
4351 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4352 output_stage
, GL_PROGRAM_OUTPUT
))
4356 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4359 /* Add inputs and outputs to the resource list. */
4360 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4361 input_stage
, GL_PROGRAM_INPUT
))
4364 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4365 output_stage
, GL_PROGRAM_OUTPUT
))
4368 if (shProg
->last_vert_prog
) {
4369 struct gl_transform_feedback_info
*linked_xfb
=
4370 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4372 /* Add transform feedback varyings. */
4373 if (linked_xfb
->NumVarying
> 0) {
4374 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4375 if (!add_program_resource(shProg
, resource_set
,
4376 GL_TRANSFORM_FEEDBACK_VARYING
,
4377 &linked_xfb
->Varyings
[i
], 0))
4382 /* Add transform feedback buffers. */
4383 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4384 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4385 linked_xfb
->Buffers
[i
].Binding
= i
;
4386 if (!add_program_resource(shProg
, resource_set
,
4387 GL_TRANSFORM_FEEDBACK_BUFFER
,
4388 &linked_xfb
->Buffers
[i
], 0))
4394 /* Add uniforms from uniform storage. */
4395 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4396 /* Do not add uniforms internally used by Mesa. */
4397 if (shProg
->data
->UniformStorage
[i
].hidden
)
4401 build_stageref(shProg
, shProg
->data
->UniformStorage
[i
].name
,
4404 /* Add stagereferences for uniforms in a uniform block. */
4405 bool is_shader_storage
=
4406 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4407 int block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4408 if (block_index
!= -1) {
4409 stageref
|= is_shader_storage
?
4410 shProg
->data
->ShaderStorageBlocks
[block_index
].stageref
:
4411 shProg
->data
->UniformBlocks
[block_index
].stageref
;
4414 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4415 if (!should_add_buffer_variable(shProg
, type
,
4416 shProg
->data
->UniformStorage
[i
].name
))
4419 if (is_shader_storage
) {
4420 calculate_array_size_and_stride(ctx
, shProg
,
4421 &shProg
->data
->UniformStorage
[i
]);
4424 if (!add_program_resource(shProg
, resource_set
, type
,
4425 &shProg
->data
->UniformStorage
[i
], stageref
))
4429 /* Add program uniform blocks. */
4430 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4431 if (!add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4432 &shProg
->data
->UniformBlocks
[i
], 0))
4436 /* Add program shader storage blocks. */
4437 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4438 if (!add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4439 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4443 /* Add atomic counter buffers. */
4444 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4445 if (!add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4446 &shProg
->data
->AtomicBuffers
[i
], 0))
4450 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4452 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4455 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4456 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4457 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4460 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4461 /* add shader subroutines */
4462 if (!add_program_resource(shProg
, resource_set
,
4463 type
, &shProg
->data
->UniformStorage
[i
], 0))
4468 unsigned mask
= shProg
->data
->linked_stages
;
4470 const int i
= u_bit_scan(&mask
);
4471 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4473 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4474 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4475 if (!add_program_resource(shProg
, resource_set
,
4476 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4481 _mesa_set_destroy(resource_set
, NULL
);
4485 * This check is done to make sure we allow only constant expression
4486 * indexing and "constant-index-expression" (indexing with an expression
4487 * that includes loop induction variable).
4490 validate_sampler_array_indexing(struct gl_context
*ctx
,
4491 struct gl_shader_program
*prog
)
4493 dynamic_sampler_array_indexing_visitor v
;
4494 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4495 if (prog
->_LinkedShaders
[i
] == NULL
)
4498 bool no_dynamic_indexing
=
4499 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4501 /* Search for array derefs in shader. */
4502 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4503 if (v
.uses_dynamic_sampler_array_indexing()) {
4504 const char *msg
= "sampler arrays indexed with non-constant "
4505 "expressions is forbidden in GLSL %s %u";
4506 /* Backend has indicated that it has no dynamic indexing support. */
4507 if (no_dynamic_indexing
) {
4508 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4509 prog
->data
->Version
);
4512 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4513 prog
->data
->Version
);
4521 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4523 unsigned mask
= prog
->data
->linked_stages
;
4525 const int i
= u_bit_scan(&mask
);
4526 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4528 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4529 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4530 ir_function
*fn
= node
->as_function();
4534 if (fn
->is_subroutine
)
4535 p
->sh
.NumSubroutineUniformTypes
++;
4537 if (!fn
->num_subroutine_types
)
4540 /* these should have been calculated earlier. */
4541 assert(fn
->subroutine_index
!= -1);
4542 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4543 linker_error(prog
, "Too many subroutine functions declared.\n");
4546 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4547 struct gl_subroutine_function
,
4548 p
->sh
.NumSubroutineFunctions
+ 1);
4549 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4550 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4551 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4552 ralloc_array(p
, const struct glsl_type
*,
4553 fn
->num_subroutine_types
);
4555 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4558 * "Each subroutine with an index qualifier in the shader must be
4559 * given a unique index, otherwise a compile or link error will be
4562 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4563 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4564 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4565 linker_error(prog
, "each subroutine index qualifier in the "
4566 "shader must be unique\n");
4570 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4571 fn
->subroutine_index
;
4573 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4574 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4576 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4577 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4578 p
->sh
.NumSubroutineFunctions
++;
4584 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4586 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4588 foreach_in_list(ir_instruction
, node
, ir
) {
4589 ir_variable
*const var
= node
->as_variable();
4591 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4594 /* Don't set always active on builtins that haven't been redeclared */
4595 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4598 var
->data
.always_active_io
= true;
4603 * When separate shader programs are enabled, only input/outputs between
4604 * the stages of a multi-stage separate program can be safely removed
4605 * from the shader interface. Other inputs/outputs must remain active.
4608 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4610 unsigned first
, last
;
4611 assert(prog
->SeparateShader
);
4613 first
= MESA_SHADER_STAGES
;
4616 /* Determine first and last stage. Excluding the compute stage */
4617 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4618 if (!prog
->_LinkedShaders
[i
])
4620 if (first
== MESA_SHADER_STAGES
)
4625 if (first
== MESA_SHADER_STAGES
)
4628 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4629 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4633 /* Prevent the removal of inputs to the first and outputs from the last
4634 * stage, unless they are the initial pipeline inputs or final pipeline
4635 * outputs, respectively.
4637 * The removal of IO between shaders in the same program is always
4640 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4641 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4642 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4643 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4648 link_and_validate_uniforms(struct gl_context
*ctx
,
4649 struct gl_shader_program
*prog
)
4651 update_array_sizes(prog
);
4652 link_assign_uniform_locations(prog
, ctx
);
4654 link_assign_atomic_counter_resources(ctx
, prog
);
4655 link_calculate_subroutine_compat(prog
);
4656 check_resources(ctx
, prog
);
4657 check_subroutine_resources(prog
);
4658 check_image_resources(ctx
, prog
);
4659 link_check_atomic_counter_resources(ctx
, prog
);
4663 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4664 struct gl_context
*ctx
,
4665 struct gl_shader_program
*prog
, void *mem_ctx
)
4667 /* Mark all generic shader inputs and outputs as unpaired. */
4668 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4669 if (prog
->_LinkedShaders
[i
] != NULL
) {
4670 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4674 unsigned prev
= first
;
4675 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4676 if (prog
->_LinkedShaders
[i
] == NULL
)
4679 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4680 prog
->_LinkedShaders
[i
]);
4684 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4685 MESA_SHADER_VERTEX
)) {
4689 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4690 MESA_SHADER_FRAGMENT
)) {
4694 prog
->last_vert_prog
= NULL
;
4695 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4696 if (prog
->_LinkedShaders
[i
] == NULL
)
4699 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4703 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4706 link_and_validate_uniforms(ctx
, prog
);
4708 if (!prog
->data
->LinkStatus
)
4711 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4712 if (prog
->_LinkedShaders
[i
] == NULL
)
4715 const struct gl_shader_compiler_options
*options
=
4716 &ctx
->Const
.ShaderCompilerOptions
[i
];
4718 if (options
->LowerBufferInterfaceBlocks
)
4719 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4720 options
->ClampBlockIndicesToArrayBounds
,
4721 ctx
->Const
.UseSTD430AsDefaultPacking
);
4723 if (i
== MESA_SHADER_COMPUTE
)
4724 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4726 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4727 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4734 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4737 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4738 /* Run it just once. */
4739 do_common_optimization(ir
, true, false,
4740 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4741 ctx
->Const
.NativeIntegers
);
4743 /* Repeat it until it stops making changes. */
4744 while (do_common_optimization(ir
, true, false,
4745 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4746 ctx
->Const
.NativeIntegers
))
4752 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4754 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4755 prog
->data
->Validated
= false;
4757 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4759 * "Linking can fail for a variety of reasons as specified in the
4760 * OpenGL Shading Language Specification, as well as any of the
4761 * following reasons:
4763 * - No shader objects are attached to program."
4765 * The Compatibility Profile specification does not list the error. In
4766 * Compatibility Profile missing shader stages are replaced by
4767 * fixed-function. This applies to the case where all stages are
4770 if (prog
->NumShaders
== 0) {
4771 if (ctx
->API
!= API_OPENGL_COMPAT
)
4772 linker_error(prog
, "no shaders attached to the program\n");
4776 #ifdef ENABLE_SHADER_CACHE
4777 if (shader_cache_read_program_metadata(ctx
, prog
))
4781 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4783 prog
->ARB_fragment_coord_conventions_enable
= false;
4785 /* Separate the shaders into groups based on their type.
4787 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4788 unsigned num_shaders
[MESA_SHADER_STAGES
];
4790 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4791 shader_list
[i
] = (struct gl_shader
**)
4792 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4796 unsigned min_version
= UINT_MAX
;
4797 unsigned max_version
= 0;
4798 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4799 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4800 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4802 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4803 linker_error(prog
, "all shaders must use same shading "
4804 "language version\n");
4808 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4809 prog
->ARB_fragment_coord_conventions_enable
= true;
4812 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4813 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4814 num_shaders
[shader_type
]++;
4817 /* In desktop GLSL, different shader versions may be linked together. In
4818 * GLSL ES, all shader versions must be the same.
4820 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4821 linker_error(prog
, "all shaders must use same shading "
4822 "language version\n");
4826 prog
->data
->Version
= max_version
;
4827 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4829 /* Some shaders have to be linked with some other shaders present.
4831 if (!prog
->SeparateShader
) {
4832 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4833 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4834 linker_error(prog
, "Geometry shader must be linked with "
4838 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4839 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4840 linker_error(prog
, "Tessellation evaluation shader must be linked "
4841 "with vertex shader\n");
4844 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4845 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4846 linker_error(prog
, "Tessellation control shader must be linked with "
4851 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4853 * "Linking can fail for [...] any of the following reasons:
4855 * * program contains an object to form a tessellation control
4856 * shader [...] and [...] the program is not separable and
4857 * contains no object to form a tessellation evaluation shader"
4859 * The OpenGL spec is contradictory. It allows linking without a tess
4860 * eval shader, but that can only be used with transform feedback and
4861 * rasterization disabled. However, transform feedback isn't allowed
4862 * with GL_PATCHES, so it can't be used.
4864 * More investigation showed that the idea of transform feedback after
4865 * a tess control shader was dropped, because some hw vendors couldn't
4866 * support tessellation without a tess eval shader, but the linker
4867 * section wasn't updated to reflect that.
4869 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4872 * Do what's reasonable and always require a tess eval shader if a tess
4873 * control shader is present.
4875 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4876 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4877 linker_error(prog
, "Tessellation control shader must be linked with "
4878 "tessellation evaluation shader\n");
4883 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4884 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4885 linker_error(prog
, "GLSL ES requires non-separable programs "
4886 "containing a tessellation evaluation shader to also "
4887 "be linked with a tessellation control shader\n");
4893 /* Compute shaders have additional restrictions. */
4894 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4895 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4896 linker_error(prog
, "Compute shaders may not be linked with any other "
4897 "type of shader\n");
4900 /* Link all shaders for a particular stage and validate the result.
4902 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4903 if (num_shaders
[stage
] > 0) {
4904 gl_linked_shader
*const sh
=
4905 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4906 num_shaders
[stage
], false);
4908 if (!prog
->data
->LinkStatus
) {
4910 _mesa_delete_linked_shader(ctx
, sh
);
4915 case MESA_SHADER_VERTEX
:
4916 validate_vertex_shader_executable(prog
, sh
, ctx
);
4918 case MESA_SHADER_TESS_CTRL
:
4919 /* nothing to be done */
4921 case MESA_SHADER_TESS_EVAL
:
4922 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4924 case MESA_SHADER_GEOMETRY
:
4925 validate_geometry_shader_executable(prog
, sh
, ctx
);
4927 case MESA_SHADER_FRAGMENT
:
4928 validate_fragment_shader_executable(prog
, sh
);
4931 if (!prog
->data
->LinkStatus
) {
4933 _mesa_delete_linked_shader(ctx
, sh
);
4937 prog
->_LinkedShaders
[stage
] = sh
;
4938 prog
->data
->linked_stages
|= 1 << stage
;
4942 /* Here begins the inter-stage linking phase. Some initial validation is
4943 * performed, then locations are assigned for uniforms, attributes, and
4946 cross_validate_uniforms(prog
);
4947 if (!prog
->data
->LinkStatus
)
4950 unsigned first
, last
, prev
;
4952 first
= MESA_SHADER_STAGES
;
4955 /* Determine first and last stage. */
4956 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4957 if (!prog
->_LinkedShaders
[i
])
4959 if (first
== MESA_SHADER_STAGES
)
4964 check_explicit_uniform_locations(ctx
, prog
);
4965 link_assign_subroutine_types(prog
);
4967 if (!prog
->data
->LinkStatus
)
4970 resize_tes_inputs(ctx
, prog
);
4972 /* Validate the inputs of each stage with the output of the preceding
4976 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4977 if (prog
->_LinkedShaders
[i
] == NULL
)
4980 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4981 prog
->_LinkedShaders
[i
]);
4982 if (!prog
->data
->LinkStatus
)
4985 cross_validate_outputs_to_inputs(ctx
, prog
,
4986 prog
->_LinkedShaders
[prev
],
4987 prog
->_LinkedShaders
[i
]);
4988 if (!prog
->data
->LinkStatus
)
4994 /* The cross validation of outputs/inputs above validates explicit locations
4995 * but for SSO programs we need to do this also for the inputs in the
4996 * first stage and outputs of the last stage included in the program, since
4997 * there is no cross validation for these.
4999 if (prog
->SeparateShader
)
5000 validate_sso_explicit_locations(ctx
, prog
,
5001 (gl_shader_stage
) first
,
5002 (gl_shader_stage
) last
);
5004 /* Cross-validate uniform blocks between shader stages */
5005 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
5006 if (!prog
->data
->LinkStatus
)
5009 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5010 if (prog
->_LinkedShaders
[i
] != NULL
)
5011 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
5014 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5015 * it before optimization because we want most of the checks to get
5016 * dropped thanks to constant propagation.
5018 * This rule also applies to GLSL ES 3.00.
5020 if (max_version
>= (prog
->IsES
? 300 : 130)) {
5021 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
5023 lower_discard_flow(sh
->ir
);
5027 if (prog
->SeparateShader
)
5028 disable_varying_optimizations_for_sso(prog
);
5031 if (!interstage_cross_validate_uniform_blocks(prog
, false))
5035 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5038 /* Do common optimization before assigning storage for attributes,
5039 * uniforms, and varyings. Later optimization could possibly make
5040 * some of that unused.
5042 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5043 if (prog
->_LinkedShaders
[i
] == NULL
)
5046 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5047 if (!prog
->data
->LinkStatus
)
5050 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5051 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5054 if (ctx
->Const
.LowerTessLevel
) {
5055 lower_tess_level(prog
->_LinkedShaders
[i
]);
5058 /* Call opts before lowering const arrays to uniforms so we can const
5059 * propagate any elements accessed directly.
5061 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5063 /* Call opts after lowering const arrays to copy propagate things. */
5064 if (lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
))
5065 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5067 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5070 /* Validation for special cases where we allow sampler array indexing
5071 * with loop induction variable. This check emits a warning or error
5072 * depending if backend can handle dynamic indexing.
5074 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
5075 (prog
->IsES
&& prog
->data
->Version
< 300)) {
5076 if (!validate_sampler_array_indexing(ctx
, prog
))
5080 /* Check and validate stream emissions in geometry shaders */
5081 validate_geometry_shader_emissions(ctx
, prog
);
5083 store_fragdepth_layout(prog
);
5085 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5088 /* Linking varyings can cause some extra, useless swizzles to be generated
5089 * due to packing and unpacking.
5091 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5092 if (prog
->_LinkedShaders
[i
] == NULL
)
5095 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5098 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5099 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5100 * anything about shader linking when one of the shaders (vertex or
5101 * fragment shader) is absent. So, the extension shouldn't change the
5102 * behavior specified in GLSL specification.
5104 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5105 * "Linking can fail for a variety of reasons as specified in the
5106 * OpenGL ES Shading Language Specification, as well as any of the
5107 * following reasons:
5111 * * program contains objects to form either a vertex shader or
5112 * fragment shader, and program is not separable, and does not
5113 * contain objects to form both a vertex shader and fragment
5116 * However, the only scenario in 3.1+ where we don't require them both is
5117 * when we have a compute shader. For example:
5119 * - No shaders is a link error.
5120 * - Geom or Tess without a Vertex shader is a link error which means we
5121 * always require a Vertex shader and hence a Fragment shader.
5122 * - Finally a Compute shader linked with any other stage is a link error.
5124 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5125 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5126 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5127 linker_error(prog
, "program lacks a vertex shader\n");
5128 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5129 linker_error(prog
, "program lacks a fragment shader\n");
5134 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5135 free(shader_list
[i
]);
5136 if (prog
->_LinkedShaders
[i
] == NULL
)
5139 /* Do a final validation step to make sure that the IR wasn't
5140 * invalidated by any modifications performed after intrastage linking.
5142 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5144 /* Retain any live IR, but trash the rest. */
5145 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5147 /* The symbol table in the linked shaders may contain references to
5148 * variables that were removed (e.g., unused uniforms). Since it may
5149 * contain junk, there is no possible valid use. Delete it and set the
5152 delete prog
->_LinkedShaders
[i
]->symbols
;
5153 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5156 ralloc_free(mem_ctx
);