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, enum ir_variable_mode mode,
206 foreach_list(node, sh->ir) {
207 ir_variable *const var = ((ir_instruction *) node)->as_variable();
209 if ((var == NULL) || (var->mode != (unsigned) mode))
212 /* Only assign locations for generic attributes / varyings / etc.
214 if ((var->location >= generic_base) && !var->explicit_location)
221 * Determine the number of attribute slots required for a particular type
223 * This code is here because it implements the language rules of a specific
224 * GLSL version. Since it's a property of the language and not a property of
225 * types in general, it doesn't really belong in glsl_type.
228 count_attribute_slots(const glsl_type *t)
230 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
232 * "A scalar input counts the same amount against this limit as a vec4,
233 * so applications may want to consider packing groups of four
234 * unrelated float inputs together into a vector to better utilize the
235 * capabilities of the underlying hardware. A matrix input will use up
236 * multiple locations. The number of locations used will equal the
237 * number of columns in the matrix."
239 * The spec does not explicitly say how arrays are counted. However, it
240 * should be safe to assume the total number of slots consumed by an array
241 * is the number of entries in the array multiplied by the number of slots
242 * consumed by a single element of the array.
246 return t->array_size() * count_attribute_slots(t->element_type());
249 return t->matrix_columns;
256 * Verify that a vertex shader executable meets all semantic requirements.
258 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
261 * \param shader Vertex shader executable to be verified
264 validate_vertex_shader_executable(struct gl_shader_program *prog,
265 struct gl_shader *shader)
270 /* From the GLSL 1.10 spec, page 48:
272 * "The variable gl_Position is available only in the vertex
273 * language and is intended for writing the homogeneous vertex
274 * position. All executions of a well-formed vertex shader
275 * executable must write a value into this variable. [...] The
276 * variable gl_Position is available only in the vertex
277 * language and is intended for writing the homogeneous vertex
278 * position. All executions of a well-formed vertex shader
279 * executable must write a value into this variable."
281 * while in GLSL 1.40 this text is changed to:
283 * "The variable gl_Position is available only in the vertex
284 * language and is intended for writing the homogeneous vertex
285 * position. It can be written at any time during shader
286 * execution. It may also be read back by a vertex shader
287 * after being written. This value will be used by primitive
288 * assembly, clipping, culling, and other fixed functionality
289 * operations, if present, that operate on primitives after
290 * vertex processing has occurred. Its value is undefined if
291 * the vertex shader executable does not write gl_Position."
293 if (prog->Version < 140) {
294 find_assignment_visitor find("gl_Position");
295 find.run(shader->ir);
296 if (!find.variable_found()) {
297 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
302 prog->Vert.ClipDistanceArraySize = 0;
304 if (prog->Version >= 130) {
305 /* From section 7.1 (Vertex Shader Special Variables) of the
308 * "It is an error for a shader to statically write both
309 * gl_ClipVertex and gl_ClipDistance."
311 find_assignment_visitor clip_vertex("gl_ClipVertex");
312 find_assignment_visitor clip_distance("gl_ClipDistance");
314 clip_vertex.run(shader->ir);
315 clip_distance.run(shader->ir);
316 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
317 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
318 "and `gl_ClipDistance'\n");
321 prog->Vert.UsesClipDistance = clip_distance.variable_found();
322 ir_variable *clip_distance_var =
323 shader->symbols->get_variable("gl_ClipDistance");
324 if (clip_distance_var)
325 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
333 * Verify that a fragment shader executable meets all semantic requirements
335 * \param shader Fragment shader executable to be verified
338 validate_fragment_shader_executable(struct gl_shader_program *prog,
339 struct gl_shader *shader)
344 find_assignment_visitor frag_color("gl_FragColor");
345 find_assignment_visitor frag_data("gl_FragData");
347 frag_color.run(shader->ir);
348 frag_data.run(shader->ir);
350 if (frag_color.variable_found() && frag_data.variable_found()) {
351 linker_error(prog, "fragment shader writes to both "
352 "`gl_FragColor' and `gl_FragData'\n");
361 * Generate a string describing the mode of a variable
364 mode_string(const ir_variable *var)
368 return (var->read_only) ? "global constant" : "global variable";
370 case ir_var_uniform: return "uniform";
371 case ir_var_in: return "shader input";
372 case ir_var_out: return "shader output";
373 case ir_var_inout: return "shader inout";
375 case ir_var_const_in:
376 case ir_var_temporary:
378 assert(!"Should not get here.");
379 return "invalid variable";
385 * Perform validation of global variables used across multiple shaders
388 cross_validate_globals(struct gl_shader_program *prog,
389 struct gl_shader **shader_list,
390 unsigned num_shaders,
393 /* Examine all of the uniforms in all of the shaders and cross validate
396 glsl_symbol_table variables;
397 for (unsigned i = 0; i < num_shaders; i++) {
398 if (shader_list[i] == NULL)
401 foreach_list(node, shader_list[i]->ir) {
402 ir_variable *const var = ((ir_instruction *) node)->as_variable();
407 if (uniforms_only && (var->mode != ir_var_uniform))
410 /* Don't cross validate temporaries that are at global scope. These
411 * will eventually get pulled into the shaders 'main'.
413 if (var->mode == ir_var_temporary)
416 /* If a global with this name has already been seen, verify that the
417 * new instance has the same type. In addition, if the globals have
418 * initializers, the values of the initializers must be the same.
420 ir_variable *const existing = variables.get_variable(var->name);
421 if (existing != NULL) {
422 if (var->type != existing->type) {
423 /* Consider the types to be "the same" if both types are arrays
424 * of the same type and one of the arrays is implicitly sized.
425 * In addition, set the type of the linked variable to the
426 * explicitly sized array.
428 if (var->type->is_array()
429 && existing->type->is_array()
430 && (var->type->fields.array == existing->type->fields.array)
431 && ((var->type->length == 0)
432 || (existing->type->length == 0))) {
433 if (var->type->length != 0) {
434 existing->type = var->type;
437 linker_error(prog, "%s `%s' declared as type "
438 "`%s' and type `%s'\n",
440 var->name, var->type->name,
441 existing->type->name);
446 if (var->explicit_location) {
447 if (existing->explicit_location
448 && (var->location != existing->location)) {
449 linker_error(prog, "explicit locations for %s "
450 "`%s' have differing values\n",
451 mode_string(var), var->name);
455 existing->location = var->location;
456 existing->explicit_location = true;
459 /* Validate layout qualifiers for gl_FragDepth.
461 * From the AMD/ARB_conservative_depth specs:
463 * "If gl_FragDepth is redeclared in any fragment shader in a
464 * program, it must be redeclared in all fragment shaders in
465 * that program that have static assignments to
466 * gl_FragDepth. All redeclarations of gl_FragDepth in all
467 * fragment shaders in a single program must have the same set
470 if (strcmp(var->name, "gl_FragDepth") == 0) {
471 bool layout_declared = var->depth_layout != ir_depth_layout_none;
472 bool layout_differs =
473 var->depth_layout != existing->depth_layout;
475 if (layout_declared && layout_differs) {
477 "All redeclarations of gl_FragDepth in all "
478 "fragment shaders in a single program must have "
479 "the same set of qualifiers.");
482 if (var->used && layout_differs) {
484 "If gl_FragDepth is redeclared with a layout "
485 "qualifier in any fragment shader, it must be "
486 "redeclared with the same layout qualifier in "
487 "all fragment shaders that have assignments to "
492 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
494 * "If a shared global has multiple initializers, the
495 * initializers must all be constant expressions, and they
496 * must all have the same value. Otherwise, a link error will
497 * result. (A shared global having only one initializer does
498 * not require that initializer to be a constant expression.)"
500 * Previous to 4.20 the GLSL spec simply said that initializers
501 * must have the same value. In this case of non-constant
502 * initializers, this was impossible to determine. As a result,
503 * no vendor actually implemented that behavior. The 4.20
504 * behavior matches the implemented behavior of at least one other
505 * vendor, so we'll implement that for all GLSL versions.
507 if (var->constant_initializer != NULL) {
508 if (existing->constant_initializer != NULL) {
509 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
510 linker_error(prog, "initializers for %s "
511 "`%s' have differing values\n",
512 mode_string(var), var->name);
516 /* If the first-seen instance of a particular uniform did not
517 * have an initializer but a later instance does, copy the
518 * initializer to the version stored in the symbol table.
520 /* FINISHME: This is wrong. The constant_value field should
521 * FINISHME: not be modified! Imagine a case where a shader
522 * FINISHME: without an initializer is linked in two different
523 * FINISHME: programs with shaders that have differing
524 * FINISHME: initializers. Linking with the first will
525 * FINISHME: modify the shader, and linking with the second
526 * FINISHME: will fail.
528 existing->constant_initializer =
529 var->constant_initializer->clone(ralloc_parent(existing),
534 if (var->has_initializer) {
535 if (existing->has_initializer
536 && (var->constant_initializer == NULL
537 || existing->constant_initializer == NULL)) {
539 "shared global variable `%s' has multiple "
540 "non-constant initializers.\n",
545 /* Some instance had an initializer, so keep track of that. In
546 * this location, all sorts of initializers (constant or
547 * otherwise) will propagate the existence to the variable
548 * stored in the symbol table.
550 existing->has_initializer = true;
553 if (existing->invariant != var->invariant) {
554 linker_error(prog, "declarations for %s `%s' have "
555 "mismatching invariant qualifiers\n",
556 mode_string(var), var->name);
559 if (existing->centroid != var->centroid) {
560 linker_error(prog, "declarations for %s `%s' have "
561 "mismatching centroid qualifiers\n",
562 mode_string(var), var->name);
566 variables.add_variable(var);
575 * Perform validation of uniforms used across multiple shader stages
578 cross_validate_uniforms(struct gl_shader_program *prog)
580 return cross_validate_globals(prog, prog->_LinkedShaders,
581 MESA_SHADER_TYPES, true);
585 * Accumulates the array of prog->UniformBlocks and checks that all
586 * definitons of blocks agree on their contents.
589 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
591 unsigned max_num_uniform_blocks = 0;
592 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
593 if (prog->_LinkedShaders[i])
594 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
597 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
598 struct gl_shader *sh = prog->_LinkedShaders[i];
600 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
601 max_num_uniform_blocks);
602 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
603 prog->UniformBlockStageIndex[i][j] = -1;
608 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
609 int index = link_cross_validate_uniform_block(prog,
610 &prog->UniformBlocks,
611 &prog->NumUniformBlocks,
612 &sh->UniformBlocks[j]);
615 linker_error(prog, "uniform block `%s' has mismatching definitions",
616 sh->UniformBlocks[j].Name);
620 prog->UniformBlockStageIndex[i][index] = j;
628 * Validate that outputs from one stage match inputs of another
631 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
632 gl_shader *producer, gl_shader *consumer)
634 glsl_symbol_table parameters;
635 /* FINISHME: Figure these out dynamically. */
636 const char *const producer_stage = "vertex";
637 const char *const consumer_stage = "fragment";
639 /* Find all shader outputs in the "producer" stage.
641 foreach_list(node, producer->ir) {
642 ir_variable *const var = ((ir_instruction *) node)->as_variable();
644 /* FINISHME: For geometry shaders, this should also look for inout
645 * FINISHME: variables.
647 if ((var == NULL) || (var->mode != ir_var_out))
650 parameters.add_variable(var);
654 /* Find all shader inputs in the "consumer" stage. Any variables that have
655 * matching outputs already in the symbol table must have the same type and
658 foreach_list(node, consumer->ir) {
659 ir_variable *const input = ((ir_instruction *) node)->as_variable();
661 /* FINISHME: For geometry shaders, this should also look for inout
662 * FINISHME: variables.
664 if ((input == NULL) || (input->mode != ir_var_in))
667 ir_variable *const output = parameters.get_variable(input->name);
668 if (output != NULL) {
669 /* Check that the types match between stages.
671 if (input->type != output->type) {
672 /* There is a bit of a special case for gl_TexCoord. This
673 * built-in is unsized by default. Applications that variable
674 * access it must redeclare it with a size. There is some
675 * language in the GLSL spec that implies the fragment shader
676 * and vertex shader do not have to agree on this size. Other
677 * driver behave this way, and one or two applications seem to
680 * Neither declaration needs to be modified here because the array
681 * sizes are fixed later when update_array_sizes is called.
683 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
685 * "Unlike user-defined varying variables, the built-in
686 * varying variables don't have a strict one-to-one
687 * correspondence between the vertex language and the
688 * fragment language."
690 if (!output->type->is_array()
691 || (strncmp("gl_", output->name, 3) != 0)) {
693 "%s shader output `%s' declared as type `%s', "
694 "but %s shader input declared as type `%s'\n",
695 producer_stage, output->name,
697 consumer_stage, input->type->name);
702 /* Check that all of the qualifiers match between stages.
704 if (input->centroid != output->centroid) {
706 "%s shader output `%s' %s centroid qualifier, "
707 "but %s shader input %s centroid qualifier\n",
710 (output->centroid) ? "has" : "lacks",
712 (input->centroid) ? "has" : "lacks");
716 if (input->invariant != output->invariant) {
718 "%s shader output `%s' %s invariant qualifier, "
719 "but %s shader input %s invariant qualifier\n",
722 (output->invariant) ? "has" : "lacks",
724 (input->invariant) ? "has" : "lacks");
728 if (input->interpolation != output->interpolation) {
730 "%s shader output `%s' specifies %s "
731 "interpolation qualifier, "
732 "but %s shader input specifies %s "
733 "interpolation qualifier\n",
736 output->interpolation_string(),
738 input->interpolation_string());
749 * Populates a shaders symbol table with all global declarations
752 populate_symbol_table(gl_shader *sh)
754 sh->symbols = new(sh) glsl_symbol_table;
756 foreach_list(node, sh->ir) {
757 ir_instruction *const inst = (ir_instruction *) node;
761 if ((func = inst->as_function()) != NULL) {
762 sh->symbols->add_function(func);
763 } else if ((var = inst->as_variable()) != NULL) {
764 sh->symbols->add_variable(var);
771 * Remap variables referenced in an instruction tree
773 * This is used when instruction trees are cloned from one shader and placed in
774 * another. These trees will contain references to \c ir_variable nodes that
775 * do not exist in the target shader. This function finds these \c ir_variable
776 * references and replaces the references with matching variables in the target
779 * If there is no matching variable in the target shader, a clone of the
780 * \c ir_variable is made and added to the target shader. The new variable is
781 * added to \b both the instruction stream and the symbol table.
783 * \param inst IR tree that is to be processed.
784 * \param symbols Symbol table containing global scope symbols in the
786 * \param instructions Instruction stream where new variable declarations
790 remap_variables(ir_instruction *inst, struct gl_shader *target,
793 class remap_visitor : public ir_hierarchical_visitor {
795 remap_visitor(struct gl_shader *target,
798 this->target = target;
799 this->symbols = target->symbols;
800 this->instructions = target->ir;
804 virtual ir_visitor_status visit(ir_dereference_variable *ir)
806 if (ir->var->mode == ir_var_temporary) {
807 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
811 return visit_continue;
814 ir_variable *const existing =
815 this->symbols->get_variable(ir->var->name);
816 if (existing != NULL)
819 ir_variable *copy = ir->var->clone(this->target, NULL);
821 this->symbols->add_variable(copy);
822 this->instructions->push_head(copy);
826 return visit_continue;
830 struct gl_shader *target;
831 glsl_symbol_table *symbols;
832 exec_list *instructions;
836 remap_visitor v(target, temps);
843 * Move non-declarations from one instruction stream to another
845 * The intended usage pattern of this function is to pass the pointer to the
846 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
847 * pointer) for \c last and \c false for \c make_copies on the first
848 * call. Successive calls pass the return value of the previous call for
849 * \c last and \c true for \c make_copies.
851 * \param instructions Source instruction stream
852 * \param last Instruction after which new instructions should be
853 * inserted in the target instruction stream
854 * \param make_copies Flag selecting whether instructions in \c instructions
855 * should be copied (via \c ir_instruction::clone) into the
856 * target list or moved.
859 * The new "last" instruction in the target instruction stream. This pointer
860 * is suitable for use as the \c last parameter of a later call to this
864 move_non_declarations(exec_list *instructions, exec_node *last,
865 bool make_copies, gl_shader *target)
867 hash_table *temps = NULL;
870 temps = hash_table_ctor(0, hash_table_pointer_hash,
871 hash_table_pointer_compare);
873 foreach_list_safe(node, instructions) {
874 ir_instruction *inst = (ir_instruction *) node;
876 if (inst->as_function())
879 ir_variable *var = inst->as_variable();
880 if ((var != NULL) && (var->mode != ir_var_temporary))
883 assert(inst->as_assignment()
885 || ((var != NULL) && (var->mode == ir_var_temporary)));
888 inst = inst->clone(target, NULL);
891 hash_table_insert(temps, inst, var);
893 remap_variables(inst, target, temps);
898 last->insert_after(inst);
903 hash_table_dtor(temps);
909 * Get the function signature for main from a shader
911 static ir_function_signature *
912 get_main_function_signature(gl_shader *sh)
914 ir_function *const f = sh->symbols->get_function("main");
916 exec_list void_parameters;
918 /* Look for the 'void main()' signature and ensure that it's defined.
919 * This keeps the linker from accidentally pick a shader that just
920 * contains a prototype for main.
922 * We don't have to check for multiple definitions of main (in multiple
923 * shaders) because that would have already been caught above.
925 ir_function_signature *sig = f->matching_signature(&void_parameters);
926 if ((sig != NULL) && sig->is_defined) {
936 * This class is only used in link_intrastage_shaders() below but declaring
937 * it inside that function leads to compiler warnings with some versions of
940 class array_sizing_visitor : public ir_hierarchical_visitor {
942 virtual ir_visitor_status visit(ir_variable *var)
944 if (var->type->is_array() && (var->type->length == 0)) {
945 const glsl_type *type =
946 glsl_type::get_array_instance(var->type->fields.array,
947 var->max_array_access + 1);
948 assert(type != NULL);
951 return visit_continue;
956 * Combine a group of shaders for a single stage to generate a linked shader
959 * If this function is supplied a single shader, it is cloned, and the new
960 * shader is returned.
962 static struct gl_shader *
963 link_intrastage_shaders(void *mem_ctx,
964 struct gl_context *ctx,
965 struct gl_shader_program *prog,
966 struct gl_shader **shader_list,
967 unsigned num_shaders)
969 struct gl_uniform_block *uniform_blocks = NULL;
970 unsigned num_uniform_blocks = 0;
972 /* Check that global variables defined in multiple shaders are consistent.
974 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
977 /* Check that uniform blocks between shaders for a stage agree. */
978 for (unsigned i = 0; i < num_shaders; i++) {
979 struct gl_shader *sh = shader_list[i];
981 for (unsigned j = 0; j < shader_list[i]->NumUniformBlocks; j++) {
982 link_assign_uniform_block_offsets(shader_list[i]);
984 int index = link_cross_validate_uniform_block(mem_ctx,
987 &sh->UniformBlocks[j]);
989 linker_error(prog, "uniform block `%s' has mismatching definitions",
990 sh->UniformBlocks[j].Name);
996 /* Check that there is only a single definition of each function signature
997 * across all shaders.
999 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1000 foreach_list(node, shader_list[i]->ir) {
1001 ir_function *const f = ((ir_instruction *) node)->as_function();
1006 for (unsigned j = i + 1; j < num_shaders; j++) {
1007 ir_function *const other =
1008 shader_list[j]->symbols->get_function(f->name);
1010 /* If the other shader has no function (and therefore no function
1011 * signatures) with the same name, skip to the next shader.
1016 foreach_iter (exec_list_iterator, iter, *f) {
1017 ir_function_signature *sig =
1018 (ir_function_signature *) iter.get();
1020 if (!sig->is_defined || sig->is_builtin)
1023 ir_function_signature *other_sig =
1024 other->exact_matching_signature(& sig->parameters);
1026 if ((other_sig != NULL) && other_sig->is_defined
1027 && !other_sig->is_builtin) {
1028 linker_error(prog, "function `%s' is multiply defined",
1037 /* Find the shader that defines main, and make a clone of it.
1039 * Starting with the clone, search for undefined references. If one is
1040 * found, find the shader that defines it. Clone the reference and add
1041 * it to the shader. Repeat until there are no undefined references or
1042 * until a reference cannot be resolved.
1044 gl_shader *main = NULL;
1045 for (unsigned i = 0; i < num_shaders; i++) {
1046 if (get_main_function_signature(shader_list[i]) != NULL) {
1047 main = shader_list[i];
1053 linker_error(prog, "%s shader lacks `main'\n",
1054 (shader_list[0]->Type == GL_VERTEX_SHADER)
1055 ? "vertex" : "fragment");
1059 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1060 linked->ir = new(linked) exec_list;
1061 clone_ir_list(mem_ctx, linked->ir, main->ir);
1063 linked->UniformBlocks = uniform_blocks;
1064 linked->NumUniformBlocks = num_uniform_blocks;
1065 ralloc_steal(linked, linked->UniformBlocks);
1067 populate_symbol_table(linked);
1069 /* The a pointer to the main function in the final linked shader (i.e., the
1070 * copy of the original shader that contained the main function).
1072 ir_function_signature *const main_sig = get_main_function_signature(linked);
1074 /* Move any instructions other than variable declarations or function
1075 * declarations into main.
1077 exec_node *insertion_point =
1078 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1081 for (unsigned i = 0; i < num_shaders; i++) {
1082 if (shader_list[i] == main)
1085 insertion_point = move_non_declarations(shader_list[i]->ir,
1086 insertion_point, true, linked);
1089 /* Resolve initializers for global variables in the linked shader.
1091 unsigned num_linking_shaders = num_shaders;
1092 for (unsigned i = 0; i < num_shaders; i++)
1093 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1095 gl_shader **linking_shaders =
1096 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1098 memcpy(linking_shaders, shader_list,
1099 sizeof(linking_shaders[0]) * num_shaders);
1101 unsigned idx = num_shaders;
1102 for (unsigned i = 0; i < num_shaders; i++) {
1103 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1104 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1105 idx += shader_list[i]->num_builtins_to_link;
1108 assert(idx == num_linking_shaders);
1110 if (!link_function_calls(prog, linked, linking_shaders,
1111 num_linking_shaders)) {
1112 ctx->Driver.DeleteShader(ctx, linked);
1116 free(linking_shaders);
1119 /* At this point linked should contain all of the linked IR, so
1120 * validate it to make sure nothing went wrong.
1123 validate_ir_tree(linked->ir);
1126 /* Make a pass over all variable declarations to ensure that arrays with
1127 * unspecified sizes have a size specified. The size is inferred from the
1128 * max_array_access field.
1130 if (linked != NULL) {
1131 array_sizing_visitor v;
1140 * Update the sizes of linked shader uniform arrays to the maximum
1143 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1145 * If one or more elements of an array are active,
1146 * GetActiveUniform will return the name of the array in name,
1147 * subject to the restrictions listed above. The type of the array
1148 * is returned in type. The size parameter contains the highest
1149 * array element index used, plus one. The compiler or linker
1150 * determines the highest index used. There will be only one
1151 * active uniform reported by the GL per uniform array.
1155 update_array_sizes(struct gl_shader_program *prog)
1157 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1158 if (prog->_LinkedShaders[i] == NULL)
1161 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1162 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1164 if ((var == NULL) || (var->mode != ir_var_uniform &&
1165 var->mode != ir_var_in &&
1166 var->mode != ir_var_out) ||
1167 !var->type->is_array())
1170 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1171 * will not be eliminated. Since we always do std140, just
1172 * don't resize arrays in UBOs.
1174 if (var->uniform_block != -1)
1177 unsigned int size = var->max_array_access;
1178 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1179 if (prog->_LinkedShaders[j] == NULL)
1182 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1183 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1187 if (strcmp(var->name, other_var->name) == 0 &&
1188 other_var->max_array_access > size) {
1189 size = other_var->max_array_access;
1194 if (size + 1 != var->type->fields.array->length) {
1195 /* If this is a built-in uniform (i.e., it's backed by some
1196 * fixed-function state), adjust the number of state slots to
1197 * match the new array size. The number of slots per array entry
1198 * is not known. It seems safe to assume that the total number of
1199 * slots is an integer multiple of the number of array elements.
1200 * Determine the number of slots per array element by dividing by
1201 * the old (total) size.
1203 if (var->num_state_slots > 0) {
1204 var->num_state_slots = (size + 1)
1205 * (var->num_state_slots / var->type->length);
1208 var->type = glsl_type::get_array_instance(var->type->fields.array,
1210 /* FINISHME: We should update the types of array
1211 * dereferences of this variable now.
1219 * Find a contiguous set of available bits in a bitmask.
1221 * \param used_mask Bits representing used (1) and unused (0) locations
1222 * \param needed_count Number of contiguous bits needed.
1225 * Base location of the available bits on success or -1 on failure.
1228 find_available_slots(unsigned used_mask, unsigned needed_count)
1230 unsigned needed_mask = (1 << needed_count) - 1;
1231 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1233 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1234 * cannot optimize possibly infinite loops" for the loop below.
1236 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1239 for (int i = 0; i <= max_bit_to_test; i++) {
1240 if ((needed_mask & ~used_mask) == needed_mask)
1251 * Assign locations for either VS inputs for FS outputs
1253 * \param prog Shader program whose variables need locations assigned
1254 * \param target_index Selector for the program target to receive location
1255 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1256 * \c MESA_SHADER_FRAGMENT.
1257 * \param max_index Maximum number of generic locations. This corresponds
1258 * to either the maximum number of draw buffers or the
1259 * maximum number of generic attributes.
1262 * If locations are successfully assigned, true is returned. Otherwise an
1263 * error is emitted to the shader link log and false is returned.
1266 assign_attribute_or_color_locations(gl_shader_program *prog,
1267 unsigned target_index,
1270 /* Mark invalid locations as being used.
1272 unsigned used_locations = (max_index >= 32)
1273 ? ~0 : ~((1 << max_index) - 1);
1275 assert((target_index == MESA_SHADER_VERTEX)
1276 || (target_index == MESA_SHADER_FRAGMENT));
1278 gl_shader *const sh = prog->_LinkedShaders[target_index];
1282 /* Operate in a total of four passes.
1284 * 1. Invalidate the location assignments for all vertex shader inputs.
1286 * 2. Assign locations for inputs that have user-defined (via
1287 * glBindVertexAttribLocation) locations and outputs that have
1288 * user-defined locations (via glBindFragDataLocation).
1290 * 3. Sort the attributes without assigned locations by number of slots
1291 * required in decreasing order. Fragmentation caused by attribute
1292 * locations assigned by the application may prevent large attributes
1293 * from having enough contiguous space.
1295 * 4. Assign locations to any inputs without assigned locations.
1298 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1299 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1301 const enum ir_variable_mode direction =
1302 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1305 link_invalidate_variable_locations(sh, direction, generic_base);
1307 /* Temporary storage for the set of attributes that need locations assigned.
1313 /* Used below in the call to qsort. */
1314 static int compare(const void *a, const void *b)
1316 const temp_attr *const l = (const temp_attr *) a;
1317 const temp_attr *const r = (const temp_attr *) b;
1319 /* Reversed because we want a descending order sort below. */
1320 return r->slots - l->slots;
1324 unsigned num_attr = 0;
1326 foreach_list(node, sh->ir) {
1327 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1329 if ((var == NULL) || (var->mode != (unsigned) direction))
1332 if (var->explicit_location) {
1333 if ((var->location >= (int)(max_index + generic_base))
1334 || (var->location < 0)) {
1336 "invalid explicit location %d specified for `%s'\n",
1338 ? var->location : var->location - generic_base,
1342 } else if (target_index == MESA_SHADER_VERTEX) {
1345 if (prog->AttributeBindings->get(binding, var->name)) {
1346 assert(binding >= VERT_ATTRIB_GENERIC0);
1347 var->location = binding;
1349 } else if (target_index == MESA_SHADER_FRAGMENT) {
1353 if (prog->FragDataBindings->get(binding, var->name)) {
1354 assert(binding >= FRAG_RESULT_DATA0);
1355 var->location = binding;
1357 if (prog->FragDataIndexBindings->get(index, var->name)) {
1363 /* If the variable is not a built-in and has a location statically
1364 * assigned in the shader (presumably via a layout qualifier), make sure
1365 * that it doesn't collide with other assigned locations. Otherwise,
1366 * add it to the list of variables that need linker-assigned locations.
1368 const unsigned slots = count_attribute_slots(var->type);
1369 if (var->location != -1) {
1370 if (var->location >= generic_base && var->index < 1) {
1371 /* From page 61 of the OpenGL 4.0 spec:
1373 * "LinkProgram will fail if the attribute bindings assigned
1374 * by BindAttribLocation do not leave not enough space to
1375 * assign a location for an active matrix attribute or an
1376 * active attribute array, both of which require multiple
1377 * contiguous generic attributes."
1379 * Previous versions of the spec contain similar language but omit
1380 * the bit about attribute arrays.
1382 * Page 61 of the OpenGL 4.0 spec also says:
1384 * "It is possible for an application to bind more than one
1385 * attribute name to the same location. This is referred to as
1386 * aliasing. This will only work if only one of the aliased
1387 * attributes is active in the executable program, or if no
1388 * path through the shader consumes more than one attribute of
1389 * a set of attributes aliased to the same location. A link
1390 * error can occur if the linker determines that every path
1391 * through the shader consumes multiple aliased attributes,
1392 * but implementations are not required to generate an error
1395 * These two paragraphs are either somewhat contradictory, or I
1396 * don't fully understand one or both of them.
1398 /* FINISHME: The code as currently written does not support
1399 * FINISHME: attribute location aliasing (see comment above).
1401 /* Mask representing the contiguous slots that will be used by
1404 const unsigned attr = var->location - generic_base;
1405 const unsigned use_mask = (1 << slots) - 1;
1407 /* Generate a link error if the set of bits requested for this
1408 * attribute overlaps any previously allocated bits.
1410 if ((~(use_mask << attr) & used_locations) != used_locations) {
1411 const char *const string = (target_index == MESA_SHADER_VERTEX)
1412 ? "vertex shader input" : "fragment shader output";
1414 "insufficient contiguous locations "
1415 "available for %s `%s' %d %d %d", string,
1416 var->name, used_locations, use_mask, attr);
1420 used_locations |= (use_mask << attr);
1426 to_assign[num_attr].slots = slots;
1427 to_assign[num_attr].var = var;
1431 /* If all of the attributes were assigned locations by the application (or
1432 * are built-in attributes with fixed locations), return early. This should
1433 * be the common case.
1438 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1440 if (target_index == MESA_SHADER_VERTEX) {
1441 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1442 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1443 * reserved to prevent it from being automatically allocated below.
1445 find_deref_visitor find("gl_Vertex");
1447 if (find.variable_found())
1448 used_locations |= (1 << 0);
1451 for (unsigned i = 0; i < num_attr; i++) {
1452 /* Mask representing the contiguous slots that will be used by this
1455 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1457 int location = find_available_slots(used_locations, to_assign[i].slots);
1460 const char *const string = (target_index == MESA_SHADER_VERTEX)
1461 ? "vertex shader input" : "fragment shader output";
1464 "insufficient contiguous locations "
1465 "available for %s `%s'",
1466 string, to_assign[i].var->name);
1470 to_assign[i].var->location = generic_base + location;
1471 used_locations |= (use_mask << location);
1479 * Demote shader inputs and outputs that are not used in other stages
1482 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1484 foreach_list(node, sh->ir) {
1485 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1487 if ((var == NULL) || (var->mode != int(mode)))
1490 /* A shader 'in' or 'out' variable is only really an input or output if
1491 * its value is used by other shader stages. This will cause the variable
1492 * to have a location assigned.
1494 if (var->location == -1) {
1495 var->mode = ir_var_auto;
1502 * Data structure tracking information about a transform feedback declaration
1505 class tfeedback_decl
1508 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1509 const void *mem_ctx, const char *input);
1510 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1511 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1512 ir_variable *output_var);
1513 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
1514 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
1515 struct gl_transform_feedback_info *info, unsigned buffer,
1516 const unsigned max_outputs) const;
1519 * True if assign_location() has been called for this object.
1521 bool is_assigned() const
1523 return this->location != -1;
1526 bool is_next_buffer_separator() const
1528 return this->next_buffer_separator;
1531 bool is_varying() const
1533 return !this->next_buffer_separator && !this->skip_components;
1537 * Determine whether this object refers to the variable var.
1539 bool matches_var(ir_variable *var) const
1541 if (this->is_clip_distance_mesa)
1542 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1544 return strcmp(var->name, this->var_name) == 0;
1548 * The total number of varying components taken up by this variable. Only
1549 * valid if is_assigned() is true.
1551 unsigned num_components() const
1553 if (this->is_clip_distance_mesa)
1556 return this->vector_elements * this->matrix_columns * this->size;
1561 * The name that was supplied to glTransformFeedbackVaryings. Used for
1562 * error reporting and glGetTransformFeedbackVarying().
1564 const char *orig_name;
1567 * The name of the variable, parsed from orig_name.
1569 const char *var_name;
1572 * True if the declaration in orig_name represents an array.
1574 bool is_subscripted;
1577 * If is_subscripted is true, the subscript that was specified in orig_name.
1579 unsigned array_subscript;
1582 * True if the variable is gl_ClipDistance and the driver lowers
1583 * gl_ClipDistance to gl_ClipDistanceMESA.
1585 bool is_clip_distance_mesa;
1588 * The vertex shader output location that the linker assigned for this
1589 * variable. -1 if a location hasn't been assigned yet.
1594 * If location != -1, the number of vector elements in this variable, or 1
1595 * if this variable is a scalar.
1597 unsigned vector_elements;
1600 * If location != -1, the number of matrix columns in this variable, or 1
1601 * if this variable is not a matrix.
1603 unsigned matrix_columns;
1605 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1609 * If location != -1, the size that should be returned by
1610 * glGetTransformFeedbackVarying().
1615 * How many components to skip. If non-zero, this is
1616 * gl_SkipComponents{1,2,3,4} from ARB_transform_feedback3.
1618 unsigned skip_components;
1621 * Whether this is gl_NextBuffer from ARB_transform_feedback3.
1623 bool next_buffer_separator;
1628 * Initialize this object based on a string that was passed to
1629 * glTransformFeedbackVaryings. If there is a parse error, the error is
1630 * reported using linker_error(), and false is returned.
1633 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1634 const void *mem_ctx, const char *input)
1636 /* We don't have to be pedantic about what is a valid GLSL variable name,
1637 * because any variable with an invalid name can't exist in the IR anyway.
1640 this->location = -1;
1641 this->orig_name = input;
1642 this->is_clip_distance_mesa = false;
1643 this->skip_components = 0;
1644 this->next_buffer_separator = false;
1646 if (ctx->Extensions.ARB_transform_feedback3) {
1647 /* Parse gl_NextBuffer. */
1648 if (strcmp(input, "gl_NextBuffer") == 0) {
1649 this->next_buffer_separator = true;
1653 /* Parse gl_SkipComponents. */
1654 if (strcmp(input, "gl_SkipComponents1") == 0)
1655 this->skip_components = 1;
1656 else if (strcmp(input, "gl_SkipComponents2") == 0)
1657 this->skip_components = 2;
1658 else if (strcmp(input, "gl_SkipComponents3") == 0)
1659 this->skip_components = 3;
1660 else if (strcmp(input, "gl_SkipComponents4") == 0)
1661 this->skip_components = 4;
1663 if (this->skip_components)
1667 /* Parse a declaration. */
1668 const char *bracket = strrchr(input, '[');
1671 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
1672 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
1673 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1676 this->is_subscripted = true;
1678 this->var_name = ralloc_strdup(mem_ctx, input);
1679 this->is_subscripted = false;
1682 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1683 * class must behave specially to account for the fact that gl_ClipDistance
1684 * is converted from a float[8] to a vec4[2].
1686 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1687 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1688 this->is_clip_distance_mesa = true;
1696 * Determine whether two tfeedback_decl objects refer to the same variable and
1697 * array index (if applicable).
1700 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1702 assert(x.is_varying() && y.is_varying());
1704 if (strcmp(x.var_name, y.var_name) != 0)
1706 if (x.is_subscripted != y.is_subscripted)
1708 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1715 * Assign a location for this tfeedback_decl object based on the location
1716 * assignment in output_var.
1718 * If an error occurs, the error is reported through linker_error() and false
1722 tfeedback_decl::assign_location(struct gl_context *ctx,
1723 struct gl_shader_program *prog,
1724 ir_variable *output_var)
1726 assert(this->is_varying());
1728 if (output_var->type->is_array()) {
1729 /* Array variable */
1730 const unsigned matrix_cols =
1731 output_var->type->fields.array->matrix_columns;
1732 unsigned actual_array_size = this->is_clip_distance_mesa ?
1733 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
1735 if (this->is_subscripted) {
1736 /* Check array bounds. */
1737 if (this->array_subscript >= actual_array_size) {
1738 linker_error(prog, "Transform feedback varying %s has index "
1739 "%i, but the array size is %u.",
1740 this->orig_name, this->array_subscript,
1744 if (this->is_clip_distance_mesa) {
1746 output_var->location + this->array_subscript / 4;
1749 output_var->location + this->array_subscript * matrix_cols;
1753 this->location = output_var->location;
1754 this->size = actual_array_size;
1756 this->vector_elements = output_var->type->fields.array->vector_elements;
1757 this->matrix_columns = matrix_cols;
1758 if (this->is_clip_distance_mesa)
1759 this->type = GL_FLOAT;
1761 this->type = output_var->type->fields.array->gl_type;
1763 /* Regular variable (scalar, vector, or matrix) */
1764 if (this->is_subscripted) {
1765 linker_error(prog, "Transform feedback varying %s requested, "
1766 "but %s is not an array.",
1767 this->orig_name, this->var_name);
1770 this->location = output_var->location;
1772 this->vector_elements = output_var->type->vector_elements;
1773 this->matrix_columns = output_var->type->matrix_columns;
1774 this->type = output_var->type->gl_type;
1777 /* From GL_EXT_transform_feedback:
1778 * A program will fail to link if:
1780 * * the total number of components to capture in any varying
1781 * variable in <varyings> is greater than the constant
1782 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1783 * buffer mode is SEPARATE_ATTRIBS_EXT;
1785 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1786 this->num_components() >
1787 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1788 linker_error(prog, "Transform feedback varying %s exceeds "
1789 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1799 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1802 if (!this->is_varying()) {
1806 if (!this->is_assigned()) {
1807 /* From GL_EXT_transform_feedback:
1808 * A program will fail to link if:
1810 * * any variable name specified in the <varyings> array is not
1811 * declared as an output in the geometry shader (if present) or
1812 * the vertex shader (if no geometry shader is present);
1814 linker_error(prog, "Transform feedback varying %s undeclared.",
1819 unsigned translated_size = this->size;
1820 if (this->is_clip_distance_mesa)
1821 translated_size = (translated_size + 3) / 4;
1823 *count += translated_size * this->matrix_columns;
1830 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1832 * If an error occurs, the error is reported through linker_error() and false
1836 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1837 struct gl_transform_feedback_info *info,
1838 unsigned buffer, const unsigned max_outputs) const
1840 assert(!this->next_buffer_separator);
1842 /* Handle gl_SkipComponents. */
1843 if (this->skip_components) {
1844 info->BufferStride[buffer] += this->skip_components;
1848 /* From GL_EXT_transform_feedback:
1849 * A program will fail to link if:
1851 * * the total number of components to capture is greater than
1852 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1853 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1855 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1856 info->BufferStride[buffer] + this->num_components() >
1857 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1858 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1859 "limit has been exceeded.");
1863 unsigned translated_size = this->size;
1864 if (this->is_clip_distance_mesa)
1865 translated_size = (translated_size + 3) / 4;
1866 unsigned components_so_far = 0;
1867 for (unsigned index = 0; index < translated_size; ++index) {
1868 for (unsigned v = 0; v < this->matrix_columns; ++v) {
1869 unsigned num_components = this->vector_elements;
1870 assert(info->NumOutputs < max_outputs);
1871 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1872 if (this->is_clip_distance_mesa) {
1873 if (this->is_subscripted) {
1875 info->Outputs[info->NumOutputs].ComponentOffset =
1876 this->array_subscript % 4;
1878 num_components = MIN2(4, this->size - components_so_far);
1881 info->Outputs[info->NumOutputs].OutputRegister =
1882 this->location + v + index * this->matrix_columns;
1883 info->Outputs[info->NumOutputs].NumComponents = num_components;
1884 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1885 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
1887 info->BufferStride[buffer] += num_components;
1888 components_so_far += num_components;
1891 assert(components_so_far == this->num_components());
1893 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
1894 info->Varyings[info->NumVarying].Type = this->type;
1895 info->Varyings[info->NumVarying].Size = this->size;
1903 * Parse all the transform feedback declarations that were passed to
1904 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1906 * If an error occurs, the error is reported through linker_error() and false
1910 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1911 const void *mem_ctx, unsigned num_names,
1912 char **varying_names, tfeedback_decl *decls)
1914 for (unsigned i = 0; i < num_names; ++i) {
1915 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1918 if (!decls[i].is_varying())
1921 /* From GL_EXT_transform_feedback:
1922 * A program will fail to link if:
1924 * * any two entries in the <varyings> array specify the same varying
1927 * We interpret this to mean "any two entries in the <varyings> array
1928 * specify the same varying variable and array index", since transform
1929 * feedback of arrays would be useless otherwise.
1931 for (unsigned j = 0; j < i; ++j) {
1932 if (!decls[j].is_varying())
1935 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1936 linker_error(prog, "Transform feedback varying %s specified "
1937 "more than once.", varying_names[i]);
1947 * Assign a location for a variable that is produced in one pipeline stage
1948 * (the "producer") and consumed in the next stage (the "consumer").
1950 * \param input_var is the input variable declaration in the consumer.
1952 * \param output_var is the output variable declaration in the producer.
1954 * \param input_index is the counter that keeps track of assigned input
1955 * locations in the consumer.
1957 * \param output_index is the counter that keeps track of assigned output
1958 * locations in the producer.
1960 * It is permissible for \c input_var to be NULL (this happens if a variable
1961 * is output by the producer and consumed by transform feedback, but not
1962 * consumed by the consumer).
1964 * If the variable has already been assigned a location, this function has no
1968 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1969 unsigned *input_index, unsigned *output_index)
1971 if (output_var->location != -1) {
1972 /* Location already assigned. */
1977 assert(input_var->location == -1);
1978 input_var->location = *input_index;
1981 output_var->location = *output_index;
1983 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1984 assert(!output_var->type->is_record());
1986 if (output_var->type->is_array()) {
1987 const unsigned slots = output_var->type->length
1988 * output_var->type->fields.array->matrix_columns;
1990 *output_index += slots;
1991 *input_index += slots;
1993 const unsigned slots = output_var->type->matrix_columns;
1995 *output_index += slots;
1996 *input_index += slots;
2002 * Is the given variable a varying variable to be counted against the
2003 * limit in ctx->Const.MaxVarying?
2004 * This includes variables such as texcoords, colors and generic
2005 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
2008 is_varying_var(GLenum shaderType, const ir_variable *var)
2010 /* Only fragment shaders will take a varying variable as an input */
2011 if (shaderType == GL_FRAGMENT_SHADER &&
2012 var->mode == ir_var_in &&
2013 var->explicit_location) {
2014 switch (var->location) {
2015 case FRAG_ATTRIB_WPOS:
2016 case FRAG_ATTRIB_FACE:
2017 case FRAG_ATTRIB_PNTC:
2028 * Assign locations for all variables that are produced in one pipeline stage
2029 * (the "producer") and consumed in the next stage (the "consumer").
2031 * Variables produced by the producer may also be consumed by transform
2034 * \param num_tfeedback_decls is the number of declarations indicating
2035 * variables that may be consumed by transform feedback.
2037 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
2038 * representing the result of parsing the strings passed to
2039 * glTransformFeedbackVaryings(). assign_location() will be called for
2040 * each of these objects that matches one of the outputs of the
2043 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
2044 * be NULL. In this case, varying locations are assigned solely based on the
2045 * requirements of transform feedback.
2048 assign_varying_locations(struct gl_context *ctx,
2049 struct gl_shader_program *prog,
2050 gl_shader *producer, gl_shader *consumer,
2051 unsigned num_tfeedback_decls,
2052 tfeedback_decl *tfeedback_decls)
2054 /* FINISHME: Set dynamically when geometry shader support is added. */
2055 unsigned output_index = VERT_RESULT_VAR0;
2056 unsigned input_index = FRAG_ATTRIB_VAR0;
2058 /* Operate in a total of three passes.
2060 * 1. Assign locations for any matching inputs and outputs.
2062 * 2. Mark output variables in the producer that do not have locations as
2063 * not being outputs. This lets the optimizer eliminate them.
2065 * 3. Mark input variables in the consumer that do not have locations as
2066 * not being inputs. This lets the optimizer eliminate them.
2069 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
2071 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
2073 foreach_list(node, producer->ir) {
2074 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
2076 if ((output_var == NULL) || (output_var->mode != ir_var_out))
2079 ir_variable *input_var =
2080 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
2082 if (input_var && input_var->mode != ir_var_in)
2086 assign_varying_location(input_var, output_var, &input_index,
2090 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2091 if (!tfeedback_decls[i].is_varying())
2094 if (!tfeedback_decls[i].is_assigned() &&
2095 tfeedback_decls[i].matches_var(output_var)) {
2096 if (output_var->location == -1) {
2097 assign_varying_location(input_var, output_var, &input_index,
2100 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
2106 unsigned varying_vectors = 0;
2109 foreach_list(node, consumer->ir) {
2110 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2112 if ((var == NULL) || (var->mode != ir_var_in))
2115 if (var->location == -1) {
2116 if (prog->Version <= 120) {
2117 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
2119 * Only those varying variables used (i.e. read) in
2120 * the fragment shader executable must be written to
2121 * by the vertex shader executable; declaring
2122 * superfluous varying variables in a vertex shader is
2125 * We interpret this text as meaning that the VS must
2126 * write the variable for the FS to read it. See
2127 * "glsl1-varying read but not written" in piglit.
2130 linker_error(prog, "fragment shader varying %s not written "
2131 "by vertex shader\n.", var->name);
2134 /* An 'in' variable is only really a shader input if its
2135 * value is written by the previous stage.
2137 var->mode = ir_var_auto;
2138 } else if (is_varying_var(consumer->Type, var)) {
2139 /* The packing rules are used for vertex shader inputs are also
2140 * used for fragment shader inputs.
2142 varying_vectors += count_attribute_slots(var->type);
2147 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
2148 if (varying_vectors > ctx->Const.MaxVarying) {
2149 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
2150 linker_warning(prog, "shader uses too many varying vectors "
2151 "(%u > %u), but the driver will try to optimize "
2152 "them out; this is non-portable out-of-spec "
2154 varying_vectors, ctx->Const.MaxVarying);
2156 linker_error(prog, "shader uses too many varying vectors "
2158 varying_vectors, ctx->Const.MaxVarying);
2163 const unsigned float_components = varying_vectors * 4;
2164 if (float_components > ctx->Const.MaxVarying * 4) {
2165 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
2166 linker_warning(prog, "shader uses too many varying components "
2167 "(%u > %u), but the driver will try to optimize "
2168 "them out; this is non-portable out-of-spec "
2170 float_components, ctx->Const.MaxVarying * 4);
2172 linker_error(prog, "shader uses too many varying components "
2174 float_components, ctx->Const.MaxVarying * 4);
2185 * Store transform feedback location assignments into
2186 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2188 * If an error occurs, the error is reported through linker_error() and false
2192 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2193 unsigned num_tfeedback_decls,
2194 tfeedback_decl *tfeedback_decls)
2196 bool separate_attribs_mode =
2197 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
2199 ralloc_free(prog->LinkedTransformFeedback.Varyings);
2200 ralloc_free(prog->LinkedTransformFeedback.Outputs);
2202 memset(&prog->LinkedTransformFeedback, 0,
2203 sizeof(prog->LinkedTransformFeedback));
2205 prog->LinkedTransformFeedback.Varyings =
2207 struct gl_transform_feedback_varying_info,
2208 num_tfeedback_decls);
2210 unsigned num_outputs = 0;
2211 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2212 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2215 prog->LinkedTransformFeedback.Outputs =
2217 struct gl_transform_feedback_output,
2220 unsigned num_buffers = 0;
2222 if (separate_attribs_mode) {
2223 /* GL_SEPARATE_ATTRIBS */
2224 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2225 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
2226 num_buffers, num_outputs))
2233 /* GL_INVERLEAVED_ATTRIBS */
2234 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2235 if (tfeedback_decls[i].is_next_buffer_separator()) {
2240 if (!tfeedback_decls[i].store(ctx, prog,
2241 &prog->LinkedTransformFeedback,
2242 num_buffers, num_outputs))
2248 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2250 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
2255 * Store the gl_FragDepth layout in the gl_shader_program struct.
2258 store_fragdepth_layout(struct gl_shader_program *prog)
2260 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2264 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2266 /* We don't look up the gl_FragDepth symbol directly because if
2267 * gl_FragDepth is not used in the shader, it's removed from the IR.
2268 * However, the symbol won't be removed from the symbol table.
2270 * We're only interested in the cases where the variable is NOT removed
2273 foreach_list(node, ir) {
2274 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2276 if (var == NULL || var->mode != ir_var_out) {
2280 if (strcmp(var->name, "gl_FragDepth") == 0) {
2281 switch (var->depth_layout) {
2282 case ir_depth_layout_none:
2283 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2285 case ir_depth_layout_any:
2286 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2288 case ir_depth_layout_greater:
2289 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2291 case ir_depth_layout_less:
2292 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2294 case ir_depth_layout_unchanged:
2295 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2306 * Validate the resources used by a program versus the implementation limits
2309 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2311 static const char *const shader_names[MESA_SHADER_TYPES] = {
2312 "vertex", "fragment", "geometry"
2315 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2316 ctx->Const.MaxVertexTextureImageUnits,
2317 ctx->Const.MaxTextureImageUnits,
2318 ctx->Const.MaxGeometryTextureImageUnits
2321 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2322 ctx->Const.VertexProgram.MaxUniformComponents,
2323 ctx->Const.FragmentProgram.MaxUniformComponents,
2324 0 /* FINISHME: Geometry shaders. */
2327 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2328 struct gl_shader *sh = prog->_LinkedShaders[i];
2333 if (sh->num_samplers > max_samplers[i]) {
2334 linker_error(prog, "Too many %s shader texture samplers",
2338 if (sh->num_uniform_components > max_uniform_components[i]) {
2339 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2340 linker_warning(prog, "Too many %s shader uniform components, "
2341 "but the driver will try to optimize them out; "
2342 "this is non-portable out-of-spec behavior\n",
2345 linker_error(prog, "Too many %s shader uniform components",
2351 return prog->LinkStatus;
2355 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2357 tfeedback_decl *tfeedback_decls = NULL;
2358 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2360 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2362 prog->LinkStatus = false;
2363 prog->Validated = false;
2364 prog->_Used = false;
2366 ralloc_free(prog->InfoLog);
2367 prog->InfoLog = ralloc_strdup(NULL, "");
2369 ralloc_free(prog->UniformBlocks);
2370 prog->UniformBlocks = NULL;
2371 prog->NumUniformBlocks = 0;
2372 for (int i = 0; i < MESA_SHADER_TYPES; i++) {
2373 ralloc_free(prog->UniformBlockStageIndex[i]);
2374 prog->UniformBlockStageIndex[i] = NULL;
2377 /* Separate the shaders into groups based on their type.
2379 struct gl_shader **vert_shader_list;
2380 unsigned num_vert_shaders = 0;
2381 struct gl_shader **frag_shader_list;
2382 unsigned num_frag_shaders = 0;
2384 vert_shader_list = (struct gl_shader **)
2385 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
2386 frag_shader_list = &vert_shader_list[prog->NumShaders];
2388 unsigned min_version = UINT_MAX;
2389 unsigned max_version = 0;
2390 for (unsigned i = 0; i < prog->NumShaders; i++) {
2391 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2392 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2394 switch (prog->Shaders[i]->Type) {
2395 case GL_VERTEX_SHADER:
2396 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2399 case GL_FRAGMENT_SHADER:
2400 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2403 case GL_GEOMETRY_SHADER:
2404 /* FINISHME: Support geometry shaders. */
2405 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2410 /* Previous to GLSL version 1.30, different compilation units could mix and
2411 * match shading language versions. With GLSL 1.30 and later, the versions
2412 * of all shaders must match.
2414 assert(min_version >= 100);
2415 assert(max_version <= 140);
2416 if ((max_version >= 130 || min_version == 100)
2417 && min_version != max_version) {
2418 linker_error(prog, "all shaders must use same shading "
2419 "language version\n");
2423 prog->Version = max_version;
2425 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2426 if (prog->_LinkedShaders[i] != NULL)
2427 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2429 prog->_LinkedShaders[i] = NULL;
2432 /* Link all shaders for a particular stage and validate the result.
2434 if (num_vert_shaders > 0) {
2435 gl_shader *const sh =
2436 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2442 if (!validate_vertex_shader_executable(prog, sh))
2445 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2449 if (num_frag_shaders > 0) {
2450 gl_shader *const sh =
2451 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2457 if (!validate_fragment_shader_executable(prog, sh))
2460 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2464 /* Here begins the inter-stage linking phase. Some initial validation is
2465 * performed, then locations are assigned for uniforms, attributes, and
2468 if (cross_validate_uniforms(prog)) {
2471 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2472 if (prog->_LinkedShaders[prev] != NULL)
2476 /* Validate the inputs of each stage with the output of the preceding
2479 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2480 if (prog->_LinkedShaders[i] == NULL)
2483 if (!cross_validate_outputs_to_inputs(prog,
2484 prog->_LinkedShaders[prev],
2485 prog->_LinkedShaders[i]))
2491 prog->LinkStatus = true;
2494 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2495 * it before optimization because we want most of the checks to get
2496 * dropped thanks to constant propagation.
2498 if (max_version >= 130) {
2499 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2501 lower_discard_flow(sh->ir);
2505 if (!interstage_cross_validate_uniform_blocks(prog))
2508 /* Do common optimization before assigning storage for attributes,
2509 * uniforms, and varyings. Later optimization could possibly make
2510 * some of that unused.
2512 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2513 if (prog->_LinkedShaders[i] == NULL)
2516 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2517 if (!prog->LinkStatus)
2520 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2521 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2523 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2525 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
2529 /* FINISHME: The value of the max_attribute_index parameter is
2530 * FINISHME: implementation dependent based on the value of
2531 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2532 * FINISHME: at least 16, so hardcode 16 for now.
2534 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2538 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2543 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2544 if (prog->_LinkedShaders[prev] != NULL)
2548 if (num_tfeedback_decls != 0) {
2549 /* From GL_EXT_transform_feedback:
2550 * A program will fail to link if:
2552 * * the <count> specified by TransformFeedbackVaryingsEXT is
2553 * non-zero, but the program object has no vertex or geometry
2556 if (prev >= MESA_SHADER_FRAGMENT) {
2557 linker_error(prog, "Transform feedback varyings specified, but "
2558 "no vertex or geometry shader is present.");
2562 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2563 prog->TransformFeedback.NumVarying);
2564 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2565 prog->TransformFeedback.VaryingNames,
2570 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2571 if (prog->_LinkedShaders[i] == NULL)
2574 if (!assign_varying_locations(
2575 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2576 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2583 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2584 /* There was no fragment shader, but we still have to assign varying
2585 * locations for use by transform feedback.
2587 if (!assign_varying_locations(
2588 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2593 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2596 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2597 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2600 /* Eliminate code that is now dead due to unused vertex outputs being
2603 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2607 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2608 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2610 demote_shader_inputs_and_outputs(sh, ir_var_in);
2611 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2612 demote_shader_inputs_and_outputs(sh, ir_var_out);
2614 /* Eliminate code that is now dead due to unused geometry outputs being
2617 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2621 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2622 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2624 demote_shader_inputs_and_outputs(sh, ir_var_in);
2626 /* Eliminate code that is now dead due to unused fragment inputs being
2627 * demoted. This shouldn't actually do anything other than remove
2628 * declarations of the (now unused) global variables.
2630 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2634 update_array_sizes(prog);
2635 link_assign_uniform_locations(prog);
2636 store_fragdepth_layout(prog);
2638 if (!check_resources(ctx, prog))
2641 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2642 * present in a linked program. By checking for use of shading language
2643 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2645 if (!prog->InternalSeparateShader &&
2646 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
2647 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2648 linker_error(prog, "program lacks a vertex shader\n");
2649 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2650 linker_error(prog, "program lacks a fragment shader\n");
2654 /* FINISHME: Assign fragment shader output locations. */
2657 free(vert_shader_list);
2659 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2660 if (prog->_LinkedShaders[i] == NULL)
2663 /* Retain any live IR, but trash the rest. */
2664 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2666 /* The symbol table in the linked shaders may contain references to
2667 * variables that were removed (e.g., unused uniforms). Since it may
2668 * contain junk, there is no possible valid use. Delete it and set the
2671 delete prog->_LinkedShaders[i]->symbols;
2672 prog->_LinkedShaders[i]->symbols = NULL;
2675 ralloc_free(mem_ctx);