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 "linker_util.h"
80 #include "link_varyings.h"
81 #include "ir_optimization.h"
82 #include "ir_rvalue_visitor.h"
83 #include "ir_uniform.h"
84 #include "builtin_functions.h"
85 #include "shader_cache.h"
86 #include "util/u_string.h"
87 #include "util/u_math.h"
89 #include "util/imports.h"
90 #include "main/shaderobj.h"
91 #include "main/enums.h"
92 #include "main/mtypes.h"
97 struct find_variable
{
101 find_variable(const char *name
) : name(name
), found(false) {}
105 * Visitor that determines whether or not a variable is ever written.
107 * Use \ref find_assignments for convenience.
109 class find_assignment_visitor
: public ir_hierarchical_visitor
{
111 find_assignment_visitor(unsigned num_vars
,
112 find_variable
* const *vars
)
113 : num_variables(num_vars
), num_found(0), variables(vars
)
117 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
119 ir_variable
*const var
= ir
->lhs
->variable_referenced();
121 return check_variable_name(var
->name
);
124 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
126 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
127 actual_node
, &ir
->actual_parameters
) {
128 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
129 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
131 if (sig_param
->data
.mode
== ir_var_function_out
||
132 sig_param
->data
.mode
== ir_var_function_inout
) {
133 ir_variable
*var
= param_rval
->variable_referenced();
134 if (var
&& check_variable_name(var
->name
) == visit_stop
)
139 if (ir
->return_deref
!= NULL
) {
140 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
142 if (check_variable_name(var
->name
) == visit_stop
)
146 return visit_continue_with_parent
;
150 ir_visitor_status
check_variable_name(const char *name
)
152 for (unsigned i
= 0; i
< num_variables
; ++i
) {
153 if (strcmp(variables
[i
]->name
, name
) == 0) {
154 if (!variables
[i
]->found
) {
155 variables
[i
]->found
= true;
157 assert(num_found
< num_variables
);
158 if (++num_found
== num_variables
)
165 return visit_continue_with_parent
;
169 unsigned num_variables
; /**< Number of variables to find */
170 unsigned num_found
; /**< Number of variables already found */
171 find_variable
* const *variables
; /**< Variables to find */
175 * Determine whether or not any of NULL-terminated list of variables is ever
179 find_assignments(exec_list
*ir
, find_variable
* const *vars
)
181 unsigned num_variables
= 0;
183 for (find_variable
* const *v
= vars
; *v
; ++v
)
186 find_assignment_visitor
visitor(num_variables
, vars
);
191 * Determine whether or not the given variable is ever written to.
194 find_assignments(exec_list
*ir
, find_variable
*var
)
196 find_assignment_visitor
visitor(1, &var
);
201 * Visitor that determines whether or not a variable is ever read.
203 class find_deref_visitor
: public ir_hierarchical_visitor
{
205 find_deref_visitor(const char *name
)
206 : name(name
), found(false)
211 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
213 if (strcmp(this->name
, ir
->var
->name
) == 0) {
218 return visit_continue
;
221 bool variable_found() const
227 const char *name
; /**< Find writes to a variable with this name. */
228 bool found
; /**< Was a write to the variable found? */
233 * A visitor helper that provides methods for updating the types of
234 * ir_dereferences. Classes that update variable types (say, updating
235 * array sizes) will want to use this so that dereference types stay in sync.
237 class deref_type_updater
: public ir_hierarchical_visitor
{
239 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
241 ir
->type
= ir
->var
->type
;
242 return visit_continue
;
245 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
247 const glsl_type
*const vt
= ir
->array
->type
;
249 ir
->type
= vt
->fields
.array
;
250 return visit_continue
;
253 virtual ir_visitor_status
visit_leave(ir_dereference_record
*ir
)
255 ir
->type
= ir
->record
->type
->fields
.structure
[ir
->field_idx
].type
;
256 return visit_continue
;
261 class array_resize_visitor
: public deref_type_updater
{
263 using deref_type_updater::visit
;
265 unsigned num_vertices
;
266 gl_shader_program
*prog
;
267 gl_shader_stage stage
;
269 array_resize_visitor(unsigned num_vertices
,
270 gl_shader_program
*prog
,
271 gl_shader_stage stage
)
273 this->num_vertices
= num_vertices
;
278 virtual ~array_resize_visitor()
283 virtual ir_visitor_status
visit(ir_variable
*var
)
285 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
287 return visit_continue
;
289 unsigned size
= var
->type
->length
;
291 if (stage
== MESA_SHADER_GEOMETRY
) {
292 /* Generate a link error if the shader has declared this array with
295 if (!var
->data
.implicit_sized_array
&&
296 size
&& size
!= this->num_vertices
) {
297 linker_error(this->prog
, "size of array %s declared as %u, "
298 "but number of input vertices is %u\n",
299 var
->name
, size
, this->num_vertices
);
300 return visit_continue
;
303 /* Generate a link error if the shader attempts to access an input
304 * array using an index too large for its actual size assigned at
307 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
308 linker_error(this->prog
, "%s shader accesses element %i of "
309 "%s, but only %i input vertices\n",
310 _mesa_shader_stage_to_string(this->stage
),
311 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
312 return visit_continue
;
316 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
318 var
->data
.max_array_access
= this->num_vertices
- 1;
320 return visit_continue
;
325 * Visitor that determines the highest stream id to which a (geometry) shader
326 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
328 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
330 find_emit_vertex_visitor(int max_allowed
)
331 : max_stream_allowed(max_allowed
),
332 invalid_stream_id(0),
333 invalid_stream_id_from_emit_vertex(false),
334 end_primitive_found(false),
335 uses_non_zero_stream(false)
340 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
342 int stream_id
= ir
->stream_id();
345 invalid_stream_id
= stream_id
;
346 invalid_stream_id_from_emit_vertex
= true;
350 if (stream_id
> max_stream_allowed
) {
351 invalid_stream_id
= stream_id
;
352 invalid_stream_id_from_emit_vertex
= true;
357 uses_non_zero_stream
= true;
359 return visit_continue
;
362 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
364 end_primitive_found
= true;
366 int stream_id
= ir
->stream_id();
369 invalid_stream_id
= stream_id
;
370 invalid_stream_id_from_emit_vertex
= false;
374 if (stream_id
> max_stream_allowed
) {
375 invalid_stream_id
= stream_id
;
376 invalid_stream_id_from_emit_vertex
= false;
381 uses_non_zero_stream
= true;
383 return visit_continue
;
388 return invalid_stream_id
!= 0;
391 const char *error_func()
393 return invalid_stream_id_from_emit_vertex
?
394 "EmitStreamVertex" : "EndStreamPrimitive";
399 return invalid_stream_id
;
404 return uses_non_zero_stream
;
407 bool uses_end_primitive()
409 return end_primitive_found
;
413 int max_stream_allowed
;
414 int invalid_stream_id
;
415 bool invalid_stream_id_from_emit_vertex
;
416 bool end_primitive_found
;
417 bool uses_non_zero_stream
;
420 /* Class that finds array derefs and check if indexes are dynamic. */
421 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
424 dynamic_sampler_array_indexing_visitor() :
425 dynamic_sampler_array_indexing(false)
429 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
431 if (!ir
->variable_referenced())
432 return visit_continue
;
434 if (!ir
->variable_referenced()->type
->contains_sampler())
435 return visit_continue
;
437 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
438 dynamic_sampler_array_indexing
= true;
441 return visit_continue
;
444 bool uses_dynamic_sampler_array_indexing()
446 return dynamic_sampler_array_indexing
;
450 bool dynamic_sampler_array_indexing
;
453 } /* anonymous namespace */
456 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
460 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
462 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
465 prog
->data
->LinkStatus
= LINKING_FAILURE
;
470 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
474 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
476 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
483 * Given a string identifying a program resource, break it into a base name
484 * and an optional array index in square brackets.
486 * If an array index is present, \c out_base_name_end is set to point to the
487 * "[" that precedes the array index, and the array index itself is returned
490 * If no array index is present (or if the array index is negative or
491 * mal-formed), \c out_base_name_end, is set to point to the null terminator
492 * at the end of the input string, and -1 is returned.
494 * Only the final array index is parsed; if the string contains other array
495 * indices (or structure field accesses), they are left in the base name.
497 * No attempt is made to check that the base name is properly formed;
498 * typically the caller will look up the base name in a hash table, so
499 * ill-formed base names simply turn into hash table lookup failures.
502 parse_program_resource_name(const GLchar
*name
,
503 const GLchar
**out_base_name_end
)
505 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
507 * "When an integer array element or block instance number is part of
508 * the name string, it will be specified in decimal form without a "+"
509 * or "-" sign or any extra leading zeroes. Additionally, the name
510 * string will not include white space anywhere in the string."
513 const size_t len
= strlen(name
);
514 *out_base_name_end
= name
+ len
;
516 if (len
== 0 || name
[len
-1] != ']')
519 /* Walk backwards over the string looking for a non-digit character. This
520 * had better be the opening bracket for an array index.
522 * Initially, i specifies the location of the ']'. Since the string may
523 * contain only the ']' charcater, walk backwards very carefully.
526 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
529 if ((i
== 0) || name
[i
-1] != '[')
532 long array_index
= strtol(&name
[i
], NULL
, 10);
536 /* Check for leading zero */
537 if (name
[i
] == '0' && name
[i
+1] != ']')
540 *out_base_name_end
= name
+ (i
- 1);
546 link_invalidate_variable_locations(exec_list
*ir
)
548 foreach_in_list(ir_instruction
, node
, ir
) {
549 ir_variable
*const var
= node
->as_variable();
554 /* Only assign locations for variables that lack an explicit location.
555 * Explicit locations are set for all built-in variables, generic vertex
556 * shader inputs (via layout(location=...)), and generic fragment shader
557 * outputs (also via layout(location=...)).
559 if (!var
->data
.explicit_location
) {
560 var
->data
.location
= -1;
561 var
->data
.location_frac
= 0;
564 /* ir_variable::is_unmatched_generic_inout is used by the linker while
565 * connecting outputs from one stage to inputs of the next stage.
567 if (var
->data
.explicit_location
&&
568 var
->data
.location
< VARYING_SLOT_VAR0
) {
569 var
->data
.is_unmatched_generic_inout
= 0;
571 var
->data
.is_unmatched_generic_inout
= 1;
578 * Set clip_distance_array_size based and cull_distance_array_size on the given
581 * Also check for errors based on incorrect usage of gl_ClipVertex and
582 * gl_ClipDistance and gl_CullDistance.
583 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
584 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
586 * Return false if an error was reported.
589 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
590 struct gl_linked_shader
*shader
,
591 struct gl_context
*ctx
,
592 struct shader_info
*info
)
594 info
->clip_distance_array_size
= 0;
595 info
->cull_distance_array_size
= 0;
597 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
598 /* From section 7.1 (Vertex Shader Special Variables) of the
601 * "It is an error for a shader to statically write both
602 * gl_ClipVertex and gl_ClipDistance."
604 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
605 * gl_ClipVertex nor gl_ClipDistance. However with
606 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
608 find_variable
gl_ClipDistance("gl_ClipDistance");
609 find_variable
gl_CullDistance("gl_CullDistance");
610 find_variable
gl_ClipVertex("gl_ClipVertex");
611 find_variable
* const variables
[] = {
614 !prog
->IsES
? &gl_ClipVertex
: NULL
,
617 find_assignments(shader
->ir
, variables
);
619 /* From the ARB_cull_distance spec:
621 * It is a compile-time or link-time error for the set of shaders forming
622 * a program to statically read or write both gl_ClipVertex and either
623 * gl_ClipDistance or gl_CullDistance.
625 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
629 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
630 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
631 "and `gl_ClipDistance'\n",
632 _mesa_shader_stage_to_string(shader
->Stage
));
635 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
636 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
637 "and `gl_CullDistance'\n",
638 _mesa_shader_stage_to_string(shader
->Stage
));
643 if (gl_ClipDistance
.found
) {
644 ir_variable
*clip_distance_var
=
645 shader
->symbols
->get_variable("gl_ClipDistance");
646 assert(clip_distance_var
);
647 info
->clip_distance_array_size
= clip_distance_var
->type
->length
;
649 if (gl_CullDistance
.found
) {
650 ir_variable
*cull_distance_var
=
651 shader
->symbols
->get_variable("gl_CullDistance");
652 assert(cull_distance_var
);
653 info
->cull_distance_array_size
= cull_distance_var
->type
->length
;
655 /* From the ARB_cull_distance spec:
657 * It is a compile-time or link-time error for the set of shaders forming
658 * a program to have the sum of the sizes of the gl_ClipDistance and
659 * gl_CullDistance arrays to be larger than
660 * gl_MaxCombinedClipAndCullDistances.
662 if ((uint32_t)(info
->clip_distance_array_size
+ info
->cull_distance_array_size
) >
663 ctx
->Const
.MaxClipPlanes
) {
664 linker_error(prog
, "%s shader: the combined size of "
665 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
667 "gl_MaxCombinedClipAndCullDistances (%u)",
668 _mesa_shader_stage_to_string(shader
->Stage
),
669 ctx
->Const
.MaxClipPlanes
);
676 * Verify that a vertex shader executable meets all semantic requirements.
678 * Also sets info.clip_distance_array_size and
679 * info.cull_distance_array_size as a side effect.
681 * \param shader Vertex shader executable to be verified
684 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
685 struct gl_linked_shader
*shader
,
686 struct gl_context
*ctx
)
691 /* From the GLSL 1.10 spec, page 48:
693 * "The 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. [...] The
697 * variable gl_Position is available only in the vertex
698 * language and is intended for writing the homogeneous vertex
699 * position. All executions of a well-formed vertex shader
700 * executable must write a value into this variable."
702 * while in GLSL 1.40 this text is changed to:
704 * "The variable gl_Position is available only in the vertex
705 * language and is intended for writing the homogeneous vertex
706 * position. It can be written at any time during shader
707 * execution. It may also be read back by a vertex shader
708 * after being written. This value will be used by primitive
709 * assembly, clipping, culling, and other fixed functionality
710 * operations, if present, that operate on primitives after
711 * vertex processing has occurred. Its value is undefined if
712 * the vertex shader executable does not write gl_Position."
714 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
715 * gl_Position is not an error.
717 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
718 find_variable
gl_Position("gl_Position");
719 find_assignments(shader
->ir
, &gl_Position
);
720 if (!gl_Position
.found
) {
723 "vertex shader does not write to `gl_Position'. "
724 "Its value is undefined. \n");
727 "vertex shader does not write to `gl_Position'. \n");
733 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
737 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
738 struct gl_linked_shader
*shader
,
739 struct gl_context
*ctx
)
744 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
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
, &shader
->Program
->info
);
795 * Check if geometry shaders emit to non-zero streams and do corresponding
799 validate_geometry_shader_emissions(struct gl_context
*ctx
,
800 struct gl_shader_program
*prog
)
802 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
805 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
806 emit_vertex
.run(sh
->ir
);
807 if (emit_vertex
.error()) {
808 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
809 "stream parameter are in the range [0, %d].\n",
810 emit_vertex
.error_func(),
811 emit_vertex
.error_stream(),
812 ctx
->Const
.MaxVertexStreams
- 1);
814 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
815 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
817 /* From the ARB_gpu_shader5 spec:
819 * "Multiple vertex streams are supported only if the output primitive
820 * type is declared to be "points". A program will fail to link if it
821 * contains a geometry shader calling EmitStreamVertex() or
822 * EndStreamPrimitive() if its output primitive type is not "points".
824 * However, in the same spec:
826 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
827 * with <stream> set to zero."
831 * "The function EndPrimitive() is equivalent to calling
832 * EndStreamPrimitive() with <stream> set to zero."
834 * Since we can call EmitVertex() and EndPrimitive() when we output
835 * primitives other than points, calling EmitStreamVertex(0) or
836 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
837 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
838 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
841 if (prog
->Geom
.UsesStreams
&&
842 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
843 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
844 "with n>0 requires point output\n");
850 validate_intrastage_arrays(struct gl_shader_program
*prog
,
851 ir_variable
*const var
,
852 ir_variable
*const existing
,
853 bool match_precision
)
855 /* Consider the types to be "the same" if both types are arrays
856 * of the same type and one of the arrays is implicitly sized.
857 * In addition, set the type of the linked variable to the
858 * explicitly sized array.
860 if (var
->type
->is_array() && existing
->type
->is_array()) {
861 const glsl_type
*no_array_var
= var
->type
->fields
.array
;
862 const glsl_type
*no_array_existing
= existing
->type
->fields
.array
;
865 type_matches
= (match_precision
?
866 no_array_var
== no_array_existing
:
867 no_array_var
->compare_no_precision(no_array_existing
));
870 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
871 if (var
->type
->length
!= 0) {
872 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
873 linker_error(prog
, "%s `%s' declared as type "
874 "`%s' but outermost dimension has an index"
877 var
->name
, var
->type
->name
,
878 existing
->data
.max_array_access
);
880 existing
->type
= var
->type
;
882 } else if (existing
->type
->length
!= 0) {
883 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
884 !existing
->data
.from_ssbo_unsized_array
) {
885 linker_error(prog
, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
889 var
->name
, existing
->type
->name
,
890 var
->data
.max_array_access
);
901 * Perform validation of global variables used across multiple shaders
904 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
905 struct exec_list
*ir
, glsl_symbol_table
*variables
,
908 foreach_in_list(ir_instruction
, node
, ir
) {
909 ir_variable
*const var
= node
->as_variable();
914 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
917 /* don't cross validate subroutine uniforms */
918 if (var
->type
->contains_subroutine())
921 /* Don't cross validate interface instances. These are only relevant
922 * inside a shader. The cross validation is done at the Interface Block
925 if (var
->is_interface_instance())
928 /* Don't cross validate temporaries that are at global scope. These
929 * will eventually get pulled into the shaders 'main'.
931 if (var
->data
.mode
== ir_var_temporary
)
934 /* If a global with this name has already been seen, verify that the
935 * new instance has the same type. In addition, if the globals have
936 * initializers, the values of the initializers must be the same.
938 ir_variable
*const existing
= variables
->get_variable(var
->name
);
939 if (existing
!= NULL
) {
940 /* Check if types match. */
941 if (var
->type
!= existing
->type
) {
942 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
943 /* If it is an unsized array in a Shader Storage Block,
944 * two different shaders can access to different elements.
945 * Because of that, they might be converted to different
946 * sized arrays, then check that they are compatible but
947 * ignore the array size.
949 if (!(var
->data
.mode
== ir_var_shader_storage
&&
950 var
->data
.from_ssbo_unsized_array
&&
951 existing
->data
.mode
== ir_var_shader_storage
&&
952 existing
->data
.from_ssbo_unsized_array
&&
953 var
->type
->gl_type
== existing
->type
->gl_type
)) {
954 linker_error(prog
, "%s `%s' declared as type "
955 "`%s' and type `%s'\n",
957 var
->name
, var
->type
->name
,
958 existing
->type
->name
);
964 if (var
->data
.explicit_location
) {
965 if (existing
->data
.explicit_location
966 && (var
->data
.location
!= existing
->data
.location
)) {
967 linker_error(prog
, "explicit locations for %s "
968 "`%s' have differing values\n",
969 mode_string(var
), var
->name
);
973 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
974 linker_error(prog
, "explicit components for %s `%s' have "
975 "differing values\n", mode_string(var
), var
->name
);
979 existing
->data
.location
= var
->data
.location
;
980 existing
->data
.explicit_location
= true;
982 /* Check if uniform with implicit location was marked explicit
983 * by earlier shader stage. If so, mark it explicit in this stage
984 * too to make sure later processing does not treat it as
987 if (existing
->data
.explicit_location
) {
988 var
->data
.location
= existing
->data
.location
;
989 var
->data
.explicit_location
= true;
993 /* From the GLSL 4.20 specification:
994 * "A link error will result if two compilation units in a program
995 * specify different integer-constant bindings for the same
996 * opaque-uniform name. However, it is not an error to specify a
997 * binding on some but not all declarations for the same name"
999 if (var
->data
.explicit_binding
) {
1000 if (existing
->data
.explicit_binding
&&
1001 var
->data
.binding
!= existing
->data
.binding
) {
1002 linker_error(prog
, "explicit bindings for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var
), var
->name
);
1008 existing
->data
.binding
= var
->data
.binding
;
1009 existing
->data
.explicit_binding
= true;
1012 if (var
->type
->contains_atomic() &&
1013 var
->data
.offset
!= existing
->data
.offset
) {
1014 linker_error(prog
, "offset specifications for %s "
1015 "`%s' have differing values\n",
1016 mode_string(var
), var
->name
);
1020 /* Validate layout qualifiers for gl_FragDepth.
1022 * From the AMD/ARB_conservative_depth specs:
1024 * "If gl_FragDepth is redeclared in any fragment shader in a
1025 * program, it must be redeclared in all fragment shaders in
1026 * that program that have static assignments to
1027 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1028 * fragment shaders in a single program must have the same set
1031 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1032 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1033 bool layout_differs
=
1034 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1036 if (layout_declared
&& layout_differs
) {
1038 "All redeclarations of gl_FragDepth in all "
1039 "fragment shaders in a single program must have "
1040 "the same set of qualifiers.\n");
1043 if (var
->data
.used
&& layout_differs
) {
1045 "If gl_FragDepth is redeclared with a layout "
1046 "qualifier in any fragment shader, it must be "
1047 "redeclared with the same layout qualifier in "
1048 "all fragment shaders that have assignments to "
1053 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1055 * "If a shared global has multiple initializers, the
1056 * initializers must all be constant expressions, and they
1057 * must all have the same value. Otherwise, a link error will
1058 * result. (A shared global having only one initializer does
1059 * not require that initializer to be a constant expression.)"
1061 * Previous to 4.20 the GLSL spec simply said that initializers
1062 * must have the same value. In this case of non-constant
1063 * initializers, this was impossible to determine. As a result,
1064 * no vendor actually implemented that behavior. The 4.20
1065 * behavior matches the implemented behavior of at least one other
1066 * vendor, so we'll implement that for all GLSL versions.
1068 if (var
->constant_initializer
!= NULL
) {
1069 if (existing
->constant_initializer
!= NULL
) {
1070 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1071 linker_error(prog
, "initializers for %s "
1072 "`%s' have differing values\n",
1073 mode_string(var
), var
->name
);
1077 /* If the first-seen instance of a particular uniform did
1078 * not have an initializer but a later instance does,
1079 * replace the former with the later.
1081 variables
->replace_variable(existing
->name
, var
);
1085 if (var
->data
.has_initializer
) {
1086 if (existing
->data
.has_initializer
1087 && (var
->constant_initializer
== NULL
1088 || existing
->constant_initializer
== NULL
)) {
1090 "shared global variable `%s' has multiple "
1091 "non-constant initializers.\n",
1097 if (existing
->data
.explicit_invariant
!= var
->data
.explicit_invariant
) {
1098 linker_error(prog
, "declarations for %s `%s' have "
1099 "mismatching invariant qualifiers\n",
1100 mode_string(var
), var
->name
);
1103 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1104 linker_error(prog
, "declarations for %s `%s' have "
1105 "mismatching centroid qualifiers\n",
1106 mode_string(var
), var
->name
);
1109 if (existing
->data
.sample
!= var
->data
.sample
) {
1110 linker_error(prog
, "declarations for %s `%s` have "
1111 "mismatching sample qualifiers\n",
1112 mode_string(var
), var
->name
);
1115 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1116 linker_error(prog
, "declarations for %s `%s` have "
1117 "mismatching image format qualifiers\n",
1118 mode_string(var
), var
->name
);
1122 /* Check the precision qualifier matches for uniform variables on
1125 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1126 prog
->IsES
&& !var
->get_interface_type() &&
1127 existing
->data
.precision
!= var
->data
.precision
) {
1128 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1129 linker_error(prog
, "declarations for %s `%s` have "
1130 "mismatching precision qualifiers\n",
1131 mode_string(var
), var
->name
);
1134 linker_warning(prog
, "declarations for %s `%s` have "
1135 "mismatching precision qualifiers\n",
1136 mode_string(var
), var
->name
);
1140 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1142 * "It is a link-time error if any particular shader interface
1145 * - two different blocks, each having no instance name, and each
1146 * having a member of the same name, or
1148 * - a variable outside a block, and a block with no instance name,
1149 * where the variable has the same name as a member in the block."
1151 const glsl_type
*var_itype
= var
->get_interface_type();
1152 const glsl_type
*existing_itype
= existing
->get_interface_type();
1153 if (var_itype
!= existing_itype
) {
1154 if (!var_itype
|| !existing_itype
) {
1155 linker_error(prog
, "declarations for %s `%s` are inside block "
1156 "`%s` and outside a block",
1157 mode_string(var
), var
->name
,
1158 var_itype
? var_itype
->name
: existing_itype
->name
);
1160 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1161 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1163 mode_string(var
), var
->name
,
1164 existing_itype
->name
,
1170 variables
->add_variable(var
);
1176 * Perform validation of uniforms used across multiple shader stages
1179 cross_validate_uniforms(struct gl_context
*ctx
,
1180 struct gl_shader_program
*prog
)
1182 glsl_symbol_table variables
;
1183 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1184 if (prog
->_LinkedShaders
[i
] == NULL
)
1187 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1193 * Accumulates the array of buffer blocks and checks that all definitions of
1194 * blocks agree on their contents.
1197 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1200 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1201 struct gl_uniform_block
*blks
= NULL
;
1202 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1203 &prog
->data
->NumUniformBlocks
;
1205 unsigned max_num_buffer_blocks
= 0;
1206 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1207 if (prog
->_LinkedShaders
[i
]) {
1208 if (validate_ssbo
) {
1209 max_num_buffer_blocks
+=
1210 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1212 max_num_buffer_blocks
+=
1213 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1218 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1219 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1221 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1222 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1223 InterfaceBlockStageIndex
[i
][j
] = -1;
1228 unsigned sh_num_blocks
;
1229 struct gl_uniform_block
**sh_blks
;
1230 if (validate_ssbo
) {
1231 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1232 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1234 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1235 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1238 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1239 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1240 num_blks
, sh_blks
[j
]);
1243 linker_error(prog
, "buffer block `%s' has mismatching "
1244 "definitions\n", sh_blks
[j
]->Name
);
1246 for (unsigned k
= 0; k
<= i
; k
++) {
1247 delete[] InterfaceBlockStageIndex
[k
];
1250 /* Reset the block count. This will help avoid various segfaults
1251 * from api calls that assume the array exists due to the count
1258 InterfaceBlockStageIndex
[i
][index
] = j
;
1262 /* Update per stage block pointers to point to the program list.
1263 * FIXME: We should be able to free the per stage blocks here.
1265 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1266 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1267 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1269 if (stage_index
!= -1) {
1270 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1272 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1273 sh
->Program
->sh
.ShaderStorageBlocks
:
1274 sh
->Program
->sh
.UniformBlocks
;
1276 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1277 sh_blks
[stage_index
] = &blks
[j
];
1282 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1283 delete[] InterfaceBlockStageIndex
[i
];
1287 prog
->data
->ShaderStorageBlocks
= blks
;
1289 prog
->data
->UniformBlocks
= blks
;
1295 * Verifies the invariance of built-in special variables.
1298 validate_invariant_builtins(struct gl_shader_program
*prog
,
1299 const gl_linked_shader
*vert
,
1300 const gl_linked_shader
*frag
)
1302 const ir_variable
*var_vert
;
1303 const ir_variable
*var_frag
;
1309 * From OpenGL ES Shading Language 1.0 specification
1310 * (4.6.4 Invariance and Linkage):
1311 * "The invariance of varyings that are declared in both the vertex and
1312 * fragment shaders must match. For the built-in special variables,
1313 * gl_FragCoord can only be declared invariant if and only if
1314 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1315 * be declared invariant if and only if gl_PointSize is declared
1316 * invariant. It is an error to declare gl_FrontFacing as invariant.
1317 * The invariance of gl_FrontFacing is the same as the invariance of
1320 var_frag
= frag
->symbols
->get_variable("gl_FragCoord");
1321 if (var_frag
&& var_frag
->data
.invariant
) {
1322 var_vert
= vert
->symbols
->get_variable("gl_Position");
1323 if (var_vert
&& !var_vert
->data
.invariant
) {
1325 "fragment shader built-in `%s' has invariant qualifier, "
1326 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1327 var_frag
->name
, var_vert
->name
);
1332 var_frag
= frag
->symbols
->get_variable("gl_PointCoord");
1333 if (var_frag
&& var_frag
->data
.invariant
) {
1334 var_vert
= vert
->symbols
->get_variable("gl_PointSize");
1335 if (var_vert
&& !var_vert
->data
.invariant
) {
1337 "fragment shader built-in `%s' has invariant qualifier, "
1338 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1339 var_frag
->name
, var_vert
->name
);
1344 var_frag
= frag
->symbols
->get_variable("gl_FrontFacing");
1345 if (var_frag
&& var_frag
->data
.invariant
) {
1347 "fragment shader built-in `%s' can not be declared as invariant\n",
1356 * Populates a shaders symbol table with all global declarations
1359 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1361 sh
->symbols
= new(sh
) glsl_symbol_table
;
1363 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1368 * Remap variables referenced in an instruction tree
1370 * This is used when instruction trees are cloned from one shader and placed in
1371 * another. These trees will contain references to \c ir_variable nodes that
1372 * do not exist in the target shader. This function finds these \c ir_variable
1373 * references and replaces the references with matching variables in the target
1376 * If there is no matching variable in the target shader, a clone of the
1377 * \c ir_variable is made and added to the target shader. The new variable is
1378 * added to \b both the instruction stream and the symbol table.
1380 * \param inst IR tree that is to be processed.
1381 * \param symbols Symbol table containing global scope symbols in the
1383 * \param instructions Instruction stream where new variable declarations
1387 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1390 class remap_visitor
: public ir_hierarchical_visitor
{
1392 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1394 this->target
= target
;
1395 this->symbols
= target
->symbols
;
1396 this->instructions
= target
->ir
;
1397 this->temps
= temps
;
1400 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1402 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1403 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1404 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1406 assert(var
!= NULL
);
1408 return visit_continue
;
1411 ir_variable
*const existing
=
1412 this->symbols
->get_variable(ir
->var
->name
);
1413 if (existing
!= NULL
)
1416 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1418 this->symbols
->add_variable(copy
);
1419 this->instructions
->push_head(copy
);
1423 return visit_continue
;
1427 struct gl_linked_shader
*target
;
1428 glsl_symbol_table
*symbols
;
1429 exec_list
*instructions
;
1433 remap_visitor
v(target
, temps
);
1440 * Move non-declarations from one instruction stream to another
1442 * The intended usage pattern of this function is to pass the pointer to the
1443 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1444 * pointer) for \c last and \c false for \c make_copies on the first
1445 * call. Successive calls pass the return value of the previous call for
1446 * \c last and \c true for \c make_copies.
1448 * \param instructions Source instruction stream
1449 * \param last Instruction after which new instructions should be
1450 * inserted in the target instruction stream
1451 * \param make_copies Flag selecting whether instructions in \c instructions
1452 * should be copied (via \c ir_instruction::clone) into the
1453 * target list or moved.
1456 * The new "last" instruction in the target instruction stream. This pointer
1457 * is suitable for use as the \c last parameter of a later call to this
1461 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1462 bool make_copies
, gl_linked_shader
*target
)
1464 hash_table
*temps
= NULL
;
1467 temps
= _mesa_pointer_hash_table_create(NULL
);
1469 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1470 if (inst
->as_function())
1473 ir_variable
*var
= inst
->as_variable();
1474 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1477 assert(inst
->as_assignment()
1479 || inst
->as_if() /* for initializers with the ?: operator */
1480 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1483 inst
= inst
->clone(target
, NULL
);
1486 _mesa_hash_table_insert(temps
, var
, inst
);
1488 remap_variables(inst
, target
, temps
);
1493 last
->insert_after(inst
);
1498 _mesa_hash_table_destroy(temps
, NULL
);
1505 * This class is only used in link_intrastage_shaders() below but declaring
1506 * it inside that function leads to compiler warnings with some versions of
1509 class array_sizing_visitor
: public deref_type_updater
{
1511 using deref_type_updater::visit
;
1513 array_sizing_visitor()
1514 : mem_ctx(ralloc_context(NULL
)),
1515 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL
))
1519 ~array_sizing_visitor()
1521 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1522 ralloc_free(this->mem_ctx
);
1525 virtual ir_visitor_status
visit(ir_variable
*var
)
1527 const glsl_type
*type_without_array
;
1528 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1529 fixup_type(&var
->type
, var
->data
.max_array_access
,
1530 var
->data
.from_ssbo_unsized_array
,
1531 &implicit_sized_array
);
1532 var
->data
.implicit_sized_array
= implicit_sized_array
;
1533 type_without_array
= var
->type
->without_array();
1534 if (var
->type
->is_interface()) {
1535 if (interface_contains_unsized_arrays(var
->type
)) {
1536 const glsl_type
*new_type
=
1537 resize_interface_members(var
->type
,
1538 var
->get_max_ifc_array_access(),
1539 var
->is_in_shader_storage_block());
1540 var
->type
= new_type
;
1541 var
->change_interface_type(new_type
);
1543 } else if (type_without_array
->is_interface()) {
1544 if (interface_contains_unsized_arrays(type_without_array
)) {
1545 const glsl_type
*new_type
=
1546 resize_interface_members(type_without_array
,
1547 var
->get_max_ifc_array_access(),
1548 var
->is_in_shader_storage_block());
1549 var
->change_interface_type(new_type
);
1550 var
->type
= update_interface_members_array(var
->type
, new_type
);
1552 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1553 /* Store a pointer to the variable in the unnamed_interfaces
1557 _mesa_hash_table_search(this->unnamed_interfaces
,
1560 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1562 if (interface_vars
== NULL
) {
1563 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1565 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1568 unsigned index
= ifc_type
->field_index(var
->name
);
1569 assert(index
< ifc_type
->length
);
1570 assert(interface_vars
[index
] == NULL
);
1571 interface_vars
[index
] = var
;
1573 return visit_continue
;
1577 * For each unnamed interface block that was discovered while running the
1578 * visitor, adjust the interface type to reflect the newly assigned array
1579 * sizes, and fix up the ir_variable nodes to point to the new interface
1582 void fixup_unnamed_interface_types()
1584 hash_table_call_foreach(this->unnamed_interfaces
,
1585 fixup_unnamed_interface_type
, NULL
);
1590 * If the type pointed to by \c type represents an unsized array, replace
1591 * it with a sized array whose size is determined by max_array_access.
1593 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1594 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1596 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1597 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1598 max_array_access
+ 1);
1599 *implicit_sized
= true;
1600 assert(*type
!= NULL
);
1604 static const glsl_type
*
1605 update_interface_members_array(const glsl_type
*type
,
1606 const glsl_type
*new_interface_type
)
1608 const glsl_type
*element_type
= type
->fields
.array
;
1609 if (element_type
->is_array()) {
1610 const glsl_type
*new_array_type
=
1611 update_interface_members_array(element_type
, new_interface_type
);
1612 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1614 return glsl_type::get_array_instance(new_interface_type
,
1620 * Determine whether the given interface type contains unsized arrays (if
1621 * it doesn't, array_sizing_visitor doesn't need to process it).
1623 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1625 for (unsigned i
= 0; i
< type
->length
; i
++) {
1626 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1627 if (elem_type
->is_unsized_array())
1634 * Create a new interface type based on the given type, with unsized arrays
1635 * replaced by sized arrays whose size is determined by
1636 * max_ifc_array_access.
1638 static const glsl_type
*
1639 resize_interface_members(const glsl_type
*type
,
1640 const int *max_ifc_array_access
,
1643 unsigned num_fields
= type
->length
;
1644 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1645 memcpy(fields
, type
->fields
.structure
,
1646 num_fields
* sizeof(*fields
));
1647 for (unsigned i
= 0; i
< num_fields
; i
++) {
1648 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1649 /* If SSBO last member is unsized array, we don't replace it by a sized
1652 if (is_ssbo
&& i
== (num_fields
- 1))
1653 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1654 true, &implicit_sized_array
);
1656 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1657 false, &implicit_sized_array
);
1658 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1660 glsl_interface_packing packing
=
1661 (glsl_interface_packing
) type
->interface_packing
;
1662 bool row_major
= (bool) type
->interface_row_major
;
1663 const glsl_type
*new_ifc_type
=
1664 glsl_type::get_interface_instance(fields
, num_fields
,
1665 packing
, row_major
, type
->name
);
1667 return new_ifc_type
;
1670 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1673 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1674 ir_variable
**interface_vars
= (ir_variable
**) data
;
1675 unsigned num_fields
= ifc_type
->length
;
1676 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1677 memcpy(fields
, ifc_type
->fields
.structure
,
1678 num_fields
* sizeof(*fields
));
1679 bool interface_type_changed
= false;
1680 for (unsigned i
= 0; i
< num_fields
; i
++) {
1681 if (interface_vars
[i
] != NULL
&&
1682 fields
[i
].type
!= interface_vars
[i
]->type
) {
1683 fields
[i
].type
= interface_vars
[i
]->type
;
1684 interface_type_changed
= true;
1687 if (!interface_type_changed
) {
1691 glsl_interface_packing packing
=
1692 (glsl_interface_packing
) ifc_type
->interface_packing
;
1693 bool row_major
= (bool) ifc_type
->interface_row_major
;
1694 const glsl_type
*new_ifc_type
=
1695 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1696 row_major
, ifc_type
->name
);
1698 for (unsigned i
= 0; i
< num_fields
; i
++) {
1699 if (interface_vars
[i
] != NULL
)
1700 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1705 * Memory context used to allocate the data in \c unnamed_interfaces.
1710 * Hash table from const glsl_type * to an array of ir_variable *'s
1711 * pointing to the ir_variables constituting each unnamed interface block.
1713 hash_table
*unnamed_interfaces
;
1717 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1718 struct gl_shader_program
*prog
)
1720 /* We will validate doubles at a later stage */
1721 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1722 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1723 "multiple of 4 or if its applied to a type that is "
1724 "or contains a double a multiple of 8.",
1725 prog
->TransformFeedback
.BufferStride
[idx
]);
1729 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1730 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1731 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1732 "limit has been exceeded.");
1740 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1744 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1745 struct gl_shader_program
*prog
,
1746 struct gl_shader
**shader_list
,
1747 unsigned num_shaders
)
1749 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1750 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1753 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1754 struct gl_shader
*shader
= shader_list
[i
];
1756 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1757 if (shader
->TransformFeedbackBufferStride
[j
]) {
1758 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1759 prog
->TransformFeedback
.BufferStride
[j
] =
1760 shader
->TransformFeedbackBufferStride
[j
];
1761 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1763 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1764 shader
->TransformFeedbackBufferStride
[j
]){
1766 "intrastage shaders defined with conflicting "
1767 "xfb_stride for buffer %d (%d and %d)\n", j
,
1768 prog
->TransformFeedback
.BufferStride
[j
],
1769 shader
->TransformFeedbackBufferStride
[j
]);
1778 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1782 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1783 struct gl_shader
**shader_list
,
1784 unsigned num_shaders
)
1786 bool bindless_sampler
, bindless_image
;
1787 bool bound_sampler
, bound_image
;
1789 bindless_sampler
= bindless_image
= false;
1790 bound_sampler
= bound_image
= false;
1792 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1793 struct gl_shader
*shader
= shader_list
[i
];
1795 if (shader
->bindless_sampler
)
1796 bindless_sampler
= true;
1797 if (shader
->bindless_image
)
1798 bindless_image
= true;
1799 if (shader
->bound_sampler
)
1800 bound_sampler
= true;
1801 if (shader
->bound_image
)
1804 if ((bindless_sampler
&& bound_sampler
) ||
1805 (bindless_image
&& bound_image
)) {
1806 /* From section 4.4.6 of the ARB_bindless_texture spec:
1808 * "If both bindless_sampler and bound_sampler, or bindless_image
1809 * and bound_image, are declared at global scope in any
1810 * compilation unit, a link- time error will be generated."
1812 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1813 "bindless_image and bound_image, can't be declared at "
1820 * Check for conflicting viewport_relative settings across shaders, and sets
1821 * the value for the linked shader.
1824 link_layer_viewport_relative_qualifier(struct gl_shader_program
*prog
,
1825 struct gl_program
*gl_prog
,
1826 struct gl_shader
**shader_list
,
1827 unsigned num_shaders
)
1831 /* Find first shader with explicit layer declaration */
1832 for (i
= 0; i
< num_shaders
; i
++) {
1833 if (shader_list
[i
]->redeclares_gl_layer
) {
1834 gl_prog
->info
.layer_viewport_relative
=
1835 shader_list
[i
]->layer_viewport_relative
;
1840 /* Now make sure that each subsequent shader's explicit layer declaration
1841 * matches the first one's.
1843 for (; i
< num_shaders
; i
++) {
1844 if (shader_list
[i
]->redeclares_gl_layer
&&
1845 shader_list
[i
]->layer_viewport_relative
!=
1846 gl_prog
->info
.layer_viewport_relative
) {
1847 linker_error(prog
, "all gl_Layer redeclarations must have identical "
1848 "viewport_relative settings");
1854 * Performs the cross-validation of tessellation control shader vertices and
1855 * layout qualifiers for the attached tessellation control shaders,
1856 * and propagates them to the linked TCS and linked shader program.
1859 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1860 struct gl_program
*gl_prog
,
1861 struct gl_shader
**shader_list
,
1862 unsigned num_shaders
)
1864 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1867 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1869 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1871 * "All tessellation control shader layout declarations in a program
1872 * must specify the same output patch vertex count. There must be at
1873 * least one layout qualifier specifying an output patch vertex count
1874 * in any program containing tessellation control shaders; however,
1875 * such a declaration is not required in all tessellation control
1879 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1880 struct gl_shader
*shader
= shader_list
[i
];
1882 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1883 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1884 gl_prog
->info
.tess
.tcs_vertices_out
!=
1885 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1886 linker_error(prog
, "tessellation control shader defined with "
1887 "conflicting output vertex count (%d and %d)\n",
1888 gl_prog
->info
.tess
.tcs_vertices_out
,
1889 shader
->info
.TessCtrl
.VerticesOut
);
1892 gl_prog
->info
.tess
.tcs_vertices_out
=
1893 shader
->info
.TessCtrl
.VerticesOut
;
1897 /* Just do the intrastage -> interstage propagation right now,
1898 * since we already know we're in the right type of shader program
1901 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1902 linker_error(prog
, "tessellation control shader didn't declare "
1903 "vertices out layout qualifier\n");
1910 * Performs the cross-validation of tessellation evaluation shader
1911 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1912 * for the attached tessellation evaluation shaders, and propagates them
1913 * to the linked TES and linked shader program.
1916 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1917 struct gl_program
*gl_prog
,
1918 struct gl_shader
**shader_list
,
1919 unsigned num_shaders
)
1921 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1924 int point_mode
= -1;
1925 unsigned vertex_order
= 0;
1927 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1928 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1930 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1932 * "At least one tessellation evaluation shader (compilation unit) in
1933 * a program must declare a primitive mode in its input layout.
1934 * Declaration vertex spacing, ordering, and point mode identifiers is
1935 * optional. It is not required that all tessellation evaluation
1936 * shaders in a program declare a primitive mode. If spacing or
1937 * vertex ordering declarations are omitted, the tessellation
1938 * primitive generator will use equal spacing or counter-clockwise
1939 * vertex ordering, respectively. If a point mode declaration is
1940 * omitted, the tessellation primitive generator will produce lines or
1941 * triangles according to the primitive mode."
1944 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1945 struct gl_shader
*shader
= shader_list
[i
];
1947 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1948 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1949 gl_prog
->info
.tess
.primitive_mode
!=
1950 shader
->info
.TessEval
.PrimitiveMode
) {
1951 linker_error(prog
, "tessellation evaluation shader defined with "
1952 "conflicting input primitive modes.\n");
1955 gl_prog
->info
.tess
.primitive_mode
=
1956 shader
->info
.TessEval
.PrimitiveMode
;
1959 if (shader
->info
.TessEval
.Spacing
!= 0) {
1960 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1961 shader
->info
.TessEval
.Spacing
) {
1962 linker_error(prog
, "tessellation evaluation shader defined with "
1963 "conflicting vertex spacing.\n");
1966 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1969 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1970 if (vertex_order
!= 0 &&
1971 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1972 linker_error(prog
, "tessellation evaluation shader defined with "
1973 "conflicting ordering.\n");
1976 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1979 if (shader
->info
.TessEval
.PointMode
!= -1) {
1980 if (point_mode
!= -1 &&
1981 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1982 linker_error(prog
, "tessellation evaluation shader defined with "
1983 "conflicting point modes.\n");
1986 point_mode
= shader
->info
.TessEval
.PointMode
;
1991 /* Just do the intrastage -> interstage propagation right now,
1992 * since we already know we're in the right type of shader program
1995 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1997 "tessellation evaluation shader didn't declare input "
1998 "primitive modes.\n");
2002 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
2003 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
2005 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
2006 gl_prog
->info
.tess
.ccw
= true;
2008 gl_prog
->info
.tess
.ccw
= false;
2011 if (point_mode
== -1 || point_mode
== GL_FALSE
)
2012 gl_prog
->info
.tess
.point_mode
= false;
2014 gl_prog
->info
.tess
.point_mode
= true;
2019 * Performs the cross-validation of layout qualifiers specified in
2020 * redeclaration of gl_FragCoord for the attached fragment shaders,
2021 * and propagates them to the linked FS and linked shader program.
2024 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2025 struct gl_linked_shader
*linked_shader
,
2026 struct gl_shader
**shader_list
,
2027 unsigned num_shaders
)
2029 bool redeclares_gl_fragcoord
= false;
2030 bool uses_gl_fragcoord
= false;
2031 bool origin_upper_left
= false;
2032 bool pixel_center_integer
= false;
2034 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
2035 (prog
->data
->Version
< 150 &&
2036 !prog
->ARB_fragment_coord_conventions_enable
))
2039 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2040 struct gl_shader
*shader
= shader_list
[i
];
2041 /* From the GLSL 1.50 spec, page 39:
2043 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2044 * it must be redeclared in all the fragment shaders in that program
2045 * that have a static use gl_FragCoord."
2047 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
2048 shader
->uses_gl_fragcoord
)
2049 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
2050 uses_gl_fragcoord
)) {
2051 linker_error(prog
, "fragment shader defined with conflicting "
2052 "layout qualifiers for gl_FragCoord\n");
2055 /* From the GLSL 1.50 spec, page 39:
2057 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2058 * single program must have the same set of qualifiers."
2060 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
2061 (shader
->origin_upper_left
!= origin_upper_left
||
2062 shader
->pixel_center_integer
!= pixel_center_integer
)) {
2063 linker_error(prog
, "fragment shader defined with conflicting "
2064 "layout qualifiers for gl_FragCoord\n");
2067 /* Update the linked shader state. Note that uses_gl_fragcoord should
2068 * accumulate the results. The other values should replace. If there
2069 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2070 * are already known to be the same.
2072 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
2073 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
2074 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
2075 origin_upper_left
= shader
->origin_upper_left
;
2076 pixel_center_integer
= shader
->pixel_center_integer
;
2079 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
2080 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
2081 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
2082 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
2083 shader
->PostDepthCoverage
;
2084 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
2085 shader
->PixelInterlockOrdered
;
2086 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
2087 shader
->PixelInterlockUnordered
;
2088 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
2089 shader
->SampleInterlockOrdered
;
2090 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
2091 shader
->SampleInterlockUnordered
;
2092 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
2095 linked_shader
->Program
->info
.fs
.pixel_center_integer
= pixel_center_integer
;
2096 linked_shader
->Program
->info
.fs
.origin_upper_left
= origin_upper_left
;
2100 * Performs the cross-validation of geometry shader max_vertices and
2101 * primitive type layout qualifiers for the attached geometry shaders,
2102 * and propagates them to the linked GS and linked shader program.
2105 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2106 struct gl_program
*gl_prog
,
2107 struct gl_shader
**shader_list
,
2108 unsigned num_shaders
)
2110 /* No in/out qualifiers defined for anything but GLSL 1.50+
2111 * geometry shaders so far.
2113 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2114 prog
->data
->Version
< 150)
2117 int vertices_out
= -1;
2119 gl_prog
->info
.gs
.invocations
= 0;
2120 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2121 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2123 /* From the GLSL 1.50 spec, page 46:
2125 * "All geometry shader output layout declarations in a program
2126 * must declare the same layout and same value for
2127 * max_vertices. There must be at least one geometry output
2128 * layout declaration somewhere in a program, but not all
2129 * geometry shaders (compilation units) are required to
2133 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2134 struct gl_shader
*shader
= shader_list
[i
];
2136 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2137 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2138 gl_prog
->info
.gs
.input_primitive
!=
2139 shader
->info
.Geom
.InputType
) {
2140 linker_error(prog
, "geometry shader defined with conflicting "
2144 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2147 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2148 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2149 gl_prog
->info
.gs
.output_primitive
!=
2150 shader
->info
.Geom
.OutputType
) {
2151 linker_error(prog
, "geometry shader defined with conflicting "
2155 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2158 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2159 if (vertices_out
!= -1 &&
2160 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2161 linker_error(prog
, "geometry shader defined with conflicting "
2162 "output vertex count (%d and %d)\n",
2163 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2166 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2169 if (shader
->info
.Geom
.Invocations
!= 0) {
2170 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2171 gl_prog
->info
.gs
.invocations
!=
2172 (unsigned) shader
->info
.Geom
.Invocations
) {
2173 linker_error(prog
, "geometry shader defined with conflicting "
2174 "invocation count (%d and %d)\n",
2175 gl_prog
->info
.gs
.invocations
,
2176 shader
->info
.Geom
.Invocations
);
2179 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2183 /* Just do the intrastage -> interstage propagation right now,
2184 * since we already know we're in the right type of shader program
2187 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2189 "geometry shader didn't declare primitive input type\n");
2193 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2195 "geometry shader didn't declare primitive output type\n");
2199 if (vertices_out
== -1) {
2201 "geometry shader didn't declare max_vertices\n");
2204 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2207 if (gl_prog
->info
.gs
.invocations
== 0)
2208 gl_prog
->info
.gs
.invocations
= 1;
2213 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2214 * derivative arrangement qualifiers for the attached compute shaders, and
2215 * propagate them to the linked CS and linked shader program.
2218 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2219 struct gl_program
*gl_prog
,
2220 struct gl_shader
**shader_list
,
2221 unsigned num_shaders
)
2223 /* This function is called for all shader stages, but it only has an effect
2224 * for compute shaders.
2226 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2229 for (int i
= 0; i
< 3; i
++)
2230 gl_prog
->info
.cs
.local_size
[i
] = 0;
2232 gl_prog
->info
.cs
.local_size_variable
= false;
2234 gl_prog
->info
.cs
.derivative_group
= DERIVATIVE_GROUP_NONE
;
2236 /* From the ARB_compute_shader spec, in the section describing local size
2239 * If multiple compute shaders attached to a single program object
2240 * declare local work-group size, the declarations must be identical;
2241 * otherwise a link-time error results. Furthermore, if a program
2242 * object contains any compute shaders, at least one must contain an
2243 * input layout qualifier specifying the local work sizes of the
2244 * program, or a link-time error will occur.
2246 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2247 struct gl_shader
*shader
= shader_list
[sh
];
2249 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2250 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2251 for (int i
= 0; i
< 3; i
++) {
2252 if (gl_prog
->info
.cs
.local_size
[i
] !=
2253 shader
->info
.Comp
.LocalSize
[i
]) {
2254 linker_error(prog
, "compute shader defined with conflicting "
2260 for (int i
= 0; i
< 3; i
++) {
2261 gl_prog
->info
.cs
.local_size
[i
] =
2262 shader
->info
.Comp
.LocalSize
[i
];
2264 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2265 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2266 /* The ARB_compute_variable_group_size spec says:
2268 * If one compute shader attached to a program declares a
2269 * variable local group size and a second compute shader
2270 * attached to the same program declares a fixed local group
2271 * size, a link-time error results.
2273 linker_error(prog
, "compute shader defined with both fixed and "
2274 "variable local group size\n");
2277 gl_prog
->info
.cs
.local_size_variable
= true;
2280 enum gl_derivative_group group
= shader
->info
.Comp
.DerivativeGroup
;
2281 if (group
!= DERIVATIVE_GROUP_NONE
) {
2282 if (gl_prog
->info
.cs
.derivative_group
!= DERIVATIVE_GROUP_NONE
&&
2283 gl_prog
->info
.cs
.derivative_group
!= group
) {
2284 linker_error(prog
, "compute shader defined with conflicting "
2285 "derivative groups\n");
2288 gl_prog
->info
.cs
.derivative_group
= group
;
2292 /* Just do the intrastage -> interstage propagation right now,
2293 * since we already know we're in the right type of shader program
2296 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2297 !gl_prog
->info
.cs
.local_size_variable
) {
2298 linker_error(prog
, "compute shader must contain a fixed or a variable "
2299 "local group size\n");
2303 if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_QUADS
) {
2304 if (gl_prog
->info
.cs
.local_size
[0] % 2 != 0) {
2305 linker_error(prog
, "derivative_group_quadsNV must be used with a "
2306 "local group size whose first dimension "
2307 "is a multiple of 2\n");
2310 if (gl_prog
->info
.cs
.local_size
[1] % 2 != 0) {
2311 linker_error(prog
, "derivative_group_quadsNV must be used with a local"
2312 "group size whose second dimension "
2313 "is a multiple of 2\n");
2316 } else if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_LINEAR
) {
2317 if ((gl_prog
->info
.cs
.local_size
[0] *
2318 gl_prog
->info
.cs
.local_size
[1] *
2319 gl_prog
->info
.cs
.local_size
[2]) % 4 != 0) {
2320 linker_error(prog
, "derivative_group_linearNV must be used with a "
2321 "local group size whose total number of invocations "
2322 "is a multiple of 4\n");
2329 * Link all out variables on a single stage which are not
2330 * directly used in a shader with the main function.
2333 link_output_variables(struct gl_linked_shader
*linked_shader
,
2334 struct gl_shader
**shader_list
,
2335 unsigned num_shaders
)
2337 struct glsl_symbol_table
*symbols
= linked_shader
->symbols
;
2339 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2341 /* Skip shader object with main function */
2342 if (shader_list
[i
]->symbols
->get_function("main"))
2345 foreach_in_list(ir_instruction
, ir
, shader_list
[i
]->ir
) {
2346 if (ir
->ir_type
!= ir_type_variable
)
2349 ir_variable
*var
= (ir_variable
*) ir
;
2351 if (var
->data
.mode
== ir_var_shader_out
&&
2352 !symbols
->get_variable(var
->name
)) {
2353 var
= var
->clone(linked_shader
, NULL
);
2354 symbols
->add_variable(var
);
2355 linked_shader
->ir
->push_head(var
);
2365 * Combine a group of shaders for a single stage to generate a linked shader
2368 * If this function is supplied a single shader, it is cloned, and the new
2369 * shader is returned.
2371 struct gl_linked_shader
*
2372 link_intrastage_shaders(void *mem_ctx
,
2373 struct gl_context
*ctx
,
2374 struct gl_shader_program
*prog
,
2375 struct gl_shader
**shader_list
,
2376 unsigned num_shaders
,
2377 bool allow_missing_main
)
2379 struct gl_uniform_block
*ubo_blocks
= NULL
;
2380 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2381 unsigned num_ubo_blocks
= 0;
2382 unsigned num_ssbo_blocks
= 0;
2384 /* Check that global variables defined in multiple shaders are consistent.
2386 glsl_symbol_table variables
;
2387 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2388 if (shader_list
[i
] == NULL
)
2390 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2394 if (!prog
->data
->LinkStatus
)
2397 /* Check that interface blocks defined in multiple shaders are consistent.
2399 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2401 if (!prog
->data
->LinkStatus
)
2404 /* Check that there is only a single definition of each function signature
2405 * across all shaders.
2407 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2408 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2409 ir_function
*const f
= node
->as_function();
2414 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2415 ir_function
*const other
=
2416 shader_list
[j
]->symbols
->get_function(f
->name
);
2418 /* If the other shader has no function (and therefore no function
2419 * signatures) with the same name, skip to the next shader.
2424 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2425 if (!sig
->is_defined
)
2428 ir_function_signature
*other_sig
=
2429 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2431 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2432 linker_error(prog
, "function `%s' is multiply defined\n",
2441 /* Find the shader that defines main, and make a clone of it.
2443 * Starting with the clone, search for undefined references. If one is
2444 * found, find the shader that defines it. Clone the reference and add
2445 * it to the shader. Repeat until there are no undefined references or
2446 * until a reference cannot be resolved.
2448 gl_shader
*main
= NULL
;
2449 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2450 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2451 main
= shader_list
[i
];
2456 if (main
== NULL
&& allow_missing_main
)
2457 main
= shader_list
[0];
2460 linker_error(prog
, "%s shader lacks `main'\n",
2461 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2465 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2466 linked
->Stage
= shader_list
[0]->Stage
;
2468 /* Create program and attach it to the linked shader */
2469 struct gl_program
*gl_prog
=
2470 ctx
->Driver
.NewProgram(ctx
,
2471 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2474 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2475 _mesa_delete_linked_shader(ctx
, linked
);
2479 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2481 /* Don't use _mesa_reference_program() just take ownership */
2482 linked
->Program
= gl_prog
;
2484 linked
->ir
= new(linked
) exec_list
;
2485 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2487 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2488 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2489 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2490 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2491 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2493 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2494 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2496 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2498 link_layer_viewport_relative_qualifier(prog
, gl_prog
, shader_list
, num_shaders
);
2500 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2502 /* The pointer to the main function in the final linked shader (i.e., the
2503 * copy of the original shader that contained the main function).
2505 ir_function_signature
*const main_sig
=
2506 _mesa_get_main_function_signature(linked
->symbols
);
2508 /* Move any instructions other than variable declarations or function
2509 * declarations into main.
2511 if (main_sig
!= NULL
) {
2512 exec_node
*insertion_point
=
2513 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2516 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2517 if (shader_list
[i
] == main
)
2520 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2521 insertion_point
, true, linked
);
2525 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2526 _mesa_delete_linked_shader(ctx
, linked
);
2530 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2531 link_output_variables(linked
, shader_list
, num_shaders
);
2533 /* Make a pass over all variable declarations to ensure that arrays with
2534 * unspecified sizes have a size specified. The size is inferred from the
2535 * max_array_access field.
2537 array_sizing_visitor v
;
2539 v
.fixup_unnamed_interface_types();
2541 /* Link up uniform blocks defined within this stage. */
2542 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2543 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2545 const unsigned max_uniform_blocks
=
2546 ctx
->Const
.Program
[linked
->Stage
].MaxUniformBlocks
;
2547 if (num_ubo_blocks
> max_uniform_blocks
) {
2548 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2549 _mesa_shader_stage_to_string(linked
->Stage
),
2550 num_ubo_blocks
, max_uniform_blocks
);
2553 const unsigned max_shader_storage_blocks
=
2554 ctx
->Const
.Program
[linked
->Stage
].MaxShaderStorageBlocks
;
2555 if (num_ssbo_blocks
> max_shader_storage_blocks
) {
2556 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2557 _mesa_shader_stage_to_string(linked
->Stage
),
2558 num_ssbo_blocks
, max_shader_storage_blocks
);
2561 if (!prog
->data
->LinkStatus
) {
2562 _mesa_delete_linked_shader(ctx
, linked
);
2566 /* Copy ubo blocks to linked shader list */
2567 linked
->Program
->sh
.UniformBlocks
=
2568 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2569 ralloc_steal(linked
, ubo_blocks
);
2570 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2571 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2573 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2575 /* Copy ssbo blocks to linked shader list */
2576 linked
->Program
->sh
.ShaderStorageBlocks
=
2577 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2578 ralloc_steal(linked
, ssbo_blocks
);
2579 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2580 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2582 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2584 /* At this point linked should contain all of the linked IR, so
2585 * validate it to make sure nothing went wrong.
2587 validate_ir_tree(linked
->ir
);
2589 /* Set the size of geometry shader input arrays */
2590 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2591 unsigned num_vertices
=
2592 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2593 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2594 MESA_SHADER_GEOMETRY
);
2595 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2596 ir
->accept(&input_resize_visitor
);
2600 if (ctx
->Const
.VertexID_is_zero_based
)
2601 lower_vertex_id(linked
);
2603 if (ctx
->Const
.LowerCsDerivedVariables
)
2604 lower_cs_derived(linked
);
2607 /* Compute the source checksum. */
2608 linked
->SourceChecksum
= 0;
2609 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2610 if (shader_list
[i
] == NULL
)
2612 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2620 * Update the sizes of linked shader uniform arrays to the maximum
2623 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2625 * If one or more elements of an array are active,
2626 * GetActiveUniform will return the name of the array in name,
2627 * subject to the restrictions listed above. The type of the array
2628 * is returned in type. The size parameter contains the highest
2629 * array element index used, plus one. The compiler or linker
2630 * determines the highest index used. There will be only one
2631 * active uniform reported by the GL per uniform array.
2635 update_array_sizes(struct gl_shader_program
*prog
)
2637 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2638 if (prog
->_LinkedShaders
[i
] == NULL
)
2641 bool types_were_updated
= false;
2643 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2644 ir_variable
*const var
= node
->as_variable();
2646 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2647 !var
->type
->is_array())
2650 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2651 * will not be eliminated. Since we always do std140, just
2652 * don't resize arrays in UBOs.
2654 * Atomic counters are supposed to get deterministic
2655 * locations assigned based on the declaration ordering and
2656 * sizes, array compaction would mess that up.
2658 * Subroutine uniforms are not removed.
2660 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2661 var
->type
->contains_subroutine() || var
->constant_initializer
)
2664 int size
= var
->data
.max_array_access
;
2665 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2666 if (prog
->_LinkedShaders
[j
] == NULL
)
2669 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2670 ir_variable
*other_var
= node2
->as_variable();
2674 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2675 other_var
->data
.max_array_access
> size
) {
2676 size
= other_var
->data
.max_array_access
;
2681 if (size
+ 1 != (int)var
->type
->length
) {
2682 /* If this is a built-in uniform (i.e., it's backed by some
2683 * fixed-function state), adjust the number of state slots to
2684 * match the new array size. The number of slots per array entry
2685 * is not known. It seems safe to assume that the total number of
2686 * slots is an integer multiple of the number of array elements.
2687 * Determine the number of slots per array element by dividing by
2688 * the old (total) size.
2690 const unsigned num_slots
= var
->get_num_state_slots();
2691 if (num_slots
> 0) {
2692 var
->set_num_state_slots((size
+ 1)
2693 * (num_slots
/ var
->type
->length
));
2696 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2698 types_were_updated
= true;
2702 /* Update the types of dereferences in case we changed any. */
2703 if (types_were_updated
) {
2704 deref_type_updater v
;
2705 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2711 * Resize tessellation evaluation per-vertex inputs to the size of
2712 * tessellation control per-vertex outputs.
2715 resize_tes_inputs(struct gl_context
*ctx
,
2716 struct gl_shader_program
*prog
)
2718 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2721 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2722 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2724 /* If no control shader is present, then the TES inputs are statically
2725 * sized to MaxPatchVertices; the actual size of the arrays won't be
2726 * known until draw time.
2728 const int num_vertices
= tcs
2729 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2730 : ctx
->Const
.MaxPatchVertices
;
2732 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2733 MESA_SHADER_TESS_EVAL
);
2734 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2735 ir
->accept(&input_resize_visitor
);
2739 /* Convert the gl_PatchVerticesIn system value into a constant, since
2740 * the value is known at this point.
2742 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2743 ir_variable
*var
= ir
->as_variable();
2744 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2745 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2746 void *mem_ctx
= ralloc_parent(var
);
2747 var
->data
.location
= 0;
2748 var
->data
.explicit_location
= false;
2749 var
->data
.mode
= ir_var_auto
;
2750 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2757 * Find a contiguous set of available bits in a bitmask.
2759 * \param used_mask Bits representing used (1) and unused (0) locations
2760 * \param needed_count Number of contiguous bits needed.
2763 * Base location of the available bits on success or -1 on failure.
2766 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2768 unsigned needed_mask
= (1 << needed_count
) - 1;
2769 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2771 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2772 * cannot optimize possibly infinite loops" for the loop below.
2774 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2777 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2778 if ((needed_mask
& ~used_mask
) == needed_mask
)
2788 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2791 * Assign locations for either VS inputs or FS outputs.
2793 * \param mem_ctx Temporary ralloc context used for linking.
2794 * \param prog Shader program whose variables need locations
2796 * \param constants Driver specific constant values for the program.
2797 * \param target_index Selector for the program target to receive location
2798 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2799 * \c MESA_SHADER_FRAGMENT.
2800 * \param do_assignment Whether we are actually marking the assignment or we
2801 * are just doing a dry-run checking.
2804 * If locations are (or can be, in case of dry-running) successfully assigned,
2805 * true is returned. Otherwise an error is emitted to the shader link log and
2806 * false is returned.
2809 assign_attribute_or_color_locations(void *mem_ctx
,
2810 gl_shader_program
*prog
,
2811 struct gl_constants
*constants
,
2812 unsigned target_index
,
2815 /* Maximum number of generic locations. This corresponds to either the
2816 * maximum number of draw buffers or the maximum number of generic
2819 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2820 constants
->Program
[target_index
].MaxAttribs
:
2821 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2823 /* Mark invalid locations as being used.
2825 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2826 unsigned double_storage_locations
= 0;
2828 assert((target_index
== MESA_SHADER_VERTEX
)
2829 || (target_index
== MESA_SHADER_FRAGMENT
));
2831 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2835 /* Operate in a total of four passes.
2837 * 1. Invalidate the location assignments for all vertex shader inputs.
2839 * 2. Assign locations for inputs that have user-defined (via
2840 * glBindVertexAttribLocation) locations and outputs that have
2841 * user-defined locations (via glBindFragDataLocation).
2843 * 3. Sort the attributes without assigned locations by number of slots
2844 * required in decreasing order. Fragmentation caused by attribute
2845 * locations assigned by the application may prevent large attributes
2846 * from having enough contiguous space.
2848 * 4. Assign locations to any inputs without assigned locations.
2851 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2852 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2854 const enum ir_variable_mode direction
=
2855 (target_index
== MESA_SHADER_VERTEX
)
2856 ? ir_var_shader_in
: ir_var_shader_out
;
2859 /* Temporary storage for the set of attributes that need locations assigned.
2865 /* Used below in the call to qsort. */
2866 static int compare(const void *a
, const void *b
)
2868 const temp_attr
*const l
= (const temp_attr
*) a
;
2869 const temp_attr
*const r
= (const temp_attr
*) b
;
2871 /* Reversed because we want a descending order sort below. */
2872 return r
->slots
- l
->slots
;
2875 assert(max_index
<= 32);
2877 /* Temporary array for the set of attributes that have locations assigned,
2878 * for the purpose of checking overlapping slots/components of (non-ES)
2879 * fragment shader outputs.
2881 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2882 unsigned assigned_attr
= 0;
2884 unsigned num_attr
= 0;
2886 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2887 ir_variable
*const var
= node
->as_variable();
2889 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2892 if (var
->data
.explicit_location
) {
2893 var
->data
.is_unmatched_generic_inout
= 0;
2894 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2895 || (var
->data
.location
< 0)) {
2897 "invalid explicit location %d specified for `%s'\n",
2898 (var
->data
.location
< 0)
2899 ? var
->data
.location
2900 : var
->data
.location
- generic_base
,
2904 } else if (target_index
== MESA_SHADER_VERTEX
) {
2907 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2908 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2909 var
->data
.location
= binding
;
2910 var
->data
.is_unmatched_generic_inout
= 0;
2912 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2915 const char *name
= var
->name
;
2916 const glsl_type
*type
= var
->type
;
2919 /* Check if there's a binding for the variable name */
2920 if (prog
->FragDataBindings
->get(binding
, name
)) {
2921 assert(binding
>= FRAG_RESULT_DATA0
);
2922 var
->data
.location
= binding
;
2923 var
->data
.is_unmatched_generic_inout
= 0;
2925 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2926 var
->data
.index
= index
;
2931 /* If not, but it's an array type, look for name[0] */
2932 if (type
->is_array()) {
2933 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2934 type
= type
->fields
.array
;
2942 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2945 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2947 * "Output binding assignments will cause LinkProgram to fail:
2949 * If the program has an active output assigned to a location greater
2950 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2951 * an active output assigned an index greater than or equal to one;"
2953 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2954 var
->data
.location
- generic_base
>=
2955 (int) constants
->MaxDualSourceDrawBuffers
) {
2957 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2958 "with index %u for %s\n",
2959 var
->data
.location
- generic_base
, var
->data
.index
,
2964 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2966 /* If the variable is not a built-in and has a location statically
2967 * assigned in the shader (presumably via a layout qualifier), make sure
2968 * that it doesn't collide with other assigned locations. Otherwise,
2969 * add it to the list of variables that need linker-assigned locations.
2971 if (var
->data
.location
!= -1) {
2972 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2973 /* From page 61 of the OpenGL 4.0 spec:
2975 * "LinkProgram will fail if the attribute bindings assigned
2976 * by BindAttribLocation do not leave not enough space to
2977 * assign a location for an active matrix attribute or an
2978 * active attribute array, both of which require multiple
2979 * contiguous generic attributes."
2981 * I think above text prohibits the aliasing of explicit and
2982 * automatic assignments. But, aliasing is allowed in manual
2983 * assignments of attribute locations. See below comments for
2986 * From OpenGL 4.0 spec, page 61:
2988 * "It is possible for an application to bind more than one
2989 * attribute name to the same location. This is referred to as
2990 * aliasing. This will only work if only one of the aliased
2991 * attributes is active in the executable program, or if no
2992 * path through the shader consumes more than one attribute of
2993 * a set of attributes aliased to the same location. A link
2994 * error can occur if the linker determines that every path
2995 * through the shader consumes multiple aliased attributes,
2996 * but implementations are not required to generate an error
2999 * From GLSL 4.30 spec, page 54:
3001 * "A program will fail to link if any two non-vertex shader
3002 * input variables are assigned to the same location. For
3003 * vertex shaders, multiple input variables may be assigned
3004 * to the same location using either layout qualifiers or via
3005 * the OpenGL API. However, such aliasing is intended only to
3006 * support vertex shaders where each execution path accesses
3007 * at most one input per each location. Implementations are
3008 * permitted, but not required, to generate link-time errors
3009 * if they detect that every path through the vertex shader
3010 * executable accesses multiple inputs assigned to any single
3011 * location. For all shader types, a program will fail to link
3012 * if explicit location assignments leave the linker unable
3013 * to find space for other variables without explicit
3016 * From OpenGL ES 3.0 spec, page 56:
3018 * "Binding more than one attribute name to the same location
3019 * is referred to as aliasing, and is not permitted in OpenGL
3020 * ES Shading Language 3.00 vertex shaders. LinkProgram will
3021 * fail when this condition exists. However, aliasing is
3022 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
3023 * This will only work if only one of the aliased attributes
3024 * is active in the executable program, or if no path through
3025 * the shader consumes more than one attribute of a set of
3026 * attributes aliased to the same location. A link error can
3027 * occur if the linker determines that every path through the
3028 * shader consumes multiple aliased attributes, but implemen-
3029 * tations are not required to generate an error in this case."
3031 * After looking at above references from OpenGL, OpenGL ES and
3032 * GLSL specifications, we allow aliasing of vertex input variables
3033 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
3035 * NOTE: This is not required by the spec but its worth mentioning
3036 * here that we're not doing anything to make sure that no path
3037 * through the vertex shader executable accesses multiple inputs
3038 * assigned to any single location.
3041 /* Mask representing the contiguous slots that will be used by
3044 const unsigned attr
= var
->data
.location
- generic_base
;
3045 const unsigned use_mask
= (1 << slots
) - 1;
3046 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3047 ? "vertex shader input" : "fragment shader output";
3049 /* Generate a link error if the requested locations for this
3050 * attribute exceed the maximum allowed attribute location.
3052 if (attr
+ slots
> max_index
) {
3054 "insufficient contiguous locations "
3055 "available for %s `%s' %d %d %d\n", string
,
3056 var
->name
, used_locations
, use_mask
, attr
);
3060 /* Generate a link error if the set of bits requested for this
3061 * attribute overlaps any previously allocated bits.
3063 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
3064 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3065 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3068 * "Additionally, for fragment shader outputs, if two
3069 * variables are placed within the same location, they
3070 * must have the same underlying type (floating-point or
3071 * integer). No component aliasing of output variables or
3072 * members is allowed.
3074 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
3075 unsigned assigned_slots
=
3076 assigned
[i
]->type
->count_attribute_slots(false);
3077 unsigned assig_attr
=
3078 assigned
[i
]->data
.location
- generic_base
;
3079 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
3081 if ((assigned_use_mask
<< assig_attr
) &
3082 (use_mask
<< attr
)) {
3084 const glsl_type
*assigned_type
=
3085 assigned
[i
]->type
->without_array();
3086 const glsl_type
*type
= var
->type
->without_array();
3087 if (assigned_type
->base_type
!= type
->base_type
) {
3088 linker_error(prog
, "types do not match for aliased"
3089 " %ss %s and %s\n", string
,
3090 assigned
[i
]->name
, var
->name
);
3094 unsigned assigned_component_mask
=
3095 ((1 << assigned_type
->vector_elements
) - 1) <<
3096 assigned
[i
]->data
.location_frac
;
3097 unsigned component_mask
=
3098 ((1 << type
->vector_elements
) - 1) <<
3099 var
->data
.location_frac
;
3100 if (assigned_component_mask
& component_mask
) {
3101 linker_error(prog
, "overlapping component is "
3102 "assigned to %ss %s and %s "
3104 string
, assigned
[i
]->name
, var
->name
,
3105 var
->data
.location_frac
);
3110 } else if (target_index
== MESA_SHADER_FRAGMENT
||
3111 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
3112 linker_error(prog
, "overlapping location is assigned "
3113 "to %s `%s' %d %d %d\n", string
, var
->name
,
3114 used_locations
, use_mask
, attr
);
3117 linker_warning(prog
, "overlapping location is assigned "
3118 "to %s `%s' %d %d %d\n", string
, var
->name
,
3119 used_locations
, use_mask
, attr
);
3123 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3124 /* Only track assigned variables for non-ES fragment shaders
3125 * to avoid overflowing the array.
3127 * At most one variable per fragment output component should
3130 assert(assigned_attr
< ARRAY_SIZE(assigned
));
3131 assigned
[assigned_attr
] = var
;
3135 used_locations
|= (use_mask
<< attr
);
3137 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3139 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3140 * active attribute variables may fail to link, unless
3141 * device-dependent optimizations are able to make the program
3142 * fit within available hardware resources. For the purposes
3143 * of this test, attribute variables of the type dvec3, dvec4,
3144 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3145 * count as consuming twice as many attributes as equivalent
3146 * single-precision types. While these types use the same number
3147 * of generic attributes as their single-precision equivalents,
3148 * implementations are permitted to consume two single-precision
3149 * vectors of internal storage for each three- or four-component
3150 * double-precision vector."
3152 * Mark this attribute slot as taking up twice as much space
3153 * so we can count it properly against limits. According to
3154 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3155 * is optional behavior, but it seems preferable.
3157 if (var
->type
->without_array()->is_dual_slot())
3158 double_storage_locations
|= (use_mask
<< attr
);
3164 if (num_attr
>= max_index
) {
3165 linker_error(prog
, "too many %s (max %u)",
3166 target_index
== MESA_SHADER_VERTEX
?
3167 "vertex shader inputs" : "fragment shader outputs",
3171 to_assign
[num_attr
].slots
= slots
;
3172 to_assign
[num_attr
].var
= var
;
3179 if (target_index
== MESA_SHADER_VERTEX
) {
3180 unsigned total_attribs_size
=
3181 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3182 util_bitcount(double_storage_locations
);
3183 if (total_attribs_size
> max_index
) {
3185 "attempt to use %d vertex attribute slots only %d available ",
3186 total_attribs_size
, max_index
);
3191 /* If all of the attributes were assigned locations by the application (or
3192 * are built-in attributes with fixed locations), return early. This should
3193 * be the common case.
3198 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
3200 if (target_index
== MESA_SHADER_VERTEX
) {
3201 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3202 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3203 * reserved to prevent it from being automatically allocated below.
3205 find_deref_visitor
find("gl_Vertex");
3207 if (find
.variable_found())
3208 used_locations
|= (1 << 0);
3211 for (unsigned i
= 0; i
< num_attr
; i
++) {
3212 /* Mask representing the contiguous slots that will be used by this
3215 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3217 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3220 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3221 ? "vertex shader input" : "fragment shader output";
3224 "insufficient contiguous locations "
3225 "available for %s `%s'\n",
3226 string
, to_assign
[i
].var
->name
);
3230 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3231 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3232 used_locations
|= (use_mask
<< location
);
3234 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3235 double_storage_locations
|= (use_mask
<< location
);
3238 /* Now that we have all the locations, from the GL 4.5 core spec, section
3239 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3240 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3241 * as equivalent single-precision types.
3243 if (target_index
== MESA_SHADER_VERTEX
) {
3244 unsigned total_attribs_size
=
3245 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3246 util_bitcount(double_storage_locations
);
3247 if (total_attribs_size
> max_index
) {
3249 "attempt to use %d vertex attribute slots only %d available ",
3250 total_attribs_size
, max_index
);
3259 * Match explicit locations of outputs to inputs and deactivate the
3260 * unmatch flag if found so we don't optimise them away.
3263 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3264 gl_linked_shader
*consumer
)
3266 glsl_symbol_table parameters
;
3267 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3270 /* Find all shader outputs in the "producer" stage.
3272 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3273 ir_variable
*const var
= node
->as_variable();
3275 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3278 if (var
->data
.explicit_location
&&
3279 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3280 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3281 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3282 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3284 /* Always match TCS outputs. They are shared by all invocations
3285 * within a patch and can be used as shared memory.
3287 if (producer
->Stage
== MESA_SHADER_TESS_CTRL
)
3288 var
->data
.is_unmatched_generic_inout
= 0;
3292 /* Match inputs to outputs */
3293 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3294 ir_variable
*const input
= node
->as_variable();
3296 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3299 ir_variable
*output
= NULL
;
3300 if (input
->data
.explicit_location
3301 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3302 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3303 [input
->data
.location_frac
];
3305 if (output
!= NULL
){
3306 input
->data
.is_unmatched_generic_inout
= 0;
3307 output
->data
.is_unmatched_generic_inout
= 0;
3314 * Store the gl_FragDepth layout in the gl_shader_program struct.
3317 store_fragdepth_layout(struct gl_shader_program
*prog
)
3319 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3323 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3325 /* We don't look up the gl_FragDepth symbol directly because if
3326 * gl_FragDepth is not used in the shader, it's removed from the IR.
3327 * However, the symbol won't be removed from the symbol table.
3329 * We're only interested in the cases where the variable is NOT removed
3332 foreach_in_list(ir_instruction
, node
, ir
) {
3333 ir_variable
*const var
= node
->as_variable();
3335 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3339 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3340 switch (var
->data
.depth_layout
) {
3341 case ir_depth_layout_none
:
3342 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3344 case ir_depth_layout_any
:
3345 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3347 case ir_depth_layout_greater
:
3348 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3350 case ir_depth_layout_less
:
3351 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3353 case ir_depth_layout_unchanged
:
3354 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3365 * Validate shader image resources.
3368 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3370 unsigned total_image_units
= 0;
3371 unsigned fragment_outputs
= 0;
3372 unsigned total_shader_storage_blocks
= 0;
3374 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3377 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3378 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3381 total_image_units
+= sh
->Program
->info
.num_images
;
3382 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3384 if (i
== MESA_SHADER_FRAGMENT
) {
3385 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3386 ir_variable
*var
= node
->as_variable();
3387 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3388 /* since there are no double fs outputs - pass false */
3389 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3395 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3396 linker_error(prog
, "Too many combined image uniforms\n");
3398 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3399 ctx
->Const
.MaxCombinedShaderOutputResources
)
3400 linker_error(prog
, "Too many combined image uniforms, shader storage "
3401 " buffers and fragment outputs\n");
3406 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3407 * for a variable, checks for overlaps between other uniforms using explicit
3411 reserve_explicit_locations(struct gl_shader_program
*prog
,
3412 string_to_uint_map
*map
, ir_variable
*var
)
3414 unsigned slots
= var
->type
->uniform_locations();
3415 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3416 unsigned return_value
= slots
;
3418 /* Resize remap table if locations do not fit in the current one. */
3419 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3420 prog
->UniformRemapTable
=
3421 reralloc(prog
, prog
->UniformRemapTable
,
3422 gl_uniform_storage
*,
3425 if (!prog
->UniformRemapTable
) {
3426 linker_error(prog
, "Out of memory during linking.\n");
3430 /* Initialize allocated space. */
3431 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3432 prog
->UniformRemapTable
[i
] = NULL
;
3434 prog
->NumUniformRemapTable
= max_loc
+ 1;
3437 for (unsigned i
= 0; i
< slots
; i
++) {
3438 unsigned loc
= var
->data
.location
+ i
;
3440 /* Check if location is already used. */
3441 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3443 /* Possibly same uniform from a different stage, this is ok. */
3445 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3450 /* ARB_explicit_uniform_location specification states:
3452 * "No two default-block uniform variables in the program can have
3453 * the same location, even if they are unused, otherwise a compiler
3454 * or linker error will be generated."
3457 "location qualifier for uniform %s overlaps "
3458 "previously used location\n",
3463 /* Initialize location as inactive before optimization
3464 * rounds and location assignment.
3466 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3469 /* Note, base location used for arrays. */
3470 map
->put(var
->data
.location
, var
->name
);
3472 return return_value
;
3476 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3477 struct gl_program
*p
,
3480 unsigned slots
= var
->type
->uniform_locations();
3481 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3483 /* Resize remap table if locations do not fit in the current one. */
3484 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3485 p
->sh
.SubroutineUniformRemapTable
=
3486 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3487 gl_uniform_storage
*,
3490 if (!p
->sh
.SubroutineUniformRemapTable
) {
3491 linker_error(prog
, "Out of memory during linking.\n");
3495 /* Initialize allocated space. */
3496 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3497 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3499 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3502 for (unsigned i
= 0; i
< slots
; i
++) {
3503 unsigned loc
= var
->data
.location
+ i
;
3505 /* Check if location is already used. */
3506 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3508 /* ARB_explicit_uniform_location specification states:
3509 * "No two subroutine uniform variables can have the same location
3510 * in the same shader stage, otherwise a compiler or linker error
3511 * will be generated."
3514 "location qualifier for uniform %s overlaps "
3515 "previously used location\n",
3520 /* Initialize location as inactive before optimization
3521 * rounds and location assignment.
3523 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3529 * Check and reserve all explicit uniform locations, called before
3530 * any optimizations happen to handle also inactive uniforms and
3531 * inactive array elements that may get trimmed away.
3534 check_explicit_uniform_locations(struct gl_context
*ctx
,
3535 struct gl_shader_program
*prog
)
3537 prog
->NumExplicitUniformLocations
= 0;
3539 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3542 /* This map is used to detect if overlapping explicit locations
3543 * occur with the same uniform (from different stage) or a different one.
3545 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3548 linker_error(prog
, "Out of memory during linking.\n");
3552 unsigned entries_total
= 0;
3553 unsigned mask
= prog
->data
->linked_stages
;
3555 const int i
= u_bit_scan(&mask
);
3556 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3558 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3559 ir_variable
*var
= node
->as_variable();
3560 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3563 if (var
->data
.explicit_location
) {
3565 if (var
->type
->without_array()->is_subroutine())
3566 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3568 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3572 entries_total
+= slots
;
3583 link_util_update_empty_uniform_locations(prog
);
3586 prog
->NumExplicitUniformLocations
= entries_total
;
3589 /* Function checks if a variable var is a packed varying and
3590 * if given name is part of packed varying's list.
3592 * If a variable is a packed varying, it has a name like
3593 * 'packed:a,b,c' where a, b and c are separate variables.
3596 included_in_packed_varying(ir_variable
*var
, const char *name
)
3598 if (strncmp(var
->name
, "packed:", 7) != 0)
3601 char *list
= strdup(var
->name
+ 7);
3606 char *token
= strtok_r(list
, ",", &saveptr
);
3608 if (strcmp(token
, name
) == 0) {
3612 token
= strtok_r(NULL
, ",", &saveptr
);
3619 * Function builds a stage reference bitmask from variable name.
3622 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3627 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3628 * used for reference mask in gl_program_resource will need to be changed.
3630 assert(MESA_SHADER_STAGES
< 8);
3632 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3633 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3637 /* Shader symbol table may contain variables that have
3638 * been optimized away. Search IR for the variable instead.
3640 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3641 ir_variable
*var
= node
->as_variable();
3643 unsigned baselen
= strlen(var
->name
);
3645 if (included_in_packed_varying(var
, name
)) {
3650 /* Type needs to match if specified, otherwise we might
3651 * pick a variable with same name but different interface.
3653 if (var
->data
.mode
!= mode
)
3656 if (strncmp(var
->name
, name
, baselen
) == 0) {
3657 /* Check for exact name matches but also check for arrays and
3660 if (name
[baselen
] == '\0' ||
3661 name
[baselen
] == '[' ||
3662 name
[baselen
] == '.') {
3674 * Create gl_shader_variable from ir_variable class.
3676 static gl_shader_variable
*
3677 create_shader_variable(struct gl_shader_program
*shProg
,
3678 const ir_variable
*in
,
3679 const char *name
, const glsl_type
*type
,
3680 const glsl_type
*interface_type
,
3681 bool use_implicit_location
, int location
,
3682 const glsl_type
*outermost_struct_type
)
3684 /* Allocate zero-initialized memory to ensure that bitfield padding
3687 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3691 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3692 * expect to see gl_VertexID in the program resource list. Pretend.
3694 if (in
->data
.mode
== ir_var_system_value
&&
3695 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3696 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3697 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3698 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3699 (in
->data
.mode
== ir_var_system_value
&&
3700 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3701 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3702 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3703 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3704 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3705 (in
->data
.mode
== ir_var_system_value
&&
3706 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3707 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3708 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3710 out
->name
= ralloc_strdup(shProg
, name
);
3716 /* The ARB_program_interface_query spec says:
3718 * "Not all active variables are assigned valid locations; the
3719 * following variables will have an effective location of -1:
3721 * * uniforms declared as atomic counters;
3723 * * members of a uniform block;
3725 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3727 * * inputs or outputs not declared with a "location" layout
3728 * qualifier, except for vertex shader inputs and fragment shader
3731 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3732 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3735 out
->location
= location
;
3739 out
->outermost_struct_type
= outermost_struct_type
;
3740 out
->interface_type
= interface_type
;
3741 out
->component
= in
->data
.location_frac
;
3742 out
->index
= in
->data
.index
;
3743 out
->patch
= in
->data
.patch
;
3744 out
->mode
= in
->data
.mode
;
3745 out
->interpolation
= in
->data
.interpolation
;
3746 out
->explicit_location
= in
->data
.explicit_location
;
3747 out
->precision
= in
->data
.precision
;
3753 add_shader_variable(const struct gl_context
*ctx
,
3754 struct gl_shader_program
*shProg
,
3755 struct set
*resource_set
,
3756 unsigned stage_mask
,
3757 GLenum programInterface
, ir_variable
*var
,
3758 const char *name
, const glsl_type
*type
,
3759 bool use_implicit_location
, int location
,
3760 bool inouts_share_location
,
3761 const glsl_type
*outermost_struct_type
= NULL
)
3763 const glsl_type
*interface_type
= var
->get_interface_type();
3765 if (outermost_struct_type
== NULL
) {
3766 if (var
->data
.from_named_ifc_block
) {
3767 const char *interface_name
= interface_type
->name
;
3769 if (interface_type
->is_array()) {
3770 /* Issue #16 of the ARB_program_interface_query spec says:
3772 * "* If a variable is a member of an interface block without an
3773 * instance name, it is enumerated using just the variable name.
3775 * * If a variable is a member of an interface block with an
3776 * instance name, it is enumerated as "BlockName.Member", where
3777 * "BlockName" is the name of the interface block (not the
3778 * instance name) and "Member" is the name of the variable."
3780 * In particular, it indicates that it should be "BlockName",
3781 * not "BlockName[array length]". The conformance suite and
3782 * dEQP both require this behavior.
3784 * Here, we unwrap the extra array level added by named interface
3785 * block array lowering so we have the correct variable type. We
3786 * also unwrap the interface type when constructing the name.
3788 * We leave interface_type the same so that ES 3.x SSO pipeline
3789 * validation can enforce the rules requiring array length to
3790 * match on interface blocks.
3792 type
= type
->fields
.array
;
3794 interface_name
= interface_type
->fields
.array
->name
;
3797 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3801 switch (type
->base_type
) {
3802 case GLSL_TYPE_STRUCT
: {
3803 /* The ARB_program_interface_query spec says:
3805 * "For an active variable declared as a structure, a separate entry
3806 * will be generated for each active structure member. The name of
3807 * each entry is formed by concatenating the name of the structure,
3808 * the "." character, and the name of the structure member. If a
3809 * structure member to enumerate is itself a structure or array,
3810 * these enumeration rules are applied recursively."
3812 if (outermost_struct_type
== NULL
)
3813 outermost_struct_type
= type
;
3815 unsigned field_location
= location
;
3816 for (unsigned i
= 0; i
< type
->length
; i
++) {
3817 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3818 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3819 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3820 stage_mask
, programInterface
,
3821 var
, field_name
, field
->type
,
3822 use_implicit_location
, field_location
,
3823 false, outermost_struct_type
))
3826 field_location
+= field
->type
->count_attribute_slots(false);
3831 case GLSL_TYPE_ARRAY
: {
3832 /* The ARB_program_interface_query spec says:
3834 * "For an active variable declared as an array of basic types, a
3835 * single entry will be generated, with its name string formed by
3836 * concatenating the name of the array and the string "[0]"."
3838 * "For an active variable declared as an array of an aggregate data
3839 * type (structures or arrays), a separate entry will be generated
3840 * for each active array element, unless noted immediately below.
3841 * The name of each entry is formed by concatenating the name of
3842 * the array, the "[" character, an integer identifying the element
3843 * number, and the "]" character. These enumeration rules are
3844 * applied recursively, treating each enumerated array element as a
3845 * separate active variable."
3847 const struct glsl_type
*array_type
= type
->fields
.array
;
3848 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3849 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3850 unsigned elem_location
= location
;
3851 unsigned stride
= inouts_share_location
? 0 :
3852 array_type
->count_attribute_slots(false);
3853 for (unsigned i
= 0; i
< type
->length
; i
++) {
3854 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3855 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3856 stage_mask
, programInterface
,
3857 var
, elem
, array_type
,
3858 use_implicit_location
, elem_location
,
3859 false, outermost_struct_type
))
3861 elem_location
+= stride
;
3869 /* The ARB_program_interface_query spec says:
3871 * "For an active variable declared as a single instance of a basic
3872 * type, a single entry will be generated, using the variable name
3873 * from the shader source."
3875 gl_shader_variable
*sha_v
=
3876 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3877 use_implicit_location
, location
,
3878 outermost_struct_type
);
3882 return link_util_add_program_resource(shProg
, resource_set
,
3883 programInterface
, sha_v
, stage_mask
);
3889 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3891 if (!var
->data
.patch
&&
3892 ((var
->data
.mode
== ir_var_shader_out
&&
3893 stage
== MESA_SHADER_TESS_CTRL
) ||
3894 (var
->data
.mode
== ir_var_shader_in
&&
3895 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3896 stage
== MESA_SHADER_GEOMETRY
))))
3903 add_interface_variables(const struct gl_context
*ctx
,
3904 struct gl_shader_program
*shProg
,
3905 struct set
*resource_set
,
3906 unsigned stage
, GLenum programInterface
)
3908 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3910 foreach_in_list(ir_instruction
, node
, ir
) {
3911 ir_variable
*var
= node
->as_variable();
3913 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3918 switch (var
->data
.mode
) {
3919 case ir_var_system_value
:
3920 case ir_var_shader_in
:
3921 if (programInterface
!= GL_PROGRAM_INPUT
)
3923 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3924 : int(VARYING_SLOT_VAR0
);
3926 case ir_var_shader_out
:
3927 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3929 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3930 : int(VARYING_SLOT_VAR0
);
3936 if (var
->data
.patch
)
3937 loc_bias
= int(VARYING_SLOT_PATCH0
);
3939 /* Skip packed varyings, packed varyings are handled separately
3940 * by add_packed_varyings.
3942 if (strncmp(var
->name
, "packed:", 7) == 0)
3945 /* Skip fragdata arrays, these are handled separately
3946 * by add_fragdata_arrays.
3948 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3951 const bool vs_input_or_fs_output
=
3952 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3953 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3955 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3956 1 << stage
, programInterface
,
3957 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3958 var
->data
.location
- loc_bias
,
3959 inout_has_same_location(var
, stage
)))
3966 add_packed_varyings(const struct gl_context
*ctx
,
3967 struct gl_shader_program
*shProg
,
3968 struct set
*resource_set
,
3969 int stage
, GLenum type
)
3971 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3974 if (!sh
|| !sh
->packed_varyings
)
3977 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3978 ir_variable
*var
= node
->as_variable();
3980 switch (var
->data
.mode
) {
3981 case ir_var_shader_in
:
3982 iface
= GL_PROGRAM_INPUT
;
3984 case ir_var_shader_out
:
3985 iface
= GL_PROGRAM_OUTPUT
;
3988 unreachable("unexpected type");
3991 if (type
== iface
) {
3992 const int stage_mask
=
3993 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3994 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3996 iface
, var
, var
->name
, var
->type
, false,
3997 var
->data
.location
- VARYING_SLOT_VAR0
,
3998 inout_has_same_location(var
, stage
)))
4007 add_fragdata_arrays(const struct gl_context
*ctx
,
4008 struct gl_shader_program
*shProg
,
4009 struct set
*resource_set
)
4011 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4013 if (!sh
|| !sh
->fragdata_arrays
)
4016 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4017 ir_variable
*var
= node
->as_variable();
4019 assert(var
->data
.mode
== ir_var_shader_out
);
4021 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4022 1 << MESA_SHADER_FRAGMENT
,
4023 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4024 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4033 * Builds up a list of program resources that point to existing
4037 build_program_resource_list(struct gl_context
*ctx
,
4038 struct gl_shader_program
*shProg
,
4039 bool add_packed_varyings_only
)
4041 /* Rebuild resource list. */
4042 if (shProg
->data
->ProgramResourceList
) {
4043 ralloc_free(shProg
->data
->ProgramResourceList
);
4044 shProg
->data
->ProgramResourceList
= NULL
;
4045 shProg
->data
->NumProgramResourceList
= 0;
4048 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4050 /* Determine first input and final output stage. These are used to
4051 * detect which variables should be enumerated in the resource list
4052 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4054 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4055 if (!shProg
->_LinkedShaders
[i
])
4057 if (input_stage
== MESA_SHADER_STAGES
)
4062 /* Empty shader, no resources. */
4063 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4066 struct set
*resource_set
= _mesa_pointer_set_create(NULL
);
4068 /* Program interface needs to expose varyings in case of SSO. */
4069 if (shProg
->SeparateShader
) {
4070 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4071 input_stage
, GL_PROGRAM_INPUT
))
4074 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4075 output_stage
, GL_PROGRAM_OUTPUT
))
4079 if (add_packed_varyings_only
) {
4080 _mesa_set_destroy(resource_set
, NULL
);
4084 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4087 /* Add inputs and outputs to the resource list. */
4088 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4089 input_stage
, GL_PROGRAM_INPUT
))
4092 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4093 output_stage
, GL_PROGRAM_OUTPUT
))
4096 if (shProg
->last_vert_prog
) {
4097 struct gl_transform_feedback_info
*linked_xfb
=
4098 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4100 /* Add transform feedback varyings. */
4101 if (linked_xfb
->NumVarying
> 0) {
4102 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4103 if (!link_util_add_program_resource(shProg
, resource_set
,
4104 GL_TRANSFORM_FEEDBACK_VARYING
,
4105 &linked_xfb
->Varyings
[i
], 0))
4110 /* Add transform feedback buffers. */
4111 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4112 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4113 linked_xfb
->Buffers
[i
].Binding
= i
;
4114 if (!link_util_add_program_resource(shProg
, resource_set
,
4115 GL_TRANSFORM_FEEDBACK_BUFFER
,
4116 &linked_xfb
->Buffers
[i
], 0))
4122 int top_level_array_base_offset
= -1;
4123 int top_level_array_size_in_bytes
= -1;
4124 int second_element_offset
= -1;
4125 int buffer_block_index
= -1;
4127 /* Add uniforms from uniform storage. */
4128 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4129 /* Do not add uniforms internally used by Mesa. */
4130 if (shProg
->data
->UniformStorage
[i
].hidden
)
4133 bool is_shader_storage
=
4134 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4135 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4136 if (!link_util_should_add_buffer_variable(shProg
,
4137 &shProg
->data
->UniformStorage
[i
],
4138 top_level_array_base_offset
,
4139 top_level_array_size_in_bytes
,
4140 second_element_offset
,
4141 buffer_block_index
))
4144 if (is_shader_storage
) {
4145 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4147 * "For an active shader storage block member declared as an array
4148 * of an aggregate type, an entry will be generated only for the
4149 * first array element, regardless of its type. Such block members
4150 * are referred to as top-level arrays. If the block member is an
4151 * aggregate type, the enumeration rules are then applied
4154 * Below we update our tracking values used by
4155 * link_util_should_add_buffer_variable(). We only want to reset the
4156 * offsets once we have moved past the first element.
4158 if (shProg
->data
->UniformStorage
[i
].offset
>= second_element_offset
) {
4159 top_level_array_base_offset
=
4160 shProg
->data
->UniformStorage
[i
].offset
;
4162 top_level_array_size_in_bytes
=
4163 shProg
->data
->UniformStorage
[i
].top_level_array_size
*
4164 shProg
->data
->UniformStorage
[i
].top_level_array_stride
;
4166 /* Set or reset the second element offset. For non arrays this
4167 * will be set to -1.
4169 second_element_offset
= top_level_array_size_in_bytes
?
4170 top_level_array_base_offset
+
4171 shProg
->data
->UniformStorage
[i
].top_level_array_stride
: -1;
4174 buffer_block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4177 uint8_t stageref
= shProg
->data
->UniformStorage
[i
].active_shader_mask
;
4178 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4179 &shProg
->data
->UniformStorage
[i
], stageref
))
4183 /* Add program uniform blocks. */
4184 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4185 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4186 &shProg
->data
->UniformBlocks
[i
], 0))
4190 /* Add program shader storage blocks. */
4191 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4192 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4193 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4197 /* Add atomic counter buffers. */
4198 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4199 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4200 &shProg
->data
->AtomicBuffers
[i
], 0))
4204 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4206 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4209 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4210 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4211 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4214 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4215 /* add shader subroutines */
4216 if (!link_util_add_program_resource(shProg
, resource_set
,
4217 type
, &shProg
->data
->UniformStorage
[i
], 0))
4222 unsigned mask
= shProg
->data
->linked_stages
;
4224 const int i
= u_bit_scan(&mask
);
4225 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4227 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4228 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4229 if (!link_util_add_program_resource(shProg
, resource_set
,
4230 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4235 _mesa_set_destroy(resource_set
, NULL
);
4239 * This check is done to make sure we allow only constant expression
4240 * indexing and "constant-index-expression" (indexing with an expression
4241 * that includes loop induction variable).
4244 validate_sampler_array_indexing(struct gl_context
*ctx
,
4245 struct gl_shader_program
*prog
)
4247 dynamic_sampler_array_indexing_visitor v
;
4248 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4249 if (prog
->_LinkedShaders
[i
] == NULL
)
4252 bool no_dynamic_indexing
=
4253 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4255 /* Search for array derefs in shader. */
4256 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4257 if (v
.uses_dynamic_sampler_array_indexing()) {
4258 const char *msg
= "sampler arrays indexed with non-constant "
4259 "expressions is forbidden in GLSL %s %u";
4260 /* Backend has indicated that it has no dynamic indexing support. */
4261 if (no_dynamic_indexing
) {
4262 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4263 prog
->data
->Version
);
4266 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4267 prog
->data
->Version
);
4275 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4277 unsigned mask
= prog
->data
->linked_stages
;
4279 const int i
= u_bit_scan(&mask
);
4280 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4282 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4283 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4284 ir_function
*fn
= node
->as_function();
4288 if (fn
->is_subroutine
)
4289 p
->sh
.NumSubroutineUniformTypes
++;
4291 if (!fn
->num_subroutine_types
)
4294 /* these should have been calculated earlier. */
4295 assert(fn
->subroutine_index
!= -1);
4296 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4297 linker_error(prog
, "Too many subroutine functions declared.\n");
4300 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4301 struct gl_subroutine_function
,
4302 p
->sh
.NumSubroutineFunctions
+ 1);
4303 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4304 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4305 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4306 ralloc_array(p
, const struct glsl_type
*,
4307 fn
->num_subroutine_types
);
4309 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4312 * "Each subroutine with an index qualifier in the shader must be
4313 * given a unique index, otherwise a compile or link error will be
4316 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4317 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4318 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4319 linker_error(prog
, "each subroutine index qualifier in the "
4320 "shader must be unique\n");
4324 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4325 fn
->subroutine_index
;
4327 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4328 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4330 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4331 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4332 p
->sh
.NumSubroutineFunctions
++;
4338 verify_subroutine_associated_funcs(struct gl_shader_program
*prog
)
4340 unsigned mask
= prog
->data
->linked_stages
;
4342 const int i
= u_bit_scan(&mask
);
4343 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4344 glsl_symbol_table
*symbols
= prog
->_LinkedShaders
[i
]->symbols
;
4346 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4348 * "A program will fail to compile or link if any shader
4349 * or stage contains two or more functions with the same
4350 * name if the name is associated with a subroutine type."
4352 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4353 unsigned definitions
= 0;
4354 char *name
= p
->sh
.SubroutineFunctions
[j
].name
;
4355 ir_function
*fn
= symbols
->get_function(name
);
4357 /* Calculate number of function definitions with the same name */
4358 foreach_in_list(ir_function_signature
, sig
, &fn
->signatures
) {
4359 if (sig
->is_defined
) {
4360 if (++definitions
> 1) {
4361 linker_error(prog
, "%s shader contains two or more function "
4362 "definitions with name `%s', which is "
4363 "associated with a subroutine type.\n",
4364 _mesa_shader_stage_to_string(i
),
4376 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4378 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4380 foreach_in_list(ir_instruction
, node
, ir
) {
4381 ir_variable
*const var
= node
->as_variable();
4383 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4386 /* Don't set always active on builtins that haven't been redeclared */
4387 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4390 var
->data
.always_active_io
= true;
4395 * When separate shader programs are enabled, only input/outputs between
4396 * the stages of a multi-stage separate program can be safely removed
4397 * from the shader interface. Other inputs/outputs must remain active.
4400 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4402 unsigned first
, last
;
4403 assert(prog
->SeparateShader
);
4405 first
= MESA_SHADER_STAGES
;
4408 /* Determine first and last stage. Excluding the compute stage */
4409 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4410 if (!prog
->_LinkedShaders
[i
])
4412 if (first
== MESA_SHADER_STAGES
)
4417 if (first
== MESA_SHADER_STAGES
)
4420 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4421 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4425 /* Prevent the removal of inputs to the first and outputs from the last
4426 * stage, unless they are the initial pipeline inputs or final pipeline
4427 * outputs, respectively.
4429 * The removal of IO between shaders in the same program is always
4432 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4433 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4434 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4435 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4440 link_and_validate_uniforms(struct gl_context
*ctx
,
4441 struct gl_shader_program
*prog
)
4443 update_array_sizes(prog
);
4445 if (!ctx
->Const
.UseNIRGLSLLinker
) {
4446 link_assign_uniform_locations(prog
, ctx
);
4448 if (prog
->data
->LinkStatus
== LINKING_FAILURE
)
4451 link_util_calculate_subroutine_compat(prog
);
4452 link_util_check_uniform_resources(ctx
, prog
);
4453 link_util_check_subroutine_resources(prog
);
4454 check_image_resources(ctx
, prog
);
4455 link_assign_atomic_counter_resources(ctx
, prog
);
4456 link_check_atomic_counter_resources(ctx
, prog
);
4461 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4462 struct gl_context
*ctx
,
4463 struct gl_shader_program
*prog
, void *mem_ctx
)
4465 /* Mark all generic shader inputs and outputs as unpaired. */
4466 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4467 if (prog
->_LinkedShaders
[i
] != NULL
) {
4468 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4472 unsigned prev
= first
;
4473 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4474 if (prog
->_LinkedShaders
[i
] == NULL
)
4477 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4478 prog
->_LinkedShaders
[i
]);
4482 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4483 MESA_SHADER_VERTEX
, true)) {
4487 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4488 MESA_SHADER_FRAGMENT
, true)) {
4492 prog
->last_vert_prog
= NULL
;
4493 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4494 if (prog
->_LinkedShaders
[i
] == NULL
)
4497 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4501 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4504 link_and_validate_uniforms(ctx
, prog
);
4506 if (!prog
->data
->LinkStatus
)
4509 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4510 if (prog
->_LinkedShaders
[i
] == NULL
)
4513 const struct gl_shader_compiler_options
*options
=
4514 &ctx
->Const
.ShaderCompilerOptions
[i
];
4516 if (options
->LowerBufferInterfaceBlocks
)
4517 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4518 options
->ClampBlockIndicesToArrayBounds
,
4519 ctx
->Const
.UseSTD430AsDefaultPacking
);
4521 if (i
== MESA_SHADER_COMPUTE
)
4522 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4524 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4525 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4532 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4535 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4536 /* Run it just once. */
4537 do_common_optimization(ir
, true, false,
4538 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4539 ctx
->Const
.NativeIntegers
);
4541 /* Repeat it until it stops making changes. */
4542 while (do_common_optimization(ir
, true, false,
4543 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4544 ctx
->Const
.NativeIntegers
))
4550 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4552 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4553 prog
->data
->Validated
= false;
4555 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4557 * "Linking can fail for a variety of reasons as specified in the
4558 * OpenGL Shading Language Specification, as well as any of the
4559 * following reasons:
4561 * - No shader objects are attached to program."
4563 * The Compatibility Profile specification does not list the error. In
4564 * Compatibility Profile missing shader stages are replaced by
4565 * fixed-function. This applies to the case where all stages are
4568 if (prog
->NumShaders
== 0) {
4569 if (ctx
->API
!= API_OPENGL_COMPAT
)
4570 linker_error(prog
, "no shaders attached to the program\n");
4574 #ifdef ENABLE_SHADER_CACHE
4575 if (shader_cache_read_program_metadata(ctx
, prog
))
4579 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4581 prog
->ARB_fragment_coord_conventions_enable
= false;
4583 /* Separate the shaders into groups based on their type.
4585 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4586 unsigned num_shaders
[MESA_SHADER_STAGES
];
4588 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4589 shader_list
[i
] = (struct gl_shader
**)
4590 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4594 unsigned min_version
= UINT_MAX
;
4595 unsigned max_version
= 0;
4596 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4597 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4598 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4600 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4601 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4602 linker_error(prog
, "all shaders must use same shading "
4603 "language version\n");
4607 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4608 prog
->ARB_fragment_coord_conventions_enable
= true;
4611 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4612 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4613 num_shaders
[shader_type
]++;
4616 /* In desktop GLSL, different shader versions may be linked together. In
4617 * GLSL ES, all shader versions must be the same.
4619 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4620 min_version
!= max_version
) {
4621 linker_error(prog
, "all shaders must use same shading "
4622 "language version\n");
4626 prog
->data
->Version
= max_version
;
4627 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4629 /* Some shaders have to be linked with some other shaders present.
4631 if (!prog
->SeparateShader
) {
4632 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4633 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4634 linker_error(prog
, "Geometry shader must be linked with "
4638 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4639 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4640 linker_error(prog
, "Tessellation evaluation shader must be linked "
4641 "with vertex shader\n");
4644 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4645 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4646 linker_error(prog
, "Tessellation control shader must be linked with "
4651 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4653 * "Linking can fail for [...] any of the following reasons:
4655 * * program contains an object to form a tessellation control
4656 * shader [...] and [...] the program is not separable and
4657 * contains no object to form a tessellation evaluation shader"
4659 * The OpenGL spec is contradictory. It allows linking without a tess
4660 * eval shader, but that can only be used with transform feedback and
4661 * rasterization disabled. However, transform feedback isn't allowed
4662 * with GL_PATCHES, so it can't be used.
4664 * More investigation showed that the idea of transform feedback after
4665 * a tess control shader was dropped, because some hw vendors couldn't
4666 * support tessellation without a tess eval shader, but the linker
4667 * section wasn't updated to reflect that.
4669 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4672 * Do what's reasonable and always require a tess eval shader if a tess
4673 * control shader is present.
4675 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4676 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4677 linker_error(prog
, "Tessellation control shader must be linked with "
4678 "tessellation evaluation shader\n");
4683 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4684 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4685 linker_error(prog
, "GLSL ES requires non-separable programs "
4686 "containing a tessellation evaluation shader to also "
4687 "be linked with a tessellation control shader\n");
4693 /* Compute shaders have additional restrictions. */
4694 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4695 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4696 linker_error(prog
, "Compute shaders may not be linked with any other "
4697 "type of shader\n");
4700 /* Link all shaders for a particular stage and validate the result.
4702 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4703 if (num_shaders
[stage
] > 0) {
4704 gl_linked_shader
*const sh
=
4705 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4706 num_shaders
[stage
], false);
4708 if (!prog
->data
->LinkStatus
) {
4710 _mesa_delete_linked_shader(ctx
, sh
);
4715 case MESA_SHADER_VERTEX
:
4716 validate_vertex_shader_executable(prog
, sh
, ctx
);
4718 case MESA_SHADER_TESS_CTRL
:
4719 /* nothing to be done */
4721 case MESA_SHADER_TESS_EVAL
:
4722 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4724 case MESA_SHADER_GEOMETRY
:
4725 validate_geometry_shader_executable(prog
, sh
, ctx
);
4727 case MESA_SHADER_FRAGMENT
:
4728 validate_fragment_shader_executable(prog
, sh
);
4731 if (!prog
->data
->LinkStatus
) {
4733 _mesa_delete_linked_shader(ctx
, sh
);
4737 prog
->_LinkedShaders
[stage
] = sh
;
4738 prog
->data
->linked_stages
|= 1 << stage
;
4742 /* Here begins the inter-stage linking phase. Some initial validation is
4743 * performed, then locations are assigned for uniforms, attributes, and
4746 cross_validate_uniforms(ctx
, prog
);
4747 if (!prog
->data
->LinkStatus
)
4750 unsigned first
, last
, prev
;
4752 first
= MESA_SHADER_STAGES
;
4755 /* Determine first and last stage. */
4756 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4757 if (!prog
->_LinkedShaders
[i
])
4759 if (first
== MESA_SHADER_STAGES
)
4764 check_explicit_uniform_locations(ctx
, prog
);
4765 link_assign_subroutine_types(prog
);
4766 verify_subroutine_associated_funcs(prog
);
4768 if (!prog
->data
->LinkStatus
)
4771 resize_tes_inputs(ctx
, prog
);
4773 /* Validate the inputs of each stage with the output of the preceding
4777 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4778 if (prog
->_LinkedShaders
[i
] == NULL
)
4781 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4782 prog
->_LinkedShaders
[i
]);
4783 if (!prog
->data
->LinkStatus
)
4786 cross_validate_outputs_to_inputs(ctx
, prog
,
4787 prog
->_LinkedShaders
[prev
],
4788 prog
->_LinkedShaders
[i
]);
4789 if (!prog
->data
->LinkStatus
)
4795 /* The cross validation of outputs/inputs above validates interstage
4796 * explicit locations. We need to do this also for the inputs in the first
4797 * stage and outputs of the last stage included in the program, since there
4798 * is no cross validation for these.
4800 validate_first_and_last_interface_explicit_locations(ctx
, prog
,
4801 (gl_shader_stage
) first
,
4802 (gl_shader_stage
) last
);
4804 /* Cross-validate uniform blocks between shader stages */
4805 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4806 if (!prog
->data
->LinkStatus
)
4809 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4810 if (prog
->_LinkedShaders
[i
] != NULL
)
4811 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4814 if (prog
->IsES
&& prog
->data
->Version
== 100)
4815 if (!validate_invariant_builtins(prog
,
4816 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
4817 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]))
4820 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4821 * it before optimization because we want most of the checks to get
4822 * dropped thanks to constant propagation.
4824 * This rule also applies to GLSL ES 3.00.
4826 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4827 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4829 lower_discard_flow(sh
->ir
);
4833 if (prog
->SeparateShader
)
4834 disable_varying_optimizations_for_sso(prog
);
4837 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4841 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4844 /* Do common optimization before assigning storage for attributes,
4845 * uniforms, and varyings. Later optimization could possibly make
4846 * some of that unused.
4848 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4849 if (prog
->_LinkedShaders
[i
] == NULL
)
4852 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4853 if (!prog
->data
->LinkStatus
)
4856 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4857 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4860 if (ctx
->Const
.LowerTessLevel
) {
4861 lower_tess_level(prog
->_LinkedShaders
[i
]);
4864 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
4865 * specification says:
4867 * "In general, the behavior of GLSL ES should not depend on compiler
4868 * optimizations which might be implementation-dependent. Name matching
4869 * rules in most languages, including C++ from which GLSL ES is derived,
4870 * are based on declarations rather than use.
4872 * RESOLUTION: The existence of aliasing is determined by declarations
4873 * present after preprocessing."
4875 * Because of this rule, we do a 'dry-run' of attribute assignment for
4876 * vertex shader inputs here.
4878 if (prog
->IsES
&& i
== MESA_SHADER_VERTEX
) {
4879 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4880 MESA_SHADER_VERTEX
, false)) {
4885 /* Call opts before lowering const arrays to uniforms so we can const
4886 * propagate any elements accessed directly.
4888 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4890 /* Call opts after lowering const arrays to copy propagate things. */
4891 if (ctx
->Const
.GLSLLowerConstArrays
&&
4892 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
,
4893 ctx
->Const
.Program
[i
].MaxUniformComponents
))
4894 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4898 /* Validation for special cases where we allow sampler array indexing
4899 * with loop induction variable. This check emits a warning or error
4900 * depending if backend can handle dynamic indexing.
4902 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
4903 (prog
->IsES
&& prog
->data
->Version
< 300)) {
4904 if (!validate_sampler_array_indexing(ctx
, prog
))
4908 /* Check and validate stream emissions in geometry shaders */
4909 validate_geometry_shader_emissions(ctx
, prog
);
4911 store_fragdepth_layout(prog
);
4913 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
4916 /* Linking varyings can cause some extra, useless swizzles to be generated
4917 * due to packing and unpacking.
4919 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4920 if (prog
->_LinkedShaders
[i
] == NULL
)
4923 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
4926 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4927 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4928 * anything about shader linking when one of the shaders (vertex or
4929 * fragment shader) is absent. So, the extension shouldn't change the
4930 * behavior specified in GLSL specification.
4932 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4933 * "Linking can fail for a variety of reasons as specified in the
4934 * OpenGL ES Shading Language Specification, as well as any of the
4935 * following reasons:
4939 * * program contains objects to form either a vertex shader or
4940 * fragment shader, and program is not separable, and does not
4941 * contain objects to form both a vertex shader and fragment
4944 * However, the only scenario in 3.1+ where we don't require them both is
4945 * when we have a compute shader. For example:
4947 * - No shaders is a link error.
4948 * - Geom or Tess without a Vertex shader is a link error which means we
4949 * always require a Vertex shader and hence a Fragment shader.
4950 * - Finally a Compute shader linked with any other stage is a link error.
4952 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4953 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4954 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4955 linker_error(prog
, "program lacks a vertex shader\n");
4956 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4957 linker_error(prog
, "program lacks a fragment shader\n");
4962 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4963 free(shader_list
[i
]);
4964 if (prog
->_LinkedShaders
[i
] == NULL
)
4967 /* Do a final validation step to make sure that the IR wasn't
4968 * invalidated by any modifications performed after intrastage linking.
4970 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4972 /* Retain any live IR, but trash the rest. */
4973 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4975 /* The symbol table in the linked shaders may contain references to
4976 * variables that were removed (e.g., unused uniforms). Since it may
4977 * contain junk, there is no possible valid use. Delete it and set the
4980 delete prog
->_LinkedShaders
[i
]->symbols
;
4981 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4984 ralloc_free(mem_ctx
);