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