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