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