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>
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
71 #include "program/hash_table.h"
73 #include "ir_optimization.h"
76 #include "main/shaderobj.h"
80 * Visitor that determines whether or not a variable is ever written.
82 class find_assignment_visitor
: public ir_hierarchical_visitor
{
84 find_assignment_visitor(const char *name
)
85 : name(name
), found(false)
90 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
92 ir_variable
*const var
= ir
->lhs
->variable_referenced();
94 if (strcmp(name
, var
->name
) == 0) {
99 return visit_continue_with_parent
;
102 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
104 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
105 foreach_iter(exec_list_iterator
, iter
, *ir
) {
106 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
107 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
109 if (sig_param
->mode
== ir_var_out
||
110 sig_param
->mode
== ir_var_inout
) {
111 ir_variable
*var
= param_rval
->variable_referenced();
112 if (var
&& strcmp(name
, var
->name
) == 0) {
120 if (ir
->return_deref
!= NULL
) {
121 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
123 if (strcmp(name
, var
->name
) == 0) {
129 return visit_continue_with_parent
;
132 bool variable_found()
138 const char *name
; /**< Find writes to a variable with this name. */
139 bool found
; /**< Was a write to the variable found? */
144 * Visitor that determines whether or not a variable is ever read.
146 class find_deref_visitor
: public ir_hierarchical_visitor
{
148 find_deref_visitor(const char *name
)
149 : name(name
), found(false)
154 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
156 if (strcmp(this->name
, ir
->var
->name
) == 0) {
161 return visit_continue
;
164 bool variable_found() const
170 const char *name
; /**< Find writes to a variable with this name. */
171 bool found
; /**< Was a write to the variable found? */
176 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
180 ralloc_strcat(&prog
->InfoLog
, "error: ");
182 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
185 prog
->LinkStatus
= false;
190 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
194 ralloc_strcat(&prog
->InfoLog
, "error: ");
196 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
203 link_invalidate_variable_locations(gl_shader
*sh
, int input_base
,
206 foreach_list(node
, sh
->ir
) {
207 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
224 /* Only assign locations for generic attributes / varyings / etc.
226 if ((var
->location
>= base
) && !var
->explicit_location
)
229 if ((var
->location
== -1) && !var
->explicit_location
)
230 var
->is_unmatched_generic_inout
= 1;
232 var
->is_unmatched_generic_inout
= 0;
238 * Determine the number of attribute slots required for a particular type
240 * This code is here because it implements the language rules of a specific
241 * GLSL version. Since it's a property of the language and not a property of
242 * types in general, it doesn't really belong in glsl_type.
245 count_attribute_slots(const glsl_type
*t
)
247 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
249 * "A scalar input counts the same amount against this limit as a vec4,
250 * so applications may want to consider packing groups of four
251 * unrelated float inputs together into a vector to better utilize the
252 * capabilities of the underlying hardware. A matrix input will use up
253 * multiple locations. The number of locations used will equal the
254 * number of columns in the matrix."
256 * The spec does not explicitly say how arrays are counted. However, it
257 * should be safe to assume the total number of slots consumed by an array
258 * is the number of entries in the array multiplied by the number of slots
259 * consumed by a single element of the array.
263 return t
->array_size() * count_attribute_slots(t
->element_type());
266 return t
->matrix_columns
;
273 * Verify that a vertex shader executable meets all semantic requirements.
275 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
278 * \param shader Vertex shader executable to be verified
281 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
282 struct gl_shader
*shader
)
287 /* From the GLSL 1.10 spec, page 48:
289 * "The variable gl_Position is available only in the vertex
290 * language and is intended for writing the homogeneous vertex
291 * position. All executions of a well-formed vertex shader
292 * executable must write a value into this variable. [...] The
293 * variable gl_Position is available only in the vertex
294 * language and is intended for writing the homogeneous vertex
295 * position. All executions of a well-formed vertex shader
296 * executable must write a value into this variable."
298 * while in GLSL 1.40 this text is changed to:
300 * "The variable gl_Position is available only in the vertex
301 * language and is intended for writing the homogeneous vertex
302 * position. It can be written at any time during shader
303 * execution. It may also be read back by a vertex shader
304 * after being written. This value will be used by primitive
305 * assembly, clipping, culling, and other fixed functionality
306 * operations, if present, that operate on primitives after
307 * vertex processing has occurred. Its value is undefined if
308 * the vertex shader executable does not write gl_Position."
310 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
313 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
314 find_assignment_visitor
find("gl_Position");
315 find
.run(shader
->ir
);
316 if (!find
.variable_found()) {
317 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
322 prog
->Vert
.ClipDistanceArraySize
= 0;
324 if (!prog
->IsES
&& prog
->Version
>= 130) {
325 /* From section 7.1 (Vertex Shader Special Variables) of the
328 * "It is an error for a shader to statically write both
329 * gl_ClipVertex and gl_ClipDistance."
331 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
332 * gl_ClipVertex nor gl_ClipDistance.
334 find_assignment_visitor
clip_vertex("gl_ClipVertex");
335 find_assignment_visitor
clip_distance("gl_ClipDistance");
337 clip_vertex
.run(shader
->ir
);
338 clip_distance
.run(shader
->ir
);
339 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
340 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
341 "and `gl_ClipDistance'\n");
344 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
345 ir_variable
*clip_distance_var
=
346 shader
->symbols
->get_variable("gl_ClipDistance");
347 if (clip_distance_var
)
348 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
356 * Verify that a fragment shader executable meets all semantic requirements
358 * \param shader Fragment shader executable to be verified
361 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
362 struct gl_shader
*shader
)
367 find_assignment_visitor
frag_color("gl_FragColor");
368 find_assignment_visitor
frag_data("gl_FragData");
370 frag_color
.run(shader
->ir
);
371 frag_data
.run(shader
->ir
);
373 if (frag_color
.variable_found() && frag_data
.variable_found()) {
374 linker_error(prog
, "fragment shader writes to both "
375 "`gl_FragColor' and `gl_FragData'\n");
384 * Generate a string describing the mode of a variable
387 mode_string(const ir_variable
*var
)
391 return (var
->read_only
) ? "global constant" : "global variable";
393 case ir_var_uniform
: return "uniform";
394 case ir_var_in
: return "shader input";
395 case ir_var_out
: return "shader output";
396 case ir_var_inout
: return "shader inout";
398 case ir_var_const_in
:
399 case ir_var_temporary
:
401 assert(!"Should not get here.");
402 return "invalid variable";
408 * Perform validation of global variables used across multiple shaders
411 cross_validate_globals(struct gl_shader_program
*prog
,
412 struct gl_shader
**shader_list
,
413 unsigned num_shaders
,
416 /* Examine all of the uniforms in all of the shaders and cross validate
419 glsl_symbol_table variables
;
420 for (unsigned i
= 0; i
< num_shaders
; i
++) {
421 if (shader_list
[i
] == NULL
)
424 foreach_list(node
, shader_list
[i
]->ir
) {
425 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
430 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
433 /* Don't cross validate temporaries that are at global scope. These
434 * will eventually get pulled into the shaders 'main'.
436 if (var
->mode
== ir_var_temporary
)
439 /* If a global with this name has already been seen, verify that the
440 * new instance has the same type. In addition, if the globals have
441 * initializers, the values of the initializers must be the same.
443 ir_variable
*const existing
= variables
.get_variable(var
->name
);
444 if (existing
!= NULL
) {
445 if (var
->type
!= existing
->type
) {
446 /* Consider the types to be "the same" if both types are arrays
447 * of the same type and one of the arrays is implicitly sized.
448 * In addition, set the type of the linked variable to the
449 * explicitly sized array.
451 if (var
->type
->is_array()
452 && existing
->type
->is_array()
453 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
454 && ((var
->type
->length
== 0)
455 || (existing
->type
->length
== 0))) {
456 if (var
->type
->length
!= 0) {
457 existing
->type
= var
->type
;
460 linker_error(prog
, "%s `%s' declared as type "
461 "`%s' and type `%s'\n",
463 var
->name
, var
->type
->name
,
464 existing
->type
->name
);
469 if (var
->explicit_location
) {
470 if (existing
->explicit_location
471 && (var
->location
!= existing
->location
)) {
472 linker_error(prog
, "explicit locations for %s "
473 "`%s' have differing values\n",
474 mode_string(var
), var
->name
);
478 existing
->location
= var
->location
;
479 existing
->explicit_location
= true;
482 /* Validate layout qualifiers for gl_FragDepth.
484 * From the AMD/ARB_conservative_depth specs:
486 * "If gl_FragDepth is redeclared in any fragment shader in a
487 * program, it must be redeclared in all fragment shaders in
488 * that program that have static assignments to
489 * gl_FragDepth. All redeclarations of gl_FragDepth in all
490 * fragment shaders in a single program must have the same set
493 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
494 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
495 bool layout_differs
=
496 var
->depth_layout
!= existing
->depth_layout
;
498 if (layout_declared
&& layout_differs
) {
500 "All redeclarations of gl_FragDepth in all "
501 "fragment shaders in a single program must have "
502 "the same set of qualifiers.");
505 if (var
->used
&& layout_differs
) {
507 "If gl_FragDepth is redeclared with a layout "
508 "qualifier in any fragment shader, it must be "
509 "redeclared with the same layout qualifier in "
510 "all fragment shaders that have assignments to "
515 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
517 * "If a shared global has multiple initializers, the
518 * initializers must all be constant expressions, and they
519 * must all have the same value. Otherwise, a link error will
520 * result. (A shared global having only one initializer does
521 * not require that initializer to be a constant expression.)"
523 * Previous to 4.20 the GLSL spec simply said that initializers
524 * must have the same value. In this case of non-constant
525 * initializers, this was impossible to determine. As a result,
526 * no vendor actually implemented that behavior. The 4.20
527 * behavior matches the implemented behavior of at least one other
528 * vendor, so we'll implement that for all GLSL versions.
530 if (var
->constant_initializer
!= NULL
) {
531 if (existing
->constant_initializer
!= NULL
) {
532 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
533 linker_error(prog
, "initializers for %s "
534 "`%s' have differing values\n",
535 mode_string(var
), var
->name
);
539 /* If the first-seen instance of a particular uniform did not
540 * have an initializer but a later instance does, copy the
541 * initializer to the version stored in the symbol table.
543 /* FINISHME: This is wrong. The constant_value field should
544 * FINISHME: not be modified! Imagine a case where a shader
545 * FINISHME: without an initializer is linked in two different
546 * FINISHME: programs with shaders that have differing
547 * FINISHME: initializers. Linking with the first will
548 * FINISHME: modify the shader, and linking with the second
549 * FINISHME: will fail.
551 existing
->constant_initializer
=
552 var
->constant_initializer
->clone(ralloc_parent(existing
),
557 if (var
->has_initializer
) {
558 if (existing
->has_initializer
559 && (var
->constant_initializer
== NULL
560 || existing
->constant_initializer
== NULL
)) {
562 "shared global variable `%s' has multiple "
563 "non-constant initializers.\n",
568 /* Some instance had an initializer, so keep track of that. In
569 * this location, all sorts of initializers (constant or
570 * otherwise) will propagate the existence to the variable
571 * stored in the symbol table.
573 existing
->has_initializer
= true;
576 if (existing
->invariant
!= var
->invariant
) {
577 linker_error(prog
, "declarations for %s `%s' have "
578 "mismatching invariant qualifiers\n",
579 mode_string(var
), var
->name
);
582 if (existing
->centroid
!= var
->centroid
) {
583 linker_error(prog
, "declarations for %s `%s' have "
584 "mismatching centroid qualifiers\n",
585 mode_string(var
), var
->name
);
589 variables
.add_variable(var
);
598 * Perform validation of uniforms used across multiple shader stages
601 cross_validate_uniforms(struct gl_shader_program
*prog
)
603 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
604 MESA_SHADER_TYPES
, true);
608 * Accumulates the array of prog->UniformBlocks and checks that all
609 * definitons of blocks agree on their contents.
612 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
614 unsigned max_num_uniform_blocks
= 0;
615 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
616 if (prog
->_LinkedShaders
[i
])
617 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
620 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
621 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
623 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
624 max_num_uniform_blocks
);
625 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
626 prog
->UniformBlockStageIndex
[i
][j
] = -1;
631 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
632 int index
= link_cross_validate_uniform_block(prog
,
633 &prog
->UniformBlocks
,
634 &prog
->NumUniformBlocks
,
635 &sh
->UniformBlocks
[j
]);
638 linker_error(prog
, "uniform block `%s' has mismatching definitions",
639 sh
->UniformBlocks
[j
].Name
);
643 prog
->UniformBlockStageIndex
[i
][index
] = j
;
651 * Validate that outputs from one stage match inputs of another
654 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
655 gl_shader
*producer
, gl_shader
*consumer
)
657 glsl_symbol_table parameters
;
658 /* FINISHME: Figure these out dynamically. */
659 const char *const producer_stage
= "vertex";
660 const char *const consumer_stage
= "fragment";
662 /* Find all shader outputs in the "producer" stage.
664 foreach_list(node
, producer
->ir
) {
665 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
667 /* FINISHME: For geometry shaders, this should also look for inout
668 * FINISHME: variables.
670 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
673 parameters
.add_variable(var
);
677 /* Find all shader inputs in the "consumer" stage. Any variables that have
678 * matching outputs already in the symbol table must have the same type and
681 foreach_list(node
, consumer
->ir
) {
682 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
684 /* FINISHME: For geometry shaders, this should also look for inout
685 * FINISHME: variables.
687 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
690 ir_variable
*const output
= parameters
.get_variable(input
->name
);
691 if (output
!= NULL
) {
692 /* Check that the types match between stages.
694 if (input
->type
!= output
->type
) {
695 /* There is a bit of a special case for gl_TexCoord. This
696 * built-in is unsized by default. Applications that variable
697 * access it must redeclare it with a size. There is some
698 * language in the GLSL spec that implies the fragment shader
699 * and vertex shader do not have to agree on this size. Other
700 * driver behave this way, and one or two applications seem to
703 * Neither declaration needs to be modified here because the array
704 * sizes are fixed later when update_array_sizes is called.
706 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
708 * "Unlike user-defined varying variables, the built-in
709 * varying variables don't have a strict one-to-one
710 * correspondence between the vertex language and the
711 * fragment language."
713 if (!output
->type
->is_array()
714 || (strncmp("gl_", output
->name
, 3) != 0)) {
716 "%s shader output `%s' declared as type `%s', "
717 "but %s shader input declared as type `%s'\n",
718 producer_stage
, output
->name
,
720 consumer_stage
, input
->type
->name
);
725 /* Check that all of the qualifiers match between stages.
727 if (input
->centroid
!= output
->centroid
) {
729 "%s shader output `%s' %s centroid qualifier, "
730 "but %s shader input %s centroid qualifier\n",
733 (output
->centroid
) ? "has" : "lacks",
735 (input
->centroid
) ? "has" : "lacks");
739 if (input
->invariant
!= output
->invariant
) {
741 "%s shader output `%s' %s invariant qualifier, "
742 "but %s shader input %s invariant qualifier\n",
745 (output
->invariant
) ? "has" : "lacks",
747 (input
->invariant
) ? "has" : "lacks");
751 if (input
->interpolation
!= output
->interpolation
) {
753 "%s shader output `%s' specifies %s "
754 "interpolation qualifier, "
755 "but %s shader input specifies %s "
756 "interpolation qualifier\n",
759 output
->interpolation_string(),
761 input
->interpolation_string());
772 * Populates a shaders symbol table with all global declarations
775 populate_symbol_table(gl_shader
*sh
)
777 sh
->symbols
= new(sh
) glsl_symbol_table
;
779 foreach_list(node
, sh
->ir
) {
780 ir_instruction
*const inst
= (ir_instruction
*) node
;
784 if ((func
= inst
->as_function()) != NULL
) {
785 sh
->symbols
->add_function(func
);
786 } else if ((var
= inst
->as_variable()) != NULL
) {
787 sh
->symbols
->add_variable(var
);
794 * Remap variables referenced in an instruction tree
796 * This is used when instruction trees are cloned from one shader and placed in
797 * another. These trees will contain references to \c ir_variable nodes that
798 * do not exist in the target shader. This function finds these \c ir_variable
799 * references and replaces the references with matching variables in the target
802 * If there is no matching variable in the target shader, a clone of the
803 * \c ir_variable is made and added to the target shader. The new variable is
804 * added to \b both the instruction stream and the symbol table.
806 * \param inst IR tree that is to be processed.
807 * \param symbols Symbol table containing global scope symbols in the
809 * \param instructions Instruction stream where new variable declarations
813 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
816 class remap_visitor
: public ir_hierarchical_visitor
{
818 remap_visitor(struct gl_shader
*target
,
821 this->target
= target
;
822 this->symbols
= target
->symbols
;
823 this->instructions
= target
->ir
;
827 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
829 if (ir
->var
->mode
== ir_var_temporary
) {
830 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
834 return visit_continue
;
837 ir_variable
*const existing
=
838 this->symbols
->get_variable(ir
->var
->name
);
839 if (existing
!= NULL
)
842 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
844 this->symbols
->add_variable(copy
);
845 this->instructions
->push_head(copy
);
849 return visit_continue
;
853 struct gl_shader
*target
;
854 glsl_symbol_table
*symbols
;
855 exec_list
*instructions
;
859 remap_visitor
v(target
, temps
);
866 * Move non-declarations from one instruction stream to another
868 * The intended usage pattern of this function is to pass the pointer to the
869 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
870 * pointer) for \c last and \c false for \c make_copies on the first
871 * call. Successive calls pass the return value of the previous call for
872 * \c last and \c true for \c make_copies.
874 * \param instructions Source instruction stream
875 * \param last Instruction after which new instructions should be
876 * inserted in the target instruction stream
877 * \param make_copies Flag selecting whether instructions in \c instructions
878 * should be copied (via \c ir_instruction::clone) into the
879 * target list or moved.
882 * The new "last" instruction in the target instruction stream. This pointer
883 * is suitable for use as the \c last parameter of a later call to this
887 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
888 bool make_copies
, gl_shader
*target
)
890 hash_table
*temps
= NULL
;
893 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
894 hash_table_pointer_compare
);
896 foreach_list_safe(node
, instructions
) {
897 ir_instruction
*inst
= (ir_instruction
*) node
;
899 if (inst
->as_function())
902 ir_variable
*var
= inst
->as_variable();
903 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
906 assert(inst
->as_assignment()
908 || inst
->as_if() /* for initializers with the ?: operator */
909 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
912 inst
= inst
->clone(target
, NULL
);
915 hash_table_insert(temps
, inst
, var
);
917 remap_variables(inst
, target
, temps
);
922 last
->insert_after(inst
);
927 hash_table_dtor(temps
);
933 * Get the function signature for main from a shader
935 static ir_function_signature
*
936 get_main_function_signature(gl_shader
*sh
)
938 ir_function
*const f
= sh
->symbols
->get_function("main");
940 exec_list void_parameters
;
942 /* Look for the 'void main()' signature and ensure that it's defined.
943 * This keeps the linker from accidentally pick a shader that just
944 * contains a prototype for main.
946 * We don't have to check for multiple definitions of main (in multiple
947 * shaders) because that would have already been caught above.
949 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
950 if ((sig
!= NULL
) && sig
->is_defined
) {
960 * This class is only used in link_intrastage_shaders() below but declaring
961 * it inside that function leads to compiler warnings with some versions of
964 class array_sizing_visitor
: public ir_hierarchical_visitor
{
966 virtual ir_visitor_status
visit(ir_variable
*var
)
968 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
969 const glsl_type
*type
=
970 glsl_type::get_array_instance(var
->type
->fields
.array
,
971 var
->max_array_access
+ 1);
972 assert(type
!= NULL
);
975 return visit_continue
;
980 * Combine a group of shaders for a single stage to generate a linked shader
983 * If this function is supplied a single shader, it is cloned, and the new
984 * shader is returned.
986 static struct gl_shader
*
987 link_intrastage_shaders(void *mem_ctx
,
988 struct gl_context
*ctx
,
989 struct gl_shader_program
*prog
,
990 struct gl_shader
**shader_list
,
991 unsigned num_shaders
)
993 struct gl_uniform_block
*uniform_blocks
= NULL
;
994 unsigned num_uniform_blocks
= 0;
996 /* Check that global variables defined in multiple shaders are consistent.
998 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
1001 /* Check that uniform blocks between shaders for a stage agree. */
1002 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1003 struct gl_shader
*sh
= shader_list
[i
];
1005 for (unsigned j
= 0; j
< shader_list
[i
]->NumUniformBlocks
; j
++) {
1006 link_assign_uniform_block_offsets(shader_list
[i
]);
1008 int index
= link_cross_validate_uniform_block(mem_ctx
,
1010 &num_uniform_blocks
,
1011 &sh
->UniformBlocks
[j
]);
1013 linker_error(prog
, "uniform block `%s' has mismatching definitions",
1014 sh
->UniformBlocks
[j
].Name
);
1020 /* Check that there is only a single definition of each function signature
1021 * across all shaders.
1023 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1024 foreach_list(node
, shader_list
[i
]->ir
) {
1025 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
1030 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
1031 ir_function
*const other
=
1032 shader_list
[j
]->symbols
->get_function(f
->name
);
1034 /* If the other shader has no function (and therefore no function
1035 * signatures) with the same name, skip to the next shader.
1040 foreach_iter (exec_list_iterator
, iter
, *f
) {
1041 ir_function_signature
*sig
=
1042 (ir_function_signature
*) iter
.get();
1044 if (!sig
->is_defined
|| sig
->is_builtin
)
1047 ir_function_signature
*other_sig
=
1048 other
->exact_matching_signature(& sig
->parameters
);
1050 if ((other_sig
!= NULL
) && other_sig
->is_defined
1051 && !other_sig
->is_builtin
) {
1052 linker_error(prog
, "function `%s' is multiply defined",
1061 /* Find the shader that defines main, and make a clone of it.
1063 * Starting with the clone, search for undefined references. If one is
1064 * found, find the shader that defines it. Clone the reference and add
1065 * it to the shader. Repeat until there are no undefined references or
1066 * until a reference cannot be resolved.
1068 gl_shader
*main
= NULL
;
1069 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1070 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1071 main
= shader_list
[i
];
1077 linker_error(prog
, "%s shader lacks `main'\n",
1078 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
1079 ? "vertex" : "fragment");
1083 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1084 linked
->ir
= new(linked
) exec_list
;
1085 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1087 linked
->UniformBlocks
= uniform_blocks
;
1088 linked
->NumUniformBlocks
= num_uniform_blocks
;
1089 ralloc_steal(linked
, linked
->UniformBlocks
);
1091 populate_symbol_table(linked
);
1093 /* The a pointer to the main function in the final linked shader (i.e., the
1094 * copy of the original shader that contained the main function).
1096 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1098 /* Move any instructions other than variable declarations or function
1099 * declarations into main.
1101 exec_node
*insertion_point
=
1102 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1105 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1106 if (shader_list
[i
] == main
)
1109 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1110 insertion_point
, true, linked
);
1113 /* Resolve initializers for global variables in the linked shader.
1115 unsigned num_linking_shaders
= num_shaders
;
1116 for (unsigned i
= 0; i
< num_shaders
; i
++)
1117 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1119 gl_shader
**linking_shaders
=
1120 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1122 memcpy(linking_shaders
, shader_list
,
1123 sizeof(linking_shaders
[0]) * num_shaders
);
1125 unsigned idx
= num_shaders
;
1126 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1127 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1128 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1129 idx
+= shader_list
[i
]->num_builtins_to_link
;
1132 assert(idx
== num_linking_shaders
);
1134 if (!link_function_calls(prog
, linked
, linking_shaders
,
1135 num_linking_shaders
)) {
1136 ctx
->Driver
.DeleteShader(ctx
, linked
);
1140 free(linking_shaders
);
1143 /* At this point linked should contain all of the linked IR, so
1144 * validate it to make sure nothing went wrong.
1147 validate_ir_tree(linked
->ir
);
1150 /* Make a pass over all variable declarations to ensure that arrays with
1151 * unspecified sizes have a size specified. The size is inferred from the
1152 * max_array_access field.
1154 if (linked
!= NULL
) {
1155 array_sizing_visitor v
;
1164 * Update the sizes of linked shader uniform arrays to the maximum
1167 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1169 * If one or more elements of an array are active,
1170 * GetActiveUniform will return the name of the array in name,
1171 * subject to the restrictions listed above. The type of the array
1172 * is returned in type. The size parameter contains the highest
1173 * array element index used, plus one. The compiler or linker
1174 * determines the highest index used. There will be only one
1175 * active uniform reported by the GL per uniform array.
1179 update_array_sizes(struct gl_shader_program
*prog
)
1181 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1182 if (prog
->_LinkedShaders
[i
] == NULL
)
1185 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1186 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1188 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
1189 var
->mode
!= ir_var_in
&&
1190 var
->mode
!= ir_var_out
) ||
1191 !var
->type
->is_array())
1194 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1195 * will not be eliminated. Since we always do std140, just
1196 * don't resize arrays in UBOs.
1198 if (var
->uniform_block
!= -1)
1201 unsigned int size
= var
->max_array_access
;
1202 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1203 if (prog
->_LinkedShaders
[j
] == NULL
)
1206 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1207 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1211 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1212 other_var
->max_array_access
> size
) {
1213 size
= other_var
->max_array_access
;
1218 if (size
+ 1 != var
->type
->fields
.array
->length
) {
1219 /* If this is a built-in uniform (i.e., it's backed by some
1220 * fixed-function state), adjust the number of state slots to
1221 * match the new array size. The number of slots per array entry
1222 * is not known. It seems safe to assume that the total number of
1223 * slots is an integer multiple of the number of array elements.
1224 * Determine the number of slots per array element by dividing by
1225 * the old (total) size.
1227 if (var
->num_state_slots
> 0) {
1228 var
->num_state_slots
= (size
+ 1)
1229 * (var
->num_state_slots
/ var
->type
->length
);
1232 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1234 /* FINISHME: We should update the types of array
1235 * dereferences of this variable now.
1243 * Find a contiguous set of available bits in a bitmask.
1245 * \param used_mask Bits representing used (1) and unused (0) locations
1246 * \param needed_count Number of contiguous bits needed.
1249 * Base location of the available bits on success or -1 on failure.
1252 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1254 unsigned needed_mask
= (1 << needed_count
) - 1;
1255 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1257 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1258 * cannot optimize possibly infinite loops" for the loop below.
1260 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1263 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1264 if ((needed_mask
& ~used_mask
) == needed_mask
)
1275 * Assign locations for either VS inputs for FS outputs
1277 * \param prog Shader program whose variables need locations assigned
1278 * \param target_index Selector for the program target to receive location
1279 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1280 * \c MESA_SHADER_FRAGMENT.
1281 * \param max_index Maximum number of generic locations. This corresponds
1282 * to either the maximum number of draw buffers or the
1283 * maximum number of generic attributes.
1286 * If locations are successfully assigned, true is returned. Otherwise an
1287 * error is emitted to the shader link log and false is returned.
1290 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1291 unsigned target_index
,
1294 /* Mark invalid locations as being used.
1296 unsigned used_locations
= (max_index
>= 32)
1297 ? ~0 : ~((1 << max_index
) - 1);
1299 assert((target_index
== MESA_SHADER_VERTEX
)
1300 || (target_index
== MESA_SHADER_FRAGMENT
));
1302 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1306 /* Operate in a total of four passes.
1308 * 1. Invalidate the location assignments for all vertex shader inputs.
1310 * 2. Assign locations for inputs that have user-defined (via
1311 * glBindVertexAttribLocation) locations and outputs that have
1312 * user-defined locations (via glBindFragDataLocation).
1314 * 3. Sort the attributes without assigned locations by number of slots
1315 * required in decreasing order. Fragmentation caused by attribute
1316 * locations assigned by the application may prevent large attributes
1317 * from having enough contiguous space.
1319 * 4. Assign locations to any inputs without assigned locations.
1322 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1323 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1325 const enum ir_variable_mode direction
=
1326 (target_index
== MESA_SHADER_VERTEX
) ? ir_var_in
: ir_var_out
;
1329 /* Temporary storage for the set of attributes that need locations assigned.
1335 /* Used below in the call to qsort. */
1336 static int compare(const void *a
, const void *b
)
1338 const temp_attr
*const l
= (const temp_attr
*) a
;
1339 const temp_attr
*const r
= (const temp_attr
*) b
;
1341 /* Reversed because we want a descending order sort below. */
1342 return r
->slots
- l
->slots
;
1346 unsigned num_attr
= 0;
1348 foreach_list(node
, sh
->ir
) {
1349 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1351 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1354 if (var
->explicit_location
) {
1355 if ((var
->location
>= (int)(max_index
+ generic_base
))
1356 || (var
->location
< 0)) {
1358 "invalid explicit location %d specified for `%s'\n",
1360 ? var
->location
: var
->location
- generic_base
,
1364 } else if (target_index
== MESA_SHADER_VERTEX
) {
1367 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1368 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1369 var
->location
= binding
;
1370 var
->is_unmatched_generic_inout
= 0;
1372 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1376 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1377 assert(binding
>= FRAG_RESULT_DATA0
);
1378 var
->location
= binding
;
1379 var
->is_unmatched_generic_inout
= 0;
1381 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1387 /* If the variable is not a built-in and has a location statically
1388 * assigned in the shader (presumably via a layout qualifier), make sure
1389 * that it doesn't collide with other assigned locations. Otherwise,
1390 * add it to the list of variables that need linker-assigned locations.
1392 const unsigned slots
= count_attribute_slots(var
->type
);
1393 if (var
->location
!= -1) {
1394 if (var
->location
>= generic_base
&& var
->index
< 1) {
1395 /* From page 61 of the OpenGL 4.0 spec:
1397 * "LinkProgram will fail if the attribute bindings assigned
1398 * by BindAttribLocation do not leave not enough space to
1399 * assign a location for an active matrix attribute or an
1400 * active attribute array, both of which require multiple
1401 * contiguous generic attributes."
1403 * Previous versions of the spec contain similar language but omit
1404 * the bit about attribute arrays.
1406 * Page 61 of the OpenGL 4.0 spec also says:
1408 * "It is possible for an application to bind more than one
1409 * attribute name to the same location. This is referred to as
1410 * aliasing. This will only work if only one of the aliased
1411 * attributes is active in the executable program, or if no
1412 * path through the shader consumes more than one attribute of
1413 * a set of attributes aliased to the same location. A link
1414 * error can occur if the linker determines that every path
1415 * through the shader consumes multiple aliased attributes,
1416 * but implementations are not required to generate an error
1419 * These two paragraphs are either somewhat contradictory, or I
1420 * don't fully understand one or both of them.
1422 /* FINISHME: The code as currently written does not support
1423 * FINISHME: attribute location aliasing (see comment above).
1425 /* Mask representing the contiguous slots that will be used by
1428 const unsigned attr
= var
->location
- generic_base
;
1429 const unsigned use_mask
= (1 << slots
) - 1;
1431 /* Generate a link error if the set of bits requested for this
1432 * attribute overlaps any previously allocated bits.
1434 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1435 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1436 ? "vertex shader input" : "fragment shader output";
1438 "insufficient contiguous locations "
1439 "available for %s `%s' %d %d %d", string
,
1440 var
->name
, used_locations
, use_mask
, attr
);
1444 used_locations
|= (use_mask
<< attr
);
1450 to_assign
[num_attr
].slots
= slots
;
1451 to_assign
[num_attr
].var
= var
;
1455 /* If all of the attributes were assigned locations by the application (or
1456 * are built-in attributes with fixed locations), return early. This should
1457 * be the common case.
1462 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1464 if (target_index
== MESA_SHADER_VERTEX
) {
1465 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1466 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1467 * reserved to prevent it from being automatically allocated below.
1469 find_deref_visitor
find("gl_Vertex");
1471 if (find
.variable_found())
1472 used_locations
|= (1 << 0);
1475 for (unsigned i
= 0; i
< num_attr
; i
++) {
1476 /* Mask representing the contiguous slots that will be used by this
1479 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1481 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1484 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1485 ? "vertex shader input" : "fragment shader output";
1488 "insufficient contiguous locations "
1489 "available for %s `%s'",
1490 string
, to_assign
[i
].var
->name
);
1494 to_assign
[i
].var
->location
= generic_base
+ location
;
1495 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1496 used_locations
|= (use_mask
<< location
);
1504 * Demote shader inputs and outputs that are not used in other stages
1507 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1509 foreach_list(node
, sh
->ir
) {
1510 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1512 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1515 /* A shader 'in' or 'out' variable is only really an input or output if
1516 * its value is used by other shader stages. This will cause the variable
1517 * to have a location assigned.
1519 if (var
->is_unmatched_generic_inout
) {
1520 var
->mode
= ir_var_auto
;
1527 * Data structure tracking information about a transform feedback declaration
1530 class tfeedback_decl
1533 bool init(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1534 const void *mem_ctx
, const char *input
);
1535 static bool is_same(const tfeedback_decl
&x
, const tfeedback_decl
&y
);
1536 bool assign_location(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1537 ir_variable
*output_var
);
1538 bool accumulate_num_outputs(struct gl_shader_program
*prog
, unsigned *count
);
1539 bool store(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1540 struct gl_transform_feedback_info
*info
, unsigned buffer
,
1541 const unsigned max_outputs
) const;
1544 * True if assign_location() has been called for this object.
1546 bool is_assigned() const
1548 return this->location
!= -1;
1551 bool is_next_buffer_separator() const
1553 return this->next_buffer_separator
;
1556 bool is_varying() const
1558 return !this->next_buffer_separator
&& !this->skip_components
;
1562 * Determine whether this object refers to the variable var.
1564 bool matches_var(ir_variable
*var
) const
1566 if (this->is_clip_distance_mesa
)
1567 return strcmp(var
->name
, "gl_ClipDistanceMESA") == 0;
1569 return strcmp(var
->name
, this->var_name
) == 0;
1573 * The total number of varying components taken up by this variable. Only
1574 * valid if is_assigned() is true.
1576 unsigned num_components() const
1578 if (this->is_clip_distance_mesa
)
1581 return this->vector_elements
* this->matrix_columns
* this->size
;
1586 * The name that was supplied to glTransformFeedbackVaryings. Used for
1587 * error reporting and glGetTransformFeedbackVarying().
1589 const char *orig_name
;
1592 * The name of the variable, parsed from orig_name.
1594 const char *var_name
;
1597 * True if the declaration in orig_name represents an array.
1599 bool is_subscripted
;
1602 * If is_subscripted is true, the subscript that was specified in orig_name.
1604 unsigned array_subscript
;
1607 * True if the variable is gl_ClipDistance and the driver lowers
1608 * gl_ClipDistance to gl_ClipDistanceMESA.
1610 bool is_clip_distance_mesa
;
1613 * The vertex shader output location that the linker assigned for this
1614 * variable. -1 if a location hasn't been assigned yet.
1619 * If location != -1, the number of vector elements in this variable, or 1
1620 * if this variable is a scalar.
1622 unsigned vector_elements
;
1625 * If location != -1, the number of matrix columns in this variable, or 1
1626 * if this variable is not a matrix.
1628 unsigned matrix_columns
;
1630 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1634 * If location != -1, the size that should be returned by
1635 * glGetTransformFeedbackVarying().
1640 * How many components to skip. If non-zero, this is
1641 * gl_SkipComponents{1,2,3,4} from ARB_transform_feedback3.
1643 unsigned skip_components
;
1646 * Whether this is gl_NextBuffer from ARB_transform_feedback3.
1648 bool next_buffer_separator
;
1653 * Initialize this object based on a string that was passed to
1654 * glTransformFeedbackVaryings. If there is a parse error, the error is
1655 * reported using linker_error(), and false is returned.
1658 tfeedback_decl::init(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1659 const void *mem_ctx
, const char *input
)
1661 /* We don't have to be pedantic about what is a valid GLSL variable name,
1662 * because any variable with an invalid name can't exist in the IR anyway.
1665 this->location
= -1;
1666 this->orig_name
= input
;
1667 this->is_clip_distance_mesa
= false;
1668 this->skip_components
= 0;
1669 this->next_buffer_separator
= false;
1671 if (ctx
->Extensions
.ARB_transform_feedback3
) {
1672 /* Parse gl_NextBuffer. */
1673 if (strcmp(input
, "gl_NextBuffer") == 0) {
1674 this->next_buffer_separator
= true;
1678 /* Parse gl_SkipComponents. */
1679 if (strcmp(input
, "gl_SkipComponents1") == 0)
1680 this->skip_components
= 1;
1681 else if (strcmp(input
, "gl_SkipComponents2") == 0)
1682 this->skip_components
= 2;
1683 else if (strcmp(input
, "gl_SkipComponents3") == 0)
1684 this->skip_components
= 3;
1685 else if (strcmp(input
, "gl_SkipComponents4") == 0)
1686 this->skip_components
= 4;
1688 if (this->skip_components
)
1692 /* Parse a declaration. */
1693 const char *bracket
= strrchr(input
, '[');
1696 this->var_name
= ralloc_strndup(mem_ctx
, input
, bracket
- input
);
1697 if (sscanf(bracket
, "[%u]", &this->array_subscript
) != 1) {
1698 linker_error(prog
, "Cannot parse transform feedback varying %s", input
);
1701 this->is_subscripted
= true;
1703 this->var_name
= ralloc_strdup(mem_ctx
, input
);
1704 this->is_subscripted
= false;
1707 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1708 * class must behave specially to account for the fact that gl_ClipDistance
1709 * is converted from a float[8] to a vec4[2].
1711 if (ctx
->ShaderCompilerOptions
[MESA_SHADER_VERTEX
].LowerClipDistance
&&
1712 strcmp(this->var_name
, "gl_ClipDistance") == 0) {
1713 this->is_clip_distance_mesa
= true;
1721 * Determine whether two tfeedback_decl objects refer to the same variable and
1722 * array index (if applicable).
1725 tfeedback_decl::is_same(const tfeedback_decl
&x
, const tfeedback_decl
&y
)
1727 assert(x
.is_varying() && y
.is_varying());
1729 if (strcmp(x
.var_name
, y
.var_name
) != 0)
1731 if (x
.is_subscripted
!= y
.is_subscripted
)
1733 if (x
.is_subscripted
&& x
.array_subscript
!= y
.array_subscript
)
1740 * Assign a location for this tfeedback_decl object based on the location
1741 * assignment in output_var.
1743 * If an error occurs, the error is reported through linker_error() and false
1747 tfeedback_decl::assign_location(struct gl_context
*ctx
,
1748 struct gl_shader_program
*prog
,
1749 ir_variable
*output_var
)
1751 assert(this->is_varying());
1753 if (output_var
->type
->is_array()) {
1754 /* Array variable */
1755 const unsigned matrix_cols
=
1756 output_var
->type
->fields
.array
->matrix_columns
;
1757 unsigned actual_array_size
= this->is_clip_distance_mesa
?
1758 prog
->Vert
.ClipDistanceArraySize
: output_var
->type
->array_size();
1760 if (this->is_subscripted
) {
1761 /* Check array bounds. */
1762 if (this->array_subscript
>= actual_array_size
) {
1763 linker_error(prog
, "Transform feedback varying %s has index "
1764 "%i, but the array size is %u.",
1765 this->orig_name
, this->array_subscript
,
1769 if (this->is_clip_distance_mesa
) {
1771 output_var
->location
+ this->array_subscript
/ 4;
1774 output_var
->location
+ this->array_subscript
* matrix_cols
;
1778 this->location
= output_var
->location
;
1779 this->size
= actual_array_size
;
1781 this->vector_elements
= output_var
->type
->fields
.array
->vector_elements
;
1782 this->matrix_columns
= matrix_cols
;
1783 if (this->is_clip_distance_mesa
)
1784 this->type
= GL_FLOAT
;
1786 this->type
= output_var
->type
->fields
.array
->gl_type
;
1788 /* Regular variable (scalar, vector, or matrix) */
1789 if (this->is_subscripted
) {
1790 linker_error(prog
, "Transform feedback varying %s requested, "
1791 "but %s is not an array.",
1792 this->orig_name
, this->var_name
);
1795 this->location
= output_var
->location
;
1797 this->vector_elements
= output_var
->type
->vector_elements
;
1798 this->matrix_columns
= output_var
->type
->matrix_columns
;
1799 this->type
= output_var
->type
->gl_type
;
1802 /* From GL_EXT_transform_feedback:
1803 * A program will fail to link if:
1805 * * the total number of components to capture in any varying
1806 * variable in <varyings> is greater than the constant
1807 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1808 * buffer mode is SEPARATE_ATTRIBS_EXT;
1810 if (prog
->TransformFeedback
.BufferMode
== GL_SEPARATE_ATTRIBS
&&
1811 this->num_components() >
1812 ctx
->Const
.MaxTransformFeedbackSeparateComponents
) {
1813 linker_error(prog
, "Transform feedback varying %s exceeds "
1814 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1824 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program
*prog
,
1827 if (!this->is_varying()) {
1831 if (!this->is_assigned()) {
1832 /* From GL_EXT_transform_feedback:
1833 * A program will fail to link if:
1835 * * any variable name specified in the <varyings> array is not
1836 * declared as an output in the geometry shader (if present) or
1837 * the vertex shader (if no geometry shader is present);
1839 linker_error(prog
, "Transform feedback varying %s undeclared.",
1844 unsigned translated_size
= this->size
;
1845 if (this->is_clip_distance_mesa
)
1846 translated_size
= (translated_size
+ 3) / 4;
1848 *count
+= translated_size
* this->matrix_columns
;
1855 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1857 * If an error occurs, the error is reported through linker_error() and false
1861 tfeedback_decl::store(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1862 struct gl_transform_feedback_info
*info
,
1863 unsigned buffer
, const unsigned max_outputs
) const
1865 assert(!this->next_buffer_separator
);
1867 /* Handle gl_SkipComponents. */
1868 if (this->skip_components
) {
1869 info
->BufferStride
[buffer
] += this->skip_components
;
1873 /* From GL_EXT_transform_feedback:
1874 * A program will fail to link if:
1876 * * the total number of components to capture is greater than
1877 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1878 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1880 if (prog
->TransformFeedback
.BufferMode
== GL_INTERLEAVED_ATTRIBS
&&
1881 info
->BufferStride
[buffer
] + this->num_components() >
1882 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1883 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1884 "limit has been exceeded.");
1888 unsigned translated_size
= this->size
;
1889 if (this->is_clip_distance_mesa
)
1890 translated_size
= (translated_size
+ 3) / 4;
1891 unsigned components_so_far
= 0;
1892 for (unsigned index
= 0; index
< translated_size
; ++index
) {
1893 for (unsigned v
= 0; v
< this->matrix_columns
; ++v
) {
1894 unsigned num_components
= this->vector_elements
;
1895 assert(info
->NumOutputs
< max_outputs
);
1896 info
->Outputs
[info
->NumOutputs
].ComponentOffset
= 0;
1897 if (this->is_clip_distance_mesa
) {
1898 if (this->is_subscripted
) {
1900 info
->Outputs
[info
->NumOutputs
].ComponentOffset
=
1901 this->array_subscript
% 4;
1903 num_components
= MIN2(4, this->size
- components_so_far
);
1906 info
->Outputs
[info
->NumOutputs
].OutputRegister
=
1907 this->location
+ v
+ index
* this->matrix_columns
;
1908 info
->Outputs
[info
->NumOutputs
].NumComponents
= num_components
;
1909 info
->Outputs
[info
->NumOutputs
].OutputBuffer
= buffer
;
1910 info
->Outputs
[info
->NumOutputs
].DstOffset
= info
->BufferStride
[buffer
];
1912 info
->BufferStride
[buffer
] += num_components
;
1913 components_so_far
+= num_components
;
1916 assert(components_so_far
== this->num_components());
1918 info
->Varyings
[info
->NumVarying
].Name
= ralloc_strdup(prog
, this->orig_name
);
1919 info
->Varyings
[info
->NumVarying
].Type
= this->type
;
1920 info
->Varyings
[info
->NumVarying
].Size
= this->size
;
1928 * Parse all the transform feedback declarations that were passed to
1929 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1931 * If an error occurs, the error is reported through linker_error() and false
1935 parse_tfeedback_decls(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1936 const void *mem_ctx
, unsigned num_names
,
1937 char **varying_names
, tfeedback_decl
*decls
)
1939 for (unsigned i
= 0; i
< num_names
; ++i
) {
1940 if (!decls
[i
].init(ctx
, prog
, mem_ctx
, varying_names
[i
]))
1943 if (!decls
[i
].is_varying())
1946 /* From GL_EXT_transform_feedback:
1947 * A program will fail to link if:
1949 * * any two entries in the <varyings> array specify the same varying
1952 * We interpret this to mean "any two entries in the <varyings> array
1953 * specify the same varying variable and array index", since transform
1954 * feedback of arrays would be useless otherwise.
1956 for (unsigned j
= 0; j
< i
; ++j
) {
1957 if (!decls
[j
].is_varying())
1960 if (tfeedback_decl::is_same(decls
[i
], decls
[j
])) {
1961 linker_error(prog
, "Transform feedback varying %s specified "
1962 "more than once.", varying_names
[i
]);
1972 * Assign a location for a variable that is produced in one pipeline stage
1973 * (the "producer") and consumed in the next stage (the "consumer").
1975 * \param input_var is the input variable declaration in the consumer.
1977 * \param output_var is the output variable declaration in the producer.
1979 * \param input_index is the counter that keeps track of assigned input
1980 * locations in the consumer.
1982 * \param output_index is the counter that keeps track of assigned output
1983 * locations in the producer.
1985 * It is permissible for \c input_var to be NULL (this happens if a variable
1986 * is output by the producer and consumed by transform feedback, but not
1987 * consumed by the consumer).
1989 * If the variable has already been assigned a location, this function has no
1993 assign_varying_location(ir_variable
*input_var
, ir_variable
*output_var
,
1994 unsigned *input_index
, unsigned *output_index
)
1996 if (!output_var
->is_unmatched_generic_inout
) {
1997 /* Location already assigned. */
2002 assert(input_var
->location
== -1);
2003 input_var
->location
= *input_index
;
2004 input_var
->is_unmatched_generic_inout
= 0;
2007 output_var
->location
= *output_index
;
2008 output_var
->is_unmatched_generic_inout
= 0;
2010 /* FINISHME: Support for "varying" records in GLSL 1.50. */
2011 assert(!output_var
->type
->is_record());
2013 if (output_var
->type
->is_array()) {
2014 const unsigned slots
= output_var
->type
->length
2015 * output_var
->type
->fields
.array
->matrix_columns
;
2017 *output_index
+= slots
;
2018 *input_index
+= slots
;
2020 const unsigned slots
= output_var
->type
->matrix_columns
;
2022 *output_index
+= slots
;
2023 *input_index
+= slots
;
2029 * Is the given variable a varying variable to be counted against the
2030 * limit in ctx->Const.MaxVarying?
2031 * This includes variables such as texcoords, colors and generic
2032 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
2035 is_varying_var(GLenum shaderType
, const ir_variable
*var
)
2037 /* Only fragment shaders will take a varying variable as an input */
2038 if (shaderType
== GL_FRAGMENT_SHADER
&&
2039 var
->mode
== ir_var_in
) {
2040 switch (var
->location
) {
2041 case FRAG_ATTRIB_WPOS
:
2042 case FRAG_ATTRIB_FACE
:
2043 case FRAG_ATTRIB_PNTC
:
2054 * Assign locations for all variables that are produced in one pipeline stage
2055 * (the "producer") and consumed in the next stage (the "consumer").
2057 * Variables produced by the producer may also be consumed by transform
2060 * \param num_tfeedback_decls is the number of declarations indicating
2061 * variables that may be consumed by transform feedback.
2063 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
2064 * representing the result of parsing the strings passed to
2065 * glTransformFeedbackVaryings(). assign_location() will be called for
2066 * each of these objects that matches one of the outputs of the
2069 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
2070 * be NULL. In this case, varying locations are assigned solely based on the
2071 * requirements of transform feedback.
2074 assign_varying_locations(struct gl_context
*ctx
,
2075 struct gl_shader_program
*prog
,
2076 gl_shader
*producer
, gl_shader
*consumer
,
2077 unsigned num_tfeedback_decls
,
2078 tfeedback_decl
*tfeedback_decls
)
2080 /* FINISHME: Set dynamically when geometry shader support is added. */
2081 unsigned output_index
= VERT_RESULT_VAR0
;
2082 unsigned input_index
= FRAG_ATTRIB_VAR0
;
2084 /* Operate in a total of three passes.
2086 * 1. Assign locations for any matching inputs and outputs.
2088 * 2. Mark output variables in the producer that do not have locations as
2089 * not being outputs. This lets the optimizer eliminate them.
2091 * 3. Mark input variables in the consumer that do not have locations as
2092 * not being inputs. This lets the optimizer eliminate them.
2095 foreach_list(node
, producer
->ir
) {
2096 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
2098 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
))
2101 ir_variable
*input_var
=
2102 consumer
? consumer
->symbols
->get_variable(output_var
->name
) : NULL
;
2104 if (input_var
&& input_var
->mode
!= ir_var_in
)
2108 assign_varying_location(input_var
, output_var
, &input_index
,
2112 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2113 if (!tfeedback_decls
[i
].is_varying())
2116 if (!tfeedback_decls
[i
].is_assigned() &&
2117 tfeedback_decls
[i
].matches_var(output_var
)) {
2118 if (output_var
->is_unmatched_generic_inout
) {
2119 assign_varying_location(input_var
, output_var
, &input_index
,
2122 if (!tfeedback_decls
[i
].assign_location(ctx
, prog
, output_var
))
2128 unsigned varying_vectors
= 0;
2131 foreach_list(node
, consumer
->ir
) {
2132 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2134 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
2137 if (var
->is_unmatched_generic_inout
) {
2138 if (prog
->Version
<= 120) {
2139 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
2141 * Only those varying variables used (i.e. read) in
2142 * the fragment shader executable must be written to
2143 * by the vertex shader executable; declaring
2144 * superfluous varying variables in a vertex shader is
2147 * We interpret this text as meaning that the VS must
2148 * write the variable for the FS to read it. See
2149 * "glsl1-varying read but not written" in piglit.
2152 linker_error(prog
, "fragment shader varying %s not written "
2153 "by vertex shader\n.", var
->name
);
2156 /* An 'in' variable is only really a shader input if its
2157 * value is written by the previous stage.
2159 var
->mode
= ir_var_auto
;
2160 } else if (is_varying_var(consumer
->Type
, var
)) {
2161 /* The packing rules are used for vertex shader inputs are also
2162 * used for fragment shader inputs.
2164 varying_vectors
+= count_attribute_slots(var
->type
);
2169 if (ctx
->API
== API_OPENGLES2
|| prog
->IsES
) {
2170 if (varying_vectors
> ctx
->Const
.MaxVarying
) {
2171 if (ctx
->Const
.GLSLSkipStrictMaxVaryingLimitCheck
) {
2172 linker_warning(prog
, "shader uses too many varying vectors "
2173 "(%u > %u), but the driver will try to optimize "
2174 "them out; this is non-portable out-of-spec "
2176 varying_vectors
, ctx
->Const
.MaxVarying
);
2178 linker_error(prog
, "shader uses too many varying vectors "
2180 varying_vectors
, ctx
->Const
.MaxVarying
);
2185 const unsigned float_components
= varying_vectors
* 4;
2186 if (float_components
> ctx
->Const
.MaxVarying
* 4) {
2187 if (ctx
->Const
.GLSLSkipStrictMaxVaryingLimitCheck
) {
2188 linker_warning(prog
, "shader uses too many varying components "
2189 "(%u > %u), but the driver will try to optimize "
2190 "them out; this is non-portable out-of-spec "
2192 float_components
, ctx
->Const
.MaxVarying
* 4);
2194 linker_error(prog
, "shader uses too many varying components "
2196 float_components
, ctx
->Const
.MaxVarying
* 4);
2207 * Store transform feedback location assignments into
2208 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2210 * If an error occurs, the error is reported through linker_error() and false
2214 store_tfeedback_info(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
2215 unsigned num_tfeedback_decls
,
2216 tfeedback_decl
*tfeedback_decls
)
2218 bool separate_attribs_mode
=
2219 prog
->TransformFeedback
.BufferMode
== GL_SEPARATE_ATTRIBS
;
2221 ralloc_free(prog
->LinkedTransformFeedback
.Varyings
);
2222 ralloc_free(prog
->LinkedTransformFeedback
.Outputs
);
2224 memset(&prog
->LinkedTransformFeedback
, 0,
2225 sizeof(prog
->LinkedTransformFeedback
));
2227 prog
->LinkedTransformFeedback
.Varyings
=
2229 struct gl_transform_feedback_varying_info
,
2230 num_tfeedback_decls
);
2232 unsigned num_outputs
= 0;
2233 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
)
2234 if (!tfeedback_decls
[i
].accumulate_num_outputs(prog
, &num_outputs
))
2237 prog
->LinkedTransformFeedback
.Outputs
=
2239 struct gl_transform_feedback_output
,
2242 unsigned num_buffers
= 0;
2244 if (separate_attribs_mode
) {
2245 /* GL_SEPARATE_ATTRIBS */
2246 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2247 if (!tfeedback_decls
[i
].store(ctx
, prog
, &prog
->LinkedTransformFeedback
,
2248 num_buffers
, num_outputs
))
2255 /* GL_INVERLEAVED_ATTRIBS */
2256 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2257 if (tfeedback_decls
[i
].is_next_buffer_separator()) {
2262 if (!tfeedback_decls
[i
].store(ctx
, prog
,
2263 &prog
->LinkedTransformFeedback
,
2264 num_buffers
, num_outputs
))
2270 assert(prog
->LinkedTransformFeedback
.NumOutputs
== num_outputs
);
2272 prog
->LinkedTransformFeedback
.NumBuffers
= num_buffers
;
2277 * Store the gl_FragDepth layout in the gl_shader_program struct.
2280 store_fragdepth_layout(struct gl_shader_program
*prog
)
2282 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2286 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2288 /* We don't look up the gl_FragDepth symbol directly because if
2289 * gl_FragDepth is not used in the shader, it's removed from the IR.
2290 * However, the symbol won't be removed from the symbol table.
2292 * We're only interested in the cases where the variable is NOT removed
2295 foreach_list(node
, ir
) {
2296 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2298 if (var
== NULL
|| var
->mode
!= ir_var_out
) {
2302 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2303 switch (var
->depth_layout
) {
2304 case ir_depth_layout_none
:
2305 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2307 case ir_depth_layout_any
:
2308 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2310 case ir_depth_layout_greater
:
2311 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2313 case ir_depth_layout_less
:
2314 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2316 case ir_depth_layout_unchanged
:
2317 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2328 * Validate the resources used by a program versus the implementation limits
2331 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2333 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
2334 "vertex", "fragment", "geometry"
2337 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
2338 ctx
->Const
.MaxVertexTextureImageUnits
,
2339 ctx
->Const
.MaxTextureImageUnits
,
2340 ctx
->Const
.MaxGeometryTextureImageUnits
2343 const unsigned max_uniform_components
[MESA_SHADER_TYPES
] = {
2344 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
2345 ctx
->Const
.FragmentProgram
.MaxUniformComponents
,
2346 0 /* FINISHME: Geometry shaders. */
2349 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
2350 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
2351 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
,
2352 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
2355 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2356 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2361 if (sh
->num_samplers
> max_samplers
[i
]) {
2362 linker_error(prog
, "Too many %s shader texture samplers",
2366 if (sh
->num_uniform_components
> max_uniform_components
[i
]) {
2367 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2368 linker_warning(prog
, "Too many %s shader uniform components, "
2369 "but the driver will try to optimize them out; "
2370 "this is non-portable out-of-spec behavior\n",
2373 linker_error(prog
, "Too many %s shader uniform components",
2379 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
2380 unsigned total_uniform_blocks
= 0;
2382 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
2383 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
2384 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2386 total_uniform_blocks
++;
2390 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2391 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
2392 prog
->NumUniformBlocks
,
2393 ctx
->Const
.MaxCombinedUniformBlocks
);
2395 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2396 if (blocks
[i
] > max_uniform_blocks
[i
]) {
2397 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
2400 max_uniform_blocks
[i
]);
2407 return prog
->LinkStatus
;
2411 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2413 tfeedback_decl
*tfeedback_decls
= NULL
;
2414 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
2416 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
2418 prog
->LinkStatus
= false;
2419 prog
->Validated
= false;
2420 prog
->_Used
= false;
2422 ralloc_free(prog
->InfoLog
);
2423 prog
->InfoLog
= ralloc_strdup(NULL
, "");
2425 ralloc_free(prog
->UniformBlocks
);
2426 prog
->UniformBlocks
= NULL
;
2427 prog
->NumUniformBlocks
= 0;
2428 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2429 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
2430 prog
->UniformBlockStageIndex
[i
] = NULL
;
2433 /* Separate the shaders into groups based on their type.
2435 struct gl_shader
**vert_shader_list
;
2436 unsigned num_vert_shaders
= 0;
2437 struct gl_shader
**frag_shader_list
;
2438 unsigned num_frag_shaders
= 0;
2440 vert_shader_list
= (struct gl_shader
**)
2441 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
2442 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
2444 unsigned min_version
= UINT_MAX
;
2445 unsigned max_version
= 0;
2446 const bool is_es_prog
=
2447 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
2448 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
2449 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
2450 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
2452 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
2453 linker_error(prog
, "all shaders must use same shading "
2454 "language version\n");
2458 switch (prog
->Shaders
[i
]->Type
) {
2459 case GL_VERTEX_SHADER
:
2460 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
2463 case GL_FRAGMENT_SHADER
:
2464 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
2467 case GL_GEOMETRY_SHADER
:
2468 /* FINISHME: Support geometry shaders. */
2469 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
2474 /* Previous to GLSL version 1.30, different compilation units could mix and
2475 * match shading language versions. With GLSL 1.30 and later, the versions
2476 * of all shaders must match.
2478 * GLSL ES has never allowed mixing of shading language versions.
2480 if ((is_es_prog
|| max_version
>= 130)
2481 && min_version
!= max_version
) {
2482 linker_error(prog
, "all shaders must use same shading "
2483 "language version\n");
2487 prog
->Version
= max_version
;
2488 prog
->IsES
= is_es_prog
;
2490 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2491 if (prog
->_LinkedShaders
[i
] != NULL
)
2492 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
2494 prog
->_LinkedShaders
[i
] = NULL
;
2497 /* Link all shaders for a particular stage and validate the result.
2499 if (num_vert_shaders
> 0) {
2500 gl_shader
*const sh
=
2501 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
2507 if (!validate_vertex_shader_executable(prog
, sh
))
2510 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2514 if (num_frag_shaders
> 0) {
2515 gl_shader
*const sh
=
2516 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
2522 if (!validate_fragment_shader_executable(prog
, sh
))
2525 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2529 /* Here begins the inter-stage linking phase. Some initial validation is
2530 * performed, then locations are assigned for uniforms, attributes, and
2533 if (cross_validate_uniforms(prog
)) {
2536 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
2537 if (prog
->_LinkedShaders
[prev
] != NULL
)
2541 /* Validate the inputs of each stage with the output of the preceding
2544 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
2545 if (prog
->_LinkedShaders
[i
] == NULL
)
2548 if (!cross_validate_outputs_to_inputs(prog
,
2549 prog
->_LinkedShaders
[prev
],
2550 prog
->_LinkedShaders
[i
]))
2556 prog
->LinkStatus
= true;
2559 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2560 * it before optimization because we want most of the checks to get
2561 * dropped thanks to constant propagation.
2563 * This rule also applies to GLSL ES 3.00.
2565 if (max_version
>= (is_es_prog
? 300 : 130)) {
2566 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2568 lower_discard_flow(sh
->ir
);
2572 if (!interstage_cross_validate_uniform_blocks(prog
))
2575 /* Do common optimization before assigning storage for attributes,
2576 * uniforms, and varyings. Later optimization could possibly make
2577 * some of that unused.
2579 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2580 if (prog
->_LinkedShaders
[i
] == NULL
)
2583 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
2584 if (!prog
->LinkStatus
)
2587 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
2588 lower_clip_distance(prog
->_LinkedShaders
[i
]);
2591 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
2593 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
))
2597 /* Mark all generic shader inputs and outputs as unpaired. */
2598 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2599 link_invalidate_variable_locations(
2600 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2601 VERT_ATTRIB_GENERIC0
, VERT_RESULT_VAR0
);
2603 /* FINISHME: Geometry shaders not implemented yet */
2604 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2605 link_invalidate_variable_locations(
2606 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2607 FRAG_ATTRIB_VAR0
, FRAG_RESULT_DATA0
);
2610 /* FINISHME: The value of the max_attribute_index parameter is
2611 * FINISHME: implementation dependent based on the value of
2612 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2613 * FINISHME: at least 16, so hardcode 16 for now.
2615 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
2619 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
2624 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
2625 if (prog
->_LinkedShaders
[prev
] != NULL
)
2629 if (num_tfeedback_decls
!= 0) {
2630 /* From GL_EXT_transform_feedback:
2631 * A program will fail to link if:
2633 * * the <count> specified by TransformFeedbackVaryingsEXT is
2634 * non-zero, but the program object has no vertex or geometry
2637 if (prev
>= MESA_SHADER_FRAGMENT
) {
2638 linker_error(prog
, "Transform feedback varyings specified, but "
2639 "no vertex or geometry shader is present.");
2643 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
2644 prog
->TransformFeedback
.NumVarying
);
2645 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
2646 prog
->TransformFeedback
.VaryingNames
,
2651 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
2652 if (prog
->_LinkedShaders
[i
] == NULL
)
2655 if (!assign_varying_locations(
2656 ctx
, prog
, prog
->_LinkedShaders
[prev
], prog
->_LinkedShaders
[i
],
2657 i
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2664 if (prev
!= MESA_SHADER_FRAGMENT
&& num_tfeedback_decls
!= 0) {
2665 /* There was no fragment shader, but we still have to assign varying
2666 * locations for use by transform feedback.
2668 if (!assign_varying_locations(
2669 ctx
, prog
, prog
->_LinkedShaders
[prev
], NULL
, num_tfeedback_decls
,
2674 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
2677 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2678 demote_shader_inputs_and_outputs(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2681 /* Eliminate code that is now dead due to unused vertex outputs being
2684 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
]->ir
, false))
2688 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
2689 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
2691 demote_shader_inputs_and_outputs(sh
, ir_var_in
);
2692 demote_shader_inputs_and_outputs(sh
, ir_var_inout
);
2693 demote_shader_inputs_and_outputs(sh
, ir_var_out
);
2695 /* Eliminate code that is now dead due to unused geometry outputs being
2698 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
, false))
2702 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2703 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2705 demote_shader_inputs_and_outputs(sh
, ir_var_in
);
2707 /* Eliminate code that is now dead due to unused fragment inputs being
2708 * demoted. This shouldn't actually do anything other than remove
2709 * declarations of the (now unused) global variables.
2711 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
, false))
2715 update_array_sizes(prog
);
2716 link_assign_uniform_locations(prog
);
2717 store_fragdepth_layout(prog
);
2719 if (!check_resources(ctx
, prog
))
2722 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2723 * present in a linked program. By checking prog->IsES, we also
2724 * catch the GL_ARB_ES2_compatibility case.
2726 if (!prog
->InternalSeparateShader
&&
2727 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
2728 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
2729 linker_error(prog
, "program lacks a vertex shader\n");
2730 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2731 linker_error(prog
, "program lacks a fragment shader\n");
2735 /* FINISHME: Assign fragment shader output locations. */
2738 free(vert_shader_list
);
2740 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2741 if (prog
->_LinkedShaders
[i
] == NULL
)
2744 /* Retain any live IR, but trash the rest. */
2745 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
2747 /* The symbol table in the linked shaders may contain references to
2748 * variables that were removed (e.g., unused uniforms). Since it may
2749 * contain junk, there is no possible valid use. Delete it and set the
2752 delete prog
->_LinkedShaders
[i
]->symbols
;
2753 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
2756 ralloc_free(mem_ctx
);