a1a65ef627090dc03c1cd4fc699ad05b2275c79d
[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_inout_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_inout_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 mem_ctx Temporary ralloc context used for linking
2534 * \param prog Shader program whose variables need locations assigned
2535 * \param constants Driver specific constant values for the program.
2536 * \param target_index Selector for the program target to receive location
2537 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2538 * \c MESA_SHADER_FRAGMENT.
2539 *
2540 * \return
2541 * If locations are successfully assigned, true is returned. Otherwise an
2542 * error is emitted to the shader link log and false is returned.
2543 */
2544 bool
2545 assign_attribute_or_color_locations(void *mem_ctx,
2546 gl_shader_program *prog,
2547 struct gl_constants *constants,
2548 unsigned target_index)
2549 {
2550 /* Maximum number of generic locations. This corresponds to either the
2551 * maximum number of draw buffers or the maximum number of generic
2552 * attributes.
2553 */
2554 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2555 constants->Program[target_index].MaxAttribs :
2556 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2557
2558 /* Mark invalid locations as being used.
2559 */
2560 unsigned used_locations = (max_index >= 32)
2561 ? ~0 : ~((1 << max_index) - 1);
2562 unsigned double_storage_locations = 0;
2563
2564 assert((target_index == MESA_SHADER_VERTEX)
2565 || (target_index == MESA_SHADER_FRAGMENT));
2566
2567 gl_linked_shader *const sh = prog->_LinkedShaders[target_index];
2568 if (sh == NULL)
2569 return true;
2570
2571 /* Operate in a total of four passes.
2572 *
2573 * 1. Invalidate the location assignments for all vertex shader inputs.
2574 *
2575 * 2. Assign locations for inputs that have user-defined (via
2576 * glBindVertexAttribLocation) locations and outputs that have
2577 * user-defined locations (via glBindFragDataLocation).
2578 *
2579 * 3. Sort the attributes without assigned locations by number of slots
2580 * required in decreasing order. Fragmentation caused by attribute
2581 * locations assigned by the application may prevent large attributes
2582 * from having enough contiguous space.
2583 *
2584 * 4. Assign locations to any inputs without assigned locations.
2585 */
2586
2587 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2588 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2589
2590 const enum ir_variable_mode direction =
2591 (target_index == MESA_SHADER_VERTEX)
2592 ? ir_var_shader_in : ir_var_shader_out;
2593
2594
2595 /* Temporary storage for the set of attributes that need locations assigned.
2596 */
2597 struct temp_attr {
2598 unsigned slots;
2599 ir_variable *var;
2600
2601 /* Used below in the call to qsort. */
2602 static int compare(const void *a, const void *b)
2603 {
2604 const temp_attr *const l = (const temp_attr *) a;
2605 const temp_attr *const r = (const temp_attr *) b;
2606
2607 /* Reversed because we want a descending order sort below. */
2608 return r->slots - l->slots;
2609 }
2610 } to_assign[32];
2611 assert(max_index <= 32);
2612
2613 /* Temporary array for the set of attributes that have locations assigned.
2614 */
2615 ir_variable *assigned[16];
2616
2617 unsigned num_attr = 0;
2618 unsigned assigned_attr = 0;
2619
2620 foreach_in_list(ir_instruction, node, sh->ir) {
2621 ir_variable *const var = node->as_variable();
2622
2623 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2624 continue;
2625
2626 if (var->data.explicit_location) {
2627 var->data.is_unmatched_generic_inout = 0;
2628 if ((var->data.location >= (int)(max_index + generic_base))
2629 || (var->data.location < 0)) {
2630 linker_error(prog,
2631 "invalid explicit location %d specified for `%s'\n",
2632 (var->data.location < 0)
2633 ? var->data.location
2634 : var->data.location - generic_base,
2635 var->name);
2636 return false;
2637 }
2638 } else if (target_index == MESA_SHADER_VERTEX) {
2639 unsigned binding;
2640
2641 if (prog->AttributeBindings->get(binding, var->name)) {
2642 assert(binding >= VERT_ATTRIB_GENERIC0);
2643 var->data.location = binding;
2644 var->data.is_unmatched_generic_inout = 0;
2645 }
2646 } else if (target_index == MESA_SHADER_FRAGMENT) {
2647 unsigned binding;
2648 unsigned index;
2649 const char *name = var->name;
2650 const glsl_type *type = var->type;
2651
2652 while (type) {
2653 /* Check if there's a binding for the variable name */
2654 if (prog->FragDataBindings->get(binding, name)) {
2655 assert(binding >= FRAG_RESULT_DATA0);
2656 var->data.location = binding;
2657 var->data.is_unmatched_generic_inout = 0;
2658
2659 if (prog->FragDataIndexBindings->get(index, name)) {
2660 var->data.index = index;
2661 }
2662 break;
2663 }
2664
2665 /* If not, but it's an array type, look for name[0] */
2666 if (type->is_array()) {
2667 name = ralloc_asprintf(mem_ctx, "%s[0]", name);
2668 type = type->fields.array;
2669 continue;
2670 }
2671
2672 break;
2673 }
2674 }
2675
2676 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2677 *
2678 * "Output binding assignments will cause LinkProgram to fail:
2679 * ...
2680 * If the program has an active output assigned to a location greater
2681 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2682 * an active output assigned an index greater than or equal to one;"
2683 */
2684 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2685 var->data.location - generic_base >=
2686 (int) constants->MaxDualSourceDrawBuffers) {
2687 linker_error(prog,
2688 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2689 "with index %u for %s\n",
2690 var->data.location - generic_base, var->data.index,
2691 var->name);
2692 return false;
2693 }
2694
2695 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2696
2697 /* If the variable is not a built-in and has a location statically
2698 * assigned in the shader (presumably via a layout qualifier), make sure
2699 * that it doesn't collide with other assigned locations. Otherwise,
2700 * add it to the list of variables that need linker-assigned locations.
2701 */
2702 if (var->data.location != -1) {
2703 if (var->data.location >= generic_base && var->data.index < 1) {
2704 /* From page 61 of the OpenGL 4.0 spec:
2705 *
2706 * "LinkProgram will fail if the attribute bindings assigned
2707 * by BindAttribLocation do not leave not enough space to
2708 * assign a location for an active matrix attribute or an
2709 * active attribute array, both of which require multiple
2710 * contiguous generic attributes."
2711 *
2712 * I think above text prohibits the aliasing of explicit and
2713 * automatic assignments. But, aliasing is allowed in manual
2714 * assignments of attribute locations. See below comments for
2715 * the details.
2716 *
2717 * From OpenGL 4.0 spec, page 61:
2718 *
2719 * "It is possible for an application to bind more than one
2720 * attribute name to the same location. This is referred to as
2721 * aliasing. This will only work if only one of the aliased
2722 * attributes is active in the executable program, or if no
2723 * path through the shader consumes more than one attribute of
2724 * a set of attributes aliased to the same location. A link
2725 * error can occur if the linker determines that every path
2726 * through the shader consumes multiple aliased attributes,
2727 * but implementations are not required to generate an error
2728 * in this case."
2729 *
2730 * From GLSL 4.30 spec, page 54:
2731 *
2732 * "A program will fail to link if any two non-vertex shader
2733 * input variables are assigned to the same location. For
2734 * vertex shaders, multiple input variables may be assigned
2735 * to the same location using either layout qualifiers or via
2736 * the OpenGL API. However, such aliasing is intended only to
2737 * support vertex shaders where each execution path accesses
2738 * at most one input per each location. Implementations are
2739 * permitted, but not required, to generate link-time errors
2740 * if they detect that every path through the vertex shader
2741 * executable accesses multiple inputs assigned to any single
2742 * location. For all shader types, a program will fail to link
2743 * if explicit location assignments leave the linker unable
2744 * to find space for other variables without explicit
2745 * assignments."
2746 *
2747 * From OpenGL ES 3.0 spec, page 56:
2748 *
2749 * "Binding more than one attribute name to the same location
2750 * is referred to as aliasing, and is not permitted in OpenGL
2751 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2752 * fail when this condition exists. However, aliasing is
2753 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2754 * This will only work if only one of the aliased attributes
2755 * is active in the executable program, or if no path through
2756 * the shader consumes more than one attribute of a set of
2757 * attributes aliased to the same location. A link error can
2758 * occur if the linker determines that every path through the
2759 * shader consumes multiple aliased attributes, but implemen-
2760 * tations are not required to generate an error in this case."
2761 *
2762 * After looking at above references from OpenGL, OpenGL ES and
2763 * GLSL specifications, we allow aliasing of vertex input variables
2764 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2765 *
2766 * NOTE: This is not required by the spec but its worth mentioning
2767 * here that we're not doing anything to make sure that no path
2768 * through the vertex shader executable accesses multiple inputs
2769 * assigned to any single location.
2770 */
2771
2772 /* Mask representing the contiguous slots that will be used by
2773 * this attribute.
2774 */
2775 const unsigned attr = var->data.location - generic_base;
2776 const unsigned use_mask = (1 << slots) - 1;
2777 const char *const string = (target_index == MESA_SHADER_VERTEX)
2778 ? "vertex shader input" : "fragment shader output";
2779
2780 /* Generate a link error if the requested locations for this
2781 * attribute exceed the maximum allowed attribute location.
2782 */
2783 if (attr + slots > max_index) {
2784 linker_error(prog,
2785 "insufficient contiguous locations "
2786 "available for %s `%s' %d %d %d\n", string,
2787 var->name, used_locations, use_mask, attr);
2788 return false;
2789 }
2790
2791 /* Generate a link error if the set of bits requested for this
2792 * attribute overlaps any previously allocated bits.
2793 */
2794 if ((~(use_mask << attr) & used_locations) != used_locations) {
2795 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
2796 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2797 * 4.40 spec:
2798 *
2799 * "Additionally, for fragment shader outputs, if two
2800 * variables are placed within the same location, they
2801 * must have the same underlying type (floating-point or
2802 * integer). No component aliasing of output variables or
2803 * members is allowed.
2804 */
2805 for (unsigned i = 0; i < assigned_attr; i++) {
2806 unsigned assigned_slots =
2807 assigned[i]->type->count_attribute_slots(false);
2808 unsigned assig_attr =
2809 assigned[i]->data.location - generic_base;
2810 unsigned assigned_use_mask = (1 << assigned_slots) - 1;
2811
2812 if ((assigned_use_mask << assig_attr) &
2813 (use_mask << attr)) {
2814
2815 const glsl_type *assigned_type =
2816 assigned[i]->type->without_array();
2817 const glsl_type *type = var->type->without_array();
2818 if (assigned_type->base_type != type->base_type) {
2819 linker_error(prog, "types do not match for aliased"
2820 " %ss %s and %s\n", string,
2821 assigned[i]->name, var->name);
2822 return false;
2823 }
2824
2825 unsigned assigned_component_mask =
2826 ((1 << assigned_type->vector_elements) - 1) <<
2827 assigned[i]->data.location_frac;
2828 unsigned component_mask =
2829 ((1 << type->vector_elements) - 1) <<
2830 var->data.location_frac;
2831 if (assigned_component_mask & component_mask) {
2832 linker_error(prog, "overlapping component is "
2833 "assigned to %ss %s and %s "
2834 "(component=%d)\n",
2835 string, assigned[i]->name, var->name,
2836 var->data.location_frac);
2837 return false;
2838 }
2839 }
2840 }
2841 } else if (target_index == MESA_SHADER_FRAGMENT ||
2842 (prog->IsES && prog->Version >= 300)) {
2843 linker_error(prog, "overlapping location is assigned "
2844 "to %s `%s' %d %d %d\n", string, var->name,
2845 used_locations, use_mask, attr);
2846 return false;
2847 } else {
2848 linker_warning(prog, "overlapping location is assigned "
2849 "to %s `%s' %d %d %d\n", string, var->name,
2850 used_locations, use_mask, attr);
2851 }
2852 }
2853
2854 used_locations |= (use_mask << attr);
2855
2856 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2857 *
2858 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2859 * active attribute variables may fail to link, unless
2860 * device-dependent optimizations are able to make the program
2861 * fit within available hardware resources. For the purposes
2862 * of this test, attribute variables of the type dvec3, dvec4,
2863 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2864 * count as consuming twice as many attributes as equivalent
2865 * single-precision types. While these types use the same number
2866 * of generic attributes as their single-precision equivalents,
2867 * implementations are permitted to consume two single-precision
2868 * vectors of internal storage for each three- or four-component
2869 * double-precision vector."
2870 *
2871 * Mark this attribute slot as taking up twice as much space
2872 * so we can count it properly against limits. According to
2873 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2874 * is optional behavior, but it seems preferable.
2875 */
2876 if (var->type->without_array()->is_dual_slot())
2877 double_storage_locations |= (use_mask << attr);
2878 }
2879
2880 assigned[assigned_attr] = var;
2881 assigned_attr++;
2882
2883 continue;
2884 }
2885
2886 if (num_attr >= max_index) {
2887 linker_error(prog, "too many %s (max %u)",
2888 target_index == MESA_SHADER_VERTEX ?
2889 "vertex shader inputs" : "fragment shader outputs",
2890 max_index);
2891 return false;
2892 }
2893 to_assign[num_attr].slots = slots;
2894 to_assign[num_attr].var = var;
2895 num_attr++;
2896 }
2897
2898 if (target_index == MESA_SHADER_VERTEX) {
2899 unsigned total_attribs_size =
2900 _mesa_bitcount(used_locations & ((1 << max_index) - 1)) +
2901 _mesa_bitcount(double_storage_locations);
2902 if (total_attribs_size > max_index) {
2903 linker_error(prog,
2904 "attempt to use %d vertex attribute slots only %d available ",
2905 total_attribs_size, max_index);
2906 return false;
2907 }
2908 }
2909
2910 /* If all of the attributes were assigned locations by the application (or
2911 * are built-in attributes with fixed locations), return early. This should
2912 * be the common case.
2913 */
2914 if (num_attr == 0)
2915 return true;
2916
2917 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2918
2919 if (target_index == MESA_SHADER_VERTEX) {
2920 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2921 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2922 * reserved to prevent it from being automatically allocated below.
2923 */
2924 find_deref_visitor find("gl_Vertex");
2925 find.run(sh->ir);
2926 if (find.variable_found())
2927 used_locations |= (1 << 0);
2928 }
2929
2930 for (unsigned i = 0; i < num_attr; i++) {
2931 /* Mask representing the contiguous slots that will be used by this
2932 * attribute.
2933 */
2934 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2935
2936 int location = find_available_slots(used_locations, to_assign[i].slots);
2937
2938 if (location < 0) {
2939 const char *const string = (target_index == MESA_SHADER_VERTEX)
2940 ? "vertex shader input" : "fragment shader output";
2941
2942 linker_error(prog,
2943 "insufficient contiguous locations "
2944 "available for %s `%s'\n",
2945 string, to_assign[i].var->name);
2946 return false;
2947 }
2948
2949 to_assign[i].var->data.location = generic_base + location;
2950 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2951 used_locations |= (use_mask << location);
2952
2953 if (to_assign[i].var->type->without_array()->is_dual_slot())
2954 double_storage_locations |= (use_mask << location);
2955 }
2956
2957 /* Now that we have all the locations, from the GL 4.5 core spec, section
2958 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
2959 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
2960 * as equivalent single-precision types.
2961 */
2962 if (target_index == MESA_SHADER_VERTEX) {
2963 unsigned total_attribs_size =
2964 _mesa_bitcount(used_locations & ((1 << max_index) - 1)) +
2965 _mesa_bitcount(double_storage_locations);
2966 if (total_attribs_size > max_index) {
2967 linker_error(prog,
2968 "attempt to use %d vertex attribute slots only %d available ",
2969 total_attribs_size, max_index);
2970 return false;
2971 }
2972 }
2973
2974 return true;
2975 }
2976
2977 /**
2978 * Match explicit locations of outputs to inputs and deactivate the
2979 * unmatch flag if found so we don't optimise them away.
2980 */
2981 static void
2982 match_explicit_outputs_to_inputs(gl_linked_shader *producer,
2983 gl_linked_shader *consumer)
2984 {
2985 glsl_symbol_table parameters;
2986 ir_variable *explicit_locations[MAX_VARYINGS_INCL_PATCH][4] =
2987 { {NULL, NULL} };
2988
2989 /* Find all shader outputs in the "producer" stage.
2990 */
2991 foreach_in_list(ir_instruction, node, producer->ir) {
2992 ir_variable *const var = node->as_variable();
2993
2994 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
2995 continue;
2996
2997 if (var->data.explicit_location &&
2998 var->data.location >= VARYING_SLOT_VAR0) {
2999 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
3000 if (explicit_locations[idx][var->data.location_frac] == NULL)
3001 explicit_locations[idx][var->data.location_frac] = var;
3002 }
3003 }
3004
3005 /* Match inputs to outputs */
3006 foreach_in_list(ir_instruction, node, consumer->ir) {
3007 ir_variable *const input = node->as_variable();
3008
3009 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
3010 continue;
3011
3012 ir_variable *output = NULL;
3013 if (input->data.explicit_location
3014 && input->data.location >= VARYING_SLOT_VAR0) {
3015 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0]
3016 [input->data.location_frac];
3017
3018 if (output != NULL){
3019 input->data.is_unmatched_generic_inout = 0;
3020 output->data.is_unmatched_generic_inout = 0;
3021 }
3022 }
3023 }
3024 }
3025
3026 /**
3027 * Store the gl_FragDepth layout in the gl_shader_program struct.
3028 */
3029 static void
3030 store_fragdepth_layout(struct gl_shader_program *prog)
3031 {
3032 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3033 return;
3034 }
3035
3036 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
3037
3038 /* We don't look up the gl_FragDepth symbol directly because if
3039 * gl_FragDepth is not used in the shader, it's removed from the IR.
3040 * However, the symbol won't be removed from the symbol table.
3041 *
3042 * We're only interested in the cases where the variable is NOT removed
3043 * from the IR.
3044 */
3045 foreach_in_list(ir_instruction, node, ir) {
3046 ir_variable *const var = node->as_variable();
3047
3048 if (var == NULL || var->data.mode != ir_var_shader_out) {
3049 continue;
3050 }
3051
3052 if (strcmp(var->name, "gl_FragDepth") == 0) {
3053 switch (var->data.depth_layout) {
3054 case ir_depth_layout_none:
3055 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
3056 return;
3057 case ir_depth_layout_any:
3058 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
3059 return;
3060 case ir_depth_layout_greater:
3061 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
3062 return;
3063 case ir_depth_layout_less:
3064 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
3065 return;
3066 case ir_depth_layout_unchanged:
3067 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3068 return;
3069 default:
3070 assert(0);
3071 return;
3072 }
3073 }
3074 }
3075 }
3076
3077 /**
3078 * Validate the resources used by a program versus the implementation limits
3079 */
3080 static void
3081 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3082 {
3083 unsigned total_uniform_blocks = 0;
3084 unsigned total_shader_storage_blocks = 0;
3085
3086 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3087 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3088
3089 if (sh == NULL)
3090 continue;
3091
3092 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
3093 linker_error(prog, "Too many %s shader texture samplers\n",
3094 _mesa_shader_stage_to_string(i));
3095 }
3096
3097 if (sh->num_uniform_components >
3098 ctx->Const.Program[i].MaxUniformComponents) {
3099 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3100 linker_warning(prog, "Too many %s shader default uniform block "
3101 "components, but the driver will try to optimize "
3102 "them out; this is non-portable out-of-spec "
3103 "behavior\n",
3104 _mesa_shader_stage_to_string(i));
3105 } else {
3106 linker_error(prog, "Too many %s shader default uniform block "
3107 "components\n",
3108 _mesa_shader_stage_to_string(i));
3109 }
3110 }
3111
3112 if (sh->num_combined_uniform_components >
3113 ctx->Const.Program[i].MaxCombinedUniformComponents) {
3114 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3115 linker_warning(prog, "Too many %s shader uniform components, "
3116 "but the driver will try to optimize them out; "
3117 "this is non-portable out-of-spec behavior\n",
3118 _mesa_shader_stage_to_string(i));
3119 } else {
3120 linker_error(prog, "Too many %s shader uniform components\n",
3121 _mesa_shader_stage_to_string(i));
3122 }
3123 }
3124
3125 total_shader_storage_blocks += sh->NumShaderStorageBlocks;
3126 total_uniform_blocks += sh->NumUniformBlocks;
3127
3128 const unsigned max_uniform_blocks =
3129 ctx->Const.Program[i].MaxUniformBlocks;
3130 if (max_uniform_blocks < sh->NumUniformBlocks) {
3131 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
3132 _mesa_shader_stage_to_string(i), sh->NumUniformBlocks,
3133 max_uniform_blocks);
3134 }
3135
3136 const unsigned max_shader_storage_blocks =
3137 ctx->Const.Program[i].MaxShaderStorageBlocks;
3138 if (max_shader_storage_blocks < sh->NumShaderStorageBlocks) {
3139 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
3140 _mesa_shader_stage_to_string(i),
3141 sh->NumShaderStorageBlocks, max_shader_storage_blocks);
3142 }
3143 }
3144
3145 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
3146 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
3147 total_uniform_blocks, ctx->Const.MaxCombinedUniformBlocks);
3148 }
3149
3150 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
3151 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
3152 total_shader_storage_blocks,
3153 ctx->Const.MaxCombinedShaderStorageBlocks);
3154 }
3155
3156 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
3157 if (prog->UniformBlocks[i].UniformBufferSize >
3158 ctx->Const.MaxUniformBlockSize) {
3159 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
3160 prog->UniformBlocks[i].Name,
3161 prog->UniformBlocks[i].UniformBufferSize,
3162 ctx->Const.MaxUniformBlockSize);
3163 }
3164 }
3165
3166 for (unsigned i = 0; i < prog->NumShaderStorageBlocks; i++) {
3167 if (prog->ShaderStorageBlocks[i].UniformBufferSize >
3168 ctx->Const.MaxShaderStorageBlockSize) {
3169 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
3170 prog->ShaderStorageBlocks[i].Name,
3171 prog->ShaderStorageBlocks[i].UniformBufferSize,
3172 ctx->Const.MaxShaderStorageBlockSize);
3173 }
3174 }
3175 }
3176
3177 static void
3178 link_calculate_subroutine_compat(struct gl_shader_program *prog)
3179 {
3180 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3181 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3182 int count;
3183 if (!sh)
3184 continue;
3185
3186 for (unsigned j = 0; j < sh->NumSubroutineUniformRemapTable; j++) {
3187 if (sh->SubroutineUniformRemapTable[j] == INACTIVE_UNIFORM_EXPLICIT_LOCATION)
3188 continue;
3189
3190 struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[j];
3191
3192 if (!uni)
3193 continue;
3194
3195 sh->NumSubroutineUniforms++;
3196 count = 0;
3197 if (sh->NumSubroutineFunctions == 0) {
3198 linker_error(prog, "subroutine uniform %s defined but no valid functions found\n", uni->type->name);
3199 continue;
3200 }
3201 for (unsigned f = 0; f < sh->NumSubroutineFunctions; f++) {
3202 struct gl_subroutine_function *fn = &sh->SubroutineFunctions[f];
3203 for (int k = 0; k < fn->num_compat_types; k++) {
3204 if (fn->types[k] == uni->type) {
3205 count++;
3206 break;
3207 }
3208 }
3209 }
3210 uni->num_compatible_subroutines = count;
3211 }
3212 }
3213 }
3214
3215 static void
3216 check_subroutine_resources(struct gl_shader_program *prog)
3217 {
3218 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3219 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3220
3221 if (sh) {
3222 if (sh->NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS)
3223 linker_error(prog, "Too many %s shader subroutine uniforms\n",
3224 _mesa_shader_stage_to_string(i));
3225 }
3226 }
3227 }
3228 /**
3229 * Validate shader image resources.
3230 */
3231 static void
3232 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3233 {
3234 unsigned total_image_units = 0;
3235 unsigned fragment_outputs = 0;
3236 unsigned total_shader_storage_blocks = 0;
3237
3238 if (!ctx->Extensions.ARB_shader_image_load_store)
3239 return;
3240
3241 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3242 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3243
3244 if (sh) {
3245 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
3246 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
3247 _mesa_shader_stage_to_string(i), sh->NumImages,
3248 ctx->Const.Program[i].MaxImageUniforms);
3249
3250 total_image_units += sh->NumImages;
3251 total_shader_storage_blocks += sh->NumShaderStorageBlocks;
3252
3253 if (i == MESA_SHADER_FRAGMENT) {
3254 foreach_in_list(ir_instruction, node, sh->ir) {
3255 ir_variable *var = node->as_variable();
3256 if (var && var->data.mode == ir_var_shader_out)
3257 /* since there are no double fs outputs - pass false */
3258 fragment_outputs += var->type->count_attribute_slots(false);
3259 }
3260 }
3261 }
3262 }
3263
3264 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3265 linker_error(prog, "Too many combined image uniforms\n");
3266
3267 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3268 ctx->Const.MaxCombinedShaderOutputResources)
3269 linker_error(prog, "Too many combined image uniforms, shader storage "
3270 " buffers and fragment outputs\n");
3271 }
3272
3273
3274 /**
3275 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3276 * for a variable, checks for overlaps between other uniforms using explicit
3277 * locations.
3278 */
3279 static int
3280 reserve_explicit_locations(struct gl_shader_program *prog,
3281 string_to_uint_map *map, ir_variable *var)
3282 {
3283 unsigned slots = var->type->uniform_locations();
3284 unsigned max_loc = var->data.location + slots - 1;
3285 unsigned return_value = slots;
3286
3287 /* Resize remap table if locations do not fit in the current one. */
3288 if (max_loc + 1 > prog->NumUniformRemapTable) {
3289 prog->UniformRemapTable =
3290 reralloc(prog, prog->UniformRemapTable,
3291 gl_uniform_storage *,
3292 max_loc + 1);
3293
3294 if (!prog->UniformRemapTable) {
3295 linker_error(prog, "Out of memory during linking.\n");
3296 return -1;
3297 }
3298
3299 /* Initialize allocated space. */
3300 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3301 prog->UniformRemapTable[i] = NULL;
3302
3303 prog->NumUniformRemapTable = max_loc + 1;
3304 }
3305
3306 for (unsigned i = 0; i < slots; i++) {
3307 unsigned loc = var->data.location + i;
3308
3309 /* Check if location is already used. */
3310 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3311
3312 /* Possibly same uniform from a different stage, this is ok. */
3313 unsigned hash_loc;
3314 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3315 return_value = 0;
3316 continue;
3317 }
3318
3319 /* ARB_explicit_uniform_location specification states:
3320 *
3321 * "No two default-block uniform variables in the program can have
3322 * the same location, even if they are unused, otherwise a compiler
3323 * or linker error will be generated."
3324 */
3325 linker_error(prog,
3326 "location qualifier for uniform %s overlaps "
3327 "previously used location\n",
3328 var->name);
3329 return -1;
3330 }
3331
3332 /* Initialize location as inactive before optimization
3333 * rounds and location assignment.
3334 */
3335 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3336 }
3337
3338 /* Note, base location used for arrays. */
3339 map->put(var->data.location, var->name);
3340
3341 return return_value;
3342 }
3343
3344 static bool
3345 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3346 struct gl_linked_shader *sh,
3347 ir_variable *var)
3348 {
3349 unsigned slots = var->type->uniform_locations();
3350 unsigned max_loc = var->data.location + slots - 1;
3351
3352 /* Resize remap table if locations do not fit in the current one. */
3353 if (max_loc + 1 > sh->NumSubroutineUniformRemapTable) {
3354 sh->SubroutineUniformRemapTable =
3355 reralloc(sh, sh->SubroutineUniformRemapTable,
3356 gl_uniform_storage *,
3357 max_loc + 1);
3358
3359 if (!sh->SubroutineUniformRemapTable) {
3360 linker_error(prog, "Out of memory during linking.\n");
3361 return false;
3362 }
3363
3364 /* Initialize allocated space. */
3365 for (unsigned i = sh->NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3366 sh->SubroutineUniformRemapTable[i] = NULL;
3367
3368 sh->NumSubroutineUniformRemapTable = max_loc + 1;
3369 }
3370
3371 for (unsigned i = 0; i < slots; i++) {
3372 unsigned loc = var->data.location + i;
3373
3374 /* Check if location is already used. */
3375 if (sh->SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3376
3377 /* ARB_explicit_uniform_location specification states:
3378 * "No two subroutine uniform variables can have the same location
3379 * in the same shader stage, otherwise a compiler or linker error
3380 * will be generated."
3381 */
3382 linker_error(prog,
3383 "location qualifier for uniform %s overlaps "
3384 "previously used location\n",
3385 var->name);
3386 return false;
3387 }
3388
3389 /* Initialize location as inactive before optimization
3390 * rounds and location assignment.
3391 */
3392 sh->SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3393 }
3394
3395 return true;
3396 }
3397 /**
3398 * Check and reserve all explicit uniform locations, called before
3399 * any optimizations happen to handle also inactive uniforms and
3400 * inactive array elements that may get trimmed away.
3401 */
3402 static unsigned
3403 check_explicit_uniform_locations(struct gl_context *ctx,
3404 struct gl_shader_program *prog)
3405 {
3406 if (!ctx->Extensions.ARB_explicit_uniform_location)
3407 return 0;
3408
3409 /* This map is used to detect if overlapping explicit locations
3410 * occur with the same uniform (from different stage) or a different one.
3411 */
3412 string_to_uint_map *uniform_map = new string_to_uint_map;
3413
3414 if (!uniform_map) {
3415 linker_error(prog, "Out of memory during linking.\n");
3416 return 0;
3417 }
3418
3419 unsigned entries_total = 0;
3420 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3421 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3422
3423 if (!sh)
3424 continue;
3425
3426 foreach_in_list(ir_instruction, node, sh->ir) {
3427 ir_variable *var = node->as_variable();
3428 if (!var || var->data.mode != ir_var_uniform)
3429 continue;
3430
3431 if (var->data.explicit_location) {
3432 bool ret = false;
3433 if (var->type->without_array()->is_subroutine())
3434 ret = reserve_subroutine_explicit_locations(prog, sh, var);
3435 else {
3436 int slots = reserve_explicit_locations(prog, uniform_map,
3437 var);
3438 if (slots != -1) {
3439 ret = true;
3440 entries_total += slots;
3441 }
3442 }
3443 if (!ret) {
3444 delete uniform_map;
3445 return 0;
3446 }
3447 }
3448 }
3449 }
3450
3451 struct empty_uniform_block *current_block = NULL;
3452
3453 for (unsigned i = 0; i < prog->NumUniformRemapTable; i++) {
3454 /* We found empty space in UniformRemapTable. */
3455 if (prog->UniformRemapTable[i] == NULL) {
3456 /* We've found the beginning of a new continous block of empty slots */
3457 if (!current_block || current_block->start + current_block->slots != i) {
3458 current_block = rzalloc(prog, struct empty_uniform_block);
3459 current_block->start = i;
3460 exec_list_push_tail(&prog->EmptyUniformLocations,
3461 &current_block->link);
3462 }
3463
3464 /* The current block continues, so we simply increment its slots */
3465 current_block->slots++;
3466 }
3467 }
3468
3469 delete uniform_map;
3470 return entries_total;
3471 }
3472
3473 static bool
3474 should_add_buffer_variable(struct gl_shader_program *shProg,
3475 GLenum type, const char *name)
3476 {
3477 bool found_interface = false;
3478 unsigned block_name_len = 0;
3479 const char *block_name_dot = strchr(name, '.');
3480
3481 /* These rules only apply to buffer variables. So we return
3482 * true for the rest of types.
3483 */
3484 if (type != GL_BUFFER_VARIABLE)
3485 return true;
3486
3487 for (unsigned i = 0; i < shProg->NumShaderStorageBlocks; i++) {
3488 const char *block_name = shProg->ShaderStorageBlocks[i].Name;
3489 block_name_len = strlen(block_name);
3490
3491 const char *block_square_bracket = strchr(block_name, '[');
3492 if (block_square_bracket) {
3493 /* The block is part of an array of named interfaces,
3494 * for the name comparison we ignore the "[x]" part.
3495 */
3496 block_name_len -= strlen(block_square_bracket);
3497 }
3498
3499 if (block_name_dot) {
3500 /* Check if the variable name starts with the interface
3501 * name. The interface name (if present) should have the
3502 * length than the interface block name we are comparing to.
3503 */
3504 unsigned len = strlen(name) - strlen(block_name_dot);
3505 if (len != block_name_len)
3506 continue;
3507 }
3508
3509 if (strncmp(block_name, name, block_name_len) == 0) {
3510 found_interface = true;
3511 break;
3512 }
3513 }
3514
3515 /* We remove the interface name from the buffer variable name,
3516 * including the dot that follows it.
3517 */
3518 if (found_interface)
3519 name = name + block_name_len + 1;
3520
3521 /* The ARB_program_interface_query spec says:
3522 *
3523 * "For an active shader storage block member declared as an array, an
3524 * entry will be generated only for the first array element, regardless
3525 * of its type. For arrays of aggregate types, the enumeration rules
3526 * are applied recursively for the single enumerated array element."
3527 */
3528 const char *struct_first_dot = strchr(name, '.');
3529 const char *first_square_bracket = strchr(name, '[');
3530
3531 /* The buffer variable is on top level and it is not an array */
3532 if (!first_square_bracket) {
3533 return true;
3534 /* The shader storage block member is a struct, then generate the entry */
3535 } else if (struct_first_dot && struct_first_dot < first_square_bracket) {
3536 return true;
3537 } else {
3538 /* Shader storage block member is an array, only generate an entry for the
3539 * first array element.
3540 */
3541 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3542 return true;
3543 }
3544
3545 return false;
3546 }
3547
3548 static bool
3549 add_program_resource(struct gl_shader_program *prog,
3550 struct set *resource_set,
3551 GLenum type, const void *data, uint8_t stages)
3552 {
3553 assert(data);
3554
3555 /* If resource already exists, do not add it again. */
3556 if (_mesa_set_search(resource_set, data))
3557 return true;
3558
3559 prog->ProgramResourceList =
3560 reralloc(prog,
3561 prog->ProgramResourceList,
3562 gl_program_resource,
3563 prog->NumProgramResourceList + 1);
3564
3565 if (!prog->ProgramResourceList) {
3566 linker_error(prog, "Out of memory during linking.\n");
3567 return false;
3568 }
3569
3570 struct gl_program_resource *res =
3571 &prog->ProgramResourceList[prog->NumProgramResourceList];
3572
3573 res->Type = type;
3574 res->Data = data;
3575 res->StageReferences = stages;
3576
3577 prog->NumProgramResourceList++;
3578
3579 _mesa_set_add(resource_set, data);
3580
3581 return true;
3582 }
3583
3584 /* Function checks if a variable var is a packed varying and
3585 * if given name is part of packed varying's list.
3586 *
3587 * If a variable is a packed varying, it has a name like
3588 * 'packed:a,b,c' where a, b and c are separate variables.
3589 */
3590 static bool
3591 included_in_packed_varying(ir_variable *var, const char *name)
3592 {
3593 if (strncmp(var->name, "packed:", 7) != 0)
3594 return false;
3595
3596 char *list = strdup(var->name + 7);
3597 assert(list);
3598
3599 bool found = false;
3600 char *saveptr;
3601 char *token = strtok_r(list, ",", &saveptr);
3602 while (token) {
3603 if (strcmp(token, name) == 0) {
3604 found = true;
3605 break;
3606 }
3607 token = strtok_r(NULL, ",", &saveptr);
3608 }
3609 free(list);
3610 return found;
3611 }
3612
3613 /**
3614 * Function builds a stage reference bitmask from variable name.
3615 */
3616 static uint8_t
3617 build_stageref(struct gl_shader_program *shProg, const char *name,
3618 unsigned mode)
3619 {
3620 uint8_t stages = 0;
3621
3622 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3623 * used for reference mask in gl_program_resource will need to be changed.
3624 */
3625 assert(MESA_SHADER_STAGES < 8);
3626
3627 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3628 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
3629 if (!sh)
3630 continue;
3631
3632 /* Shader symbol table may contain variables that have
3633 * been optimized away. Search IR for the variable instead.
3634 */
3635 foreach_in_list(ir_instruction, node, sh->ir) {
3636 ir_variable *var = node->as_variable();
3637 if (var) {
3638 unsigned baselen = strlen(var->name);
3639
3640 if (included_in_packed_varying(var, name)) {
3641 stages |= (1 << i);
3642 break;
3643 }
3644
3645 /* Type needs to match if specified, otherwise we might
3646 * pick a variable with same name but different interface.
3647 */
3648 if (var->data.mode != mode)
3649 continue;
3650
3651 if (strncmp(var->name, name, baselen) == 0) {
3652 /* Check for exact name matches but also check for arrays and
3653 * structs.
3654 */
3655 if (name[baselen] == '\0' ||
3656 name[baselen] == '[' ||
3657 name[baselen] == '.') {
3658 stages |= (1 << i);
3659 break;
3660 }
3661 }
3662 }
3663 }
3664 }
3665 return stages;
3666 }
3667
3668 /**
3669 * Create gl_shader_variable from ir_variable class.
3670 */
3671 static gl_shader_variable *
3672 create_shader_variable(struct gl_shader_program *shProg,
3673 const ir_variable *in,
3674 const char *name, const glsl_type *type,
3675 bool use_implicit_location, int location,
3676 const glsl_type *outermost_struct_type)
3677 {
3678 gl_shader_variable *out = ralloc(shProg, struct gl_shader_variable);
3679 if (!out)
3680 return NULL;
3681
3682 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3683 * expect to see gl_VertexID in the program resource list. Pretend.
3684 */
3685 if (in->data.mode == ir_var_system_value &&
3686 in->data.location == SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) {
3687 out->name = ralloc_strdup(shProg, "gl_VertexID");
3688 } else if ((in->data.mode == ir_var_shader_out &&
3689 in->data.location == VARYING_SLOT_TESS_LEVEL_OUTER) ||
3690 (in->data.mode == ir_var_system_value &&
3691 in->data.location == SYSTEM_VALUE_TESS_LEVEL_OUTER)) {
3692 out->name = ralloc_strdup(shProg, "gl_TessLevelOuter");
3693 type = glsl_type::get_array_instance(glsl_type::float_type, 4);
3694 } else if ((in->data.mode == ir_var_shader_out &&
3695 in->data.location == VARYING_SLOT_TESS_LEVEL_INNER) ||
3696 (in->data.mode == ir_var_system_value &&
3697 in->data.location == SYSTEM_VALUE_TESS_LEVEL_INNER)) {
3698 out->name = ralloc_strdup(shProg, "gl_TessLevelInner");
3699 type = glsl_type::get_array_instance(glsl_type::float_type, 2);
3700 } else {
3701 out->name = ralloc_strdup(shProg, name);
3702 }
3703
3704 if (!out->name)
3705 return NULL;
3706
3707 /* The ARB_program_interface_query spec says:
3708 *
3709 * "Not all active variables are assigned valid locations; the
3710 * following variables will have an effective location of -1:
3711 *
3712 * * uniforms declared as atomic counters;
3713 *
3714 * * members of a uniform block;
3715 *
3716 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3717 *
3718 * * inputs or outputs not declared with a "location" layout
3719 * qualifier, except for vertex shader inputs and fragment shader
3720 * outputs."
3721 */
3722 if (in->type->base_type == GLSL_TYPE_ATOMIC_UINT ||
3723 is_gl_identifier(in->name) ||
3724 !(in->data.explicit_location || use_implicit_location)) {
3725 out->location = -1;
3726 } else {
3727 out->location = location;
3728 }
3729
3730 out->type = type;
3731 out->outermost_struct_type = outermost_struct_type;
3732 out->interface_type = in->get_interface_type();
3733 out->component = in->data.location_frac;
3734 out->index = in->data.index;
3735 out->patch = in->data.patch;
3736 out->mode = in->data.mode;
3737 out->interpolation = in->data.interpolation;
3738 out->explicit_location = in->data.explicit_location;
3739 out->precision = in->data.precision;
3740
3741 return out;
3742 }
3743
3744 static bool
3745 add_shader_variable(struct gl_shader_program *shProg, struct set *resource_set,
3746 unsigned stage_mask,
3747 GLenum programInterface, ir_variable *var,
3748 const char *name, const glsl_type *type,
3749 bool use_implicit_location, int location,
3750 const glsl_type *outermost_struct_type = NULL)
3751 {
3752 const bool is_vertex_input =
3753 programInterface == GL_PROGRAM_INPUT &&
3754 stage_mask == MESA_SHADER_VERTEX;
3755
3756 switch (type->base_type) {
3757 case GLSL_TYPE_STRUCT: {
3758 /* The ARB_program_interface_query spec says:
3759 *
3760 * "For an active variable declared as a structure, a separate entry
3761 * will be generated for each active structure member. The name of
3762 * each entry is formed by concatenating the name of the structure,
3763 * the "." character, and the name of the structure member. If a
3764 * structure member to enumerate is itself a structure or array,
3765 * these enumeration rules are applied recursively."
3766 */
3767 if (outermost_struct_type == NULL)
3768 outermost_struct_type = type;
3769
3770 unsigned field_location = location;
3771 for (unsigned i = 0; i < type->length; i++) {
3772 const struct glsl_struct_field *field = &type->fields.structure[i];
3773 char *field_name = ralloc_asprintf(shProg, "%s.%s", name, field->name);
3774 if (!add_shader_variable(shProg, resource_set,
3775 stage_mask, programInterface,
3776 var, field_name, field->type,
3777 use_implicit_location, field_location,
3778 outermost_struct_type))
3779 return false;
3780
3781 field_location +=
3782 field->type->count_attribute_slots(is_vertex_input);
3783 }
3784 return true;
3785 }
3786
3787 default: {
3788 /* Issue #16 of the ARB_program_interface_query spec says:
3789 *
3790 * "* If a variable is a member of an interface block without an
3791 * instance name, it is enumerated using just the variable name.
3792 *
3793 * * If a variable is a member of an interface block with an instance
3794 * name, it is enumerated as "BlockName.Member", where "BlockName" is
3795 * the name of the interface block (not the instance name) and
3796 * "Member" is the name of the variable."
3797 */
3798 const char *prefixed_name = (var->data.from_named_ifc_block &&
3799 !is_gl_identifier(var->name))
3800 ? ralloc_asprintf(shProg, "%s.%s", var->get_interface_type()->name,
3801 name)
3802 : name;
3803
3804 /* The ARB_program_interface_query spec says:
3805 *
3806 * "For an active variable declared as a single instance of a basic
3807 * type, a single entry will be generated, using the variable name
3808 * from the shader source."
3809 */
3810 gl_shader_variable *sha_v =
3811 create_shader_variable(shProg, var, prefixed_name, type,
3812 use_implicit_location, location,
3813 outermost_struct_type);
3814 if (!sha_v)
3815 return false;
3816
3817 return add_program_resource(shProg, resource_set,
3818 programInterface, sha_v, stage_mask);
3819 }
3820 }
3821 }
3822
3823 static bool
3824 add_interface_variables(struct gl_shader_program *shProg,
3825 struct set *resource_set,
3826 unsigned stage, GLenum programInterface)
3827 {
3828 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
3829
3830 foreach_in_list(ir_instruction, node, ir) {
3831 ir_variable *var = node->as_variable();
3832
3833 if (!var || var->data.how_declared == ir_var_hidden)
3834 continue;
3835
3836 int loc_bias;
3837
3838 switch (var->data.mode) {
3839 case ir_var_system_value:
3840 case ir_var_shader_in:
3841 if (programInterface != GL_PROGRAM_INPUT)
3842 continue;
3843 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
3844 : int(VARYING_SLOT_VAR0);
3845 break;
3846 case ir_var_shader_out:
3847 if (programInterface != GL_PROGRAM_OUTPUT)
3848 continue;
3849 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
3850 : int(VARYING_SLOT_VAR0);
3851 break;
3852 default:
3853 continue;
3854 };
3855
3856 if (var->data.patch)
3857 loc_bias = int(VARYING_SLOT_PATCH0);
3858
3859 /* Skip packed varyings, packed varyings are handled separately
3860 * by add_packed_varyings.
3861 */
3862 if (strncmp(var->name, "packed:", 7) == 0)
3863 continue;
3864
3865 /* Skip fragdata arrays, these are handled separately
3866 * by add_fragdata_arrays.
3867 */
3868 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
3869 continue;
3870
3871 const bool vs_input_or_fs_output =
3872 (stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
3873 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out);
3874
3875 if (!add_shader_variable(shProg, resource_set,
3876 1 << stage, programInterface,
3877 var, var->name, var->type, vs_input_or_fs_output,
3878 var->data.location - loc_bias))
3879 return false;
3880 }
3881 return true;
3882 }
3883
3884 static bool
3885 add_packed_varyings(struct gl_shader_program *shProg, struct set *resource_set,
3886 int stage, GLenum type)
3887 {
3888 struct gl_linked_shader *sh = shProg->_LinkedShaders[stage];
3889 GLenum iface;
3890
3891 if (!sh || !sh->packed_varyings)
3892 return true;
3893
3894 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
3895 ir_variable *var = node->as_variable();
3896 if (var) {
3897 switch (var->data.mode) {
3898 case ir_var_shader_in:
3899 iface = GL_PROGRAM_INPUT;
3900 break;
3901 case ir_var_shader_out:
3902 iface = GL_PROGRAM_OUTPUT;
3903 break;
3904 default:
3905 unreachable("unexpected type");
3906 }
3907
3908 if (type == iface) {
3909 const int stage_mask =
3910 build_stageref(shProg, var->name, var->data.mode);
3911 if (!add_shader_variable(shProg, resource_set,
3912 stage_mask,
3913 iface, var, var->name, var->type, false,
3914 var->data.location - VARYING_SLOT_VAR0))
3915 return false;
3916 }
3917 }
3918 }
3919 return true;
3920 }
3921
3922 static bool
3923 add_fragdata_arrays(struct gl_shader_program *shProg, struct set *resource_set)
3924 {
3925 struct gl_linked_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
3926
3927 if (!sh || !sh->fragdata_arrays)
3928 return true;
3929
3930 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
3931 ir_variable *var = node->as_variable();
3932 if (var) {
3933 assert(var->data.mode == ir_var_shader_out);
3934
3935 if (!add_shader_variable(shProg, resource_set,
3936 1 << MESA_SHADER_FRAGMENT,
3937 GL_PROGRAM_OUTPUT, var, var->name, var->type,
3938 true, var->data.location - FRAG_RESULT_DATA0))
3939 return false;
3940 }
3941 }
3942 return true;
3943 }
3944
3945 static char*
3946 get_top_level_name(const char *name)
3947 {
3948 const char *first_dot = strchr(name, '.');
3949 const char *first_square_bracket = strchr(name, '[');
3950 int name_size = 0;
3951
3952 /* The ARB_program_interface_query spec says:
3953 *
3954 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3955 * the number of active array elements of the top-level shader storage
3956 * block member containing to the active variable is written to
3957 * <params>. If the top-level block member is not declared as an
3958 * array, the value one is written to <params>. If the top-level block
3959 * member is an array with no declared size, the value zero is written
3960 * to <params>."
3961 */
3962
3963 /* The buffer variable is on top level.*/
3964 if (!first_square_bracket && !first_dot)
3965 name_size = strlen(name);
3966 else if ((!first_square_bracket ||
3967 (first_dot && first_dot < first_square_bracket)))
3968 name_size = first_dot - name;
3969 else
3970 name_size = first_square_bracket - name;
3971
3972 return strndup(name, name_size);
3973 }
3974
3975 static char*
3976 get_var_name(const char *name)
3977 {
3978 const char *first_dot = strchr(name, '.');
3979
3980 if (!first_dot)
3981 return strdup(name);
3982
3983 return strndup(first_dot+1, strlen(first_dot) - 1);
3984 }
3985
3986 static bool
3987 is_top_level_shader_storage_block_member(const char* name,
3988 const char* interface_name,
3989 const char* field_name)
3990 {
3991 bool result = false;
3992
3993 /* If the given variable is already a top-level shader storage
3994 * block member, then return array_size = 1.
3995 * We could have two possibilities: if we have an instanced
3996 * shader storage block or not instanced.
3997 *
3998 * For the first, we check create a name as it was in top level and
3999 * compare it with the real name. If they are the same, then
4000 * the variable is already at top-level.
4001 *
4002 * Full instanced name is: interface name + '.' + var name +
4003 * NULL character
4004 */
4005 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
4006 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
4007 if (!full_instanced_name) {
4008 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
4009 return false;
4010 }
4011
4012 snprintf(full_instanced_name, name_length, "%s.%s",
4013 interface_name, field_name);
4014
4015 /* Check if its top-level shader storage block member of an
4016 * instanced interface block, or of a unnamed interface block.
4017 */
4018 if (strcmp(name, full_instanced_name) == 0 ||
4019 strcmp(name, field_name) == 0)
4020 result = true;
4021
4022 free(full_instanced_name);
4023 return result;
4024 }
4025
4026 static int
4027 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
4028 char *interface_name, char *var_name)
4029 {
4030 /* The ARB_program_interface_query spec says:
4031 *
4032 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4033 * the number of active array elements of the top-level shader storage
4034 * block member containing to the active variable is written to
4035 * <params>. If the top-level block member is not declared as an
4036 * array, the value one is written to <params>. If the top-level block
4037 * member is an array with no declared size, the value zero is written
4038 * to <params>."
4039 */
4040 if (is_top_level_shader_storage_block_member(uni->name,
4041 interface_name,
4042 var_name))
4043 return 1;
4044 else if (field->type->is_unsized_array())
4045 return 0;
4046 else if (field->type->is_array())
4047 return field->type->length;
4048
4049 return 1;
4050 }
4051
4052 static int
4053 get_array_stride(struct gl_uniform_storage *uni, const glsl_type *interface,
4054 const glsl_struct_field *field, char *interface_name,
4055 char *var_name)
4056 {
4057 /* The ARB_program_interface_query spec says:
4058 *
4059 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4060 * identifying the stride between array elements of the top-level
4061 * shader storage block member containing the active variable is
4062 * written to <params>. For top-level block members declared as
4063 * arrays, the value written is the difference, in basic machine units,
4064 * between the offsets of the active variable for consecutive elements
4065 * in the top-level array. For top-level block members not declared as
4066 * an array, zero is written to <params>."
4067 */
4068 if (field->type->is_array()) {
4069 const enum glsl_matrix_layout matrix_layout =
4070 glsl_matrix_layout(field->matrix_layout);
4071 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
4072 const glsl_type *array_type = field->type->fields.array;
4073
4074 if (is_top_level_shader_storage_block_member(uni->name,
4075 interface_name,
4076 var_name))
4077 return 0;
4078
4079 if (interface->interface_packing != GLSL_INTERFACE_PACKING_STD430) {
4080 if (array_type->is_record() || array_type->is_array())
4081 return glsl_align(array_type->std140_size(row_major), 16);
4082 else
4083 return MAX2(array_type->std140_base_alignment(row_major), 16);
4084 } else {
4085 return array_type->std430_array_stride(row_major);
4086 }
4087 }
4088 return 0;
4089 }
4090
4091 static void
4092 calculate_array_size_and_stride(struct gl_shader_program *shProg,
4093 struct gl_uniform_storage *uni)
4094 {
4095 int block_index = uni->block_index;
4096 int array_size = -1;
4097 int array_stride = -1;
4098 char *var_name = get_top_level_name(uni->name);
4099 char *interface_name =
4100 get_top_level_name(uni->is_shader_storage ?
4101 shProg->ShaderStorageBlocks[block_index].Name :
4102 shProg->UniformBlocks[block_index].Name);
4103
4104 if (strcmp(var_name, interface_name) == 0) {
4105 /* Deal with instanced array of SSBOs */
4106 char *temp_name = get_var_name(uni->name);
4107 if (!temp_name) {
4108 linker_error(shProg, "Out of memory during linking.\n");
4109 goto write_top_level_array_size_and_stride;
4110 }
4111 free(var_name);
4112 var_name = get_top_level_name(temp_name);
4113 free(temp_name);
4114 if (!var_name) {
4115 linker_error(shProg, "Out of memory during linking.\n");
4116 goto write_top_level_array_size_and_stride;
4117 }
4118 }
4119
4120 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4121 const gl_linked_shader *sh = shProg->_LinkedShaders[i];
4122 if (sh == NULL)
4123 continue;
4124
4125 foreach_in_list(ir_instruction, node, sh->ir) {
4126 ir_variable *var = node->as_variable();
4127 if (!var || !var->get_interface_type() ||
4128 var->data.mode != ir_var_shader_storage)
4129 continue;
4130
4131 const glsl_type *interface = var->get_interface_type();
4132
4133 if (strcmp(interface_name, interface->name) != 0)
4134 continue;
4135
4136 for (unsigned i = 0; i < interface->length; i++) {
4137 const glsl_struct_field *field = &interface->fields.structure[i];
4138 if (strcmp(field->name, var_name) != 0)
4139 continue;
4140
4141 array_stride = get_array_stride(uni, interface, field,
4142 interface_name, var_name);
4143 array_size = get_array_size(uni, field, interface_name, var_name);
4144 goto write_top_level_array_size_and_stride;
4145 }
4146 }
4147 }
4148 write_top_level_array_size_and_stride:
4149 free(interface_name);
4150 free(var_name);
4151 uni->top_level_array_stride = array_stride;
4152 uni->top_level_array_size = array_size;
4153 }
4154
4155 /**
4156 * Builds up a list of program resources that point to existing
4157 * resource data.
4158 */
4159 void
4160 build_program_resource_list(struct gl_context *ctx,
4161 struct gl_shader_program *shProg)
4162 {
4163 /* Rebuild resource list. */
4164 if (shProg->ProgramResourceList) {
4165 ralloc_free(shProg->ProgramResourceList);
4166 shProg->ProgramResourceList = NULL;
4167 shProg->NumProgramResourceList = 0;
4168 }
4169
4170 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
4171
4172 /* Determine first input and final output stage. These are used to
4173 * detect which variables should be enumerated in the resource list
4174 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4175 */
4176 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4177 if (!shProg->_LinkedShaders[i])
4178 continue;
4179 if (input_stage == MESA_SHADER_STAGES)
4180 input_stage = i;
4181 output_stage = i;
4182 }
4183
4184 /* Empty shader, no resources. */
4185 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
4186 return;
4187
4188 struct set *resource_set = _mesa_set_create(NULL,
4189 _mesa_hash_pointer,
4190 _mesa_key_pointer_equal);
4191
4192 /* Program interface needs to expose varyings in case of SSO. */
4193 if (shProg->SeparateShader) {
4194 if (!add_packed_varyings(shProg, resource_set,
4195 input_stage, GL_PROGRAM_INPUT))
4196 return;
4197
4198 if (!add_packed_varyings(shProg, resource_set,
4199 output_stage, GL_PROGRAM_OUTPUT))
4200 return;
4201 }
4202
4203 if (!add_fragdata_arrays(shProg, resource_set))
4204 return;
4205
4206 /* Add inputs and outputs to the resource list. */
4207 if (!add_interface_variables(shProg, resource_set,
4208 input_stage, GL_PROGRAM_INPUT))
4209 return;
4210
4211 if (!add_interface_variables(shProg, resource_set,
4212 output_stage, GL_PROGRAM_OUTPUT))
4213 return;
4214
4215 /* Add transform feedback varyings. */
4216 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
4217 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
4218 if (!add_program_resource(shProg, resource_set,
4219 GL_TRANSFORM_FEEDBACK_VARYING,
4220 &shProg->LinkedTransformFeedback.Varyings[i],
4221 0))
4222 return;
4223 }
4224 }
4225
4226 /* Add transform feedback buffers. */
4227 for (unsigned i = 0; i < ctx->Const.MaxTransformFeedbackBuffers; i++) {
4228 if ((shProg->LinkedTransformFeedback.ActiveBuffers >> i) & 1) {
4229 shProg->LinkedTransformFeedback.Buffers[i].Binding = i;
4230 if (!add_program_resource(shProg, resource_set,
4231 GL_TRANSFORM_FEEDBACK_BUFFER,
4232 &shProg->LinkedTransformFeedback.Buffers[i],
4233 0))
4234 return;
4235 }
4236 }
4237
4238 /* Add uniforms from uniform storage. */
4239 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
4240 /* Do not add uniforms internally used by Mesa. */
4241 if (shProg->UniformStorage[i].hidden)
4242 continue;
4243
4244 uint8_t stageref =
4245 build_stageref(shProg, shProg->UniformStorage[i].name,
4246 ir_var_uniform);
4247
4248 /* Add stagereferences for uniforms in a uniform block. */
4249 bool is_shader_storage = shProg->UniformStorage[i].is_shader_storage;
4250 int block_index = shProg->UniformStorage[i].block_index;
4251 if (block_index != -1) {
4252 stageref |= is_shader_storage ?
4253 shProg->ShaderStorageBlocks[block_index].stageref :
4254 shProg->UniformBlocks[block_index].stageref;
4255 }
4256
4257 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
4258 if (!should_add_buffer_variable(shProg, type,
4259 shProg->UniformStorage[i].name))
4260 continue;
4261
4262 if (is_shader_storage) {
4263 calculate_array_size_and_stride(shProg, &shProg->UniformStorage[i]);
4264 }
4265
4266 if (!add_program_resource(shProg, resource_set, type,
4267 &shProg->UniformStorage[i], stageref))
4268 return;
4269 }
4270
4271 /* Add program uniform blocks. */
4272 for (unsigned i = 0; i < shProg->NumUniformBlocks; i++) {
4273 if (!add_program_resource(shProg, resource_set, GL_UNIFORM_BLOCK,
4274 &shProg->UniformBlocks[i], 0))
4275 return;
4276 }
4277
4278 /* Add program shader storage blocks. */
4279 for (unsigned i = 0; i < shProg->NumShaderStorageBlocks; i++) {
4280 if (!add_program_resource(shProg, resource_set, GL_SHADER_STORAGE_BLOCK,
4281 &shProg->ShaderStorageBlocks[i], 0))
4282 return;
4283 }
4284
4285 /* Add atomic counter buffers. */
4286 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
4287 if (!add_program_resource(shProg, resource_set, GL_ATOMIC_COUNTER_BUFFER,
4288 &shProg->AtomicBuffers[i], 0))
4289 return;
4290 }
4291
4292 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
4293 GLenum type;
4294 if (!shProg->UniformStorage[i].hidden)
4295 continue;
4296
4297 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
4298 if (!shProg->UniformStorage[i].opaque[j].active ||
4299 !shProg->UniformStorage[i].type->is_subroutine())
4300 continue;
4301
4302 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
4303 /* add shader subroutines */
4304 if (!add_program_resource(shProg, resource_set,
4305 type, &shProg->UniformStorage[i], 0))
4306 return;
4307 }
4308 }
4309
4310 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4311 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
4312 GLuint type;
4313
4314 if (!sh)
4315 continue;
4316
4317 type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
4318 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4319 if (!add_program_resource(shProg, resource_set,
4320 type, &sh->SubroutineFunctions[j], 0))
4321 return;
4322 }
4323 }
4324
4325 _mesa_set_destroy(resource_set, NULL);
4326 }
4327
4328 /**
4329 * This check is done to make sure we allow only constant expression
4330 * indexing and "constant-index-expression" (indexing with an expression
4331 * that includes loop induction variable).
4332 */
4333 static bool
4334 validate_sampler_array_indexing(struct gl_context *ctx,
4335 struct gl_shader_program *prog)
4336 {
4337 dynamic_sampler_array_indexing_visitor v;
4338 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4339 if (prog->_LinkedShaders[i] == NULL)
4340 continue;
4341
4342 bool no_dynamic_indexing =
4343 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4344
4345 /* Search for array derefs in shader. */
4346 v.run(prog->_LinkedShaders[i]->ir);
4347 if (v.uses_dynamic_sampler_array_indexing()) {
4348 const char *msg = "sampler arrays indexed with non-constant "
4349 "expressions is forbidden in GLSL %s %u";
4350 /* Backend has indicated that it has no dynamic indexing support. */
4351 if (no_dynamic_indexing) {
4352 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
4353 return false;
4354 } else {
4355 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
4356 }
4357 }
4358 }
4359 return true;
4360 }
4361
4362 static void
4363 link_assign_subroutine_types(struct gl_shader_program *prog)
4364 {
4365 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4366 gl_linked_shader *sh = prog->_LinkedShaders[i];
4367
4368 if (sh == NULL)
4369 continue;
4370
4371 sh->MaxSubroutineFunctionIndex = 0;
4372 foreach_in_list(ir_instruction, node, sh->ir) {
4373 ir_function *fn = node->as_function();
4374 if (!fn)
4375 continue;
4376
4377 if (fn->is_subroutine)
4378 sh->NumSubroutineUniformTypes++;
4379
4380 if (!fn->num_subroutine_types)
4381 continue;
4382
4383 /* these should have been calculated earlier. */
4384 assert(fn->subroutine_index != -1);
4385 if (sh->NumSubroutineFunctions + 1 > MAX_SUBROUTINES) {
4386 linker_error(prog, "Too many subroutine functions declared.\n");
4387 return;
4388 }
4389 sh->SubroutineFunctions = reralloc(sh, sh->SubroutineFunctions,
4390 struct gl_subroutine_function,
4391 sh->NumSubroutineFunctions + 1);
4392 sh->SubroutineFunctions[sh->NumSubroutineFunctions].name = ralloc_strdup(sh, fn->name);
4393 sh->SubroutineFunctions[sh->NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
4394 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types =
4395 ralloc_array(sh, const struct glsl_type *,
4396 fn->num_subroutine_types);
4397
4398 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4399 * GLSL 4.5 spec:
4400 *
4401 * "Each subroutine with an index qualifier in the shader must be
4402 * given a unique index, otherwise a compile or link error will be
4403 * generated."
4404 */
4405 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4406 if (sh->SubroutineFunctions[j].index != -1 &&
4407 sh->SubroutineFunctions[j].index == fn->subroutine_index) {
4408 linker_error(prog, "each subroutine index qualifier in the "
4409 "shader must be unique\n");
4410 return;
4411 }
4412 }
4413 sh->SubroutineFunctions[sh->NumSubroutineFunctions].index =
4414 fn->subroutine_index;
4415
4416 if (fn->subroutine_index > (int)sh->MaxSubroutineFunctionIndex)
4417 sh->MaxSubroutineFunctionIndex = fn->subroutine_index;
4418
4419 for (int j = 0; j < fn->num_subroutine_types; j++)
4420 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4421 sh->NumSubroutineFunctions++;
4422 }
4423 }
4424 }
4425
4426 static void
4427 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4428 {
4429 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4430
4431 foreach_in_list(ir_instruction, node, ir) {
4432 ir_variable *const var = node->as_variable();
4433
4434 if (var == NULL || var->data.mode != io_mode)
4435 continue;
4436
4437 /* Don't set always active on builtins that haven't been redeclared */
4438 if (var->data.how_declared == ir_var_declared_implicitly)
4439 continue;
4440
4441 var->data.always_active_io = true;
4442 }
4443 }
4444
4445 /**
4446 * When separate shader programs are enabled, only input/outputs between
4447 * the stages of a multi-stage separate program can be safely removed
4448 * from the shader interface. Other inputs/outputs must remain active.
4449 */
4450 static void
4451 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4452 {
4453 unsigned first, last;
4454 assert(prog->SeparateShader);
4455
4456 first = MESA_SHADER_STAGES;
4457 last = 0;
4458
4459 /* Determine first and last stage. Excluding the compute stage */
4460 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4461 if (!prog->_LinkedShaders[i])
4462 continue;
4463 if (first == MESA_SHADER_STAGES)
4464 first = i;
4465 last = i;
4466 }
4467
4468 if (first == MESA_SHADER_STAGES)
4469 return;
4470
4471 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4472 gl_linked_shader *sh = prog->_LinkedShaders[stage];
4473 if (!sh)
4474 continue;
4475
4476 if (first == last) {
4477 /* For a single shader program only allow inputs to the vertex shader
4478 * and outputs from the fragment shader to be removed.
4479 */
4480 if (stage != MESA_SHADER_VERTEX)
4481 set_always_active_io(sh->ir, ir_var_shader_in);
4482 if (stage != MESA_SHADER_FRAGMENT)
4483 set_always_active_io(sh->ir, ir_var_shader_out);
4484 } else {
4485 /* For multi-stage separate shader programs only allow inputs and
4486 * outputs between the shader stages to be removed as well as inputs
4487 * to the vertex shader and outputs from the fragment shader.
4488 */
4489 if (stage == first && stage != MESA_SHADER_VERTEX)
4490 set_always_active_io(sh->ir, ir_var_shader_in);
4491 else if (stage == last && stage != MESA_SHADER_FRAGMENT)
4492 set_always_active_io(sh->ir, ir_var_shader_out);
4493 }
4494 }
4495 }
4496
4497 static bool
4498 link_varyings_and_uniforms(unsigned first, unsigned last,
4499 unsigned num_explicit_uniform_locs,
4500 struct gl_context *ctx,
4501 struct gl_shader_program *prog, void *mem_ctx)
4502 {
4503 bool has_xfb_qualifiers = false;
4504 unsigned num_tfeedback_decls = 0;
4505 char **varying_names = NULL;
4506 tfeedback_decl *tfeedback_decls = NULL;
4507
4508 /* Mark all generic shader inputs and outputs as unpaired. */
4509 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4510 if (prog->_LinkedShaders[i] != NULL) {
4511 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4512 }
4513 }
4514
4515 unsigned prev = first;
4516 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4517 if (prog->_LinkedShaders[i] == NULL)
4518 continue;
4519
4520 match_explicit_outputs_to_inputs(prog->_LinkedShaders[prev],
4521 prog->_LinkedShaders[i]);
4522 prev = i;
4523 }
4524
4525 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4526 MESA_SHADER_VERTEX)) {
4527 return false;
4528 }
4529
4530 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4531 MESA_SHADER_FRAGMENT)) {
4532 return false;
4533 }
4534
4535 /* From the ARB_enhanced_layouts spec:
4536 *
4537 * "If the shader used to record output variables for transform feedback
4538 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4539 * qualifiers, the values specified by TransformFeedbackVaryings are
4540 * ignored, and the set of variables captured for transform feedback is
4541 * instead derived from the specified layout qualifiers."
4542 */
4543 for (int i = MESA_SHADER_FRAGMENT - 1; i >= 0; i--) {
4544 /* Find last stage before fragment shader */
4545 if (prog->_LinkedShaders[i]) {
4546 has_xfb_qualifiers =
4547 process_xfb_layout_qualifiers(mem_ctx, prog->_LinkedShaders[i],
4548 &num_tfeedback_decls,
4549 &varying_names);
4550 break;
4551 }
4552 }
4553
4554 if (!has_xfb_qualifiers) {
4555 num_tfeedback_decls = prog->TransformFeedback.NumVarying;
4556 varying_names = prog->TransformFeedback.VaryingNames;
4557 }
4558
4559 if (num_tfeedback_decls != 0) {
4560 /* From GL_EXT_transform_feedback:
4561 * A program will fail to link if:
4562 *
4563 * * the <count> specified by TransformFeedbackVaryingsEXT is
4564 * non-zero, but the program object has no vertex or geometry
4565 * shader;
4566 */
4567 if (first >= MESA_SHADER_FRAGMENT) {
4568 linker_error(prog, "Transform feedback varyings specified, but "
4569 "no vertex, tessellation, or geometry shader is "
4570 "present.\n");
4571 return false;
4572 }
4573
4574 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
4575 num_tfeedback_decls);
4576 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
4577 varying_names, tfeedback_decls))
4578 return false;
4579 }
4580
4581 /* If there is no fragment shader we need to set transform feedback.
4582 *
4583 * For SSO we also need to assign output locations. We assign them here
4584 * because we need to do it for both single stage programs and multi stage
4585 * programs.
4586 */
4587 if (last < MESA_SHADER_FRAGMENT &&
4588 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
4589 const uint64_t reserved_out_slots =
4590 reserved_varying_slot(prog->_LinkedShaders[last], ir_var_shader_out);
4591 if (!assign_varying_locations(ctx, mem_ctx, prog,
4592 prog->_LinkedShaders[last], NULL,
4593 num_tfeedback_decls, tfeedback_decls,
4594 reserved_out_slots))
4595 return false;
4596 }
4597
4598 if (last <= MESA_SHADER_FRAGMENT) {
4599 /* Remove unused varyings from the first/last stage unless SSO */
4600 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4601 prog->_LinkedShaders[first],
4602 ir_var_shader_in);
4603 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4604 prog->_LinkedShaders[last],
4605 ir_var_shader_out);
4606
4607 /* If the program is made up of only a single stage */
4608 if (first == last) {
4609 gl_linked_shader *const sh = prog->_LinkedShaders[last];
4610
4611 do_dead_builtin_varyings(ctx, NULL, sh, 0, NULL);
4612 do_dead_builtin_varyings(ctx, sh, NULL, num_tfeedback_decls,
4613 tfeedback_decls);
4614
4615 if (prog->SeparateShader) {
4616 const uint64_t reserved_slots =
4617 reserved_varying_slot(sh, ir_var_shader_in);
4618
4619 /* Assign input locations for SSO, output locations are already
4620 * assigned.
4621 */
4622 if (!assign_varying_locations(ctx, mem_ctx, prog,
4623 NULL /* producer */,
4624 sh /* consumer */,
4625 0 /* num_tfeedback_decls */,
4626 NULL /* tfeedback_decls */,
4627 reserved_slots))
4628 return false;
4629 }
4630 } else {
4631 /* Linking the stages in the opposite order (from fragment to vertex)
4632 * ensures that inter-shader outputs written to in an earlier stage
4633 * are eliminated if they are (transitively) not used in a later
4634 * stage.
4635 */
4636 int next = last;
4637 for (int i = next - 1; i >= 0; i--) {
4638 if (prog->_LinkedShaders[i] == NULL && i != 0)
4639 continue;
4640
4641 gl_linked_shader *const sh_i = prog->_LinkedShaders[i];
4642 gl_linked_shader *const sh_next = prog->_LinkedShaders[next];
4643
4644 const uint64_t reserved_out_slots =
4645 reserved_varying_slot(sh_i, ir_var_shader_out);
4646 const uint64_t reserved_in_slots =
4647 reserved_varying_slot(sh_next, ir_var_shader_in);
4648
4649 do_dead_builtin_varyings(ctx, sh_i, sh_next,
4650 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4651 tfeedback_decls);
4652
4653 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
4654 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4655 tfeedback_decls,
4656 reserved_out_slots | reserved_in_slots))
4657 return false;
4658
4659 /* This must be done after all dead varyings are eliminated. */
4660 if (sh_i != NULL) {
4661 unsigned slots_used = _mesa_bitcount_64(reserved_out_slots);
4662 if (!check_against_output_limit(ctx, prog, sh_i, slots_used)) {
4663 return false;
4664 }
4665 }
4666
4667 unsigned slots_used = _mesa_bitcount_64(reserved_in_slots);
4668 if (!check_against_input_limit(ctx, prog, sh_next, slots_used))
4669 return false;
4670
4671 next = i;
4672 }
4673 }
4674 }
4675
4676 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls,
4677 has_xfb_qualifiers))
4678 return false;
4679
4680 update_array_sizes(prog);
4681 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue,
4682 num_explicit_uniform_locs,
4683 ctx->Const.MaxUserAssignableUniformLocations);
4684 link_assign_atomic_counter_resources(ctx, prog);
4685
4686 link_calculate_subroutine_compat(prog);
4687 check_resources(ctx, prog);
4688 check_subroutine_resources(prog);
4689 check_image_resources(ctx, prog);
4690 link_check_atomic_counter_resources(ctx, prog);
4691
4692 if (!prog->LinkStatus)
4693 return false;
4694
4695 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4696 if (prog->_LinkedShaders[i] == NULL)
4697 continue;
4698
4699 const struct gl_shader_compiler_options *options =
4700 &ctx->Const.ShaderCompilerOptions[i];
4701
4702 if (options->LowerBufferInterfaceBlocks)
4703 lower_ubo_reference(prog->_LinkedShaders[i],
4704 options->ClampBlockIndicesToArrayBounds);
4705
4706 if (options->LowerShaderSharedVariables)
4707 lower_shared_reference(prog->_LinkedShaders[i],
4708 &prog->Comp.SharedSize);
4709
4710 lower_vector_derefs(prog->_LinkedShaders[i]);
4711 do_vec_index_to_swizzle(prog->_LinkedShaders[i]->ir);
4712 }
4713
4714 return true;
4715 }
4716
4717 void
4718 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4719 {
4720 prog->LinkStatus = true; /* All error paths will set this to false */
4721 prog->Validated = false;
4722 prog->_Used = false;
4723
4724 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4725 *
4726 * "Linking can fail for a variety of reasons as specified in the
4727 * OpenGL Shading Language Specification, as well as any of the
4728 * following reasons:
4729 *
4730 * - No shader objects are attached to program."
4731 *
4732 * The Compatibility Profile specification does not list the error. In
4733 * Compatibility Profile missing shader stages are replaced by
4734 * fixed-function. This applies to the case where all stages are
4735 * missing.
4736 */
4737 if (prog->NumShaders == 0) {
4738 if (ctx->API != API_OPENGL_COMPAT)
4739 linker_error(prog, "no shaders attached to the program\n");
4740 return;
4741 }
4742
4743 unsigned int num_explicit_uniform_locs = 0;
4744
4745 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4746
4747 prog->ARB_fragment_coord_conventions_enable = false;
4748
4749 /* Separate the shaders into groups based on their type.
4750 */
4751 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4752 unsigned num_shaders[MESA_SHADER_STAGES];
4753
4754 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4755 shader_list[i] = (struct gl_shader **)
4756 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4757 num_shaders[i] = 0;
4758 }
4759
4760 unsigned min_version = UINT_MAX;
4761 unsigned max_version = 0;
4762 for (unsigned i = 0; i < prog->NumShaders; i++) {
4763 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4764 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4765
4766 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4767 linker_error(prog, "all shaders must use same shading "
4768 "language version\n");
4769 goto done;
4770 }
4771
4772 if (prog->Shaders[i]->info.ARB_fragment_coord_conventions_enable) {
4773 prog->ARB_fragment_coord_conventions_enable = true;
4774 }
4775
4776 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4777 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4778 num_shaders[shader_type]++;
4779 }
4780
4781 /* In desktop GLSL, different shader versions may be linked together. In
4782 * GLSL ES, all shader versions must be the same.
4783 */
4784 if (prog->Shaders[0]->IsES && min_version != max_version) {
4785 linker_error(prog, "all shaders must use same shading "
4786 "language version\n");
4787 goto done;
4788 }
4789
4790 prog->Version = max_version;
4791 prog->IsES = prog->Shaders[0]->IsES;
4792
4793 /* Some shaders have to be linked with some other shaders present.
4794 */
4795 if (!prog->SeparateShader) {
4796 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4797 num_shaders[MESA_SHADER_VERTEX] == 0) {
4798 linker_error(prog, "Geometry shader must be linked with "
4799 "vertex shader\n");
4800 goto done;
4801 }
4802 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4803 num_shaders[MESA_SHADER_VERTEX] == 0) {
4804 linker_error(prog, "Tessellation evaluation shader must be linked "
4805 "with vertex shader\n");
4806 goto done;
4807 }
4808 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4809 num_shaders[MESA_SHADER_VERTEX] == 0) {
4810 linker_error(prog, "Tessellation control shader must be linked with "
4811 "vertex shader\n");
4812 goto done;
4813 }
4814
4815 /* The spec is self-contradictory here. It allows linking without a tess
4816 * eval shader, but that can only be used with transform feedback and
4817 * rasterization disabled. However, transform feedback isn't allowed
4818 * with GL_PATCHES, so it can't be used.
4819 *
4820 * More investigation showed that the idea of transform feedback after
4821 * a tess control shader was dropped, because some hw vendors couldn't
4822 * support tessellation without a tess eval shader, but the linker
4823 * section wasn't updated to reflect that.
4824 *
4825 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4826 * spec bug.
4827 *
4828 * Do what's reasonable and always require a tess eval shader if a tess
4829 * control shader is present.
4830 */
4831 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4832 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4833 linker_error(prog, "Tessellation control shader must be linked with "
4834 "tessellation evaluation shader\n");
4835 goto done;
4836 }
4837 }
4838
4839 /* Compute shaders have additional restrictions. */
4840 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4841 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4842 linker_error(prog, "Compute shaders may not be linked with any other "
4843 "type of shader\n");
4844 }
4845
4846 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4847 if (prog->_LinkedShaders[i] != NULL) {
4848 _mesa_delete_linked_shader(ctx, prog->_LinkedShaders[i]);
4849 }
4850
4851 prog->_LinkedShaders[i] = NULL;
4852 }
4853
4854 /* Link all shaders for a particular stage and validate the result.
4855 */
4856 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4857 if (num_shaders[stage] > 0) {
4858 gl_linked_shader *const sh =
4859 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4860 num_shaders[stage]);
4861
4862 if (!prog->LinkStatus) {
4863 if (sh)
4864 _mesa_delete_linked_shader(ctx, sh);
4865 goto done;
4866 }
4867
4868 switch (stage) {
4869 case MESA_SHADER_VERTEX:
4870 validate_vertex_shader_executable(prog, sh, ctx);
4871 break;
4872 case MESA_SHADER_TESS_CTRL:
4873 /* nothing to be done */
4874 break;
4875 case MESA_SHADER_TESS_EVAL:
4876 validate_tess_eval_shader_executable(prog, sh, ctx);
4877 break;
4878 case MESA_SHADER_GEOMETRY:
4879 validate_geometry_shader_executable(prog, sh, ctx);
4880 break;
4881 case MESA_SHADER_FRAGMENT:
4882 validate_fragment_shader_executable(prog, sh);
4883 break;
4884 }
4885 if (!prog->LinkStatus) {
4886 if (sh)
4887 _mesa_delete_linked_shader(ctx, sh);
4888 goto done;
4889 }
4890
4891 prog->_LinkedShaders[stage] = sh;
4892 }
4893 }
4894
4895 if (num_shaders[MESA_SHADER_GEOMETRY] > 0) {
4896 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
4897 prog->LastCullDistanceArraySize = prog->Geom.CullDistanceArraySize;
4898 } else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0) {
4899 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
4900 prog->LastCullDistanceArraySize = prog->TessEval.CullDistanceArraySize;
4901 } else if (num_shaders[MESA_SHADER_VERTEX] > 0) {
4902 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
4903 prog->LastCullDistanceArraySize = prog->Vert.CullDistanceArraySize;
4904 } else {
4905 prog->LastClipDistanceArraySize = 0; /* Not used */
4906 prog->LastCullDistanceArraySize = 0; /* Not used */
4907 }
4908
4909 /* Here begins the inter-stage linking phase. Some initial validation is
4910 * performed, then locations are assigned for uniforms, attributes, and
4911 * varyings.
4912 */
4913 cross_validate_uniforms(prog);
4914 if (!prog->LinkStatus)
4915 goto done;
4916
4917 unsigned first, last, prev;
4918
4919 first = MESA_SHADER_STAGES;
4920 last = 0;
4921
4922 /* Determine first and last stage. */
4923 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4924 if (!prog->_LinkedShaders[i])
4925 continue;
4926 if (first == MESA_SHADER_STAGES)
4927 first = i;
4928 last = i;
4929 }
4930
4931 num_explicit_uniform_locs = check_explicit_uniform_locations(ctx, prog);
4932 link_assign_subroutine_types(prog);
4933
4934 if (!prog->LinkStatus)
4935 goto done;
4936
4937 resize_tes_inputs(ctx, prog);
4938
4939 /* Validate the inputs of each stage with the output of the preceding
4940 * stage.
4941 */
4942 prev = first;
4943 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4944 if (prog->_LinkedShaders[i] == NULL)
4945 continue;
4946
4947 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4948 prog->_LinkedShaders[i]);
4949 if (!prog->LinkStatus)
4950 goto done;
4951
4952 cross_validate_outputs_to_inputs(prog,
4953 prog->_LinkedShaders[prev],
4954 prog->_LinkedShaders[i]);
4955 if (!prog->LinkStatus)
4956 goto done;
4957
4958 prev = i;
4959 }
4960
4961 /* Cross-validate uniform blocks between shader stages */
4962 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
4963 if (!prog->LinkStatus)
4964 goto done;
4965
4966 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4967 if (prog->_LinkedShaders[i] != NULL)
4968 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
4969 }
4970
4971 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4972 * it before optimization because we want most of the checks to get
4973 * dropped thanks to constant propagation.
4974 *
4975 * This rule also applies to GLSL ES 3.00.
4976 */
4977 if (max_version >= (prog->IsES ? 300 : 130)) {
4978 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4979 if (sh) {
4980 lower_discard_flow(sh->ir);
4981 }
4982 }
4983
4984 if (prog->SeparateShader)
4985 disable_varying_optimizations_for_sso(prog);
4986
4987 /* Process UBOs */
4988 if (!interstage_cross_validate_uniform_blocks(prog, false))
4989 goto done;
4990
4991 /* Process SSBOs */
4992 if (!interstage_cross_validate_uniform_blocks(prog, true))
4993 goto done;
4994
4995 /* Do common optimization before assigning storage for attributes,
4996 * uniforms, and varyings. Later optimization could possibly make
4997 * some of that unused.
4998 */
4999 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5000 if (prog->_LinkedShaders[i] == NULL)
5001 continue;
5002
5003 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
5004 if (!prog->LinkStatus)
5005 goto done;
5006
5007 if (ctx->Const.ShaderCompilerOptions[i].LowerCombinedClipCullDistance) {
5008 lower_clip_cull_distance(prog, prog->_LinkedShaders[i]);
5009 }
5010
5011 if (ctx->Const.LowerTessLevel) {
5012 lower_tess_level(prog->_LinkedShaders[i]);
5013 }
5014
5015 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
5016 &ctx->Const.ShaderCompilerOptions[i],
5017 ctx->Const.NativeIntegers))
5018 ;
5019
5020 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
5021 propagate_invariance(prog->_LinkedShaders[i]->ir);
5022 }
5023
5024 /* Validation for special cases where we allow sampler array indexing
5025 * with loop induction variable. This check emits a warning or error
5026 * depending if backend can handle dynamic indexing.
5027 */
5028 if ((!prog->IsES && prog->Version < 130) ||
5029 (prog->IsES && prog->Version < 300)) {
5030 if (!validate_sampler_array_indexing(ctx, prog))
5031 goto done;
5032 }
5033
5034 /* Check and validate stream emissions in geometry shaders */
5035 validate_geometry_shader_emissions(ctx, prog);
5036
5037 store_fragdepth_layout(prog);
5038
5039 if(!link_varyings_and_uniforms(first, last, num_explicit_uniform_locs, ctx,
5040 prog, mem_ctx))
5041 goto done;
5042
5043 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5044 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5045 * anything about shader linking when one of the shaders (vertex or
5046 * fragment shader) is absent. So, the extension shouldn't change the
5047 * behavior specified in GLSL specification.
5048 *
5049 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5050 * "Linking can fail for a variety of reasons as specified in the
5051 * OpenGL ES Shading Language Specification, as well as any of the
5052 * following reasons:
5053 *
5054 * ...
5055 *
5056 * * program contains objects to form either a vertex shader or
5057 * fragment shader, and program is not separable, and does not
5058 * contain objects to form both a vertex shader and fragment
5059 * shader."
5060 *
5061 * However, the only scenario in 3.1+ where we don't require them both is
5062 * when we have a compute shader. For example:
5063 *
5064 * - No shaders is a link error.
5065 * - Geom or Tess without a Vertex shader is a link error which means we
5066 * always require a Vertex shader and hence a Fragment shader.
5067 * - Finally a Compute shader linked with any other stage is a link error.
5068 */
5069 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
5070 num_shaders[MESA_SHADER_COMPUTE] == 0) {
5071 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
5072 linker_error(prog, "program lacks a vertex shader\n");
5073 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
5074 linker_error(prog, "program lacks a fragment shader\n");
5075 }
5076 }
5077
5078 done:
5079 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5080 free(shader_list[i]);
5081 if (prog->_LinkedShaders[i] == NULL)
5082 continue;
5083
5084 /* Do a final validation step to make sure that the IR wasn't
5085 * invalidated by any modifications performed after intrastage linking.
5086 */
5087 validate_ir_tree(prog->_LinkedShaders[i]->ir);
5088
5089 /* Retain any live IR, but trash the rest. */
5090 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
5091
5092 /* The symbol table in the linked shaders may contain references to
5093 * variables that were removed (e.g., unused uniforms). Since it may
5094 * contain junk, there is no possible valid use. Delete it and set the
5095 * pointer to NULL.
5096 */
5097 delete prog->_LinkedShaders[i]->symbols;
5098 prog->_LinkedShaders[i]->symbols = NULL;
5099 }
5100
5101 ralloc_free(mem_ctx);
5102 }