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