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