glsl/linker: Make separate ir_variable field to mean "unmatched".
[mesa.git] / src / glsl / linker.cpp
1 /*
2 * Copyright © 2010 Intel Corporation
3 *
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:
10 *
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
13 * Software.
14 *
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.
22 */
23
24 /**
25 * \file linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
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
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
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.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
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
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
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.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
66
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
69 #include "ir.h"
70 #include "program.h"
71 #include "program/hash_table.h"
72 #include "linker.h"
73 #include "ir_optimization.h"
74
75 extern "C" {
76 #include "main/shaderobj.h"
77 }
78
79 /**
80 * Visitor that determines whether or not a variable is ever written.
81 */
82 class find_assignment_visitor : public ir_hierarchical_visitor {
83 public:
84 find_assignment_visitor(const char *name)
85 : name(name), found(false)
86 {
87 /* empty */
88 }
89
90 virtual ir_visitor_status visit_enter(ir_assignment *ir)
91 {
92 ir_variable *const var = ir->lhs->variable_referenced();
93
94 if (strcmp(name, var->name) == 0) {
95 found = true;
96 return visit_stop;
97 }
98
99 return visit_continue_with_parent;
100 }
101
102 virtual ir_visitor_status visit_enter(ir_call *ir)
103 {
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();
108
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) {
113 found = true;
114 return visit_stop;
115 }
116 }
117 sig_iter.next();
118 }
119
120 if (ir->return_deref != NULL) {
121 ir_variable *const var = ir->return_deref->variable_referenced();
122
123 if (strcmp(name, var->name) == 0) {
124 found = true;
125 return visit_stop;
126 }
127 }
128
129 return visit_continue_with_parent;
130 }
131
132 bool variable_found()
133 {
134 return found;
135 }
136
137 private:
138 const char *name; /**< Find writes to a variable with this name. */
139 bool found; /**< Was a write to the variable found? */
140 };
141
142
143 /**
144 * Visitor that determines whether or not a variable is ever read.
145 */
146 class find_deref_visitor : public ir_hierarchical_visitor {
147 public:
148 find_deref_visitor(const char *name)
149 : name(name), found(false)
150 {
151 /* empty */
152 }
153
154 virtual ir_visitor_status visit(ir_dereference_variable *ir)
155 {
156 if (strcmp(this->name, ir->var->name) == 0) {
157 this->found = true;
158 return visit_stop;
159 }
160
161 return visit_continue;
162 }
163
164 bool variable_found() const
165 {
166 return this->found;
167 }
168
169 private:
170 const char *name; /**< Find writes to a variable with this name. */
171 bool found; /**< Was a write to the variable found? */
172 };
173
174
175 void
176 linker_error(gl_shader_program *prog, const char *fmt, ...)
177 {
178 va_list ap;
179
180 ralloc_strcat(&prog->InfoLog, "error: ");
181 va_start(ap, fmt);
182 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
183 va_end(ap);
184
185 prog->LinkStatus = false;
186 }
187
188
189 void
190 linker_warning(gl_shader_program *prog, const char *fmt, ...)
191 {
192 va_list ap;
193
194 ralloc_strcat(&prog->InfoLog, "error: ");
195 va_start(ap, fmt);
196 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
197 va_end(ap);
198
199 }
200
201
202 void
203 link_invalidate_variable_locations(gl_shader *sh, int input_base,
204 int output_base)
205 {
206 foreach_list(node, sh->ir) {
207 ir_variable *const var = ((ir_instruction *) node)->as_variable();
208
209 if (var == NULL)
210 continue;
211
212 int base;
213 switch (var->mode) {
214 case ir_var_in:
215 base = input_base;
216 break;
217 case ir_var_out:
218 base = output_base;
219 break;
220 default:
221 continue;
222 }
223
224 /* Only assign locations for generic attributes / varyings / etc.
225 */
226 if ((var->location >= base) && !var->explicit_location)
227 var->location = -1;
228
229 if ((var->location == -1) && !var->explicit_location)
230 var->is_unmatched_generic_inout = 1;
231 else
232 var->is_unmatched_generic_inout = 0;
233 }
234 }
235
236
237 /**
238 * Determine the number of attribute slots required for a particular type
239 *
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.
243 */
244 unsigned
245 count_attribute_slots(const glsl_type *t)
246 {
247 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
248 *
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."
255 *
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.
260 */
261
262 if (t->is_array())
263 return t->array_size() * count_attribute_slots(t->element_type());
264
265 if (t->is_matrix())
266 return t->matrix_columns;
267
268 return 1;
269 }
270
271
272 /**
273 * Verify that a vertex shader executable meets all semantic requirements.
274 *
275 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
276 * as a side effect.
277 *
278 * \param shader Vertex shader executable to be verified
279 */
280 bool
281 validate_vertex_shader_executable(struct gl_shader_program *prog,
282 struct gl_shader *shader)
283 {
284 if (shader == NULL)
285 return true;
286
287 /* From the GLSL 1.10 spec, page 48:
288 *
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."
297 *
298 * while in GLSL 1.40 this text is changed to:
299 *
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."
309 *
310 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
311 * not an error.
312 */
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");
318 return false;
319 }
320 }
321
322 prog->Vert.ClipDistanceArraySize = 0;
323
324 if (!prog->IsES && prog->Version >= 130) {
325 /* From section 7.1 (Vertex Shader Special Variables) of the
326 * GLSL 1.30 spec:
327 *
328 * "It is an error for a shader to statically write both
329 * gl_ClipVertex and gl_ClipDistance."
330 *
331 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
332 * gl_ClipVertex nor gl_ClipDistance.
333 */
334 find_assignment_visitor clip_vertex("gl_ClipVertex");
335 find_assignment_visitor clip_distance("gl_ClipDistance");
336
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");
342 return false;
343 }
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;
349 }
350
351 return true;
352 }
353
354
355 /**
356 * Verify that a fragment shader executable meets all semantic requirements
357 *
358 * \param shader Fragment shader executable to be verified
359 */
360 bool
361 validate_fragment_shader_executable(struct gl_shader_program *prog,
362 struct gl_shader *shader)
363 {
364 if (shader == NULL)
365 return true;
366
367 find_assignment_visitor frag_color("gl_FragColor");
368 find_assignment_visitor frag_data("gl_FragData");
369
370 frag_color.run(shader->ir);
371 frag_data.run(shader->ir);
372
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");
376 return false;
377 }
378
379 return true;
380 }
381
382
383 /**
384 * Generate a string describing the mode of a variable
385 */
386 static const char *
387 mode_string(const ir_variable *var)
388 {
389 switch (var->mode) {
390 case ir_var_auto:
391 return (var->read_only) ? "global constant" : "global variable";
392
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";
397
398 case ir_var_const_in:
399 case ir_var_temporary:
400 default:
401 assert(!"Should not get here.");
402 return "invalid variable";
403 }
404 }
405
406
407 /**
408 * Perform validation of global variables used across multiple shaders
409 */
410 bool
411 cross_validate_globals(struct gl_shader_program *prog,
412 struct gl_shader **shader_list,
413 unsigned num_shaders,
414 bool uniforms_only)
415 {
416 /* Examine all of the uniforms in all of the shaders and cross validate
417 * them.
418 */
419 glsl_symbol_table variables;
420 for (unsigned i = 0; i < num_shaders; i++) {
421 if (shader_list[i] == NULL)
422 continue;
423
424 foreach_list(node, shader_list[i]->ir) {
425 ir_variable *const var = ((ir_instruction *) node)->as_variable();
426
427 if (var == NULL)
428 continue;
429
430 if (uniforms_only && (var->mode != ir_var_uniform))
431 continue;
432
433 /* Don't cross validate temporaries that are at global scope. These
434 * will eventually get pulled into the shaders 'main'.
435 */
436 if (var->mode == ir_var_temporary)
437 continue;
438
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.
442 */
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.
450 */
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;
458 }
459 } else {
460 linker_error(prog, "%s `%s' declared as type "
461 "`%s' and type `%s'\n",
462 mode_string(var),
463 var->name, var->type->name,
464 existing->type->name);
465 return false;
466 }
467 }
468
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);
475 return false;
476 }
477
478 existing->location = var->location;
479 existing->explicit_location = true;
480 }
481
482 /* Validate layout qualifiers for gl_FragDepth.
483 *
484 * From the AMD/ARB_conservative_depth specs:
485 *
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
491 * of qualifiers."
492 */
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;
497
498 if (layout_declared && layout_differs) {
499 linker_error(prog,
500 "All redeclarations of gl_FragDepth in all "
501 "fragment shaders in a single program must have "
502 "the same set of qualifiers.");
503 }
504
505 if (var->used && layout_differs) {
506 linker_error(prog,
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 "
511 "gl_FragDepth");
512 }
513 }
514
515 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
516 *
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.)"
522 *
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.
529 */
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);
536 return false;
537 }
538 } else {
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.
542 */
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.
550 */
551 existing->constant_initializer =
552 var->constant_initializer->clone(ralloc_parent(existing),
553 NULL);
554 }
555 }
556
557 if (var->has_initializer) {
558 if (existing->has_initializer
559 && (var->constant_initializer == NULL
560 || existing->constant_initializer == NULL)) {
561 linker_error(prog,
562 "shared global variable `%s' has multiple "
563 "non-constant initializers.\n",
564 var->name);
565 return false;
566 }
567
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.
572 */
573 existing->has_initializer = true;
574 }
575
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);
580 return false;
581 }
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);
586 return false;
587 }
588 } else
589 variables.add_variable(var);
590 }
591 }
592
593 return true;
594 }
595
596
597 /**
598 * Perform validation of uniforms used across multiple shader stages
599 */
600 bool
601 cross_validate_uniforms(struct gl_shader_program *prog)
602 {
603 return cross_validate_globals(prog, prog->_LinkedShaders,
604 MESA_SHADER_TYPES, true);
605 }
606
607 /**
608 * Accumulates the array of prog->UniformBlocks and checks that all
609 * definitons of blocks agree on their contents.
610 */
611 static bool
612 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
613 {
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;
618 }
619
620 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
621 struct gl_shader *sh = prog->_LinkedShaders[i];
622
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;
627
628 if (sh == NULL)
629 continue;
630
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]);
636
637 if (index == -1) {
638 linker_error(prog, "uniform block `%s' has mismatching definitions",
639 sh->UniformBlocks[j].Name);
640 return false;
641 }
642
643 prog->UniformBlockStageIndex[i][index] = j;
644 }
645 }
646
647 return true;
648 }
649
650 /**
651 * Validate that outputs from one stage match inputs of another
652 */
653 bool
654 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
655 gl_shader *producer, gl_shader *consumer)
656 {
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";
661
662 /* Find all shader outputs in the "producer" stage.
663 */
664 foreach_list(node, producer->ir) {
665 ir_variable *const var = ((ir_instruction *) node)->as_variable();
666
667 /* FINISHME: For geometry shaders, this should also look for inout
668 * FINISHME: variables.
669 */
670 if ((var == NULL) || (var->mode != ir_var_out))
671 continue;
672
673 parameters.add_variable(var);
674 }
675
676
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
679 * qualifiers.
680 */
681 foreach_list(node, consumer->ir) {
682 ir_variable *const input = ((ir_instruction *) node)->as_variable();
683
684 /* FINISHME: For geometry shaders, this should also look for inout
685 * FINISHME: variables.
686 */
687 if ((input == NULL) || (input->mode != ir_var_in))
688 continue;
689
690 ir_variable *const output = parameters.get_variable(input->name);
691 if (output != NULL) {
692 /* Check that the types match between stages.
693 */
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
701 * rely on it.
702 *
703 * Neither declaration needs to be modified here because the array
704 * sizes are fixed later when update_array_sizes is called.
705 *
706 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
707 *
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."
712 */
713 if (!output->type->is_array()
714 || (strncmp("gl_", output->name, 3) != 0)) {
715 linker_error(prog,
716 "%s shader output `%s' declared as type `%s', "
717 "but %s shader input declared as type `%s'\n",
718 producer_stage, output->name,
719 output->type->name,
720 consumer_stage, input->type->name);
721 return false;
722 }
723 }
724
725 /* Check that all of the qualifiers match between stages.
726 */
727 if (input->centroid != output->centroid) {
728 linker_error(prog,
729 "%s shader output `%s' %s centroid qualifier, "
730 "but %s shader input %s centroid qualifier\n",
731 producer_stage,
732 output->name,
733 (output->centroid) ? "has" : "lacks",
734 consumer_stage,
735 (input->centroid) ? "has" : "lacks");
736 return false;
737 }
738
739 if (input->invariant != output->invariant) {
740 linker_error(prog,
741 "%s shader output `%s' %s invariant qualifier, "
742 "but %s shader input %s invariant qualifier\n",
743 producer_stage,
744 output->name,
745 (output->invariant) ? "has" : "lacks",
746 consumer_stage,
747 (input->invariant) ? "has" : "lacks");
748 return false;
749 }
750
751 if (input->interpolation != output->interpolation) {
752 linker_error(prog,
753 "%s shader output `%s' specifies %s "
754 "interpolation qualifier, "
755 "but %s shader input specifies %s "
756 "interpolation qualifier\n",
757 producer_stage,
758 output->name,
759 output->interpolation_string(),
760 consumer_stage,
761 input->interpolation_string());
762 return false;
763 }
764 }
765 }
766
767 return true;
768 }
769
770
771 /**
772 * Populates a shaders symbol table with all global declarations
773 */
774 static void
775 populate_symbol_table(gl_shader *sh)
776 {
777 sh->symbols = new(sh) glsl_symbol_table;
778
779 foreach_list(node, sh->ir) {
780 ir_instruction *const inst = (ir_instruction *) node;
781 ir_variable *var;
782 ir_function *func;
783
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);
788 }
789 }
790 }
791
792
793 /**
794 * Remap variables referenced in an instruction tree
795 *
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
800 * shader.
801 *
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.
805 *
806 * \param inst IR tree that is to be processed.
807 * \param symbols Symbol table containing global scope symbols in the
808 * linked shader.
809 * \param instructions Instruction stream where new variable declarations
810 * should be added.
811 */
812 void
813 remap_variables(ir_instruction *inst, struct gl_shader *target,
814 hash_table *temps)
815 {
816 class remap_visitor : public ir_hierarchical_visitor {
817 public:
818 remap_visitor(struct gl_shader *target,
819 hash_table *temps)
820 {
821 this->target = target;
822 this->symbols = target->symbols;
823 this->instructions = target->ir;
824 this->temps = temps;
825 }
826
827 virtual ir_visitor_status visit(ir_dereference_variable *ir)
828 {
829 if (ir->var->mode == ir_var_temporary) {
830 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
831
832 assert(var != NULL);
833 ir->var = var;
834 return visit_continue;
835 }
836
837 ir_variable *const existing =
838 this->symbols->get_variable(ir->var->name);
839 if (existing != NULL)
840 ir->var = existing;
841 else {
842 ir_variable *copy = ir->var->clone(this->target, NULL);
843
844 this->symbols->add_variable(copy);
845 this->instructions->push_head(copy);
846 ir->var = copy;
847 }
848
849 return visit_continue;
850 }
851
852 private:
853 struct gl_shader *target;
854 glsl_symbol_table *symbols;
855 exec_list *instructions;
856 hash_table *temps;
857 };
858
859 remap_visitor v(target, temps);
860
861 inst->accept(&v);
862 }
863
864
865 /**
866 * Move non-declarations from one instruction stream to another
867 *
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.
873 *
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.
880 *
881 * \return
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
884 * function.
885 */
886 exec_node *
887 move_non_declarations(exec_list *instructions, exec_node *last,
888 bool make_copies, gl_shader *target)
889 {
890 hash_table *temps = NULL;
891
892 if (make_copies)
893 temps = hash_table_ctor(0, hash_table_pointer_hash,
894 hash_table_pointer_compare);
895
896 foreach_list_safe(node, instructions) {
897 ir_instruction *inst = (ir_instruction *) node;
898
899 if (inst->as_function())
900 continue;
901
902 ir_variable *var = inst->as_variable();
903 if ((var != NULL) && (var->mode != ir_var_temporary))
904 continue;
905
906 assert(inst->as_assignment()
907 || inst->as_call()
908 || inst->as_if() /* for initializers with the ?: operator */
909 || ((var != NULL) && (var->mode == ir_var_temporary)));
910
911 if (make_copies) {
912 inst = inst->clone(target, NULL);
913
914 if (var != NULL)
915 hash_table_insert(temps, inst, var);
916 else
917 remap_variables(inst, target, temps);
918 } else {
919 inst->remove();
920 }
921
922 last->insert_after(inst);
923 last = inst;
924 }
925
926 if (make_copies)
927 hash_table_dtor(temps);
928
929 return last;
930 }
931
932 /**
933 * Get the function signature for main from a shader
934 */
935 static ir_function_signature *
936 get_main_function_signature(gl_shader *sh)
937 {
938 ir_function *const f = sh->symbols->get_function("main");
939 if (f != NULL) {
940 exec_list void_parameters;
941
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.
945 *
946 * We don't have to check for multiple definitions of main (in multiple
947 * shaders) because that would have already been caught above.
948 */
949 ir_function_signature *sig = f->matching_signature(&void_parameters);
950 if ((sig != NULL) && sig->is_defined) {
951 return sig;
952 }
953 }
954
955 return NULL;
956 }
957
958
959 /**
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
962 * gcc.
963 */
964 class array_sizing_visitor : public ir_hierarchical_visitor {
965 public:
966 virtual ir_visitor_status visit(ir_variable *var)
967 {
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);
973 var->type = type;
974 }
975 return visit_continue;
976 }
977 };
978
979 /**
980 * Combine a group of shaders for a single stage to generate a linked shader
981 *
982 * \note
983 * If this function is supplied a single shader, it is cloned, and the new
984 * shader is returned.
985 */
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)
992 {
993 struct gl_uniform_block *uniform_blocks = NULL;
994 unsigned num_uniform_blocks = 0;
995
996 /* Check that global variables defined in multiple shaders are consistent.
997 */
998 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
999 return NULL;
1000
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];
1004
1005 for (unsigned j = 0; j < shader_list[i]->NumUniformBlocks; j++) {
1006 link_assign_uniform_block_offsets(shader_list[i]);
1007
1008 int index = link_cross_validate_uniform_block(mem_ctx,
1009 &uniform_blocks,
1010 &num_uniform_blocks,
1011 &sh->UniformBlocks[j]);
1012 if (index == -1) {
1013 linker_error(prog, "uniform block `%s' has mismatching definitions",
1014 sh->UniformBlocks[j].Name);
1015 return NULL;
1016 }
1017 }
1018 }
1019
1020 /* Check that there is only a single definition of each function signature
1021 * across all shaders.
1022 */
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();
1026
1027 if (f == NULL)
1028 continue;
1029
1030 for (unsigned j = i + 1; j < num_shaders; j++) {
1031 ir_function *const other =
1032 shader_list[j]->symbols->get_function(f->name);
1033
1034 /* If the other shader has no function (and therefore no function
1035 * signatures) with the same name, skip to the next shader.
1036 */
1037 if (other == NULL)
1038 continue;
1039
1040 foreach_iter (exec_list_iterator, iter, *f) {
1041 ir_function_signature *sig =
1042 (ir_function_signature *) iter.get();
1043
1044 if (!sig->is_defined || sig->is_builtin)
1045 continue;
1046
1047 ir_function_signature *other_sig =
1048 other->exact_matching_signature(& sig->parameters);
1049
1050 if ((other_sig != NULL) && other_sig->is_defined
1051 && !other_sig->is_builtin) {
1052 linker_error(prog, "function `%s' is multiply defined",
1053 f->name);
1054 return NULL;
1055 }
1056 }
1057 }
1058 }
1059 }
1060
1061 /* Find the shader that defines main, and make a clone of it.
1062 *
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.
1067 */
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];
1072 break;
1073 }
1074 }
1075
1076 if (main == NULL) {
1077 linker_error(prog, "%s shader lacks `main'\n",
1078 (shader_list[0]->Type == GL_VERTEX_SHADER)
1079 ? "vertex" : "fragment");
1080 return NULL;
1081 }
1082
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);
1086
1087 linked->UniformBlocks = uniform_blocks;
1088 linked->NumUniformBlocks = num_uniform_blocks;
1089 ralloc_steal(linked, linked->UniformBlocks);
1090
1091 populate_symbol_table(linked);
1092
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).
1095 */
1096 ir_function_signature *const main_sig = get_main_function_signature(linked);
1097
1098 /* Move any instructions other than variable declarations or function
1099 * declarations into main.
1100 */
1101 exec_node *insertion_point =
1102 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1103 linked);
1104
1105 for (unsigned i = 0; i < num_shaders; i++) {
1106 if (shader_list[i] == main)
1107 continue;
1108
1109 insertion_point = move_non_declarations(shader_list[i]->ir,
1110 insertion_point, true, linked);
1111 }
1112
1113 /* Resolve initializers for global variables in the linked shader.
1114 */
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;
1118
1119 gl_shader **linking_shaders =
1120 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1121
1122 memcpy(linking_shaders, shader_list,
1123 sizeof(linking_shaders[0]) * num_shaders);
1124
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;
1130 }
1131
1132 assert(idx == num_linking_shaders);
1133
1134 if (!link_function_calls(prog, linked, linking_shaders,
1135 num_linking_shaders)) {
1136 ctx->Driver.DeleteShader(ctx, linked);
1137 linked = NULL;
1138 }
1139
1140 free(linking_shaders);
1141
1142 #ifdef DEBUG
1143 /* At this point linked should contain all of the linked IR, so
1144 * validate it to make sure nothing went wrong.
1145 */
1146 if (linked)
1147 validate_ir_tree(linked->ir);
1148 #endif
1149
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.
1153 */
1154 if (linked != NULL) {
1155 array_sizing_visitor v;
1156
1157 v.run(linked->ir);
1158 }
1159
1160 return linked;
1161 }
1162
1163 /**
1164 * Update the sizes of linked shader uniform arrays to the maximum
1165 * array index used.
1166 *
1167 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1168 *
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.
1176
1177 */
1178 static void
1179 update_array_sizes(struct gl_shader_program *prog)
1180 {
1181 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1182 if (prog->_LinkedShaders[i] == NULL)
1183 continue;
1184
1185 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1186 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1187
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())
1192 continue;
1193
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.
1197 */
1198 if (var->uniform_block != -1)
1199 continue;
1200
1201 unsigned int size = var->max_array_access;
1202 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1203 if (prog->_LinkedShaders[j] == NULL)
1204 continue;
1205
1206 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1207 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1208 if (!other_var)
1209 continue;
1210
1211 if (strcmp(var->name, other_var->name) == 0 &&
1212 other_var->max_array_access > size) {
1213 size = other_var->max_array_access;
1214 }
1215 }
1216 }
1217
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.
1226 */
1227 if (var->num_state_slots > 0) {
1228 var->num_state_slots = (size + 1)
1229 * (var->num_state_slots / var->type->length);
1230 }
1231
1232 var->type = glsl_type::get_array_instance(var->type->fields.array,
1233 size + 1);
1234 /* FINISHME: We should update the types of array
1235 * dereferences of this variable now.
1236 */
1237 }
1238 }
1239 }
1240 }
1241
1242 /**
1243 * Find a contiguous set of available bits in a bitmask.
1244 *
1245 * \param used_mask Bits representing used (1) and unused (0) locations
1246 * \param needed_count Number of contiguous bits needed.
1247 *
1248 * \return
1249 * Base location of the available bits on success or -1 on failure.
1250 */
1251 int
1252 find_available_slots(unsigned used_mask, unsigned needed_count)
1253 {
1254 unsigned needed_mask = (1 << needed_count) - 1;
1255 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1256
1257 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1258 * cannot optimize possibly infinite loops" for the loop below.
1259 */
1260 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1261 return -1;
1262
1263 for (int i = 0; i <= max_bit_to_test; i++) {
1264 if ((needed_mask & ~used_mask) == needed_mask)
1265 return i;
1266
1267 needed_mask <<= 1;
1268 }
1269
1270 return -1;
1271 }
1272
1273
1274 /**
1275 * Assign locations for either VS inputs for FS outputs
1276 *
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.
1284 *
1285 * \return
1286 * If locations are successfully assigned, true is returned. Otherwise an
1287 * error is emitted to the shader link log and false is returned.
1288 */
1289 bool
1290 assign_attribute_or_color_locations(gl_shader_program *prog,
1291 unsigned target_index,
1292 unsigned max_index)
1293 {
1294 /* Mark invalid locations as being used.
1295 */
1296 unsigned used_locations = (max_index >= 32)
1297 ? ~0 : ~((1 << max_index) - 1);
1298
1299 assert((target_index == MESA_SHADER_VERTEX)
1300 || (target_index == MESA_SHADER_FRAGMENT));
1301
1302 gl_shader *const sh = prog->_LinkedShaders[target_index];
1303 if (sh == NULL)
1304 return true;
1305
1306 /* Operate in a total of four passes.
1307 *
1308 * 1. Invalidate the location assignments for all vertex shader inputs.
1309 *
1310 * 2. Assign locations for inputs that have user-defined (via
1311 * glBindVertexAttribLocation) locations and outputs that have
1312 * user-defined locations (via glBindFragDataLocation).
1313 *
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.
1318 *
1319 * 4. Assign locations to any inputs without assigned locations.
1320 */
1321
1322 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1323 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1324
1325 const enum ir_variable_mode direction =
1326 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1327
1328
1329 /* Temporary storage for the set of attributes that need locations assigned.
1330 */
1331 struct temp_attr {
1332 unsigned slots;
1333 ir_variable *var;
1334
1335 /* Used below in the call to qsort. */
1336 static int compare(const void *a, const void *b)
1337 {
1338 const temp_attr *const l = (const temp_attr *) a;
1339 const temp_attr *const r = (const temp_attr *) b;
1340
1341 /* Reversed because we want a descending order sort below. */
1342 return r->slots - l->slots;
1343 }
1344 } to_assign[16];
1345
1346 unsigned num_attr = 0;
1347
1348 foreach_list(node, sh->ir) {
1349 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1350
1351 if ((var == NULL) || (var->mode != (unsigned) direction))
1352 continue;
1353
1354 if (var->explicit_location) {
1355 if ((var->location >= (int)(max_index + generic_base))
1356 || (var->location < 0)) {
1357 linker_error(prog,
1358 "invalid explicit location %d specified for `%s'\n",
1359 (var->location < 0)
1360 ? var->location : var->location - generic_base,
1361 var->name);
1362 return false;
1363 }
1364 } else if (target_index == MESA_SHADER_VERTEX) {
1365 unsigned binding;
1366
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;
1371 }
1372 } else if (target_index == MESA_SHADER_FRAGMENT) {
1373 unsigned binding;
1374 unsigned index;
1375
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;
1380
1381 if (prog->FragDataIndexBindings->get(index, var->name)) {
1382 var->index = index;
1383 }
1384 }
1385 }
1386
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.
1391 */
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:
1396 *
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."
1402 *
1403 * Previous versions of the spec contain similar language but omit
1404 * the bit about attribute arrays.
1405 *
1406 * Page 61 of the OpenGL 4.0 spec also says:
1407 *
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
1417 * in this case."
1418 *
1419 * These two paragraphs are either somewhat contradictory, or I
1420 * don't fully understand one or both of them.
1421 */
1422 /* FINISHME: The code as currently written does not support
1423 * FINISHME: attribute location aliasing (see comment above).
1424 */
1425 /* Mask representing the contiguous slots that will be used by
1426 * this attribute.
1427 */
1428 const unsigned attr = var->location - generic_base;
1429 const unsigned use_mask = (1 << slots) - 1;
1430
1431 /* Generate a link error if the set of bits requested for this
1432 * attribute overlaps any previously allocated bits.
1433 */
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";
1437 linker_error(prog,
1438 "insufficient contiguous locations "
1439 "available for %s `%s' %d %d %d", string,
1440 var->name, used_locations, use_mask, attr);
1441 return false;
1442 }
1443
1444 used_locations |= (use_mask << attr);
1445 }
1446
1447 continue;
1448 }
1449
1450 to_assign[num_attr].slots = slots;
1451 to_assign[num_attr].var = var;
1452 num_attr++;
1453 }
1454
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.
1458 */
1459 if (num_attr == 0)
1460 return true;
1461
1462 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1463
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.
1468 */
1469 find_deref_visitor find("gl_Vertex");
1470 find.run(sh->ir);
1471 if (find.variable_found())
1472 used_locations |= (1 << 0);
1473 }
1474
1475 for (unsigned i = 0; i < num_attr; i++) {
1476 /* Mask representing the contiguous slots that will be used by this
1477 * attribute.
1478 */
1479 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1480
1481 int location = find_available_slots(used_locations, to_assign[i].slots);
1482
1483 if (location < 0) {
1484 const char *const string = (target_index == MESA_SHADER_VERTEX)
1485 ? "vertex shader input" : "fragment shader output";
1486
1487 linker_error(prog,
1488 "insufficient contiguous locations "
1489 "available for %s `%s'",
1490 string, to_assign[i].var->name);
1491 return false;
1492 }
1493
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);
1497 }
1498
1499 return true;
1500 }
1501
1502
1503 /**
1504 * Demote shader inputs and outputs that are not used in other stages
1505 */
1506 void
1507 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1508 {
1509 foreach_list(node, sh->ir) {
1510 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1511
1512 if ((var == NULL) || (var->mode != int(mode)))
1513 continue;
1514
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.
1518 */
1519 if (var->is_unmatched_generic_inout) {
1520 var->mode = ir_var_auto;
1521 }
1522 }
1523 }
1524
1525
1526 /**
1527 * Data structure tracking information about a transform feedback declaration
1528 * during linking.
1529 */
1530 class tfeedback_decl
1531 {
1532 public:
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;
1542
1543 /**
1544 * True if assign_location() has been called for this object.
1545 */
1546 bool is_assigned() const
1547 {
1548 return this->location != -1;
1549 }
1550
1551 bool is_next_buffer_separator() const
1552 {
1553 return this->next_buffer_separator;
1554 }
1555
1556 bool is_varying() const
1557 {
1558 return !this->next_buffer_separator && !this->skip_components;
1559 }
1560
1561 /**
1562 * Determine whether this object refers to the variable var.
1563 */
1564 bool matches_var(ir_variable *var) const
1565 {
1566 if (this->is_clip_distance_mesa)
1567 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1568 else
1569 return strcmp(var->name, this->var_name) == 0;
1570 }
1571
1572 /**
1573 * The total number of varying components taken up by this variable. Only
1574 * valid if is_assigned() is true.
1575 */
1576 unsigned num_components() const
1577 {
1578 if (this->is_clip_distance_mesa)
1579 return this->size;
1580 else
1581 return this->vector_elements * this->matrix_columns * this->size;
1582 }
1583
1584 private:
1585 /**
1586 * The name that was supplied to glTransformFeedbackVaryings. Used for
1587 * error reporting and glGetTransformFeedbackVarying().
1588 */
1589 const char *orig_name;
1590
1591 /**
1592 * The name of the variable, parsed from orig_name.
1593 */
1594 const char *var_name;
1595
1596 /**
1597 * True if the declaration in orig_name represents an array.
1598 */
1599 bool is_subscripted;
1600
1601 /**
1602 * If is_subscripted is true, the subscript that was specified in orig_name.
1603 */
1604 unsigned array_subscript;
1605
1606 /**
1607 * True if the variable is gl_ClipDistance and the driver lowers
1608 * gl_ClipDistance to gl_ClipDistanceMESA.
1609 */
1610 bool is_clip_distance_mesa;
1611
1612 /**
1613 * The vertex shader output location that the linker assigned for this
1614 * variable. -1 if a location hasn't been assigned yet.
1615 */
1616 int location;
1617
1618 /**
1619 * If location != -1, the number of vector elements in this variable, or 1
1620 * if this variable is a scalar.
1621 */
1622 unsigned vector_elements;
1623
1624 /**
1625 * If location != -1, the number of matrix columns in this variable, or 1
1626 * if this variable is not a matrix.
1627 */
1628 unsigned matrix_columns;
1629
1630 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1631 GLenum type;
1632
1633 /**
1634 * If location != -1, the size that should be returned by
1635 * glGetTransformFeedbackVarying().
1636 */
1637 unsigned size;
1638
1639 /**
1640 * How many components to skip. If non-zero, this is
1641 * gl_SkipComponents{1,2,3,4} from ARB_transform_feedback3.
1642 */
1643 unsigned skip_components;
1644
1645 /**
1646 * Whether this is gl_NextBuffer from ARB_transform_feedback3.
1647 */
1648 bool next_buffer_separator;
1649 };
1650
1651
1652 /**
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.
1656 */
1657 bool
1658 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1659 const void *mem_ctx, const char *input)
1660 {
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.
1663 */
1664
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;
1670
1671 if (ctx->Extensions.ARB_transform_feedback3) {
1672 /* Parse gl_NextBuffer. */
1673 if (strcmp(input, "gl_NextBuffer") == 0) {
1674 this->next_buffer_separator = true;
1675 return true;
1676 }
1677
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;
1687
1688 if (this->skip_components)
1689 return true;
1690 }
1691
1692 /* Parse a declaration. */
1693 const char *bracket = strrchr(input, '[');
1694
1695 if (bracket) {
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);
1699 return false;
1700 }
1701 this->is_subscripted = true;
1702 } else {
1703 this->var_name = ralloc_strdup(mem_ctx, input);
1704 this->is_subscripted = false;
1705 }
1706
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].
1710 */
1711 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1712 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1713 this->is_clip_distance_mesa = true;
1714 }
1715
1716 return true;
1717 }
1718
1719
1720 /**
1721 * Determine whether two tfeedback_decl objects refer to the same variable and
1722 * array index (if applicable).
1723 */
1724 bool
1725 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1726 {
1727 assert(x.is_varying() && y.is_varying());
1728
1729 if (strcmp(x.var_name, y.var_name) != 0)
1730 return false;
1731 if (x.is_subscripted != y.is_subscripted)
1732 return false;
1733 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1734 return false;
1735 return true;
1736 }
1737
1738
1739 /**
1740 * Assign a location for this tfeedback_decl object based on the location
1741 * assignment in output_var.
1742 *
1743 * If an error occurs, the error is reported through linker_error() and false
1744 * is returned.
1745 */
1746 bool
1747 tfeedback_decl::assign_location(struct gl_context *ctx,
1748 struct gl_shader_program *prog,
1749 ir_variable *output_var)
1750 {
1751 assert(this->is_varying());
1752
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();
1759
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,
1766 actual_array_size);
1767 return false;
1768 }
1769 if (this->is_clip_distance_mesa) {
1770 this->location =
1771 output_var->location + this->array_subscript / 4;
1772 } else {
1773 this->location =
1774 output_var->location + this->array_subscript * matrix_cols;
1775 }
1776 this->size = 1;
1777 } else {
1778 this->location = output_var->location;
1779 this->size = actual_array_size;
1780 }
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;
1785 else
1786 this->type = output_var->type->fields.array->gl_type;
1787 } else {
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);
1793 return false;
1794 }
1795 this->location = output_var->location;
1796 this->size = 1;
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;
1800 }
1801
1802 /* From GL_EXT_transform_feedback:
1803 * A program will fail to link if:
1804 *
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;
1809 */
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.",
1815 this->orig_name);
1816 return false;
1817 }
1818
1819 return true;
1820 }
1821
1822
1823 bool
1824 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1825 unsigned *count)
1826 {
1827 if (!this->is_varying()) {
1828 return true;
1829 }
1830
1831 if (!this->is_assigned()) {
1832 /* From GL_EXT_transform_feedback:
1833 * A program will fail to link if:
1834 *
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);
1838 */
1839 linker_error(prog, "Transform feedback varying %s undeclared.",
1840 this->orig_name);
1841 return false;
1842 }
1843
1844 unsigned translated_size = this->size;
1845 if (this->is_clip_distance_mesa)
1846 translated_size = (translated_size + 3) / 4;
1847
1848 *count += translated_size * this->matrix_columns;
1849
1850 return true;
1851 }
1852
1853
1854 /**
1855 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1856 *
1857 * If an error occurs, the error is reported through linker_error() and false
1858 * is returned.
1859 */
1860 bool
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
1864 {
1865 assert(!this->next_buffer_separator);
1866
1867 /* Handle gl_SkipComponents. */
1868 if (this->skip_components) {
1869 info->BufferStride[buffer] += this->skip_components;
1870 return true;
1871 }
1872
1873 /* From GL_EXT_transform_feedback:
1874 * A program will fail to link if:
1875 *
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.
1879 */
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.");
1885 return false;
1886 }
1887
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) {
1899 num_components = 1;
1900 info->Outputs[info->NumOutputs].ComponentOffset =
1901 this->array_subscript % 4;
1902 } else {
1903 num_components = MIN2(4, this->size - components_so_far);
1904 }
1905 }
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];
1911 ++info->NumOutputs;
1912 info->BufferStride[buffer] += num_components;
1913 components_so_far += num_components;
1914 }
1915 }
1916 assert(components_so_far == this->num_components());
1917
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;
1921 info->NumVarying++;
1922
1923 return true;
1924 }
1925
1926
1927 /**
1928 * Parse all the transform feedback declarations that were passed to
1929 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1930 *
1931 * If an error occurs, the error is reported through linker_error() and false
1932 * is returned.
1933 */
1934 static bool
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)
1938 {
1939 for (unsigned i = 0; i < num_names; ++i) {
1940 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1941 return false;
1942
1943 if (!decls[i].is_varying())
1944 continue;
1945
1946 /* From GL_EXT_transform_feedback:
1947 * A program will fail to link if:
1948 *
1949 * * any two entries in the <varyings> array specify the same varying
1950 * variable;
1951 *
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.
1955 */
1956 for (unsigned j = 0; j < i; ++j) {
1957 if (!decls[j].is_varying())
1958 continue;
1959
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]);
1963 return false;
1964 }
1965 }
1966 }
1967 return true;
1968 }
1969
1970
1971 /**
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").
1974 *
1975 * \param input_var is the input variable declaration in the consumer.
1976 *
1977 * \param output_var is the output variable declaration in the producer.
1978 *
1979 * \param input_index is the counter that keeps track of assigned input
1980 * locations in the consumer.
1981 *
1982 * \param output_index is the counter that keeps track of assigned output
1983 * locations in the producer.
1984 *
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).
1988 *
1989 * If the variable has already been assigned a location, this function has no
1990 * effect.
1991 */
1992 void
1993 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1994 unsigned *input_index, unsigned *output_index)
1995 {
1996 if (!output_var->is_unmatched_generic_inout) {
1997 /* Location already assigned. */
1998 return;
1999 }
2000
2001 if (input_var) {
2002 assert(input_var->location == -1);
2003 input_var->location = *input_index;
2004 input_var->is_unmatched_generic_inout = 0;
2005 }
2006
2007 output_var->location = *output_index;
2008 output_var->is_unmatched_generic_inout = 0;
2009
2010 /* FINISHME: Support for "varying" records in GLSL 1.50. */
2011 assert(!output_var->type->is_record());
2012
2013 if (output_var->type->is_array()) {
2014 const unsigned slots = output_var->type->length
2015 * output_var->type->fields.array->matrix_columns;
2016
2017 *output_index += slots;
2018 *input_index += slots;
2019 } else {
2020 const unsigned slots = output_var->type->matrix_columns;
2021
2022 *output_index += slots;
2023 *input_index += slots;
2024 }
2025 }
2026
2027
2028 /**
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.
2033 */
2034 static bool
2035 is_varying_var(GLenum shaderType, const ir_variable *var)
2036 {
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:
2044 return false;
2045 default:
2046 return true;
2047 }
2048 }
2049 return false;
2050 }
2051
2052
2053 /**
2054 * Assign locations for all variables that are produced in one pipeline stage
2055 * (the "producer") and consumed in the next stage (the "consumer").
2056 *
2057 * Variables produced by the producer may also be consumed by transform
2058 * feedback.
2059 *
2060 * \param num_tfeedback_decls is the number of declarations indicating
2061 * variables that may be consumed by transform feedback.
2062 *
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
2067 * producer.
2068 *
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.
2072 */
2073 bool
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)
2079 {
2080 /* FINISHME: Set dynamically when geometry shader support is added. */
2081 unsigned output_index = VERT_RESULT_VAR0;
2082 unsigned input_index = FRAG_ATTRIB_VAR0;
2083
2084 /* Operate in a total of three passes.
2085 *
2086 * 1. Assign locations for any matching inputs and outputs.
2087 *
2088 * 2. Mark output variables in the producer that do not have locations as
2089 * not being outputs. This lets the optimizer eliminate them.
2090 *
2091 * 3. Mark input variables in the consumer that do not have locations as
2092 * not being inputs. This lets the optimizer eliminate them.
2093 */
2094
2095 foreach_list(node, producer->ir) {
2096 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
2097
2098 if ((output_var == NULL) || (output_var->mode != ir_var_out))
2099 continue;
2100
2101 ir_variable *input_var =
2102 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
2103
2104 if (input_var && input_var->mode != ir_var_in)
2105 input_var = NULL;
2106
2107 if (input_var) {
2108 assign_varying_location(input_var, output_var, &input_index,
2109 &output_index);
2110 }
2111
2112 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2113 if (!tfeedback_decls[i].is_varying())
2114 continue;
2115
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,
2120 &output_index);
2121 }
2122 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
2123 return false;
2124 }
2125 }
2126 }
2127
2128 unsigned varying_vectors = 0;
2129
2130 if (consumer) {
2131 foreach_list(node, consumer->ir) {
2132 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2133
2134 if ((var == NULL) || (var->mode != ir_var_in))
2135 continue;
2136
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:
2140 *
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
2145 * permissible.
2146 *
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.
2150 */
2151
2152 linker_error(prog, "fragment shader varying %s not written "
2153 "by vertex shader\n.", var->name);
2154 }
2155
2156 /* An 'in' variable is only really a shader input if its
2157 * value is written by the previous stage.
2158 */
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.
2163 */
2164 varying_vectors += count_attribute_slots(var->type);
2165 }
2166 }
2167 }
2168
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 "
2175 "behavior\n",
2176 varying_vectors, ctx->Const.MaxVarying);
2177 } else {
2178 linker_error(prog, "shader uses too many varying vectors "
2179 "(%u > %u)\n",
2180 varying_vectors, ctx->Const.MaxVarying);
2181 return false;
2182 }
2183 }
2184 } else {
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 "
2191 "behavior\n",
2192 float_components, ctx->Const.MaxVarying * 4);
2193 } else {
2194 linker_error(prog, "shader uses too many varying components "
2195 "(%u > %u)\n",
2196 float_components, ctx->Const.MaxVarying * 4);
2197 return false;
2198 }
2199 }
2200 }
2201
2202 return true;
2203 }
2204
2205
2206 /**
2207 * Store transform feedback location assignments into
2208 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2209 *
2210 * If an error occurs, the error is reported through linker_error() and false
2211 * is returned.
2212 */
2213 static bool
2214 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2215 unsigned num_tfeedback_decls,
2216 tfeedback_decl *tfeedback_decls)
2217 {
2218 bool separate_attribs_mode =
2219 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
2220
2221 ralloc_free(prog->LinkedTransformFeedback.Varyings);
2222 ralloc_free(prog->LinkedTransformFeedback.Outputs);
2223
2224 memset(&prog->LinkedTransformFeedback, 0,
2225 sizeof(prog->LinkedTransformFeedback));
2226
2227 prog->LinkedTransformFeedback.Varyings =
2228 rzalloc_array(prog,
2229 struct gl_transform_feedback_varying_info,
2230 num_tfeedback_decls);
2231
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))
2235 return false;
2236
2237 prog->LinkedTransformFeedback.Outputs =
2238 rzalloc_array(prog,
2239 struct gl_transform_feedback_output,
2240 num_outputs);
2241
2242 unsigned num_buffers = 0;
2243
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))
2249 return false;
2250
2251 num_buffers++;
2252 }
2253 }
2254 else {
2255 /* GL_INVERLEAVED_ATTRIBS */
2256 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2257 if (tfeedback_decls[i].is_next_buffer_separator()) {
2258 num_buffers++;
2259 continue;
2260 }
2261
2262 if (!tfeedback_decls[i].store(ctx, prog,
2263 &prog->LinkedTransformFeedback,
2264 num_buffers, num_outputs))
2265 return false;
2266 }
2267 num_buffers++;
2268 }
2269
2270 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2271
2272 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
2273 return true;
2274 }
2275
2276 /**
2277 * Store the gl_FragDepth layout in the gl_shader_program struct.
2278 */
2279 static void
2280 store_fragdepth_layout(struct gl_shader_program *prog)
2281 {
2282 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2283 return;
2284 }
2285
2286 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2287
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.
2291 *
2292 * We're only interested in the cases where the variable is NOT removed
2293 * from the IR.
2294 */
2295 foreach_list(node, ir) {
2296 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2297
2298 if (var == NULL || var->mode != ir_var_out) {
2299 continue;
2300 }
2301
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;
2306 return;
2307 case ir_depth_layout_any:
2308 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2309 return;
2310 case ir_depth_layout_greater:
2311 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2312 return;
2313 case ir_depth_layout_less:
2314 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2315 return;
2316 case ir_depth_layout_unchanged:
2317 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2318 return;
2319 default:
2320 assert(0);
2321 return;
2322 }
2323 }
2324 }
2325 }
2326
2327 /**
2328 * Validate the resources used by a program versus the implementation limits
2329 */
2330 static bool
2331 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2332 {
2333 static const char *const shader_names[MESA_SHADER_TYPES] = {
2334 "vertex", "fragment", "geometry"
2335 };
2336
2337 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2338 ctx->Const.MaxVertexTextureImageUnits,
2339 ctx->Const.MaxTextureImageUnits,
2340 ctx->Const.MaxGeometryTextureImageUnits
2341 };
2342
2343 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2344 ctx->Const.VertexProgram.MaxUniformComponents,
2345 ctx->Const.FragmentProgram.MaxUniformComponents,
2346 0 /* FINISHME: Geometry shaders. */
2347 };
2348
2349 const unsigned max_uniform_blocks[MESA_SHADER_TYPES] = {
2350 ctx->Const.VertexProgram.MaxUniformBlocks,
2351 ctx->Const.FragmentProgram.MaxUniformBlocks,
2352 ctx->Const.GeometryProgram.MaxUniformBlocks,
2353 };
2354
2355 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2356 struct gl_shader *sh = prog->_LinkedShaders[i];
2357
2358 if (sh == NULL)
2359 continue;
2360
2361 if (sh->num_samplers > max_samplers[i]) {
2362 linker_error(prog, "Too many %s shader texture samplers",
2363 shader_names[i]);
2364 }
2365
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",
2371 shader_names[i]);
2372 } else {
2373 linker_error(prog, "Too many %s shader uniform components",
2374 shader_names[i]);
2375 }
2376 }
2377 }
2378
2379 unsigned blocks[MESA_SHADER_TYPES] = {0};
2380 unsigned total_uniform_blocks = 0;
2381
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) {
2385 blocks[j]++;
2386 total_uniform_blocks++;
2387 }
2388 }
2389
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);
2394 } else {
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)",
2398 shader_names[i],
2399 blocks[i],
2400 max_uniform_blocks[i]);
2401 break;
2402 }
2403 }
2404 }
2405 }
2406
2407 return prog->LinkStatus;
2408 }
2409
2410 void
2411 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2412 {
2413 tfeedback_decl *tfeedback_decls = NULL;
2414 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2415
2416 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2417
2418 prog->LinkStatus = false;
2419 prog->Validated = false;
2420 prog->_Used = false;
2421
2422 ralloc_free(prog->InfoLog);
2423 prog->InfoLog = ralloc_strdup(NULL, "");
2424
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;
2431 }
2432
2433 /* Separate the shaders into groups based on their type.
2434 */
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;
2439
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];
2443
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);
2451
2452 if (prog->Shaders[i]->IsES != is_es_prog) {
2453 linker_error(prog, "all shaders must use same shading "
2454 "language version\n");
2455 goto done;
2456 }
2457
2458 switch (prog->Shaders[i]->Type) {
2459 case GL_VERTEX_SHADER:
2460 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2461 num_vert_shaders++;
2462 break;
2463 case GL_FRAGMENT_SHADER:
2464 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2465 num_frag_shaders++;
2466 break;
2467 case GL_GEOMETRY_SHADER:
2468 /* FINISHME: Support geometry shaders. */
2469 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2470 break;
2471 }
2472 }
2473
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.
2477 *
2478 * GLSL ES has never allowed mixing of shading language versions.
2479 */
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");
2484 goto done;
2485 }
2486
2487 prog->Version = max_version;
2488 prog->IsES = is_es_prog;
2489
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]);
2493
2494 prog->_LinkedShaders[i] = NULL;
2495 }
2496
2497 /* Link all shaders for a particular stage and validate the result.
2498 */
2499 if (num_vert_shaders > 0) {
2500 gl_shader *const sh =
2501 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2502 num_vert_shaders);
2503
2504 if (sh == NULL)
2505 goto done;
2506
2507 if (!validate_vertex_shader_executable(prog, sh))
2508 goto done;
2509
2510 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2511 sh);
2512 }
2513
2514 if (num_frag_shaders > 0) {
2515 gl_shader *const sh =
2516 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2517 num_frag_shaders);
2518
2519 if (sh == NULL)
2520 goto done;
2521
2522 if (!validate_fragment_shader_executable(prog, sh))
2523 goto done;
2524
2525 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2526 sh);
2527 }
2528
2529 /* Here begins the inter-stage linking phase. Some initial validation is
2530 * performed, then locations are assigned for uniforms, attributes, and
2531 * varyings.
2532 */
2533 if (cross_validate_uniforms(prog)) {
2534 unsigned prev;
2535
2536 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2537 if (prog->_LinkedShaders[prev] != NULL)
2538 break;
2539 }
2540
2541 /* Validate the inputs of each stage with the output of the preceding
2542 * stage.
2543 */
2544 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2545 if (prog->_LinkedShaders[i] == NULL)
2546 continue;
2547
2548 if (!cross_validate_outputs_to_inputs(prog,
2549 prog->_LinkedShaders[prev],
2550 prog->_LinkedShaders[i]))
2551 goto done;
2552
2553 prev = i;
2554 }
2555
2556 prog->LinkStatus = true;
2557 }
2558
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.
2562 *
2563 * This rule also applies to GLSL ES 3.00.
2564 */
2565 if (max_version >= (is_es_prog ? 300 : 130)) {
2566 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2567 if (sh) {
2568 lower_discard_flow(sh->ir);
2569 }
2570 }
2571
2572 if (!interstage_cross_validate_uniform_blocks(prog))
2573 goto done;
2574
2575 /* Do common optimization before assigning storage for attributes,
2576 * uniforms, and varyings. Later optimization could possibly make
2577 * some of that unused.
2578 */
2579 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2580 if (prog->_LinkedShaders[i] == NULL)
2581 continue;
2582
2583 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2584 if (!prog->LinkStatus)
2585 goto done;
2586
2587 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
2588 lower_clip_distance(prog->_LinkedShaders[i]);
2589 }
2590
2591 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2592
2593 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
2594 ;
2595 }
2596
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);
2602 }
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);
2608 }
2609
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.
2614 */
2615 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2616 goto done;
2617 }
2618
2619 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2620 goto done;
2621 }
2622
2623 unsigned prev;
2624 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2625 if (prog->_LinkedShaders[prev] != NULL)
2626 break;
2627 }
2628
2629 if (num_tfeedback_decls != 0) {
2630 /* From GL_EXT_transform_feedback:
2631 * A program will fail to link if:
2632 *
2633 * * the <count> specified by TransformFeedbackVaryingsEXT is
2634 * non-zero, but the program object has no vertex or geometry
2635 * shader;
2636 */
2637 if (prev >= MESA_SHADER_FRAGMENT) {
2638 linker_error(prog, "Transform feedback varyings specified, but "
2639 "no vertex or geometry shader is present.");
2640 goto done;
2641 }
2642
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,
2647 tfeedback_decls))
2648 goto done;
2649 }
2650
2651 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2652 if (prog->_LinkedShaders[i] == NULL)
2653 continue;
2654
2655 if (!assign_varying_locations(
2656 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2657 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2658 tfeedback_decls))
2659 goto done;
2660
2661 prev = i;
2662 }
2663
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.
2667 */
2668 if (!assign_varying_locations(
2669 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2670 tfeedback_decls))
2671 goto done;
2672 }
2673
2674 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2675 goto done;
2676
2677 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2678 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2679 ir_var_out);
2680
2681 /* Eliminate code that is now dead due to unused vertex outputs being
2682 * demoted.
2683 */
2684 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2685 ;
2686 }
2687
2688 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2689 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2690
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);
2694
2695 /* Eliminate code that is now dead due to unused geometry outputs being
2696 * demoted.
2697 */
2698 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2699 ;
2700 }
2701
2702 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2703 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2704
2705 demote_shader_inputs_and_outputs(sh, ir_var_in);
2706
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.
2710 */
2711 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2712 ;
2713 }
2714
2715 update_array_sizes(prog);
2716 link_assign_uniform_locations(prog);
2717 store_fragdepth_layout(prog);
2718
2719 if (!check_resources(ctx, prog))
2720 goto done;
2721
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.
2725 */
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");
2732 }
2733 }
2734
2735 /* FINISHME: Assign fragment shader output locations. */
2736
2737 done:
2738 free(vert_shader_list);
2739
2740 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2741 if (prog->_LinkedShaders[i] == NULL)
2742 continue;
2743
2744 /* Retain any live IR, but trash the rest. */
2745 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2746
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
2750 * pointer to NULL.
2751 */
2752 delete prog->_LinkedShaders[i]->symbols;
2753 prog->_LinkedShaders[i]->symbols = NULL;
2754 }
2755
2756 ralloc_free(mem_ctx);
2757 }