glsl: check _mesa_hash_table_create return value in link_uniform_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 #include "ir_uniform.h"
78
79 extern "C" {
80 #include "main/shaderobj.h"
81 #include "main/enums.h"
82 }
83
84 void linker_error(gl_shader_program *, const char *, ...);
85
86 namespace {
87
88 /**
89 * Visitor that determines whether or not a variable is ever written.
90 */
91 class find_assignment_visitor : public ir_hierarchical_visitor {
92 public:
93 find_assignment_visitor(const char *name)
94 : name(name), found(false)
95 {
96 /* empty */
97 }
98
99 virtual ir_visitor_status visit_enter(ir_assignment *ir)
100 {
101 ir_variable *const var = ir->lhs->variable_referenced();
102
103 if (strcmp(name, var->name) == 0) {
104 found = true;
105 return visit_stop;
106 }
107
108 return visit_continue_with_parent;
109 }
110
111 virtual ir_visitor_status visit_enter(ir_call *ir)
112 {
113 foreach_two_lists(formal_node, &ir->callee->parameters,
114 actual_node, &ir->actual_parameters) {
115 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
116 ir_variable *sig_param = (ir_variable *) formal_node;
117
118 if (sig_param->data.mode == ir_var_function_out ||
119 sig_param->data.mode == ir_var_function_inout) {
120 ir_variable *var = param_rval->variable_referenced();
121 if (var && strcmp(name, var->name) == 0) {
122 found = true;
123 return visit_stop;
124 }
125 }
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->data.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->data.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->data.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->data.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, "warning: ");
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(exec_list *ir)
370 {
371 foreach_list(node, ir) {
372 ir_variable *const var = ((ir_instruction *) node)->as_variable();
373
374 if (var == NULL)
375 continue;
376
377 /* Only assign locations for variables that lack an explicit location.
378 * Explicit locations are set for all built-in variables, generic vertex
379 * shader inputs (via layout(location=...)), and generic fragment shader
380 * outputs (also via layout(location=...)).
381 */
382 if (!var->data.explicit_location) {
383 var->data.location = -1;
384 var->data.location_frac = 0;
385 }
386
387 /* ir_variable::is_unmatched_generic_inout is used by the linker while
388 * connecting outputs from one stage to inputs of the next stage.
389 *
390 * There are two implicit assumptions here. First, we assume that any
391 * built-in variable (i.e., non-generic in or out) will have
392 * explicit_location set. Second, we assume that any generic in or out
393 * will not have explicit_location set.
394 *
395 * This second assumption will only be valid until
396 * GL_ARB_separate_shader_objects is supported. When that extension is
397 * implemented, this function will need some modifications.
398 */
399 if (!var->data.explicit_location) {
400 var->data.is_unmatched_generic_inout = 1;
401 } else {
402 var->data.is_unmatched_generic_inout = 0;
403 }
404 }
405 }
406
407
408 /**
409 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
410 *
411 * Also check for errors based on incorrect usage of gl_ClipVertex and
412 * gl_ClipDistance.
413 *
414 * Return false if an error was reported.
415 */
416 static void
417 analyze_clip_usage(struct gl_shader_program *prog,
418 struct gl_shader *shader, GLboolean *UsesClipDistance,
419 GLuint *ClipDistanceArraySize)
420 {
421 *ClipDistanceArraySize = 0;
422
423 if (!prog->IsES && prog->Version >= 130) {
424 /* From section 7.1 (Vertex Shader Special Variables) of the
425 * GLSL 1.30 spec:
426 *
427 * "It is an error for a shader to statically write both
428 * gl_ClipVertex and gl_ClipDistance."
429 *
430 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
431 * gl_ClipVertex nor gl_ClipDistance.
432 */
433 find_assignment_visitor clip_vertex("gl_ClipVertex");
434 find_assignment_visitor clip_distance("gl_ClipDistance");
435
436 clip_vertex.run(shader->ir);
437 clip_distance.run(shader->ir);
438 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
439 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
440 "and `gl_ClipDistance'\n",
441 _mesa_shader_stage_to_string(shader->Stage));
442 return;
443 }
444 *UsesClipDistance = clip_distance.variable_found();
445 ir_variable *clip_distance_var =
446 shader->symbols->get_variable("gl_ClipDistance");
447 if (clip_distance_var)
448 *ClipDistanceArraySize = clip_distance_var->type->length;
449 } else {
450 *UsesClipDistance = false;
451 }
452 }
453
454
455 /**
456 * Verify that a vertex shader executable meets all semantic requirements.
457 *
458 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
459 * as a side effect.
460 *
461 * \param shader Vertex shader executable to be verified
462 */
463 void
464 validate_vertex_shader_executable(struct gl_shader_program *prog,
465 struct gl_shader *shader)
466 {
467 if (shader == NULL)
468 return;
469
470 /* From the GLSL 1.10 spec, page 48:
471 *
472 * "The 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. [...] The
476 * variable gl_Position is available only in the vertex
477 * language and is intended for writing the homogeneous vertex
478 * position. All executions of a well-formed vertex shader
479 * executable must write a value into this variable."
480 *
481 * while in GLSL 1.40 this text is changed to:
482 *
483 * "The variable gl_Position is available only in the vertex
484 * language and is intended for writing the homogeneous vertex
485 * position. It can be written at any time during shader
486 * execution. It may also be read back by a vertex shader
487 * after being written. This value will be used by primitive
488 * assembly, clipping, culling, and other fixed functionality
489 * operations, if present, that operate on primitives after
490 * vertex processing has occurred. Its value is undefined if
491 * the vertex shader executable does not write gl_Position."
492 *
493 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
494 * not an error.
495 */
496 if (prog->Version < (prog->IsES ? 300 : 140)) {
497 find_assignment_visitor find("gl_Position");
498 find.run(shader->ir);
499 if (!find.variable_found()) {
500 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
501 return;
502 }
503 }
504
505 analyze_clip_usage(prog, shader, &prog->Vert.UsesClipDistance,
506 &prog->Vert.ClipDistanceArraySize);
507 }
508
509
510 /**
511 * Verify that a fragment shader executable meets all semantic requirements
512 *
513 * \param shader Fragment shader executable to be verified
514 */
515 void
516 validate_fragment_shader_executable(struct gl_shader_program *prog,
517 struct gl_shader *shader)
518 {
519 if (shader == NULL)
520 return;
521
522 find_assignment_visitor frag_color("gl_FragColor");
523 find_assignment_visitor frag_data("gl_FragData");
524
525 frag_color.run(shader->ir);
526 frag_data.run(shader->ir);
527
528 if (frag_color.variable_found() && frag_data.variable_found()) {
529 linker_error(prog, "fragment shader writes to both "
530 "`gl_FragColor' and `gl_FragData'\n");
531 }
532 }
533
534 /**
535 * Verify that a geometry shader executable meets all semantic requirements
536 *
537 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
538 * prog->Geom.ClipDistanceArraySize as a side effect.
539 *
540 * \param shader Geometry shader executable to be verified
541 */
542 void
543 validate_geometry_shader_executable(struct gl_shader_program *prog,
544 struct gl_shader *shader)
545 {
546 if (shader == NULL)
547 return;
548
549 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
550 prog->Geom.VerticesIn = num_vertices;
551
552 analyze_clip_usage(prog, shader, &prog->Geom.UsesClipDistance,
553 &prog->Geom.ClipDistanceArraySize);
554
555 find_end_primitive_visitor end_primitive;
556 end_primitive.run(shader->ir);
557 prog->Geom.UsesEndPrimitive = end_primitive.end_primitive_found();
558 }
559
560
561 /**
562 * Perform validation of global variables used across multiple shaders
563 */
564 void
565 cross_validate_globals(struct gl_shader_program *prog,
566 struct gl_shader **shader_list,
567 unsigned num_shaders,
568 bool uniforms_only)
569 {
570 /* Examine all of the uniforms in all of the shaders and cross validate
571 * them.
572 */
573 glsl_symbol_table variables;
574 for (unsigned i = 0; i < num_shaders; i++) {
575 if (shader_list[i] == NULL)
576 continue;
577
578 foreach_list(node, shader_list[i]->ir) {
579 ir_variable *const var = ((ir_instruction *) node)->as_variable();
580
581 if (var == NULL)
582 continue;
583
584 if (uniforms_only && (var->data.mode != ir_var_uniform))
585 continue;
586
587 /* Don't cross validate temporaries that are at global scope. These
588 * will eventually get pulled into the shaders 'main'.
589 */
590 if (var->data.mode == ir_var_temporary)
591 continue;
592
593 /* If a global with this name has already been seen, verify that the
594 * new instance has the same type. In addition, if the globals have
595 * initializers, the values of the initializers must be the same.
596 */
597 ir_variable *const existing = variables.get_variable(var->name);
598 if (existing != NULL) {
599 if (var->type != existing->type) {
600 /* Consider the types to be "the same" if both types are arrays
601 * of the same type and one of the arrays is implicitly sized.
602 * In addition, set the type of the linked variable to the
603 * explicitly sized array.
604 */
605 if (var->type->is_array()
606 && existing->type->is_array()
607 && (var->type->fields.array == existing->type->fields.array)
608 && ((var->type->length == 0)
609 || (existing->type->length == 0))) {
610 if (var->type->length != 0) {
611 existing->type = var->type;
612 }
613 } else if (var->type->is_record()
614 && existing->type->is_record()
615 && existing->type->record_compare(var->type)) {
616 existing->type = var->type;
617 } else {
618 linker_error(prog, "%s `%s' declared as type "
619 "`%s' and type `%s'\n",
620 mode_string(var),
621 var->name, var->type->name,
622 existing->type->name);
623 return;
624 }
625 }
626
627 if (var->data.explicit_location) {
628 if (existing->data.explicit_location
629 && (var->data.location != existing->data.location)) {
630 linker_error(prog, "explicit locations for %s "
631 "`%s' have differing values\n",
632 mode_string(var), var->name);
633 return;
634 }
635
636 existing->data.location = var->data.location;
637 existing->data.explicit_location = true;
638 }
639
640 /* From the GLSL 4.20 specification:
641 * "A link error will result if two compilation units in a program
642 * specify different integer-constant bindings for the same
643 * opaque-uniform name. However, it is not an error to specify a
644 * binding on some but not all declarations for the same name"
645 */
646 if (var->data.explicit_binding) {
647 if (existing->data.explicit_binding &&
648 var->data.binding != existing->data.binding) {
649 linker_error(prog, "explicit bindings for %s "
650 "`%s' have differing values\n",
651 mode_string(var), var->name);
652 return;
653 }
654
655 existing->data.binding = var->data.binding;
656 existing->data.explicit_binding = true;
657 }
658
659 if (var->type->contains_atomic() &&
660 var->data.atomic.offset != existing->data.atomic.offset) {
661 linker_error(prog, "offset specifications for %s "
662 "`%s' have differing values\n",
663 mode_string(var), var->name);
664 return;
665 }
666
667 /* Validate layout qualifiers for gl_FragDepth.
668 *
669 * From the AMD/ARB_conservative_depth specs:
670 *
671 * "If gl_FragDepth is redeclared in any fragment shader in a
672 * program, it must be redeclared in all fragment shaders in
673 * that program that have static assignments to
674 * gl_FragDepth. All redeclarations of gl_FragDepth in all
675 * fragment shaders in a single program must have the same set
676 * of qualifiers."
677 */
678 if (strcmp(var->name, "gl_FragDepth") == 0) {
679 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
680 bool layout_differs =
681 var->data.depth_layout != existing->data.depth_layout;
682
683 if (layout_declared && layout_differs) {
684 linker_error(prog,
685 "All redeclarations of gl_FragDepth in all "
686 "fragment shaders in a single program must have "
687 "the same set of qualifiers.");
688 }
689
690 if (var->data.used && layout_differs) {
691 linker_error(prog,
692 "If gl_FragDepth is redeclared with a layout "
693 "qualifier in any fragment shader, it must be "
694 "redeclared with the same layout qualifier in "
695 "all fragment shaders that have assignments to "
696 "gl_FragDepth");
697 }
698 }
699
700 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
701 *
702 * "If a shared global has multiple initializers, the
703 * initializers must all be constant expressions, and they
704 * must all have the same value. Otherwise, a link error will
705 * result. (A shared global having only one initializer does
706 * not require that initializer to be a constant expression.)"
707 *
708 * Previous to 4.20 the GLSL spec simply said that initializers
709 * must have the same value. In this case of non-constant
710 * initializers, this was impossible to determine. As a result,
711 * no vendor actually implemented that behavior. The 4.20
712 * behavior matches the implemented behavior of at least one other
713 * vendor, so we'll implement that for all GLSL versions.
714 */
715 if (var->constant_initializer != NULL) {
716 if (existing->constant_initializer != NULL) {
717 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
718 linker_error(prog, "initializers for %s "
719 "`%s' have differing values\n",
720 mode_string(var), var->name);
721 return;
722 }
723 } else {
724 /* If the first-seen instance of a particular uniform did not
725 * have an initializer but a later instance does, copy the
726 * initializer to the version stored in the symbol table.
727 */
728 /* FINISHME: This is wrong. The constant_value field should
729 * FINISHME: not be modified! Imagine a case where a shader
730 * FINISHME: without an initializer is linked in two different
731 * FINISHME: programs with shaders that have differing
732 * FINISHME: initializers. Linking with the first will
733 * FINISHME: modify the shader, and linking with the second
734 * FINISHME: will fail.
735 */
736 existing->constant_initializer =
737 var->constant_initializer->clone(ralloc_parent(existing),
738 NULL);
739 }
740 }
741
742 if (var->data.has_initializer) {
743 if (existing->data.has_initializer
744 && (var->constant_initializer == NULL
745 || existing->constant_initializer == NULL)) {
746 linker_error(prog,
747 "shared global variable `%s' has multiple "
748 "non-constant initializers.\n",
749 var->name);
750 return;
751 }
752
753 /* Some instance had an initializer, so keep track of that. In
754 * this location, all sorts of initializers (constant or
755 * otherwise) will propagate the existence to the variable
756 * stored in the symbol table.
757 */
758 existing->data.has_initializer = true;
759 }
760
761 if (existing->data.invariant != var->data.invariant) {
762 linker_error(prog, "declarations for %s `%s' have "
763 "mismatching invariant qualifiers\n",
764 mode_string(var), var->name);
765 return;
766 }
767 if (existing->data.centroid != var->data.centroid) {
768 linker_error(prog, "declarations for %s `%s' have "
769 "mismatching centroid qualifiers\n",
770 mode_string(var), var->name);
771 return;
772 }
773 if (existing->data.sample != var->data.sample) {
774 linker_error(prog, "declarations for %s `%s` have "
775 "mismatching sample qualifiers\n",
776 mode_string(var), var->name);
777 return;
778 }
779 } else
780 variables.add_variable(var);
781 }
782 }
783 }
784
785
786 /**
787 * Perform validation of uniforms used across multiple shader stages
788 */
789 void
790 cross_validate_uniforms(struct gl_shader_program *prog)
791 {
792 cross_validate_globals(prog, prog->_LinkedShaders,
793 MESA_SHADER_STAGES, true);
794 }
795
796 /**
797 * Accumulates the array of prog->UniformBlocks and checks that all
798 * definitons of blocks agree on their contents.
799 */
800 static bool
801 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
802 {
803 unsigned max_num_uniform_blocks = 0;
804 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
805 if (prog->_LinkedShaders[i])
806 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
807 }
808
809 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
810 struct gl_shader *sh = prog->_LinkedShaders[i];
811
812 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
813 max_num_uniform_blocks);
814 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
815 prog->UniformBlockStageIndex[i][j] = -1;
816
817 if (sh == NULL)
818 continue;
819
820 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
821 int index = link_cross_validate_uniform_block(prog,
822 &prog->UniformBlocks,
823 &prog->NumUniformBlocks,
824 &sh->UniformBlocks[j]);
825
826 if (index == -1) {
827 linker_error(prog, "uniform block `%s' has mismatching definitions",
828 sh->UniformBlocks[j].Name);
829 return false;
830 }
831
832 prog->UniformBlockStageIndex[i][index] = j;
833 }
834 }
835
836 return true;
837 }
838
839
840 /**
841 * Populates a shaders symbol table with all global declarations
842 */
843 static void
844 populate_symbol_table(gl_shader *sh)
845 {
846 sh->symbols = new(sh) glsl_symbol_table;
847
848 foreach_list(node, sh->ir) {
849 ir_instruction *const inst = (ir_instruction *) node;
850 ir_variable *var;
851 ir_function *func;
852
853 if ((func = inst->as_function()) != NULL) {
854 sh->symbols->add_function(func);
855 } else if ((var = inst->as_variable()) != NULL) {
856 sh->symbols->add_variable(var);
857 }
858 }
859 }
860
861
862 /**
863 * Remap variables referenced in an instruction tree
864 *
865 * This is used when instruction trees are cloned from one shader and placed in
866 * another. These trees will contain references to \c ir_variable nodes that
867 * do not exist in the target shader. This function finds these \c ir_variable
868 * references and replaces the references with matching variables in the target
869 * shader.
870 *
871 * If there is no matching variable in the target shader, a clone of the
872 * \c ir_variable is made and added to the target shader. The new variable is
873 * added to \b both the instruction stream and the symbol table.
874 *
875 * \param inst IR tree that is to be processed.
876 * \param symbols Symbol table containing global scope symbols in the
877 * linked shader.
878 * \param instructions Instruction stream where new variable declarations
879 * should be added.
880 */
881 void
882 remap_variables(ir_instruction *inst, struct gl_shader *target,
883 hash_table *temps)
884 {
885 class remap_visitor : public ir_hierarchical_visitor {
886 public:
887 remap_visitor(struct gl_shader *target,
888 hash_table *temps)
889 {
890 this->target = target;
891 this->symbols = target->symbols;
892 this->instructions = target->ir;
893 this->temps = temps;
894 }
895
896 virtual ir_visitor_status visit(ir_dereference_variable *ir)
897 {
898 if (ir->var->data.mode == ir_var_temporary) {
899 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
900
901 assert(var != NULL);
902 ir->var = var;
903 return visit_continue;
904 }
905
906 ir_variable *const existing =
907 this->symbols->get_variable(ir->var->name);
908 if (existing != NULL)
909 ir->var = existing;
910 else {
911 ir_variable *copy = ir->var->clone(this->target, NULL);
912
913 this->symbols->add_variable(copy);
914 this->instructions->push_head(copy);
915 ir->var = copy;
916 }
917
918 return visit_continue;
919 }
920
921 private:
922 struct gl_shader *target;
923 glsl_symbol_table *symbols;
924 exec_list *instructions;
925 hash_table *temps;
926 };
927
928 remap_visitor v(target, temps);
929
930 inst->accept(&v);
931 }
932
933
934 /**
935 * Move non-declarations from one instruction stream to another
936 *
937 * The intended usage pattern of this function is to pass the pointer to the
938 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
939 * pointer) for \c last and \c false for \c make_copies on the first
940 * call. Successive calls pass the return value of the previous call for
941 * \c last and \c true for \c make_copies.
942 *
943 * \param instructions Source instruction stream
944 * \param last Instruction after which new instructions should be
945 * inserted in the target instruction stream
946 * \param make_copies Flag selecting whether instructions in \c instructions
947 * should be copied (via \c ir_instruction::clone) into the
948 * target list or moved.
949 *
950 * \return
951 * The new "last" instruction in the target instruction stream. This pointer
952 * is suitable for use as the \c last parameter of a later call to this
953 * function.
954 */
955 exec_node *
956 move_non_declarations(exec_list *instructions, exec_node *last,
957 bool make_copies, gl_shader *target)
958 {
959 hash_table *temps = NULL;
960
961 if (make_copies)
962 temps = hash_table_ctor(0, hash_table_pointer_hash,
963 hash_table_pointer_compare);
964
965 foreach_list_safe(node, instructions) {
966 ir_instruction *inst = (ir_instruction *) node;
967
968 if (inst->as_function())
969 continue;
970
971 ir_variable *var = inst->as_variable();
972 if ((var != NULL) && (var->data.mode != ir_var_temporary))
973 continue;
974
975 assert(inst->as_assignment()
976 || inst->as_call()
977 || inst->as_if() /* for initializers with the ?: operator */
978 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
979
980 if (make_copies) {
981 inst = inst->clone(target, NULL);
982
983 if (var != NULL)
984 hash_table_insert(temps, inst, var);
985 else
986 remap_variables(inst, target, temps);
987 } else {
988 inst->remove();
989 }
990
991 last->insert_after(inst);
992 last = inst;
993 }
994
995 if (make_copies)
996 hash_table_dtor(temps);
997
998 return last;
999 }
1000
1001 /**
1002 * Get the function signature for main from a shader
1003 */
1004 static ir_function_signature *
1005 get_main_function_signature(gl_shader *sh)
1006 {
1007 ir_function *const f = sh->symbols->get_function("main");
1008 if (f != NULL) {
1009 exec_list void_parameters;
1010
1011 /* Look for the 'void main()' signature and ensure that it's defined.
1012 * This keeps the linker from accidentally pick a shader that just
1013 * contains a prototype for main.
1014 *
1015 * We don't have to check for multiple definitions of main (in multiple
1016 * shaders) because that would have already been caught above.
1017 */
1018 ir_function_signature *sig = f->matching_signature(NULL, &void_parameters);
1019 if ((sig != NULL) && sig->is_defined) {
1020 return sig;
1021 }
1022 }
1023
1024 return NULL;
1025 }
1026
1027
1028 /**
1029 * This class is only used in link_intrastage_shaders() below but declaring
1030 * it inside that function leads to compiler warnings with some versions of
1031 * gcc.
1032 */
1033 class array_sizing_visitor : public ir_hierarchical_visitor {
1034 public:
1035 array_sizing_visitor()
1036 : mem_ctx(ralloc_context(NULL)),
1037 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1038 hash_table_pointer_compare))
1039 {
1040 }
1041
1042 ~array_sizing_visitor()
1043 {
1044 hash_table_dtor(this->unnamed_interfaces);
1045 ralloc_free(this->mem_ctx);
1046 }
1047
1048 virtual ir_visitor_status visit(ir_variable *var)
1049 {
1050 fixup_type(&var->type, var->data.max_array_access);
1051 if (var->type->is_interface()) {
1052 if (interface_contains_unsized_arrays(var->type)) {
1053 const glsl_type *new_type =
1054 resize_interface_members(var->type, var->max_ifc_array_access);
1055 var->type = new_type;
1056 var->change_interface_type(new_type);
1057 }
1058 } else if (var->type->is_array() &&
1059 var->type->fields.array->is_interface()) {
1060 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1061 const glsl_type *new_type =
1062 resize_interface_members(var->type->fields.array,
1063 var->max_ifc_array_access);
1064 var->change_interface_type(new_type);
1065 var->type =
1066 glsl_type::get_array_instance(new_type, var->type->length);
1067 }
1068 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1069 /* Store a pointer to the variable in the unnamed_interfaces
1070 * hashtable.
1071 */
1072 ir_variable **interface_vars = (ir_variable **)
1073 hash_table_find(this->unnamed_interfaces, ifc_type);
1074 if (interface_vars == NULL) {
1075 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1076 ifc_type->length);
1077 hash_table_insert(this->unnamed_interfaces, interface_vars,
1078 ifc_type);
1079 }
1080 unsigned index = ifc_type->field_index(var->name);
1081 assert(index < ifc_type->length);
1082 assert(interface_vars[index] == NULL);
1083 interface_vars[index] = var;
1084 }
1085 return visit_continue;
1086 }
1087
1088 /**
1089 * For each unnamed interface block that was discovered while running the
1090 * visitor, adjust the interface type to reflect the newly assigned array
1091 * sizes, and fix up the ir_variable nodes to point to the new interface
1092 * type.
1093 */
1094 void fixup_unnamed_interface_types()
1095 {
1096 hash_table_call_foreach(this->unnamed_interfaces,
1097 fixup_unnamed_interface_type, NULL);
1098 }
1099
1100 private:
1101 /**
1102 * If the type pointed to by \c type represents an unsized array, replace
1103 * it with a sized array whose size is determined by max_array_access.
1104 */
1105 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1106 {
1107 if ((*type)->is_unsized_array()) {
1108 *type = glsl_type::get_array_instance((*type)->fields.array,
1109 max_array_access + 1);
1110 assert(*type != NULL);
1111 }
1112 }
1113
1114 /**
1115 * Determine whether the given interface type contains unsized arrays (if
1116 * it doesn't, array_sizing_visitor doesn't need to process it).
1117 */
1118 static bool interface_contains_unsized_arrays(const glsl_type *type)
1119 {
1120 for (unsigned i = 0; i < type->length; i++) {
1121 const glsl_type *elem_type = type->fields.structure[i].type;
1122 if (elem_type->is_unsized_array())
1123 return true;
1124 }
1125 return false;
1126 }
1127
1128 /**
1129 * Create a new interface type based on the given type, with unsized arrays
1130 * replaced by sized arrays whose size is determined by
1131 * max_ifc_array_access.
1132 */
1133 static const glsl_type *
1134 resize_interface_members(const glsl_type *type,
1135 const unsigned *max_ifc_array_access)
1136 {
1137 unsigned num_fields = type->length;
1138 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1139 memcpy(fields, type->fields.structure,
1140 num_fields * sizeof(*fields));
1141 for (unsigned i = 0; i < num_fields; i++) {
1142 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1143 }
1144 glsl_interface_packing packing =
1145 (glsl_interface_packing) type->interface_packing;
1146 const glsl_type *new_ifc_type =
1147 glsl_type::get_interface_instance(fields, num_fields,
1148 packing, type->name);
1149 delete [] fields;
1150 return new_ifc_type;
1151 }
1152
1153 static void fixup_unnamed_interface_type(const void *key, void *data,
1154 void *)
1155 {
1156 const glsl_type *ifc_type = (const glsl_type *) key;
1157 ir_variable **interface_vars = (ir_variable **) data;
1158 unsigned num_fields = ifc_type->length;
1159 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1160 memcpy(fields, ifc_type->fields.structure,
1161 num_fields * sizeof(*fields));
1162 bool interface_type_changed = false;
1163 for (unsigned i = 0; i < num_fields; i++) {
1164 if (interface_vars[i] != NULL &&
1165 fields[i].type != interface_vars[i]->type) {
1166 fields[i].type = interface_vars[i]->type;
1167 interface_type_changed = true;
1168 }
1169 }
1170 if (!interface_type_changed) {
1171 delete [] fields;
1172 return;
1173 }
1174 glsl_interface_packing packing =
1175 (glsl_interface_packing) ifc_type->interface_packing;
1176 const glsl_type *new_ifc_type =
1177 glsl_type::get_interface_instance(fields, num_fields, packing,
1178 ifc_type->name);
1179 delete [] fields;
1180 for (unsigned i = 0; i < num_fields; i++) {
1181 if (interface_vars[i] != NULL)
1182 interface_vars[i]->change_interface_type(new_ifc_type);
1183 }
1184 }
1185
1186 /**
1187 * Memory context used to allocate the data in \c unnamed_interfaces.
1188 */
1189 void *mem_ctx;
1190
1191 /**
1192 * Hash table from const glsl_type * to an array of ir_variable *'s
1193 * pointing to the ir_variables constituting each unnamed interface block.
1194 */
1195 hash_table *unnamed_interfaces;
1196 };
1197
1198 /**
1199 * Performs the cross-validation of layout qualifiers specified in
1200 * redeclaration of gl_FragCoord for the attached fragment shaders,
1201 * and propagates them to the linked FS and linked shader program.
1202 */
1203 static void
1204 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1205 struct gl_shader *linked_shader,
1206 struct gl_shader **shader_list,
1207 unsigned num_shaders)
1208 {
1209 linked_shader->redeclares_gl_fragcoord = false;
1210 linked_shader->uses_gl_fragcoord = false;
1211 linked_shader->origin_upper_left = false;
1212 linked_shader->pixel_center_integer = false;
1213
1214 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1215 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1216 return;
1217
1218 for (unsigned i = 0; i < num_shaders; i++) {
1219 struct gl_shader *shader = shader_list[i];
1220 /* From the GLSL 1.50 spec, page 39:
1221 *
1222 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1223 * it must be redeclared in all the fragment shaders in that program
1224 * that have a static use gl_FragCoord."
1225 *
1226 * Exclude the case when one of the 'linked_shader' or 'shader' redeclares
1227 * gl_FragCoord with no layout qualifiers but the other one doesn't
1228 * redeclare it. If we strictly follow GLSL 1.50 spec's language, it
1229 * should be a link error. But, generating link error for this case will
1230 * be a wrong behaviour which spec didn't intend to do and it could also
1231 * break some applications.
1232 */
1233 if ((linked_shader->redeclares_gl_fragcoord
1234 && !shader->redeclares_gl_fragcoord
1235 && shader->uses_gl_fragcoord
1236 && (linked_shader->origin_upper_left
1237 || linked_shader->pixel_center_integer))
1238 || (shader->redeclares_gl_fragcoord
1239 && !linked_shader->redeclares_gl_fragcoord
1240 && linked_shader->uses_gl_fragcoord
1241 && (shader->origin_upper_left
1242 || shader->pixel_center_integer))) {
1243 linker_error(prog, "fragment shader defined with conflicting "
1244 "layout qualifiers for gl_FragCoord\n");
1245 }
1246
1247 /* From the GLSL 1.50 spec, page 39:
1248 *
1249 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1250 * single program must have the same set of qualifiers."
1251 */
1252 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1253 && (shader->origin_upper_left != linked_shader->origin_upper_left
1254 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1255 linker_error(prog, "fragment shader defined with conflicting "
1256 "layout qualifiers for gl_FragCoord\n");
1257 }
1258
1259 /* Update the linked shader state.  Note that uses_gl_fragcoord should
1260 * accumulate the results.  The other values should replace.  If there
1261 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1262 * are already known to be the same.
1263 */
1264 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1265 linked_shader->redeclares_gl_fragcoord =
1266 shader->redeclares_gl_fragcoord;
1267 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1268 || shader->uses_gl_fragcoord;
1269 linked_shader->origin_upper_left = shader->origin_upper_left;
1270 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1271 }
1272 }
1273 }
1274
1275 /**
1276 * Performs the cross-validation of geometry shader max_vertices and
1277 * primitive type layout qualifiers for the attached geometry shaders,
1278 * and propagates them to the linked GS and linked shader program.
1279 */
1280 static void
1281 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1282 struct gl_shader *linked_shader,
1283 struct gl_shader **shader_list,
1284 unsigned num_shaders)
1285 {
1286 linked_shader->Geom.VerticesOut = 0;
1287 linked_shader->Geom.Invocations = 0;
1288 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1289 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1290
1291 /* No in/out qualifiers defined for anything but GLSL 1.50+
1292 * geometry shaders so far.
1293 */
1294 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1295 return;
1296
1297 /* From the GLSL 1.50 spec, page 46:
1298 *
1299 * "All geometry shader output layout declarations in a program
1300 * must declare the same layout and same value for
1301 * max_vertices. There must be at least one geometry output
1302 * layout declaration somewhere in a program, but not all
1303 * geometry shaders (compilation units) are required to
1304 * declare it."
1305 */
1306
1307 for (unsigned i = 0; i < num_shaders; i++) {
1308 struct gl_shader *shader = shader_list[i];
1309
1310 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1311 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1312 linked_shader->Geom.InputType != shader->Geom.InputType) {
1313 linker_error(prog, "geometry shader defined with conflicting "
1314 "input types\n");
1315 return;
1316 }
1317 linked_shader->Geom.InputType = shader->Geom.InputType;
1318 }
1319
1320 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1321 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1322 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1323 linker_error(prog, "geometry shader defined with conflicting "
1324 "output types\n");
1325 return;
1326 }
1327 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1328 }
1329
1330 if (shader->Geom.VerticesOut != 0) {
1331 if (linked_shader->Geom.VerticesOut != 0 &&
1332 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1333 linker_error(prog, "geometry shader defined with conflicting "
1334 "output vertex count (%d and %d)\n",
1335 linked_shader->Geom.VerticesOut,
1336 shader->Geom.VerticesOut);
1337 return;
1338 }
1339 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1340 }
1341
1342 if (shader->Geom.Invocations != 0) {
1343 if (linked_shader->Geom.Invocations != 0 &&
1344 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1345 linker_error(prog, "geometry shader defined with conflicting "
1346 "invocation count (%d and %d)\n",
1347 linked_shader->Geom.Invocations,
1348 shader->Geom.Invocations);
1349 return;
1350 }
1351 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1352 }
1353 }
1354
1355 /* Just do the intrastage -> interstage propagation right now,
1356 * since we already know we're in the right type of shader program
1357 * for doing it.
1358 */
1359 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1360 linker_error(prog,
1361 "geometry shader didn't declare primitive input type\n");
1362 return;
1363 }
1364 prog->Geom.InputType = linked_shader->Geom.InputType;
1365
1366 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1367 linker_error(prog,
1368 "geometry shader didn't declare primitive output type\n");
1369 return;
1370 }
1371 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1372
1373 if (linked_shader->Geom.VerticesOut == 0) {
1374 linker_error(prog,
1375 "geometry shader didn't declare max_vertices\n");
1376 return;
1377 }
1378 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1379
1380 if (linked_shader->Geom.Invocations == 0)
1381 linked_shader->Geom.Invocations = 1;
1382
1383 prog->Geom.Invocations = linked_shader->Geom.Invocations;
1384 }
1385
1386
1387 /**
1388 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1389 * qualifiers for the attached compute shaders, and propagate them to the
1390 * linked CS and linked shader program.
1391 */
1392 static void
1393 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1394 struct gl_shader *linked_shader,
1395 struct gl_shader **shader_list,
1396 unsigned num_shaders)
1397 {
1398 for (int i = 0; i < 3; i++)
1399 linked_shader->Comp.LocalSize[i] = 0;
1400
1401 /* This function is called for all shader stages, but it only has an effect
1402 * for compute shaders.
1403 */
1404 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1405 return;
1406
1407 /* From the ARB_compute_shader spec, in the section describing local size
1408 * declarations:
1409 *
1410 * If multiple compute shaders attached to a single program object
1411 * declare local work-group size, the declarations must be identical;
1412 * otherwise a link-time error results. Furthermore, if a program
1413 * object contains any compute shaders, at least one must contain an
1414 * input layout qualifier specifying the local work sizes of the
1415 * program, or a link-time error will occur.
1416 */
1417 for (unsigned sh = 0; sh < num_shaders; sh++) {
1418 struct gl_shader *shader = shader_list[sh];
1419
1420 if (shader->Comp.LocalSize[0] != 0) {
1421 if (linked_shader->Comp.LocalSize[0] != 0) {
1422 for (int i = 0; i < 3; i++) {
1423 if (linked_shader->Comp.LocalSize[i] !=
1424 shader->Comp.LocalSize[i]) {
1425 linker_error(prog, "compute shader defined with conflicting "
1426 "local sizes\n");
1427 return;
1428 }
1429 }
1430 }
1431 for (int i = 0; i < 3; i++)
1432 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1433 }
1434 }
1435
1436 /* Just do the intrastage -> interstage propagation right now,
1437 * since we already know we're in the right type of shader program
1438 * for doing it.
1439 */
1440 if (linked_shader->Comp.LocalSize[0] == 0) {
1441 linker_error(prog, "compute shader didn't declare local size\n");
1442 return;
1443 }
1444 for (int i = 0; i < 3; i++)
1445 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1446 }
1447
1448
1449 /**
1450 * Combine a group of shaders for a single stage to generate a linked shader
1451 *
1452 * \note
1453 * If this function is supplied a single shader, it is cloned, and the new
1454 * shader is returned.
1455 */
1456 static struct gl_shader *
1457 link_intrastage_shaders(void *mem_ctx,
1458 struct gl_context *ctx,
1459 struct gl_shader_program *prog,
1460 struct gl_shader **shader_list,
1461 unsigned num_shaders)
1462 {
1463 struct gl_uniform_block *uniform_blocks = NULL;
1464
1465 /* Check that global variables defined in multiple shaders are consistent.
1466 */
1467 cross_validate_globals(prog, shader_list, num_shaders, false);
1468 if (!prog->LinkStatus)
1469 return NULL;
1470
1471 /* Check that interface blocks defined in multiple shaders are consistent.
1472 */
1473 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1474 num_shaders);
1475 if (!prog->LinkStatus)
1476 return NULL;
1477
1478 /* Link up uniform blocks defined within this stage. */
1479 const unsigned num_uniform_blocks =
1480 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1481 &uniform_blocks);
1482 if (!prog->LinkStatus)
1483 return NULL;
1484
1485 /* Check that there is only a single definition of each function signature
1486 * across all shaders.
1487 */
1488 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1489 foreach_list(node, shader_list[i]->ir) {
1490 ir_function *const f = ((ir_instruction *) node)->as_function();
1491
1492 if (f == NULL)
1493 continue;
1494
1495 for (unsigned j = i + 1; j < num_shaders; j++) {
1496 ir_function *const other =
1497 shader_list[j]->symbols->get_function(f->name);
1498
1499 /* If the other shader has no function (and therefore no function
1500 * signatures) with the same name, skip to the next shader.
1501 */
1502 if (other == NULL)
1503 continue;
1504
1505 foreach_list(n, &f->signatures) {
1506 ir_function_signature *sig = (ir_function_signature *) n;
1507
1508 if (!sig->is_defined || sig->is_builtin())
1509 continue;
1510
1511 ir_function_signature *other_sig =
1512 other->exact_matching_signature(NULL, &sig->parameters);
1513
1514 if ((other_sig != NULL) && other_sig->is_defined
1515 && !other_sig->is_builtin()) {
1516 linker_error(prog, "function `%s' is multiply defined",
1517 f->name);
1518 return NULL;
1519 }
1520 }
1521 }
1522 }
1523 }
1524
1525 /* Find the shader that defines main, and make a clone of it.
1526 *
1527 * Starting with the clone, search for undefined references. If one is
1528 * found, find the shader that defines it. Clone the reference and add
1529 * it to the shader. Repeat until there are no undefined references or
1530 * until a reference cannot be resolved.
1531 */
1532 gl_shader *main = NULL;
1533 for (unsigned i = 0; i < num_shaders; i++) {
1534 if (get_main_function_signature(shader_list[i]) != NULL) {
1535 main = shader_list[i];
1536 break;
1537 }
1538 }
1539
1540 if (main == NULL) {
1541 linker_error(prog, "%s shader lacks `main'\n",
1542 _mesa_shader_stage_to_string(shader_list[0]->Stage));
1543 return NULL;
1544 }
1545
1546 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1547 linked->ir = new(linked) exec_list;
1548 clone_ir_list(mem_ctx, linked->ir, main->ir);
1549
1550 linked->UniformBlocks = uniform_blocks;
1551 linked->NumUniformBlocks = num_uniform_blocks;
1552 ralloc_steal(linked, linked->UniformBlocks);
1553
1554 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1555 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
1556 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1557
1558 populate_symbol_table(linked);
1559
1560 /* The a pointer to the main function in the final linked shader (i.e., the
1561 * copy of the original shader that contained the main function).
1562 */
1563 ir_function_signature *const main_sig = get_main_function_signature(linked);
1564
1565 /* Move any instructions other than variable declarations or function
1566 * declarations into main.
1567 */
1568 exec_node *insertion_point =
1569 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1570 linked);
1571
1572 for (unsigned i = 0; i < num_shaders; i++) {
1573 if (shader_list[i] == main)
1574 continue;
1575
1576 insertion_point = move_non_declarations(shader_list[i]->ir,
1577 insertion_point, true, linked);
1578 }
1579
1580 /* Check if any shader needs built-in functions. */
1581 bool need_builtins = false;
1582 for (unsigned i = 0; i < num_shaders; i++) {
1583 if (shader_list[i]->uses_builtin_functions) {
1584 need_builtins = true;
1585 break;
1586 }
1587 }
1588
1589 bool ok;
1590 if (need_builtins) {
1591 /* Make a temporary array one larger than shader_list, which will hold
1592 * the built-in function shader as well.
1593 */
1594 gl_shader **linking_shaders = (gl_shader **)
1595 calloc(num_shaders + 1, sizeof(gl_shader *));
1596 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
1597 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
1598
1599 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
1600
1601 free(linking_shaders);
1602 } else {
1603 ok = link_function_calls(prog, linked, shader_list, num_shaders);
1604 }
1605
1606
1607 if (!ok) {
1608 ctx->Driver.DeleteShader(ctx, linked);
1609 return NULL;
1610 }
1611
1612 /* At this point linked should contain all of the linked IR, so
1613 * validate it to make sure nothing went wrong.
1614 */
1615 validate_ir_tree(linked->ir);
1616
1617 /* Set the size of geometry shader input arrays */
1618 if (linked->Stage == MESA_SHADER_GEOMETRY) {
1619 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
1620 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
1621 foreach_list(n, linked->ir) {
1622 ir_instruction *ir = (ir_instruction *) n;
1623 ir->accept(&input_resize_visitor);
1624 }
1625 }
1626
1627 /* Make a pass over all variable declarations to ensure that arrays with
1628 * unspecified sizes have a size specified. The size is inferred from the
1629 * max_array_access field.
1630 */
1631 array_sizing_visitor v;
1632 v.run(linked->ir);
1633 v.fixup_unnamed_interface_types();
1634
1635 return linked;
1636 }
1637
1638 /**
1639 * Update the sizes of linked shader uniform arrays to the maximum
1640 * array index used.
1641 *
1642 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1643 *
1644 * If one or more elements of an array are active,
1645 * GetActiveUniform will return the name of the array in name,
1646 * subject to the restrictions listed above. The type of the array
1647 * is returned in type. The size parameter contains the highest
1648 * array element index used, plus one. The compiler or linker
1649 * determines the highest index used. There will be only one
1650 * active uniform reported by the GL per uniform array.
1651
1652 */
1653 static void
1654 update_array_sizes(struct gl_shader_program *prog)
1655 {
1656 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1657 if (prog->_LinkedShaders[i] == NULL)
1658 continue;
1659
1660 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1661 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1662
1663 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
1664 !var->type->is_array())
1665 continue;
1666
1667 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1668 * will not be eliminated. Since we always do std140, just
1669 * don't resize arrays in UBOs.
1670 *
1671 * Atomic counters are supposed to get deterministic
1672 * locations assigned based on the declaration ordering and
1673 * sizes, array compaction would mess that up.
1674 */
1675 if (var->is_in_uniform_block() || var->type->contains_atomic())
1676 continue;
1677
1678 unsigned int size = var->data.max_array_access;
1679 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
1680 if (prog->_LinkedShaders[j] == NULL)
1681 continue;
1682
1683 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1684 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1685 if (!other_var)
1686 continue;
1687
1688 if (strcmp(var->name, other_var->name) == 0 &&
1689 other_var->data.max_array_access > size) {
1690 size = other_var->data.max_array_access;
1691 }
1692 }
1693 }
1694
1695 if (size + 1 != var->type->length) {
1696 /* If this is a built-in uniform (i.e., it's backed by some
1697 * fixed-function state), adjust the number of state slots to
1698 * match the new array size. The number of slots per array entry
1699 * is not known. It seems safe to assume that the total number of
1700 * slots is an integer multiple of the number of array elements.
1701 * Determine the number of slots per array element by dividing by
1702 * the old (total) size.
1703 */
1704 if (var->num_state_slots > 0) {
1705 var->num_state_slots = (size + 1)
1706 * (var->num_state_slots / var->type->length);
1707 }
1708
1709 var->type = glsl_type::get_array_instance(var->type->fields.array,
1710 size + 1);
1711 /* FINISHME: We should update the types of array
1712 * dereferences of this variable now.
1713 */
1714 }
1715 }
1716 }
1717 }
1718
1719 /**
1720 * Find a contiguous set of available bits in a bitmask.
1721 *
1722 * \param used_mask Bits representing used (1) and unused (0) locations
1723 * \param needed_count Number of contiguous bits needed.
1724 *
1725 * \return
1726 * Base location of the available bits on success or -1 on failure.
1727 */
1728 int
1729 find_available_slots(unsigned used_mask, unsigned needed_count)
1730 {
1731 unsigned needed_mask = (1 << needed_count) - 1;
1732 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1733
1734 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1735 * cannot optimize possibly infinite loops" for the loop below.
1736 */
1737 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1738 return -1;
1739
1740 for (int i = 0; i <= max_bit_to_test; i++) {
1741 if ((needed_mask & ~used_mask) == needed_mask)
1742 return i;
1743
1744 needed_mask <<= 1;
1745 }
1746
1747 return -1;
1748 }
1749
1750
1751 /**
1752 * Assign locations for either VS inputs for FS outputs
1753 *
1754 * \param prog Shader program whose variables need locations assigned
1755 * \param target_index Selector for the program target to receive location
1756 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1757 * \c MESA_SHADER_FRAGMENT.
1758 * \param max_index Maximum number of generic locations. This corresponds
1759 * to either the maximum number of draw buffers or the
1760 * maximum number of generic attributes.
1761 *
1762 * \return
1763 * If locations are successfully assigned, true is returned. Otherwise an
1764 * error is emitted to the shader link log and false is returned.
1765 */
1766 bool
1767 assign_attribute_or_color_locations(gl_shader_program *prog,
1768 unsigned target_index,
1769 unsigned max_index)
1770 {
1771 /* Mark invalid locations as being used.
1772 */
1773 unsigned used_locations = (max_index >= 32)
1774 ? ~0 : ~((1 << max_index) - 1);
1775
1776 assert((target_index == MESA_SHADER_VERTEX)
1777 || (target_index == MESA_SHADER_FRAGMENT));
1778
1779 gl_shader *const sh = prog->_LinkedShaders[target_index];
1780 if (sh == NULL)
1781 return true;
1782
1783 /* Operate in a total of four passes.
1784 *
1785 * 1. Invalidate the location assignments for all vertex shader inputs.
1786 *
1787 * 2. Assign locations for inputs that have user-defined (via
1788 * glBindVertexAttribLocation) locations and outputs that have
1789 * user-defined locations (via glBindFragDataLocation).
1790 *
1791 * 3. Sort the attributes without assigned locations by number of slots
1792 * required in decreasing order. Fragmentation caused by attribute
1793 * locations assigned by the application may prevent large attributes
1794 * from having enough contiguous space.
1795 *
1796 * 4. Assign locations to any inputs without assigned locations.
1797 */
1798
1799 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1800 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1801
1802 const enum ir_variable_mode direction =
1803 (target_index == MESA_SHADER_VERTEX)
1804 ? ir_var_shader_in : ir_var_shader_out;
1805
1806
1807 /* Temporary storage for the set of attributes that need locations assigned.
1808 */
1809 struct temp_attr {
1810 unsigned slots;
1811 ir_variable *var;
1812
1813 /* Used below in the call to qsort. */
1814 static int compare(const void *a, const void *b)
1815 {
1816 const temp_attr *const l = (const temp_attr *) a;
1817 const temp_attr *const r = (const temp_attr *) b;
1818
1819 /* Reversed because we want a descending order sort below. */
1820 return r->slots - l->slots;
1821 }
1822 } to_assign[16];
1823
1824 unsigned num_attr = 0;
1825
1826 foreach_list(node, sh->ir) {
1827 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1828
1829 if ((var == NULL) || (var->data.mode != (unsigned) direction))
1830 continue;
1831
1832 if (var->data.explicit_location) {
1833 if ((var->data.location >= (int)(max_index + generic_base))
1834 || (var->data.location < 0)) {
1835 linker_error(prog,
1836 "invalid explicit location %d specified for `%s'\n",
1837 (var->data.location < 0)
1838 ? var->data.location
1839 : var->data.location - generic_base,
1840 var->name);
1841 return false;
1842 }
1843 } else if (target_index == MESA_SHADER_VERTEX) {
1844 unsigned binding;
1845
1846 if (prog->AttributeBindings->get(binding, var->name)) {
1847 assert(binding >= VERT_ATTRIB_GENERIC0);
1848 var->data.location = binding;
1849 var->data.is_unmatched_generic_inout = 0;
1850 }
1851 } else if (target_index == MESA_SHADER_FRAGMENT) {
1852 unsigned binding;
1853 unsigned index;
1854
1855 if (prog->FragDataBindings->get(binding, var->name)) {
1856 assert(binding >= FRAG_RESULT_DATA0);
1857 var->data.location = binding;
1858 var->data.is_unmatched_generic_inout = 0;
1859
1860 if (prog->FragDataIndexBindings->get(index, var->name)) {
1861 var->data.index = index;
1862 }
1863 }
1864 }
1865
1866 /* If the variable is not a built-in and has a location statically
1867 * assigned in the shader (presumably via a layout qualifier), make sure
1868 * that it doesn't collide with other assigned locations. Otherwise,
1869 * add it to the list of variables that need linker-assigned locations.
1870 */
1871 const unsigned slots = var->type->count_attribute_slots();
1872 if (var->data.location != -1) {
1873 if (var->data.location >= generic_base && var->data.index < 1) {
1874 /* From page 61 of the OpenGL 4.0 spec:
1875 *
1876 * "LinkProgram will fail if the attribute bindings assigned
1877 * by BindAttribLocation do not leave not enough space to
1878 * assign a location for an active matrix attribute or an
1879 * active attribute array, both of which require multiple
1880 * contiguous generic attributes."
1881 *
1882 * I think above text prohibits the aliasing of explicit and
1883 * automatic assignments. But, aliasing is allowed in manual
1884 * assignments of attribute locations. See below comments for
1885 * the details.
1886 *
1887 * From OpenGL 4.0 spec, page 61:
1888 *
1889 * "It is possible for an application to bind more than one
1890 * attribute name to the same location. This is referred to as
1891 * aliasing. This will only work if only one of the aliased
1892 * attributes is active in the executable program, or if no
1893 * path through the shader consumes more than one attribute of
1894 * a set of attributes aliased to the same location. A link
1895 * error can occur if the linker determines that every path
1896 * through the shader consumes multiple aliased attributes,
1897 * but implementations are not required to generate an error
1898 * in this case."
1899 *
1900 * From GLSL 4.30 spec, page 54:
1901 *
1902 * "A program will fail to link if any two non-vertex shader
1903 * input variables are assigned to the same location. For
1904 * vertex shaders, multiple input variables may be assigned
1905 * to the same location using either layout qualifiers or via
1906 * the OpenGL API. However, such aliasing is intended only to
1907 * support vertex shaders where each execution path accesses
1908 * at most one input per each location. Implementations are
1909 * permitted, but not required, to generate link-time errors
1910 * if they detect that every path through the vertex shader
1911 * executable accesses multiple inputs assigned to any single
1912 * location. For all shader types, a program will fail to link
1913 * if explicit location assignments leave the linker unable
1914 * to find space for other variables without explicit
1915 * assignments."
1916 *
1917 * From OpenGL ES 3.0 spec, page 56:
1918 *
1919 * "Binding more than one attribute name to the same location
1920 * is referred to as aliasing, and is not permitted in OpenGL
1921 * ES Shading Language 3.00 vertex shaders. LinkProgram will
1922 * fail when this condition exists. However, aliasing is
1923 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
1924 * This will only work if only one of the aliased attributes
1925 * is active in the executable program, or if no path through
1926 * the shader consumes more than one attribute of a set of
1927 * attributes aliased to the same location. A link error can
1928 * occur if the linker determines that every path through the
1929 * shader consumes multiple aliased attributes, but implemen-
1930 * tations are not required to generate an error in this case."
1931 *
1932 * After looking at above references from OpenGL, OpenGL ES and
1933 * GLSL specifications, we allow aliasing of vertex input variables
1934 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
1935 *
1936 * NOTE: This is not required by the spec but its worth mentioning
1937 * here that we're not doing anything to make sure that no path
1938 * through the vertex shader executable accesses multiple inputs
1939 * assigned to any single location.
1940 */
1941
1942 /* Mask representing the contiguous slots that will be used by
1943 * this attribute.
1944 */
1945 const unsigned attr = var->data.location - generic_base;
1946 const unsigned use_mask = (1 << slots) - 1;
1947 const char *const string = (target_index == MESA_SHADER_VERTEX)
1948 ? "vertex shader input" : "fragment shader output";
1949
1950 /* Generate a link error if the requested locations for this
1951 * attribute exceed the maximum allowed attribute location.
1952 */
1953 if (attr + slots > max_index) {
1954 linker_error(prog,
1955 "insufficient contiguous locations "
1956 "available for %s `%s' %d %d %d", string,
1957 var->name, used_locations, use_mask, attr);
1958 return false;
1959 }
1960
1961 /* Generate a link error if the set of bits requested for this
1962 * attribute overlaps any previously allocated bits.
1963 */
1964 if ((~(use_mask << attr) & used_locations) != used_locations) {
1965 if (target_index == MESA_SHADER_FRAGMENT ||
1966 (prog->IsES && prog->Version >= 300)) {
1967 linker_error(prog,
1968 "overlapping location is assigned "
1969 "to %s `%s' %d %d %d\n", string,
1970 var->name, used_locations, use_mask, attr);
1971 return false;
1972 } else {
1973 linker_warning(prog,
1974 "overlapping location is assigned "
1975 "to %s `%s' %d %d %d\n", string,
1976 var->name, used_locations, use_mask, attr);
1977 }
1978 }
1979
1980 used_locations |= (use_mask << attr);
1981 }
1982
1983 continue;
1984 }
1985
1986 to_assign[num_attr].slots = slots;
1987 to_assign[num_attr].var = var;
1988 num_attr++;
1989 }
1990
1991 /* If all of the attributes were assigned locations by the application (or
1992 * are built-in attributes with fixed locations), return early. This should
1993 * be the common case.
1994 */
1995 if (num_attr == 0)
1996 return true;
1997
1998 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1999
2000 if (target_index == MESA_SHADER_VERTEX) {
2001 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2002 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2003 * reserved to prevent it from being automatically allocated below.
2004 */
2005 find_deref_visitor find("gl_Vertex");
2006 find.run(sh->ir);
2007 if (find.variable_found())
2008 used_locations |= (1 << 0);
2009 }
2010
2011 for (unsigned i = 0; i < num_attr; i++) {
2012 /* Mask representing the contiguous slots that will be used by this
2013 * attribute.
2014 */
2015 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2016
2017 int location = find_available_slots(used_locations, to_assign[i].slots);
2018
2019 if (location < 0) {
2020 const char *const string = (target_index == MESA_SHADER_VERTEX)
2021 ? "vertex shader input" : "fragment shader output";
2022
2023 linker_error(prog,
2024 "insufficient contiguous locations "
2025 "available for %s `%s'",
2026 string, to_assign[i].var->name);
2027 return false;
2028 }
2029
2030 to_assign[i].var->data.location = generic_base + location;
2031 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2032 used_locations |= (use_mask << location);
2033 }
2034
2035 return true;
2036 }
2037
2038
2039 /**
2040 * Demote shader inputs and outputs that are not used in other stages
2041 */
2042 void
2043 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
2044 {
2045 foreach_list(node, sh->ir) {
2046 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2047
2048 if ((var == NULL) || (var->data.mode != int(mode)))
2049 continue;
2050
2051 /* A shader 'in' or 'out' variable is only really an input or output if
2052 * its value is used by other shader stages. This will cause the variable
2053 * to have a location assigned.
2054 */
2055 if (var->data.is_unmatched_generic_inout) {
2056 var->data.mode = ir_var_auto;
2057 }
2058 }
2059 }
2060
2061
2062 /**
2063 * Store the gl_FragDepth layout in the gl_shader_program struct.
2064 */
2065 static void
2066 store_fragdepth_layout(struct gl_shader_program *prog)
2067 {
2068 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2069 return;
2070 }
2071
2072 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2073
2074 /* We don't look up the gl_FragDepth symbol directly because if
2075 * gl_FragDepth is not used in the shader, it's removed from the IR.
2076 * However, the symbol won't be removed from the symbol table.
2077 *
2078 * We're only interested in the cases where the variable is NOT removed
2079 * from the IR.
2080 */
2081 foreach_list(node, ir) {
2082 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2083
2084 if (var == NULL || var->data.mode != ir_var_shader_out) {
2085 continue;
2086 }
2087
2088 if (strcmp(var->name, "gl_FragDepth") == 0) {
2089 switch (var->data.depth_layout) {
2090 case ir_depth_layout_none:
2091 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2092 return;
2093 case ir_depth_layout_any:
2094 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2095 return;
2096 case ir_depth_layout_greater:
2097 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2098 return;
2099 case ir_depth_layout_less:
2100 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2101 return;
2102 case ir_depth_layout_unchanged:
2103 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2104 return;
2105 default:
2106 assert(0);
2107 return;
2108 }
2109 }
2110 }
2111 }
2112
2113 /**
2114 * Validate the resources used by a program versus the implementation limits
2115 */
2116 static void
2117 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2118 {
2119 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2120 struct gl_shader *sh = prog->_LinkedShaders[i];
2121
2122 if (sh == NULL)
2123 continue;
2124
2125 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2126 linker_error(prog, "Too many %s shader texture samplers",
2127 _mesa_shader_stage_to_string(i));
2128 }
2129
2130 if (sh->num_uniform_components >
2131 ctx->Const.Program[i].MaxUniformComponents) {
2132 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2133 linker_warning(prog, "Too many %s shader default uniform block "
2134 "components, but the driver will try to optimize "
2135 "them out; this is non-portable out-of-spec "
2136 "behavior\n",
2137 _mesa_shader_stage_to_string(i));
2138 } else {
2139 linker_error(prog, "Too many %s shader default uniform block "
2140 "components",
2141 _mesa_shader_stage_to_string(i));
2142 }
2143 }
2144
2145 if (sh->num_combined_uniform_components >
2146 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2147 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2148 linker_warning(prog, "Too many %s shader uniform components, "
2149 "but the driver will try to optimize them out; "
2150 "this is non-portable out-of-spec behavior\n",
2151 _mesa_shader_stage_to_string(i));
2152 } else {
2153 linker_error(prog, "Too many %s shader uniform components",
2154 _mesa_shader_stage_to_string(i));
2155 }
2156 }
2157 }
2158
2159 unsigned blocks[MESA_SHADER_STAGES] = {0};
2160 unsigned total_uniform_blocks = 0;
2161
2162 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
2163 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2164 if (prog->UniformBlockStageIndex[j][i] != -1) {
2165 blocks[j]++;
2166 total_uniform_blocks++;
2167 }
2168 }
2169
2170 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2171 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
2172 prog->NumUniformBlocks,
2173 ctx->Const.MaxCombinedUniformBlocks);
2174 } else {
2175 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2176 const unsigned max_uniform_blocks =
2177 ctx->Const.Program[i].MaxUniformBlocks;
2178 if (blocks[i] > max_uniform_blocks) {
2179 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
2180 _mesa_shader_stage_to_string(i),
2181 blocks[i],
2182 max_uniform_blocks);
2183 break;
2184 }
2185 }
2186 }
2187 }
2188 }
2189
2190 /**
2191 * Validate shader image resources.
2192 */
2193 static void
2194 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2195 {
2196 unsigned total_image_units = 0;
2197 unsigned fragment_outputs = 0;
2198
2199 if (!ctx->Extensions.ARB_shader_image_load_store)
2200 return;
2201
2202 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2203 struct gl_shader *sh = prog->_LinkedShaders[i];
2204
2205 if (sh) {
2206 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2207 linker_error(prog, "Too many %s shader image uniforms",
2208 _mesa_shader_stage_to_string(i));
2209
2210 total_image_units += sh->NumImages;
2211
2212 if (i == MESA_SHADER_FRAGMENT) {
2213 foreach_list(node, sh->ir) {
2214 ir_variable *var = ((ir_instruction *)node)->as_variable();
2215 if (var && var->data.mode == ir_var_shader_out)
2216 fragment_outputs += var->type->count_attribute_slots();
2217 }
2218 }
2219 }
2220 }
2221
2222 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
2223 linker_error(prog, "Too many combined image uniforms");
2224
2225 if (total_image_units + fragment_outputs >
2226 ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
2227 linker_error(prog, "Too many combined image uniforms and fragment outputs");
2228 }
2229
2230
2231 /**
2232 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2233 * for a variable, checks for overlaps between other uniforms using explicit
2234 * locations.
2235 */
2236 static bool
2237 reserve_explicit_locations(struct gl_shader_program *prog,
2238 string_to_uint_map *map, ir_variable *var)
2239 {
2240 unsigned slots = var->type->uniform_locations();
2241 unsigned max_loc = var->data.location + slots - 1;
2242
2243 /* Resize remap table if locations do not fit in the current one. */
2244 if (max_loc + 1 > prog->NumUniformRemapTable) {
2245 prog->UniformRemapTable =
2246 reralloc(prog, prog->UniformRemapTable,
2247 gl_uniform_storage *,
2248 max_loc + 1);
2249
2250 if (!prog->UniformRemapTable) {
2251 linker_error(prog, "Out of memory during linking.");
2252 return false;
2253 }
2254
2255 /* Initialize allocated space. */
2256 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2257 prog->UniformRemapTable[i] = NULL;
2258
2259 prog->NumUniformRemapTable = max_loc + 1;
2260 }
2261
2262 for (unsigned i = 0; i < slots; i++) {
2263 unsigned loc = var->data.location + i;
2264
2265 /* Check if location is already used. */
2266 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2267
2268 /* Possibly same uniform from a different stage, this is ok. */
2269 unsigned hash_loc;
2270 if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2271 continue;
2272
2273 /* ARB_explicit_uniform_location specification states:
2274 *
2275 * "No two default-block uniform variables in the program can have
2276 * the same location, even if they are unused, otherwise a compiler
2277 * or linker error will be generated."
2278 */
2279 linker_error(prog,
2280 "location qualifier for uniform %s overlaps"
2281 "previously used location",
2282 var->name);
2283 return false;
2284 }
2285
2286 /* Initialize location as inactive before optimization
2287 * rounds and location assignment.
2288 */
2289 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2290 }
2291
2292 /* Note, base location used for arrays. */
2293 map->put(var->data.location, var->name);
2294
2295 return true;
2296 }
2297
2298 /**
2299 * Check and reserve all explicit uniform locations, called before
2300 * any optimizations happen to handle also inactive uniforms and
2301 * inactive array elements that may get trimmed away.
2302 */
2303 static void
2304 check_explicit_uniform_locations(struct gl_context *ctx,
2305 struct gl_shader_program *prog)
2306 {
2307 if (!ctx->Extensions.ARB_explicit_uniform_location)
2308 return;
2309
2310 /* This map is used to detect if overlapping explicit locations
2311 * occur with the same uniform (from different stage) or a different one.
2312 */
2313 string_to_uint_map *uniform_map = new string_to_uint_map;
2314
2315 if (!uniform_map) {
2316 linker_error(prog, "Out of memory during linking.");
2317 return;
2318 }
2319
2320 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2321 struct gl_shader *sh = prog->_LinkedShaders[i];
2322
2323 if (!sh)
2324 continue;
2325
2326 foreach_list(node, sh->ir) {
2327 ir_variable *var = ((ir_instruction *)node)->as_variable();
2328 if ((var && var->data.mode == ir_var_uniform) &&
2329 var->data.explicit_location) {
2330 if (!reserve_explicit_locations(prog, uniform_map, var))
2331 return;
2332 }
2333 }
2334 }
2335
2336 delete uniform_map;
2337 }
2338
2339 void
2340 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2341 {
2342 tfeedback_decl *tfeedback_decls = NULL;
2343 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2344
2345 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2346
2347 prog->LinkStatus = true; /* All error paths will set this to false */
2348 prog->Validated = false;
2349 prog->_Used = false;
2350
2351 ralloc_free(prog->InfoLog);
2352 prog->InfoLog = ralloc_strdup(NULL, "");
2353
2354 ralloc_free(prog->UniformBlocks);
2355 prog->UniformBlocks = NULL;
2356 prog->NumUniformBlocks = 0;
2357 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2358 ralloc_free(prog->UniformBlockStageIndex[i]);
2359 prog->UniformBlockStageIndex[i] = NULL;
2360 }
2361
2362 ralloc_free(prog->AtomicBuffers);
2363 prog->AtomicBuffers = NULL;
2364 prog->NumAtomicBuffers = 0;
2365 prog->ARB_fragment_coord_conventions_enable = false;
2366
2367 /* Separate the shaders into groups based on their type.
2368 */
2369 struct gl_shader **shader_list[MESA_SHADER_STAGES];
2370 unsigned num_shaders[MESA_SHADER_STAGES];
2371
2372 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2373 shader_list[i] = (struct gl_shader **)
2374 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2375 num_shaders[i] = 0;
2376 }
2377
2378 unsigned min_version = UINT_MAX;
2379 unsigned max_version = 0;
2380 const bool is_es_prog =
2381 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
2382 for (unsigned i = 0; i < prog->NumShaders; i++) {
2383 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2384 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2385
2386 if (prog->Shaders[i]->IsES != is_es_prog) {
2387 linker_error(prog, "all shaders must use same shading "
2388 "language version\n");
2389 goto done;
2390 }
2391
2392 prog->ARB_fragment_coord_conventions_enable |=
2393 prog->Shaders[i]->ARB_fragment_coord_conventions_enable;
2394
2395 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
2396 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
2397 num_shaders[shader_type]++;
2398 }
2399
2400 /* In desktop GLSL, different shader versions may be linked together. In
2401 * GLSL ES, all shader versions must be the same.
2402 */
2403 if (is_es_prog && min_version != max_version) {
2404 linker_error(prog, "all shaders must use same shading "
2405 "language version\n");
2406 goto done;
2407 }
2408
2409 prog->Version = max_version;
2410 prog->IsES = is_es_prog;
2411
2412 /* Geometry shaders have to be linked with vertex shaders.
2413 */
2414 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
2415 num_shaders[MESA_SHADER_VERTEX] == 0 &&
2416 !prog->SeparateShader) {
2417 linker_error(prog, "Geometry shader must be linked with "
2418 "vertex shader\n");
2419 goto done;
2420 }
2421
2422 /* Compute shaders have additional restrictions. */
2423 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
2424 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
2425 linker_error(prog, "Compute shaders may not be linked with any other "
2426 "type of shader\n");
2427 }
2428
2429 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2430 if (prog->_LinkedShaders[i] != NULL)
2431 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2432
2433 prog->_LinkedShaders[i] = NULL;
2434 }
2435
2436 /* Link all shaders for a particular stage and validate the result.
2437 */
2438 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
2439 if (num_shaders[stage] > 0) {
2440 gl_shader *const sh =
2441 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
2442 num_shaders[stage]);
2443
2444 if (!prog->LinkStatus)
2445 goto done;
2446
2447 switch (stage) {
2448 case MESA_SHADER_VERTEX:
2449 validate_vertex_shader_executable(prog, sh);
2450 break;
2451 case MESA_SHADER_GEOMETRY:
2452 validate_geometry_shader_executable(prog, sh);
2453 break;
2454 case MESA_SHADER_FRAGMENT:
2455 validate_fragment_shader_executable(prog, sh);
2456 break;
2457 }
2458 if (!prog->LinkStatus)
2459 goto done;
2460
2461 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
2462 }
2463 }
2464
2465 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
2466 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
2467 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
2468 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
2469 else
2470 prog->LastClipDistanceArraySize = 0; /* Not used */
2471
2472 /* Here begins the inter-stage linking phase. Some initial validation is
2473 * performed, then locations are assigned for uniforms, attributes, and
2474 * varyings.
2475 */
2476 cross_validate_uniforms(prog);
2477 if (!prog->LinkStatus)
2478 goto done;
2479
2480 unsigned prev;
2481
2482 for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
2483 if (prog->_LinkedShaders[prev] != NULL)
2484 break;
2485 }
2486
2487 check_explicit_uniform_locations(ctx, prog);
2488 if (!prog->LinkStatus)
2489 goto done;
2490
2491 /* Validate the inputs of each stage with the output of the preceding
2492 * stage.
2493 */
2494 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
2495 if (prog->_LinkedShaders[i] == NULL)
2496 continue;
2497
2498 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
2499 prog->_LinkedShaders[i]);
2500 if (!prog->LinkStatus)
2501 goto done;
2502
2503 cross_validate_outputs_to_inputs(prog,
2504 prog->_LinkedShaders[prev],
2505 prog->_LinkedShaders[i]);
2506 if (!prog->LinkStatus)
2507 goto done;
2508
2509 prev = i;
2510 }
2511
2512 /* Cross-validate uniform blocks between shader stages */
2513 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
2514 MESA_SHADER_STAGES);
2515 if (!prog->LinkStatus)
2516 goto done;
2517
2518 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2519 if (prog->_LinkedShaders[i] != NULL)
2520 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
2521 }
2522
2523 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2524 * it before optimization because we want most of the checks to get
2525 * dropped thanks to constant propagation.
2526 *
2527 * This rule also applies to GLSL ES 3.00.
2528 */
2529 if (max_version >= (is_es_prog ? 300 : 130)) {
2530 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2531 if (sh) {
2532 lower_discard_flow(sh->ir);
2533 }
2534 }
2535
2536 if (!interstage_cross_validate_uniform_blocks(prog))
2537 goto done;
2538
2539 /* Do common optimization before assigning storage for attributes,
2540 * uniforms, and varyings. Later optimization could possibly make
2541 * some of that unused.
2542 */
2543 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2544 if (prog->_LinkedShaders[i] == NULL)
2545 continue;
2546
2547 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2548 if (!prog->LinkStatus)
2549 goto done;
2550
2551 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
2552 lower_clip_distance(prog->_LinkedShaders[i]);
2553 }
2554
2555 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
2556 &ctx->ShaderCompilerOptions[i],
2557 ctx->Const.NativeIntegers))
2558 ;
2559 }
2560
2561 /* Mark all generic shader inputs and outputs as unpaired. */
2562 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
2563 if (prog->_LinkedShaders[i] != NULL) {
2564 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
2565 }
2566 }
2567
2568 /* FINISHME: The value of the max_attribute_index parameter is
2569 * FINISHME: implementation dependent based on the value of
2570 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2571 * FINISHME: at least 16, so hardcode 16 for now.
2572 */
2573 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2574 goto done;
2575 }
2576
2577 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2578 goto done;
2579 }
2580
2581 unsigned first;
2582 for (first = 0; first <= MESA_SHADER_FRAGMENT; first++) {
2583 if (prog->_LinkedShaders[first] != NULL)
2584 break;
2585 }
2586
2587 if (num_tfeedback_decls != 0) {
2588 /* From GL_EXT_transform_feedback:
2589 * A program will fail to link if:
2590 *
2591 * * the <count> specified by TransformFeedbackVaryingsEXT is
2592 * non-zero, but the program object has no vertex or geometry
2593 * shader;
2594 */
2595 if (first == MESA_SHADER_FRAGMENT) {
2596 linker_error(prog, "Transform feedback varyings specified, but "
2597 "no vertex or geometry shader is present.");
2598 goto done;
2599 }
2600
2601 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2602 prog->TransformFeedback.NumVarying);
2603 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2604 prog->TransformFeedback.VaryingNames,
2605 tfeedback_decls))
2606 goto done;
2607 }
2608
2609 /* Linking the stages in the opposite order (from fragment to vertex)
2610 * ensures that inter-shader outputs written to in an earlier stage are
2611 * eliminated if they are (transitively) not used in a later stage.
2612 */
2613 int last, next;
2614 for (last = MESA_SHADER_FRAGMENT; last >= 0; last--) {
2615 if (prog->_LinkedShaders[last] != NULL)
2616 break;
2617 }
2618
2619 if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
2620 gl_shader *const sh = prog->_LinkedShaders[last];
2621
2622 if (num_tfeedback_decls != 0 || prog->SeparateShader) {
2623 /* There was no fragment shader, but we still have to assign varying
2624 * locations for use by transform feedback.
2625 */
2626 if (!assign_varying_locations(ctx, mem_ctx, prog,
2627 sh, NULL,
2628 num_tfeedback_decls, tfeedback_decls,
2629 0))
2630 goto done;
2631 }
2632
2633 do_dead_builtin_varyings(ctx, sh, NULL,
2634 num_tfeedback_decls, tfeedback_decls);
2635
2636 if (!prog->SeparateShader)
2637 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
2638
2639 /* Eliminate code that is now dead due to unused outputs being demoted.
2640 */
2641 while (do_dead_code(sh->ir, false))
2642 ;
2643 }
2644 else if (first == MESA_SHADER_FRAGMENT) {
2645 /* If the program only contains a fragment shader...
2646 */
2647 gl_shader *const sh = prog->_LinkedShaders[first];
2648
2649 do_dead_builtin_varyings(ctx, NULL, sh,
2650 num_tfeedback_decls, tfeedback_decls);
2651
2652 if (prog->SeparateShader) {
2653 if (!assign_varying_locations(ctx, mem_ctx, prog,
2654 NULL /* producer */,
2655 sh /* consumer */,
2656 0 /* num_tfeedback_decls */,
2657 NULL /* tfeedback_decls */,
2658 0 /* gs_input_vertices */))
2659 goto done;
2660 } else
2661 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
2662
2663 while (do_dead_code(sh->ir, false))
2664 ;
2665 }
2666
2667 next = last;
2668 for (int i = next - 1; i >= 0; i--) {
2669 if (prog->_LinkedShaders[i] == NULL)
2670 continue;
2671
2672 gl_shader *const sh_i = prog->_LinkedShaders[i];
2673 gl_shader *const sh_next = prog->_LinkedShaders[next];
2674 unsigned gs_input_vertices =
2675 next == MESA_SHADER_GEOMETRY ? prog->Geom.VerticesIn : 0;
2676
2677 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2678 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2679 tfeedback_decls, gs_input_vertices))
2680 goto done;
2681
2682 do_dead_builtin_varyings(ctx, sh_i, sh_next,
2683 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2684 tfeedback_decls);
2685
2686 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
2687 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
2688
2689 /* Eliminate code that is now dead due to unused outputs being demoted.
2690 */
2691 while (do_dead_code(sh_i->ir, false))
2692 ;
2693 while (do_dead_code(sh_next->ir, false))
2694 ;
2695
2696 /* This must be done after all dead varyings are eliminated. */
2697 if (!check_against_output_limit(ctx, prog, sh_i))
2698 goto done;
2699 if (!check_against_input_limit(ctx, prog, sh_next))
2700 goto done;
2701
2702 next = i;
2703 }
2704
2705 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2706 goto done;
2707
2708 update_array_sizes(prog);
2709 link_assign_uniform_locations(prog);
2710 link_assign_atomic_counter_resources(ctx, prog);
2711 store_fragdepth_layout(prog);
2712
2713 check_resources(ctx, prog);
2714 check_image_resources(ctx, prog);
2715 link_check_atomic_counter_resources(ctx, prog);
2716
2717 if (!prog->LinkStatus)
2718 goto done;
2719
2720 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2721 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
2722 * anything about shader linking when one of the shaders (vertex or
2723 * fragment shader) is absent. So, the extension shouldn't change the
2724 * behavior specified in GLSL specification.
2725 */
2726 if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
2727 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2728 linker_error(prog, "program lacks a vertex shader\n");
2729 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2730 linker_error(prog, "program lacks a fragment shader\n");
2731 }
2732 }
2733
2734 /* FINISHME: Assign fragment shader output locations. */
2735
2736 done:
2737 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2738 free(shader_list[i]);
2739 if (prog->_LinkedShaders[i] == NULL)
2740 continue;
2741
2742 /* Do a final validation step to make sure that the IR wasn't
2743 * invalidated by any modifications performed after intrastage linking.
2744 */
2745 validate_ir_tree(prog->_LinkedShaders[i]->ir);
2746
2747 /* Retain any live IR, but trash the rest. */
2748 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2749
2750 /* The symbol table in the linked shaders may contain references to
2751 * variables that were removed (e.g., unused uniforms). Since it may
2752 * contain junk, there is no possible valid use. Delete it and set the
2753 * pointer to NULL.
2754 */
2755 delete prog->_LinkedShaders[i]->symbols;
2756 prog->_LinkedShaders[i]->symbols = NULL;
2757 }
2758
2759 ralloc_free(mem_ctx);
2760 }