glsl: basic linking support for xfb qualifiers
[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 /* Update per stage block pointers to point to the program list.
1208 * FIXME: We should be able to free the per stage blocks here.
1209 */
1210 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1211 for (unsigned j = 0; j < prog->NumBufferInterfaceBlocks; j++) {
1212 int stage_index =
1213 prog->InterfaceBlockStageIndex[i][j];
1214
1215 if (stage_index != -1) {
1216 struct gl_shader *sh = prog->_LinkedShaders[i];
1217
1218 sh->BufferInterfaceBlocks[stage_index] =
1219 &prog->BufferInterfaceBlocks[j];
1220 }
1221 }
1222 }
1223
1224 return true;
1225 }
1226
1227
1228 /**
1229 * Populates a shaders symbol table with all global declarations
1230 */
1231 static void
1232 populate_symbol_table(gl_shader *sh)
1233 {
1234 sh->symbols = new(sh) glsl_symbol_table;
1235
1236 foreach_in_list(ir_instruction, inst, sh->ir) {
1237 ir_variable *var;
1238 ir_function *func;
1239
1240 if ((func = inst->as_function()) != NULL) {
1241 sh->symbols->add_function(func);
1242 } else if ((var = inst->as_variable()) != NULL) {
1243 if (var->data.mode != ir_var_temporary)
1244 sh->symbols->add_variable(var);
1245 }
1246 }
1247 }
1248
1249
1250 /**
1251 * Remap variables referenced in an instruction tree
1252 *
1253 * This is used when instruction trees are cloned from one shader and placed in
1254 * another. These trees will contain references to \c ir_variable nodes that
1255 * do not exist in the target shader. This function finds these \c ir_variable
1256 * references and replaces the references with matching variables in the target
1257 * shader.
1258 *
1259 * If there is no matching variable in the target shader, a clone of the
1260 * \c ir_variable is made and added to the target shader. The new variable is
1261 * added to \b both the instruction stream and the symbol table.
1262 *
1263 * \param inst IR tree that is to be processed.
1264 * \param symbols Symbol table containing global scope symbols in the
1265 * linked shader.
1266 * \param instructions Instruction stream where new variable declarations
1267 * should be added.
1268 */
1269 void
1270 remap_variables(ir_instruction *inst, struct gl_shader *target,
1271 hash_table *temps)
1272 {
1273 class remap_visitor : public ir_hierarchical_visitor {
1274 public:
1275 remap_visitor(struct gl_shader *target,
1276 hash_table *temps)
1277 {
1278 this->target = target;
1279 this->symbols = target->symbols;
1280 this->instructions = target->ir;
1281 this->temps = temps;
1282 }
1283
1284 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1285 {
1286 if (ir->var->data.mode == ir_var_temporary) {
1287 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1288
1289 assert(var != NULL);
1290 ir->var = var;
1291 return visit_continue;
1292 }
1293
1294 ir_variable *const existing =
1295 this->symbols->get_variable(ir->var->name);
1296 if (existing != NULL)
1297 ir->var = existing;
1298 else {
1299 ir_variable *copy = ir->var->clone(this->target, NULL);
1300
1301 this->symbols->add_variable(copy);
1302 this->instructions->push_head(copy);
1303 ir->var = copy;
1304 }
1305
1306 return visit_continue;
1307 }
1308
1309 private:
1310 struct gl_shader *target;
1311 glsl_symbol_table *symbols;
1312 exec_list *instructions;
1313 hash_table *temps;
1314 };
1315
1316 remap_visitor v(target, temps);
1317
1318 inst->accept(&v);
1319 }
1320
1321
1322 /**
1323 * Move non-declarations from one instruction stream to another
1324 *
1325 * The intended usage pattern of this function is to pass the pointer to the
1326 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1327 * pointer) for \c last and \c false for \c make_copies on the first
1328 * call. Successive calls pass the return value of the previous call for
1329 * \c last and \c true for \c make_copies.
1330 *
1331 * \param instructions Source instruction stream
1332 * \param last Instruction after which new instructions should be
1333 * inserted in the target instruction stream
1334 * \param make_copies Flag selecting whether instructions in \c instructions
1335 * should be copied (via \c ir_instruction::clone) into the
1336 * target list or moved.
1337 *
1338 * \return
1339 * The new "last" instruction in the target instruction stream. This pointer
1340 * is suitable for use as the \c last parameter of a later call to this
1341 * function.
1342 */
1343 exec_node *
1344 move_non_declarations(exec_list *instructions, exec_node *last,
1345 bool make_copies, gl_shader *target)
1346 {
1347 hash_table *temps = NULL;
1348
1349 if (make_copies)
1350 temps = hash_table_ctor(0, hash_table_pointer_hash,
1351 hash_table_pointer_compare);
1352
1353 foreach_in_list_safe(ir_instruction, inst, instructions) {
1354 if (inst->as_function())
1355 continue;
1356
1357 ir_variable *var = inst->as_variable();
1358 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1359 continue;
1360
1361 assert(inst->as_assignment()
1362 || inst->as_call()
1363 || inst->as_if() /* for initializers with the ?: operator */
1364 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1365
1366 if (make_copies) {
1367 inst = inst->clone(target, NULL);
1368
1369 if (var != NULL)
1370 hash_table_insert(temps, inst, var);
1371 else
1372 remap_variables(inst, target, temps);
1373 } else {
1374 inst->remove();
1375 }
1376
1377 last->insert_after(inst);
1378 last = inst;
1379 }
1380
1381 if (make_copies)
1382 hash_table_dtor(temps);
1383
1384 return last;
1385 }
1386
1387
1388 /**
1389 * This class is only used in link_intrastage_shaders() below but declaring
1390 * it inside that function leads to compiler warnings with some versions of
1391 * gcc.
1392 */
1393 class array_sizing_visitor : public ir_hierarchical_visitor {
1394 public:
1395 array_sizing_visitor()
1396 : mem_ctx(ralloc_context(NULL)),
1397 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1398 hash_table_pointer_compare))
1399 {
1400 }
1401
1402 ~array_sizing_visitor()
1403 {
1404 hash_table_dtor(this->unnamed_interfaces);
1405 ralloc_free(this->mem_ctx);
1406 }
1407
1408 virtual ir_visitor_status visit(ir_variable *var)
1409 {
1410 const glsl_type *type_without_array;
1411 fixup_type(&var->type, var->data.max_array_access,
1412 var->data.from_ssbo_unsized_array);
1413 type_without_array = var->type->without_array();
1414 if (var->type->is_interface()) {
1415 if (interface_contains_unsized_arrays(var->type)) {
1416 const glsl_type *new_type =
1417 resize_interface_members(var->type,
1418 var->get_max_ifc_array_access(),
1419 var->is_in_shader_storage_block());
1420 var->type = new_type;
1421 var->change_interface_type(new_type);
1422 }
1423 } else if (type_without_array->is_interface()) {
1424 if (interface_contains_unsized_arrays(type_without_array)) {
1425 const glsl_type *new_type =
1426 resize_interface_members(type_without_array,
1427 var->get_max_ifc_array_access(),
1428 var->is_in_shader_storage_block());
1429 var->change_interface_type(new_type);
1430 var->type = update_interface_members_array(var->type, new_type);
1431 }
1432 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1433 /* Store a pointer to the variable in the unnamed_interfaces
1434 * hashtable.
1435 */
1436 ir_variable **interface_vars = (ir_variable **)
1437 hash_table_find(this->unnamed_interfaces, ifc_type);
1438 if (interface_vars == NULL) {
1439 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1440 ifc_type->length);
1441 hash_table_insert(this->unnamed_interfaces, interface_vars,
1442 ifc_type);
1443 }
1444 unsigned index = ifc_type->field_index(var->name);
1445 assert(index < ifc_type->length);
1446 assert(interface_vars[index] == NULL);
1447 interface_vars[index] = var;
1448 }
1449 return visit_continue;
1450 }
1451
1452 /**
1453 * For each unnamed interface block that was discovered while running the
1454 * visitor, adjust the interface type to reflect the newly assigned array
1455 * sizes, and fix up the ir_variable nodes to point to the new interface
1456 * type.
1457 */
1458 void fixup_unnamed_interface_types()
1459 {
1460 hash_table_call_foreach(this->unnamed_interfaces,
1461 fixup_unnamed_interface_type, NULL);
1462 }
1463
1464 private:
1465 /**
1466 * If the type pointed to by \c type represents an unsized array, replace
1467 * it with a sized array whose size is determined by max_array_access.
1468 */
1469 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1470 bool from_ssbo_unsized_array)
1471 {
1472 if (!from_ssbo_unsized_array && (*type)->is_unsized_array()) {
1473 *type = glsl_type::get_array_instance((*type)->fields.array,
1474 max_array_access + 1);
1475 assert(*type != NULL);
1476 }
1477 }
1478
1479 static const glsl_type *
1480 update_interface_members_array(const glsl_type *type,
1481 const glsl_type *new_interface_type)
1482 {
1483 const glsl_type *element_type = type->fields.array;
1484 if (element_type->is_array()) {
1485 const glsl_type *new_array_type =
1486 update_interface_members_array(element_type, new_interface_type);
1487 return glsl_type::get_array_instance(new_array_type, type->length);
1488 } else {
1489 return glsl_type::get_array_instance(new_interface_type,
1490 type->length);
1491 }
1492 }
1493
1494 /**
1495 * Determine whether the given interface type contains unsized arrays (if
1496 * it doesn't, array_sizing_visitor doesn't need to process it).
1497 */
1498 static bool interface_contains_unsized_arrays(const glsl_type *type)
1499 {
1500 for (unsigned i = 0; i < type->length; i++) {
1501 const glsl_type *elem_type = type->fields.structure[i].type;
1502 if (elem_type->is_unsized_array())
1503 return true;
1504 }
1505 return false;
1506 }
1507
1508 /**
1509 * Create a new interface type based on the given type, with unsized arrays
1510 * replaced by sized arrays whose size is determined by
1511 * max_ifc_array_access.
1512 */
1513 static const glsl_type *
1514 resize_interface_members(const glsl_type *type,
1515 const unsigned *max_ifc_array_access,
1516 bool is_ssbo)
1517 {
1518 unsigned num_fields = type->length;
1519 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1520 memcpy(fields, type->fields.structure,
1521 num_fields * sizeof(*fields));
1522 for (unsigned i = 0; i < num_fields; i++) {
1523 /* If SSBO last member is unsized array, we don't replace it by a sized
1524 * array.
1525 */
1526 if (is_ssbo && i == (num_fields - 1))
1527 fixup_type(&fields[i].type, max_ifc_array_access[i],
1528 true);
1529 else
1530 fixup_type(&fields[i].type, max_ifc_array_access[i],
1531 false);
1532 }
1533 glsl_interface_packing packing =
1534 (glsl_interface_packing) type->interface_packing;
1535 const glsl_type *new_ifc_type =
1536 glsl_type::get_interface_instance(fields, num_fields,
1537 packing, type->name);
1538 delete [] fields;
1539 return new_ifc_type;
1540 }
1541
1542 static void fixup_unnamed_interface_type(const void *key, void *data,
1543 void *)
1544 {
1545 const glsl_type *ifc_type = (const glsl_type *) key;
1546 ir_variable **interface_vars = (ir_variable **) data;
1547 unsigned num_fields = ifc_type->length;
1548 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1549 memcpy(fields, ifc_type->fields.structure,
1550 num_fields * sizeof(*fields));
1551 bool interface_type_changed = false;
1552 for (unsigned i = 0; i < num_fields; i++) {
1553 if (interface_vars[i] != NULL &&
1554 fields[i].type != interface_vars[i]->type) {
1555 fields[i].type = interface_vars[i]->type;
1556 interface_type_changed = true;
1557 }
1558 }
1559 if (!interface_type_changed) {
1560 delete [] fields;
1561 return;
1562 }
1563 glsl_interface_packing packing =
1564 (glsl_interface_packing) ifc_type->interface_packing;
1565 const glsl_type *new_ifc_type =
1566 glsl_type::get_interface_instance(fields, num_fields, packing,
1567 ifc_type->name);
1568 delete [] fields;
1569 for (unsigned i = 0; i < num_fields; i++) {
1570 if (interface_vars[i] != NULL)
1571 interface_vars[i]->change_interface_type(new_ifc_type);
1572 }
1573 }
1574
1575 /**
1576 * Memory context used to allocate the data in \c unnamed_interfaces.
1577 */
1578 void *mem_ctx;
1579
1580 /**
1581 * Hash table from const glsl_type * to an array of ir_variable *'s
1582 * pointing to the ir_variables constituting each unnamed interface block.
1583 */
1584 hash_table *unnamed_interfaces;
1585 };
1586
1587
1588 /**
1589 * Performs the cross-validation of tessellation control shader vertices and
1590 * layout qualifiers for the attached tessellation control shaders,
1591 * and propagates them to the linked TCS and linked shader program.
1592 */
1593 static void
1594 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1595 struct gl_shader *linked_shader,
1596 struct gl_shader **shader_list,
1597 unsigned num_shaders)
1598 {
1599 linked_shader->TessCtrl.VerticesOut = 0;
1600
1601 if (linked_shader->Stage != MESA_SHADER_TESS_CTRL)
1602 return;
1603
1604 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1605 *
1606 * "All tessellation control shader layout declarations in a program
1607 * must specify the same output patch vertex count. There must be at
1608 * least one layout qualifier specifying an output patch vertex count
1609 * in any program containing tessellation control shaders; however,
1610 * such a declaration is not required in all tessellation control
1611 * shaders."
1612 */
1613
1614 for (unsigned i = 0; i < num_shaders; i++) {
1615 struct gl_shader *shader = shader_list[i];
1616
1617 if (shader->TessCtrl.VerticesOut != 0) {
1618 if (linked_shader->TessCtrl.VerticesOut != 0 &&
1619 linked_shader->TessCtrl.VerticesOut != shader->TessCtrl.VerticesOut) {
1620 linker_error(prog, "tessellation control shader defined with "
1621 "conflicting output vertex count (%d and %d)\n",
1622 linked_shader->TessCtrl.VerticesOut,
1623 shader->TessCtrl.VerticesOut);
1624 return;
1625 }
1626 linked_shader->TessCtrl.VerticesOut = shader->TessCtrl.VerticesOut;
1627 }
1628 }
1629
1630 /* Just do the intrastage -> interstage propagation right now,
1631 * since we already know we're in the right type of shader program
1632 * for doing it.
1633 */
1634 if (linked_shader->TessCtrl.VerticesOut == 0) {
1635 linker_error(prog, "tessellation control shader didn't declare "
1636 "vertices out layout qualifier\n");
1637 return;
1638 }
1639 prog->TessCtrl.VerticesOut = linked_shader->TessCtrl.VerticesOut;
1640 }
1641
1642
1643 /**
1644 * Performs the cross-validation of tessellation evaluation shader
1645 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1646 * for the attached tessellation evaluation shaders, and propagates them
1647 * to the linked TES and linked shader program.
1648 */
1649 static void
1650 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1651 struct gl_shader *linked_shader,
1652 struct gl_shader **shader_list,
1653 unsigned num_shaders)
1654 {
1655 linked_shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1656 linked_shader->TessEval.Spacing = 0;
1657 linked_shader->TessEval.VertexOrder = 0;
1658 linked_shader->TessEval.PointMode = -1;
1659
1660 if (linked_shader->Stage != MESA_SHADER_TESS_EVAL)
1661 return;
1662
1663 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1664 *
1665 * "At least one tessellation evaluation shader (compilation unit) in
1666 * a program must declare a primitive mode in its input layout.
1667 * Declaration vertex spacing, ordering, and point mode identifiers is
1668 * optional. It is not required that all tessellation evaluation
1669 * shaders in a program declare a primitive mode. If spacing or
1670 * vertex ordering declarations are omitted, the tessellation
1671 * primitive generator will use equal spacing or counter-clockwise
1672 * vertex ordering, respectively. If a point mode declaration is
1673 * omitted, the tessellation primitive generator will produce lines or
1674 * triangles according to the primitive mode."
1675 */
1676
1677 for (unsigned i = 0; i < num_shaders; i++) {
1678 struct gl_shader *shader = shader_list[i];
1679
1680 if (shader->TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1681 if (linked_shader->TessEval.PrimitiveMode != PRIM_UNKNOWN &&
1682 linked_shader->TessEval.PrimitiveMode != shader->TessEval.PrimitiveMode) {
1683 linker_error(prog, "tessellation evaluation shader defined with "
1684 "conflicting input primitive modes.\n");
1685 return;
1686 }
1687 linked_shader->TessEval.PrimitiveMode = shader->TessEval.PrimitiveMode;
1688 }
1689
1690 if (shader->TessEval.Spacing != 0) {
1691 if (linked_shader->TessEval.Spacing != 0 &&
1692 linked_shader->TessEval.Spacing != shader->TessEval.Spacing) {
1693 linker_error(prog, "tessellation evaluation shader defined with "
1694 "conflicting vertex spacing.\n");
1695 return;
1696 }
1697 linked_shader->TessEval.Spacing = shader->TessEval.Spacing;
1698 }
1699
1700 if (shader->TessEval.VertexOrder != 0) {
1701 if (linked_shader->TessEval.VertexOrder != 0 &&
1702 linked_shader->TessEval.VertexOrder != shader->TessEval.VertexOrder) {
1703 linker_error(prog, "tessellation evaluation shader defined with "
1704 "conflicting ordering.\n");
1705 return;
1706 }
1707 linked_shader->TessEval.VertexOrder = shader->TessEval.VertexOrder;
1708 }
1709
1710 if (shader->TessEval.PointMode != -1) {
1711 if (linked_shader->TessEval.PointMode != -1 &&
1712 linked_shader->TessEval.PointMode != shader->TessEval.PointMode) {
1713 linker_error(prog, "tessellation evaluation shader defined with "
1714 "conflicting point modes.\n");
1715 return;
1716 }
1717 linked_shader->TessEval.PointMode = shader->TessEval.PointMode;
1718 }
1719
1720 }
1721
1722 /* Just do the intrastage -> interstage propagation right now,
1723 * since we already know we're in the right type of shader program
1724 * for doing it.
1725 */
1726 if (linked_shader->TessEval.PrimitiveMode == PRIM_UNKNOWN) {
1727 linker_error(prog,
1728 "tessellation evaluation shader didn't declare input "
1729 "primitive modes.\n");
1730 return;
1731 }
1732 prog->TessEval.PrimitiveMode = linked_shader->TessEval.PrimitiveMode;
1733
1734 if (linked_shader->TessEval.Spacing == 0)
1735 linked_shader->TessEval.Spacing = GL_EQUAL;
1736 prog->TessEval.Spacing = linked_shader->TessEval.Spacing;
1737
1738 if (linked_shader->TessEval.VertexOrder == 0)
1739 linked_shader->TessEval.VertexOrder = GL_CCW;
1740 prog->TessEval.VertexOrder = linked_shader->TessEval.VertexOrder;
1741
1742 if (linked_shader->TessEval.PointMode == -1)
1743 linked_shader->TessEval.PointMode = GL_FALSE;
1744 prog->TessEval.PointMode = linked_shader->TessEval.PointMode;
1745 }
1746
1747
1748 /**
1749 * Performs the cross-validation of layout qualifiers specified in
1750 * redeclaration of gl_FragCoord for the attached fragment shaders,
1751 * and propagates them to the linked FS and linked shader program.
1752 */
1753 static void
1754 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1755 struct gl_shader *linked_shader,
1756 struct gl_shader **shader_list,
1757 unsigned num_shaders)
1758 {
1759 linked_shader->redeclares_gl_fragcoord = false;
1760 linked_shader->uses_gl_fragcoord = false;
1761 linked_shader->origin_upper_left = false;
1762 linked_shader->pixel_center_integer = false;
1763
1764 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1765 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1766 return;
1767
1768 for (unsigned i = 0; i < num_shaders; i++) {
1769 struct gl_shader *shader = shader_list[i];
1770 /* From the GLSL 1.50 spec, page 39:
1771 *
1772 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1773 * it must be redeclared in all the fragment shaders in that program
1774 * that have a static use gl_FragCoord."
1775 */
1776 if ((linked_shader->redeclares_gl_fragcoord
1777 && !shader->redeclares_gl_fragcoord
1778 && shader->uses_gl_fragcoord)
1779 || (shader->redeclares_gl_fragcoord
1780 && !linked_shader->redeclares_gl_fragcoord
1781 && linked_shader->uses_gl_fragcoord)) {
1782 linker_error(prog, "fragment shader defined with conflicting "
1783 "layout qualifiers for gl_FragCoord\n");
1784 }
1785
1786 /* From the GLSL 1.50 spec, page 39:
1787 *
1788 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1789 * single program must have the same set of qualifiers."
1790 */
1791 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1792 && (shader->origin_upper_left != linked_shader->origin_upper_left
1793 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1794 linker_error(prog, "fragment shader defined with conflicting "
1795 "layout qualifiers for gl_FragCoord\n");
1796 }
1797
1798 /* Update the linked shader state. Note that uses_gl_fragcoord should
1799 * accumulate the results. The other values should replace. If there
1800 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1801 * are already known to be the same.
1802 */
1803 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1804 linked_shader->redeclares_gl_fragcoord =
1805 shader->redeclares_gl_fragcoord;
1806 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1807 || shader->uses_gl_fragcoord;
1808 linked_shader->origin_upper_left = shader->origin_upper_left;
1809 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1810 }
1811
1812 linked_shader->EarlyFragmentTests |= shader->EarlyFragmentTests;
1813 }
1814 }
1815
1816 /**
1817 * Performs the cross-validation of geometry shader max_vertices and
1818 * primitive type layout qualifiers for the attached geometry shaders,
1819 * and propagates them to the linked GS and linked shader program.
1820 */
1821 static void
1822 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1823 struct gl_shader *linked_shader,
1824 struct gl_shader **shader_list,
1825 unsigned num_shaders)
1826 {
1827 linked_shader->Geom.VerticesOut = 0;
1828 linked_shader->Geom.Invocations = 0;
1829 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1830 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1831
1832 /* No in/out qualifiers defined for anything but GLSL 1.50+
1833 * geometry shaders so far.
1834 */
1835 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1836 return;
1837
1838 /* From the GLSL 1.50 spec, page 46:
1839 *
1840 * "All geometry shader output layout declarations in a program
1841 * must declare the same layout and same value for
1842 * max_vertices. There must be at least one geometry output
1843 * layout declaration somewhere in a program, but not all
1844 * geometry shaders (compilation units) are required to
1845 * declare it."
1846 */
1847
1848 for (unsigned i = 0; i < num_shaders; i++) {
1849 struct gl_shader *shader = shader_list[i];
1850
1851 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1852 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1853 linked_shader->Geom.InputType != shader->Geom.InputType) {
1854 linker_error(prog, "geometry shader defined with conflicting "
1855 "input types\n");
1856 return;
1857 }
1858 linked_shader->Geom.InputType = shader->Geom.InputType;
1859 }
1860
1861 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1862 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1863 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1864 linker_error(prog, "geometry shader defined with conflicting "
1865 "output types\n");
1866 return;
1867 }
1868 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1869 }
1870
1871 if (shader->Geom.VerticesOut != 0) {
1872 if (linked_shader->Geom.VerticesOut != 0 &&
1873 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1874 linker_error(prog, "geometry shader defined with conflicting "
1875 "output vertex count (%d and %d)\n",
1876 linked_shader->Geom.VerticesOut,
1877 shader->Geom.VerticesOut);
1878 return;
1879 }
1880 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1881 }
1882
1883 if (shader->Geom.Invocations != 0) {
1884 if (linked_shader->Geom.Invocations != 0 &&
1885 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1886 linker_error(prog, "geometry shader defined with conflicting "
1887 "invocation count (%d and %d)\n",
1888 linked_shader->Geom.Invocations,
1889 shader->Geom.Invocations);
1890 return;
1891 }
1892 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1893 }
1894 }
1895
1896 /* Just do the intrastage -> interstage propagation right now,
1897 * since we already know we're in the right type of shader program
1898 * for doing it.
1899 */
1900 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1901 linker_error(prog,
1902 "geometry shader didn't declare primitive input type\n");
1903 return;
1904 }
1905 prog->Geom.InputType = linked_shader->Geom.InputType;
1906
1907 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1908 linker_error(prog,
1909 "geometry shader didn't declare primitive output type\n");
1910 return;
1911 }
1912 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1913
1914 if (linked_shader->Geom.VerticesOut == 0) {
1915 linker_error(prog,
1916 "geometry shader didn't declare max_vertices\n");
1917 return;
1918 }
1919 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1920
1921 if (linked_shader->Geom.Invocations == 0)
1922 linked_shader->Geom.Invocations = 1;
1923
1924 prog->Geom.Invocations = linked_shader->Geom.Invocations;
1925 }
1926
1927
1928 /**
1929 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1930 * qualifiers for the attached compute shaders, and propagate them to the
1931 * linked CS and linked shader program.
1932 */
1933 static void
1934 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1935 struct gl_shader *linked_shader,
1936 struct gl_shader **shader_list,
1937 unsigned num_shaders)
1938 {
1939 for (int i = 0; i < 3; i++)
1940 linked_shader->Comp.LocalSize[i] = 0;
1941
1942 /* This function is called for all shader stages, but it only has an effect
1943 * for compute shaders.
1944 */
1945 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1946 return;
1947
1948 /* From the ARB_compute_shader spec, in the section describing local size
1949 * declarations:
1950 *
1951 * If multiple compute shaders attached to a single program object
1952 * declare local work-group size, the declarations must be identical;
1953 * otherwise a link-time error results. Furthermore, if a program
1954 * object contains any compute shaders, at least one must contain an
1955 * input layout qualifier specifying the local work sizes of the
1956 * program, or a link-time error will occur.
1957 */
1958 for (unsigned sh = 0; sh < num_shaders; sh++) {
1959 struct gl_shader *shader = shader_list[sh];
1960
1961 if (shader->Comp.LocalSize[0] != 0) {
1962 if (linked_shader->Comp.LocalSize[0] != 0) {
1963 for (int i = 0; i < 3; i++) {
1964 if (linked_shader->Comp.LocalSize[i] !=
1965 shader->Comp.LocalSize[i]) {
1966 linker_error(prog, "compute shader defined with conflicting "
1967 "local sizes\n");
1968 return;
1969 }
1970 }
1971 }
1972 for (int i = 0; i < 3; i++)
1973 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1974 }
1975 }
1976
1977 /* Just do the intrastage -> interstage propagation right now,
1978 * since we already know we're in the right type of shader program
1979 * for doing it.
1980 */
1981 if (linked_shader->Comp.LocalSize[0] == 0) {
1982 linker_error(prog, "compute shader didn't declare local size\n");
1983 return;
1984 }
1985 for (int i = 0; i < 3; i++)
1986 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1987 }
1988
1989
1990 /**
1991 * Combine a group of shaders for a single stage to generate a linked shader
1992 *
1993 * \note
1994 * If this function is supplied a single shader, it is cloned, and the new
1995 * shader is returned.
1996 */
1997 static struct gl_shader *
1998 link_intrastage_shaders(void *mem_ctx,
1999 struct gl_context *ctx,
2000 struct gl_shader_program *prog,
2001 struct gl_shader **shader_list,
2002 unsigned num_shaders)
2003 {
2004 struct gl_uniform_block *uniform_blocks = NULL;
2005
2006 /* Check that global variables defined in multiple shaders are consistent.
2007 */
2008 cross_validate_globals(prog, shader_list, num_shaders, false);
2009 if (!prog->LinkStatus)
2010 return NULL;
2011
2012 /* Check that interface blocks defined in multiple shaders are consistent.
2013 */
2014 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2015 num_shaders);
2016 if (!prog->LinkStatus)
2017 return NULL;
2018
2019 /* Link up uniform blocks defined within this stage. */
2020 const unsigned num_uniform_blocks =
2021 link_uniform_blocks(mem_ctx, ctx, prog, shader_list, num_shaders,
2022 &uniform_blocks);
2023 if (!prog->LinkStatus)
2024 return NULL;
2025
2026 /* Check that there is only a single definition of each function signature
2027 * across all shaders.
2028 */
2029 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2030 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2031 ir_function *const f = node->as_function();
2032
2033 if (f == NULL)
2034 continue;
2035
2036 for (unsigned j = i + 1; j < num_shaders; j++) {
2037 ir_function *const other =
2038 shader_list[j]->symbols->get_function(f->name);
2039
2040 /* If the other shader has no function (and therefore no function
2041 * signatures) with the same name, skip to the next shader.
2042 */
2043 if (other == NULL)
2044 continue;
2045
2046 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2047 if (!sig->is_defined || sig->is_builtin())
2048 continue;
2049
2050 ir_function_signature *other_sig =
2051 other->exact_matching_signature(NULL, &sig->parameters);
2052
2053 if ((other_sig != NULL) && other_sig->is_defined
2054 && !other_sig->is_builtin()) {
2055 linker_error(prog, "function `%s' is multiply defined\n",
2056 f->name);
2057 return NULL;
2058 }
2059 }
2060 }
2061 }
2062 }
2063
2064 /* Find the shader that defines main, and make a clone of it.
2065 *
2066 * Starting with the clone, search for undefined references. If one is
2067 * found, find the shader that defines it. Clone the reference and add
2068 * it to the shader. Repeat until there are no undefined references or
2069 * until a reference cannot be resolved.
2070 */
2071 gl_shader *main = NULL;
2072 for (unsigned i = 0; i < num_shaders; i++) {
2073 if (_mesa_get_main_function_signature(shader_list[i]) != NULL) {
2074 main = shader_list[i];
2075 break;
2076 }
2077 }
2078
2079 if (main == NULL) {
2080 linker_error(prog, "%s shader lacks `main'\n",
2081 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2082 return NULL;
2083 }
2084
2085 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
2086 linked->ir = new(linked) exec_list;
2087 clone_ir_list(mem_ctx, linked->ir, main->ir);
2088
2089 linked->BufferInterfaceBlocks =
2090 ralloc_array(linked, gl_uniform_block *, num_uniform_blocks);
2091
2092 ralloc_steal(linked, uniform_blocks);
2093 for (unsigned i = 0; i < num_uniform_blocks; i++) {
2094 linked->BufferInterfaceBlocks[i] = &uniform_blocks[i];
2095 }
2096
2097 linked->NumBufferInterfaceBlocks = num_uniform_blocks;
2098
2099 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2100 link_tcs_out_layout_qualifiers(prog, linked, shader_list, num_shaders);
2101 link_tes_in_layout_qualifiers(prog, linked, shader_list, num_shaders);
2102 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2103 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2104
2105 populate_symbol_table(linked);
2106
2107 /* The pointer to the main function in the final linked shader (i.e., the
2108 * copy of the original shader that contained the main function).
2109 */
2110 ir_function_signature *const main_sig =
2111 _mesa_get_main_function_signature(linked);
2112
2113 /* Move any instructions other than variable declarations or function
2114 * declarations into main.
2115 */
2116 exec_node *insertion_point =
2117 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2118 linked);
2119
2120 for (unsigned i = 0; i < num_shaders; i++) {
2121 if (shader_list[i] == main)
2122 continue;
2123
2124 insertion_point = move_non_declarations(shader_list[i]->ir,
2125 insertion_point, true, linked);
2126 }
2127
2128 /* Check if any shader needs built-in functions. */
2129 bool need_builtins = false;
2130 for (unsigned i = 0; i < num_shaders; i++) {
2131 if (shader_list[i]->uses_builtin_functions) {
2132 need_builtins = true;
2133 break;
2134 }
2135 }
2136
2137 bool ok;
2138 if (need_builtins) {
2139 /* Make a temporary array one larger than shader_list, which will hold
2140 * the built-in function shader as well.
2141 */
2142 gl_shader **linking_shaders = (gl_shader **)
2143 calloc(num_shaders + 1, sizeof(gl_shader *));
2144
2145 ok = linking_shaders != NULL;
2146
2147 if (ok) {
2148 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
2149 _mesa_glsl_initialize_builtin_functions();
2150 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
2151
2152 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
2153
2154 free(linking_shaders);
2155 } else {
2156 _mesa_error_no_memory(__func__);
2157 }
2158 } else {
2159 ok = link_function_calls(prog, linked, shader_list, num_shaders);
2160 }
2161
2162
2163 if (!ok) {
2164 _mesa_delete_shader(ctx, linked);
2165 return NULL;
2166 }
2167
2168 /* At this point linked should contain all of the linked IR, so
2169 * validate it to make sure nothing went wrong.
2170 */
2171 validate_ir_tree(linked->ir);
2172
2173 /* Set the size of geometry shader input arrays */
2174 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2175 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
2176 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
2177 foreach_in_list(ir_instruction, ir, linked->ir) {
2178 ir->accept(&input_resize_visitor);
2179 }
2180 }
2181
2182 if (ctx->Const.VertexID_is_zero_based)
2183 lower_vertex_id(linked);
2184
2185 /* Validate correct usage of barrier() in the tess control shader */
2186 if (linked->Stage == MESA_SHADER_TESS_CTRL) {
2187 barrier_use_visitor visitor(prog);
2188 foreach_in_list(ir_instruction, ir, linked->ir) {
2189 ir->accept(&visitor);
2190 }
2191 }
2192
2193 /* Make a pass over all variable declarations to ensure that arrays with
2194 * unspecified sizes have a size specified. The size is inferred from the
2195 * max_array_access field.
2196 */
2197 array_sizing_visitor v;
2198 v.run(linked->ir);
2199 v.fixup_unnamed_interface_types();
2200
2201 return linked;
2202 }
2203
2204 /**
2205 * Update the sizes of linked shader uniform arrays to the maximum
2206 * array index used.
2207 *
2208 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2209 *
2210 * If one or more elements of an array are active,
2211 * GetActiveUniform will return the name of the array in name,
2212 * subject to the restrictions listed above. The type of the array
2213 * is returned in type. The size parameter contains the highest
2214 * array element index used, plus one. The compiler or linker
2215 * determines the highest index used. There will be only one
2216 * active uniform reported by the GL per uniform array.
2217
2218 */
2219 static void
2220 update_array_sizes(struct gl_shader_program *prog)
2221 {
2222 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2223 if (prog->_LinkedShaders[i] == NULL)
2224 continue;
2225
2226 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2227 ir_variable *const var = node->as_variable();
2228
2229 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2230 !var->type->is_array())
2231 continue;
2232
2233 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2234 * will not be eliminated. Since we always do std140, just
2235 * don't resize arrays in UBOs.
2236 *
2237 * Atomic counters are supposed to get deterministic
2238 * locations assigned based on the declaration ordering and
2239 * sizes, array compaction would mess that up.
2240 *
2241 * Subroutine uniforms are not removed.
2242 */
2243 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2244 var->type->contains_subroutine())
2245 continue;
2246
2247 unsigned int size = var->data.max_array_access;
2248 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2249 if (prog->_LinkedShaders[j] == NULL)
2250 continue;
2251
2252 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2253 ir_variable *other_var = node2->as_variable();
2254 if (!other_var)
2255 continue;
2256
2257 if (strcmp(var->name, other_var->name) == 0 &&
2258 other_var->data.max_array_access > size) {
2259 size = other_var->data.max_array_access;
2260 }
2261 }
2262 }
2263
2264 if (size + 1 != var->type->length) {
2265 /* If this is a built-in uniform (i.e., it's backed by some
2266 * fixed-function state), adjust the number of state slots to
2267 * match the new array size. The number of slots per array entry
2268 * is not known. It seems safe to assume that the total number of
2269 * slots is an integer multiple of the number of array elements.
2270 * Determine the number of slots per array element by dividing by
2271 * the old (total) size.
2272 */
2273 const unsigned num_slots = var->get_num_state_slots();
2274 if (num_slots > 0) {
2275 var->set_num_state_slots((size + 1)
2276 * (num_slots / var->type->length));
2277 }
2278
2279 var->type = glsl_type::get_array_instance(var->type->fields.array,
2280 size + 1);
2281 /* FINISHME: We should update the types of array
2282 * dereferences of this variable now.
2283 */
2284 }
2285 }
2286 }
2287 }
2288
2289 /**
2290 * Resize tessellation evaluation per-vertex inputs to the size of
2291 * tessellation control per-vertex outputs.
2292 */
2293 static void
2294 resize_tes_inputs(struct gl_context *ctx,
2295 struct gl_shader_program *prog)
2296 {
2297 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2298 return;
2299
2300 gl_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2301 gl_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2302
2303 /* If no control shader is present, then the TES inputs are statically
2304 * sized to MaxPatchVertices; the actual size of the arrays won't be
2305 * known until draw time.
2306 */
2307 const int num_vertices = tcs
2308 ? tcs->TessCtrl.VerticesOut
2309 : ctx->Const.MaxPatchVertices;
2310
2311 tess_eval_array_resize_visitor input_resize_visitor(num_vertices, prog);
2312 foreach_in_list(ir_instruction, ir, tes->ir) {
2313 ir->accept(&input_resize_visitor);
2314 }
2315
2316 if (tcs) {
2317 /* Convert the gl_PatchVerticesIn system value into a constant, since
2318 * the value is known at this point.
2319 */
2320 foreach_in_list(ir_instruction, ir, tes->ir) {
2321 ir_variable *var = ir->as_variable();
2322 if (var && var->data.mode == ir_var_system_value &&
2323 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2324 void *mem_ctx = ralloc_parent(var);
2325 var->data.mode = ir_var_auto;
2326 var->data.location = 0;
2327 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2328 }
2329 }
2330 }
2331 }
2332
2333 /**
2334 * Find a contiguous set of available bits in a bitmask.
2335 *
2336 * \param used_mask Bits representing used (1) and unused (0) locations
2337 * \param needed_count Number of contiguous bits needed.
2338 *
2339 * \return
2340 * Base location of the available bits on success or -1 on failure.
2341 */
2342 int
2343 find_available_slots(unsigned used_mask, unsigned needed_count)
2344 {
2345 unsigned needed_mask = (1 << needed_count) - 1;
2346 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2347
2348 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2349 * cannot optimize possibly infinite loops" for the loop below.
2350 */
2351 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2352 return -1;
2353
2354 for (int i = 0; i <= max_bit_to_test; i++) {
2355 if ((needed_mask & ~used_mask) == needed_mask)
2356 return i;
2357
2358 needed_mask <<= 1;
2359 }
2360
2361 return -1;
2362 }
2363
2364
2365 /**
2366 * Assign locations for either VS inputs or FS outputs
2367 *
2368 * \param prog Shader program whose variables need locations assigned
2369 * \param constants Driver specific constant values for the program.
2370 * \param target_index Selector for the program target to receive location
2371 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2372 * \c MESA_SHADER_FRAGMENT.
2373 *
2374 * \return
2375 * If locations are successfully assigned, true is returned. Otherwise an
2376 * error is emitted to the shader link log and false is returned.
2377 */
2378 bool
2379 assign_attribute_or_color_locations(gl_shader_program *prog,
2380 struct gl_constants *constants,
2381 unsigned target_index)
2382 {
2383 /* Maximum number of generic locations. This corresponds to either the
2384 * maximum number of draw buffers or the maximum number of generic
2385 * attributes.
2386 */
2387 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2388 constants->Program[target_index].MaxAttribs :
2389 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2390
2391 /* Mark invalid locations as being used.
2392 */
2393 unsigned used_locations = (max_index >= 32)
2394 ? ~0 : ~((1 << max_index) - 1);
2395 unsigned double_storage_locations = 0;
2396
2397 assert((target_index == MESA_SHADER_VERTEX)
2398 || (target_index == MESA_SHADER_FRAGMENT));
2399
2400 gl_shader *const sh = prog->_LinkedShaders[target_index];
2401 if (sh == NULL)
2402 return true;
2403
2404 /* Operate in a total of four passes.
2405 *
2406 * 1. Invalidate the location assignments for all vertex shader inputs.
2407 *
2408 * 2. Assign locations for inputs that have user-defined (via
2409 * glBindVertexAttribLocation) locations and outputs that have
2410 * user-defined locations (via glBindFragDataLocation).
2411 *
2412 * 3. Sort the attributes without assigned locations by number of slots
2413 * required in decreasing order. Fragmentation caused by attribute
2414 * locations assigned by the application may prevent large attributes
2415 * from having enough contiguous space.
2416 *
2417 * 4. Assign locations to any inputs without assigned locations.
2418 */
2419
2420 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2421 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2422
2423 const enum ir_variable_mode direction =
2424 (target_index == MESA_SHADER_VERTEX)
2425 ? ir_var_shader_in : ir_var_shader_out;
2426
2427
2428 /* Temporary storage for the set of attributes that need locations assigned.
2429 */
2430 struct temp_attr {
2431 unsigned slots;
2432 ir_variable *var;
2433
2434 /* Used below in the call to qsort. */
2435 static int compare(const void *a, const void *b)
2436 {
2437 const temp_attr *const l = (const temp_attr *) a;
2438 const temp_attr *const r = (const temp_attr *) b;
2439
2440 /* Reversed because we want a descending order sort below. */
2441 return r->slots - l->slots;
2442 }
2443 } to_assign[32];
2444 assert(max_index <= 32);
2445
2446 unsigned num_attr = 0;
2447
2448 foreach_in_list(ir_instruction, node, sh->ir) {
2449 ir_variable *const var = node->as_variable();
2450
2451 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2452 continue;
2453
2454 if (var->data.explicit_location) {
2455 var->data.is_unmatched_generic_inout = 0;
2456 if ((var->data.location >= (int)(max_index + generic_base))
2457 || (var->data.location < 0)) {
2458 linker_error(prog,
2459 "invalid explicit location %d specified for `%s'\n",
2460 (var->data.location < 0)
2461 ? var->data.location
2462 : var->data.location - generic_base,
2463 var->name);
2464 return false;
2465 }
2466 } else if (target_index == MESA_SHADER_VERTEX) {
2467 unsigned binding;
2468
2469 if (prog->AttributeBindings->get(binding, var->name)) {
2470 assert(binding >= VERT_ATTRIB_GENERIC0);
2471 var->data.location = binding;
2472 var->data.is_unmatched_generic_inout = 0;
2473 }
2474 } else if (target_index == MESA_SHADER_FRAGMENT) {
2475 unsigned binding;
2476 unsigned index;
2477
2478 if (prog->FragDataBindings->get(binding, var->name)) {
2479 assert(binding >= FRAG_RESULT_DATA0);
2480 var->data.location = binding;
2481 var->data.is_unmatched_generic_inout = 0;
2482
2483 if (prog->FragDataIndexBindings->get(index, var->name)) {
2484 var->data.index = index;
2485 }
2486 }
2487 }
2488
2489 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2490 *
2491 * "Output binding assignments will cause LinkProgram to fail:
2492 * ...
2493 * If the program has an active output assigned to a location greater
2494 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2495 * an active output assigned an index greater than or equal to one;"
2496 */
2497 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2498 var->data.location - generic_base >=
2499 (int) constants->MaxDualSourceDrawBuffers) {
2500 linker_error(prog,
2501 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2502 "with index %u for %s\n",
2503 var->data.location - generic_base, var->data.index,
2504 var->name);
2505 return false;
2506 }
2507
2508 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX ? true : false);
2509
2510 /* If the variable is not a built-in and has a location statically
2511 * assigned in the shader (presumably via a layout qualifier), make sure
2512 * that it doesn't collide with other assigned locations. Otherwise,
2513 * add it to the list of variables that need linker-assigned locations.
2514 */
2515 if (var->data.location != -1) {
2516 if (var->data.location >= generic_base && var->data.index < 1) {
2517 /* From page 61 of the OpenGL 4.0 spec:
2518 *
2519 * "LinkProgram will fail if the attribute bindings assigned
2520 * by BindAttribLocation do not leave not enough space to
2521 * assign a location for an active matrix attribute or an
2522 * active attribute array, both of which require multiple
2523 * contiguous generic attributes."
2524 *
2525 * I think above text prohibits the aliasing of explicit and
2526 * automatic assignments. But, aliasing is allowed in manual
2527 * assignments of attribute locations. See below comments for
2528 * the details.
2529 *
2530 * From OpenGL 4.0 spec, page 61:
2531 *
2532 * "It is possible for an application to bind more than one
2533 * attribute name to the same location. This is referred to as
2534 * aliasing. This will only work if only one of the aliased
2535 * attributes is active in the executable program, or if no
2536 * path through the shader consumes more than one attribute of
2537 * a set of attributes aliased to the same location. A link
2538 * error can occur if the linker determines that every path
2539 * through the shader consumes multiple aliased attributes,
2540 * but implementations are not required to generate an error
2541 * in this case."
2542 *
2543 * From GLSL 4.30 spec, page 54:
2544 *
2545 * "A program will fail to link if any two non-vertex shader
2546 * input variables are assigned to the same location. For
2547 * vertex shaders, multiple input variables may be assigned
2548 * to the same location using either layout qualifiers or via
2549 * the OpenGL API. However, such aliasing is intended only to
2550 * support vertex shaders where each execution path accesses
2551 * at most one input per each location. Implementations are
2552 * permitted, but not required, to generate link-time errors
2553 * if they detect that every path through the vertex shader
2554 * executable accesses multiple inputs assigned to any single
2555 * location. For all shader types, a program will fail to link
2556 * if explicit location assignments leave the linker unable
2557 * to find space for other variables without explicit
2558 * assignments."
2559 *
2560 * From OpenGL ES 3.0 spec, page 56:
2561 *
2562 * "Binding more than one attribute name to the same location
2563 * is referred to as aliasing, and is not permitted in OpenGL
2564 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2565 * fail when this condition exists. However, aliasing is
2566 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2567 * This will only work if only one of the aliased attributes
2568 * is active in the executable program, or if no path through
2569 * the shader consumes more than one attribute of a set of
2570 * attributes aliased to the same location. A link error can
2571 * occur if the linker determines that every path through the
2572 * shader consumes multiple aliased attributes, but implemen-
2573 * tations are not required to generate an error in this case."
2574 *
2575 * After looking at above references from OpenGL, OpenGL ES and
2576 * GLSL specifications, we allow aliasing of vertex input variables
2577 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2578 *
2579 * NOTE: This is not required by the spec but its worth mentioning
2580 * here that we're not doing anything to make sure that no path
2581 * through the vertex shader executable accesses multiple inputs
2582 * assigned to any single location.
2583 */
2584
2585 /* Mask representing the contiguous slots that will be used by
2586 * this attribute.
2587 */
2588 const unsigned attr = var->data.location - generic_base;
2589 const unsigned use_mask = (1 << slots) - 1;
2590 const char *const string = (target_index == MESA_SHADER_VERTEX)
2591 ? "vertex shader input" : "fragment shader output";
2592
2593 /* Generate a link error if the requested locations for this
2594 * attribute exceed the maximum allowed attribute location.
2595 */
2596 if (attr + slots > max_index) {
2597 linker_error(prog,
2598 "insufficient contiguous locations "
2599 "available for %s `%s' %d %d %d\n", string,
2600 var->name, used_locations, use_mask, attr);
2601 return false;
2602 }
2603
2604 /* Generate a link error if the set of bits requested for this
2605 * attribute overlaps any previously allocated bits.
2606 */
2607 if ((~(use_mask << attr) & used_locations) != used_locations) {
2608 if (target_index == MESA_SHADER_FRAGMENT ||
2609 (prog->IsES && prog->Version >= 300)) {
2610 linker_error(prog,
2611 "overlapping location is assigned "
2612 "to %s `%s' %d %d %d\n", string,
2613 var->name, used_locations, use_mask, attr);
2614 return false;
2615 } else {
2616 linker_warning(prog,
2617 "overlapping location is assigned "
2618 "to %s `%s' %d %d %d\n", string,
2619 var->name, used_locations, use_mask, attr);
2620 }
2621 }
2622
2623 used_locations |= (use_mask << attr);
2624
2625 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2626 *
2627 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2628 * active attribute variables may fail to link, unless
2629 * device-dependent optimizations are able to make the program
2630 * fit within available hardware resources. For the purposes
2631 * of this test, attribute variables of the type dvec3, dvec4,
2632 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2633 * count as consuming twice as many attributes as equivalent
2634 * single-precision types. While these types use the same number
2635 * of generic attributes as their single-precision equivalents,
2636 * implementations are permitted to consume two single-precision
2637 * vectors of internal storage for each three- or four-component
2638 * double-precision vector."
2639 *
2640 * Mark this attribute slot as taking up twice as much space
2641 * so we can count it properly against limits. According to
2642 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2643 * is optional behavior, but it seems preferable.
2644 */
2645 if (var->type->without_array()->is_dual_slot_double())
2646 double_storage_locations |= (use_mask << attr);
2647 }
2648
2649 continue;
2650 }
2651
2652 if (num_attr >= max_index) {
2653 linker_error(prog, "too many %s (max %u)",
2654 target_index == MESA_SHADER_VERTEX ?
2655 "vertex shader inputs" : "fragment shader outputs",
2656 max_index);
2657 return false;
2658 }
2659 to_assign[num_attr].slots = slots;
2660 to_assign[num_attr].var = var;
2661 num_attr++;
2662 }
2663
2664 if (target_index == MESA_SHADER_VERTEX) {
2665 unsigned total_attribs_size =
2666 _mesa_bitcount(used_locations & ((1 << max_index) - 1)) +
2667 _mesa_bitcount(double_storage_locations);
2668 if (total_attribs_size > max_index) {
2669 linker_error(prog,
2670 "attempt to use %d vertex attribute slots only %d available ",
2671 total_attribs_size, max_index);
2672 return false;
2673 }
2674 }
2675
2676 /* If all of the attributes were assigned locations by the application (or
2677 * are built-in attributes with fixed locations), return early. This should
2678 * be the common case.
2679 */
2680 if (num_attr == 0)
2681 return true;
2682
2683 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2684
2685 if (target_index == MESA_SHADER_VERTEX) {
2686 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2687 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2688 * reserved to prevent it from being automatically allocated below.
2689 */
2690 find_deref_visitor find("gl_Vertex");
2691 find.run(sh->ir);
2692 if (find.variable_found())
2693 used_locations |= (1 << 0);
2694 }
2695
2696 for (unsigned i = 0; i < num_attr; i++) {
2697 /* Mask representing the contiguous slots that will be used by this
2698 * attribute.
2699 */
2700 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2701
2702 int location = find_available_slots(used_locations, to_assign[i].slots);
2703
2704 if (location < 0) {
2705 const char *const string = (target_index == MESA_SHADER_VERTEX)
2706 ? "vertex shader input" : "fragment shader output";
2707
2708 linker_error(prog,
2709 "insufficient contiguous locations "
2710 "available for %s `%s'\n",
2711 string, to_assign[i].var->name);
2712 return false;
2713 }
2714
2715 to_assign[i].var->data.location = generic_base + location;
2716 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2717 used_locations |= (use_mask << location);
2718 }
2719
2720 return true;
2721 }
2722
2723 /**
2724 * Match explicit locations of outputs to inputs and deactivate the
2725 * unmatch flag if found so we don't optimise them away.
2726 */
2727 static void
2728 match_explicit_outputs_to_inputs(struct gl_shader_program *prog,
2729 gl_shader *producer,
2730 gl_shader *consumer)
2731 {
2732 glsl_symbol_table parameters;
2733 ir_variable *explicit_locations[MAX_VARYING] = { NULL };
2734
2735 /* Find all shader outputs in the "producer" stage.
2736 */
2737 foreach_in_list(ir_instruction, node, producer->ir) {
2738 ir_variable *const var = node->as_variable();
2739
2740 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
2741 continue;
2742
2743 if (var->data.explicit_location &&
2744 var->data.location >= VARYING_SLOT_VAR0) {
2745 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
2746 if (explicit_locations[idx] == NULL)
2747 explicit_locations[idx] = var;
2748 }
2749 }
2750
2751 /* Match inputs to outputs */
2752 foreach_in_list(ir_instruction, node, consumer->ir) {
2753 ir_variable *const input = node->as_variable();
2754
2755 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
2756 continue;
2757
2758 ir_variable *output = NULL;
2759 if (input->data.explicit_location
2760 && input->data.location >= VARYING_SLOT_VAR0) {
2761 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0];
2762
2763 if (output != NULL){
2764 input->data.is_unmatched_generic_inout = 0;
2765 output->data.is_unmatched_generic_inout = 0;
2766 }
2767 }
2768 }
2769 }
2770
2771 /**
2772 * Store the gl_FragDepth layout in the gl_shader_program struct.
2773 */
2774 static void
2775 store_fragdepth_layout(struct gl_shader_program *prog)
2776 {
2777 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2778 return;
2779 }
2780
2781 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2782
2783 /* We don't look up the gl_FragDepth symbol directly because if
2784 * gl_FragDepth is not used in the shader, it's removed from the IR.
2785 * However, the symbol won't be removed from the symbol table.
2786 *
2787 * We're only interested in the cases where the variable is NOT removed
2788 * from the IR.
2789 */
2790 foreach_in_list(ir_instruction, node, ir) {
2791 ir_variable *const var = node->as_variable();
2792
2793 if (var == NULL || var->data.mode != ir_var_shader_out) {
2794 continue;
2795 }
2796
2797 if (strcmp(var->name, "gl_FragDepth") == 0) {
2798 switch (var->data.depth_layout) {
2799 case ir_depth_layout_none:
2800 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2801 return;
2802 case ir_depth_layout_any:
2803 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2804 return;
2805 case ir_depth_layout_greater:
2806 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2807 return;
2808 case ir_depth_layout_less:
2809 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2810 return;
2811 case ir_depth_layout_unchanged:
2812 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2813 return;
2814 default:
2815 assert(0);
2816 return;
2817 }
2818 }
2819 }
2820 }
2821
2822 /**
2823 * Validate the resources used by a program versus the implementation limits
2824 */
2825 static void
2826 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2827 {
2828 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2829 struct gl_shader *sh = prog->_LinkedShaders[i];
2830
2831 if (sh == NULL)
2832 continue;
2833
2834 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2835 linker_error(prog, "Too many %s shader texture samplers\n",
2836 _mesa_shader_stage_to_string(i));
2837 }
2838
2839 if (sh->num_uniform_components >
2840 ctx->Const.Program[i].MaxUniformComponents) {
2841 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2842 linker_warning(prog, "Too many %s shader default uniform block "
2843 "components, but the driver will try to optimize "
2844 "them out; this is non-portable out-of-spec "
2845 "behavior\n",
2846 _mesa_shader_stage_to_string(i));
2847 } else {
2848 linker_error(prog, "Too many %s shader default uniform block "
2849 "components\n",
2850 _mesa_shader_stage_to_string(i));
2851 }
2852 }
2853
2854 if (sh->num_combined_uniform_components >
2855 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2856 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2857 linker_warning(prog, "Too many %s shader uniform components, "
2858 "but the driver will try to optimize them out; "
2859 "this is non-portable out-of-spec behavior\n",
2860 _mesa_shader_stage_to_string(i));
2861 } else {
2862 linker_error(prog, "Too many %s shader uniform components\n",
2863 _mesa_shader_stage_to_string(i));
2864 }
2865 }
2866 }
2867
2868 unsigned blocks[MESA_SHADER_STAGES] = {0};
2869 unsigned total_uniform_blocks = 0;
2870 unsigned shader_blocks[MESA_SHADER_STAGES] = {0};
2871 unsigned total_shader_storage_blocks = 0;
2872
2873 for (unsigned i = 0; i < prog->NumBufferInterfaceBlocks; i++) {
2874 /* Don't check SSBOs for Uniform Block Size */
2875 if (!prog->BufferInterfaceBlocks[i].IsShaderStorage &&
2876 prog->BufferInterfaceBlocks[i].UniformBufferSize > ctx->Const.MaxUniformBlockSize) {
2877 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
2878 prog->BufferInterfaceBlocks[i].Name,
2879 prog->BufferInterfaceBlocks[i].UniformBufferSize,
2880 ctx->Const.MaxUniformBlockSize);
2881 }
2882
2883 if (prog->BufferInterfaceBlocks[i].IsShaderStorage &&
2884 prog->BufferInterfaceBlocks[i].UniformBufferSize > ctx->Const.MaxShaderStorageBlockSize) {
2885 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
2886 prog->BufferInterfaceBlocks[i].Name,
2887 prog->BufferInterfaceBlocks[i].UniformBufferSize,
2888 ctx->Const.MaxShaderStorageBlockSize);
2889 }
2890
2891 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2892 if (prog->InterfaceBlockStageIndex[j][i] != -1) {
2893 struct gl_shader *sh = prog->_LinkedShaders[j];
2894 int stage_index = prog->InterfaceBlockStageIndex[j][i];
2895 if (sh &&
2896 sh->BufferInterfaceBlocks[stage_index]->IsShaderStorage) {
2897 shader_blocks[j]++;
2898 total_shader_storage_blocks++;
2899 } else {
2900 blocks[j]++;
2901 total_uniform_blocks++;
2902 }
2903 }
2904 }
2905
2906 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2907 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
2908 total_uniform_blocks,
2909 ctx->Const.MaxCombinedUniformBlocks);
2910 } else {
2911 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2912 const unsigned max_uniform_blocks =
2913 ctx->Const.Program[i].MaxUniformBlocks;
2914 if (blocks[i] > max_uniform_blocks) {
2915 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2916 _mesa_shader_stage_to_string(i),
2917 blocks[i],
2918 max_uniform_blocks);
2919 break;
2920 }
2921 }
2922 }
2923
2924 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
2925 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
2926 total_shader_storage_blocks,
2927 ctx->Const.MaxCombinedShaderStorageBlocks);
2928 } else {
2929 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2930 const unsigned max_shader_storage_blocks =
2931 ctx->Const.Program[i].MaxShaderStorageBlocks;
2932 if (shader_blocks[i] > max_shader_storage_blocks) {
2933 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
2934 _mesa_shader_stage_to_string(i),
2935 shader_blocks[i],
2936 max_shader_storage_blocks);
2937 break;
2938 }
2939 }
2940 }
2941 }
2942 }
2943
2944 static void
2945 link_calculate_subroutine_compat(struct gl_shader_program *prog)
2946 {
2947 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2948 struct gl_shader *sh = prog->_LinkedShaders[i];
2949 int count;
2950 if (!sh)
2951 continue;
2952
2953 for (unsigned j = 0; j < sh->NumSubroutineUniformRemapTable; j++) {
2954 struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[j];
2955
2956 if (!uni)
2957 continue;
2958
2959 count = 0;
2960 for (unsigned f = 0; f < sh->NumSubroutineFunctions; f++) {
2961 struct gl_subroutine_function *fn = &sh->SubroutineFunctions[f];
2962 for (int k = 0; k < fn->num_compat_types; k++) {
2963 if (fn->types[k] == uni->type) {
2964 count++;
2965 break;
2966 }
2967 }
2968 }
2969 uni->num_compatible_subroutines = count;
2970 }
2971 }
2972 }
2973
2974 static void
2975 check_subroutine_resources(struct gl_shader_program *prog)
2976 {
2977 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2978 struct gl_shader *sh = prog->_LinkedShaders[i];
2979
2980 if (sh) {
2981 if (sh->NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS)
2982 linker_error(prog, "Too many %s shader subroutine uniforms\n",
2983 _mesa_shader_stage_to_string(i));
2984 }
2985 }
2986 }
2987 /**
2988 * Validate shader image resources.
2989 */
2990 static void
2991 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2992 {
2993 unsigned total_image_units = 0;
2994 unsigned fragment_outputs = 0;
2995 unsigned total_shader_storage_blocks = 0;
2996
2997 if (!ctx->Extensions.ARB_shader_image_load_store)
2998 return;
2999
3000 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3001 struct gl_shader *sh = prog->_LinkedShaders[i];
3002
3003 if (sh) {
3004 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
3005 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
3006 _mesa_shader_stage_to_string(i), sh->NumImages,
3007 ctx->Const.Program[i].MaxImageUniforms);
3008
3009 total_image_units += sh->NumImages;
3010
3011 for (unsigned j = 0; j < prog->NumBufferInterfaceBlocks; j++) {
3012 int stage_index = prog->InterfaceBlockStageIndex[i][j];
3013 if (stage_index != -1 &&
3014 sh->BufferInterfaceBlocks[stage_index]->IsShaderStorage)
3015 total_shader_storage_blocks++;
3016 }
3017
3018 if (i == MESA_SHADER_FRAGMENT) {
3019 foreach_in_list(ir_instruction, node, sh->ir) {
3020 ir_variable *var = node->as_variable();
3021 if (var && var->data.mode == ir_var_shader_out)
3022 /* since there are no double fs outputs - pass false */
3023 fragment_outputs += var->type->count_attribute_slots(false);
3024 }
3025 }
3026 }
3027 }
3028
3029 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3030 linker_error(prog, "Too many combined image uniforms\n");
3031
3032 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3033 ctx->Const.MaxCombinedShaderOutputResources)
3034 linker_error(prog, "Too many combined image uniforms, shader storage "
3035 " buffers and fragment outputs\n");
3036 }
3037
3038
3039 /**
3040 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3041 * for a variable, checks for overlaps between other uniforms using explicit
3042 * locations.
3043 */
3044 static int
3045 reserve_explicit_locations(struct gl_shader_program *prog,
3046 string_to_uint_map *map, ir_variable *var)
3047 {
3048 unsigned slots = var->type->uniform_locations();
3049 unsigned max_loc = var->data.location + slots - 1;
3050 unsigned return_value = slots;
3051
3052 /* Resize remap table if locations do not fit in the current one. */
3053 if (max_loc + 1 > prog->NumUniformRemapTable) {
3054 prog->UniformRemapTable =
3055 reralloc(prog, prog->UniformRemapTable,
3056 gl_uniform_storage *,
3057 max_loc + 1);
3058
3059 if (!prog->UniformRemapTable) {
3060 linker_error(prog, "Out of memory during linking.\n");
3061 return -1;
3062 }
3063
3064 /* Initialize allocated space. */
3065 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3066 prog->UniformRemapTable[i] = NULL;
3067
3068 prog->NumUniformRemapTable = max_loc + 1;
3069 }
3070
3071 for (unsigned i = 0; i < slots; i++) {
3072 unsigned loc = var->data.location + i;
3073
3074 /* Check if location is already used. */
3075 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3076
3077 /* Possibly same uniform from a different stage, this is ok. */
3078 unsigned hash_loc;
3079 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3080 return_value = 0;
3081 continue;
3082 }
3083
3084 /* ARB_explicit_uniform_location specification states:
3085 *
3086 * "No two default-block uniform variables in the program can have
3087 * the same location, even if they are unused, otherwise a compiler
3088 * or linker error will be generated."
3089 */
3090 linker_error(prog,
3091 "location qualifier for uniform %s overlaps "
3092 "previously used location\n",
3093 var->name);
3094 return -1;
3095 }
3096
3097 /* Initialize location as inactive before optimization
3098 * rounds and location assignment.
3099 */
3100 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3101 }
3102
3103 /* Note, base location used for arrays. */
3104 map->put(var->data.location, var->name);
3105
3106 return return_value;
3107 }
3108
3109 static bool
3110 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3111 struct gl_shader *sh,
3112 ir_variable *var)
3113 {
3114 unsigned slots = var->type->uniform_locations();
3115 unsigned max_loc = var->data.location + slots - 1;
3116
3117 /* Resize remap table if locations do not fit in the current one. */
3118 if (max_loc + 1 > sh->NumSubroutineUniformRemapTable) {
3119 sh->SubroutineUniformRemapTable =
3120 reralloc(sh, sh->SubroutineUniformRemapTable,
3121 gl_uniform_storage *,
3122 max_loc + 1);
3123
3124 if (!sh->SubroutineUniformRemapTable) {
3125 linker_error(prog, "Out of memory during linking.\n");
3126 return false;
3127 }
3128
3129 /* Initialize allocated space. */
3130 for (unsigned i = sh->NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3131 sh->SubroutineUniformRemapTable[i] = NULL;
3132
3133 sh->NumSubroutineUniformRemapTable = max_loc + 1;
3134 }
3135
3136 for (unsigned i = 0; i < slots; i++) {
3137 unsigned loc = var->data.location + i;
3138
3139 /* Check if location is already used. */
3140 if (sh->SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3141
3142 /* ARB_explicit_uniform_location specification states:
3143 * "No two subroutine uniform variables can have the same location
3144 * in the same shader stage, otherwise a compiler or linker error
3145 * will be generated."
3146 */
3147 linker_error(prog,
3148 "location qualifier for uniform %s overlaps "
3149 "previously used location\n",
3150 var->name);
3151 return false;
3152 }
3153
3154 /* Initialize location as inactive before optimization
3155 * rounds and location assignment.
3156 */
3157 sh->SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3158 }
3159
3160 return true;
3161 }
3162 /**
3163 * Check and reserve all explicit uniform locations, called before
3164 * any optimizations happen to handle also inactive uniforms and
3165 * inactive array elements that may get trimmed away.
3166 */
3167 static int
3168 check_explicit_uniform_locations(struct gl_context *ctx,
3169 struct gl_shader_program *prog)
3170 {
3171 if (!ctx->Extensions.ARB_explicit_uniform_location)
3172 return -1;
3173
3174 /* This map is used to detect if overlapping explicit locations
3175 * occur with the same uniform (from different stage) or a different one.
3176 */
3177 string_to_uint_map *uniform_map = new string_to_uint_map;
3178
3179 if (!uniform_map) {
3180 linker_error(prog, "Out of memory during linking.\n");
3181 return -1;
3182 }
3183
3184 unsigned entries_total = 0;
3185 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3186 struct gl_shader *sh = prog->_LinkedShaders[i];
3187
3188 if (!sh)
3189 continue;
3190
3191 foreach_in_list(ir_instruction, node, sh->ir) {
3192 ir_variable *var = node->as_variable();
3193 if (!var || var->data.mode != ir_var_uniform)
3194 continue;
3195
3196 if (var->data.explicit_location) {
3197 bool ret = false;
3198 if (var->type->without_array()->is_subroutine())
3199 ret = reserve_subroutine_explicit_locations(prog, sh, var);
3200 else {
3201 int slots = reserve_explicit_locations(prog, uniform_map,
3202 var);
3203 if (slots != -1) {
3204 ret = true;
3205 entries_total += slots;
3206 }
3207 }
3208 if (!ret) {
3209 delete uniform_map;
3210 return -1;
3211 }
3212 }
3213 }
3214 }
3215
3216 struct empty_uniform_block *current_block = NULL;
3217
3218 for (unsigned i = 0; i < prog->NumUniformRemapTable; i++) {
3219 /* We found empty space in UniformRemapTable. */
3220 if (prog->UniformRemapTable[i] == NULL) {
3221 /* We've found the beginning of a new continous block of empty slots */
3222 if (!current_block || current_block->start + current_block->slots != i) {
3223 current_block = rzalloc(prog, struct empty_uniform_block);
3224 current_block->start = i;
3225 exec_list_push_tail(&prog->EmptyUniformLocations,
3226 &current_block->link);
3227 }
3228
3229 /* The current block continues, so we simply increment its slots */
3230 current_block->slots++;
3231 }
3232 }
3233
3234 delete uniform_map;
3235 return entries_total;
3236 }
3237
3238 static bool
3239 should_add_buffer_variable(struct gl_shader_program *shProg,
3240 GLenum type, const char *name)
3241 {
3242 bool found_interface = false;
3243 unsigned block_name_len = 0;
3244 const char *block_name_dot = strchr(name, '.');
3245
3246 /* These rules only apply to buffer variables. So we return
3247 * true for the rest of types.
3248 */
3249 if (type != GL_BUFFER_VARIABLE)
3250 return true;
3251
3252 for (unsigned i = 0; i < shProg->NumBufferInterfaceBlocks; i++) {
3253 const char *block_name = shProg->BufferInterfaceBlocks[i].Name;
3254 block_name_len = strlen(block_name);
3255
3256 const char *block_square_bracket = strchr(block_name, '[');
3257 if (block_square_bracket) {
3258 /* The block is part of an array of named interfaces,
3259 * for the name comparison we ignore the "[x]" part.
3260 */
3261 block_name_len -= strlen(block_square_bracket);
3262 }
3263
3264 if (block_name_dot) {
3265 /* Check if the variable name starts with the interface
3266 * name. The interface name (if present) should have the
3267 * length than the interface block name we are comparing to.
3268 */
3269 unsigned len = strlen(name) - strlen(block_name_dot);
3270 if (len != block_name_len)
3271 continue;
3272 }
3273
3274 if (strncmp(block_name, name, block_name_len) == 0) {
3275 found_interface = true;
3276 break;
3277 }
3278 }
3279
3280 /* We remove the interface name from the buffer variable name,
3281 * including the dot that follows it.
3282 */
3283 if (found_interface)
3284 name = name + block_name_len + 1;
3285
3286 /* From: ARB_program_interface_query extension:
3287 *
3288 * "For an active shader storage block member declared as an array, an
3289 * entry will be generated only for the first array element, regardless
3290 * of its type. For arrays of aggregate types, the enumeration rules are
3291 * applied recursively for the single enumerated array element.
3292 */
3293 const char *struct_first_dot = strchr(name, '.');
3294 const char *first_square_bracket = strchr(name, '[');
3295
3296 /* The buffer variable is on top level and it is not an array */
3297 if (!first_square_bracket) {
3298 return true;
3299 /* The shader storage block member is a struct, then generate the entry */
3300 } else if (struct_first_dot && struct_first_dot < first_square_bracket) {
3301 return true;
3302 } else {
3303 /* Shader storage block member is an array, only generate an entry for the
3304 * first array element.
3305 */
3306 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3307 return true;
3308 }
3309
3310 return false;
3311 }
3312
3313 static bool
3314 add_program_resource(struct gl_shader_program *prog, GLenum type,
3315 const void *data, uint8_t stages)
3316 {
3317 assert(data);
3318
3319 /* If resource already exists, do not add it again. */
3320 for (unsigned i = 0; i < prog->NumProgramResourceList; i++)
3321 if (prog->ProgramResourceList[i].Data == data)
3322 return true;
3323
3324 prog->ProgramResourceList =
3325 reralloc(prog,
3326 prog->ProgramResourceList,
3327 gl_program_resource,
3328 prog->NumProgramResourceList + 1);
3329
3330 if (!prog->ProgramResourceList) {
3331 linker_error(prog, "Out of memory during linking.\n");
3332 return false;
3333 }
3334
3335 struct gl_program_resource *res =
3336 &prog->ProgramResourceList[prog->NumProgramResourceList];
3337
3338 res->Type = type;
3339 res->Data = data;
3340 res->StageReferences = stages;
3341
3342 prog->NumProgramResourceList++;
3343
3344 return true;
3345 }
3346
3347 /* Function checks if a variable var is a packed varying and
3348 * if given name is part of packed varying's list.
3349 *
3350 * If a variable is a packed varying, it has a name like
3351 * 'packed:a,b,c' where a, b and c are separate variables.
3352 */
3353 static bool
3354 included_in_packed_varying(ir_variable *var, const char *name)
3355 {
3356 if (strncmp(var->name, "packed:", 7) != 0)
3357 return false;
3358
3359 char *list = strdup(var->name + 7);
3360 assert(list);
3361
3362 bool found = false;
3363 char *saveptr;
3364 char *token = strtok_r(list, ",", &saveptr);
3365 while (token) {
3366 if (strcmp(token, name) == 0) {
3367 found = true;
3368 break;
3369 }
3370 token = strtok_r(NULL, ",", &saveptr);
3371 }
3372 free(list);
3373 return found;
3374 }
3375
3376 /**
3377 * Function builds a stage reference bitmask from variable name.
3378 */
3379 static uint8_t
3380 build_stageref(struct gl_shader_program *shProg, const char *name,
3381 unsigned mode)
3382 {
3383 uint8_t stages = 0;
3384
3385 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3386 * used for reference mask in gl_program_resource will need to be changed.
3387 */
3388 assert(MESA_SHADER_STAGES < 8);
3389
3390 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3391 struct gl_shader *sh = shProg->_LinkedShaders[i];
3392 if (!sh)
3393 continue;
3394
3395 /* Shader symbol table may contain variables that have
3396 * been optimized away. Search IR for the variable instead.
3397 */
3398 foreach_in_list(ir_instruction, node, sh->ir) {
3399 ir_variable *var = node->as_variable();
3400 if (var) {
3401 unsigned baselen = strlen(var->name);
3402
3403 if (included_in_packed_varying(var, name)) {
3404 stages |= (1 << i);
3405 break;
3406 }
3407
3408 /* Type needs to match if specified, otherwise we might
3409 * pick a variable with same name but different interface.
3410 */
3411 if (var->data.mode != mode)
3412 continue;
3413
3414 if (strncmp(var->name, name, baselen) == 0) {
3415 /* Check for exact name matches but also check for arrays and
3416 * structs.
3417 */
3418 if (name[baselen] == '\0' ||
3419 name[baselen] == '[' ||
3420 name[baselen] == '.') {
3421 stages |= (1 << i);
3422 break;
3423 }
3424 }
3425 }
3426 }
3427 }
3428 return stages;
3429 }
3430
3431 /**
3432 * Create gl_shader_variable from ir_variable class.
3433 */
3434 static gl_shader_variable *
3435 create_shader_variable(struct gl_shader_program *shProg, const ir_variable *in)
3436 {
3437 gl_shader_variable *out = ralloc(shProg, struct gl_shader_variable);
3438 if (!out)
3439 return NULL;
3440
3441 out->type = in->type;
3442 out->name = ralloc_strdup(shProg, in->name);
3443
3444 if (!out->name)
3445 return NULL;
3446
3447 out->location = in->data.location;
3448 out->index = in->data.index;
3449 out->patch = in->data.patch;
3450 out->mode = in->data.mode;
3451
3452 return out;
3453 }
3454
3455 static bool
3456 add_interface_variables(struct gl_shader_program *shProg,
3457 exec_list *ir, GLenum programInterface)
3458 {
3459 foreach_in_list(ir_instruction, node, ir) {
3460 ir_variable *var = node->as_variable();
3461 uint8_t mask = 0;
3462
3463 if (!var)
3464 continue;
3465
3466 switch (var->data.mode) {
3467 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3468 * "For GetActiveAttrib, all active vertex shader input variables
3469 * are enumerated, including the special built-in inputs gl_VertexID
3470 * and gl_InstanceID."
3471 */
3472 case ir_var_system_value:
3473 if (var->data.location != SYSTEM_VALUE_VERTEX_ID &&
3474 var->data.location != SYSTEM_VALUE_VERTEX_ID_ZERO_BASE &&
3475 var->data.location != SYSTEM_VALUE_INSTANCE_ID)
3476 continue;
3477 /* Mark special built-in inputs referenced by the vertex stage so
3478 * that they are considered active by the shader queries.
3479 */
3480 mask = (1 << (MESA_SHADER_VERTEX));
3481 /* FALLTHROUGH */
3482 case ir_var_shader_in:
3483 if (programInterface != GL_PROGRAM_INPUT)
3484 continue;
3485 break;
3486 case ir_var_shader_out:
3487 if (programInterface != GL_PROGRAM_OUTPUT)
3488 continue;
3489 break;
3490 default:
3491 continue;
3492 };
3493
3494 /* Skip packed varyings, packed varyings are handled separately
3495 * by add_packed_varyings.
3496 */
3497 if (strncmp(var->name, "packed:", 7) == 0)
3498 continue;
3499
3500 /* Skip fragdata arrays, these are handled separately
3501 * by add_fragdata_arrays.
3502 */
3503 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
3504 continue;
3505
3506 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3507 if (!sha_v)
3508 return false;
3509
3510 if (!add_program_resource(shProg, programInterface, sha_v,
3511 build_stageref(shProg, sha_v->name,
3512 sha_v->mode) | mask))
3513 return false;
3514 }
3515 return true;
3516 }
3517
3518 static bool
3519 add_packed_varyings(struct gl_shader_program *shProg, int stage, GLenum type)
3520 {
3521 struct gl_shader *sh = shProg->_LinkedShaders[stage];
3522 GLenum iface;
3523
3524 if (!sh || !sh->packed_varyings)
3525 return true;
3526
3527 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
3528 ir_variable *var = node->as_variable();
3529 if (var) {
3530 switch (var->data.mode) {
3531 case ir_var_shader_in:
3532 iface = GL_PROGRAM_INPUT;
3533 break;
3534 case ir_var_shader_out:
3535 iface = GL_PROGRAM_OUTPUT;
3536 break;
3537 default:
3538 unreachable("unexpected type");
3539 }
3540
3541 if (type == iface) {
3542 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3543 if (!sha_v)
3544 return false;
3545 if (!add_program_resource(shProg, iface, sha_v,
3546 build_stageref(shProg, sha_v->name,
3547 sha_v->mode)))
3548 return false;
3549 }
3550 }
3551 }
3552 return true;
3553 }
3554
3555 static bool
3556 add_fragdata_arrays(struct gl_shader_program *shProg)
3557 {
3558 struct gl_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
3559
3560 if (!sh || !sh->fragdata_arrays)
3561 return true;
3562
3563 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
3564 ir_variable *var = node->as_variable();
3565 if (var) {
3566 assert(var->data.mode == ir_var_shader_out);
3567 gl_shader_variable *sha_v = create_shader_variable(shProg, var);
3568 if (!sha_v)
3569 return false;
3570 if (!add_program_resource(shProg, GL_PROGRAM_OUTPUT, sha_v,
3571 1 << MESA_SHADER_FRAGMENT))
3572 return false;
3573 }
3574 }
3575 return true;
3576 }
3577
3578 static char*
3579 get_top_level_name(const char *name)
3580 {
3581 const char *first_dot = strchr(name, '.');
3582 const char *first_square_bracket = strchr(name, '[');
3583 int name_size = 0;
3584 /* From ARB_program_interface_query spec:
3585 *
3586 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3587 * number of active array elements of the top-level shader storage block
3588 * member containing to the active variable is written to <params>. If the
3589 * top-level block member is not declared as an array, the value one is
3590 * written to <params>. If the top-level block member is an array with no
3591 * declared size, the value zero is written to <params>.
3592 */
3593
3594 /* The buffer variable is on top level.*/
3595 if (!first_square_bracket && !first_dot)
3596 name_size = strlen(name);
3597 else if ((!first_square_bracket ||
3598 (first_dot && first_dot < first_square_bracket)))
3599 name_size = first_dot - name;
3600 else
3601 name_size = first_square_bracket - name;
3602
3603 return strndup(name, name_size);
3604 }
3605
3606 static char*
3607 get_var_name(const char *name)
3608 {
3609 const char *first_dot = strchr(name, '.');
3610
3611 if (!first_dot)
3612 return strdup(name);
3613
3614 return strndup(first_dot+1, strlen(first_dot) - 1);
3615 }
3616
3617 static bool
3618 is_top_level_shader_storage_block_member(const char* name,
3619 const char* interface_name,
3620 const char* field_name)
3621 {
3622 bool result = false;
3623
3624 /* If the given variable is already a top-level shader storage
3625 * block member, then return array_size = 1.
3626 * We could have two possibilities: if we have an instanced
3627 * shader storage block or not instanced.
3628 *
3629 * For the first, we check create a name as it was in top level and
3630 * compare it with the real name. If they are the same, then
3631 * the variable is already at top-level.
3632 *
3633 * Full instanced name is: interface name + '.' + var name +
3634 * NULL character
3635 */
3636 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
3637 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
3638 if (!full_instanced_name) {
3639 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
3640 return false;
3641 }
3642
3643 snprintf(full_instanced_name, name_length, "%s.%s",
3644 interface_name, field_name);
3645
3646 /* Check if its top-level shader storage block member of an
3647 * instanced interface block, or of a unnamed interface block.
3648 */
3649 if (strcmp(name, full_instanced_name) == 0 ||
3650 strcmp(name, field_name) == 0)
3651 result = true;
3652
3653 free(full_instanced_name);
3654 return result;
3655 }
3656
3657 static int
3658 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
3659 char *interface_name, char *var_name)
3660 {
3661 /* From GL_ARB_program_interface_query spec:
3662 *
3663 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3664 * identifying the number of active array elements of the top-level
3665 * shader storage block member containing to the active variable is
3666 * written to <params>. If the top-level block member is not
3667 * declared as an array, the value one is written to <params>. If
3668 * the top-level block member is an array with no declared size,
3669 * the value zero is written to <params>.
3670 */
3671 if (is_top_level_shader_storage_block_member(uni->name,
3672 interface_name,
3673 var_name))
3674 return 1;
3675 else if (field->type->is_unsized_array())
3676 return 0;
3677 else if (field->type->is_array())
3678 return field->type->length;
3679
3680 return 1;
3681 }
3682
3683 static int
3684 get_array_stride(struct gl_uniform_storage *uni, const glsl_type *interface,
3685 const glsl_struct_field *field, char *interface_name,
3686 char *var_name)
3687 {
3688 /* From GL_ARB_program_interface_query:
3689 *
3690 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3691 * identifying the stride between array elements of the top-level
3692 * shader storage block member containing the active variable is
3693 * written to <params>. For top-level block members declared as
3694 * arrays, the value written is the difference, in basic machine
3695 * units, between the offsets of the active variable for
3696 * consecutive elements in the top-level array. For top-level
3697 * block members not declared as an array, zero is written to
3698 * <params>."
3699 */
3700 if (field->type->is_array()) {
3701 const enum glsl_matrix_layout matrix_layout =
3702 glsl_matrix_layout(field->matrix_layout);
3703 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
3704 const glsl_type *array_type = field->type->fields.array;
3705
3706 if (is_top_level_shader_storage_block_member(uni->name,
3707 interface_name,
3708 var_name))
3709 return 0;
3710
3711 if (interface->interface_packing != GLSL_INTERFACE_PACKING_STD430) {
3712 if (array_type->is_record() || array_type->is_array())
3713 return glsl_align(array_type->std140_size(row_major), 16);
3714 else
3715 return MAX2(array_type->std140_base_alignment(row_major), 16);
3716 } else {
3717 return array_type->std430_array_stride(row_major);
3718 }
3719 }
3720 return 0;
3721 }
3722
3723 static void
3724 calculate_array_size_and_stride(struct gl_shader_program *shProg,
3725 struct gl_uniform_storage *uni)
3726 {
3727 int block_index = uni->block_index;
3728 int array_size = -1;
3729 int array_stride = -1;
3730 char *var_name = get_top_level_name(uni->name);
3731 char *interface_name =
3732 get_top_level_name(shProg->BufferInterfaceBlocks[block_index].Name);
3733
3734 if (strcmp(var_name, interface_name) == 0) {
3735 /* Deal with instanced array of SSBOs */
3736 char *temp_name = get_var_name(uni->name);
3737 if (!temp_name) {
3738 linker_error(shProg, "Out of memory during linking.\n");
3739 goto write_top_level_array_size_and_stride;
3740 }
3741 free(var_name);
3742 var_name = get_top_level_name(temp_name);
3743 free(temp_name);
3744 if (!var_name) {
3745 linker_error(shProg, "Out of memory during linking.\n");
3746 goto write_top_level_array_size_and_stride;
3747 }
3748 }
3749
3750 for (unsigned i = 0; i < shProg->NumShaders; i++) {
3751 if (shProg->Shaders[i] == NULL)
3752 continue;
3753
3754 const gl_shader *stage = shProg->Shaders[i];
3755 foreach_in_list(ir_instruction, node, stage->ir) {
3756 ir_variable *var = node->as_variable();
3757 if (!var || !var->get_interface_type() ||
3758 var->data.mode != ir_var_shader_storage)
3759 continue;
3760
3761 const glsl_type *interface = var->get_interface_type();
3762
3763 if (strcmp(interface_name, interface->name) != 0)
3764 continue;
3765
3766 for (unsigned i = 0; i < interface->length; i++) {
3767 const glsl_struct_field *field = &interface->fields.structure[i];
3768 if (strcmp(field->name, var_name) != 0)
3769 continue;
3770
3771 array_stride = get_array_stride(uni, interface, field,
3772 interface_name, var_name);
3773 array_size = get_array_size(uni, field, interface_name, var_name);
3774 goto write_top_level_array_size_and_stride;
3775 }
3776 }
3777 }
3778 write_top_level_array_size_and_stride:
3779 free(interface_name);
3780 free(var_name);
3781 uni->top_level_array_stride = array_stride;
3782 uni->top_level_array_size = array_size;
3783 }
3784
3785 /**
3786 * Builds up a list of program resources that point to existing
3787 * resource data.
3788 */
3789 void
3790 build_program_resource_list(struct gl_shader_program *shProg)
3791 {
3792 /* Rebuild resource list. */
3793 if (shProg->ProgramResourceList) {
3794 ralloc_free(shProg->ProgramResourceList);
3795 shProg->ProgramResourceList = NULL;
3796 shProg->NumProgramResourceList = 0;
3797 }
3798
3799 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
3800
3801 /* Determine first input and final output stage. These are used to
3802 * detect which variables should be enumerated in the resource list
3803 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3804 */
3805 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3806 if (!shProg->_LinkedShaders[i])
3807 continue;
3808 if (input_stage == MESA_SHADER_STAGES)
3809 input_stage = i;
3810 output_stage = i;
3811 }
3812
3813 /* Empty shader, no resources. */
3814 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
3815 return;
3816
3817 /* Program interface needs to expose varyings in case of SSO. */
3818 if (shProg->SeparateShader) {
3819 if (!add_packed_varyings(shProg, input_stage, GL_PROGRAM_INPUT))
3820 return;
3821
3822 if (!add_packed_varyings(shProg, output_stage, GL_PROGRAM_OUTPUT))
3823 return;
3824 }
3825
3826 if (!add_fragdata_arrays(shProg))
3827 return;
3828
3829 /* Add inputs and outputs to the resource list. */
3830 if (!add_interface_variables(shProg, shProg->_LinkedShaders[input_stage]->ir,
3831 GL_PROGRAM_INPUT))
3832 return;
3833
3834 if (!add_interface_variables(shProg, shProg->_LinkedShaders[output_stage]->ir,
3835 GL_PROGRAM_OUTPUT))
3836 return;
3837
3838 /* Add transform feedback varyings. */
3839 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
3840 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
3841 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
3842 &shProg->LinkedTransformFeedback.Varyings[i],
3843 0))
3844 return;
3845 }
3846 }
3847
3848 /* Add uniforms from uniform storage. */
3849 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
3850 /* Do not add uniforms internally used by Mesa. */
3851 if (shProg->UniformStorage[i].hidden)
3852 continue;
3853
3854 uint8_t stageref =
3855 build_stageref(shProg, shProg->UniformStorage[i].name,
3856 ir_var_uniform);
3857
3858 /* Add stagereferences for uniforms in a uniform block. */
3859 int block_index = shProg->UniformStorage[i].block_index;
3860 if (block_index != -1) {
3861 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
3862 if (shProg->InterfaceBlockStageIndex[j][block_index] != -1)
3863 stageref |= (1 << j);
3864 }
3865 }
3866
3867 bool is_shader_storage = shProg->UniformStorage[i].is_shader_storage;
3868 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
3869 if (!should_add_buffer_variable(shProg, type,
3870 shProg->UniformStorage[i].name))
3871 continue;
3872
3873 if (is_shader_storage) {
3874 calculate_array_size_and_stride(shProg, &shProg->UniformStorage[i]);
3875 }
3876
3877 if (!add_program_resource(shProg, type,
3878 &shProg->UniformStorage[i], stageref))
3879 return;
3880 }
3881
3882 /* Add program uniform blocks and shader storage blocks. */
3883 for (unsigned i = 0; i < shProg->NumBufferInterfaceBlocks; i++) {
3884 bool is_shader_storage = shProg->BufferInterfaceBlocks[i].IsShaderStorage;
3885 GLenum type = is_shader_storage ? GL_SHADER_STORAGE_BLOCK : GL_UNIFORM_BLOCK;
3886 if (!add_program_resource(shProg, type,
3887 &shProg->BufferInterfaceBlocks[i], 0))
3888 return;
3889 }
3890
3891 /* Add atomic counter buffers. */
3892 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
3893 if (!add_program_resource(shProg, GL_ATOMIC_COUNTER_BUFFER,
3894 &shProg->AtomicBuffers[i], 0))
3895 return;
3896 }
3897
3898 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
3899 GLenum type;
3900 if (!shProg->UniformStorage[i].hidden)
3901 continue;
3902
3903 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
3904 if (!shProg->UniformStorage[i].opaque[j].active ||
3905 !shProg->UniformStorage[i].type->is_subroutine())
3906 continue;
3907
3908 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
3909 /* add shader subroutines */
3910 if (!add_program_resource(shProg, type, &shProg->UniformStorage[i], 0))
3911 return;
3912 }
3913 }
3914
3915 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3916 struct gl_shader *sh = shProg->_LinkedShaders[i];
3917 GLuint type;
3918
3919 if (!sh)
3920 continue;
3921
3922 type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
3923 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
3924 if (!add_program_resource(shProg, type, &sh->SubroutineFunctions[j], 0))
3925 return;
3926 }
3927 }
3928 }
3929
3930 /**
3931 * This check is done to make sure we allow only constant expression
3932 * indexing and "constant-index-expression" (indexing with an expression
3933 * that includes loop induction variable).
3934 */
3935 static bool
3936 validate_sampler_array_indexing(struct gl_context *ctx,
3937 struct gl_shader_program *prog)
3938 {
3939 dynamic_sampler_array_indexing_visitor v;
3940 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3941 if (prog->_LinkedShaders[i] == NULL)
3942 continue;
3943
3944 bool no_dynamic_indexing =
3945 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
3946
3947 /* Search for array derefs in shader. */
3948 v.run(prog->_LinkedShaders[i]->ir);
3949 if (v.uses_dynamic_sampler_array_indexing()) {
3950 const char *msg = "sampler arrays indexed with non-constant "
3951 "expressions is forbidden in GLSL %s %u";
3952 /* Backend has indicated that it has no dynamic indexing support. */
3953 if (no_dynamic_indexing) {
3954 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3955 return false;
3956 } else {
3957 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3958 }
3959 }
3960 }
3961 return true;
3962 }
3963
3964 static void
3965 link_assign_subroutine_types(struct gl_shader_program *prog)
3966 {
3967 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3968 gl_shader *sh = prog->_LinkedShaders[i];
3969
3970 if (sh == NULL)
3971 continue;
3972
3973 foreach_in_list(ir_instruction, node, sh->ir) {
3974 ir_function *fn = node->as_function();
3975 if (!fn)
3976 continue;
3977
3978 if (fn->is_subroutine)
3979 sh->NumSubroutineUniformTypes++;
3980
3981 if (!fn->num_subroutine_types)
3982 continue;
3983
3984 sh->SubroutineFunctions = reralloc(sh, sh->SubroutineFunctions,
3985 struct gl_subroutine_function,
3986 sh->NumSubroutineFunctions + 1);
3987 sh->SubroutineFunctions[sh->NumSubroutineFunctions].name = ralloc_strdup(sh, fn->name);
3988 sh->SubroutineFunctions[sh->NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
3989 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types =
3990 ralloc_array(sh, const struct glsl_type *,
3991 fn->num_subroutine_types);
3992
3993 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
3994 * GLSL 4.5 spec:
3995 *
3996 * "Each subroutine with an index qualifier in the shader must be
3997 * given a unique index, otherwise a compile or link error will be
3998 * generated."
3999 */
4000 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4001 if (sh->SubroutineFunctions[j].index != -1 &&
4002 sh->SubroutineFunctions[j].index == fn->subroutine_index) {
4003 linker_error(prog, "each subroutine index qualifier in the "
4004 "shader must be unique\n");
4005 return;
4006 }
4007 }
4008 sh->SubroutineFunctions[sh->NumSubroutineFunctions].index =
4009 fn->subroutine_index;
4010
4011 for (int j = 0; j < fn->num_subroutine_types; j++)
4012 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4013 sh->NumSubroutineFunctions++;
4014 }
4015
4016 /* Assign index for subroutines without an explicit index*/
4017 int index = 0;
4018 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4019 while (sh->SubroutineFunctions[j].index == -1) {
4020 for (unsigned k = 0; k < sh->NumSubroutineFunctions; k++) {
4021 if (sh->SubroutineFunctions[k].index == index)
4022 break;
4023 else if (k == sh->NumSubroutineFunctions - 1)
4024 sh->SubroutineFunctions[j].index = index;
4025 }
4026 index++;
4027 }
4028 }
4029 }
4030 }
4031
4032 static void
4033 split_ubos_and_ssbos(void *mem_ctx,
4034 struct gl_uniform_block **s_blks,
4035 struct gl_uniform_block *p_blks,
4036 unsigned num_blocks,
4037 struct gl_uniform_block ***ubos,
4038 unsigned *num_ubos,
4039 struct gl_uniform_block ***ssbos,
4040 unsigned *num_ssbos)
4041 {
4042 unsigned num_ubo_blocks = 0;
4043 unsigned num_ssbo_blocks = 0;
4044
4045 /* Are we spliting the list of blocks for the shader or the program */
4046 bool is_shader = p_blks == NULL;
4047
4048 for (unsigned i = 0; i < num_blocks; i++) {
4049 if (is_shader ? s_blks[i]->IsShaderStorage : p_blks[i].IsShaderStorage)
4050 num_ssbo_blocks++;
4051 else
4052 num_ubo_blocks++;
4053 }
4054
4055 *ubos = ralloc_array(mem_ctx, gl_uniform_block *, num_ubo_blocks);
4056 *num_ubos = 0;
4057
4058 *ssbos = ralloc_array(mem_ctx, gl_uniform_block *, num_ssbo_blocks);
4059 *num_ssbos = 0;
4060
4061 for (unsigned i = 0; i < num_blocks; i++) {
4062 struct gl_uniform_block *blk = is_shader ? s_blks[i] : &p_blks[i];
4063 if (blk->IsShaderStorage) {
4064 (*ssbos)[*num_ssbos] = blk;
4065 (*num_ssbos)++;
4066 } else {
4067 (*ubos)[*num_ubos] = blk;
4068 (*num_ubos)++;
4069 }
4070 }
4071
4072 assert(*num_ubos + *num_ssbos == num_blocks);
4073 }
4074
4075 static void
4076 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4077 {
4078 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4079
4080 foreach_in_list(ir_instruction, node, ir) {
4081 ir_variable *const var = node->as_variable();
4082
4083 if (var == NULL || var->data.mode != io_mode)
4084 continue;
4085
4086 /* Don't set always active on builtins that haven't been redeclared */
4087 if (var->data.how_declared == ir_var_declared_implicitly)
4088 continue;
4089
4090 var->data.always_active_io = true;
4091 }
4092 }
4093
4094 /**
4095 * When separate shader programs are enabled, only input/outputs between
4096 * the stages of a multi-stage separate program can be safely removed
4097 * from the shader interface. Other inputs/outputs must remain active.
4098 */
4099 static void
4100 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4101 {
4102 unsigned first, last;
4103 assert(prog->SeparateShader);
4104
4105 first = MESA_SHADER_STAGES;
4106 last = 0;
4107
4108 /* Determine first and last stage. Excluding the compute stage */
4109 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4110 if (!prog->_LinkedShaders[i])
4111 continue;
4112 if (first == MESA_SHADER_STAGES)
4113 first = i;
4114 last = i;
4115 }
4116
4117 if (first == MESA_SHADER_STAGES)
4118 return;
4119
4120 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4121 gl_shader *sh = prog->_LinkedShaders[stage];
4122 if (!sh)
4123 continue;
4124
4125 if (first == last) {
4126 /* For a single shader program only allow inputs to the vertex shader
4127 * and outputs from the fragment shader to be removed.
4128 */
4129 if (stage != MESA_SHADER_VERTEX)
4130 set_always_active_io(sh->ir, ir_var_shader_in);
4131 if (stage != MESA_SHADER_FRAGMENT)
4132 set_always_active_io(sh->ir, ir_var_shader_out);
4133 } else {
4134 /* For multi-stage separate shader programs only allow inputs and
4135 * outputs between the shader stages to be removed as well as inputs
4136 * to the vertex shader and outputs from the fragment shader.
4137 */
4138 if (stage == first && stage != MESA_SHADER_VERTEX)
4139 set_always_active_io(sh->ir, ir_var_shader_in);
4140 else if (stage == last && stage != MESA_SHADER_FRAGMENT)
4141 set_always_active_io(sh->ir, ir_var_shader_out);
4142 }
4143 }
4144 }
4145
4146 void
4147 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4148 {
4149 prog->LinkStatus = true; /* All error paths will set this to false */
4150 prog->Validated = false;
4151 prog->_Used = false;
4152
4153 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4154 *
4155 * "Linking can fail for a variety of reasons as specified in the
4156 * OpenGL Shading Language Specification, as well as any of the
4157 * following reasons:
4158 *
4159 * - No shader objects are attached to program."
4160 *
4161 * The Compatibility Profile specification does not list the error. In
4162 * Compatibility Profile missing shader stages are replaced by
4163 * fixed-function. This applies to the case where all stages are
4164 * missing.
4165 */
4166 if (prog->NumShaders == 0) {
4167 if (ctx->API != API_OPENGL_COMPAT)
4168 linker_error(prog, "no shaders attached to the program\n");
4169 return;
4170 }
4171
4172 unsigned num_tfeedback_decls = 0;
4173 unsigned int num_explicit_uniform_locs = 0;
4174 bool has_xfb_qualifiers = false;
4175 char **varying_names = NULL;
4176 tfeedback_decl *tfeedback_decls = NULL;
4177
4178 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4179
4180 prog->ARB_fragment_coord_conventions_enable = false;
4181
4182 /* Separate the shaders into groups based on their type.
4183 */
4184 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4185 unsigned num_shaders[MESA_SHADER_STAGES];
4186
4187 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4188 shader_list[i] = (struct gl_shader **)
4189 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4190 num_shaders[i] = 0;
4191 }
4192
4193 unsigned min_version = UINT_MAX;
4194 unsigned max_version = 0;
4195 for (unsigned i = 0; i < prog->NumShaders; i++) {
4196 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4197 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4198
4199 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4200 linker_error(prog, "all shaders must use same shading "
4201 "language version\n");
4202 goto done;
4203 }
4204
4205 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4206 prog->ARB_fragment_coord_conventions_enable = true;
4207 }
4208
4209 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4210 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4211 num_shaders[shader_type]++;
4212 }
4213
4214 /* In desktop GLSL, different shader versions may be linked together. In
4215 * GLSL ES, all shader versions must be the same.
4216 */
4217 if (prog->Shaders[0]->IsES && min_version != max_version) {
4218 linker_error(prog, "all shaders must use same shading "
4219 "language version\n");
4220 goto done;
4221 }
4222
4223 prog->Version = max_version;
4224 prog->IsES = prog->Shaders[0]->IsES;
4225
4226 /* Some shaders have to be linked with some other shaders present.
4227 */
4228 if (!prog->SeparateShader) {
4229 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4230 num_shaders[MESA_SHADER_VERTEX] == 0) {
4231 linker_error(prog, "Geometry shader must be linked with "
4232 "vertex shader\n");
4233 goto done;
4234 }
4235 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4236 num_shaders[MESA_SHADER_VERTEX] == 0) {
4237 linker_error(prog, "Tessellation evaluation shader must be linked "
4238 "with vertex shader\n");
4239 goto done;
4240 }
4241 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4242 num_shaders[MESA_SHADER_VERTEX] == 0) {
4243 linker_error(prog, "Tessellation control shader must be linked with "
4244 "vertex shader\n");
4245 goto done;
4246 }
4247
4248 /* The spec is self-contradictory here. It allows linking without a tess
4249 * eval shader, but that can only be used with transform feedback and
4250 * rasterization disabled. However, transform feedback isn't allowed
4251 * with GL_PATCHES, so it can't be used.
4252 *
4253 * More investigation showed that the idea of transform feedback after
4254 * a tess control shader was dropped, because some hw vendors couldn't
4255 * support tessellation without a tess eval shader, but the linker
4256 * section wasn't updated to reflect that.
4257 *
4258 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4259 * spec bug.
4260 *
4261 * Do what's reasonable and always require a tess eval shader if a tess
4262 * control shader is present.
4263 */
4264 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4265 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4266 linker_error(prog, "Tessellation control shader must be linked with "
4267 "tessellation evaluation shader\n");
4268 goto done;
4269 }
4270 }
4271
4272 /* Compute shaders have additional restrictions. */
4273 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4274 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4275 linker_error(prog, "Compute shaders may not be linked with any other "
4276 "type of shader\n");
4277 }
4278
4279 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4280 if (prog->_LinkedShaders[i] != NULL)
4281 _mesa_delete_shader(ctx, prog->_LinkedShaders[i]);
4282
4283 prog->_LinkedShaders[i] = NULL;
4284 }
4285
4286 /* Link all shaders for a particular stage and validate the result.
4287 */
4288 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4289 if (num_shaders[stage] > 0) {
4290 gl_shader *const sh =
4291 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4292 num_shaders[stage]);
4293
4294 if (!prog->LinkStatus) {
4295 if (sh)
4296 _mesa_delete_shader(ctx, sh);
4297 goto done;
4298 }
4299
4300 switch (stage) {
4301 case MESA_SHADER_VERTEX:
4302 validate_vertex_shader_executable(prog, sh);
4303 break;
4304 case MESA_SHADER_TESS_CTRL:
4305 /* nothing to be done */
4306 break;
4307 case MESA_SHADER_TESS_EVAL:
4308 validate_tess_eval_shader_executable(prog, sh);
4309 break;
4310 case MESA_SHADER_GEOMETRY:
4311 validate_geometry_shader_executable(prog, sh);
4312 break;
4313 case MESA_SHADER_FRAGMENT:
4314 validate_fragment_shader_executable(prog, sh);
4315 break;
4316 }
4317 if (!prog->LinkStatus) {
4318 if (sh)
4319 _mesa_delete_shader(ctx, sh);
4320 goto done;
4321 }
4322
4323 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
4324 }
4325 }
4326
4327 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
4328 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
4329 else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0)
4330 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
4331 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
4332 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
4333 else
4334 prog->LastClipDistanceArraySize = 0; /* Not used */
4335
4336 /* Here begins the inter-stage linking phase. Some initial validation is
4337 * performed, then locations are assigned for uniforms, attributes, and
4338 * varyings.
4339 */
4340 cross_validate_uniforms(prog);
4341 if (!prog->LinkStatus)
4342 goto done;
4343
4344 unsigned first, last, prev;
4345
4346 first = MESA_SHADER_STAGES;
4347 last = 0;
4348
4349 /* Determine first and last stage. */
4350 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4351 if (!prog->_LinkedShaders[i])
4352 continue;
4353 if (first == MESA_SHADER_STAGES)
4354 first = i;
4355 last = i;
4356 }
4357
4358 num_explicit_uniform_locs = check_explicit_uniform_locations(ctx, prog);
4359 link_assign_subroutine_types(prog);
4360
4361 if (!prog->LinkStatus)
4362 goto done;
4363
4364 resize_tes_inputs(ctx, prog);
4365
4366 /* Validate the inputs of each stage with the output of the preceding
4367 * stage.
4368 */
4369 prev = first;
4370 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4371 if (prog->_LinkedShaders[i] == NULL)
4372 continue;
4373
4374 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4375 prog->_LinkedShaders[i]);
4376 if (!prog->LinkStatus)
4377 goto done;
4378
4379 cross_validate_outputs_to_inputs(prog,
4380 prog->_LinkedShaders[prev],
4381 prog->_LinkedShaders[i]);
4382 if (!prog->LinkStatus)
4383 goto done;
4384
4385 prev = i;
4386 }
4387
4388 /* Cross-validate uniform blocks between shader stages */
4389 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
4390 MESA_SHADER_STAGES);
4391 if (!prog->LinkStatus)
4392 goto done;
4393
4394 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4395 if (prog->_LinkedShaders[i] != NULL)
4396 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
4397 }
4398
4399 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4400 * it before optimization because we want most of the checks to get
4401 * dropped thanks to constant propagation.
4402 *
4403 * This rule also applies to GLSL ES 3.00.
4404 */
4405 if (max_version >= (prog->IsES ? 300 : 130)) {
4406 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4407 if (sh) {
4408 lower_discard_flow(sh->ir);
4409 }
4410 }
4411
4412 if (prog->SeparateShader)
4413 disable_varying_optimizations_for_sso(prog);
4414
4415 if (!interstage_cross_validate_uniform_blocks(prog))
4416 goto done;
4417
4418 /* Do common optimization before assigning storage for attributes,
4419 * uniforms, and varyings. Later optimization could possibly make
4420 * some of that unused.
4421 */
4422 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4423 if (prog->_LinkedShaders[i] == NULL)
4424 continue;
4425
4426 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
4427 if (!prog->LinkStatus)
4428 goto done;
4429
4430 if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
4431 lower_clip_distance(prog->_LinkedShaders[i]);
4432 }
4433
4434 if (ctx->Const.LowerTessLevel) {
4435 lower_tess_level(prog->_LinkedShaders[i]);
4436 }
4437
4438 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
4439 &ctx->Const.ShaderCompilerOptions[i],
4440 ctx->Const.NativeIntegers))
4441 ;
4442
4443 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
4444 }
4445
4446 /* Validation for special cases where we allow sampler array indexing
4447 * with loop induction variable. This check emits a warning or error
4448 * depending if backend can handle dynamic indexing.
4449 */
4450 if ((!prog->IsES && prog->Version < 130) ||
4451 (prog->IsES && prog->Version < 300)) {
4452 if (!validate_sampler_array_indexing(ctx, prog))
4453 goto done;
4454 }
4455
4456 /* Check and validate stream emissions in geometry shaders */
4457 validate_geometry_shader_emissions(ctx, prog);
4458
4459 /* Mark all generic shader inputs and outputs as unpaired. */
4460 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4461 if (prog->_LinkedShaders[i] != NULL) {
4462 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4463 }
4464 }
4465
4466 prev = first;
4467 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4468 if (prog->_LinkedShaders[i] == NULL)
4469 continue;
4470
4471 match_explicit_outputs_to_inputs(prog, prog->_LinkedShaders[prev],
4472 prog->_LinkedShaders[i]);
4473 prev = i;
4474 }
4475
4476 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4477 MESA_SHADER_VERTEX)) {
4478 goto done;
4479 }
4480
4481 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4482 MESA_SHADER_FRAGMENT)) {
4483 goto done;
4484 }
4485
4486 /* From the ARB_enhanced_layouts spec:
4487 *
4488 * "If the shader used to record output variables for transform feedback
4489 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4490 * qualifiers, the values specified by TransformFeedbackVaryings are
4491 * ignored, and the set of variables captured for transform feedback is
4492 * instead derived from the specified layout qualifiers."
4493 */
4494 for (int i = MESA_SHADER_FRAGMENT - 1; i >= 0; i--) {
4495 /* Find last stage before fragment shader */
4496 if (prog->_LinkedShaders[i]) {
4497 has_xfb_qualifiers =
4498 process_xfb_layout_qualifiers(mem_ctx, prog->_LinkedShaders[i],
4499 &num_tfeedback_decls,
4500 &varying_names);
4501 break;
4502 }
4503 }
4504
4505 if (!has_xfb_qualifiers) {
4506 num_tfeedback_decls = prog->TransformFeedback.NumVarying;
4507 varying_names = prog->TransformFeedback.VaryingNames;
4508 }
4509
4510 if (num_tfeedback_decls != 0) {
4511 /* From GL_EXT_transform_feedback:
4512 * A program will fail to link if:
4513 *
4514 * * the <count> specified by TransformFeedbackVaryingsEXT is
4515 * non-zero, but the program object has no vertex or geometry
4516 * shader;
4517 */
4518 if (first >= MESA_SHADER_FRAGMENT) {
4519 linker_error(prog, "Transform feedback varyings specified, but "
4520 "no vertex, tessellation, or geometry shader is "
4521 "present.\n");
4522 goto done;
4523 }
4524
4525 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
4526 num_tfeedback_decls);
4527 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
4528 varying_names, tfeedback_decls))
4529 goto done;
4530 }
4531
4532 /* If there is no fragment shader we need to set transform feedback.
4533 *
4534 * For SSO we need also need to assign output locations, we assign them
4535 * here because we need to do it for both single stage programs and multi
4536 * stage programs.
4537 */
4538 if (last < MESA_SHADER_FRAGMENT &&
4539 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
4540 if (!assign_varying_locations(ctx, mem_ctx, prog,
4541 prog->_LinkedShaders[last], NULL,
4542 num_tfeedback_decls, tfeedback_decls))
4543 goto done;
4544 }
4545
4546 if (last <= MESA_SHADER_FRAGMENT) {
4547 /* Remove unused varyings from the first/last stage unless SSO */
4548 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4549 prog->_LinkedShaders[first],
4550 ir_var_shader_in);
4551 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4552 prog->_LinkedShaders[last],
4553 ir_var_shader_out);
4554
4555 /* If the program is made up of only a single stage */
4556 if (first == last) {
4557
4558 gl_shader *const sh = prog->_LinkedShaders[last];
4559 if (prog->SeparateShader) {
4560 /* Assign input locations for SSO, output locations are already
4561 * assigned.
4562 */
4563 if (!assign_varying_locations(ctx, mem_ctx, prog,
4564 NULL /* producer */,
4565 sh /* consumer */,
4566 0 /* num_tfeedback_decls */,
4567 NULL /* tfeedback_decls */))
4568 goto done;
4569 }
4570
4571 do_dead_builtin_varyings(ctx, NULL, sh, 0, NULL);
4572 do_dead_builtin_varyings(ctx, sh, NULL, num_tfeedback_decls,
4573 tfeedback_decls);
4574 } else {
4575 /* Linking the stages in the opposite order (from fragment to vertex)
4576 * ensures that inter-shader outputs written to in an earlier stage
4577 * are eliminated if they are (transitively) not used in a later
4578 * stage.
4579 */
4580 int next = last;
4581 for (int i = next - 1; i >= 0; i--) {
4582 if (prog->_LinkedShaders[i] == NULL)
4583 continue;
4584
4585 gl_shader *const sh_i = prog->_LinkedShaders[i];
4586 gl_shader *const sh_next = prog->_LinkedShaders[next];
4587
4588 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
4589 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4590 tfeedback_decls))
4591 goto done;
4592
4593 do_dead_builtin_varyings(ctx, sh_i, sh_next,
4594 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4595 tfeedback_decls);
4596
4597 /* This must be done after all dead varyings are eliminated. */
4598 if (!check_against_output_limit(ctx, prog, sh_i))
4599 goto done;
4600 if (!check_against_input_limit(ctx, prog, sh_next))
4601 goto done;
4602
4603 next = i;
4604 }
4605 }
4606 }
4607
4608 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls,
4609 has_xfb_qualifiers))
4610 goto done;
4611
4612 update_array_sizes(prog);
4613 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue,
4614 num_explicit_uniform_locs,
4615 ctx->Const.MaxUserAssignableUniformLocations);
4616 link_assign_atomic_counter_resources(ctx, prog);
4617 store_fragdepth_layout(prog);
4618
4619 link_calculate_subroutine_compat(prog);
4620 check_resources(ctx, prog);
4621 check_subroutine_resources(prog);
4622 check_image_resources(ctx, prog);
4623 link_check_atomic_counter_resources(ctx, prog);
4624
4625 if (!prog->LinkStatus)
4626 goto done;
4627
4628 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4629 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4630 * anything about shader linking when one of the shaders (vertex or
4631 * fragment shader) is absent. So, the extension shouldn't change the
4632 * behavior specified in GLSL specification.
4633 *
4634 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4635 * "Linking can fail for a variety of reasons as specified in the
4636 * OpenGL ES Shading Language Specification, as well as any of the
4637 * following reasons:
4638 *
4639 * ...
4640 *
4641 * * program contains objects to form either a vertex shader or
4642 * fragment shader, and program is not separable, and does not
4643 * contain objects to form both a vertex shader and fragment
4644 * shader."
4645 *
4646 * However, the only scenario in 3.1+ where we don't require them both is
4647 * when we have a compute shader. For example:
4648 *
4649 * - No shaders is a link error.
4650 * - Geom or Tess without a Vertex shader is a link error which means we
4651 * always require a Vertex shader and hence a Fragment shader.
4652 * - Finally a Compute shader linked with any other stage is a link error.
4653 */
4654 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
4655 num_shaders[MESA_SHADER_COMPUTE] == 0) {
4656 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
4657 linker_error(prog, "program lacks a vertex shader\n");
4658 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
4659 linker_error(prog, "program lacks a fragment shader\n");
4660 }
4661 }
4662
4663 /* Split BufferInterfaceBlocks into UniformBlocks and ShaderStorageBlocks
4664 * for gl_shader_program and gl_shader, so that drivers that need separate
4665 * index spaces for each set can have that.
4666 */
4667 for (unsigned i = MESA_SHADER_VERTEX; i < MESA_SHADER_STAGES; i++) {
4668 if (prog->_LinkedShaders[i] != NULL) {
4669 gl_shader *sh = prog->_LinkedShaders[i];
4670 split_ubos_and_ssbos(sh,
4671 sh->BufferInterfaceBlocks,
4672 NULL,
4673 sh->NumBufferInterfaceBlocks,
4674 &sh->UniformBlocks,
4675 &sh->NumUniformBlocks,
4676 &sh->ShaderStorageBlocks,
4677 &sh->NumShaderStorageBlocks);
4678 }
4679 }
4680
4681 split_ubos_and_ssbos(prog,
4682 NULL,
4683 prog->BufferInterfaceBlocks,
4684 prog->NumBufferInterfaceBlocks,
4685 &prog->UniformBlocks,
4686 &prog->NumUniformBlocks,
4687 &prog->ShaderStorageBlocks,
4688 &prog->NumShaderStorageBlocks);
4689
4690 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4691 if (prog->_LinkedShaders[i] == NULL)
4692 continue;
4693
4694 if (ctx->Const.ShaderCompilerOptions[i].LowerBufferInterfaceBlocks)
4695 lower_ubo_reference(prog->_LinkedShaders[i]);
4696
4697 if (ctx->Const.ShaderCompilerOptions[i].LowerShaderSharedVariables)
4698 lower_shared_reference(prog->_LinkedShaders[i],
4699 &prog->Comp.SharedSize);
4700
4701 lower_vector_derefs(prog->_LinkedShaders[i]);
4702 }
4703
4704 done:
4705 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4706 free(shader_list[i]);
4707 if (prog->_LinkedShaders[i] == NULL)
4708 continue;
4709
4710 /* Do a final validation step to make sure that the IR wasn't
4711 * invalidated by any modifications performed after intrastage linking.
4712 */
4713 validate_ir_tree(prog->_LinkedShaders[i]->ir);
4714
4715 /* Retain any live IR, but trash the rest. */
4716 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
4717
4718 /* The symbol table in the linked shaders may contain references to
4719 * variables that were removed (e.g., unused uniforms). Since it may
4720 * contain junk, there is no possible valid use. Delete it and set the
4721 * pointer to NULL.
4722 */
4723 delete prog->_LinkedShaders[i]->symbols;
4724 prog->_LinkedShaders[i]->symbols = NULL;
4725 }
4726
4727 ralloc_free(mem_ctx);
4728 }