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