glsl: Modify array_sizing_visitor to handle unnamed interface blocks.
[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 "glsl_parser_extras.h"
70 #include "ir.h"
71 #include "program.h"
72 #include "program/hash_table.h"
73 #include "linker.h"
74 #include "link_varyings.h"
75 #include "ir_optimization.h"
76 #include "ir_rvalue_visitor.h"
77
78 extern "C" {
79 #include "main/shaderobj.h"
80 #include "main/enums.h"
81 }
82
83 void linker_error(gl_shader_program *, const char *, ...);
84
85 namespace {
86
87 /**
88 * Visitor that determines whether or not a variable is ever written.
89 */
90 class find_assignment_visitor : public ir_hierarchical_visitor {
91 public:
92 find_assignment_visitor(const char *name)
93 : name(name), found(false)
94 {
95 /* empty */
96 }
97
98 virtual ir_visitor_status visit_enter(ir_assignment *ir)
99 {
100 ir_variable *const var = ir->lhs->variable_referenced();
101
102 if (strcmp(name, var->name) == 0) {
103 found = true;
104 return visit_stop;
105 }
106
107 return visit_continue_with_parent;
108 }
109
110 virtual ir_visitor_status visit_enter(ir_call *ir)
111 {
112 exec_list_iterator sig_iter = ir->callee->parameters.iterator();
113 foreach_iter(exec_list_iterator, iter, *ir) {
114 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
115 ir_variable *sig_param = (ir_variable *)sig_iter.get();
116
117 if (sig_param->mode == ir_var_function_out ||
118 sig_param->mode == ir_var_function_inout) {
119 ir_variable *var = param_rval->variable_referenced();
120 if (var && strcmp(name, var->name) == 0) {
121 found = true;
122 return visit_stop;
123 }
124 }
125 sig_iter.next();
126 }
127
128 if (ir->return_deref != NULL) {
129 ir_variable *const var = ir->return_deref->variable_referenced();
130
131 if (strcmp(name, var->name) == 0) {
132 found = true;
133 return visit_stop;
134 }
135 }
136
137 return visit_continue_with_parent;
138 }
139
140 bool variable_found()
141 {
142 return found;
143 }
144
145 private:
146 const char *name; /**< Find writes to a variable with this name. */
147 bool found; /**< Was a write to the variable found? */
148 };
149
150
151 /**
152 * Visitor that determines whether or not a variable is ever read.
153 */
154 class find_deref_visitor : public ir_hierarchical_visitor {
155 public:
156 find_deref_visitor(const char *name)
157 : name(name), found(false)
158 {
159 /* empty */
160 }
161
162 virtual ir_visitor_status visit(ir_dereference_variable *ir)
163 {
164 if (strcmp(this->name, ir->var->name) == 0) {
165 this->found = true;
166 return visit_stop;
167 }
168
169 return visit_continue;
170 }
171
172 bool variable_found() const
173 {
174 return this->found;
175 }
176
177 private:
178 const char *name; /**< Find writes to a variable with this name. */
179 bool found; /**< Was a write to the variable found? */
180 };
181
182
183 class geom_array_resize_visitor : public ir_hierarchical_visitor {
184 public:
185 unsigned num_vertices;
186 gl_shader_program *prog;
187
188 geom_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
189 {
190 this->num_vertices = num_vertices;
191 this->prog = prog;
192 }
193
194 virtual ~geom_array_resize_visitor()
195 {
196 /* empty */
197 }
198
199 virtual ir_visitor_status visit(ir_variable *var)
200 {
201 if (!var->type->is_array() || var->mode != ir_var_shader_in)
202 return visit_continue;
203
204 unsigned size = var->type->length;
205
206 /* Generate a link error if the shader has declared this array with an
207 * incorrect size.
208 */
209 if (size && size != this->num_vertices) {
210 linker_error(this->prog, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var->name, size, this->num_vertices);
213 return visit_continue;
214 }
215
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
218 * time.
219 */
220 if (var->max_array_access >= this->num_vertices) {
221 linker_error(this->prog, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
223 var->max_array_access, var->name, this->num_vertices);
224 return visit_continue;
225 }
226
227 var->type = glsl_type::get_array_instance(var->type->element_type(),
228 this->num_vertices);
229 var->max_array_access = this->num_vertices - 1;
230
231 return visit_continue;
232 }
233
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status visit(ir_dereference_variable *ir)
237 {
238 ir->type = ir->var->type;
239 return visit_continue;
240 }
241
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
245 {
246 const glsl_type *const vt = ir->array->type;
247 if (vt->is_array())
248 ir->type = vt->element_type();
249 return visit_continue;
250 }
251 };
252
253
254 /**
255 * Visitor that determines whether or not a shader uses ir_end_primitive.
256 */
257 class find_end_primitive_visitor : public ir_hierarchical_visitor {
258 public:
259 find_end_primitive_visitor()
260 : found(false)
261 {
262 /* empty */
263 }
264
265 virtual ir_visitor_status visit(ir_end_primitive *)
266 {
267 found = true;
268 return visit_stop;
269 }
270
271 bool end_primitive_found()
272 {
273 return found;
274 }
275
276 private:
277 bool found;
278 };
279
280 } /* anonymous namespace */
281
282 void
283 linker_error(gl_shader_program *prog, const char *fmt, ...)
284 {
285 va_list ap;
286
287 ralloc_strcat(&prog->InfoLog, "error: ");
288 va_start(ap, fmt);
289 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
290 va_end(ap);
291
292 prog->LinkStatus = false;
293 }
294
295
296 void
297 linker_warning(gl_shader_program *prog, const char *fmt, ...)
298 {
299 va_list ap;
300
301 ralloc_strcat(&prog->InfoLog, "error: ");
302 va_start(ap, fmt);
303 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
304 va_end(ap);
305
306 }
307
308
309 /**
310 * Given a string identifying a program resource, break it into a base name
311 * and an optional array index in square brackets.
312 *
313 * If an array index is present, \c out_base_name_end is set to point to the
314 * "[" that precedes the array index, and the array index itself is returned
315 * as a long.
316 *
317 * If no array index is present (or if the array index is negative or
318 * mal-formed), \c out_base_name_end, is set to point to the null terminator
319 * at the end of the input string, and -1 is returned.
320 *
321 * Only the final array index is parsed; if the string contains other array
322 * indices (or structure field accesses), they are left in the base name.
323 *
324 * No attempt is made to check that the base name is properly formed;
325 * typically the caller will look up the base name in a hash table, so
326 * ill-formed base names simply turn into hash table lookup failures.
327 */
328 long
329 parse_program_resource_name(const GLchar *name,
330 const GLchar **out_base_name_end)
331 {
332 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
333 *
334 * "When an integer array element or block instance number is part of
335 * the name string, it will be specified in decimal form without a "+"
336 * or "-" sign or any extra leading zeroes. Additionally, the name
337 * string will not include white space anywhere in the string."
338 */
339
340 const size_t len = strlen(name);
341 *out_base_name_end = name + len;
342
343 if (len == 0 || name[len-1] != ']')
344 return -1;
345
346 /* Walk backwards over the string looking for a non-digit character. This
347 * had better be the opening bracket for an array index.
348 *
349 * Initially, i specifies the location of the ']'. Since the string may
350 * contain only the ']' charcater, walk backwards very carefully.
351 */
352 unsigned i;
353 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
354 /* empty */ ;
355
356 if ((i == 0) || name[i-1] != '[')
357 return -1;
358
359 long array_index = strtol(&name[i], NULL, 10);
360 if (array_index < 0)
361 return -1;
362
363 *out_base_name_end = name + (i - 1);
364 return array_index;
365 }
366
367
368 void
369 link_invalidate_variable_locations(gl_shader *sh, int input_base,
370 int output_base)
371 {
372 foreach_list(node, sh->ir) {
373 ir_variable *const var = ((ir_instruction *) node)->as_variable();
374
375 if (var == NULL)
376 continue;
377
378 int base;
379 switch (var->mode) {
380 case ir_var_shader_in:
381 base = input_base;
382 break;
383 case ir_var_shader_out:
384 base = output_base;
385 break;
386 default:
387 continue;
388 }
389
390 /* Only assign locations for generic attributes / varyings / etc.
391 */
392 if ((var->location >= base) && !var->explicit_location)
393 var->location = -1;
394
395 if ((var->location == -1) && !var->explicit_location) {
396 var->is_unmatched_generic_inout = 1;
397 var->location_frac = 0;
398 } else {
399 var->is_unmatched_generic_inout = 0;
400 }
401 }
402 }
403
404
405 /**
406 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
407 *
408 * Also check for errors based on incorrect usage of gl_ClipVertex and
409 * gl_ClipDistance.
410 *
411 * Return false if an error was reported.
412 */
413 static void
414 analyze_clip_usage(const char *shader_type, struct gl_shader_program *prog,
415 struct gl_shader *shader, GLboolean *UsesClipDistance,
416 GLuint *ClipDistanceArraySize)
417 {
418 *ClipDistanceArraySize = 0;
419
420 if (!prog->IsES && prog->Version >= 130) {
421 /* From section 7.1 (Vertex Shader Special Variables) of the
422 * GLSL 1.30 spec:
423 *
424 * "It is an error for a shader to statically write both
425 * gl_ClipVertex and gl_ClipDistance."
426 *
427 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
428 * gl_ClipVertex nor gl_ClipDistance.
429 */
430 find_assignment_visitor clip_vertex("gl_ClipVertex");
431 find_assignment_visitor clip_distance("gl_ClipDistance");
432
433 clip_vertex.run(shader->ir);
434 clip_distance.run(shader->ir);
435 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
436 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
437 "and `gl_ClipDistance'\n", shader_type);
438 return;
439 }
440 *UsesClipDistance = clip_distance.variable_found();
441 ir_variable *clip_distance_var =
442 shader->symbols->get_variable("gl_ClipDistance");
443 if (clip_distance_var)
444 *ClipDistanceArraySize = clip_distance_var->type->length;
445 } else {
446 *UsesClipDistance = false;
447 }
448 }
449
450
451 /**
452 * Verify that a vertex shader executable meets all semantic requirements.
453 *
454 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
455 * as a side effect.
456 *
457 * \param shader Vertex shader executable to be verified
458 */
459 void
460 validate_vertex_shader_executable(struct gl_shader_program *prog,
461 struct gl_shader *shader)
462 {
463 if (shader == NULL)
464 return;
465
466 /* From the GLSL 1.10 spec, page 48:
467 *
468 * "The variable gl_Position is available only in the vertex
469 * language and is intended for writing the homogeneous vertex
470 * position. All executions of a well-formed vertex shader
471 * executable must write a value into this variable. [...] The
472 * variable gl_Position is available only in the vertex
473 * language and is intended for writing the homogeneous vertex
474 * position. All executions of a well-formed vertex shader
475 * executable must write a value into this variable."
476 *
477 * while in GLSL 1.40 this text is changed to:
478 *
479 * "The variable gl_Position is available only in the vertex
480 * language and is intended for writing the homogeneous vertex
481 * position. It can be written at any time during shader
482 * execution. It may also be read back by a vertex shader
483 * after being written. This value will be used by primitive
484 * assembly, clipping, culling, and other fixed functionality
485 * operations, if present, that operate on primitives after
486 * vertex processing has occurred. Its value is undefined if
487 * the vertex shader executable does not write gl_Position."
488 *
489 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
490 * not an error.
491 */
492 if (prog->Version < (prog->IsES ? 300 : 140)) {
493 find_assignment_visitor find("gl_Position");
494 find.run(shader->ir);
495 if (!find.variable_found()) {
496 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
497 return;
498 }
499 }
500
501 analyze_clip_usage("vertex", prog, shader, &prog->Vert.UsesClipDistance,
502 &prog->Vert.ClipDistanceArraySize);
503 }
504
505
506 /**
507 * Verify that a fragment shader executable meets all semantic requirements
508 *
509 * \param shader Fragment shader executable to be verified
510 */
511 void
512 validate_fragment_shader_executable(struct gl_shader_program *prog,
513 struct gl_shader *shader)
514 {
515 if (shader == NULL)
516 return;
517
518 find_assignment_visitor frag_color("gl_FragColor");
519 find_assignment_visitor frag_data("gl_FragData");
520
521 frag_color.run(shader->ir);
522 frag_data.run(shader->ir);
523
524 if (frag_color.variable_found() && frag_data.variable_found()) {
525 linker_error(prog, "fragment shader writes to both "
526 "`gl_FragColor' and `gl_FragData'\n");
527 }
528 }
529
530 /**
531 * Verify that a geometry shader executable meets all semantic requirements
532 *
533 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
534 * prog->Geom.ClipDistanceArraySize as a side effect.
535 *
536 * \param shader Geometry shader executable to be verified
537 */
538 void
539 validate_geometry_shader_executable(struct gl_shader_program *prog,
540 struct gl_shader *shader)
541 {
542 if (shader == NULL)
543 return;
544
545 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
546 prog->Geom.VerticesIn = num_vertices;
547
548 analyze_clip_usage("geometry", prog, shader, &prog->Geom.UsesClipDistance,
549 &prog->Geom.ClipDistanceArraySize);
550
551 find_end_primitive_visitor end_primitive;
552 end_primitive.run(shader->ir);
553 prog->Geom.UsesEndPrimitive = end_primitive.end_primitive_found();
554 }
555
556
557 /**
558 * Generate a string describing the mode of a variable
559 */
560 static const char *
561 mode_string(const ir_variable *var)
562 {
563 switch (var->mode) {
564 case ir_var_auto:
565 return (var->read_only) ? "global constant" : "global variable";
566
567 case ir_var_uniform: return "uniform";
568 case ir_var_shader_in: return "shader input";
569 case ir_var_shader_out: return "shader output";
570
571 case ir_var_const_in:
572 case ir_var_temporary:
573 default:
574 assert(!"Should not get here.");
575 return "invalid variable";
576 }
577 }
578
579
580 /**
581 * Perform validation of global variables used across multiple shaders
582 */
583 void
584 cross_validate_globals(struct gl_shader_program *prog,
585 struct gl_shader **shader_list,
586 unsigned num_shaders,
587 bool uniforms_only)
588 {
589 /* Examine all of the uniforms in all of the shaders and cross validate
590 * them.
591 */
592 glsl_symbol_table variables;
593 for (unsigned i = 0; i < num_shaders; i++) {
594 if (shader_list[i] == NULL)
595 continue;
596
597 foreach_list(node, shader_list[i]->ir) {
598 ir_variable *const var = ((ir_instruction *) node)->as_variable();
599
600 if (var == NULL)
601 continue;
602
603 if (uniforms_only && (var->mode != ir_var_uniform))
604 continue;
605
606 /* Don't cross validate temporaries that are at global scope. These
607 * will eventually get pulled into the shaders 'main'.
608 */
609 if (var->mode == ir_var_temporary)
610 continue;
611
612 /* If a global with this name has already been seen, verify that the
613 * new instance has the same type. In addition, if the globals have
614 * initializers, the values of the initializers must be the same.
615 */
616 ir_variable *const existing = variables.get_variable(var->name);
617 if (existing != NULL) {
618 if (var->type != existing->type) {
619 /* Consider the types to be "the same" if both types are arrays
620 * of the same type and one of the arrays is implicitly sized.
621 * In addition, set the type of the linked variable to the
622 * explicitly sized array.
623 */
624 if (var->type->is_array()
625 && existing->type->is_array()
626 && (var->type->fields.array == existing->type->fields.array)
627 && ((var->type->length == 0)
628 || (existing->type->length == 0))) {
629 if (var->type->length != 0) {
630 existing->type = var->type;
631 }
632 } else {
633 linker_error(prog, "%s `%s' declared as type "
634 "`%s' and type `%s'\n",
635 mode_string(var),
636 var->name, var->type->name,
637 existing->type->name);
638 return;
639 }
640 }
641
642 if (var->explicit_location) {
643 if (existing->explicit_location
644 && (var->location != existing->location)) {
645 linker_error(prog, "explicit locations for %s "
646 "`%s' have differing values\n",
647 mode_string(var), var->name);
648 return;
649 }
650
651 existing->location = var->location;
652 existing->explicit_location = true;
653 }
654
655 /* From the GLSL 4.20 specification:
656 * "A link error will result if two compilation units in a program
657 * specify different integer-constant bindings for the same
658 * opaque-uniform name. However, it is not an error to specify a
659 * binding on some but not all declarations for the same name"
660 */
661 if (var->explicit_binding) {
662 if (existing->explicit_binding &&
663 var->binding != existing->binding) {
664 linker_error(prog, "explicit bindings for %s "
665 "`%s' have differing values\n",
666 mode_string(var), var->name);
667 return;
668 }
669
670 existing->binding = var->binding;
671 existing->explicit_binding = true;
672 }
673
674 /* Validate layout qualifiers for gl_FragDepth.
675 *
676 * From the AMD/ARB_conservative_depth specs:
677 *
678 * "If gl_FragDepth is redeclared in any fragment shader in a
679 * program, it must be redeclared in all fragment shaders in
680 * that program that have static assignments to
681 * gl_FragDepth. All redeclarations of gl_FragDepth in all
682 * fragment shaders in a single program must have the same set
683 * of qualifiers."
684 */
685 if (strcmp(var->name, "gl_FragDepth") == 0) {
686 bool layout_declared = var->depth_layout != ir_depth_layout_none;
687 bool layout_differs =
688 var->depth_layout != existing->depth_layout;
689
690 if (layout_declared && layout_differs) {
691 linker_error(prog,
692 "All redeclarations of gl_FragDepth in all "
693 "fragment shaders in a single program must have "
694 "the same set of qualifiers.");
695 }
696
697 if (var->used && layout_differs) {
698 linker_error(prog,
699 "If gl_FragDepth is redeclared with a layout "
700 "qualifier in any fragment shader, it must be "
701 "redeclared with the same layout qualifier in "
702 "all fragment shaders that have assignments to "
703 "gl_FragDepth");
704 }
705 }
706
707 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
708 *
709 * "If a shared global has multiple initializers, the
710 * initializers must all be constant expressions, and they
711 * must all have the same value. Otherwise, a link error will
712 * result. (A shared global having only one initializer does
713 * not require that initializer to be a constant expression.)"
714 *
715 * Previous to 4.20 the GLSL spec simply said that initializers
716 * must have the same value. In this case of non-constant
717 * initializers, this was impossible to determine. As a result,
718 * no vendor actually implemented that behavior. The 4.20
719 * behavior matches the implemented behavior of at least one other
720 * vendor, so we'll implement that for all GLSL versions.
721 */
722 if (var->constant_initializer != NULL) {
723 if (existing->constant_initializer != NULL) {
724 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
725 linker_error(prog, "initializers for %s "
726 "`%s' have differing values\n",
727 mode_string(var), var->name);
728 return;
729 }
730 } else {
731 /* If the first-seen instance of a particular uniform did not
732 * have an initializer but a later instance does, copy the
733 * initializer to the version stored in the symbol table.
734 */
735 /* FINISHME: This is wrong. The constant_value field should
736 * FINISHME: not be modified! Imagine a case where a shader
737 * FINISHME: without an initializer is linked in two different
738 * FINISHME: programs with shaders that have differing
739 * FINISHME: initializers. Linking with the first will
740 * FINISHME: modify the shader, and linking with the second
741 * FINISHME: will fail.
742 */
743 existing->constant_initializer =
744 var->constant_initializer->clone(ralloc_parent(existing),
745 NULL);
746 }
747 }
748
749 if (var->has_initializer) {
750 if (existing->has_initializer
751 && (var->constant_initializer == NULL
752 || existing->constant_initializer == NULL)) {
753 linker_error(prog,
754 "shared global variable `%s' has multiple "
755 "non-constant initializers.\n",
756 var->name);
757 return;
758 }
759
760 /* Some instance had an initializer, so keep track of that. In
761 * this location, all sorts of initializers (constant or
762 * otherwise) will propagate the existence to the variable
763 * stored in the symbol table.
764 */
765 existing->has_initializer = true;
766 }
767
768 if (existing->invariant != var->invariant) {
769 linker_error(prog, "declarations for %s `%s' have "
770 "mismatching invariant qualifiers\n",
771 mode_string(var), var->name);
772 return;
773 }
774 if (existing->centroid != var->centroid) {
775 linker_error(prog, "declarations for %s `%s' have "
776 "mismatching centroid qualifiers\n",
777 mode_string(var), var->name);
778 return;
779 }
780 } else
781 variables.add_variable(var);
782 }
783 }
784 }
785
786
787 /**
788 * Perform validation of uniforms used across multiple shader stages
789 */
790 void
791 cross_validate_uniforms(struct gl_shader_program *prog)
792 {
793 cross_validate_globals(prog, prog->_LinkedShaders,
794 MESA_SHADER_TYPES, true);
795 }
796
797 /**
798 * Accumulates the array of prog->UniformBlocks and checks that all
799 * definitons of blocks agree on their contents.
800 */
801 static bool
802 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
803 {
804 unsigned max_num_uniform_blocks = 0;
805 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
806 if (prog->_LinkedShaders[i])
807 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
808 }
809
810 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
811 struct gl_shader *sh = prog->_LinkedShaders[i];
812
813 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
814 max_num_uniform_blocks);
815 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
816 prog->UniformBlockStageIndex[i][j] = -1;
817
818 if (sh == NULL)
819 continue;
820
821 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
822 int index = link_cross_validate_uniform_block(prog,
823 &prog->UniformBlocks,
824 &prog->NumUniformBlocks,
825 &sh->UniformBlocks[j]);
826
827 if (index == -1) {
828 linker_error(prog, "uniform block `%s' has mismatching definitions",
829 sh->UniformBlocks[j].Name);
830 return false;
831 }
832
833 prog->UniformBlockStageIndex[i][index] = j;
834 }
835 }
836
837 return true;
838 }
839
840
841 /**
842 * Populates a shaders symbol table with all global declarations
843 */
844 static void
845 populate_symbol_table(gl_shader *sh)
846 {
847 sh->symbols = new(sh) glsl_symbol_table;
848
849 foreach_list(node, sh->ir) {
850 ir_instruction *const inst = (ir_instruction *) node;
851 ir_variable *var;
852 ir_function *func;
853
854 if ((func = inst->as_function()) != NULL) {
855 sh->symbols->add_function(func);
856 } else if ((var = inst->as_variable()) != NULL) {
857 sh->symbols->add_variable(var);
858 }
859 }
860 }
861
862
863 /**
864 * Remap variables referenced in an instruction tree
865 *
866 * This is used when instruction trees are cloned from one shader and placed in
867 * another. These trees will contain references to \c ir_variable nodes that
868 * do not exist in the target shader. This function finds these \c ir_variable
869 * references and replaces the references with matching variables in the target
870 * shader.
871 *
872 * If there is no matching variable in the target shader, a clone of the
873 * \c ir_variable is made and added to the target shader. The new variable is
874 * added to \b both the instruction stream and the symbol table.
875 *
876 * \param inst IR tree that is to be processed.
877 * \param symbols Symbol table containing global scope symbols in the
878 * linked shader.
879 * \param instructions Instruction stream where new variable declarations
880 * should be added.
881 */
882 void
883 remap_variables(ir_instruction *inst, struct gl_shader *target,
884 hash_table *temps)
885 {
886 class remap_visitor : public ir_hierarchical_visitor {
887 public:
888 remap_visitor(struct gl_shader *target,
889 hash_table *temps)
890 {
891 this->target = target;
892 this->symbols = target->symbols;
893 this->instructions = target->ir;
894 this->temps = temps;
895 }
896
897 virtual ir_visitor_status visit(ir_dereference_variable *ir)
898 {
899 if (ir->var->mode == ir_var_temporary) {
900 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
901
902 assert(var != NULL);
903 ir->var = var;
904 return visit_continue;
905 }
906
907 ir_variable *const existing =
908 this->symbols->get_variable(ir->var->name);
909 if (existing != NULL)
910 ir->var = existing;
911 else {
912 ir_variable *copy = ir->var->clone(this->target, NULL);
913
914 this->symbols->add_variable(copy);
915 this->instructions->push_head(copy);
916 ir->var = copy;
917 }
918
919 return visit_continue;
920 }
921
922 private:
923 struct gl_shader *target;
924 glsl_symbol_table *symbols;
925 exec_list *instructions;
926 hash_table *temps;
927 };
928
929 remap_visitor v(target, temps);
930
931 inst->accept(&v);
932 }
933
934
935 /**
936 * Move non-declarations from one instruction stream to another
937 *
938 * The intended usage pattern of this function is to pass the pointer to the
939 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
940 * pointer) for \c last and \c false for \c make_copies on the first
941 * call. Successive calls pass the return value of the previous call for
942 * \c last and \c true for \c make_copies.
943 *
944 * \param instructions Source instruction stream
945 * \param last Instruction after which new instructions should be
946 * inserted in the target instruction stream
947 * \param make_copies Flag selecting whether instructions in \c instructions
948 * should be copied (via \c ir_instruction::clone) into the
949 * target list or moved.
950 *
951 * \return
952 * The new "last" instruction in the target instruction stream. This pointer
953 * is suitable for use as the \c last parameter of a later call to this
954 * function.
955 */
956 exec_node *
957 move_non_declarations(exec_list *instructions, exec_node *last,
958 bool make_copies, gl_shader *target)
959 {
960 hash_table *temps = NULL;
961
962 if (make_copies)
963 temps = hash_table_ctor(0, hash_table_pointer_hash,
964 hash_table_pointer_compare);
965
966 foreach_list_safe(node, instructions) {
967 ir_instruction *inst = (ir_instruction *) node;
968
969 if (inst->as_function())
970 continue;
971
972 ir_variable *var = inst->as_variable();
973 if ((var != NULL) && (var->mode != ir_var_temporary))
974 continue;
975
976 assert(inst->as_assignment()
977 || inst->as_call()
978 || inst->as_if() /* for initializers with the ?: operator */
979 || ((var != NULL) && (var->mode == ir_var_temporary)));
980
981 if (make_copies) {
982 inst = inst->clone(target, NULL);
983
984 if (var != NULL)
985 hash_table_insert(temps, inst, var);
986 else
987 remap_variables(inst, target, temps);
988 } else {
989 inst->remove();
990 }
991
992 last->insert_after(inst);
993 last = inst;
994 }
995
996 if (make_copies)
997 hash_table_dtor(temps);
998
999 return last;
1000 }
1001
1002 /**
1003 * Get the function signature for main from a shader
1004 */
1005 static ir_function_signature *
1006 get_main_function_signature(gl_shader *sh)
1007 {
1008 ir_function *const f = sh->symbols->get_function("main");
1009 if (f != NULL) {
1010 exec_list void_parameters;
1011
1012 /* Look for the 'void main()' signature and ensure that it's defined.
1013 * This keeps the linker from accidentally pick a shader that just
1014 * contains a prototype for main.
1015 *
1016 * We don't have to check for multiple definitions of main (in multiple
1017 * shaders) because that would have already been caught above.
1018 */
1019 ir_function_signature *sig = f->matching_signature(NULL, &void_parameters);
1020 if ((sig != NULL) && sig->is_defined) {
1021 return sig;
1022 }
1023 }
1024
1025 return NULL;
1026 }
1027
1028
1029 /**
1030 * This class is only used in link_intrastage_shaders() below but declaring
1031 * it inside that function leads to compiler warnings with some versions of
1032 * gcc.
1033 */
1034 class array_sizing_visitor : public ir_hierarchical_visitor {
1035 public:
1036 array_sizing_visitor()
1037 : mem_ctx(ralloc_context(NULL)),
1038 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1039 hash_table_pointer_compare))
1040 {
1041 }
1042
1043 ~array_sizing_visitor()
1044 {
1045 hash_table_dtor(this->unnamed_interfaces);
1046 ralloc_free(this->mem_ctx);
1047 }
1048
1049 virtual ir_visitor_status visit(ir_variable *var)
1050 {
1051 fixup_type(&var->type, var->max_array_access);
1052 if (var->type->is_interface()) {
1053 if (interface_contains_unsized_arrays(var->type)) {
1054 const glsl_type *new_type =
1055 resize_interface_members(var->type, var->max_ifc_array_access);
1056 var->type = new_type;
1057 var->change_interface_type(new_type);
1058 }
1059 } else if (var->type->is_array() &&
1060 var->type->fields.array->is_interface()) {
1061 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1062 const glsl_type *new_type =
1063 resize_interface_members(var->type->fields.array,
1064 var->max_ifc_array_access);
1065 var->change_interface_type(new_type);
1066 var->type =
1067 glsl_type::get_array_instance(new_type, var->type->length);
1068 }
1069 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1070 /* Store a pointer to the variable in the unnamed_interfaces
1071 * hashtable.
1072 */
1073 ir_variable **interface_vars = (ir_variable **)
1074 hash_table_find(this->unnamed_interfaces, ifc_type);
1075 if (interface_vars == NULL) {
1076 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1077 ifc_type->length);
1078 hash_table_insert(this->unnamed_interfaces, interface_vars,
1079 ifc_type);
1080 }
1081 unsigned index = ifc_type->field_index(var->name);
1082 assert(index < ifc_type->length);
1083 assert(interface_vars[index] == NULL);
1084 interface_vars[index] = var;
1085 }
1086 return visit_continue;
1087 }
1088
1089 /**
1090 * For each unnamed interface block that was discovered while running the
1091 * visitor, adjust the interface type to reflect the newly assigned array
1092 * sizes, and fix up the ir_variable nodes to point to the new interface
1093 * type.
1094 */
1095 void fixup_unnamed_interface_types()
1096 {
1097 hash_table_call_foreach(this->unnamed_interfaces,
1098 fixup_unnamed_interface_type, NULL);
1099 }
1100
1101 private:
1102 /**
1103 * If the type pointed to by \c type represents an unsized array, replace
1104 * it with a sized array whose size is determined by max_array_access.
1105 */
1106 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1107 {
1108 if ((*type)->is_array() && (*type)->length == 0) {
1109 *type = glsl_type::get_array_instance((*type)->fields.array,
1110 max_array_access + 1);
1111 assert(*type != NULL);
1112 }
1113 }
1114
1115 /**
1116 * Determine whether the given interface type contains unsized arrays (if
1117 * it doesn't, array_sizing_visitor doesn't need to process it).
1118 */
1119 static bool interface_contains_unsized_arrays(const glsl_type *type)
1120 {
1121 for (unsigned i = 0; i < type->length; i++) {
1122 const glsl_type *elem_type = type->fields.structure[i].type;
1123 if (elem_type->is_array() && elem_type->length == 0)
1124 return true;
1125 }
1126 return false;
1127 }
1128
1129 /**
1130 * Create a new interface type based on the given type, with unsized arrays
1131 * replaced by sized arrays whose size is determined by
1132 * max_ifc_array_access.
1133 */
1134 static const glsl_type *
1135 resize_interface_members(const glsl_type *type,
1136 const unsigned *max_ifc_array_access)
1137 {
1138 unsigned num_fields = type->length;
1139 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1140 memcpy(fields, type->fields.structure,
1141 num_fields * sizeof(*fields));
1142 for (unsigned i = 0; i < num_fields; i++) {
1143 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1144 }
1145 glsl_interface_packing packing =
1146 (glsl_interface_packing) type->interface_packing;
1147 const glsl_type *new_ifc_type =
1148 glsl_type::get_interface_instance(fields, num_fields,
1149 packing, type->name);
1150 delete [] fields;
1151 return new_ifc_type;
1152 }
1153
1154 static void fixup_unnamed_interface_type(const void *key, void *data,
1155 void *)
1156 {
1157 const glsl_type *ifc_type = (const glsl_type *) key;
1158 ir_variable **interface_vars = (ir_variable **) data;
1159 unsigned num_fields = ifc_type->length;
1160 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1161 memcpy(fields, ifc_type->fields.structure,
1162 num_fields * sizeof(*fields));
1163 bool interface_type_changed = false;
1164 for (unsigned i = 0; i < num_fields; i++) {
1165 if (interface_vars[i] != NULL &&
1166 fields[i].type != interface_vars[i]->type) {
1167 fields[i].type = interface_vars[i]->type;
1168 interface_type_changed = true;
1169 }
1170 }
1171 if (!interface_type_changed) {
1172 delete [] fields;
1173 return;
1174 }
1175 glsl_interface_packing packing =
1176 (glsl_interface_packing) ifc_type->interface_packing;
1177 const glsl_type *new_ifc_type =
1178 glsl_type::get_interface_instance(fields, num_fields, packing,
1179 ifc_type->name);
1180 delete [] fields;
1181 for (unsigned i = 0; i < num_fields; i++) {
1182 if (interface_vars[i] != NULL)
1183 interface_vars[i]->change_interface_type(new_ifc_type);
1184 }
1185 }
1186
1187 /**
1188 * Memory context used to allocate the data in \c unnamed_interfaces.
1189 */
1190 void *mem_ctx;
1191
1192 /**
1193 * Hash table from const glsl_type * to an array of ir_variable *'s
1194 * pointing to the ir_variables constituting each unnamed interface block.
1195 */
1196 hash_table *unnamed_interfaces;
1197 };
1198
1199 /**
1200 * Performs the cross-validation of geometry shader max_vertices and
1201 * primitive type layout qualifiers for the attached geometry shaders,
1202 * and propagates them to the linked GS and linked shader program.
1203 */
1204 static void
1205 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1206 struct gl_shader *linked_shader,
1207 struct gl_shader **shader_list,
1208 unsigned num_shaders)
1209 {
1210 linked_shader->Geom.VerticesOut = 0;
1211 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1212 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1213
1214 /* No in/out qualifiers defined for anything but GLSL 1.50+
1215 * geometry shaders so far.
1216 */
1217 if (linked_shader->Type != GL_GEOMETRY_SHADER || prog->Version < 150)
1218 return;
1219
1220 /* From the GLSL 1.50 spec, page 46:
1221 *
1222 * "All geometry shader output layout declarations in a program
1223 * must declare the same layout and same value for
1224 * max_vertices. There must be at least one geometry output
1225 * layout declaration somewhere in a program, but not all
1226 * geometry shaders (compilation units) are required to
1227 * declare it."
1228 */
1229
1230 for (unsigned i = 0; i < num_shaders; i++) {
1231 struct gl_shader *shader = shader_list[i];
1232
1233 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1234 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1235 linked_shader->Geom.InputType != shader->Geom.InputType) {
1236 linker_error(prog, "geometry shader defined with conflicting "
1237 "input types\n");
1238 return;
1239 }
1240 linked_shader->Geom.InputType = shader->Geom.InputType;
1241 }
1242
1243 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1244 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1245 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1246 linker_error(prog, "geometry shader defined with conflicting "
1247 "output types\n");
1248 return;
1249 }
1250 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1251 }
1252
1253 if (shader->Geom.VerticesOut != 0) {
1254 if (linked_shader->Geom.VerticesOut != 0 &&
1255 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1256 linker_error(prog, "geometry shader defined with conflicting "
1257 "output vertex count (%d and %d)\n",
1258 linked_shader->Geom.VerticesOut,
1259 shader->Geom.VerticesOut);
1260 return;
1261 }
1262 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1263 }
1264 }
1265
1266 /* Just do the intrastage -> interstage propagation right now,
1267 * since we already know we're in the right type of shader program
1268 * for doing it.
1269 */
1270 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1271 linker_error(prog,
1272 "geometry shader didn't declare primitive input type\n");
1273 return;
1274 }
1275 prog->Geom.InputType = linked_shader->Geom.InputType;
1276
1277 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1278 linker_error(prog,
1279 "geometry shader didn't declare primitive output type\n");
1280 return;
1281 }
1282 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1283
1284 if (linked_shader->Geom.VerticesOut == 0) {
1285 linker_error(prog,
1286 "geometry shader didn't declare max_vertices\n");
1287 return;
1288 }
1289 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1290 }
1291
1292 /**
1293 * Combine a group of shaders for a single stage to generate a linked shader
1294 *
1295 * \note
1296 * If this function is supplied a single shader, it is cloned, and the new
1297 * shader is returned.
1298 */
1299 static struct gl_shader *
1300 link_intrastage_shaders(void *mem_ctx,
1301 struct gl_context *ctx,
1302 struct gl_shader_program *prog,
1303 struct gl_shader **shader_list,
1304 unsigned num_shaders)
1305 {
1306 struct gl_uniform_block *uniform_blocks = NULL;
1307
1308 /* Check that global variables defined in multiple shaders are consistent.
1309 */
1310 cross_validate_globals(prog, shader_list, num_shaders, false);
1311 if (!prog->LinkStatus)
1312 return NULL;
1313
1314 /* Check that interface blocks defined in multiple shaders are consistent.
1315 */
1316 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1317 num_shaders);
1318 if (!prog->LinkStatus)
1319 return NULL;
1320
1321 /* Link up uniform blocks defined within this stage. */
1322 const unsigned num_uniform_blocks =
1323 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1324 &uniform_blocks);
1325
1326 /* Check that there is only a single definition of each function signature
1327 * across all shaders.
1328 */
1329 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1330 foreach_list(node, shader_list[i]->ir) {
1331 ir_function *const f = ((ir_instruction *) node)->as_function();
1332
1333 if (f == NULL)
1334 continue;
1335
1336 for (unsigned j = i + 1; j < num_shaders; j++) {
1337 ir_function *const other =
1338 shader_list[j]->symbols->get_function(f->name);
1339
1340 /* If the other shader has no function (and therefore no function
1341 * signatures) with the same name, skip to the next shader.
1342 */
1343 if (other == NULL)
1344 continue;
1345
1346 foreach_iter (exec_list_iterator, iter, *f) {
1347 ir_function_signature *sig =
1348 (ir_function_signature *) iter.get();
1349
1350 if (!sig->is_defined || sig->is_builtin())
1351 continue;
1352
1353 ir_function_signature *other_sig =
1354 other->exact_matching_signature(NULL, &sig->parameters);
1355
1356 if ((other_sig != NULL) && other_sig->is_defined
1357 && !other_sig->is_builtin()) {
1358 linker_error(prog, "function `%s' is multiply defined",
1359 f->name);
1360 return NULL;
1361 }
1362 }
1363 }
1364 }
1365 }
1366
1367 /* Find the shader that defines main, and make a clone of it.
1368 *
1369 * Starting with the clone, search for undefined references. If one is
1370 * found, find the shader that defines it. Clone the reference and add
1371 * it to the shader. Repeat until there are no undefined references or
1372 * until a reference cannot be resolved.
1373 */
1374 gl_shader *main = NULL;
1375 for (unsigned i = 0; i < num_shaders; i++) {
1376 if (get_main_function_signature(shader_list[i]) != NULL) {
1377 main = shader_list[i];
1378 break;
1379 }
1380 }
1381
1382 if (main == NULL) {
1383 linker_error(prog, "%s shader lacks `main'\n",
1384 _mesa_glsl_shader_target_name(shader_list[0]->Type));
1385 return NULL;
1386 }
1387
1388 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1389 linked->ir = new(linked) exec_list;
1390 clone_ir_list(mem_ctx, linked->ir, main->ir);
1391
1392 linked->UniformBlocks = uniform_blocks;
1393 linked->NumUniformBlocks = num_uniform_blocks;
1394 ralloc_steal(linked, linked->UniformBlocks);
1395
1396 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
1397
1398 populate_symbol_table(linked);
1399
1400 /* The a pointer to the main function in the final linked shader (i.e., the
1401 * copy of the original shader that contained the main function).
1402 */
1403 ir_function_signature *const main_sig = get_main_function_signature(linked);
1404
1405 /* Move any instructions other than variable declarations or function
1406 * declarations into main.
1407 */
1408 exec_node *insertion_point =
1409 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1410 linked);
1411
1412 for (unsigned i = 0; i < num_shaders; i++) {
1413 if (shader_list[i] == main)
1414 continue;
1415
1416 insertion_point = move_non_declarations(shader_list[i]->ir,
1417 insertion_point, true, linked);
1418 }
1419
1420 /* Resolve initializers for global variables in the linked shader.
1421 */
1422 unsigned num_linking_shaders = num_shaders;
1423 for (unsigned i = 0; i < num_shaders; i++)
1424 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1425
1426 gl_shader **linking_shaders =
1427 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1428
1429 memcpy(linking_shaders, shader_list,
1430 sizeof(linking_shaders[0]) * num_shaders);
1431
1432 unsigned idx = num_shaders;
1433 for (unsigned i = 0; i < num_shaders; i++) {
1434 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1435 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1436 idx += shader_list[i]->num_builtins_to_link;
1437 }
1438
1439 assert(idx == num_linking_shaders);
1440
1441 if (!link_function_calls(prog, linked, linking_shaders,
1442 num_linking_shaders)) {
1443 ctx->Driver.DeleteShader(ctx, linked);
1444 free(linking_shaders);
1445 return NULL;
1446 }
1447
1448 free(linking_shaders);
1449
1450 /* At this point linked should contain all of the linked IR, so
1451 * validate it to make sure nothing went wrong.
1452 */
1453 validate_ir_tree(linked->ir);
1454
1455 /* Set the size of geometry shader input arrays */
1456 if (linked->Type == GL_GEOMETRY_SHADER) {
1457 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
1458 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
1459 foreach_iter(exec_list_iterator, iter, *linked->ir) {
1460 ir_instruction *ir = (ir_instruction *)iter.get();
1461 ir->accept(&input_resize_visitor);
1462 }
1463 }
1464
1465 /* Make a pass over all variable declarations to ensure that arrays with
1466 * unspecified sizes have a size specified. The size is inferred from the
1467 * max_array_access field.
1468 */
1469 array_sizing_visitor v;
1470 v.run(linked->ir);
1471 v.fixup_unnamed_interface_types();
1472
1473 return linked;
1474 }
1475
1476 /**
1477 * Update the sizes of linked shader uniform arrays to the maximum
1478 * array index used.
1479 *
1480 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1481 *
1482 * If one or more elements of an array are active,
1483 * GetActiveUniform will return the name of the array in name,
1484 * subject to the restrictions listed above. The type of the array
1485 * is returned in type. The size parameter contains the highest
1486 * array element index used, plus one. The compiler or linker
1487 * determines the highest index used. There will be only one
1488 * active uniform reported by the GL per uniform array.
1489
1490 */
1491 static void
1492 update_array_sizes(struct gl_shader_program *prog)
1493 {
1494 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1495 if (prog->_LinkedShaders[i] == NULL)
1496 continue;
1497
1498 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1499 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1500
1501 if ((var == NULL) || (var->mode != ir_var_uniform) ||
1502 !var->type->is_array())
1503 continue;
1504
1505 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1506 * will not be eliminated. Since we always do std140, just
1507 * don't resize arrays in UBOs.
1508 */
1509 if (var->is_in_uniform_block())
1510 continue;
1511
1512 unsigned int size = var->max_array_access;
1513 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1514 if (prog->_LinkedShaders[j] == NULL)
1515 continue;
1516
1517 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1518 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1519 if (!other_var)
1520 continue;
1521
1522 if (strcmp(var->name, other_var->name) == 0 &&
1523 other_var->max_array_access > size) {
1524 size = other_var->max_array_access;
1525 }
1526 }
1527 }
1528
1529 if (size + 1 != var->type->length) {
1530 /* If this is a built-in uniform (i.e., it's backed by some
1531 * fixed-function state), adjust the number of state slots to
1532 * match the new array size. The number of slots per array entry
1533 * is not known. It seems safe to assume that the total number of
1534 * slots is an integer multiple of the number of array elements.
1535 * Determine the number of slots per array element by dividing by
1536 * the old (total) size.
1537 */
1538 if (var->num_state_slots > 0) {
1539 var->num_state_slots = (size + 1)
1540 * (var->num_state_slots / var->type->length);
1541 }
1542
1543 var->type = glsl_type::get_array_instance(var->type->fields.array,
1544 size + 1);
1545 /* FINISHME: We should update the types of array
1546 * dereferences of this variable now.
1547 */
1548 }
1549 }
1550 }
1551 }
1552
1553 /**
1554 * Find a contiguous set of available bits in a bitmask.
1555 *
1556 * \param used_mask Bits representing used (1) and unused (0) locations
1557 * \param needed_count Number of contiguous bits needed.
1558 *
1559 * \return
1560 * Base location of the available bits on success or -1 on failure.
1561 */
1562 int
1563 find_available_slots(unsigned used_mask, unsigned needed_count)
1564 {
1565 unsigned needed_mask = (1 << needed_count) - 1;
1566 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1567
1568 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1569 * cannot optimize possibly infinite loops" for the loop below.
1570 */
1571 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1572 return -1;
1573
1574 for (int i = 0; i <= max_bit_to_test; i++) {
1575 if ((needed_mask & ~used_mask) == needed_mask)
1576 return i;
1577
1578 needed_mask <<= 1;
1579 }
1580
1581 return -1;
1582 }
1583
1584
1585 /**
1586 * Assign locations for either VS inputs for FS outputs
1587 *
1588 * \param prog Shader program whose variables need locations assigned
1589 * \param target_index Selector for the program target to receive location
1590 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1591 * \c MESA_SHADER_FRAGMENT.
1592 * \param max_index Maximum number of generic locations. This corresponds
1593 * to either the maximum number of draw buffers or the
1594 * maximum number of generic attributes.
1595 *
1596 * \return
1597 * If locations are successfully assigned, true is returned. Otherwise an
1598 * error is emitted to the shader link log and false is returned.
1599 */
1600 bool
1601 assign_attribute_or_color_locations(gl_shader_program *prog,
1602 unsigned target_index,
1603 unsigned max_index)
1604 {
1605 /* Mark invalid locations as being used.
1606 */
1607 unsigned used_locations = (max_index >= 32)
1608 ? ~0 : ~((1 << max_index) - 1);
1609
1610 assert((target_index == MESA_SHADER_VERTEX)
1611 || (target_index == MESA_SHADER_FRAGMENT));
1612
1613 gl_shader *const sh = prog->_LinkedShaders[target_index];
1614 if (sh == NULL)
1615 return true;
1616
1617 /* Operate in a total of four passes.
1618 *
1619 * 1. Invalidate the location assignments for all vertex shader inputs.
1620 *
1621 * 2. Assign locations for inputs that have user-defined (via
1622 * glBindVertexAttribLocation) locations and outputs that have
1623 * user-defined locations (via glBindFragDataLocation).
1624 *
1625 * 3. Sort the attributes without assigned locations by number of slots
1626 * required in decreasing order. Fragmentation caused by attribute
1627 * locations assigned by the application may prevent large attributes
1628 * from having enough contiguous space.
1629 *
1630 * 4. Assign locations to any inputs without assigned locations.
1631 */
1632
1633 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1634 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1635
1636 const enum ir_variable_mode direction =
1637 (target_index == MESA_SHADER_VERTEX)
1638 ? ir_var_shader_in : ir_var_shader_out;
1639
1640
1641 /* Temporary storage for the set of attributes that need locations assigned.
1642 */
1643 struct temp_attr {
1644 unsigned slots;
1645 ir_variable *var;
1646
1647 /* Used below in the call to qsort. */
1648 static int compare(const void *a, const void *b)
1649 {
1650 const temp_attr *const l = (const temp_attr *) a;
1651 const temp_attr *const r = (const temp_attr *) b;
1652
1653 /* Reversed because we want a descending order sort below. */
1654 return r->slots - l->slots;
1655 }
1656 } to_assign[16];
1657
1658 unsigned num_attr = 0;
1659
1660 foreach_list(node, sh->ir) {
1661 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1662
1663 if ((var == NULL) || (var->mode != (unsigned) direction))
1664 continue;
1665
1666 if (var->explicit_location) {
1667 if ((var->location >= (int)(max_index + generic_base))
1668 || (var->location < 0)) {
1669 linker_error(prog,
1670 "invalid explicit location %d specified for `%s'\n",
1671 (var->location < 0)
1672 ? var->location : var->location - generic_base,
1673 var->name);
1674 return false;
1675 }
1676 } else if (target_index == MESA_SHADER_VERTEX) {
1677 unsigned binding;
1678
1679 if (prog->AttributeBindings->get(binding, var->name)) {
1680 assert(binding >= VERT_ATTRIB_GENERIC0);
1681 var->location = binding;
1682 var->is_unmatched_generic_inout = 0;
1683 }
1684 } else if (target_index == MESA_SHADER_FRAGMENT) {
1685 unsigned binding;
1686 unsigned index;
1687
1688 if (prog->FragDataBindings->get(binding, var->name)) {
1689 assert(binding >= FRAG_RESULT_DATA0);
1690 var->location = binding;
1691 var->is_unmatched_generic_inout = 0;
1692
1693 if (prog->FragDataIndexBindings->get(index, var->name)) {
1694 var->index = index;
1695 }
1696 }
1697 }
1698
1699 /* If the variable is not a built-in and has a location statically
1700 * assigned in the shader (presumably via a layout qualifier), make sure
1701 * that it doesn't collide with other assigned locations. Otherwise,
1702 * add it to the list of variables that need linker-assigned locations.
1703 */
1704 const unsigned slots = var->type->count_attribute_slots();
1705 if (var->location != -1) {
1706 if (var->location >= generic_base && var->index < 1) {
1707 /* From page 61 of the OpenGL 4.0 spec:
1708 *
1709 * "LinkProgram will fail if the attribute bindings assigned
1710 * by BindAttribLocation do not leave not enough space to
1711 * assign a location for an active matrix attribute or an
1712 * active attribute array, both of which require multiple
1713 * contiguous generic attributes."
1714 *
1715 * Previous versions of the spec contain similar language but omit
1716 * the bit about attribute arrays.
1717 *
1718 * Page 61 of the OpenGL 4.0 spec also says:
1719 *
1720 * "It is possible for an application to bind more than one
1721 * attribute name to the same location. This is referred to as
1722 * aliasing. This will only work if only one of the aliased
1723 * attributes is active in the executable program, or if no
1724 * path through the shader consumes more than one attribute of
1725 * a set of attributes aliased to the same location. A link
1726 * error can occur if the linker determines that every path
1727 * through the shader consumes multiple aliased attributes,
1728 * but implementations are not required to generate an error
1729 * in this case."
1730 *
1731 * These two paragraphs are either somewhat contradictory, or I
1732 * don't fully understand one or both of them.
1733 */
1734 /* FINISHME: The code as currently written does not support
1735 * FINISHME: attribute location aliasing (see comment above).
1736 */
1737 /* Mask representing the contiguous slots that will be used by
1738 * this attribute.
1739 */
1740 const unsigned attr = var->location - generic_base;
1741 const unsigned use_mask = (1 << slots) - 1;
1742
1743 /* Generate a link error if the set of bits requested for this
1744 * attribute overlaps any previously allocated bits.
1745 */
1746 if ((~(use_mask << attr) & used_locations) != used_locations) {
1747 const char *const string = (target_index == MESA_SHADER_VERTEX)
1748 ? "vertex shader input" : "fragment shader output";
1749 linker_error(prog,
1750 "insufficient contiguous locations "
1751 "available for %s `%s' %d %d %d", string,
1752 var->name, used_locations, use_mask, attr);
1753 return false;
1754 }
1755
1756 used_locations |= (use_mask << attr);
1757 }
1758
1759 continue;
1760 }
1761
1762 to_assign[num_attr].slots = slots;
1763 to_assign[num_attr].var = var;
1764 num_attr++;
1765 }
1766
1767 /* If all of the attributes were assigned locations by the application (or
1768 * are built-in attributes with fixed locations), return early. This should
1769 * be the common case.
1770 */
1771 if (num_attr == 0)
1772 return true;
1773
1774 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1775
1776 if (target_index == MESA_SHADER_VERTEX) {
1777 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1778 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1779 * reserved to prevent it from being automatically allocated below.
1780 */
1781 find_deref_visitor find("gl_Vertex");
1782 find.run(sh->ir);
1783 if (find.variable_found())
1784 used_locations |= (1 << 0);
1785 }
1786
1787 for (unsigned i = 0; i < num_attr; i++) {
1788 /* Mask representing the contiguous slots that will be used by this
1789 * attribute.
1790 */
1791 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1792
1793 int location = find_available_slots(used_locations, to_assign[i].slots);
1794
1795 if (location < 0) {
1796 const char *const string = (target_index == MESA_SHADER_VERTEX)
1797 ? "vertex shader input" : "fragment shader output";
1798
1799 linker_error(prog,
1800 "insufficient contiguous locations "
1801 "available for %s `%s'",
1802 string, to_assign[i].var->name);
1803 return false;
1804 }
1805
1806 to_assign[i].var->location = generic_base + location;
1807 to_assign[i].var->is_unmatched_generic_inout = 0;
1808 used_locations |= (use_mask << location);
1809 }
1810
1811 return true;
1812 }
1813
1814
1815 /**
1816 * Demote shader inputs and outputs that are not used in other stages
1817 */
1818 void
1819 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1820 {
1821 foreach_list(node, sh->ir) {
1822 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1823
1824 if ((var == NULL) || (var->mode != int(mode)))
1825 continue;
1826
1827 /* A shader 'in' or 'out' variable is only really an input or output if
1828 * its value is used by other shader stages. This will cause the variable
1829 * to have a location assigned.
1830 */
1831 if (var->is_unmatched_generic_inout) {
1832 var->mode = ir_var_auto;
1833 }
1834 }
1835 }
1836
1837
1838 /**
1839 * Store the gl_FragDepth layout in the gl_shader_program struct.
1840 */
1841 static void
1842 store_fragdepth_layout(struct gl_shader_program *prog)
1843 {
1844 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
1845 return;
1846 }
1847
1848 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
1849
1850 /* We don't look up the gl_FragDepth symbol directly because if
1851 * gl_FragDepth is not used in the shader, it's removed from the IR.
1852 * However, the symbol won't be removed from the symbol table.
1853 *
1854 * We're only interested in the cases where the variable is NOT removed
1855 * from the IR.
1856 */
1857 foreach_list(node, ir) {
1858 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1859
1860 if (var == NULL || var->mode != ir_var_shader_out) {
1861 continue;
1862 }
1863
1864 if (strcmp(var->name, "gl_FragDepth") == 0) {
1865 switch (var->depth_layout) {
1866 case ir_depth_layout_none:
1867 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
1868 return;
1869 case ir_depth_layout_any:
1870 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
1871 return;
1872 case ir_depth_layout_greater:
1873 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
1874 return;
1875 case ir_depth_layout_less:
1876 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
1877 return;
1878 case ir_depth_layout_unchanged:
1879 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
1880 return;
1881 default:
1882 assert(0);
1883 return;
1884 }
1885 }
1886 }
1887 }
1888
1889 /**
1890 * Validate the resources used by a program versus the implementation limits
1891 */
1892 static void
1893 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
1894 {
1895 static const char *const shader_names[MESA_SHADER_TYPES] = {
1896 "vertex", "geometry", "fragment"
1897 };
1898
1899 const unsigned max_samplers[MESA_SHADER_TYPES] = {
1900 ctx->Const.VertexProgram.MaxTextureImageUnits,
1901 ctx->Const.GeometryProgram.MaxTextureImageUnits,
1902 ctx->Const.FragmentProgram.MaxTextureImageUnits
1903 };
1904
1905 const unsigned max_default_uniform_components[MESA_SHADER_TYPES] = {
1906 ctx->Const.VertexProgram.MaxUniformComponents,
1907 ctx->Const.GeometryProgram.MaxUniformComponents,
1908 ctx->Const.FragmentProgram.MaxUniformComponents
1909 };
1910
1911 const unsigned max_combined_uniform_components[MESA_SHADER_TYPES] = {
1912 ctx->Const.VertexProgram.MaxCombinedUniformComponents,
1913 ctx->Const.GeometryProgram.MaxCombinedUniformComponents,
1914 ctx->Const.FragmentProgram.MaxCombinedUniformComponents
1915 };
1916
1917 const unsigned max_uniform_blocks[MESA_SHADER_TYPES] = {
1918 ctx->Const.VertexProgram.MaxUniformBlocks,
1919 ctx->Const.GeometryProgram.MaxUniformBlocks,
1920 ctx->Const.FragmentProgram.MaxUniformBlocks
1921 };
1922
1923 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1924 struct gl_shader *sh = prog->_LinkedShaders[i];
1925
1926 if (sh == NULL)
1927 continue;
1928
1929 if (sh->num_samplers > max_samplers[i]) {
1930 linker_error(prog, "Too many %s shader texture samplers",
1931 shader_names[i]);
1932 }
1933
1934 if (sh->num_uniform_components > max_default_uniform_components[i]) {
1935 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
1936 linker_warning(prog, "Too many %s shader default uniform block "
1937 "components, but the driver will try to optimize "
1938 "them out; this is non-portable out-of-spec "
1939 "behavior\n",
1940 shader_names[i]);
1941 } else {
1942 linker_error(prog, "Too many %s shader default uniform block "
1943 "components",
1944 shader_names[i]);
1945 }
1946 }
1947
1948 if (sh->num_combined_uniform_components >
1949 max_combined_uniform_components[i]) {
1950 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
1951 linker_warning(prog, "Too many %s shader uniform components, "
1952 "but the driver will try to optimize them out; "
1953 "this is non-portable out-of-spec behavior\n",
1954 shader_names[i]);
1955 } else {
1956 linker_error(prog, "Too many %s shader uniform components",
1957 shader_names[i]);
1958 }
1959 }
1960 }
1961
1962 unsigned blocks[MESA_SHADER_TYPES] = {0};
1963 unsigned total_uniform_blocks = 0;
1964
1965 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
1966 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1967 if (prog->UniformBlockStageIndex[j][i] != -1) {
1968 blocks[j]++;
1969 total_uniform_blocks++;
1970 }
1971 }
1972
1973 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
1974 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
1975 prog->NumUniformBlocks,
1976 ctx->Const.MaxCombinedUniformBlocks);
1977 } else {
1978 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1979 if (blocks[i] > max_uniform_blocks[i]) {
1980 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
1981 shader_names[i],
1982 blocks[i],
1983 max_uniform_blocks[i]);
1984 break;
1985 }
1986 }
1987 }
1988 }
1989 }
1990
1991 void
1992 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
1993 {
1994 tfeedback_decl *tfeedback_decls = NULL;
1995 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
1996
1997 void *mem_ctx = ralloc_context(NULL); // temporary linker context
1998
1999 prog->LinkStatus = true; /* All error paths will set this to false */
2000 prog->Validated = false;
2001 prog->_Used = false;
2002
2003 ralloc_free(prog->InfoLog);
2004 prog->InfoLog = ralloc_strdup(NULL, "");
2005
2006 ralloc_free(prog->UniformBlocks);
2007 prog->UniformBlocks = NULL;
2008 prog->NumUniformBlocks = 0;
2009 for (int i = 0; i < MESA_SHADER_TYPES; i++) {
2010 ralloc_free(prog->UniformBlockStageIndex[i]);
2011 prog->UniformBlockStageIndex[i] = NULL;
2012 }
2013
2014 /* Separate the shaders into groups based on their type.
2015 */
2016 struct gl_shader **vert_shader_list;
2017 unsigned num_vert_shaders = 0;
2018 struct gl_shader **frag_shader_list;
2019 unsigned num_frag_shaders = 0;
2020 struct gl_shader **geom_shader_list;
2021 unsigned num_geom_shaders = 0;
2022
2023 vert_shader_list = (struct gl_shader **)
2024 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2025 frag_shader_list = (struct gl_shader **)
2026 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2027 geom_shader_list = (struct gl_shader **)
2028 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2029
2030 unsigned min_version = UINT_MAX;
2031 unsigned max_version = 0;
2032 const bool is_es_prog =
2033 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
2034 for (unsigned i = 0; i < prog->NumShaders; i++) {
2035 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2036 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2037
2038 if (prog->Shaders[i]->IsES != is_es_prog) {
2039 linker_error(prog, "all shaders must use same shading "
2040 "language version\n");
2041 goto done;
2042 }
2043
2044 switch (prog->Shaders[i]->Type) {
2045 case GL_VERTEX_SHADER:
2046 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2047 num_vert_shaders++;
2048 break;
2049 case GL_FRAGMENT_SHADER:
2050 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2051 num_frag_shaders++;
2052 break;
2053 case GL_GEOMETRY_SHADER:
2054 geom_shader_list[num_geom_shaders] = prog->Shaders[i];
2055 num_geom_shaders++;
2056 break;
2057 }
2058 }
2059
2060 /* Previous to GLSL version 1.30, different compilation units could mix and
2061 * match shading language versions. With GLSL 1.30 and later, the versions
2062 * of all shaders must match.
2063 *
2064 * GLSL ES has never allowed mixing of shading language versions.
2065 */
2066 if ((is_es_prog || max_version >= 130)
2067 && min_version != max_version) {
2068 linker_error(prog, "all shaders must use same shading "
2069 "language version\n");
2070 goto done;
2071 }
2072
2073 prog->Version = max_version;
2074 prog->IsES = is_es_prog;
2075
2076 /* Geometry shaders have to be linked with vertex shaders.
2077 */
2078 if (num_geom_shaders > 0 && num_vert_shaders == 0) {
2079 linker_error(prog, "Geometry shader must be linked with "
2080 "vertex shader\n");
2081 goto done;
2082 }
2083
2084 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2085 if (prog->_LinkedShaders[i] != NULL)
2086 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2087
2088 prog->_LinkedShaders[i] = NULL;
2089 }
2090
2091 /* Link all shaders for a particular stage and validate the result.
2092 */
2093 if (num_vert_shaders > 0) {
2094 gl_shader *const sh =
2095 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2096 num_vert_shaders);
2097
2098 if (!prog->LinkStatus)
2099 goto done;
2100
2101 validate_vertex_shader_executable(prog, sh);
2102 if (!prog->LinkStatus)
2103 goto done;
2104
2105 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2106 sh);
2107 }
2108
2109 if (num_frag_shaders > 0) {
2110 gl_shader *const sh =
2111 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2112 num_frag_shaders);
2113
2114 if (!prog->LinkStatus)
2115 goto done;
2116
2117 validate_fragment_shader_executable(prog, sh);
2118 if (!prog->LinkStatus)
2119 goto done;
2120
2121 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2122 sh);
2123 }
2124
2125 if (num_geom_shaders > 0) {
2126 gl_shader *const sh =
2127 link_intrastage_shaders(mem_ctx, ctx, prog, geom_shader_list,
2128 num_geom_shaders);
2129
2130 if (!prog->LinkStatus)
2131 goto done;
2132
2133 validate_geometry_shader_executable(prog, sh);
2134 if (!prog->LinkStatus)
2135 goto done;
2136
2137 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_GEOMETRY],
2138 sh);
2139 }
2140
2141 /* Here begins the inter-stage linking phase. Some initial validation is
2142 * performed, then locations are assigned for uniforms, attributes, and
2143 * varyings.
2144 */
2145 cross_validate_uniforms(prog);
2146 if (!prog->LinkStatus)
2147 goto done;
2148
2149 unsigned prev;
2150
2151 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2152 if (prog->_LinkedShaders[prev] != NULL)
2153 break;
2154 }
2155
2156 /* Validate the inputs of each stage with the output of the preceding
2157 * stage.
2158 */
2159 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2160 if (prog->_LinkedShaders[i] == NULL)
2161 continue;
2162
2163 validate_interstage_interface_blocks(prog, prog->_LinkedShaders[prev],
2164 prog->_LinkedShaders[i]);
2165 if (!prog->LinkStatus)
2166 goto done;
2167
2168 cross_validate_outputs_to_inputs(prog,
2169 prog->_LinkedShaders[prev],
2170 prog->_LinkedShaders[i]);
2171 if (!prog->LinkStatus)
2172 goto done;
2173
2174 prev = i;
2175 }
2176
2177
2178 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2179 if (prog->_LinkedShaders[i] != NULL)
2180 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
2181 }
2182
2183 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2184 * it before optimization because we want most of the checks to get
2185 * dropped thanks to constant propagation.
2186 *
2187 * This rule also applies to GLSL ES 3.00.
2188 */
2189 if (max_version >= (is_es_prog ? 300 : 130)) {
2190 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2191 if (sh) {
2192 lower_discard_flow(sh->ir);
2193 }
2194 }
2195
2196 if (!interstage_cross_validate_uniform_blocks(prog))
2197 goto done;
2198
2199 /* Do common optimization before assigning storage for attributes,
2200 * uniforms, and varyings. Later optimization could possibly make
2201 * some of that unused.
2202 */
2203 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2204 if (prog->_LinkedShaders[i] == NULL)
2205 continue;
2206
2207 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2208 if (!prog->LinkStatus)
2209 goto done;
2210
2211 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
2212 lower_clip_distance(prog->_LinkedShaders[i]);
2213 }
2214
2215 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2216
2217 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll, &ctx->ShaderCompilerOptions[i]))
2218 ;
2219 }
2220
2221 /* Mark all generic shader inputs and outputs as unpaired. */
2222 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2223 link_invalidate_variable_locations(
2224 prog->_LinkedShaders[MESA_SHADER_VERTEX],
2225 VERT_ATTRIB_GENERIC0, VARYING_SLOT_VAR0);
2226 }
2227 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2228 link_invalidate_variable_locations(
2229 prog->_LinkedShaders[MESA_SHADER_GEOMETRY],
2230 VARYING_SLOT_VAR0, VARYING_SLOT_VAR0);
2231 }
2232 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2233 link_invalidate_variable_locations(
2234 prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2235 VARYING_SLOT_VAR0, FRAG_RESULT_DATA0);
2236 }
2237
2238 /* FINISHME: The value of the max_attribute_index parameter is
2239 * FINISHME: implementation dependent based on the value of
2240 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2241 * FINISHME: at least 16, so hardcode 16 for now.
2242 */
2243 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2244 goto done;
2245 }
2246
2247 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2248 goto done;
2249 }
2250
2251 unsigned first;
2252 for (first = 0; first < MESA_SHADER_TYPES; first++) {
2253 if (prog->_LinkedShaders[first] != NULL)
2254 break;
2255 }
2256
2257 if (num_tfeedback_decls != 0) {
2258 /* From GL_EXT_transform_feedback:
2259 * A program will fail to link if:
2260 *
2261 * * the <count> specified by TransformFeedbackVaryingsEXT is
2262 * non-zero, but the program object has no vertex or geometry
2263 * shader;
2264 */
2265 if (first == MESA_SHADER_FRAGMENT) {
2266 linker_error(prog, "Transform feedback varyings specified, but "
2267 "no vertex or geometry shader is present.");
2268 goto done;
2269 }
2270
2271 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2272 prog->TransformFeedback.NumVarying);
2273 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2274 prog->TransformFeedback.VaryingNames,
2275 tfeedback_decls))
2276 goto done;
2277 }
2278
2279 /* Linking the stages in the opposite order (from fragment to vertex)
2280 * ensures that inter-shader outputs written to in an earlier stage are
2281 * eliminated if they are (transitively) not used in a later stage.
2282 */
2283 int last, next;
2284 for (last = MESA_SHADER_TYPES-1; last >= 0; last--) {
2285 if (prog->_LinkedShaders[last] != NULL)
2286 break;
2287 }
2288
2289 if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
2290 gl_shader *const sh = prog->_LinkedShaders[last];
2291
2292 if (num_tfeedback_decls != 0) {
2293 /* There was no fragment shader, but we still have to assign varying
2294 * locations for use by transform feedback.
2295 */
2296 if (!assign_varying_locations(ctx, mem_ctx, prog,
2297 sh, NULL,
2298 num_tfeedback_decls, tfeedback_decls,
2299 0))
2300 goto done;
2301 }
2302
2303 do_dead_builtin_varyings(ctx, sh, NULL,
2304 num_tfeedback_decls, tfeedback_decls);
2305
2306 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
2307
2308 /* Eliminate code that is now dead due to unused outputs being demoted.
2309 */
2310 while (do_dead_code(sh->ir, false))
2311 ;
2312 }
2313 else if (first == MESA_SHADER_FRAGMENT) {
2314 /* If the program only contains a fragment shader...
2315 */
2316 gl_shader *const sh = prog->_LinkedShaders[first];
2317
2318 do_dead_builtin_varyings(ctx, NULL, sh,
2319 num_tfeedback_decls, tfeedback_decls);
2320
2321 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
2322
2323 while (do_dead_code(sh->ir, false))
2324 ;
2325 }
2326
2327 next = last;
2328 for (int i = next - 1; i >= 0; i--) {
2329 if (prog->_LinkedShaders[i] == NULL)
2330 continue;
2331
2332 gl_shader *const sh_i = prog->_LinkedShaders[i];
2333 gl_shader *const sh_next = prog->_LinkedShaders[next];
2334 unsigned gs_input_vertices =
2335 next == MESA_SHADER_GEOMETRY ? prog->Geom.VerticesIn : 0;
2336
2337 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2338 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2339 tfeedback_decls, gs_input_vertices))
2340 goto done;
2341
2342 do_dead_builtin_varyings(ctx, sh_i, sh_next,
2343 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2344 tfeedback_decls);
2345
2346 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
2347 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
2348
2349 /* Eliminate code that is now dead due to unused outputs being demoted.
2350 */
2351 while (do_dead_code(sh_i->ir, false))
2352 ;
2353 while (do_dead_code(sh_next->ir, false))
2354 ;
2355
2356 /* This must be done after all dead varyings are eliminated. */
2357 if (!check_against_output_limit(ctx, prog, sh_i))
2358 goto done;
2359 if (!check_against_input_limit(ctx, prog, sh_next))
2360 goto done;
2361
2362 next = i;
2363 }
2364
2365 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2366 goto done;
2367
2368 update_array_sizes(prog);
2369 link_assign_uniform_locations(prog);
2370 store_fragdepth_layout(prog);
2371
2372 check_resources(ctx, prog);
2373 if (!prog->LinkStatus)
2374 goto done;
2375
2376 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2377 * present in a linked program. By checking prog->IsES, we also
2378 * catch the GL_ARB_ES2_compatibility case.
2379 */
2380 if (!prog->InternalSeparateShader &&
2381 (ctx->API == API_OPENGLES2 || prog->IsES)) {
2382 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2383 linker_error(prog, "program lacks a vertex shader\n");
2384 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2385 linker_error(prog, "program lacks a fragment shader\n");
2386 }
2387 }
2388
2389 /* FINISHME: Assign fragment shader output locations. */
2390
2391 done:
2392 free(vert_shader_list);
2393 free(frag_shader_list);
2394 free(geom_shader_list);
2395
2396 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2397 if (prog->_LinkedShaders[i] == NULL)
2398 continue;
2399
2400 /* Retain any live IR, but trash the rest. */
2401 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2402
2403 /* The symbol table in the linked shaders may contain references to
2404 * variables that were removed (e.g., unused uniforms). Since it may
2405 * contain junk, there is no possible valid use. Delete it and set the
2406 * pointer to NULL.
2407 */
2408 delete prog->_LinkedShaders[i]->symbols;
2409 prog->_LinkedShaders[i]->symbols = NULL;
2410 }
2411
2412 ralloc_free(mem_ctx);
2413 }