glsl: avoid stack smashing when there are too many attributes
[mesa.git] / src / compiler / 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 <ctype.h>
68 #include "util/strndup.h"
69 #include "main/core.h"
70 #include "glsl_symbol_table.h"
71 #include "glsl_parser_extras.h"
72 #include "ir.h"
73 #include "program.h"
74 #include "program/hash_table.h"
75 #include "linker.h"
76 #include "link_varyings.h"
77 #include "ir_optimization.h"
78 #include "ir_rvalue_visitor.h"
79 #include "ir_uniform.h"
80
81 #include "main/shaderobj.h"
82 #include "main/enums.h"
83
84
85 namespace {
86
87 /**
88 * Visitor that determines whether or not a variable is ever written.
89 */
90 class find_assignment_visitor : public ir_hierarchical_visitor {
91 public:
92 find_assignment_visitor(const char *name)
93 : name(name), found(false)
94 {
95 /* empty */
96 }
97
98 virtual ir_visitor_status visit_enter(ir_assignment *ir)
99 {
100 ir_variable *const var = ir->lhs->variable_referenced();
101
102 if (strcmp(name, var->name) == 0) {
103 found = true;
104 return visit_stop;
105 }
106
107 return visit_continue_with_parent;
108 }
109
110 virtual ir_visitor_status visit_enter(ir_call *ir)
111 {
112 foreach_two_lists(formal_node, &ir->callee->parameters,
113 actual_node, &ir->actual_parameters) {
114 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
115 ir_variable *sig_param = (ir_variable *) formal_node;
116
117 if (sig_param->data.mode == ir_var_function_out ||
118 sig_param->data.mode == ir_var_function_inout) {
119 ir_variable *var = param_rval->variable_referenced();
120 if (var && strcmp(name, var->name) == 0) {
121 found = true;
122 return visit_stop;
123 }
124 }
125 }
126
127 if (ir->return_deref != NULL) {
128 ir_variable *const var = ir->return_deref->variable_referenced();
129
130 if (strcmp(name, var->name) == 0) {
131 found = true;
132 return visit_stop;
133 }
134 }
135
136 return visit_continue_with_parent;
137 }
138
139 bool variable_found()
140 {
141 return found;
142 }
143
144 private:
145 const char *name; /**< Find writes to a variable with this name. */
146 bool found; /**< Was a write to the variable found? */
147 };
148
149
150 /**
151 * Visitor that determines whether or not a variable is ever read.
152 */
153 class find_deref_visitor : public ir_hierarchical_visitor {
154 public:
155 find_deref_visitor(const char *name)
156 : name(name), found(false)
157 {
158 /* empty */
159 }
160
161 virtual ir_visitor_status visit(ir_dereference_variable *ir)
162 {
163 if (strcmp(this->name, ir->var->name) == 0) {
164 this->found = true;
165 return visit_stop;
166 }
167
168 return visit_continue;
169 }
170
171 bool variable_found() const
172 {
173 return this->found;
174 }
175
176 private:
177 const char *name; /**< Find writes to a variable with this name. */
178 bool found; /**< Was a write to the variable found? */
179 };
180
181
182 class geom_array_resize_visitor : public ir_hierarchical_visitor {
183 public:
184 unsigned num_vertices;
185 gl_shader_program *prog;
186
187 geom_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
188 {
189 this->num_vertices = num_vertices;
190 this->prog = prog;
191 }
192
193 virtual ~geom_array_resize_visitor()
194 {
195 /* empty */
196 }
197
198 virtual ir_visitor_status visit(ir_variable *var)
199 {
200 if (!var->type->is_array() || var->data.mode != ir_var_shader_in)
201 return visit_continue;
202
203 unsigned size = var->type->length;
204
205 /* Generate a link error if the shader has declared this array with an
206 * incorrect size.
207 */
208 if (size && size != this->num_vertices) {
209 linker_error(this->prog, "size of array %s declared as %u, "
210 "but number of input vertices is %u\n",
211 var->name, size, this->num_vertices);
212 return visit_continue;
213 }
214
215 /* Generate a link error if the shader attempts to access an input
216 * array using an index too large for its actual size assigned at link
217 * time.
218 */
219 if (var->data.max_array_access >= this->num_vertices) {
220 linker_error(this->prog, "geometry shader accesses element %i of "
221 "%s, but only %i input vertices\n",
222 var->data.max_array_access, var->name, this->num_vertices);
223 return visit_continue;
224 }
225
226 var->type = glsl_type::get_array_instance(var->type->fields.array,
227 this->num_vertices);
228 var->data.max_array_access = this->num_vertices - 1;
229
230 return visit_continue;
231 }
232
233 /* Dereferences of input variables need to be updated so that their type
234 * matches the newly assigned type of the variable they are accessing. */
235 virtual ir_visitor_status visit(ir_dereference_variable *ir)
236 {
237 ir->type = ir->var->type;
238 return visit_continue;
239 }
240
241 /* Dereferences of 2D input arrays need to be updated so that their type
242 * matches the newly assigned type of the array they are accessing. */
243 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
244 {
245 const glsl_type *const vt = ir->array->type;
246 if (vt->is_array())
247 ir->type = vt->fields.array;
248 return visit_continue;
249 }
250 };
251
252 class tess_eval_array_resize_visitor : public ir_hierarchical_visitor {
253 public:
254 unsigned num_vertices;
255 gl_shader_program *prog;
256
257 tess_eval_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
258 {
259 this->num_vertices = num_vertices;
260 this->prog = prog;
261 }
262
263 virtual ~tess_eval_array_resize_visitor()
264 {
265 /* empty */
266 }
267
268 virtual ir_visitor_status visit(ir_variable *var)
269 {
270 if (!var->type->is_array() || var->data.mode != ir_var_shader_in || var->data.patch)
271 return visit_continue;
272
273 var->type = glsl_type::get_array_instance(var->type->fields.array,
274 this->num_vertices);
275 var->data.max_array_access = this->num_vertices - 1;
276
277 return visit_continue;
278 }
279
280 /* Dereferences of input variables need to be updated so that their type
281 * matches the newly assigned type of the variable they are accessing. */
282 virtual ir_visitor_status visit(ir_dereference_variable *ir)
283 {
284 ir->type = ir->var->type;
285 return visit_continue;
286 }
287
288 /* Dereferences of 2D input arrays need to be updated so that their type
289 * matches the newly assigned type of the array they are accessing. */
290 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
291 {
292 const glsl_type *const vt = ir->array->type;
293 if (vt->is_array())
294 ir->type = vt->fields.array;
295 return visit_continue;
296 }
297 };
298
299 class barrier_use_visitor : public ir_hierarchical_visitor {
300 public:
301 barrier_use_visitor(gl_shader_program *prog)
302 : prog(prog), in_main(false), after_return(false), control_flow(0)
303 {
304 }
305
306 virtual ~barrier_use_visitor()
307 {
308 /* empty */
309 }
310
311 virtual ir_visitor_status visit_enter(ir_function *ir)
312 {
313 if (strcmp(ir->name, "main") == 0)
314 in_main = true;
315
316 return visit_continue;
317 }
318
319 virtual ir_visitor_status visit_leave(ir_function *)
320 {
321 in_main = false;
322 after_return = false;
323 return visit_continue;
324 }
325
326 virtual ir_visitor_status visit_leave(ir_return *)
327 {
328 after_return = true;
329 return visit_continue;
330 }
331
332 virtual ir_visitor_status visit_enter(ir_if *)
333 {
334 ++control_flow;
335 return visit_continue;
336 }
337
338 virtual ir_visitor_status visit_leave(ir_if *)
339 {
340 --control_flow;
341 return visit_continue;
342 }
343
344 virtual ir_visitor_status visit_enter(ir_loop *)
345 {
346 ++control_flow;
347 return visit_continue;
348 }
349
350 virtual ir_visitor_status visit_leave(ir_loop *)
351 {
352 --control_flow;
353 return visit_continue;
354 }
355
356 /* FINISHME: `switch` is not expressed at the IR level -- it's already
357 * been lowered to a mess of `if`s. We'll correctly disallow any use of
358 * barrier() in a conditional path within the switch, but not in a path
359 * which is always hit.
360 */
361
362 virtual ir_visitor_status visit_enter(ir_call *ir)
363 {
364 if (ir->use_builtin && strcmp(ir->callee_name(), "barrier") == 0) {
365 /* Use of barrier(); determine if it is legal: */
366 if (!in_main) {
367 linker_error(prog, "Builtin barrier() may only be used in main");
368 return visit_stop;
369 }
370
371 if (after_return) {
372 linker_error(prog, "Builtin barrier() may not be used after return");
373 return visit_stop;
374 }
375
376 if (control_flow != 0) {
377 linker_error(prog, "Builtin barrier() may not be used inside control flow");
378 return visit_stop;
379 }
380 }
381 return visit_continue;
382 }
383
384 private:
385 gl_shader_program *prog;
386 bool in_main, after_return;
387 int control_flow;
388 };
389
390 /**
391 * Visitor that determines the highest stream id to which a (geometry) shader
392 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
393 */
394 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
395 public:
396 find_emit_vertex_visitor(int max_allowed)
397 : max_stream_allowed(max_allowed),
398 invalid_stream_id(0),
399 invalid_stream_id_from_emit_vertex(false),
400 end_primitive_found(false),
401 uses_non_zero_stream(false)
402 {
403 /* empty */
404 }
405
406 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
407 {
408 int stream_id = ir->stream_id();
409
410 if (stream_id < 0) {
411 invalid_stream_id = stream_id;
412 invalid_stream_id_from_emit_vertex = true;
413 return visit_stop;
414 }
415
416 if (stream_id > max_stream_allowed) {
417 invalid_stream_id = stream_id;
418 invalid_stream_id_from_emit_vertex = true;
419 return visit_stop;
420 }
421
422 if (stream_id != 0)
423 uses_non_zero_stream = true;
424
425 return visit_continue;
426 }
427
428 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
429 {
430 end_primitive_found = true;
431
432 int stream_id = ir->stream_id();
433
434 if (stream_id < 0) {
435 invalid_stream_id = stream_id;
436 invalid_stream_id_from_emit_vertex = false;
437 return visit_stop;
438 }
439
440 if (stream_id > max_stream_allowed) {
441 invalid_stream_id = stream_id;
442 invalid_stream_id_from_emit_vertex = false;
443 return visit_stop;
444 }
445
446 if (stream_id != 0)
447 uses_non_zero_stream = true;
448
449 return visit_continue;
450 }
451
452 bool error()
453 {
454 return invalid_stream_id != 0;
455 }
456
457 const char *error_func()
458 {
459 return invalid_stream_id_from_emit_vertex ?
460 "EmitStreamVertex" : "EndStreamPrimitive";
461 }
462
463 int error_stream()
464 {
465 return invalid_stream_id;
466 }
467
468 bool uses_streams()
469 {
470 return uses_non_zero_stream;
471 }
472
473 bool uses_end_primitive()
474 {
475 return end_primitive_found;
476 }
477
478 private:
479 int max_stream_allowed;
480 int invalid_stream_id;
481 bool invalid_stream_id_from_emit_vertex;
482 bool end_primitive_found;
483 bool uses_non_zero_stream;
484 };
485
486 /* Class that finds array derefs and check if indexes are dynamic. */
487 class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
488 {
489 public:
490 dynamic_sampler_array_indexing_visitor() :
491 dynamic_sampler_array_indexing(false)
492 {
493 }
494
495 ir_visitor_status visit_enter(ir_dereference_array *ir)
496 {
497 if (!ir->variable_referenced())
498 return visit_continue;
499
500 if (!ir->variable_referenced()->type->contains_sampler())
501 return visit_continue;
502
503 if (!ir->array_index->constant_expression_value()) {
504 dynamic_sampler_array_indexing = true;
505 return visit_stop;
506 }
507 return visit_continue;
508 }
509
510 bool uses_dynamic_sampler_array_indexing()
511 {
512 return dynamic_sampler_array_indexing;
513 }
514
515 private:
516 bool dynamic_sampler_array_indexing;
517 };
518
519 } /* anonymous namespace */
520
521 void
522 linker_error(gl_shader_program *prog, const char *fmt, ...)
523 {
524 va_list ap;
525
526 ralloc_strcat(&prog->InfoLog, "error: ");
527 va_start(ap, fmt);
528 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
529 va_end(ap);
530
531 prog->LinkStatus = false;
532 }
533
534
535 void
536 linker_warning(gl_shader_program *prog, const char *fmt, ...)
537 {
538 va_list ap;
539
540 ralloc_strcat(&prog->InfoLog, "warning: ");
541 va_start(ap, fmt);
542 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
543 va_end(ap);
544
545 }
546
547
548 /**
549 * Given a string identifying a program resource, break it into a base name
550 * and an optional array index in square brackets.
551 *
552 * If an array index is present, \c out_base_name_end is set to point to the
553 * "[" that precedes the array index, and the array index itself is returned
554 * as a long.
555 *
556 * If no array index is present (or if the array index is negative or
557 * mal-formed), \c out_base_name_end, is set to point to the null terminator
558 * at the end of the input string, and -1 is returned.
559 *
560 * Only the final array index is parsed; if the string contains other array
561 * indices (or structure field accesses), they are left in the base name.
562 *
563 * No attempt is made to check that the base name is properly formed;
564 * typically the caller will look up the base name in a hash table, so
565 * ill-formed base names simply turn into hash table lookup failures.
566 */
567 long
568 parse_program_resource_name(const GLchar *name,
569 const GLchar **out_base_name_end)
570 {
571 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
572 *
573 * "When an integer array element or block instance number is part of
574 * the name string, it will be specified in decimal form without a "+"
575 * or "-" sign or any extra leading zeroes. Additionally, the name
576 * string will not include white space anywhere in the string."
577 */
578
579 const size_t len = strlen(name);
580 *out_base_name_end = name + len;
581
582 if (len == 0 || name[len-1] != ']')
583 return -1;
584
585 /* Walk backwards over the string looking for a non-digit character. This
586 * had better be the opening bracket for an array index.
587 *
588 * Initially, i specifies the location of the ']'. Since the string may
589 * contain only the ']' charcater, walk backwards very carefully.
590 */
591 unsigned i;
592 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
593 /* empty */ ;
594
595 if ((i == 0) || name[i-1] != '[')
596 return -1;
597
598 long array_index = strtol(&name[i], NULL, 10);
599 if (array_index < 0)
600 return -1;
601
602 /* Check for leading zero */
603 if (name[i] == '0' && name[i+1] != ']')
604 return -1;
605
606 *out_base_name_end = name + (i - 1);
607 return array_index;
608 }
609
610
611 void
612 link_invalidate_variable_locations(exec_list *ir)
613 {
614 foreach_in_list(ir_instruction, node, ir) {
615 ir_variable *const var = node->as_variable();
616
617 if (var == NULL)
618 continue;
619
620 /* Only assign locations for variables that lack an explicit location.
621 * Explicit locations are set for all built-in variables, generic vertex
622 * shader inputs (via layout(location=...)), and generic fragment shader
623 * outputs (also via layout(location=...)).
624 */
625 if (!var->data.explicit_location) {
626 var->data.location = -1;
627 var->data.location_frac = 0;
628 }
629
630 /* ir_variable::is_unmatched_generic_inout is used by the linker while
631 * connecting outputs from one stage to inputs of the next stage.
632 */
633 if (var->data.explicit_location &&
634 var->data.location < VARYING_SLOT_VAR0) {
635 var->data.is_unmatched_generic_inout = 0;
636 } else {
637 var->data.is_unmatched_generic_inout = 1;
638 }
639 }
640 }
641
642
643 /**
644 * Set clip_distance_array_size based on the given shader.
645 *
646 * Also check for errors based on incorrect usage of gl_ClipVertex and
647 * gl_ClipDistance.
648 *
649 * Return false if an error was reported.
650 */
651 static void
652 analyze_clip_usage(struct gl_shader_program *prog,
653 struct gl_shader *shader,
654 GLuint *clip_distance_array_size)
655 {
656 *clip_distance_array_size = 0;
657
658 if (!prog->IsES && prog->Version >= 130) {
659 /* From section 7.1 (Vertex Shader Special Variables) of the
660 * GLSL 1.30 spec:
661 *
662 * "It is an error for a shader to statically write both
663 * gl_ClipVertex and gl_ClipDistance."
664 *
665 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
666 * gl_ClipVertex nor gl_ClipDistance.
667 */
668 find_assignment_visitor clip_vertex("gl_ClipVertex");
669 find_assignment_visitor clip_distance("gl_ClipDistance");
670
671 clip_vertex.run(shader->ir);
672 clip_distance.run(shader->ir);
673 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
674 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
675 "and `gl_ClipDistance'\n",
676 _mesa_shader_stage_to_string(shader->Stage));
677 return;
678 }
679
680 if (clip_distance.variable_found()) {
681 ir_variable *clip_distance_var =
682 shader->symbols->get_variable("gl_ClipDistance");
683
684 assert(clip_distance_var);
685 *clip_distance_array_size = clip_distance_var->type->length;
686 }
687 }
688 }
689
690
691 /**
692 * Verify that a vertex shader executable meets all semantic requirements.
693 *
694 * Also sets prog->Vert.ClipDistanceArraySize as a side effect.
695 *
696 * \param shader Vertex shader executable to be verified
697 */
698 void
699 validate_vertex_shader_executable(struct gl_shader_program *prog,
700 struct gl_shader *shader)
701 {
702 if (shader == NULL)
703 return;
704
705 /* From the GLSL 1.10 spec, page 48:
706 *
707 * "The variable gl_Position is available only in the vertex
708 * language and is intended for writing the homogeneous vertex
709 * position. All executions of a well-formed vertex shader
710 * executable must write a value into this variable. [...] The
711 * variable gl_Position is available only in the vertex
712 * language and is intended for writing the homogeneous vertex
713 * position. All executions of a well-formed vertex shader
714 * executable must write a value into this variable."
715 *
716 * while in GLSL 1.40 this text is changed to:
717 *
718 * "The variable gl_Position is available only in the vertex
719 * language and is intended for writing the homogeneous vertex
720 * position. It can be written at any time during shader
721 * execution. It may also be read back by a vertex shader
722 * after being written. This value will be used by primitive
723 * assembly, clipping, culling, and other fixed functionality
724 * operations, if present, that operate on primitives after
725 * vertex processing has occurred. Its value is undefined if
726 * the vertex shader executable does not write gl_Position."
727 *
728 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
729 * gl_Position is not an error.
730 */
731 if (prog->Version < (prog->IsES ? 300 : 140)) {
732 find_assignment_visitor find("gl_Position");
733 find.run(shader->ir);
734 if (!find.variable_found()) {
735 if (prog->IsES) {
736 linker_warning(prog,
737 "vertex shader does not write to `gl_Position'."
738 "It's value is undefined. \n");
739 } else {
740 linker_error(prog,
741 "vertex shader does not write to `gl_Position'. \n");
742 }
743 return;
744 }
745 }
746
747 analyze_clip_usage(prog, shader, &prog->Vert.ClipDistanceArraySize);
748 }
749
750 void
751 validate_tess_eval_shader_executable(struct gl_shader_program *prog,
752 struct gl_shader *shader)
753 {
754 if (shader == NULL)
755 return;
756
757 analyze_clip_usage(prog, shader, &prog->TessEval.ClipDistanceArraySize);
758 }
759
760
761 /**
762 * Verify that a fragment shader executable meets all semantic requirements
763 *
764 * \param shader Fragment shader executable to be verified
765 */
766 void
767 validate_fragment_shader_executable(struct gl_shader_program *prog,
768 struct gl_shader *shader)
769 {
770 if (shader == NULL)
771 return;
772
773 find_assignment_visitor frag_color("gl_FragColor");
774 find_assignment_visitor frag_data("gl_FragData");
775
776 frag_color.run(shader->ir);
777 frag_data.run(shader->ir);
778
779 if (frag_color.variable_found() && frag_data.variable_found()) {
780 linker_error(prog, "fragment shader writes to both "
781 "`gl_FragColor' and `gl_FragData'\n");
782 }
783 }
784
785 /**
786 * Verify that a geometry shader executable meets all semantic requirements
787 *
788 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize as
789 * a side effect.
790 *
791 * \param shader Geometry shader executable to be verified
792 */
793 void
794 validate_geometry_shader_executable(struct gl_shader_program *prog,
795 struct gl_shader *shader)
796 {
797 if (shader == NULL)
798 return;
799
800 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
801 prog->Geom.VerticesIn = num_vertices;
802
803 analyze_clip_usage(prog, shader, &prog->Geom.ClipDistanceArraySize);
804 }
805
806 /**
807 * Check if geometry shaders emit to non-zero streams and do corresponding
808 * validations.
809 */
810 static void
811 validate_geometry_shader_emissions(struct gl_context *ctx,
812 struct gl_shader_program *prog)
813 {
814 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
815 find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
816 emit_vertex.run(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir);
817 if (emit_vertex.error()) {
818 linker_error(prog, "Invalid call %s(%d). Accepted values for the "
819 "stream parameter are in the range [0, %d].\n",
820 emit_vertex.error_func(),
821 emit_vertex.error_stream(),
822 ctx->Const.MaxVertexStreams - 1);
823 }
824 prog->Geom.UsesStreams = emit_vertex.uses_streams();
825 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
826
827 /* From the ARB_gpu_shader5 spec:
828 *
829 * "Multiple vertex streams are supported only if the output primitive
830 * type is declared to be "points". A program will fail to link if it
831 * contains a geometry shader calling EmitStreamVertex() or
832 * EndStreamPrimitive() if its output primitive type is not "points".
833 *
834 * However, in the same spec:
835 *
836 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
837 * with <stream> set to zero."
838 *
839 * And:
840 *
841 * "The function EndPrimitive() is equivalent to calling
842 * EndStreamPrimitive() with <stream> set to zero."
843 *
844 * Since we can call EmitVertex() and EndPrimitive() when we output
845 * primitives other than points, calling EmitStreamVertex(0) or
846 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
847 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
848 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
849 * stream.
850 */
851 if (prog->Geom.UsesStreams && prog->Geom.OutputType != GL_POINTS) {
852 linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
853 "with n>0 requires point output\n");
854 }
855 }
856 }
857
858 bool
859 validate_intrastage_arrays(struct gl_shader_program *prog,
860 ir_variable *const var,
861 ir_variable *const existing)
862 {
863 /* Consider the types to be "the same" if both types are arrays
864 * of the same type and one of the arrays is implicitly sized.
865 * In addition, set the type of the linked variable to the
866 * explicitly sized array.
867 */
868 if (var->type->is_array() && existing->type->is_array()) {
869 if ((var->type->fields.array == existing->type->fields.array) &&
870 ((var->type->length == 0)|| (existing->type->length == 0))) {
871 if (var->type->length != 0) {
872 if (var->type->length <= existing->data.max_array_access) {
873 linker_error(prog, "%s `%s' declared as type "
874 "`%s' but outermost dimension has an index"
875 " of `%i'\n",
876 mode_string(var),
877 var->name, var->type->name,
878 existing->data.max_array_access);
879 }
880 existing->type = var->type;
881 return true;
882 } else if (existing->type->length != 0) {
883 if(existing->type->length <= var->data.max_array_access &&
884 !existing->data.from_ssbo_unsized_array) {
885 linker_error(prog, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
887 " of `%i'\n",
888 mode_string(var),
889 var->name, existing->type->name,
890 var->data.max_array_access);
891 }
892 return true;
893 }
894 } else {
895 /* The arrays of structs could have different glsl_type pointers but
896 * they are actually the same type. Use record_compare() to check that.
897 */
898 if (existing->type->fields.array->is_record() &&
899 var->type->fields.array->is_record() &&
900 existing->type->fields.array->record_compare(var->type->fields.array))
901 return true;
902 }
903 }
904 return false;
905 }
906
907
908 /**
909 * Perform validation of global variables used across multiple shaders
910 */
911 void
912 cross_validate_globals(struct gl_shader_program *prog,
913 struct gl_shader **shader_list,
914 unsigned num_shaders,
915 bool uniforms_only)
916 {
917 /* Examine all of the uniforms in all of the shaders and cross validate
918 * them.
919 */
920 glsl_symbol_table variables;
921 for (unsigned i = 0; i < num_shaders; i++) {
922 if (shader_list[i] == NULL)
923 continue;
924
925 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
926 ir_variable *const var = node->as_variable();
927
928 if (var == NULL)
929 continue;
930
931 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
932 continue;
933
934 /* don't cross validate subroutine uniforms */
935 if (var->type->contains_subroutine())
936 continue;
937
938 /* Don't cross validate temporaries that are at global scope. These
939 * will eventually get pulled into the shaders 'main'.
940 */
941 if (var->data.mode == ir_var_temporary)
942 continue;
943
944 /* If a global with this name has already been seen, verify that the
945 * new instance has the same type. In addition, if the globals have
946 * initializers, the values of the initializers must be the same.
947 */
948 ir_variable *const existing = variables.get_variable(var->name);
949 if (existing != NULL) {
950 /* Check if types match. Interface blocks have some special
951 * rules so we handle those elsewhere.
952 */
953 if (var->type != existing->type &&
954 !var->is_interface_instance()) {
955 if (!validate_intrastage_arrays(prog, var, existing)) {
956 if (var->type->is_record() && existing->type->is_record()
957 && existing->type->record_compare(var->type)) {
958 existing->type = var->type;
959 } else {
960 /* If it is an unsized array in a Shader Storage Block,
961 * two different shaders can access to different elements.
962 * Because of that, they might be converted to different
963 * sized arrays, then check that they are compatible but
964 * ignore the array size.
965 */
966 if (!(var->data.mode == ir_var_shader_storage &&
967 var->data.from_ssbo_unsized_array &&
968 existing->data.mode == ir_var_shader_storage &&
969 existing->data.from_ssbo_unsized_array &&
970 var->type->gl_type == existing->type->gl_type)) {
971 linker_error(prog, "%s `%s' declared as type "
972 "`%s' and type `%s'\n",
973 mode_string(var),
974 var->name, var->type->name,
975 existing->type->name);
976 return;
977 }
978 }
979 }
980 }
981
982 if (var->data.explicit_location) {
983 if (existing->data.explicit_location
984 && (var->data.location != existing->data.location)) {
985 linker_error(prog, "explicit locations for %s "
986 "`%s' have differing values\n",
987 mode_string(var), var->name);
988 return;
989 }
990
991 existing->data.location = var->data.location;
992 existing->data.explicit_location = true;
993 } else {
994 /* Check if uniform with implicit location was marked explicit
995 * by earlier shader stage. If so, mark it explicit in this stage
996 * too to make sure later processing does not treat it as
997 * implicit one.
998 */
999 if (existing->data.explicit_location) {
1000 var->data.location = existing->data.location;
1001 var->data.explicit_location = true;
1002 }
1003 }
1004
1005 /* From the GLSL 4.20 specification:
1006 * "A link error will result if two compilation units in a program
1007 * specify different integer-constant bindings for the same
1008 * opaque-uniform name. However, it is not an error to specify a
1009 * binding on some but not all declarations for the same name"
1010 */
1011 if (var->data.explicit_binding) {
1012 if (existing->data.explicit_binding &&
1013 var->data.binding != existing->data.binding) {
1014 linker_error(prog, "explicit bindings for %s "
1015 "`%s' have differing values\n",
1016 mode_string(var), var->name);
1017 return;
1018 }
1019
1020 existing->data.binding = var->data.binding;
1021 existing->data.explicit_binding = true;
1022 }
1023
1024 if (var->type->contains_atomic() &&
1025 var->data.offset != existing->data.offset) {
1026 linker_error(prog, "offset specifications for %s "
1027 "`%s' have differing values\n",
1028 mode_string(var), var->name);
1029 return;
1030 }
1031
1032 /* Validate layout qualifiers for gl_FragDepth.
1033 *
1034 * From the AMD/ARB_conservative_depth specs:
1035 *
1036 * "If gl_FragDepth is redeclared in any fragment shader in a
1037 * program, it must be redeclared in all fragment shaders in
1038 * that program that have static assignments to
1039 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1040 * fragment shaders in a single program must have the same set
1041 * of qualifiers."
1042 */
1043 if (strcmp(var->name, "gl_FragDepth") == 0) {
1044 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
1045 bool layout_differs =
1046 var->data.depth_layout != existing->data.depth_layout;
1047
1048 if (layout_declared && layout_differs) {
1049 linker_error(prog,
1050 "All redeclarations of gl_FragDepth in all "
1051 "fragment shaders in a single program must have "
1052 "the same set of qualifiers.\n");
1053 }
1054
1055 if (var->data.used && layout_differs) {
1056 linker_error(prog,
1057 "If gl_FragDepth is redeclared with a layout "
1058 "qualifier in any fragment shader, it must be "
1059 "redeclared with the same layout qualifier in "
1060 "all fragment shaders that have assignments to "
1061 "gl_FragDepth\n");
1062 }
1063 }
1064
1065 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1066 *
1067 * "If a shared global has multiple initializers, the
1068 * initializers must all be constant expressions, and they
1069 * must all have the same value. Otherwise, a link error will
1070 * result. (A shared global having only one initializer does
1071 * not require that initializer to be a constant expression.)"
1072 *
1073 * Previous to 4.20 the GLSL spec simply said that initializers
1074 * must have the same value. In this case of non-constant
1075 * initializers, this was impossible to determine. As a result,
1076 * no vendor actually implemented that behavior. The 4.20
1077 * behavior matches the implemented behavior of at least one other
1078 * vendor, so we'll implement that for all GLSL versions.
1079 */
1080 if (var->constant_initializer != NULL) {
1081 if (existing->constant_initializer != NULL) {
1082 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
1083 linker_error(prog, "initializers for %s "
1084 "`%s' have differing values\n",
1085 mode_string(var), var->name);
1086 return;
1087 }
1088 } else {
1089 /* If the first-seen instance of a particular uniform did not
1090 * have an initializer but a later instance does, copy the
1091 * initializer to the version stored in the symbol table.
1092 */
1093 /* FINISHME: This is wrong. The constant_value field should
1094 * FINISHME: not be modified! Imagine a case where a shader
1095 * FINISHME: without an initializer is linked in two different
1096 * FINISHME: programs with shaders that have differing
1097 * FINISHME: initializers. Linking with the first will
1098 * FINISHME: modify the shader, and linking with the second
1099 * FINISHME: will fail.
1100 */
1101 existing->constant_initializer =
1102 var->constant_initializer->clone(ralloc_parent(existing),
1103 NULL);
1104 }
1105 }
1106
1107 if (var->data.has_initializer) {
1108 if (existing->data.has_initializer
1109 && (var->constant_initializer == NULL
1110 || existing->constant_initializer == NULL)) {
1111 linker_error(prog,
1112 "shared global variable `%s' has multiple "
1113 "non-constant initializers.\n",
1114 var->name);
1115 return;
1116 }
1117
1118 /* Some instance had an initializer, so keep track of that. In
1119 * this location, all sorts of initializers (constant or
1120 * otherwise) will propagate the existence to the variable
1121 * stored in the symbol table.
1122 */
1123 existing->data.has_initializer = true;
1124 }
1125
1126 if (existing->data.invariant != var->data.invariant) {
1127 linker_error(prog, "declarations for %s `%s' have "
1128 "mismatching invariant qualifiers\n",
1129 mode_string(var), var->name);
1130 return;
1131 }
1132 if (existing->data.centroid != var->data.centroid) {
1133 linker_error(prog, "declarations for %s `%s' have "
1134 "mismatching centroid qualifiers\n",
1135 mode_string(var), var->name);
1136 return;
1137 }
1138 if (existing->data.sample != var->data.sample) {
1139 linker_error(prog, "declarations for %s `%s` have "
1140 "mismatching sample qualifiers\n",
1141 mode_string(var), var->name);
1142 return;
1143 }
1144 if (existing->data.image_format != var->data.image_format) {
1145 linker_error(prog, "declarations for %s `%s` have "
1146 "mismatching image format qualifiers\n",
1147 mode_string(var), var->name);
1148 return;
1149 }
1150 } else
1151 variables.add_variable(var);
1152 }
1153 }
1154 }
1155
1156
1157 /**
1158 * Perform validation of uniforms used across multiple shader stages
1159 */
1160 void
1161 cross_validate_uniforms(struct gl_shader_program *prog)
1162 {
1163 cross_validate_globals(prog, prog->_LinkedShaders,
1164 MESA_SHADER_STAGES, true);
1165 }
1166
1167 /**
1168 * Accumulates the array of prog->BufferInterfaceBlocks and checks that all
1169 * definitons of blocks agree on their contents.
1170 */
1171 static bool
1172 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
1173 {
1174 unsigned max_num_uniform_blocks = 0;
1175 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1176 if (prog->_LinkedShaders[i])
1177 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumBufferInterfaceBlocks;
1178 }
1179
1180 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1181 struct gl_shader *sh = prog->_LinkedShaders[i];
1182
1183 prog->InterfaceBlockStageIndex[i] = ralloc_array(prog, int,
1184 max_num_uniform_blocks);
1185 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
1186 prog->InterfaceBlockStageIndex[i][j] = -1;
1187
1188 if (sh == NULL)
1189 continue;
1190
1191 for (unsigned int j = 0; j < sh->NumBufferInterfaceBlocks; j++) {
1192 int index = link_cross_validate_uniform_block(prog,
1193 &prog->BufferInterfaceBlocks,
1194 &prog->NumBufferInterfaceBlocks,
1195 &sh->BufferInterfaceBlocks[j]);
1196
1197 if (index == -1) {
1198 linker_error(prog, "uniform block `%s' has mismatching definitions\n",
1199 sh->BufferInterfaceBlocks[j].Name);
1200 return false;
1201 }
1202
1203 prog->InterfaceBlockStageIndex[i][index] = j;
1204 }
1205 }
1206
1207 return true;
1208 }
1209
1210
1211 /**
1212 * Populates a shaders symbol table with all global declarations
1213 */
1214 static void
1215 populate_symbol_table(gl_shader *sh)
1216 {
1217 sh->symbols = new(sh) glsl_symbol_table;
1218
1219 foreach_in_list(ir_instruction, inst, sh->ir) {
1220 ir_variable *var;
1221 ir_function *func;
1222
1223 if ((func = inst->as_function()) != NULL) {
1224 sh->symbols->add_function(func);
1225 } else if ((var = inst->as_variable()) != NULL) {
1226 if (var->data.mode != ir_var_temporary)
1227 sh->symbols->add_variable(var);
1228 }
1229 }
1230 }
1231
1232
1233 /**
1234 * Remap variables referenced in an instruction tree
1235 *
1236 * This is used when instruction trees are cloned from one shader and placed in
1237 * another. These trees will contain references to \c ir_variable nodes that
1238 * do not exist in the target shader. This function finds these \c ir_variable
1239 * references and replaces the references with matching variables in the target
1240 * shader.
1241 *
1242 * If there is no matching variable in the target shader, a clone of the
1243 * \c ir_variable is made and added to the target shader. The new variable is
1244 * added to \b both the instruction stream and the symbol table.
1245 *
1246 * \param inst IR tree that is to be processed.
1247 * \param symbols Symbol table containing global scope symbols in the
1248 * linked shader.
1249 * \param instructions Instruction stream where new variable declarations
1250 * should be added.
1251 */
1252 void
1253 remap_variables(ir_instruction *inst, struct gl_shader *target,
1254 hash_table *temps)
1255 {
1256 class remap_visitor : public ir_hierarchical_visitor {
1257 public:
1258 remap_visitor(struct gl_shader *target,
1259 hash_table *temps)
1260 {
1261 this->target = target;
1262 this->symbols = target->symbols;
1263 this->instructions = target->ir;
1264 this->temps = temps;
1265 }
1266
1267 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1268 {
1269 if (ir->var->data.mode == ir_var_temporary) {
1270 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1271
1272 assert(var != NULL);
1273 ir->var = var;
1274 return visit_continue;
1275 }
1276
1277 ir_variable *const existing =
1278 this->symbols->get_variable(ir->var->name);
1279 if (existing != NULL)
1280 ir->var = existing;
1281 else {
1282 ir_variable *copy = ir->var->clone(this->target, NULL);
1283
1284 this->symbols->add_variable(copy);
1285 this->instructions->push_head(copy);
1286 ir->var = copy;
1287 }
1288
1289 return visit_continue;
1290 }
1291
1292 private:
1293 struct gl_shader *target;
1294 glsl_symbol_table *symbols;
1295 exec_list *instructions;
1296 hash_table *temps;
1297 };
1298
1299 remap_visitor v(target, temps);
1300
1301 inst->accept(&v);
1302 }
1303
1304
1305 /**
1306 * Move non-declarations from one instruction stream to another
1307 *
1308 * The intended usage pattern of this function is to pass the pointer to the
1309 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1310 * pointer) for \c last and \c false for \c make_copies on the first
1311 * call. Successive calls pass the return value of the previous call for
1312 * \c last and \c true for \c make_copies.
1313 *
1314 * \param instructions Source instruction stream
1315 * \param last Instruction after which new instructions should be
1316 * inserted in the target instruction stream
1317 * \param make_copies Flag selecting whether instructions in \c instructions
1318 * should be copied (via \c ir_instruction::clone) into the
1319 * target list or moved.
1320 *
1321 * \return
1322 * The new "last" instruction in the target instruction stream. This pointer
1323 * is suitable for use as the \c last parameter of a later call to this
1324 * function.
1325 */
1326 exec_node *
1327 move_non_declarations(exec_list *instructions, exec_node *last,
1328 bool make_copies, gl_shader *target)
1329 {
1330 hash_table *temps = NULL;
1331
1332 if (make_copies)
1333 temps = hash_table_ctor(0, hash_table_pointer_hash,
1334 hash_table_pointer_compare);
1335
1336 foreach_in_list_safe(ir_instruction, inst, instructions) {
1337 if (inst->as_function())
1338 continue;
1339
1340 ir_variable *var = inst->as_variable();
1341 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1342 continue;
1343
1344 assert(inst->as_assignment()
1345 || inst->as_call()
1346 || inst->as_if() /* for initializers with the ?: operator */
1347 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1348
1349 if (make_copies) {
1350 inst = inst->clone(target, NULL);
1351
1352 if (var != NULL)
1353 hash_table_insert(temps, inst, var);
1354 else
1355 remap_variables(inst, target, temps);
1356 } else {
1357 inst->remove();
1358 }
1359
1360 last->insert_after(inst);
1361 last = inst;
1362 }
1363
1364 if (make_copies)
1365 hash_table_dtor(temps);
1366
1367 return last;
1368 }
1369
1370
1371 /**
1372 * This class is only used in link_intrastage_shaders() below but declaring
1373 * it inside that function leads to compiler warnings with some versions of
1374 * gcc.
1375 */
1376 class array_sizing_visitor : public ir_hierarchical_visitor {
1377 public:
1378 array_sizing_visitor()
1379 : mem_ctx(ralloc_context(NULL)),
1380 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1381 hash_table_pointer_compare))
1382 {
1383 }
1384
1385 ~array_sizing_visitor()
1386 {
1387 hash_table_dtor(this->unnamed_interfaces);
1388 ralloc_free(this->mem_ctx);
1389 }
1390
1391 virtual ir_visitor_status visit(ir_variable *var)
1392 {
1393 const glsl_type *type_without_array;
1394 fixup_type(&var->type, var->data.max_array_access,
1395 var->data.from_ssbo_unsized_array);
1396 type_without_array = var->type->without_array();
1397 if (var->type->is_interface()) {
1398 if (interface_contains_unsized_arrays(var->type)) {
1399 const glsl_type *new_type =
1400 resize_interface_members(var->type,
1401 var->get_max_ifc_array_access(),
1402 var->is_in_shader_storage_block());
1403 var->type = new_type;
1404 var->change_interface_type(new_type);
1405 }
1406 } else if (type_without_array->is_interface()) {
1407 if (interface_contains_unsized_arrays(type_without_array)) {
1408 const glsl_type *new_type =
1409 resize_interface_members(type_without_array,
1410 var->get_max_ifc_array_access(),
1411 var->is_in_shader_storage_block());
1412 var->change_interface_type(new_type);
1413 var->type = update_interface_members_array(var->type, new_type);
1414 }
1415 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1416 /* Store a pointer to the variable in the unnamed_interfaces
1417 * hashtable.
1418 */
1419 ir_variable **interface_vars = (ir_variable **)
1420 hash_table_find(this->unnamed_interfaces, ifc_type);
1421 if (interface_vars == NULL) {
1422 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1423 ifc_type->length);
1424 hash_table_insert(this->unnamed_interfaces, interface_vars,
1425 ifc_type);
1426 }
1427 unsigned index = ifc_type->field_index(var->name);
1428 assert(index < ifc_type->length);
1429 assert(interface_vars[index] == NULL);
1430 interface_vars[index] = var;
1431 }
1432 return visit_continue;
1433 }
1434
1435 /**
1436 * For each unnamed interface block that was discovered while running the
1437 * visitor, adjust the interface type to reflect the newly assigned array
1438 * sizes, and fix up the ir_variable nodes to point to the new interface
1439 * type.
1440 */
1441 void fixup_unnamed_interface_types()
1442 {
1443 hash_table_call_foreach(this->unnamed_interfaces,
1444 fixup_unnamed_interface_type, NULL);
1445 }
1446
1447 private:
1448 /**
1449 * If the type pointed to by \c type represents an unsized array, replace
1450 * it with a sized array whose size is determined by max_array_access.
1451 */
1452 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1453 bool from_ssbo_unsized_array)
1454 {
1455 if (!from_ssbo_unsized_array && (*type)->is_unsized_array()) {
1456 *type = glsl_type::get_array_instance((*type)->fields.array,
1457 max_array_access + 1);
1458 assert(*type != NULL);
1459 }
1460 }
1461
1462 static const glsl_type *
1463 update_interface_members_array(const glsl_type *type,
1464 const glsl_type *new_interface_type)
1465 {
1466 const glsl_type *element_type = type->fields.array;
1467 if (element_type->is_array()) {
1468 const glsl_type *new_array_type =
1469 update_interface_members_array(element_type, new_interface_type);
1470 return glsl_type::get_array_instance(new_array_type, type->length);
1471 } else {
1472 return glsl_type::get_array_instance(new_interface_type,
1473 type->length);
1474 }
1475 }
1476
1477 /**
1478 * Determine whether the given interface type contains unsized arrays (if
1479 * it doesn't, array_sizing_visitor doesn't need to process it).
1480 */
1481 static bool interface_contains_unsized_arrays(const glsl_type *type)
1482 {
1483 for (unsigned i = 0; i < type->length; i++) {
1484 const glsl_type *elem_type = type->fields.structure[i].type;
1485 if (elem_type->is_unsized_array())
1486 return true;
1487 }
1488 return false;
1489 }
1490
1491 /**
1492 * Create a new interface type based on the given type, with unsized arrays
1493 * replaced by sized arrays whose size is determined by
1494 * max_ifc_array_access.
1495 */
1496 static const glsl_type *
1497 resize_interface_members(const glsl_type *type,
1498 const unsigned *max_ifc_array_access,
1499 bool is_ssbo)
1500 {
1501 unsigned num_fields = type->length;
1502 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1503 memcpy(fields, type->fields.structure,
1504 num_fields * sizeof(*fields));
1505 for (unsigned i = 0; i < num_fields; i++) {
1506 /* If SSBO last member is unsized array, we don't replace it by a sized
1507 * array.
1508 */
1509 if (is_ssbo && i == (num_fields - 1))
1510 fixup_type(&fields[i].type, max_ifc_array_access[i],
1511 true);
1512 else
1513 fixup_type(&fields[i].type, max_ifc_array_access[i],
1514 false);
1515 }
1516 glsl_interface_packing packing =
1517 (glsl_interface_packing) type->interface_packing;
1518 const glsl_type *new_ifc_type =
1519 glsl_type::get_interface_instance(fields, num_fields,
1520 packing, type->name);
1521 delete [] fields;
1522 return new_ifc_type;
1523 }
1524
1525 static void fixup_unnamed_interface_type(const void *key, void *data,
1526 void *)
1527 {
1528 const glsl_type *ifc_type = (const glsl_type *) key;
1529 ir_variable **interface_vars = (ir_variable **) data;
1530 unsigned num_fields = ifc_type->length;
1531 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1532 memcpy(fields, ifc_type->fields.structure,
1533 num_fields * sizeof(*fields));
1534 bool interface_type_changed = false;
1535 for (unsigned i = 0; i < num_fields; i++) {
1536 if (interface_vars[i] != NULL &&
1537 fields[i].type != interface_vars[i]->type) {
1538 fields[i].type = interface_vars[i]->type;
1539 interface_type_changed = true;
1540 }
1541 }
1542 if (!interface_type_changed) {
1543 delete [] fields;
1544 return;
1545 }
1546 glsl_interface_packing packing =
1547 (glsl_interface_packing) ifc_type->interface_packing;
1548 const glsl_type *new_ifc_type =
1549 glsl_type::get_interface_instance(fields, num_fields, packing,
1550 ifc_type->name);
1551 delete [] fields;
1552 for (unsigned i = 0; i < num_fields; i++) {
1553 if (interface_vars[i] != NULL)
1554 interface_vars[i]->change_interface_type(new_ifc_type);
1555 }
1556 }
1557
1558 /**
1559 * Memory context used to allocate the data in \c unnamed_interfaces.
1560 */
1561 void *mem_ctx;
1562
1563 /**
1564 * Hash table from const glsl_type * to an array of ir_variable *'s
1565 * pointing to the ir_variables constituting each unnamed interface block.
1566 */
1567 hash_table *unnamed_interfaces;
1568 };
1569
1570
1571 /**
1572 * Performs the cross-validation of tessellation control shader vertices and
1573 * layout qualifiers for the attached tessellation control shaders,
1574 * and propagates them to the linked TCS and linked shader program.
1575 */
1576 static void
1577 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1578 struct gl_shader *linked_shader,
1579 struct gl_shader **shader_list,
1580 unsigned num_shaders)
1581 {
1582 linked_shader->TessCtrl.VerticesOut = 0;
1583
1584 if (linked_shader->Stage != MESA_SHADER_TESS_CTRL)
1585 return;
1586
1587 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1588 *
1589 * "All tessellation control shader layout declarations in a program
1590 * must specify the same output patch vertex count. There must be at
1591 * least one layout qualifier specifying an output patch vertex count
1592 * in any program containing tessellation control shaders; however,
1593 * such a declaration is not required in all tessellation control
1594 * shaders."
1595 */
1596
1597 for (unsigned i = 0; i < num_shaders; i++) {
1598 struct gl_shader *shader = shader_list[i];
1599
1600 if (shader->TessCtrl.VerticesOut != 0) {
1601 if (linked_shader->TessCtrl.VerticesOut != 0 &&
1602 linked_shader->TessCtrl.VerticesOut != shader->TessCtrl.VerticesOut) {
1603 linker_error(prog, "tessellation control shader defined with "
1604 "conflicting output vertex count (%d and %d)\n",
1605 linked_shader->TessCtrl.VerticesOut,
1606 shader->TessCtrl.VerticesOut);
1607 return;
1608 }
1609 linked_shader->TessCtrl.VerticesOut = shader->TessCtrl.VerticesOut;
1610 }
1611 }
1612
1613 /* Just do the intrastage -> interstage propagation right now,
1614 * since we already know we're in the right type of shader program
1615 * for doing it.
1616 */
1617 if (linked_shader->TessCtrl.VerticesOut == 0) {
1618 linker_error(prog, "tessellation control shader didn't declare "
1619 "vertices out layout qualifier\n");
1620 return;
1621 }
1622 prog->TessCtrl.VerticesOut = linked_shader->TessCtrl.VerticesOut;
1623 }
1624
1625
1626 /**
1627 * Performs the cross-validation of tessellation evaluation shader
1628 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1629 * for the attached tessellation evaluation shaders, and propagates them
1630 * to the linked TES and linked shader program.
1631 */
1632 static void
1633 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1634 struct gl_shader *linked_shader,
1635 struct gl_shader **shader_list,
1636 unsigned num_shaders)
1637 {
1638 linked_shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1639 linked_shader->TessEval.Spacing = 0;
1640 linked_shader->TessEval.VertexOrder = 0;
1641 linked_shader->TessEval.PointMode = -1;
1642
1643 if (linked_shader->Stage != MESA_SHADER_TESS_EVAL)
1644 return;
1645
1646 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1647 *
1648 * "At least one tessellation evaluation shader (compilation unit) in
1649 * a program must declare a primitive mode in its input layout.
1650 * Declaration vertex spacing, ordering, and point mode identifiers is
1651 * optional. It is not required that all tessellation evaluation
1652 * shaders in a program declare a primitive mode. If spacing or
1653 * vertex ordering declarations are omitted, the tessellation
1654 * primitive generator will use equal spacing or counter-clockwise
1655 * vertex ordering, respectively. If a point mode declaration is
1656 * omitted, the tessellation primitive generator will produce lines or
1657 * triangles according to the primitive mode."
1658 */
1659
1660 for (unsigned i = 0; i < num_shaders; i++) {
1661 struct gl_shader *shader = shader_list[i];
1662
1663 if (shader->TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1664 if (linked_shader->TessEval.PrimitiveMode != PRIM_UNKNOWN &&
1665 linked_shader->TessEval.PrimitiveMode != shader->TessEval.PrimitiveMode) {
1666 linker_error(prog, "tessellation evaluation shader defined with "
1667 "conflicting input primitive modes.\n");
1668 return;
1669 }
1670 linked_shader->TessEval.PrimitiveMode = shader->TessEval.PrimitiveMode;
1671 }
1672
1673 if (shader->TessEval.Spacing != 0) {
1674 if (linked_shader->TessEval.Spacing != 0 &&
1675 linked_shader->TessEval.Spacing != shader->TessEval.Spacing) {
1676 linker_error(prog, "tessellation evaluation shader defined with "
1677 "conflicting vertex spacing.\n");
1678 return;
1679 }
1680 linked_shader->TessEval.Spacing = shader->TessEval.Spacing;
1681 }
1682
1683 if (shader->TessEval.VertexOrder != 0) {
1684 if (linked_shader->TessEval.VertexOrder != 0 &&
1685 linked_shader->TessEval.VertexOrder != shader->TessEval.VertexOrder) {
1686 linker_error(prog, "tessellation evaluation shader defined with "
1687 "conflicting ordering.\n");
1688 return;
1689 }
1690 linked_shader->TessEval.VertexOrder = shader->TessEval.VertexOrder;
1691 }
1692
1693 if (shader->TessEval.PointMode != -1) {
1694 if (linked_shader->TessEval.PointMode != -1 &&
1695 linked_shader->TessEval.PointMode != shader->TessEval.PointMode) {
1696 linker_error(prog, "tessellation evaluation shader defined with "
1697 "conflicting point modes.\n");
1698 return;
1699 }
1700 linked_shader->TessEval.PointMode = shader->TessEval.PointMode;
1701 }
1702
1703 }
1704
1705 /* Just do the intrastage -> interstage propagation right now,
1706 * since we already know we're in the right type of shader program
1707 * for doing it.
1708 */
1709 if (linked_shader->TessEval.PrimitiveMode == PRIM_UNKNOWN) {
1710 linker_error(prog,
1711 "tessellation evaluation shader didn't declare input "
1712 "primitive modes.\n");
1713 return;
1714 }
1715 prog->TessEval.PrimitiveMode = linked_shader->TessEval.PrimitiveMode;
1716
1717 if (linked_shader->TessEval.Spacing == 0)
1718 linked_shader->TessEval.Spacing = GL_EQUAL;
1719 prog->TessEval.Spacing = linked_shader->TessEval.Spacing;
1720
1721 if (linked_shader->TessEval.VertexOrder == 0)
1722 linked_shader->TessEval.VertexOrder = GL_CCW;
1723 prog->TessEval.VertexOrder = linked_shader->TessEval.VertexOrder;
1724
1725 if (linked_shader->TessEval.PointMode == -1)
1726 linked_shader->TessEval.PointMode = GL_FALSE;
1727 prog->TessEval.PointMode = linked_shader->TessEval.PointMode;
1728 }
1729
1730
1731 /**
1732 * Performs the cross-validation of layout qualifiers specified in
1733 * redeclaration of gl_FragCoord for the attached fragment shaders,
1734 * and propagates them to the linked FS and linked shader program.
1735 */
1736 static void
1737 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1738 struct gl_shader *linked_shader,
1739 struct gl_shader **shader_list,
1740 unsigned num_shaders)
1741 {
1742 linked_shader->redeclares_gl_fragcoord = false;
1743 linked_shader->uses_gl_fragcoord = false;
1744 linked_shader->origin_upper_left = false;
1745 linked_shader->pixel_center_integer = false;
1746
1747 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1748 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1749 return;
1750
1751 for (unsigned i = 0; i < num_shaders; i++) {
1752 struct gl_shader *shader = shader_list[i];
1753 /* From the GLSL 1.50 spec, page 39:
1754 *
1755 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1756 * it must be redeclared in all the fragment shaders in that program
1757 * that have a static use gl_FragCoord."
1758 */
1759 if ((linked_shader->redeclares_gl_fragcoord
1760 && !shader->redeclares_gl_fragcoord
1761 && shader->uses_gl_fragcoord)
1762 || (shader->redeclares_gl_fragcoord
1763 && !linked_shader->redeclares_gl_fragcoord
1764 && linked_shader->uses_gl_fragcoord)) {
1765 linker_error(prog, "fragment shader defined with conflicting "
1766 "layout qualifiers for gl_FragCoord\n");
1767 }
1768
1769 /* From the GLSL 1.50 spec, page 39:
1770 *
1771 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1772 * single program must have the same set of qualifiers."
1773 */
1774 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1775 && (shader->origin_upper_left != linked_shader->origin_upper_left
1776 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1777 linker_error(prog, "fragment shader defined with conflicting "
1778 "layout qualifiers for gl_FragCoord\n");
1779 }
1780
1781 /* Update the linked shader state. Note that uses_gl_fragcoord should
1782 * accumulate the results. The other values should replace. If there
1783 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1784 * are already known to be the same.
1785 */
1786 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1787 linked_shader->redeclares_gl_fragcoord =
1788 shader->redeclares_gl_fragcoord;
1789 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1790 || shader->uses_gl_fragcoord;
1791 linked_shader->origin_upper_left = shader->origin_upper_left;
1792 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1793 }
1794
1795 linked_shader->EarlyFragmentTests |= shader->EarlyFragmentTests;
1796 }
1797 }
1798
1799 /**
1800 * Performs the cross-validation of geometry shader max_vertices and
1801 * primitive type layout qualifiers for the attached geometry shaders,
1802 * and propagates them to the linked GS and linked shader program.
1803 */
1804 static void
1805 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1806 struct gl_shader *linked_shader,
1807 struct gl_shader **shader_list,
1808 unsigned num_shaders)
1809 {
1810 linked_shader->Geom.VerticesOut = 0;
1811 linked_shader->Geom.Invocations = 0;
1812 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1813 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1814
1815 /* No in/out qualifiers defined for anything but GLSL 1.50+
1816 * geometry shaders so far.
1817 */
1818 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1819 return;
1820
1821 /* From the GLSL 1.50 spec, page 46:
1822 *
1823 * "All geometry shader output layout declarations in a program
1824 * must declare the same layout and same value for
1825 * max_vertices. There must be at least one geometry output
1826 * layout declaration somewhere in a program, but not all
1827 * geometry shaders (compilation units) are required to
1828 * declare it."
1829 */
1830
1831 for (unsigned i = 0; i < num_shaders; i++) {
1832 struct gl_shader *shader = shader_list[i];
1833
1834 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1835 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1836 linked_shader->Geom.InputType != shader->Geom.InputType) {
1837 linker_error(prog, "geometry shader defined with conflicting "
1838 "input types\n");
1839 return;
1840 }
1841 linked_shader->Geom.InputType = shader->Geom.InputType;
1842 }
1843
1844 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1845 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1846 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1847 linker_error(prog, "geometry shader defined with conflicting "
1848 "output types\n");
1849 return;
1850 }
1851 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1852 }
1853
1854 if (shader->Geom.VerticesOut != 0) {
1855 if (linked_shader->Geom.VerticesOut != 0 &&
1856 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1857 linker_error(prog, "geometry shader defined with conflicting "
1858 "output vertex count (%d and %d)\n",
1859 linked_shader->Geom.VerticesOut,
1860 shader->Geom.VerticesOut);
1861 return;
1862 }
1863 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1864 }
1865
1866 if (shader->Geom.Invocations != 0) {
1867 if (linked_shader->Geom.Invocations != 0 &&
1868 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1869 linker_error(prog, "geometry shader defined with conflicting "
1870 "invocation count (%d and %d)\n",
1871 linked_shader->Geom.Invocations,
1872 shader->Geom.Invocations);
1873 return;
1874 }
1875 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1876 }
1877 }
1878
1879 /* Just do the intrastage -> interstage propagation right now,
1880 * since we already know we're in the right type of shader program
1881 * for doing it.
1882 */
1883 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1884 linker_error(prog,
1885 "geometry shader didn't declare primitive input type\n");
1886 return;
1887 }
1888 prog->Geom.InputType = linked_shader->Geom.InputType;
1889
1890 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1891 linker_error(prog,
1892 "geometry shader didn't declare primitive output type\n");
1893 return;
1894 }
1895 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1896
1897 if (linked_shader->Geom.VerticesOut == 0) {
1898 linker_error(prog,
1899 "geometry shader didn't declare max_vertices\n");
1900 return;
1901 }
1902 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1903
1904 if (linked_shader->Geom.Invocations == 0)
1905 linked_shader->Geom.Invocations = 1;
1906
1907 prog->Geom.Invocations = linked_shader->Geom.Invocations;
1908 }
1909
1910
1911 /**
1912 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1913 * qualifiers for the attached compute shaders, and propagate them to the
1914 * linked CS and linked shader program.
1915 */
1916 static void
1917 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1918 struct gl_shader *linked_shader,
1919 struct gl_shader **shader_list,
1920 unsigned num_shaders)
1921 {
1922 for (int i = 0; i < 3; i++)
1923 linked_shader->Comp.LocalSize[i] = 0;
1924
1925 /* This function is called for all shader stages, but it only has an effect
1926 * for compute shaders.
1927 */
1928 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1929 return;
1930
1931 /* From the ARB_compute_shader spec, in the section describing local size
1932 * declarations:
1933 *
1934 * If multiple compute shaders attached to a single program object
1935 * declare local work-group size, the declarations must be identical;
1936 * otherwise a link-time error results. Furthermore, if a program
1937 * object contains any compute shaders, at least one must contain an
1938 * input layout qualifier specifying the local work sizes of the
1939 * program, or a link-time error will occur.
1940 */
1941 for (unsigned sh = 0; sh < num_shaders; sh++) {
1942 struct gl_shader *shader = shader_list[sh];
1943
1944 if (shader->Comp.LocalSize[0] != 0) {
1945 if (linked_shader->Comp.LocalSize[0] != 0) {
1946 for (int i = 0; i < 3; i++) {
1947 if (linked_shader->Comp.LocalSize[i] !=
1948 shader->Comp.LocalSize[i]) {
1949 linker_error(prog, "compute shader defined with conflicting "
1950 "local sizes\n");
1951 return;
1952 }
1953 }
1954 }
1955 for (int i = 0; i < 3; i++)
1956 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1957 }
1958 }
1959
1960 /* Just do the intrastage -> interstage propagation right now,
1961 * since we already know we're in the right type of shader program
1962 * for doing it.
1963 */
1964 if (linked_shader->Comp.LocalSize[0] == 0) {
1965 linker_error(prog, "compute shader didn't declare local size\n");
1966 return;
1967 }
1968 for (int i = 0; i < 3; i++)
1969 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1970 }
1971
1972
1973 /**
1974 * Combine a group of shaders for a single stage to generate a linked shader
1975 *
1976 * \note
1977 * If this function is supplied a single shader, it is cloned, and the new
1978 * shader is returned.
1979 */
1980 static struct gl_shader *
1981 link_intrastage_shaders(void *mem_ctx,
1982 struct gl_context *ctx,
1983 struct gl_shader_program *prog,
1984 struct gl_shader **shader_list,
1985 unsigned num_shaders)
1986 {
1987 struct gl_uniform_block *uniform_blocks = NULL;
1988
1989 /* Check that global variables defined in multiple shaders are consistent.
1990 */
1991 cross_validate_globals(prog, shader_list, num_shaders, false);
1992 if (!prog->LinkStatus)
1993 return NULL;
1994
1995 /* Check that interface blocks defined in multiple shaders are consistent.
1996 */
1997 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1998 num_shaders);
1999 if (!prog->LinkStatus)
2000 return NULL;
2001
2002 /* Link up uniform blocks defined within this stage. */
2003 const unsigned num_uniform_blocks =
2004 link_uniform_blocks(mem_ctx, ctx, prog, shader_list, num_shaders,
2005 &uniform_blocks);
2006 if (!prog->LinkStatus)
2007 return NULL;
2008
2009 /* Check that there is only a single definition of each function signature
2010 * across all shaders.
2011 */
2012 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2013 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2014 ir_function *const f = node->as_function();
2015
2016 if (f == NULL)
2017 continue;
2018
2019 for (unsigned j = i + 1; j < num_shaders; j++) {
2020 ir_function *const other =
2021 shader_list[j]->symbols->get_function(f->name);
2022
2023 /* If the other shader has no function (and therefore no function
2024 * signatures) with the same name, skip to the next shader.
2025 */
2026 if (other == NULL)
2027 continue;
2028
2029 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2030 if (!sig->is_defined || sig->is_builtin())
2031 continue;
2032
2033 ir_function_signature *other_sig =
2034 other->exact_matching_signature(NULL, &sig->parameters);
2035
2036 if ((other_sig != NULL) && other_sig->is_defined
2037 && !other_sig->is_builtin()) {
2038 linker_error(prog, "function `%s' is multiply defined\n",
2039 f->name);
2040 return NULL;
2041 }
2042 }
2043 }
2044 }
2045 }
2046
2047 /* Find the shader that defines main, and make a clone of it.
2048 *
2049 * Starting with the clone, search for undefined references. If one is
2050 * found, find the shader that defines it. Clone the reference and add
2051 * it to the shader. Repeat until there are no undefined references or
2052 * until a reference cannot be resolved.
2053 */
2054 gl_shader *main = NULL;
2055 for (unsigned i = 0; i < num_shaders; i++) {
2056 if (_mesa_get_main_function_signature(shader_list[i]) != NULL) {
2057 main = shader_list[i];
2058 break;
2059 }
2060 }
2061
2062 if (main == NULL) {
2063 linker_error(prog, "%s shader lacks `main'\n",
2064 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2065 return NULL;
2066 }
2067
2068 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
2069 linked->ir = new(linked) exec_list;
2070 clone_ir_list(mem_ctx, linked->ir, main->ir);
2071
2072 linked->BufferInterfaceBlocks = uniform_blocks;
2073 linked->NumBufferInterfaceBlocks = num_uniform_blocks;
2074 ralloc_steal(linked, linked->BufferInterfaceBlocks);
2075
2076 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2077 link_tcs_out_layout_qualifiers(prog, linked, shader_list, num_shaders);
2078 link_tes_in_layout_qualifiers(prog, linked, shader_list, num_shaders);
2079 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2080 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2081
2082 populate_symbol_table(linked);
2083
2084 /* The pointer to the main function in the final linked shader (i.e., the
2085 * copy of the original shader that contained the main function).
2086 */
2087 ir_function_signature *const main_sig =
2088 _mesa_get_main_function_signature(linked);
2089
2090 /* Move any instructions other than variable declarations or function
2091 * declarations into main.
2092 */
2093 exec_node *insertion_point =
2094 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2095 linked);
2096
2097 for (unsigned i = 0; i < num_shaders; i++) {
2098 if (shader_list[i] == main)
2099 continue;
2100
2101 insertion_point = move_non_declarations(shader_list[i]->ir,
2102 insertion_point, true, linked);
2103 }
2104
2105 /* Check if any shader needs built-in functions. */
2106 bool need_builtins = false;
2107 for (unsigned i = 0; i < num_shaders; i++) {
2108 if (shader_list[i]->uses_builtin_functions) {
2109 need_builtins = true;
2110 break;
2111 }
2112 }
2113
2114 bool ok;
2115 if (need_builtins) {
2116 /* Make a temporary array one larger than shader_list, which will hold
2117 * the built-in function shader as well.
2118 */
2119 gl_shader **linking_shaders = (gl_shader **)
2120 calloc(num_shaders + 1, sizeof(gl_shader *));
2121
2122 ok = linking_shaders != NULL;
2123
2124 if (ok) {
2125 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
2126 _mesa_glsl_initialize_builtin_functions();
2127 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
2128
2129 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
2130
2131 free(linking_shaders);
2132 } else {
2133 _mesa_error_no_memory(__func__);
2134 }
2135 } else {
2136 ok = link_function_calls(prog, linked, shader_list, num_shaders);
2137 }
2138
2139
2140 if (!ok) {
2141 _mesa_delete_shader(ctx, linked);
2142 return NULL;
2143 }
2144
2145 /* At this point linked should contain all of the linked IR, so
2146 * validate it to make sure nothing went wrong.
2147 */
2148 validate_ir_tree(linked->ir);
2149
2150 /* Set the size of geometry shader input arrays */
2151 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2152 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
2153 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
2154 foreach_in_list(ir_instruction, ir, linked->ir) {
2155 ir->accept(&input_resize_visitor);
2156 }
2157 }
2158
2159 if (ctx->Const.VertexID_is_zero_based)
2160 lower_vertex_id(linked);
2161
2162 /* Validate correct usage of barrier() in the tess control shader */
2163 if (linked->Stage == MESA_SHADER_TESS_CTRL) {
2164 barrier_use_visitor visitor(prog);
2165 foreach_in_list(ir_instruction, ir, linked->ir) {
2166 ir->accept(&visitor);
2167 }
2168 }
2169
2170 /* Make a pass over all variable declarations to ensure that arrays with
2171 * unspecified sizes have a size specified. The size is inferred from the
2172 * max_array_access field.
2173 */
2174 array_sizing_visitor v;
2175 v.run(linked->ir);
2176 v.fixup_unnamed_interface_types();
2177
2178 return linked;
2179 }
2180
2181 /**
2182 * Update the sizes of linked shader uniform arrays to the maximum
2183 * array index used.
2184 *
2185 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2186 *
2187 * If one or more elements of an array are active,
2188 * GetActiveUniform will return the name of the array in name,
2189 * subject to the restrictions listed above. The type of the array
2190 * is returned in type. The size parameter contains the highest
2191 * array element index used, plus one. The compiler or linker
2192 * determines the highest index used. There will be only one
2193 * active uniform reported by the GL per uniform array.
2194
2195 */
2196 static void
2197 update_array_sizes(struct gl_shader_program *prog)
2198 {
2199 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2200 if (prog->_LinkedShaders[i] == NULL)
2201 continue;
2202
2203 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2204 ir_variable *const var = node->as_variable();
2205
2206 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2207 !var->type->is_array())
2208 continue;
2209
2210 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2211 * will not be eliminated. Since we always do std140, just
2212 * don't resize arrays in UBOs.
2213 *
2214 * Atomic counters are supposed to get deterministic
2215 * locations assigned based on the declaration ordering and
2216 * sizes, array compaction would mess that up.
2217 *
2218 * Subroutine uniforms are not removed.
2219 */
2220 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2221 var->type->contains_subroutine())
2222 continue;
2223
2224 unsigned int size = var->data.max_array_access;
2225 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2226 if (prog->_LinkedShaders[j] == NULL)
2227 continue;
2228
2229 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2230 ir_variable *other_var = node2->as_variable();
2231 if (!other_var)
2232 continue;
2233
2234 if (strcmp(var->name, other_var->name) == 0 &&
2235 other_var->data.max_array_access > size) {
2236 size = other_var->data.max_array_access;
2237 }
2238 }
2239 }
2240
2241 if (size + 1 != var->type->length) {
2242 /* If this is a built-in uniform (i.e., it's backed by some
2243 * fixed-function state), adjust the number of state slots to
2244 * match the new array size. The number of slots per array entry
2245 * is not known. It seems safe to assume that the total number of
2246 * slots is an integer multiple of the number of array elements.
2247 * Determine the number of slots per array element by dividing by
2248 * the old (total) size.
2249 */
2250 const unsigned num_slots = var->get_num_state_slots();
2251 if (num_slots > 0) {
2252 var->set_num_state_slots((size + 1)
2253 * (num_slots / var->type->length));
2254 }
2255
2256 var->type = glsl_type::get_array_instance(var->type->fields.array,
2257 size + 1);
2258 /* FINISHME: We should update the types of array
2259 * dereferences of this variable now.
2260 */
2261 }
2262 }
2263 }
2264 }
2265
2266 /**
2267 * Resize tessellation evaluation per-vertex inputs to the size of
2268 * tessellation control per-vertex outputs.
2269 */
2270 static void
2271 resize_tes_inputs(struct gl_context *ctx,
2272 struct gl_shader_program *prog)
2273 {
2274 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2275 return;
2276
2277 gl_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2278 gl_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2279
2280 /* If no control shader is present, then the TES inputs are statically
2281 * sized to MaxPatchVertices; the actual size of the arrays won't be
2282 * known until draw time.
2283 */
2284 const int num_vertices = tcs
2285 ? tcs->TessCtrl.VerticesOut
2286 : ctx->Const.MaxPatchVertices;
2287
2288 tess_eval_array_resize_visitor input_resize_visitor(num_vertices, prog);
2289 foreach_in_list(ir_instruction, ir, tes->ir) {
2290 ir->accept(&input_resize_visitor);
2291 }
2292
2293 if (tcs) {
2294 /* Convert the gl_PatchVerticesIn system value into a constant, since
2295 * the value is known at this point.
2296 */
2297 foreach_in_list(ir_instruction, ir, tes->ir) {
2298 ir_variable *var = ir->as_variable();
2299 if (var && var->data.mode == ir_var_system_value &&
2300 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2301 void *mem_ctx = ralloc_parent(var);
2302 var->data.mode = ir_var_auto;
2303 var->data.location = 0;
2304 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2305 }
2306 }
2307 }
2308 }
2309
2310 /**
2311 * Find a contiguous set of available bits in a bitmask.
2312 *
2313 * \param used_mask Bits representing used (1) and unused (0) locations
2314 * \param needed_count Number of contiguous bits needed.
2315 *
2316 * \return
2317 * Base location of the available bits on success or -1 on failure.
2318 */
2319 int
2320 find_available_slots(unsigned used_mask, unsigned needed_count)
2321 {
2322 unsigned needed_mask = (1 << needed_count) - 1;
2323 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2324
2325 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2326 * cannot optimize possibly infinite loops" for the loop below.
2327 */
2328 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2329 return -1;
2330
2331 for (int i = 0; i <= max_bit_to_test; i++) {
2332 if ((needed_mask & ~used_mask) == needed_mask)
2333 return i;
2334
2335 needed_mask <<= 1;
2336 }
2337
2338 return -1;
2339 }
2340
2341
2342 /**
2343 * Assign locations for either VS inputs or FS outputs
2344 *
2345 * \param prog Shader program whose variables need locations assigned
2346 * \param constants Driver specific constant values for the program.
2347 * \param target_index Selector for the program target to receive location
2348 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2349 * \c MESA_SHADER_FRAGMENT.
2350 *
2351 * \return
2352 * If locations are successfully assigned, true is returned. Otherwise an
2353 * error is emitted to the shader link log and false is returned.
2354 */
2355 bool
2356 assign_attribute_or_color_locations(gl_shader_program *prog,
2357 struct gl_constants *constants,
2358 unsigned target_index)
2359 {
2360 /* Maximum number of generic locations. This corresponds to either the
2361 * maximum number of draw buffers or the maximum number of generic
2362 * attributes.
2363 */
2364 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2365 constants->Program[target_index].MaxAttribs :
2366 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2367
2368 /* Mark invalid locations as being used.
2369 */
2370 unsigned used_locations = (max_index >= 32)
2371 ? ~0 : ~((1 << max_index) - 1);
2372 unsigned double_storage_locations = 0;
2373
2374 assert((target_index == MESA_SHADER_VERTEX)
2375 || (target_index == MESA_SHADER_FRAGMENT));
2376
2377 gl_shader *const sh = prog->_LinkedShaders[target_index];
2378 if (sh == NULL)
2379 return true;
2380
2381 /* Operate in a total of four passes.
2382 *
2383 * 1. Invalidate the location assignments for all vertex shader inputs.
2384 *
2385 * 2. Assign locations for inputs that have user-defined (via
2386 * glBindVertexAttribLocation) locations and outputs that have
2387 * user-defined locations (via glBindFragDataLocation).
2388 *
2389 * 3. Sort the attributes without assigned locations by number of slots
2390 * required in decreasing order. Fragmentation caused by attribute
2391 * locations assigned by the application may prevent large attributes
2392 * from having enough contiguous space.
2393 *
2394 * 4. Assign locations to any inputs without assigned locations.
2395 */
2396
2397 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2398 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2399
2400 const enum ir_variable_mode direction =
2401 (target_index == MESA_SHADER_VERTEX)
2402 ? ir_var_shader_in : ir_var_shader_out;
2403
2404
2405 /* Temporary storage for the set of attributes that need locations assigned.
2406 */
2407 struct temp_attr {
2408 unsigned slots;
2409 ir_variable *var;
2410
2411 /* Used below in the call to qsort. */
2412 static int compare(const void *a, const void *b)
2413 {
2414 const temp_attr *const l = (const temp_attr *) a;
2415 const temp_attr *const r = (const temp_attr *) b;
2416
2417 /* Reversed because we want a descending order sort below. */
2418 return r->slots - l->slots;
2419 }
2420 } to_assign[16];
2421
2422 unsigned num_attr = 0;
2423
2424 foreach_in_list(ir_instruction, node, sh->ir) {
2425 ir_variable *const var = node->as_variable();
2426
2427 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2428 continue;
2429
2430 if (var->data.explicit_location) {
2431 var->data.is_unmatched_generic_inout = 0;
2432 if ((var->data.location >= (int)(max_index + generic_base))
2433 || (var->data.location < 0)) {
2434 linker_error(prog,
2435 "invalid explicit location %d specified for `%s'\n",
2436 (var->data.location < 0)
2437 ? var->data.location
2438 : var->data.location - generic_base,
2439 var->name);
2440 return false;
2441 }
2442 } else if (target_index == MESA_SHADER_VERTEX) {
2443 unsigned binding;
2444
2445 if (prog->AttributeBindings->get(binding, var->name)) {
2446 assert(binding >= VERT_ATTRIB_GENERIC0);
2447 var->data.location = binding;
2448 var->data.is_unmatched_generic_inout = 0;
2449 }
2450 } else if (target_index == MESA_SHADER_FRAGMENT) {
2451 unsigned binding;
2452 unsigned index;
2453
2454 if (prog->FragDataBindings->get(binding, var->name)) {
2455 assert(binding >= FRAG_RESULT_DATA0);
2456 var->data.location = binding;
2457 var->data.is_unmatched_generic_inout = 0;
2458
2459 if (prog->FragDataIndexBindings->get(index, var->name)) {
2460 var->data.index = index;
2461 }
2462 }
2463 }
2464
2465 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2466 *
2467 * "Output binding assignments will cause LinkProgram to fail:
2468 * ...
2469 * If the program has an active output assigned to a location greater
2470 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2471 * an active output assigned an index greater than or equal to one;"
2472 */
2473 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2474 var->data.location - generic_base >=
2475 (int) constants->MaxDualSourceDrawBuffers) {
2476 linker_error(prog,
2477 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2478 "with index %u for %s\n",
2479 var->data.location - generic_base, var->data.index,
2480 var->name);
2481 return false;
2482 }
2483
2484 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX ? true : false);
2485
2486 /* If the variable is not a built-in and has a location statically
2487 * assigned in the shader (presumably via a layout qualifier), make sure
2488 * that it doesn't collide with other assigned locations. Otherwise,
2489 * add it to the list of variables that need linker-assigned locations.
2490 */
2491 if (var->data.location != -1) {
2492 if (var->data.location >= generic_base && var->data.index < 1) {
2493 /* From page 61 of the OpenGL 4.0 spec:
2494 *
2495 * "LinkProgram will fail if the attribute bindings assigned
2496 * by BindAttribLocation do not leave not enough space to
2497 * assign a location for an active matrix attribute or an
2498 * active attribute array, both of which require multiple
2499 * contiguous generic attributes."
2500 *
2501 * I think above text prohibits the aliasing of explicit and
2502 * automatic assignments. But, aliasing is allowed in manual
2503 * assignments of attribute locations. See below comments for
2504 * the details.
2505 *
2506 * From OpenGL 4.0 spec, page 61:
2507 *
2508 * "It is possible for an application to bind more than one
2509 * attribute name to the same location. This is referred to as
2510 * aliasing. This will only work if only one of the aliased
2511 * attributes is active in the executable program, or if no
2512 * path through the shader consumes more than one attribute of
2513 * a set of attributes aliased to the same location. A link
2514 * error can occur if the linker determines that every path
2515 * through the shader consumes multiple aliased attributes,
2516 * but implementations are not required to generate an error
2517 * in this case."
2518 *
2519 * From GLSL 4.30 spec, page 54:
2520 *
2521 * "A program will fail to link if any two non-vertex shader
2522 * input variables are assigned to the same location. For
2523 * vertex shaders, multiple input variables may be assigned
2524 * to the same location using either layout qualifiers or via
2525 * the OpenGL API. However, such aliasing is intended only to
2526 * support vertex shaders where each execution path accesses
2527 * at most one input per each location. Implementations are
2528 * permitted, but not required, to generate link-time errors
2529 * if they detect that every path through the vertex shader
2530 * executable accesses multiple inputs assigned to any single
2531 * location. For all shader types, a program will fail to link
2532 * if explicit location assignments leave the linker unable
2533 * to find space for other variables without explicit
2534 * assignments."
2535 *
2536 * From OpenGL ES 3.0 spec, page 56:
2537 *
2538 * "Binding more than one attribute name to the same location
2539 * is referred to as aliasing, and is not permitted in OpenGL
2540 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2541 * fail when this condition exists. However, aliasing is
2542 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2543 * This will only work if only one of the aliased attributes
2544 * is active in the executable program, or if no path through
2545 * the shader consumes more than one attribute of a set of
2546 * attributes aliased to the same location. A link error can
2547 * occur if the linker determines that every path through the
2548 * shader consumes multiple aliased attributes, but implemen-
2549 * tations are not required to generate an error in this case."
2550 *
2551 * After looking at above references from OpenGL, OpenGL ES and
2552 * GLSL specifications, we allow aliasing of vertex input variables
2553 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2554 *
2555 * NOTE: This is not required by the spec but its worth mentioning
2556 * here that we're not doing anything to make sure that no path
2557 * through the vertex shader executable accesses multiple inputs
2558 * assigned to any single location.
2559 */
2560
2561 /* Mask representing the contiguous slots that will be used by
2562 * this attribute.
2563 */
2564 const unsigned attr = var->data.location - generic_base;
2565 const unsigned use_mask = (1 << slots) - 1;
2566 const char *const string = (target_index == MESA_SHADER_VERTEX)
2567 ? "vertex shader input" : "fragment shader output";
2568
2569 /* Generate a link error if the requested locations for this
2570 * attribute exceed the maximum allowed attribute location.
2571 */
2572 if (attr + slots > max_index) {
2573 linker_error(prog,
2574 "insufficient contiguous locations "
2575 "available for %s `%s' %d %d %d\n", string,
2576 var->name, used_locations, use_mask, attr);
2577 return false;
2578 }
2579
2580 /* Generate a link error if the set of bits requested for this
2581 * attribute overlaps any previously allocated bits.
2582 */
2583 if ((~(use_mask << attr) & used_locations) != used_locations) {
2584 if (target_index == MESA_SHADER_FRAGMENT ||
2585 (prog->IsES && prog->Version >= 300)) {
2586 linker_error(prog,
2587 "overlapping location is assigned "
2588 "to %s `%s' %d %d %d\n", string,
2589 var->name, used_locations, use_mask, attr);
2590 return false;
2591 } else {
2592 linker_warning(prog,
2593 "overlapping location is assigned "
2594 "to %s `%s' %d %d %d\n", string,
2595 var->name, used_locations, use_mask, attr);
2596 }
2597 }
2598
2599 used_locations |= (use_mask << attr);
2600
2601 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2602 *
2603 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2604 * active attribute variables may fail to link, unless
2605 * device-dependent optimizations are able to make the program
2606 * fit within available hardware resources. For the purposes
2607 * of this test, attribute variables of the type dvec3, dvec4,
2608 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2609 * count as consuming twice as many attributes as equivalent
2610 * single-precision types. While these types use the same number
2611 * of generic attributes as their single-precision equivalents,
2612 * implementations are permitted to consume two single-precision
2613 * vectors of internal storage for each three- or four-component
2614 * double-precision vector."
2615 *
2616 * Mark this attribute slot as taking up twice as much space
2617 * so we can count it properly against limits. According to
2618 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2619 * is optional behavior, but it seems preferable.
2620 */
2621 if (var->type->without_array()->is_dual_slot_double())
2622 double_storage_locations |= (use_mask << attr);
2623 }
2624
2625 continue;
2626 }
2627
2628 if (num_attr >= ARRAY_SIZE(to_assign)) {
2629 linker_error(prog, "too many %s (max %u)",
2630 target_index == MESA_SHADER_VERTEX ?
2631 "vertex shader inputs" : "fragment shader outputs",
2632 (unsigned)ARRAY_SIZE(to_assign));
2633 return false;
2634 }
2635 to_assign[num_attr].slots = slots;
2636 to_assign[num_attr].var = var;
2637 num_attr++;
2638 }
2639
2640 if (target_index == MESA_SHADER_VERTEX) {
2641 unsigned total_attribs_size =
2642 _mesa_bitcount(used_locations & ((1 << max_index) - 1)) +
2643 _mesa_bitcount(double_storage_locations);
2644 if (total_attribs_size > max_index) {
2645 linker_error(prog,
2646 "attempt to use %d vertex attribute slots only %d available ",
2647 total_attribs_size, max_index);
2648 return false;
2649 }
2650 }
2651
2652 /* If all of the attributes were assigned locations by the application (or
2653 * are built-in attributes with fixed locations), return early. This should
2654 * be the common case.
2655 */
2656 if (num_attr == 0)
2657 return true;
2658
2659 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2660
2661 if (target_index == MESA_SHADER_VERTEX) {
2662 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2663 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2664 * reserved to prevent it from being automatically allocated below.
2665 */
2666 find_deref_visitor find("gl_Vertex");
2667 find.run(sh->ir);
2668 if (find.variable_found())
2669 used_locations |= (1 << 0);
2670 }
2671
2672 for (unsigned i = 0; i < num_attr; i++) {
2673 /* Mask representing the contiguous slots that will be used by this
2674 * attribute.
2675 */
2676 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2677
2678 int location = find_available_slots(used_locations, to_assign[i].slots);
2679
2680 if (location < 0) {
2681 const char *const string = (target_index == MESA_SHADER_VERTEX)
2682 ? "vertex shader input" : "fragment shader output";
2683
2684 linker_error(prog,
2685 "insufficient contiguous locations "
2686 "available for %s `%s'\n",
2687 string, to_assign[i].var->name);
2688 return false;
2689 }
2690
2691 to_assign[i].var->data.location = generic_base + location;
2692 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2693 used_locations |= (use_mask << location);
2694 }
2695
2696 return true;
2697 }
2698
2699 /**
2700 * Match explicit locations of outputs to inputs and deactivate the
2701 * unmatch flag if found so we don't optimise them away.
2702 */
2703 static void
2704 match_explicit_outputs_to_inputs(struct gl_shader_program *prog,
2705 gl_shader *producer,
2706 gl_shader *consumer)
2707 {
2708 glsl_symbol_table parameters;
2709 ir_variable *explicit_locations[MAX_VARYING] = { NULL };
2710
2711 /* Find all shader outputs in the "producer" stage.
2712 */
2713 foreach_in_list(ir_instruction, node, producer->ir) {
2714 ir_variable *const var = node->as_variable();
2715
2716 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
2717 continue;
2718
2719 if (var->data.explicit_location &&
2720 var->data.location >= VARYING_SLOT_VAR0) {
2721 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
2722 if (explicit_locations[idx] == NULL)
2723 explicit_locations[idx] = var;
2724 }
2725 }
2726
2727 /* Match inputs to outputs */
2728 foreach_in_list(ir_instruction, node, consumer->ir) {
2729 ir_variable *const input = node->as_variable();
2730
2731 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
2732 continue;
2733
2734 ir_variable *output = NULL;
2735 if (input->data.explicit_location
2736 && input->data.location >= VARYING_SLOT_VAR0) {
2737 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0];
2738
2739 if (output != NULL){
2740 input->data.is_unmatched_generic_inout = 0;
2741 output->data.is_unmatched_generic_inout = 0;
2742 }
2743 }
2744 }
2745 }
2746
2747 /**
2748 * Store the gl_FragDepth layout in the gl_shader_program struct.
2749 */
2750 static void
2751 store_fragdepth_layout(struct gl_shader_program *prog)
2752 {
2753 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2754 return;
2755 }
2756
2757 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2758
2759 /* We don't look up the gl_FragDepth symbol directly because if
2760 * gl_FragDepth is not used in the shader, it's removed from the IR.
2761 * However, the symbol won't be removed from the symbol table.
2762 *
2763 * We're only interested in the cases where the variable is NOT removed
2764 * from the IR.
2765 */
2766 foreach_in_list(ir_instruction, node, ir) {
2767 ir_variable *const var = node->as_variable();
2768
2769 if (var == NULL || var->data.mode != ir_var_shader_out) {
2770 continue;
2771 }
2772
2773 if (strcmp(var->name, "gl_FragDepth") == 0) {
2774 switch (var->data.depth_layout) {
2775 case ir_depth_layout_none:
2776 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2777 return;
2778 case ir_depth_layout_any:
2779 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2780 return;
2781 case ir_depth_layout_greater:
2782 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2783 return;
2784 case ir_depth_layout_less:
2785 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2786 return;
2787 case ir_depth_layout_unchanged:
2788 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2789 return;
2790 default:
2791 assert(0);
2792 return;
2793 }
2794 }
2795 }
2796 }
2797
2798 /**
2799 * Validate the resources used by a program versus the implementation limits
2800 */
2801 static void
2802 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2803 {
2804 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2805 struct gl_shader *sh = prog->_LinkedShaders[i];
2806
2807 if (sh == NULL)
2808 continue;
2809
2810 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2811 linker_error(prog, "Too many %s shader texture samplers\n",
2812 _mesa_shader_stage_to_string(i));
2813 }
2814
2815 if (sh->num_uniform_components >
2816 ctx->Const.Program[i].MaxUniformComponents) {
2817 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2818 linker_warning(prog, "Too many %s shader default uniform block "
2819 "components, but the driver will try to optimize "
2820 "them out; this is non-portable out-of-spec "
2821 "behavior\n",
2822 _mesa_shader_stage_to_string(i));
2823 } else {
2824 linker_error(prog, "Too many %s shader default uniform block "
2825 "components\n",
2826 _mesa_shader_stage_to_string(i));
2827 }
2828 }
2829
2830 if (sh->num_combined_uniform_components >
2831 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2832 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2833 linker_warning(prog, "Too many %s shader uniform components, "
2834 "but the driver will try to optimize them out; "
2835 "this is non-portable out-of-spec behavior\n",
2836 _mesa_shader_stage_to_string(i));
2837 } else {
2838 linker_error(prog, "Too many %s shader uniform components\n",
2839 _mesa_shader_stage_to_string(i));
2840 }
2841 }
2842 }
2843
2844 unsigned blocks[MESA_SHADER_STAGES] = {0};
2845 unsigned total_uniform_blocks = 0;
2846 unsigned shader_blocks[MESA_SHADER_STAGES] = {0};
2847 unsigned total_shader_storage_blocks = 0;
2848
2849 for (unsigned i = 0; i < prog->NumBufferInterfaceBlocks; i++) {
2850 /* Don't check SSBOs for Uniform Block Size */
2851 if (!prog->BufferInterfaceBlocks[i].IsShaderStorage &&
2852 prog->BufferInterfaceBlocks[i].UniformBufferSize > ctx->Const.MaxUniformBlockSize) {
2853 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
2854 prog->BufferInterfaceBlocks[i].Name,
2855 prog->BufferInterfaceBlocks[i].UniformBufferSize,
2856 ctx->Const.MaxUniformBlockSize);
2857 }
2858
2859 if (prog->BufferInterfaceBlocks[i].IsShaderStorage &&
2860 prog->BufferInterfaceBlocks[i].UniformBufferSize > ctx->Const.MaxShaderStorageBlockSize) {
2861 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
2862 prog->BufferInterfaceBlocks[i].Name,
2863 prog->BufferInterfaceBlocks[i].UniformBufferSize,
2864 ctx->Const.MaxShaderStorageBlockSize);
2865 }
2866
2867 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2868 if (prog->InterfaceBlockStageIndex[j][i] != -1) {
2869 struct gl_shader *sh = prog->_LinkedShaders[j];
2870 int stage_index = prog->InterfaceBlockStageIndex[j][i];
2871 if (sh && sh->BufferInterfaceBlocks[stage_index].IsShaderStorage) {
2872 shader_blocks[j]++;
2873 total_shader_storage_blocks++;
2874 } else {
2875 blocks[j]++;
2876 total_uniform_blocks++;
2877 }
2878 }
2879 }
2880
2881 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2882 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
2883 total_uniform_blocks,
2884 ctx->Const.MaxCombinedUniformBlocks);
2885 } else {
2886 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2887 const unsigned max_uniform_blocks =
2888 ctx->Const.Program[i].MaxUniformBlocks;
2889 if (blocks[i] > max_uniform_blocks) {
2890 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2891 _mesa_shader_stage_to_string(i),
2892 blocks[i],
2893 max_uniform_blocks);
2894 break;
2895 }
2896 }
2897 }
2898
2899 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
2900 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
2901 total_shader_storage_blocks,
2902 ctx->Const.MaxCombinedShaderStorageBlocks);
2903 } else {
2904 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2905 const unsigned max_shader_storage_blocks =
2906 ctx->Const.Program[i].MaxShaderStorageBlocks;
2907 if (shader_blocks[i] > max_shader_storage_blocks) {
2908 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
2909 _mesa_shader_stage_to_string(i),
2910 shader_blocks[i],
2911 max_shader_storage_blocks);
2912 break;
2913 }
2914 }
2915 }
2916 }
2917 }
2918
2919 static void
2920 link_calculate_subroutine_compat(struct gl_shader_program *prog)
2921 {
2922 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2923 struct gl_shader *sh = prog->_LinkedShaders[i];
2924 int count;
2925 if (!sh)
2926 continue;
2927
2928 for (unsigned j = 0; j < sh->NumSubroutineUniformRemapTable; j++) {
2929 struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[j];
2930
2931 if (!uni)
2932 continue;
2933
2934 count = 0;
2935 for (unsigned f = 0; f < sh->NumSubroutineFunctions; f++) {
2936 struct gl_subroutine_function *fn = &sh->SubroutineFunctions[f];
2937 for (int k = 0; k < fn->num_compat_types; k++) {
2938 if (fn->types[k] == uni->type) {
2939 count++;
2940 break;
2941 }
2942 }
2943 }
2944 uni->num_compatible_subroutines = count;
2945 }
2946 }
2947 }
2948
2949 static void
2950 check_subroutine_resources(struct gl_shader_program *prog)
2951 {
2952 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2953 struct gl_shader *sh = prog->_LinkedShaders[i];
2954
2955 if (sh) {
2956 if (sh->NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS)
2957 linker_error(prog, "Too many %s shader subroutine uniforms\n",
2958 _mesa_shader_stage_to_string(i));
2959 }
2960 }
2961 }
2962 /**
2963 * Validate shader image resources.
2964 */
2965 static void
2966 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2967 {
2968 unsigned total_image_units = 0;
2969 unsigned fragment_outputs = 0;
2970 unsigned total_shader_storage_blocks = 0;
2971
2972 if (!ctx->Extensions.ARB_shader_image_load_store)
2973 return;
2974
2975 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2976 struct gl_shader *sh = prog->_LinkedShaders[i];
2977
2978 if (sh) {
2979 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2980 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
2981 _mesa_shader_stage_to_string(i), sh->NumImages,
2982 ctx->Const.Program[i].MaxImageUniforms);
2983
2984 total_image_units += sh->NumImages;
2985
2986 for (unsigned j = 0; j < prog->NumBufferInterfaceBlocks; j++) {
2987 int stage_index = prog->InterfaceBlockStageIndex[i][j];
2988 if (stage_index != -1 && sh->BufferInterfaceBlocks[stage_index].IsShaderStorage)
2989 total_shader_storage_blocks++;
2990 }
2991
2992 if (i == MESA_SHADER_FRAGMENT) {
2993 foreach_in_list(ir_instruction, node, sh->ir) {
2994 ir_variable *var = node->as_variable();
2995 if (var && var->data.mode == ir_var_shader_out)
2996 /* since there are no double fs outputs - pass false */
2997 fragment_outputs += var->type->count_attribute_slots(false);
2998 }
2999 }
3000 }
3001 }
3002
3003 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3004 linker_error(prog, "Too many combined image uniforms\n");
3005
3006 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3007 ctx->Const.MaxCombinedShaderOutputResources)
3008 linker_error(prog, "Too many combined image uniforms, shader storage "
3009 " buffers and fragment outputs\n");
3010 }
3011
3012
3013 /**
3014 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3015 * for a variable, checks for overlaps between other uniforms using explicit
3016 * locations.
3017 */
3018 static int
3019 reserve_explicit_locations(struct gl_shader_program *prog,
3020 string_to_uint_map *map, ir_variable *var)
3021 {
3022 unsigned slots = var->type->uniform_locations();
3023 unsigned max_loc = var->data.location + slots - 1;
3024 unsigned return_value = slots;
3025
3026 /* Resize remap table if locations do not fit in the current one. */
3027 if (max_loc + 1 > prog->NumUniformRemapTable) {
3028 prog->UniformRemapTable =
3029 reralloc(prog, prog->UniformRemapTable,
3030 gl_uniform_storage *,
3031 max_loc + 1);
3032
3033 if (!prog->UniformRemapTable) {
3034 linker_error(prog, "Out of memory during linking.\n");
3035 return -1;
3036 }
3037
3038 /* Initialize allocated space. */
3039 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3040 prog->UniformRemapTable[i] = NULL;
3041
3042 prog->NumUniformRemapTable = max_loc + 1;
3043 }
3044
3045 for (unsigned i = 0; i < slots; i++) {
3046 unsigned loc = var->data.location + i;
3047
3048 /* Check if location is already used. */
3049 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3050
3051 /* Possibly same uniform from a different stage, this is ok. */
3052 unsigned hash_loc;
3053 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3054 return_value = 0;
3055 continue;
3056 }
3057
3058 /* ARB_explicit_uniform_location specification states:
3059 *
3060 * "No two default-block uniform variables in the program can have
3061 * the same location, even if they are unused, otherwise a compiler
3062 * or linker error will be generated."
3063 */
3064 linker_error(prog,
3065 "location qualifier for uniform %s overlaps "
3066 "previously used location\n",
3067 var->name);
3068 return -1;
3069 }
3070
3071 /* Initialize location as inactive before optimization
3072 * rounds and location assignment.
3073 */
3074 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3075 }
3076
3077 /* Note, base location used for arrays. */
3078 map->put(var->data.location, var->name);
3079
3080 return return_value;
3081 }
3082
3083 static bool
3084 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3085 struct gl_shader *sh,
3086 ir_variable *var)
3087 {
3088 unsigned slots = var->type->uniform_locations();
3089 unsigned max_loc = var->data.location + slots - 1;
3090
3091 /* Resize remap table if locations do not fit in the current one. */
3092 if (max_loc + 1 > sh->NumSubroutineUniformRemapTable) {
3093 sh->SubroutineUniformRemapTable =
3094 reralloc(sh, sh->SubroutineUniformRemapTable,
3095 gl_uniform_storage *,
3096 max_loc + 1);
3097
3098 if (!sh->SubroutineUniformRemapTable) {
3099 linker_error(prog, "Out of memory during linking.\n");
3100 return false;
3101 }
3102
3103 /* Initialize allocated space. */
3104 for (unsigned i = sh->NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3105 sh->SubroutineUniformRemapTable[i] = NULL;
3106
3107 sh->NumSubroutineUniformRemapTable = max_loc + 1;
3108 }
3109
3110 for (unsigned i = 0; i < slots; i++) {
3111 unsigned loc = var->data.location + i;
3112
3113 /* Check if location is already used. */
3114 if (sh->SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3115
3116 /* ARB_explicit_uniform_location specification states:
3117 * "No two subroutine uniform variables can have the same location
3118 * in the same shader stage, otherwise a compiler or linker error
3119 * will be generated."
3120 */
3121 linker_error(prog,
3122 "location qualifier for uniform %s overlaps "
3123 "previously used location\n",
3124 var->name);
3125 return false;
3126 }
3127
3128 /* Initialize location as inactive before optimization
3129 * rounds and location assignment.
3130 */
3131 sh->SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3132 }
3133
3134 return true;
3135 }
3136 /**
3137 * Check and reserve all explicit uniform locations, called before
3138 * any optimizations happen to handle also inactive uniforms and
3139 * inactive array elements that may get trimmed away.
3140 */
3141 static int
3142 check_explicit_uniform_locations(struct gl_context *ctx,
3143 struct gl_shader_program *prog)
3144 {
3145 if (!ctx->Extensions.ARB_explicit_uniform_location)
3146 return -1;
3147
3148 /* This map is used to detect if overlapping explicit locations
3149 * occur with the same uniform (from different stage) or a different one.
3150 */
3151 string_to_uint_map *uniform_map = new string_to_uint_map;
3152
3153 if (!uniform_map) {
3154 linker_error(prog, "Out of memory during linking.\n");
3155 return -1;
3156 }
3157
3158 unsigned entries_total = 0;
3159 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3160 struct gl_shader *sh = prog->_LinkedShaders[i];
3161
3162 if (!sh)
3163 continue;
3164
3165 foreach_in_list(ir_instruction, node, sh->ir) {
3166 ir_variable *var = node->as_variable();
3167 if (!var || var->data.mode != ir_var_uniform)
3168 continue;
3169
3170 if (var->data.explicit_location) {
3171 bool ret = false;
3172 if (var->type->without_array()->is_subroutine())
3173 ret = reserve_subroutine_explicit_locations(prog, sh, var);
3174 else {
3175 int slots = reserve_explicit_locations(prog, uniform_map,
3176 var);
3177 if (slots != -1) {
3178 ret = true;
3179 entries_total += slots;
3180 }
3181 }
3182 if (!ret) {
3183 delete uniform_map;
3184 return -1;
3185 }
3186 }
3187 }
3188 }
3189
3190 struct empty_uniform_block *current_block = NULL;
3191
3192 for (unsigned i = 0; i < prog->NumUniformRemapTable; i++) {
3193 /* We found empty space in UniformRemapTable. */
3194 if (prog->UniformRemapTable[i] == NULL) {
3195 /* We've found the beginning of a new continous block of empty slots */
3196 if (!current_block || current_block->start + current_block->slots != i) {
3197 current_block = rzalloc(prog, struct empty_uniform_block);
3198 current_block->start = i;
3199 exec_list_push_tail(&prog->EmptyUniformLocations,
3200 &current_block->link);
3201 }
3202
3203 /* The current block continues, so we simply increment its slots */
3204 current_block->slots++;
3205 }
3206 }
3207
3208 delete uniform_map;
3209 return entries_total;
3210 }
3211
3212 static bool
3213 should_add_buffer_variable(struct gl_shader_program *shProg,
3214 GLenum type, const char *name)
3215 {
3216 bool found_interface = false;
3217 unsigned block_name_len = 0;
3218 const char *block_name_dot = strchr(name, '.');
3219
3220 /* These rules only apply to buffer variables. So we return
3221 * true for the rest of types.
3222 */
3223 if (type != GL_BUFFER_VARIABLE)
3224 return true;
3225
3226 for (unsigned i = 0; i < shProg->NumBufferInterfaceBlocks; i++) {
3227 const char *block_name = shProg->BufferInterfaceBlocks[i].Name;
3228 block_name_len = strlen(block_name);
3229
3230 const char *block_square_bracket = strchr(block_name, '[');
3231 if (block_square_bracket) {
3232 /* The block is part of an array of named interfaces,
3233 * for the name comparison we ignore the "[x]" part.
3234 */
3235 block_name_len -= strlen(block_square_bracket);
3236 }
3237
3238 if (block_name_dot) {
3239 /* Check if the variable name starts with the interface
3240 * name. The interface name (if present) should have the
3241 * length than the interface block name we are comparing to.
3242 */
3243 unsigned len = strlen(name) - strlen(block_name_dot);
3244 if (len != block_name_len)
3245 continue;
3246 }
3247
3248 if (strncmp(block_name, name, block_name_len) == 0) {
3249 found_interface = true;
3250 break;
3251 }
3252 }
3253
3254 /* We remove the interface name from the buffer variable name,
3255 * including the dot that follows it.
3256 */
3257 if (found_interface)
3258 name = name + block_name_len + 1;
3259
3260 /* From: ARB_program_interface_query extension:
3261 *
3262 * "For an active shader storage block member declared as an array, an
3263 * entry will be generated only for the first array element, regardless
3264 * of its type. For arrays of aggregate types, the enumeration rules are
3265 * applied recursively for the single enumerated array element.
3266 */
3267 const char *struct_first_dot = strchr(name, '.');
3268 const char *first_square_bracket = strchr(name, '[');
3269
3270 /* The buffer variable is on top level and it is not an array */
3271 if (!first_square_bracket) {
3272 return true;
3273 /* The shader storage block member is a struct, then generate the entry */
3274 } else if (struct_first_dot && struct_first_dot < first_square_bracket) {
3275 return true;
3276 } else {
3277 /* Shader storage block member is an array, only generate an entry for the
3278 * first array element.
3279 */
3280 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3281 return true;
3282 }
3283
3284 return false;
3285 }
3286
3287 static bool
3288 add_program_resource(struct gl_shader_program *prog, GLenum type,
3289 const void *data, uint8_t stages)
3290 {
3291 assert(data);
3292
3293 /* If resource already exists, do not add it again. */
3294 for (unsigned i = 0; i < prog->NumProgramResourceList; i++)
3295 if (prog->ProgramResourceList[i].Data == data)
3296 return true;
3297
3298 prog->ProgramResourceList =
3299 reralloc(prog,
3300 prog->ProgramResourceList,
3301 gl_program_resource,
3302 prog->NumProgramResourceList + 1);
3303
3304 if (!prog->ProgramResourceList) {
3305 linker_error(prog, "Out of memory during linking.\n");
3306 return false;
3307 }
3308
3309 struct gl_program_resource *res =
3310 &prog->ProgramResourceList[prog->NumProgramResourceList];
3311
3312 res->Type = type;
3313 res->Data = data;
3314 res->StageReferences = stages;
3315
3316 prog->NumProgramResourceList++;
3317
3318 return true;
3319 }
3320
3321 /* Function checks if a variable var is a packed varying and
3322 * if given name is part of packed varying's list.
3323 *
3324 * If a variable is a packed varying, it has a name like
3325 * 'packed:a,b,c' where a, b and c are separate variables.
3326 */
3327 static bool
3328 included_in_packed_varying(ir_variable *var, const char *name)
3329 {
3330 if (strncmp(var->name, "packed:", 7) != 0)
3331 return false;
3332
3333 char *list = strdup(var->name + 7);
3334 assert(list);
3335
3336 bool found = false;
3337 char *saveptr;
3338 char *token = strtok_r(list, ",", &saveptr);
3339 while (token) {
3340 if (strcmp(token, name) == 0) {
3341 found = true;
3342 break;
3343 }
3344 token = strtok_r(NULL, ",", &saveptr);
3345 }
3346 free(list);
3347 return found;
3348 }
3349
3350 /**
3351 * Function builds a stage reference bitmask from variable name.
3352 */
3353 static uint8_t
3354 build_stageref(struct gl_shader_program *shProg, const char *name,
3355 unsigned mode)
3356 {
3357 uint8_t stages = 0;
3358
3359 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3360 * used for reference mask in gl_program_resource will need to be changed.
3361 */
3362 assert(MESA_SHADER_STAGES < 8);
3363
3364 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3365 struct gl_shader *sh = shProg->_LinkedShaders[i];
3366 if (!sh)
3367 continue;
3368
3369 /* Shader symbol table may contain variables that have
3370 * been optimized away. Search IR for the variable instead.
3371 */
3372 foreach_in_list(ir_instruction, node, sh->ir) {
3373 ir_variable *var = node->as_variable();
3374 if (var) {
3375 unsigned baselen = strlen(var->name);
3376
3377 if (included_in_packed_varying(var, name)) {
3378 stages |= (1 << i);
3379 break;
3380 }
3381
3382 /* Type needs to match if specified, otherwise we might
3383 * pick a variable with same name but different interface.
3384 */
3385 if (var->data.mode != mode)
3386 continue;
3387
3388 if (strncmp(var->name, name, baselen) == 0) {
3389 /* Check for exact name matches but also check for arrays and
3390 * structs.
3391 */
3392 if (name[baselen] == '\0' ||
3393 name[baselen] == '[' ||
3394 name[baselen] == '.') {
3395 stages |= (1 << i);
3396 break;
3397 }
3398 }
3399 }
3400 }
3401 }
3402 return stages;
3403 }
3404
3405 /**
3406 * Create gl_shader_variable from ir_variable class.
3407 */
3408 static gl_shader_variable *
3409 create_shader_variable(struct gl_shader_program *shProg, const ir_variable *in)
3410 {
3411 gl_shader_variable *out = ralloc(shProg, struct gl_shader_variable);
3412 if (!out)
3413 return NULL;
3414
3415 out->type = in->type;
3416 out->name = ralloc_strdup(shProg, in->name);
3417
3418 if (!out->name)
3419 return NULL;
3420
3421 out->location = in->data.location;
3422 out->index = in->data.index;
3423 out->patch = in->data.patch;
3424 out->mode = in->data.mode;
3425
3426 return out;
3427 }
3428
3429 static bool
3430 add_interface_variables(struct gl_shader_program *shProg,
3431 exec_list *ir, GLenum programInterface)
3432 {
3433 foreach_in_list(ir_instruction, node, ir) {
3434 ir_variable *var = node->as_variable();
3435 uint8_t mask = 0;
3436
3437 if (!var)
3438 continue;
3439
3440 switch (var->data.mode) {
3441 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3442 * "For GetActiveAttrib, all active vertex shader input variables
3443 * are enumerated, including the special built-in inputs gl_VertexID
3444 * and gl_InstanceID."
3445 */
3446 case ir_var_system_value:
3447 if (var->data.location != SYSTEM_VALUE_VERTEX_ID &&
3448 var->data.location != SYSTEM_VALUE_VERTEX_ID_ZERO_BASE &&
3449 var->data.location != SYSTEM_VALUE_INSTANCE_ID)
3450 continue;
3451 /* Mark special built-in inputs referenced by the vertex stage so
3452 * that they are considered active by the shader queries.
3453 */
3454 mask = (1 << (MESA_SHADER_VERTEX));
3455 /* FALLTHROUGH */
3456 case ir_var_shader_in:
3457 if (programInterface != GL_PROGRAM_INPUT)
3458 continue;
3459 break;
3460 case ir_var_shader_out:
3461 if (programInterface != GL_PROGRAM_OUTPUT)
3462 continue;
3463 break;
3464 default:
3465 continue;
3466 };
3467
3468 /* Skip packed varyings, packed varyings are handled separately
3469 * by add_packed_varyings.
3470 */
3471 if (strncmp(var->name, "packed:", 7) == 0)
3472 continue;
3473
3474 /* Skip fragdata arrays, these are handled separately
3475 * by add_fragdata_arrays.
3476 */
3477 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
3478 continue;
3479
3480 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3481 if (!sha_v)
3482 return false;
3483
3484 if (!add_program_resource(shProg, programInterface, sha_v,
3485 build_stageref(shProg, sha_v->name,
3486 sha_v->mode) | mask))
3487 return false;
3488 }
3489 return true;
3490 }
3491
3492 static bool
3493 add_packed_varyings(struct gl_shader_program *shProg, int stage, GLenum type)
3494 {
3495 struct gl_shader *sh = shProg->_LinkedShaders[stage];
3496 GLenum iface;
3497
3498 if (!sh || !sh->packed_varyings)
3499 return true;
3500
3501 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
3502 ir_variable *var = node->as_variable();
3503 if (var) {
3504 switch (var->data.mode) {
3505 case ir_var_shader_in:
3506 iface = GL_PROGRAM_INPUT;
3507 break;
3508 case ir_var_shader_out:
3509 iface = GL_PROGRAM_OUTPUT;
3510 break;
3511 default:
3512 unreachable("unexpected type");
3513 }
3514
3515 if (type == iface) {
3516 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3517 if (!sha_v)
3518 return false;
3519 if (!add_program_resource(shProg, iface, sha_v,
3520 build_stageref(shProg, sha_v->name,
3521 sha_v->mode)))
3522 return false;
3523 }
3524 }
3525 }
3526 return true;
3527 }
3528
3529 static bool
3530 add_fragdata_arrays(struct gl_shader_program *shProg)
3531 {
3532 struct gl_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
3533
3534 if (!sh || !sh->fragdata_arrays)
3535 return true;
3536
3537 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
3538 ir_variable *var = node->as_variable();
3539 if (var) {
3540 assert(var->data.mode == ir_var_shader_out);
3541 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3542 if (!sha_v)
3543 return false;
3544 if (!add_program_resource(shProg, GL_PROGRAM_OUTPUT, sha_v,
3545 1 << MESA_SHADER_FRAGMENT))
3546 return false;
3547 }
3548 }
3549 return true;
3550 }
3551
3552 static char*
3553 get_top_level_name(const char *name)
3554 {
3555 const char *first_dot = strchr(name, '.');
3556 const char *first_square_bracket = strchr(name, '[');
3557 int name_size = 0;
3558 /* From ARB_program_interface_query spec:
3559 *
3560 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3561 * number of active array elements of the top-level shader storage block
3562 * member containing to the active variable is written to <params>. If the
3563 * top-level block member is not declared as an array, the value one is
3564 * written to <params>. If the top-level block member is an array with no
3565 * declared size, the value zero is written to <params>.
3566 */
3567
3568 /* The buffer variable is on top level.*/
3569 if (!first_square_bracket && !first_dot)
3570 name_size = strlen(name);
3571 else if ((!first_square_bracket ||
3572 (first_dot && first_dot < first_square_bracket)))
3573 name_size = first_dot - name;
3574 else
3575 name_size = first_square_bracket - name;
3576
3577 return strndup(name, name_size);
3578 }
3579
3580 static char*
3581 get_var_name(const char *name)
3582 {
3583 const char *first_dot = strchr(name, '.');
3584
3585 if (!first_dot)
3586 return strdup(name);
3587
3588 return strndup(first_dot+1, strlen(first_dot) - 1);
3589 }
3590
3591 static bool
3592 is_top_level_shader_storage_block_member(const char* name,
3593 const char* interface_name,
3594 const char* field_name)
3595 {
3596 bool result = false;
3597
3598 /* If the given variable is already a top-level shader storage
3599 * block member, then return array_size = 1.
3600 * We could have two possibilities: if we have an instanced
3601 * shader storage block or not instanced.
3602 *
3603 * For the first, we check create a name as it was in top level and
3604 * compare it with the real name. If they are the same, then
3605 * the variable is already at top-level.
3606 *
3607 * Full instanced name is: interface name + '.' + var name +
3608 * NULL character
3609 */
3610 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
3611 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
3612 if (!full_instanced_name) {
3613 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
3614 return false;
3615 }
3616
3617 snprintf(full_instanced_name, name_length, "%s.%s",
3618 interface_name, field_name);
3619
3620 /* Check if its top-level shader storage block member of an
3621 * instanced interface block, or of a unnamed interface block.
3622 */
3623 if (strcmp(name, full_instanced_name) == 0 ||
3624 strcmp(name, field_name) == 0)
3625 result = true;
3626
3627 free(full_instanced_name);
3628 return result;
3629 }
3630
3631 static int
3632 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
3633 char *interface_name, char *var_name)
3634 {
3635 /* From GL_ARB_program_interface_query spec:
3636 *
3637 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3638 * identifying the number of active array elements of the top-level
3639 * shader storage block member containing to the active variable is
3640 * written to <params>. If the top-level block member is not
3641 * declared as an array, the value one is written to <params>. If
3642 * the top-level block member is an array with no declared size,
3643 * the value zero is written to <params>.
3644 */
3645 if (is_top_level_shader_storage_block_member(uni->name,
3646 interface_name,
3647 var_name))
3648 return 1;
3649 else if (field->type->is_unsized_array())
3650 return 0;
3651 else if (field->type->is_array())
3652 return field->type->length;
3653
3654 return 1;
3655 }
3656
3657 static int
3658 get_array_stride(struct gl_uniform_storage *uni, const glsl_type *interface,
3659 const glsl_struct_field *field, char *interface_name,
3660 char *var_name)
3661 {
3662 /* From GL_ARB_program_interface_query:
3663 *
3664 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3665 * identifying the stride between array elements of the top-level
3666 * shader storage block member containing the active variable is
3667 * written to <params>. For top-level block members declared as
3668 * arrays, the value written is the difference, in basic machine
3669 * units, between the offsets of the active variable for
3670 * consecutive elements in the top-level array. For top-level
3671 * block members not declared as an array, zero is written to
3672 * <params>."
3673 */
3674 if (field->type->is_array()) {
3675 const enum glsl_matrix_layout matrix_layout =
3676 glsl_matrix_layout(field->matrix_layout);
3677 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
3678 const glsl_type *array_type = field->type->fields.array;
3679
3680 if (is_top_level_shader_storage_block_member(uni->name,
3681 interface_name,
3682 var_name))
3683 return 0;
3684
3685 if (interface->interface_packing != GLSL_INTERFACE_PACKING_STD430) {
3686 if (array_type->is_record() || array_type->is_array())
3687 return glsl_align(array_type->std140_size(row_major), 16);
3688 else
3689 return MAX2(array_type->std140_base_alignment(row_major), 16);
3690 } else {
3691 return array_type->std430_array_stride(row_major);
3692 }
3693 }
3694 return 0;
3695 }
3696
3697 static void
3698 calculate_array_size_and_stride(struct gl_shader_program *shProg,
3699 struct gl_uniform_storage *uni)
3700 {
3701 int block_index = uni->block_index;
3702 int array_size = -1;
3703 int array_stride = -1;
3704 char *var_name = get_top_level_name(uni->name);
3705 char *interface_name =
3706 get_top_level_name(shProg->BufferInterfaceBlocks[block_index].Name);
3707
3708 if (strcmp(var_name, interface_name) == 0) {
3709 /* Deal with instanced array of SSBOs */
3710 char *temp_name = get_var_name(uni->name);
3711 if (!temp_name) {
3712 linker_error(shProg, "Out of memory during linking.\n");
3713 goto write_top_level_array_size_and_stride;
3714 }
3715 free(var_name);
3716 var_name = get_top_level_name(temp_name);
3717 free(temp_name);
3718 if (!var_name) {
3719 linker_error(shProg, "Out of memory during linking.\n");
3720 goto write_top_level_array_size_and_stride;
3721 }
3722 }
3723
3724 for (unsigned i = 0; i < shProg->NumShaders; i++) {
3725 if (shProg->Shaders[i] == NULL)
3726 continue;
3727
3728 const gl_shader *stage = shProg->Shaders[i];
3729 foreach_in_list(ir_instruction, node, stage->ir) {
3730 ir_variable *var = node->as_variable();
3731 if (!var || !var->get_interface_type() ||
3732 var->data.mode != ir_var_shader_storage)
3733 continue;
3734
3735 const glsl_type *interface = var->get_interface_type();
3736
3737 if (strcmp(interface_name, interface->name) != 0)
3738 continue;
3739
3740 for (unsigned i = 0; i < interface->length; i++) {
3741 const glsl_struct_field *field = &interface->fields.structure[i];
3742 if (strcmp(field->name, var_name) != 0)
3743 continue;
3744
3745 array_stride = get_array_stride(uni, interface, field,
3746 interface_name, var_name);
3747 array_size = get_array_size(uni, field, interface_name, var_name);
3748 goto write_top_level_array_size_and_stride;
3749 }
3750 }
3751 }
3752 write_top_level_array_size_and_stride:
3753 free(interface_name);
3754 free(var_name);
3755 uni->top_level_array_stride = array_stride;
3756 uni->top_level_array_size = array_size;
3757 }
3758
3759 /**
3760 * Builds up a list of program resources that point to existing
3761 * resource data.
3762 */
3763 void
3764 build_program_resource_list(struct gl_shader_program *shProg)
3765 {
3766 /* Rebuild resource list. */
3767 if (shProg->ProgramResourceList) {
3768 ralloc_free(shProg->ProgramResourceList);
3769 shProg->ProgramResourceList = NULL;
3770 shProg->NumProgramResourceList = 0;
3771 }
3772
3773 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
3774
3775 /* Determine first input and final output stage. These are used to
3776 * detect which variables should be enumerated in the resource list
3777 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3778 */
3779 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3780 if (!shProg->_LinkedShaders[i])
3781 continue;
3782 if (input_stage == MESA_SHADER_STAGES)
3783 input_stage = i;
3784 output_stage = i;
3785 }
3786
3787 /* Empty shader, no resources. */
3788 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
3789 return;
3790
3791 /* Program interface needs to expose varyings in case of SSO. */
3792 if (shProg->SeparateShader) {
3793 if (!add_packed_varyings(shProg, input_stage, GL_PROGRAM_INPUT))
3794 return;
3795
3796 if (!add_packed_varyings(shProg, output_stage, GL_PROGRAM_OUTPUT))
3797 return;
3798 }
3799
3800 if (!add_fragdata_arrays(shProg))
3801 return;
3802
3803 /* Add inputs and outputs to the resource list. */
3804 if (!add_interface_variables(shProg, shProg->_LinkedShaders[input_stage]->ir,
3805 GL_PROGRAM_INPUT))
3806 return;
3807
3808 if (!add_interface_variables(shProg, shProg->_LinkedShaders[output_stage]->ir,
3809 GL_PROGRAM_OUTPUT))
3810 return;
3811
3812 /* Add transform feedback varyings. */
3813 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
3814 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
3815 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
3816 &shProg->LinkedTransformFeedback.Varyings[i],
3817 0))
3818 return;
3819 }
3820 }
3821
3822 /* Add uniforms from uniform storage. */
3823 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
3824 /* Do not add uniforms internally used by Mesa. */
3825 if (shProg->UniformStorage[i].hidden)
3826 continue;
3827
3828 uint8_t stageref =
3829 build_stageref(shProg, shProg->UniformStorage[i].name,
3830 ir_var_uniform);
3831
3832 /* Add stagereferences for uniforms in a uniform block. */
3833 int block_index = shProg->UniformStorage[i].block_index;
3834 if (block_index != -1) {
3835 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
3836 if (shProg->InterfaceBlockStageIndex[j][block_index] != -1)
3837 stageref |= (1 << j);
3838 }
3839 }
3840
3841 bool is_shader_storage = shProg->UniformStorage[i].is_shader_storage;
3842 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
3843 if (!should_add_buffer_variable(shProg, type,
3844 shProg->UniformStorage[i].name))
3845 continue;
3846
3847 if (is_shader_storage) {
3848 calculate_array_size_and_stride(shProg, &shProg->UniformStorage[i]);
3849 }
3850
3851 if (!add_program_resource(shProg, type,
3852 &shProg->UniformStorage[i], stageref))
3853 return;
3854 }
3855
3856 /* Add program uniform blocks and shader storage blocks. */
3857 for (unsigned i = 0; i < shProg->NumBufferInterfaceBlocks; i++) {
3858 bool is_shader_storage = shProg->BufferInterfaceBlocks[i].IsShaderStorage;
3859 GLenum type = is_shader_storage ? GL_SHADER_STORAGE_BLOCK : GL_UNIFORM_BLOCK;
3860 if (!add_program_resource(shProg, type,
3861 &shProg->BufferInterfaceBlocks[i], 0))
3862 return;
3863 }
3864
3865 /* Add atomic counter buffers. */
3866 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
3867 if (!add_program_resource(shProg, GL_ATOMIC_COUNTER_BUFFER,
3868 &shProg->AtomicBuffers[i], 0))
3869 return;
3870 }
3871
3872 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
3873 GLenum type;
3874 if (!shProg->UniformStorage[i].hidden)
3875 continue;
3876
3877 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
3878 if (!shProg->UniformStorage[i].opaque[j].active ||
3879 !shProg->UniformStorage[i].type->is_subroutine())
3880 continue;
3881
3882 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
3883 /* add shader subroutines */
3884 if (!add_program_resource(shProg, type, &shProg->UniformStorage[i], 0))
3885 return;
3886 }
3887 }
3888
3889 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3890 struct gl_shader *sh = shProg->_LinkedShaders[i];
3891 GLuint type;
3892
3893 if (!sh)
3894 continue;
3895
3896 type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
3897 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
3898 if (!add_program_resource(shProg, type, &sh->SubroutineFunctions[j], 0))
3899 return;
3900 }
3901 }
3902 }
3903
3904 /**
3905 * This check is done to make sure we allow only constant expression
3906 * indexing and "constant-index-expression" (indexing with an expression
3907 * that includes loop induction variable).
3908 */
3909 static bool
3910 validate_sampler_array_indexing(struct gl_context *ctx,
3911 struct gl_shader_program *prog)
3912 {
3913 dynamic_sampler_array_indexing_visitor v;
3914 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3915 if (prog->_LinkedShaders[i] == NULL)
3916 continue;
3917
3918 bool no_dynamic_indexing =
3919 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
3920
3921 /* Search for array derefs in shader. */
3922 v.run(prog->_LinkedShaders[i]->ir);
3923 if (v.uses_dynamic_sampler_array_indexing()) {
3924 const char *msg = "sampler arrays indexed with non-constant "
3925 "expressions is forbidden in GLSL %s %u";
3926 /* Backend has indicated that it has no dynamic indexing support. */
3927 if (no_dynamic_indexing) {
3928 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3929 return false;
3930 } else {
3931 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3932 }
3933 }
3934 }
3935 return true;
3936 }
3937
3938 static void
3939 link_assign_subroutine_types(struct gl_shader_program *prog)
3940 {
3941 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3942 gl_shader *sh = prog->_LinkedShaders[i];
3943
3944 if (sh == NULL)
3945 continue;
3946
3947 foreach_in_list(ir_instruction, node, sh->ir) {
3948 ir_function *fn = node->as_function();
3949 if (!fn)
3950 continue;
3951
3952 if (fn->is_subroutine)
3953 sh->NumSubroutineUniformTypes++;
3954
3955 if (!fn->num_subroutine_types)
3956 continue;
3957
3958 sh->SubroutineFunctions = reralloc(sh, sh->SubroutineFunctions,
3959 struct gl_subroutine_function,
3960 sh->NumSubroutineFunctions + 1);
3961 sh->SubroutineFunctions[sh->NumSubroutineFunctions].name = ralloc_strdup(sh, fn->name);
3962 sh->SubroutineFunctions[sh->NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
3963 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types =
3964 ralloc_array(sh, const struct glsl_type *,
3965 fn->num_subroutine_types);
3966
3967 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
3968 * GLSL 4.5 spec:
3969 *
3970 * "Each subroutine with an index qualifier in the shader must be
3971 * given a unique index, otherwise a compile or link error will be
3972 * generated."
3973 */
3974 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
3975 if (sh->SubroutineFunctions[j].index != -1 &&
3976 sh->SubroutineFunctions[j].index == fn->subroutine_index) {
3977 linker_error(prog, "each subroutine index qualifier in the "
3978 "shader must be unique\n");
3979 return;
3980 }
3981 }
3982 sh->SubroutineFunctions[sh->NumSubroutineFunctions].index =
3983 fn->subroutine_index;
3984
3985 for (int j = 0; j < fn->num_subroutine_types; j++)
3986 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
3987 sh->NumSubroutineFunctions++;
3988 }
3989
3990 /* Assign index for subroutines without an explicit index*/
3991 int index = 0;
3992 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
3993 while (sh->SubroutineFunctions[j].index == -1) {
3994 for (unsigned k = 0; k < sh->NumSubroutineFunctions; k++) {
3995 if (sh->SubroutineFunctions[k].index == index)
3996 break;
3997 else if (k == sh->NumSubroutineFunctions - 1)
3998 sh->SubroutineFunctions[j].index = index;
3999 }
4000 index++;
4001 }
4002 }
4003 }
4004 }
4005
4006 static void
4007 split_ubos_and_ssbos(void *mem_ctx,
4008 struct gl_uniform_block *blocks,
4009 unsigned num_blocks,
4010 struct gl_uniform_block ***ubos,
4011 unsigned *num_ubos,
4012 unsigned **ubo_interface_block_indices,
4013 struct gl_uniform_block ***ssbos,
4014 unsigned *num_ssbos,
4015 unsigned **ssbo_interface_block_indices)
4016 {
4017 unsigned num_ubo_blocks = 0;
4018 unsigned num_ssbo_blocks = 0;
4019
4020 for (unsigned i = 0; i < num_blocks; i++) {
4021 if (blocks[i].IsShaderStorage)
4022 num_ssbo_blocks++;
4023 else
4024 num_ubo_blocks++;
4025 }
4026
4027 *ubos = ralloc_array(mem_ctx, gl_uniform_block *, num_ubo_blocks);
4028 *num_ubos = 0;
4029
4030 *ssbos = ralloc_array(mem_ctx, gl_uniform_block *, num_ssbo_blocks);
4031 *num_ssbos = 0;
4032
4033 if (ubo_interface_block_indices)
4034 *ubo_interface_block_indices =
4035 ralloc_array(mem_ctx, unsigned, num_ubo_blocks);
4036
4037 if (ssbo_interface_block_indices)
4038 *ssbo_interface_block_indices =
4039 ralloc_array(mem_ctx, unsigned, num_ssbo_blocks);
4040
4041 for (unsigned i = 0; i < num_blocks; i++) {
4042 if (blocks[i].IsShaderStorage) {
4043 (*ssbos)[*num_ssbos] = &blocks[i];
4044 if (ssbo_interface_block_indices)
4045 (*ssbo_interface_block_indices)[*num_ssbos] = i;
4046 (*num_ssbos)++;
4047 } else {
4048 (*ubos)[*num_ubos] = &blocks[i];
4049 if (ubo_interface_block_indices)
4050 (*ubo_interface_block_indices)[*num_ubos] = i;
4051 (*num_ubos)++;
4052 }
4053 }
4054
4055 assert(*num_ubos + *num_ssbos == num_blocks);
4056 }
4057
4058 static void
4059 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4060 {
4061 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4062
4063 foreach_in_list(ir_instruction, node, ir) {
4064 ir_variable *const var = node->as_variable();
4065
4066 if (var == NULL || var->data.mode != io_mode)
4067 continue;
4068
4069 /* Don't set always active on builtins that haven't been redeclared */
4070 if (var->data.how_declared == ir_var_declared_implicitly)
4071 continue;
4072
4073 var->data.always_active_io = true;
4074 }
4075 }
4076
4077 /**
4078 * When separate shader programs are enabled, only input/outputs between
4079 * the stages of a multi-stage separate program can be safely removed
4080 * from the shader interface. Other inputs/outputs must remain active.
4081 */
4082 static void
4083 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4084 {
4085 unsigned first, last;
4086 assert(prog->SeparateShader);
4087
4088 first = MESA_SHADER_STAGES;
4089 last = 0;
4090
4091 /* Determine first and last stage. Excluding the compute stage */
4092 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4093 if (!prog->_LinkedShaders[i])
4094 continue;
4095 if (first == MESA_SHADER_STAGES)
4096 first = i;
4097 last = i;
4098 }
4099
4100 if (first == MESA_SHADER_STAGES)
4101 return;
4102
4103 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4104 gl_shader *sh = prog->_LinkedShaders[stage];
4105 if (!sh)
4106 continue;
4107
4108 if (first == last) {
4109 /* For a single shader program only allow inputs to the vertex shader
4110 * and outputs from the fragment shader to be removed.
4111 */
4112 if (stage != MESA_SHADER_VERTEX)
4113 set_always_active_io(sh->ir, ir_var_shader_in);
4114 if (stage != MESA_SHADER_FRAGMENT)
4115 set_always_active_io(sh->ir, ir_var_shader_out);
4116 } else {
4117 /* For multi-stage separate shader programs only allow inputs and
4118 * outputs between the shader stages to be removed as well as inputs
4119 * to the vertex shader and outputs from the fragment shader.
4120 */
4121 if (stage == first && stage != MESA_SHADER_VERTEX)
4122 set_always_active_io(sh->ir, ir_var_shader_in);
4123 else if (stage == last && stage != MESA_SHADER_FRAGMENT)
4124 set_always_active_io(sh->ir, ir_var_shader_out);
4125 }
4126 }
4127 }
4128
4129 void
4130 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4131 {
4132 prog->LinkStatus = true; /* All error paths will set this to false */
4133 prog->Validated = false;
4134 prog->_Used = false;
4135
4136 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4137 *
4138 * "Linking can fail for a variety of reasons as specified in the
4139 * OpenGL Shading Language Specification, as well as any of the
4140 * following reasons:
4141 *
4142 * - No shader objects are attached to program."
4143 *
4144 * The Compatibility Profile specification does not list the error. In
4145 * Compatibility Profile missing shader stages are replaced by
4146 * fixed-function. This applies to the case where all stages are
4147 * missing.
4148 */
4149 if (prog->NumShaders == 0) {
4150 if (ctx->API != API_OPENGL_COMPAT)
4151 linker_error(prog, "no shaders attached to the program\n");
4152 return;
4153 }
4154
4155 tfeedback_decl *tfeedback_decls = NULL;
4156 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
4157 unsigned int num_explicit_uniform_locs = 0;
4158
4159 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4160
4161 prog->ARB_fragment_coord_conventions_enable = false;
4162
4163 /* Separate the shaders into groups based on their type.
4164 */
4165 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4166 unsigned num_shaders[MESA_SHADER_STAGES];
4167
4168 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4169 shader_list[i] = (struct gl_shader **)
4170 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4171 num_shaders[i] = 0;
4172 }
4173
4174 unsigned min_version = UINT_MAX;
4175 unsigned max_version = 0;
4176 for (unsigned i = 0; i < prog->NumShaders; i++) {
4177 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4178 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4179
4180 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4181 linker_error(prog, "all shaders must use same shading "
4182 "language version\n");
4183 goto done;
4184 }
4185
4186 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4187 prog->ARB_fragment_coord_conventions_enable = true;
4188 }
4189
4190 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4191 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4192 num_shaders[shader_type]++;
4193 }
4194
4195 /* In desktop GLSL, different shader versions may be linked together. In
4196 * GLSL ES, all shader versions must be the same.
4197 */
4198 if (prog->Shaders[0]->IsES && min_version != max_version) {
4199 linker_error(prog, "all shaders must use same shading "
4200 "language version\n");
4201 goto done;
4202 }
4203
4204 prog->Version = max_version;
4205 prog->IsES = prog->Shaders[0]->IsES;
4206
4207 /* Some shaders have to be linked with some other shaders present.
4208 */
4209 if (!prog->SeparateShader) {
4210 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4211 num_shaders[MESA_SHADER_VERTEX] == 0) {
4212 linker_error(prog, "Geometry shader must be linked with "
4213 "vertex shader\n");
4214 goto done;
4215 }
4216 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4217 num_shaders[MESA_SHADER_VERTEX] == 0) {
4218 linker_error(prog, "Tessellation evaluation shader must be linked "
4219 "with vertex shader\n");
4220 goto done;
4221 }
4222 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4223 num_shaders[MESA_SHADER_VERTEX] == 0) {
4224 linker_error(prog, "Tessellation control shader must be linked with "
4225 "vertex shader\n");
4226 goto done;
4227 }
4228
4229 /* The spec is self-contradictory here. It allows linking without a tess
4230 * eval shader, but that can only be used with transform feedback and
4231 * rasterization disabled. However, transform feedback isn't allowed
4232 * with GL_PATCHES, so it can't be used.
4233 *
4234 * More investigation showed that the idea of transform feedback after
4235 * a tess control shader was dropped, because some hw vendors couldn't
4236 * support tessellation without a tess eval shader, but the linker
4237 * section wasn't updated to reflect that.
4238 *
4239 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4240 * spec bug.
4241 *
4242 * Do what's reasonable and always require a tess eval shader if a tess
4243 * control shader is present.
4244 */
4245 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4246 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4247 linker_error(prog, "Tessellation control shader must be linked with "
4248 "tessellation evaluation shader\n");
4249 goto done;
4250 }
4251 }
4252
4253 /* Compute shaders have additional restrictions. */
4254 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4255 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4256 linker_error(prog, "Compute shaders may not be linked with any other "
4257 "type of shader\n");
4258 }
4259
4260 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4261 if (prog->_LinkedShaders[i] != NULL)
4262 _mesa_delete_shader(ctx, prog->_LinkedShaders[i]);
4263
4264 prog->_LinkedShaders[i] = NULL;
4265 }
4266
4267 /* Link all shaders for a particular stage and validate the result.
4268 */
4269 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4270 if (num_shaders[stage] > 0) {
4271 gl_shader *const sh =
4272 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4273 num_shaders[stage]);
4274
4275 if (!prog->LinkStatus) {
4276 if (sh)
4277 _mesa_delete_shader(ctx, sh);
4278 goto done;
4279 }
4280
4281 switch (stage) {
4282 case MESA_SHADER_VERTEX:
4283 validate_vertex_shader_executable(prog, sh);
4284 break;
4285 case MESA_SHADER_TESS_CTRL:
4286 /* nothing to be done */
4287 break;
4288 case MESA_SHADER_TESS_EVAL:
4289 validate_tess_eval_shader_executable(prog, sh);
4290 break;
4291 case MESA_SHADER_GEOMETRY:
4292 validate_geometry_shader_executable(prog, sh);
4293 break;
4294 case MESA_SHADER_FRAGMENT:
4295 validate_fragment_shader_executable(prog, sh);
4296 break;
4297 }
4298 if (!prog->LinkStatus) {
4299 if (sh)
4300 _mesa_delete_shader(ctx, sh);
4301 goto done;
4302 }
4303
4304 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
4305 }
4306 }
4307
4308 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
4309 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
4310 else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0)
4311 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
4312 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
4313 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
4314 else
4315 prog->LastClipDistanceArraySize = 0; /* Not used */
4316
4317 /* Here begins the inter-stage linking phase. Some initial validation is
4318 * performed, then locations are assigned for uniforms, attributes, and
4319 * varyings.
4320 */
4321 cross_validate_uniforms(prog);
4322 if (!prog->LinkStatus)
4323 goto done;
4324
4325 unsigned first, last, prev;
4326
4327 first = MESA_SHADER_STAGES;
4328 last = 0;
4329
4330 /* Determine first and last stage. */
4331 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4332 if (!prog->_LinkedShaders[i])
4333 continue;
4334 if (first == MESA_SHADER_STAGES)
4335 first = i;
4336 last = i;
4337 }
4338
4339 num_explicit_uniform_locs = check_explicit_uniform_locations(ctx, prog);
4340 link_assign_subroutine_types(prog);
4341
4342 if (!prog->LinkStatus)
4343 goto done;
4344
4345 resize_tes_inputs(ctx, prog);
4346
4347 /* Validate the inputs of each stage with the output of the preceding
4348 * stage.
4349 */
4350 prev = first;
4351 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4352 if (prog->_LinkedShaders[i] == NULL)
4353 continue;
4354
4355 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4356 prog->_LinkedShaders[i]);
4357 if (!prog->LinkStatus)
4358 goto done;
4359
4360 cross_validate_outputs_to_inputs(prog,
4361 prog->_LinkedShaders[prev],
4362 prog->_LinkedShaders[i]);
4363 if (!prog->LinkStatus)
4364 goto done;
4365
4366 prev = i;
4367 }
4368
4369 /* Cross-validate uniform blocks between shader stages */
4370 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
4371 MESA_SHADER_STAGES);
4372 if (!prog->LinkStatus)
4373 goto done;
4374
4375 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4376 if (prog->_LinkedShaders[i] != NULL)
4377 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
4378 }
4379
4380 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4381 * it before optimization because we want most of the checks to get
4382 * dropped thanks to constant propagation.
4383 *
4384 * This rule also applies to GLSL ES 3.00.
4385 */
4386 if (max_version >= (prog->IsES ? 300 : 130)) {
4387 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4388 if (sh) {
4389 lower_discard_flow(sh->ir);
4390 }
4391 }
4392
4393 if (prog->SeparateShader)
4394 disable_varying_optimizations_for_sso(prog);
4395
4396 if (!interstage_cross_validate_uniform_blocks(prog))
4397 goto done;
4398
4399 /* Do common optimization before assigning storage for attributes,
4400 * uniforms, and varyings. Later optimization could possibly make
4401 * some of that unused.
4402 */
4403 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4404 if (prog->_LinkedShaders[i] == NULL)
4405 continue;
4406
4407 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
4408 if (!prog->LinkStatus)
4409 goto done;
4410
4411 if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
4412 lower_clip_distance(prog->_LinkedShaders[i]);
4413 }
4414
4415 if (ctx->Const.LowerTessLevel) {
4416 lower_tess_level(prog->_LinkedShaders[i]);
4417 }
4418
4419 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
4420 &ctx->Const.ShaderCompilerOptions[i],
4421 ctx->Const.NativeIntegers))
4422 ;
4423
4424 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
4425 }
4426
4427 /* Validation for special cases where we allow sampler array indexing
4428 * with loop induction variable. This check emits a warning or error
4429 * depending if backend can handle dynamic indexing.
4430 */
4431 if ((!prog->IsES && prog->Version < 130) ||
4432 (prog->IsES && prog->Version < 300)) {
4433 if (!validate_sampler_array_indexing(ctx, prog))
4434 goto done;
4435 }
4436
4437 /* Check and validate stream emissions in geometry shaders */
4438 validate_geometry_shader_emissions(ctx, prog);
4439
4440 /* Mark all generic shader inputs and outputs as unpaired. */
4441 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4442 if (prog->_LinkedShaders[i] != NULL) {
4443 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4444 }
4445 }
4446
4447 prev = first;
4448 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4449 if (prog->_LinkedShaders[i] == NULL)
4450 continue;
4451
4452 match_explicit_outputs_to_inputs(prog, prog->_LinkedShaders[prev],
4453 prog->_LinkedShaders[i]);
4454 prev = i;
4455 }
4456
4457 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4458 MESA_SHADER_VERTEX)) {
4459 goto done;
4460 }
4461
4462 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4463 MESA_SHADER_FRAGMENT)) {
4464 goto done;
4465 }
4466
4467 if (num_tfeedback_decls != 0) {
4468 /* From GL_EXT_transform_feedback:
4469 * A program will fail to link if:
4470 *
4471 * * the <count> specified by TransformFeedbackVaryingsEXT is
4472 * non-zero, but the program object has no vertex or geometry
4473 * shader;
4474 */
4475 if (first >= MESA_SHADER_FRAGMENT) {
4476 linker_error(prog, "Transform feedback varyings specified, but "
4477 "no vertex, tessellation, or geometry shader is "
4478 "present.\n");
4479 goto done;
4480 }
4481
4482 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
4483 prog->TransformFeedback.NumVarying);
4484 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
4485 prog->TransformFeedback.VaryingNames,
4486 tfeedback_decls))
4487 goto done;
4488 }
4489
4490 /* If there is no fragment shader we need to set transform feedback.
4491 *
4492 * For SSO we need also need to assign output locations, we assign them
4493 * here because we need to do it for both single stage programs and multi
4494 * stage programs.
4495 */
4496 if (last < MESA_SHADER_FRAGMENT &&
4497 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
4498 if (!assign_varying_locations(ctx, mem_ctx, prog,
4499 prog->_LinkedShaders[last], NULL,
4500 num_tfeedback_decls, tfeedback_decls))
4501 goto done;
4502 }
4503
4504 if (last <= MESA_SHADER_FRAGMENT) {
4505 /* Remove unused varyings from the first/last stage unless SSO */
4506 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4507 prog->_LinkedShaders[first],
4508 ir_var_shader_in);
4509 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4510 prog->_LinkedShaders[last],
4511 ir_var_shader_out);
4512
4513 /* If the program is made up of only a single stage */
4514 if (first == last) {
4515
4516 gl_shader *const sh = prog->_LinkedShaders[last];
4517 if (prog->SeparateShader) {
4518 /* Assign input locations for SSO, output locations are already
4519 * assigned.
4520 */
4521 if (!assign_varying_locations(ctx, mem_ctx, prog,
4522 NULL /* producer */,
4523 sh /* consumer */,
4524 0 /* num_tfeedback_decls */,
4525 NULL /* tfeedback_decls */))
4526 goto done;
4527 }
4528
4529 do_dead_builtin_varyings(ctx, NULL, sh, 0, NULL);
4530 do_dead_builtin_varyings(ctx, sh, NULL, num_tfeedback_decls,
4531 tfeedback_decls);
4532 } else {
4533 /* Linking the stages in the opposite order (from fragment to vertex)
4534 * ensures that inter-shader outputs written to in an earlier stage
4535 * are eliminated if they are (transitively) not used in a later
4536 * stage.
4537 */
4538 int next = last;
4539 for (int i = next - 1; i >= 0; i--) {
4540 if (prog->_LinkedShaders[i] == NULL)
4541 continue;
4542
4543 gl_shader *const sh_i = prog->_LinkedShaders[i];
4544 gl_shader *const sh_next = prog->_LinkedShaders[next];
4545
4546 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
4547 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4548 tfeedback_decls))
4549 goto done;
4550
4551 do_dead_builtin_varyings(ctx, sh_i, sh_next,
4552 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4553 tfeedback_decls);
4554
4555 /* This must be done after all dead varyings are eliminated. */
4556 if (!check_against_output_limit(ctx, prog, sh_i))
4557 goto done;
4558 if (!check_against_input_limit(ctx, prog, sh_next))
4559 goto done;
4560
4561 next = i;
4562 }
4563 }
4564 }
4565
4566 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
4567 goto done;
4568
4569 update_array_sizes(prog);
4570 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue,
4571 num_explicit_uniform_locs,
4572 ctx->Const.MaxUserAssignableUniformLocations);
4573 link_assign_atomic_counter_resources(ctx, prog);
4574 store_fragdepth_layout(prog);
4575
4576 link_calculate_subroutine_compat(prog);
4577 check_resources(ctx, prog);
4578 check_subroutine_resources(prog);
4579 check_image_resources(ctx, prog);
4580 link_check_atomic_counter_resources(ctx, prog);
4581
4582 if (!prog->LinkStatus)
4583 goto done;
4584
4585 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4586 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4587 * anything about shader linking when one of the shaders (vertex or
4588 * fragment shader) is absent. So, the extension shouldn't change the
4589 * behavior specified in GLSL specification.
4590 *
4591 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4592 * "Linking can fail for a variety of reasons as specified in the
4593 * OpenGL ES Shading Language Specification, as well as any of the
4594 * following reasons:
4595 *
4596 * ...
4597 *
4598 * * program contains objects to form either a vertex shader or
4599 * fragment shader, and program is not separable, and does not
4600 * contain objects to form both a vertex shader and fragment
4601 * shader."
4602 *
4603 * However, the only scenario in 3.1+ where we don't require them both is
4604 * when we have a compute shader. For example:
4605 *
4606 * - No shaders is a link error.
4607 * - Geom or Tess without a Vertex shader is a link error which means we
4608 * always require a Vertex shader and hence a Fragment shader.
4609 * - Finally a Compute shader linked with any other stage is a link error.
4610 */
4611 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
4612 num_shaders[MESA_SHADER_COMPUTE] == 0) {
4613 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
4614 linker_error(prog, "program lacks a vertex shader\n");
4615 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
4616 linker_error(prog, "program lacks a fragment shader\n");
4617 }
4618 }
4619
4620 /* Split BufferInterfaceBlocks into UniformBlocks and ShaderStorageBlocks
4621 * for gl_shader_program and gl_shader, so that drivers that need separate
4622 * index spaces for each set can have that.
4623 */
4624 for (unsigned i = MESA_SHADER_VERTEX; i < MESA_SHADER_STAGES; i++) {
4625 if (prog->_LinkedShaders[i] != NULL) {
4626 gl_shader *sh = prog->_LinkedShaders[i];
4627 split_ubos_and_ssbos(sh,
4628 sh->BufferInterfaceBlocks,
4629 sh->NumBufferInterfaceBlocks,
4630 &sh->UniformBlocks,
4631 &sh->NumUniformBlocks,
4632 NULL,
4633 &sh->ShaderStorageBlocks,
4634 &sh->NumShaderStorageBlocks,
4635 NULL);
4636 }
4637 }
4638
4639 split_ubos_and_ssbos(prog,
4640 prog->BufferInterfaceBlocks,
4641 prog->NumBufferInterfaceBlocks,
4642 &prog->UniformBlocks,
4643 &prog->NumUniformBlocks,
4644 &prog->UboInterfaceBlockIndex,
4645 &prog->ShaderStorageBlocks,
4646 &prog->NumShaderStorageBlocks,
4647 &prog->SsboInterfaceBlockIndex);
4648
4649 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4650 if (prog->_LinkedShaders[i] == NULL)
4651 continue;
4652
4653 if (ctx->Const.ShaderCompilerOptions[i].LowerBufferInterfaceBlocks)
4654 lower_ubo_reference(prog->_LinkedShaders[i]);
4655
4656 if (ctx->Const.ShaderCompilerOptions[i].LowerShaderSharedVariables)
4657 lower_shared_reference(prog->_LinkedShaders[i],
4658 &prog->Comp.SharedSize);
4659
4660 lower_vector_derefs(prog->_LinkedShaders[i]);
4661 }
4662
4663 done:
4664 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4665 free(shader_list[i]);
4666 if (prog->_LinkedShaders[i] == NULL)
4667 continue;
4668
4669 /* Do a final validation step to make sure that the IR wasn't
4670 * invalidated by any modifications performed after intrastage linking.
4671 */
4672 validate_ir_tree(prog->_LinkedShaders[i]->ir);
4673
4674 /* Retain any live IR, but trash the rest. */
4675 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
4676
4677 /* The symbol table in the linked shaders may contain references to
4678 * variables that were removed (e.g., unused uniforms). Since it may
4679 * contain junk, there is no possible valid use. Delete it and set the
4680 * pointer to NULL.
4681 */
4682 delete prog->_LinkedShaders[i]->symbols;
4683 prog->_LinkedShaders[i]->symbols = NULL;
4684 }
4685
4686 ralloc_free(mem_ctx);
4687 }