glsl/linker: location aliasing requires types to have the same width
[mesa.git] / src / compiler / glsl / link_varyings.cpp
1 /*
2 * Copyright © 2012 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 link_varyings.cpp
26 *
27 * Linker functions related specifically to linking varyings between shader
28 * stages.
29 */
30
31
32 #include "main/errors.h"
33 #include "main/mtypes.h"
34 #include "glsl_symbol_table.h"
35 #include "glsl_parser_extras.h"
36 #include "ir_optimization.h"
37 #include "linker.h"
38 #include "link_varyings.h"
39 #include "main/macros.h"
40 #include "util/hash_table.h"
41 #include "util/u_math.h"
42 #include "program.h"
43
44
45 /**
46 * Get the varying type stripped of the outermost array if we're processing
47 * a stage whose varyings are arrays indexed by a vertex number (such as
48 * geometry shader inputs).
49 */
50 static const glsl_type *
51 get_varying_type(const ir_variable *var, gl_shader_stage stage)
52 {
53 const glsl_type *type = var->type;
54
55 if (!var->data.patch &&
56 ((var->data.mode == ir_var_shader_out &&
57 stage == MESA_SHADER_TESS_CTRL) ||
58 (var->data.mode == ir_var_shader_in &&
59 (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL ||
60 stage == MESA_SHADER_GEOMETRY)))) {
61 assert(type->is_array());
62 type = type->fields.array;
63 }
64
65 return type;
66 }
67
68 static void
69 create_xfb_varying_names(void *mem_ctx, const glsl_type *t, char **name,
70 size_t name_length, unsigned *count,
71 const char *ifc_member_name,
72 const glsl_type *ifc_member_t, char ***varying_names)
73 {
74 if (t->is_interface()) {
75 size_t new_length = name_length;
76
77 assert(ifc_member_name && ifc_member_t);
78 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s", ifc_member_name);
79
80 create_xfb_varying_names(mem_ctx, ifc_member_t, name, new_length, count,
81 NULL, NULL, varying_names);
82 } else if (t->is_struct()) {
83 for (unsigned i = 0; i < t->length; i++) {
84 const char *field = t->fields.structure[i].name;
85 size_t new_length = name_length;
86
87 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s", field);
88
89 create_xfb_varying_names(mem_ctx, t->fields.structure[i].type, name,
90 new_length, count, NULL, NULL,
91 varying_names);
92 }
93 } else if (t->without_array()->is_struct() ||
94 t->without_array()->is_interface() ||
95 (t->is_array() && t->fields.array->is_array())) {
96 for (unsigned i = 0; i < t->length; i++) {
97 size_t new_length = name_length;
98
99 /* Append the subscript to the current variable name */
100 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
101
102 create_xfb_varying_names(mem_ctx, t->fields.array, name, new_length,
103 count, ifc_member_name, ifc_member_t,
104 varying_names);
105 }
106 } else {
107 (*varying_names)[(*count)++] = ralloc_strdup(mem_ctx, *name);
108 }
109 }
110
111 static bool
112 process_xfb_layout_qualifiers(void *mem_ctx, const gl_linked_shader *sh,
113 struct gl_shader_program *prog,
114 unsigned *num_tfeedback_decls,
115 char ***varying_names)
116 {
117 bool has_xfb_qualifiers = false;
118
119 /* We still need to enable transform feedback mode even if xfb_stride is
120 * only applied to a global out. Also we don't bother to propagate
121 * xfb_stride to interface block members so this will catch that case also.
122 */
123 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
124 if (prog->TransformFeedback.BufferStride[j]) {
125 has_xfb_qualifiers = true;
126 break;
127 }
128 }
129
130 foreach_in_list(ir_instruction, node, sh->ir) {
131 ir_variable *var = node->as_variable();
132 if (!var || var->data.mode != ir_var_shader_out)
133 continue;
134
135 /* From the ARB_enhanced_layouts spec:
136 *
137 * "Any shader making any static use (after preprocessing) of any of
138 * these *xfb_* qualifiers will cause the shader to be in a
139 * transform feedback capturing mode and hence responsible for
140 * describing the transform feedback setup. This mode will capture
141 * any output selected by *xfb_offset*, directly or indirectly, to
142 * a transform feedback buffer."
143 */
144 if (var->data.explicit_xfb_buffer || var->data.explicit_xfb_stride) {
145 has_xfb_qualifiers = true;
146 }
147
148 if (var->data.explicit_xfb_offset) {
149 *num_tfeedback_decls += var->type->varying_count();
150 has_xfb_qualifiers = true;
151 }
152 }
153
154 if (*num_tfeedback_decls == 0)
155 return has_xfb_qualifiers;
156
157 unsigned i = 0;
158 *varying_names = ralloc_array(mem_ctx, char *, *num_tfeedback_decls);
159 foreach_in_list(ir_instruction, node, sh->ir) {
160 ir_variable *var = node->as_variable();
161 if (!var || var->data.mode != ir_var_shader_out)
162 continue;
163
164 if (var->data.explicit_xfb_offset) {
165 char *name;
166 const glsl_type *type, *member_type;
167
168 if (var->data.from_named_ifc_block) {
169 type = var->get_interface_type();
170
171 /* Find the member type before it was altered by lowering */
172 const glsl_type *type_wa = type->without_array();
173 member_type =
174 type_wa->fields.structure[type_wa->field_index(var->name)].type;
175 name = ralloc_strdup(NULL, type_wa->name);
176 } else {
177 type = var->type;
178 member_type = NULL;
179 name = ralloc_strdup(NULL, var->name);
180 }
181 create_xfb_varying_names(mem_ctx, type, &name, strlen(name), &i,
182 var->name, member_type, varying_names);
183 ralloc_free(name);
184 }
185 }
186
187 assert(i == *num_tfeedback_decls);
188 return has_xfb_qualifiers;
189 }
190
191 /**
192 * Validate the types and qualifiers of an output from one stage against the
193 * matching input to another stage.
194 */
195 static void
196 cross_validate_types_and_qualifiers(struct gl_context *ctx,
197 struct gl_shader_program *prog,
198 const ir_variable *input,
199 const ir_variable *output,
200 gl_shader_stage consumer_stage,
201 gl_shader_stage producer_stage)
202 {
203 /* Check that the types match between stages.
204 */
205 const glsl_type *type_to_match = input->type;
206
207 /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
208 const bool extra_array_level = (producer_stage == MESA_SHADER_VERTEX &&
209 consumer_stage != MESA_SHADER_FRAGMENT) ||
210 consumer_stage == MESA_SHADER_GEOMETRY;
211 if (extra_array_level) {
212 assert(type_to_match->is_array());
213 type_to_match = type_to_match->fields.array;
214 }
215
216 if (type_to_match != output->type) {
217 if (output->type->is_struct()) {
218 /* Structures across shader stages can have different name
219 * and considered to match in type if and only if structure
220 * members match in name, type, qualification, and declaration
221 * order.
222 */
223 if (!output->type->record_compare(type_to_match, false, true)) {
224 linker_error(prog,
225 "%s shader output `%s' declared as struct `%s', "
226 "doesn't match in type with %s shader input "
227 "declared as struct `%s'\n",
228 _mesa_shader_stage_to_string(producer_stage),
229 output->name,
230 output->type->name,
231 _mesa_shader_stage_to_string(consumer_stage),
232 input->type->name);
233 }
234 } else if (!output->type->is_array() || !is_gl_identifier(output->name)) {
235 /* There is a bit of a special case for gl_TexCoord. This
236 * built-in is unsized by default. Applications that variable
237 * access it must redeclare it with a size. There is some
238 * language in the GLSL spec that implies the fragment shader
239 * and vertex shader do not have to agree on this size. Other
240 * driver behave this way, and one or two applications seem to
241 * rely on it.
242 *
243 * Neither declaration needs to be modified here because the array
244 * sizes are fixed later when update_array_sizes is called.
245 *
246 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
247 *
248 * "Unlike user-defined varying variables, the built-in
249 * varying variables don't have a strict one-to-one
250 * correspondence between the vertex language and the
251 * fragment language."
252 */
253 linker_error(prog,
254 "%s shader output `%s' declared as type `%s', "
255 "but %s shader input declared as type `%s'\n",
256 _mesa_shader_stage_to_string(producer_stage),
257 output->name,
258 output->type->name,
259 _mesa_shader_stage_to_string(consumer_stage),
260 input->type->name);
261 return;
262 }
263 }
264
265 /* Check that all of the qualifiers match between stages.
266 */
267
268 /* According to the OpenGL and OpenGLES GLSL specs, the centroid qualifier
269 * should match until OpenGL 4.3 and OpenGLES 3.1. The OpenGLES 3.0
270 * conformance test suite does not verify that the qualifiers must match.
271 * The deqp test suite expects the opposite (OpenGLES 3.1) behavior for
272 * OpenGLES 3.0 drivers, so we relax the checking in all cases.
273 */
274 if (false /* always skip the centroid check */ &&
275 prog->data->Version < (prog->IsES ? 310 : 430) &&
276 input->data.centroid != output->data.centroid) {
277 linker_error(prog,
278 "%s shader output `%s' %s centroid qualifier, "
279 "but %s shader input %s centroid qualifier\n",
280 _mesa_shader_stage_to_string(producer_stage),
281 output->name,
282 (output->data.centroid) ? "has" : "lacks",
283 _mesa_shader_stage_to_string(consumer_stage),
284 (input->data.centroid) ? "has" : "lacks");
285 return;
286 }
287
288 if (input->data.sample != output->data.sample) {
289 linker_error(prog,
290 "%s shader output `%s' %s sample qualifier, "
291 "but %s shader input %s sample qualifier\n",
292 _mesa_shader_stage_to_string(producer_stage),
293 output->name,
294 (output->data.sample) ? "has" : "lacks",
295 _mesa_shader_stage_to_string(consumer_stage),
296 (input->data.sample) ? "has" : "lacks");
297 return;
298 }
299
300 if (input->data.patch != output->data.patch) {
301 linker_error(prog,
302 "%s shader output `%s' %s patch qualifier, "
303 "but %s shader input %s patch qualifier\n",
304 _mesa_shader_stage_to_string(producer_stage),
305 output->name,
306 (output->data.patch) ? "has" : "lacks",
307 _mesa_shader_stage_to_string(consumer_stage),
308 (input->data.patch) ? "has" : "lacks");
309 return;
310 }
311
312 /* The GLSL 4.30 and GLSL ES 3.00 specifications say:
313 *
314 * "As only outputs need be declared with invariant, an output from
315 * one shader stage will still match an input of a subsequent stage
316 * without the input being declared as invariant."
317 *
318 * while GLSL 4.20 says:
319 *
320 * "For variables leaving one shader and coming into another shader,
321 * the invariant keyword has to be used in both shaders, or a link
322 * error will result."
323 *
324 * and GLSL ES 1.00 section 4.6.4 "Invariance and Linking" says:
325 *
326 * "The invariance of varyings that are declared in both the vertex
327 * and fragment shaders must match."
328 */
329 if (input->data.explicit_invariant != output->data.explicit_invariant &&
330 prog->data->Version < (prog->IsES ? 300 : 430)) {
331 linker_error(prog,
332 "%s shader output `%s' %s invariant qualifier, "
333 "but %s shader input %s invariant qualifier\n",
334 _mesa_shader_stage_to_string(producer_stage),
335 output->name,
336 (output->data.explicit_invariant) ? "has" : "lacks",
337 _mesa_shader_stage_to_string(consumer_stage),
338 (input->data.explicit_invariant) ? "has" : "lacks");
339 return;
340 }
341
342 /* GLSL >= 4.40 removes text requiring interpolation qualifiers
343 * to match cross stage, they must only match within the same stage.
344 *
345 * From page 84 (page 90 of the PDF) of the GLSL 4.40 spec:
346 *
347 * "It is a link-time error if, within the same stage, the interpolation
348 * qualifiers of variables of the same name do not match.
349 *
350 * Section 4.3.9 (Interpolation) of the GLSL ES 3.00 spec says:
351 *
352 * "When no interpolation qualifier is present, smooth interpolation
353 * is used."
354 *
355 * So we match variables where one is smooth and the other has no explicit
356 * qualifier.
357 */
358 unsigned input_interpolation = input->data.interpolation;
359 unsigned output_interpolation = output->data.interpolation;
360 if (prog->IsES) {
361 if (input_interpolation == INTERP_MODE_NONE)
362 input_interpolation = INTERP_MODE_SMOOTH;
363 if (output_interpolation == INTERP_MODE_NONE)
364 output_interpolation = INTERP_MODE_SMOOTH;
365 }
366 if (input_interpolation != output_interpolation &&
367 prog->data->Version < 440) {
368 if (!ctx->Const.AllowGLSLCrossStageInterpolationMismatch) {
369 linker_error(prog,
370 "%s shader output `%s' specifies %s "
371 "interpolation qualifier, "
372 "but %s shader input specifies %s "
373 "interpolation qualifier\n",
374 _mesa_shader_stage_to_string(producer_stage),
375 output->name,
376 interpolation_string(output->data.interpolation),
377 _mesa_shader_stage_to_string(consumer_stage),
378 interpolation_string(input->data.interpolation));
379 return;
380 } else {
381 linker_warning(prog,
382 "%s shader output `%s' specifies %s "
383 "interpolation qualifier, "
384 "but %s shader input specifies %s "
385 "interpolation qualifier\n",
386 _mesa_shader_stage_to_string(producer_stage),
387 output->name,
388 interpolation_string(output->data.interpolation),
389 _mesa_shader_stage_to_string(consumer_stage),
390 interpolation_string(input->data.interpolation));
391 }
392 }
393 }
394
395 /**
396 * Validate front and back color outputs against single color input
397 */
398 static void
399 cross_validate_front_and_back_color(struct gl_context *ctx,
400 struct gl_shader_program *prog,
401 const ir_variable *input,
402 const ir_variable *front_color,
403 const ir_variable *back_color,
404 gl_shader_stage consumer_stage,
405 gl_shader_stage producer_stage)
406 {
407 if (front_color != NULL && front_color->data.assigned)
408 cross_validate_types_and_qualifiers(ctx, prog, input, front_color,
409 consumer_stage, producer_stage);
410
411 if (back_color != NULL && back_color->data.assigned)
412 cross_validate_types_and_qualifiers(ctx, prog, input, back_color,
413 consumer_stage, producer_stage);
414 }
415
416 static unsigned
417 compute_variable_location_slot(ir_variable *var, gl_shader_stage stage)
418 {
419 unsigned location_start = VARYING_SLOT_VAR0;
420
421 switch (stage) {
422 case MESA_SHADER_VERTEX:
423 if (var->data.mode == ir_var_shader_in)
424 location_start = VERT_ATTRIB_GENERIC0;
425 break;
426 case MESA_SHADER_TESS_CTRL:
427 case MESA_SHADER_TESS_EVAL:
428 if (var->data.patch)
429 location_start = VARYING_SLOT_PATCH0;
430 break;
431 case MESA_SHADER_FRAGMENT:
432 if (var->data.mode == ir_var_shader_out)
433 location_start = FRAG_RESULT_DATA0;
434 break;
435 default:
436 break;
437 }
438
439 return var->data.location - location_start;
440 }
441
442 struct explicit_location_info {
443 ir_variable *var;
444 bool base_type_is_integer;
445 unsigned base_type_bit_size;
446 unsigned interpolation;
447 bool centroid;
448 bool sample;
449 bool patch;
450 };
451
452 static bool
453 check_location_aliasing(struct explicit_location_info explicit_locations[][4],
454 ir_variable *var,
455 unsigned location,
456 unsigned component,
457 unsigned location_limit,
458 const glsl_type *type,
459 unsigned interpolation,
460 bool centroid,
461 bool sample,
462 bool patch,
463 gl_shader_program *prog,
464 gl_shader_stage stage)
465 {
466 unsigned last_comp;
467 unsigned base_type_bit_size;
468 const glsl_type *type_without_array = type->without_array();
469 const bool base_type_is_integer =
470 glsl_base_type_is_integer(type_without_array->base_type);
471 const bool is_struct = type_without_array->is_struct();
472 if (is_struct) {
473 /* structs don't have a defined underlying base type so just treat all
474 * component slots as used and set the bit size to 0. If there is
475 * location aliasing, we'll fail anyway later.
476 */
477 last_comp = 4;
478 base_type_bit_size = 0;
479 } else {
480 unsigned dmul = type_without_array->is_64bit() ? 2 : 1;
481 last_comp = component + type_without_array->vector_elements * dmul;
482 base_type_bit_size =
483 glsl_base_type_get_bit_size(type_without_array->base_type);
484 }
485
486 while (location < location_limit) {
487 unsigned comp = 0;
488 while (comp < 4) {
489 struct explicit_location_info *info =
490 &explicit_locations[location][comp];
491
492 if (info->var) {
493 if (info->var->type->without_array()->is_struct() || is_struct) {
494 /* Structs cannot share location since they are incompatible
495 * with any other underlying numerical type.
496 */
497 linker_error(prog,
498 "%s shader has multiple %sputs sharing the "
499 "same location that don't have the same "
500 "underlying numerical type. Struct variable '%s', "
501 "location %u\n",
502 _mesa_shader_stage_to_string(stage),
503 var->data.mode == ir_var_shader_in ? "in" : "out",
504 is_struct ? var->name : info->var->name,
505 location);
506 return false;
507 } else if (comp >= component && comp < last_comp) {
508 /* Component aliasing is not allowed */
509 linker_error(prog,
510 "%s shader has multiple %sputs explicitly "
511 "assigned to location %d and component %d\n",
512 _mesa_shader_stage_to_string(stage),
513 var->data.mode == ir_var_shader_in ? "in" : "out",
514 location, comp);
515 return false;
516 } else {
517 /* From the OpenGL 4.60.5 spec, section 4.4.1 Input Layout
518 * Qualifiers, Page 67, (Location aliasing):
519 *
520 * " Further, when location aliasing, the aliases sharing the
521 * location must have the same underlying numerical type
522 * and bit width (floating-point or integer, 32-bit versus
523 * 64-bit, etc.) and the same auxiliary storage and
524 * interpolation qualification."
525 */
526
527 /* If the underlying numerical type isn't integer, implicitly
528 * it will be float or else we would have failed by now.
529 */
530 if (info->base_type_is_integer != base_type_is_integer) {
531 linker_error(prog,
532 "%s shader has multiple %sputs sharing the "
533 "same location that don't have the same "
534 "underlying numerical type. Location %u "
535 "component %u.\n",
536 _mesa_shader_stage_to_string(stage),
537 var->data.mode == ir_var_shader_in ?
538 "in" : "out", location, comp);
539 return false;
540 }
541
542 if (info->base_type_bit_size != base_type_bit_size) {
543 linker_error(prog,
544 "%s shader has multiple %sputs sharing the "
545 "same location that don't have the same "
546 "underlying numerical bit size. Location %u "
547 "component %u.\n",
548 _mesa_shader_stage_to_string(stage),
549 var->data.mode == ir_var_shader_in ?
550 "in" : "out", location, comp);
551 return false;
552 }
553
554 if (info->interpolation != interpolation) {
555 linker_error(prog,
556 "%s shader has multiple %sputs sharing the "
557 "same location that don't have the same "
558 "interpolation qualification. Location %u "
559 "component %u.\n",
560 _mesa_shader_stage_to_string(stage),
561 var->data.mode == ir_var_shader_in ?
562 "in" : "out", location, comp);
563 return false;
564 }
565
566 if (info->centroid != centroid ||
567 info->sample != sample ||
568 info->patch != patch) {
569 linker_error(prog,
570 "%s shader has multiple %sputs sharing the "
571 "same location that don't have the same "
572 "auxiliary storage qualification. Location %u "
573 "component %u.\n",
574 _mesa_shader_stage_to_string(stage),
575 var->data.mode == ir_var_shader_in ?
576 "in" : "out", location, comp);
577 return false;
578 }
579 }
580 } else if (comp >= component && comp < last_comp) {
581 info->var = var;
582 info->base_type_is_integer = base_type_is_integer;
583 info->base_type_bit_size = base_type_bit_size;
584 info->interpolation = interpolation;
585 info->centroid = centroid;
586 info->sample = sample;
587 info->patch = patch;
588 }
589
590 comp++;
591
592 /* We need to do some special handling for doubles as dvec3 and
593 * dvec4 consume two consecutive locations. We don't need to
594 * worry about components beginning at anything other than 0 as
595 * the spec does not allow this for dvec3 and dvec4.
596 */
597 if (comp == 4 && last_comp > 4) {
598 last_comp = last_comp - 4;
599 /* Bump location index and reset the component index */
600 location++;
601 comp = 0;
602 component = 0;
603 }
604 }
605
606 location++;
607 }
608
609 return true;
610 }
611
612 static bool
613 validate_explicit_variable_location(struct gl_context *ctx,
614 struct explicit_location_info explicit_locations[][4],
615 ir_variable *var,
616 gl_shader_program *prog,
617 gl_linked_shader *sh)
618 {
619 const glsl_type *type = get_varying_type(var, sh->Stage);
620 unsigned num_elements = type->count_attribute_slots(false);
621 unsigned idx = compute_variable_location_slot(var, sh->Stage);
622 unsigned slot_limit = idx + num_elements;
623
624 /* Vertex shader inputs and fragment shader outputs are validated in
625 * assign_attribute_or_color_locations() so we should not attempt to
626 * validate them again here.
627 */
628 unsigned slot_max;
629 if (var->data.mode == ir_var_shader_out) {
630 assert(sh->Stage != MESA_SHADER_FRAGMENT);
631 slot_max =
632 ctx->Const.Program[sh->Stage].MaxOutputComponents / 4;
633 } else {
634 assert(var->data.mode == ir_var_shader_in);
635 assert(sh->Stage != MESA_SHADER_VERTEX);
636 slot_max =
637 ctx->Const.Program[sh->Stage].MaxInputComponents / 4;
638 }
639
640 if (slot_limit > slot_max) {
641 linker_error(prog,
642 "Invalid location %u in %s shader\n",
643 idx, _mesa_shader_stage_to_string(sh->Stage));
644 return false;
645 }
646
647 const glsl_type *type_without_array = type->without_array();
648 if (type_without_array->is_interface()) {
649 for (unsigned i = 0; i < type_without_array->length; i++) {
650 glsl_struct_field *field = &type_without_array->fields.structure[i];
651 unsigned field_location = field->location -
652 (field->patch ? VARYING_SLOT_PATCH0 : VARYING_SLOT_VAR0);
653 if (!check_location_aliasing(explicit_locations, var,
654 field_location,
655 0, field_location + 1,
656 field->type,
657 field->interpolation,
658 field->centroid,
659 field->sample,
660 field->patch,
661 prog, sh->Stage)) {
662 return false;
663 }
664 }
665 } else if (!check_location_aliasing(explicit_locations, var,
666 idx, var->data.location_frac,
667 slot_limit, type,
668 var->data.interpolation,
669 var->data.centroid,
670 var->data.sample,
671 var->data.patch,
672 prog, sh->Stage)) {
673 return false;
674 }
675
676 return true;
677 }
678
679 /**
680 * Validate explicit locations for the inputs to the first stage and the
681 * outputs of the last stage in an SSO program (everything in between is
682 * validated in cross_validate_outputs_to_inputs).
683 */
684 void
685 validate_sso_explicit_locations(struct gl_context *ctx,
686 struct gl_shader_program *prog,
687 gl_shader_stage first_stage,
688 gl_shader_stage last_stage)
689 {
690 assert(prog->SeparateShader);
691
692 /* VS inputs and FS outputs are validated in
693 * assign_attribute_or_color_locations()
694 */
695 bool validate_first_stage = first_stage != MESA_SHADER_VERTEX;
696 bool validate_last_stage = last_stage != MESA_SHADER_FRAGMENT;
697 if (!validate_first_stage && !validate_last_stage)
698 return;
699
700 struct explicit_location_info explicit_locations[MAX_VARYING][4];
701
702 gl_shader_stage stages[2] = { first_stage, last_stage };
703 bool validate_stage[2] = { validate_first_stage, validate_last_stage };
704 ir_variable_mode var_direction[2] = { ir_var_shader_in, ir_var_shader_out };
705
706 for (unsigned i = 0; i < 2; i++) {
707 if (!validate_stage[i])
708 continue;
709
710 gl_shader_stage stage = stages[i];
711
712 gl_linked_shader *sh = prog->_LinkedShaders[stage];
713 assert(sh);
714
715 memset(explicit_locations, 0, sizeof(explicit_locations));
716
717 foreach_in_list(ir_instruction, node, sh->ir) {
718 ir_variable *const var = node->as_variable();
719
720 if (var == NULL ||
721 !var->data.explicit_location ||
722 var->data.location < VARYING_SLOT_VAR0 ||
723 var->data.mode != var_direction[i])
724 continue;
725
726 if (!validate_explicit_variable_location(
727 ctx, explicit_locations, var, prog, sh)) {
728 return;
729 }
730 }
731 }
732 }
733
734 /**
735 * Validate that outputs from one stage match inputs of another
736 */
737 void
738 cross_validate_outputs_to_inputs(struct gl_context *ctx,
739 struct gl_shader_program *prog,
740 gl_linked_shader *producer,
741 gl_linked_shader *consumer)
742 {
743 glsl_symbol_table parameters;
744 struct explicit_location_info output_explicit_locations[MAX_VARYING][4] = { 0 };
745 struct explicit_location_info input_explicit_locations[MAX_VARYING][4] = { 0 };
746
747 /* Find all shader outputs in the "producer" stage.
748 */
749 foreach_in_list(ir_instruction, node, producer->ir) {
750 ir_variable *const var = node->as_variable();
751
752 if (var == NULL || var->data.mode != ir_var_shader_out)
753 continue;
754
755 if (!var->data.explicit_location
756 || var->data.location < VARYING_SLOT_VAR0)
757 parameters.add_variable(var);
758 else {
759 /* User-defined varyings with explicit locations are handled
760 * differently because they do not need to have matching names.
761 */
762 if (!validate_explicit_variable_location(ctx,
763 output_explicit_locations,
764 var, prog, producer)) {
765 return;
766 }
767 }
768 }
769
770
771 /* Find all shader inputs in the "consumer" stage. Any variables that have
772 * matching outputs already in the symbol table must have the same type and
773 * qualifiers.
774 *
775 * Exception: if the consumer is the geometry shader, then the inputs
776 * should be arrays and the type of the array element should match the type
777 * of the corresponding producer output.
778 */
779 foreach_in_list(ir_instruction, node, consumer->ir) {
780 ir_variable *const input = node->as_variable();
781
782 if (input == NULL || input->data.mode != ir_var_shader_in)
783 continue;
784
785 if (strcmp(input->name, "gl_Color") == 0 && input->data.used) {
786 const ir_variable *const front_color =
787 parameters.get_variable("gl_FrontColor");
788
789 const ir_variable *const back_color =
790 parameters.get_variable("gl_BackColor");
791
792 cross_validate_front_and_back_color(ctx, prog, input,
793 front_color, back_color,
794 consumer->Stage, producer->Stage);
795 } else if (strcmp(input->name, "gl_SecondaryColor") == 0 && input->data.used) {
796 const ir_variable *const front_color =
797 parameters.get_variable("gl_FrontSecondaryColor");
798
799 const ir_variable *const back_color =
800 parameters.get_variable("gl_BackSecondaryColor");
801
802 cross_validate_front_and_back_color(ctx, prog, input,
803 front_color, back_color,
804 consumer->Stage, producer->Stage);
805 } else {
806 /* The rules for connecting inputs and outputs change in the presence
807 * of explicit locations. In this case, we no longer care about the
808 * names of the variables. Instead, we care only about the
809 * explicitly assigned location.
810 */
811 ir_variable *output = NULL;
812 if (input->data.explicit_location
813 && input->data.location >= VARYING_SLOT_VAR0) {
814
815 const glsl_type *type = get_varying_type(input, consumer->Stage);
816 unsigned num_elements = type->count_attribute_slots(false);
817 unsigned idx =
818 compute_variable_location_slot(input, consumer->Stage);
819 unsigned slot_limit = idx + num_elements;
820
821 if (!validate_explicit_variable_location(ctx,
822 input_explicit_locations,
823 input, prog, consumer)) {
824 return;
825 }
826
827 while (idx < slot_limit) {
828 if (idx >= MAX_VARYING) {
829 linker_error(prog,
830 "Invalid location %u in %s shader\n", idx,
831 _mesa_shader_stage_to_string(consumer->Stage));
832 return;
833 }
834
835 output = output_explicit_locations[idx][input->data.location_frac].var;
836
837 if (output == NULL) {
838 /* A linker failure should only happen when there is no
839 * output declaration and there is Static Use of the
840 * declared input.
841 */
842 if (input->data.used) {
843 linker_error(prog,
844 "%s shader input `%s' with explicit location "
845 "has no matching output\n",
846 _mesa_shader_stage_to_string(consumer->Stage),
847 input->name);
848 break;
849 }
850 } else if (input->data.location != output->data.location) {
851 linker_error(prog,
852 "%s shader input `%s' with explicit location "
853 "has no matching output\n",
854 _mesa_shader_stage_to_string(consumer->Stage),
855 input->name);
856 break;
857 }
858 idx++;
859 }
860 } else {
861 output = parameters.get_variable(input->name);
862 }
863
864 if (output != NULL) {
865 /* Interface blocks have their own validation elsewhere so don't
866 * try validating them here.
867 */
868 if (!(input->get_interface_type() &&
869 output->get_interface_type()))
870 cross_validate_types_and_qualifiers(ctx, prog, input, output,
871 consumer->Stage,
872 producer->Stage);
873 } else {
874 /* Check for input vars with unmatched output vars in prev stage
875 * taking into account that interface blocks could have a matching
876 * output but with different name, so we ignore them.
877 */
878 assert(!input->data.assigned);
879 if (input->data.used && !input->get_interface_type() &&
880 !input->data.explicit_location)
881 linker_error(prog,
882 "%s shader input `%s' "
883 "has no matching output in the previous stage\n",
884 _mesa_shader_stage_to_string(consumer->Stage),
885 input->name);
886 }
887 }
888 }
889 }
890
891 /**
892 * Demote shader inputs and outputs that are not used in other stages, and
893 * remove them via dead code elimination.
894 */
895 static void
896 remove_unused_shader_inputs_and_outputs(bool is_separate_shader_object,
897 gl_linked_shader *sh,
898 enum ir_variable_mode mode)
899 {
900 if (is_separate_shader_object)
901 return;
902
903 foreach_in_list(ir_instruction, node, sh->ir) {
904 ir_variable *const var = node->as_variable();
905
906 if (var == NULL || var->data.mode != int(mode))
907 continue;
908
909 /* A shader 'in' or 'out' variable is only really an input or output if
910 * its value is used by other shader stages. This will cause the
911 * variable to have a location assigned.
912 */
913 if (var->data.is_unmatched_generic_inout && !var->data.is_xfb_only) {
914 assert(var->data.mode != ir_var_temporary);
915
916 /* Assign zeros to demoted inputs to allow more optimizations. */
917 if (var->data.mode == ir_var_shader_in && !var->constant_value)
918 var->constant_value = ir_constant::zero(var, var->type);
919
920 var->data.mode = ir_var_auto;
921 }
922 }
923
924 /* Eliminate code that is now dead due to unused inputs/outputs being
925 * demoted.
926 */
927 while (do_dead_code(sh->ir, false))
928 ;
929
930 }
931
932 /**
933 * Initialize this object based on a string that was passed to
934 * glTransformFeedbackVaryings.
935 *
936 * If the input is mal-formed, this call still succeeds, but it sets
937 * this->var_name to a mal-formed input, so tfeedback_decl::find_output_var()
938 * will fail to find any matching variable.
939 */
940 void
941 tfeedback_decl::init(struct gl_context *ctx, const void *mem_ctx,
942 const char *input)
943 {
944 /* We don't have to be pedantic about what is a valid GLSL variable name,
945 * because any variable with an invalid name can't exist in the IR anyway.
946 */
947
948 this->location = -1;
949 this->orig_name = input;
950 this->lowered_builtin_array_variable = none;
951 this->skip_components = 0;
952 this->next_buffer_separator = false;
953 this->matched_candidate = NULL;
954 this->stream_id = 0;
955 this->buffer = 0;
956 this->offset = 0;
957
958 if (ctx->Extensions.ARB_transform_feedback3) {
959 /* Parse gl_NextBuffer. */
960 if (strcmp(input, "gl_NextBuffer") == 0) {
961 this->next_buffer_separator = true;
962 return;
963 }
964
965 /* Parse gl_SkipComponents. */
966 if (strcmp(input, "gl_SkipComponents1") == 0)
967 this->skip_components = 1;
968 else if (strcmp(input, "gl_SkipComponents2") == 0)
969 this->skip_components = 2;
970 else if (strcmp(input, "gl_SkipComponents3") == 0)
971 this->skip_components = 3;
972 else if (strcmp(input, "gl_SkipComponents4") == 0)
973 this->skip_components = 4;
974
975 if (this->skip_components)
976 return;
977 }
978
979 /* Parse a declaration. */
980 const char *base_name_end;
981 long subscript = parse_program_resource_name(input, &base_name_end);
982 this->var_name = ralloc_strndup(mem_ctx, input, base_name_end - input);
983 if (this->var_name == NULL) {
984 _mesa_error_no_memory(__func__);
985 return;
986 }
987
988 if (subscript >= 0) {
989 this->array_subscript = subscript;
990 this->is_subscripted = true;
991 } else {
992 this->is_subscripted = false;
993 }
994
995 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
996 * class must behave specially to account for the fact that gl_ClipDistance
997 * is converted from a float[8] to a vec4[2].
998 */
999 if (ctx->Const.ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerCombinedClipCullDistance &&
1000 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1001 this->lowered_builtin_array_variable = clip_distance;
1002 }
1003 if (ctx->Const.ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerCombinedClipCullDistance &&
1004 strcmp(this->var_name, "gl_CullDistance") == 0) {
1005 this->lowered_builtin_array_variable = cull_distance;
1006 }
1007
1008 if (ctx->Const.LowerTessLevel &&
1009 (strcmp(this->var_name, "gl_TessLevelOuter") == 0))
1010 this->lowered_builtin_array_variable = tess_level_outer;
1011 if (ctx->Const.LowerTessLevel &&
1012 (strcmp(this->var_name, "gl_TessLevelInner") == 0))
1013 this->lowered_builtin_array_variable = tess_level_inner;
1014 }
1015
1016
1017 /**
1018 * Determine whether two tfeedback_decl objects refer to the same variable and
1019 * array index (if applicable).
1020 */
1021 bool
1022 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1023 {
1024 assert(x.is_varying() && y.is_varying());
1025
1026 if (strcmp(x.var_name, y.var_name) != 0)
1027 return false;
1028 if (x.is_subscripted != y.is_subscripted)
1029 return false;
1030 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1031 return false;
1032 return true;
1033 }
1034
1035
1036 /**
1037 * Assign a location and stream ID for this tfeedback_decl object based on the
1038 * transform feedback candidate found by find_candidate.
1039 *
1040 * If an error occurs, the error is reported through linker_error() and false
1041 * is returned.
1042 */
1043 bool
1044 tfeedback_decl::assign_location(struct gl_context *ctx,
1045 struct gl_shader_program *prog)
1046 {
1047 assert(this->is_varying());
1048
1049 unsigned fine_location
1050 = this->matched_candidate->toplevel_var->data.location * 4
1051 + this->matched_candidate->toplevel_var->data.location_frac
1052 + this->matched_candidate->offset;
1053 const unsigned dmul =
1054 this->matched_candidate->type->without_array()->is_64bit() ? 2 : 1;
1055
1056 if (this->matched_candidate->type->is_array()) {
1057 /* Array variable */
1058 const unsigned matrix_cols =
1059 this->matched_candidate->type->fields.array->matrix_columns;
1060 const unsigned vector_elements =
1061 this->matched_candidate->type->fields.array->vector_elements;
1062 unsigned actual_array_size;
1063 switch (this->lowered_builtin_array_variable) {
1064 case clip_distance:
1065 actual_array_size = prog->last_vert_prog ?
1066 prog->last_vert_prog->info.clip_distance_array_size : 0;
1067 break;
1068 case cull_distance:
1069 actual_array_size = prog->last_vert_prog ?
1070 prog->last_vert_prog->info.cull_distance_array_size : 0;
1071 break;
1072 case tess_level_outer:
1073 actual_array_size = 4;
1074 break;
1075 case tess_level_inner:
1076 actual_array_size = 2;
1077 break;
1078 case none:
1079 default:
1080 actual_array_size = this->matched_candidate->type->array_size();
1081 break;
1082 }
1083
1084 if (this->is_subscripted) {
1085 /* Check array bounds. */
1086 if (this->array_subscript >= actual_array_size) {
1087 linker_error(prog, "Transform feedback varying %s has index "
1088 "%i, but the array size is %u.",
1089 this->orig_name, this->array_subscript,
1090 actual_array_size);
1091 return false;
1092 }
1093 unsigned array_elem_size = this->lowered_builtin_array_variable ?
1094 1 : vector_elements * matrix_cols * dmul;
1095 fine_location += array_elem_size * this->array_subscript;
1096 this->size = 1;
1097 } else {
1098 this->size = actual_array_size;
1099 }
1100 this->vector_elements = vector_elements;
1101 this->matrix_columns = matrix_cols;
1102 if (this->lowered_builtin_array_variable)
1103 this->type = GL_FLOAT;
1104 else
1105 this->type = this->matched_candidate->type->fields.array->gl_type;
1106 } else {
1107 /* Regular variable (scalar, vector, or matrix) */
1108 if (this->is_subscripted) {
1109 linker_error(prog, "Transform feedback varying %s requested, "
1110 "but %s is not an array.",
1111 this->orig_name, this->var_name);
1112 return false;
1113 }
1114 this->size = 1;
1115 this->vector_elements = this->matched_candidate->type->vector_elements;
1116 this->matrix_columns = this->matched_candidate->type->matrix_columns;
1117 this->type = this->matched_candidate->type->gl_type;
1118 }
1119 this->location = fine_location / 4;
1120 this->location_frac = fine_location % 4;
1121
1122 /* From GL_EXT_transform_feedback:
1123 * A program will fail to link if:
1124 *
1125 * * the total number of components to capture in any varying
1126 * variable in <varyings> is greater than the constant
1127 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1128 * buffer mode is SEPARATE_ATTRIBS_EXT;
1129 */
1130 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1131 this->num_components() >
1132 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1133 linker_error(prog, "Transform feedback varying %s exceeds "
1134 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1135 this->orig_name);
1136 return false;
1137 }
1138
1139 /* Only transform feedback varyings can be assigned to non-zero streams,
1140 * so assign the stream id here.
1141 */
1142 this->stream_id = this->matched_candidate->toplevel_var->data.stream;
1143
1144 unsigned array_offset = this->array_subscript * 4 * dmul;
1145 unsigned struct_offset = this->matched_candidate->offset * 4 * dmul;
1146 this->buffer = this->matched_candidate->toplevel_var->data.xfb_buffer;
1147 this->offset = this->matched_candidate->toplevel_var->data.offset +
1148 array_offset + struct_offset;
1149
1150 return true;
1151 }
1152
1153
1154 unsigned
1155 tfeedback_decl::get_num_outputs() const
1156 {
1157 if (!this->is_varying()) {
1158 return 0;
1159 }
1160 return (this->num_components() + this->location_frac + 3)/4;
1161 }
1162
1163
1164 /**
1165 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1166 *
1167 * If an error occurs, the error is reported through linker_error() and false
1168 * is returned.
1169 */
1170 bool
1171 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1172 struct gl_transform_feedback_info *info,
1173 unsigned buffer, unsigned buffer_index,
1174 const unsigned max_outputs, bool *explicit_stride,
1175 bool has_xfb_qualifiers) const
1176 {
1177 unsigned xfb_offset = 0;
1178 unsigned size = this->size;
1179 /* Handle gl_SkipComponents. */
1180 if (this->skip_components) {
1181 info->Buffers[buffer].Stride += this->skip_components;
1182 size = this->skip_components;
1183 goto store_varying;
1184 }
1185
1186 if (this->next_buffer_separator) {
1187 size = 0;
1188 goto store_varying;
1189 }
1190
1191 if (has_xfb_qualifiers) {
1192 xfb_offset = this->offset / 4;
1193 } else {
1194 xfb_offset = info->Buffers[buffer].Stride;
1195 }
1196 info->Varyings[info->NumVarying].Offset = xfb_offset * 4;
1197
1198 {
1199 unsigned location = this->location;
1200 unsigned location_frac = this->location_frac;
1201 unsigned num_components = this->num_components();
1202 while (num_components > 0) {
1203 unsigned output_size = MIN2(num_components, 4 - location_frac);
1204 assert((info->NumOutputs == 0 && max_outputs == 0) ||
1205 info->NumOutputs < max_outputs);
1206
1207 /* From the ARB_enhanced_layouts spec:
1208 *
1209 * "If such a block member or variable is not written during a shader
1210 * invocation, the buffer contents at the assigned offset will be
1211 * undefined. Even if there are no static writes to a variable or
1212 * member that is assigned a transform feedback offset, the space is
1213 * still allocated in the buffer and still affects the stride."
1214 */
1215 if (this->is_varying_written()) {
1216 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
1217 info->Outputs[info->NumOutputs].OutputRegister = location;
1218 info->Outputs[info->NumOutputs].NumComponents = output_size;
1219 info->Outputs[info->NumOutputs].StreamId = stream_id;
1220 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1221 info->Outputs[info->NumOutputs].DstOffset = xfb_offset;
1222 ++info->NumOutputs;
1223 }
1224 info->Buffers[buffer].Stream = this->stream_id;
1225 xfb_offset += output_size;
1226
1227 num_components -= output_size;
1228 location++;
1229 location_frac = 0;
1230 }
1231 }
1232
1233 if (explicit_stride && explicit_stride[buffer]) {
1234 if (this->is_64bit() && info->Buffers[buffer].Stride % 2) {
1235 linker_error(prog, "invalid qualifier xfb_stride=%d must be a "
1236 "multiple of 8 as its applied to a type that is or "
1237 "contains a double.",
1238 info->Buffers[buffer].Stride * 4);
1239 return false;
1240 }
1241
1242 if (xfb_offset > info->Buffers[buffer].Stride) {
1243 linker_error(prog, "xfb_offset (%d) overflows xfb_stride (%d) for "
1244 "buffer (%d)", xfb_offset * 4,
1245 info->Buffers[buffer].Stride * 4, buffer);
1246 return false;
1247 }
1248 } else {
1249 info->Buffers[buffer].Stride = xfb_offset;
1250 }
1251
1252 /* From GL_EXT_transform_feedback:
1253 * A program will fail to link if:
1254 *
1255 * * the total number of components to capture is greater than
1256 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1257 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1258 *
1259 * From GL_ARB_enhanced_layouts:
1260 *
1261 * "The resulting stride (implicit or explicit) must be less than or
1262 * equal to the implementation-dependent constant
1263 * gl_MaxTransformFeedbackInterleavedComponents."
1264 */
1265 if ((prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS ||
1266 has_xfb_qualifiers) &&
1267 info->Buffers[buffer].Stride >
1268 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1269 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1270 "limit has been exceeded.");
1271 return false;
1272 }
1273
1274 store_varying:
1275 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog,
1276 this->orig_name);
1277 info->Varyings[info->NumVarying].Type = this->type;
1278 info->Varyings[info->NumVarying].Size = size;
1279 info->Varyings[info->NumVarying].BufferIndex = buffer_index;
1280 info->NumVarying++;
1281 info->Buffers[buffer].NumVaryings++;
1282
1283 return true;
1284 }
1285
1286
1287 const tfeedback_candidate *
1288 tfeedback_decl::find_candidate(gl_shader_program *prog,
1289 hash_table *tfeedback_candidates)
1290 {
1291 const char *name = this->var_name;
1292 switch (this->lowered_builtin_array_variable) {
1293 case none:
1294 name = this->var_name;
1295 break;
1296 case clip_distance:
1297 name = "gl_ClipDistanceMESA";
1298 break;
1299 case cull_distance:
1300 name = "gl_CullDistanceMESA";
1301 break;
1302 case tess_level_outer:
1303 name = "gl_TessLevelOuterMESA";
1304 break;
1305 case tess_level_inner:
1306 name = "gl_TessLevelInnerMESA";
1307 break;
1308 }
1309 hash_entry *entry = _mesa_hash_table_search(tfeedback_candidates, name);
1310
1311 this->matched_candidate = entry ?
1312 (const tfeedback_candidate *) entry->data : NULL;
1313
1314 if (!this->matched_candidate) {
1315 /* From GL_EXT_transform_feedback:
1316 * A program will fail to link if:
1317 *
1318 * * any variable name specified in the <varyings> array is not
1319 * declared as an output in the geometry shader (if present) or
1320 * the vertex shader (if no geometry shader is present);
1321 */
1322 linker_error(prog, "Transform feedback varying %s undeclared.",
1323 this->orig_name);
1324 }
1325
1326 return this->matched_candidate;
1327 }
1328
1329
1330 /**
1331 * Parse all the transform feedback declarations that were passed to
1332 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1333 *
1334 * If an error occurs, the error is reported through linker_error() and false
1335 * is returned.
1336 */
1337 static bool
1338 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1339 const void *mem_ctx, unsigned num_names,
1340 char **varying_names, tfeedback_decl *decls)
1341 {
1342 for (unsigned i = 0; i < num_names; ++i) {
1343 decls[i].init(ctx, mem_ctx, varying_names[i]);
1344
1345 if (!decls[i].is_varying())
1346 continue;
1347
1348 /* From GL_EXT_transform_feedback:
1349 * A program will fail to link if:
1350 *
1351 * * any two entries in the <varyings> array specify the same varying
1352 * variable;
1353 *
1354 * We interpret this to mean "any two entries in the <varyings> array
1355 * specify the same varying variable and array index", since transform
1356 * feedback of arrays would be useless otherwise.
1357 */
1358 for (unsigned j = 0; j < i; ++j) {
1359 if (decls[j].is_varying()) {
1360 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1361 linker_error(prog, "Transform feedback varying %s specified "
1362 "more than once.", varying_names[i]);
1363 return false;
1364 }
1365 }
1366 }
1367 }
1368 return true;
1369 }
1370
1371
1372 static int
1373 cmp_xfb_offset(const void * x_generic, const void * y_generic)
1374 {
1375 tfeedback_decl *x = (tfeedback_decl *) x_generic;
1376 tfeedback_decl *y = (tfeedback_decl *) y_generic;
1377
1378 if (x->get_buffer() != y->get_buffer())
1379 return x->get_buffer() - y->get_buffer();
1380 return x->get_offset() - y->get_offset();
1381 }
1382
1383 /**
1384 * Store transform feedback location assignments into
1385 * prog->sh.LinkedTransformFeedback based on the data stored in
1386 * tfeedback_decls.
1387 *
1388 * If an error occurs, the error is reported through linker_error() and false
1389 * is returned.
1390 */
1391 static bool
1392 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
1393 unsigned num_tfeedback_decls,
1394 tfeedback_decl *tfeedback_decls, bool has_xfb_qualifiers)
1395 {
1396 if (!prog->last_vert_prog)
1397 return true;
1398
1399 /* Make sure MaxTransformFeedbackBuffers is less than 32 so the bitmask for
1400 * tracking the number of buffers doesn't overflow.
1401 */
1402 assert(ctx->Const.MaxTransformFeedbackBuffers < 32);
1403
1404 bool separate_attribs_mode =
1405 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
1406
1407 struct gl_program *xfb_prog = prog->last_vert_prog;
1408 xfb_prog->sh.LinkedTransformFeedback =
1409 rzalloc(xfb_prog, struct gl_transform_feedback_info);
1410
1411 /* The xfb_offset qualifier does not have to be used in increasing order
1412 * however some drivers expect to receive the list of transform feedback
1413 * declarations in order so sort it now for convenience.
1414 */
1415 if (has_xfb_qualifiers) {
1416 qsort(tfeedback_decls, num_tfeedback_decls, sizeof(*tfeedback_decls),
1417 cmp_xfb_offset);
1418 }
1419
1420 xfb_prog->sh.LinkedTransformFeedback->Varyings =
1421 rzalloc_array(xfb_prog, struct gl_transform_feedback_varying_info,
1422 num_tfeedback_decls);
1423
1424 unsigned num_outputs = 0;
1425 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1426 if (tfeedback_decls[i].is_varying_written())
1427 num_outputs += tfeedback_decls[i].get_num_outputs();
1428 }
1429
1430 xfb_prog->sh.LinkedTransformFeedback->Outputs =
1431 rzalloc_array(xfb_prog, struct gl_transform_feedback_output,
1432 num_outputs);
1433
1434 unsigned num_buffers = 0;
1435 unsigned buffers = 0;
1436
1437 if (!has_xfb_qualifiers && separate_attribs_mode) {
1438 /* GL_SEPARATE_ATTRIBS */
1439 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1440 if (!tfeedback_decls[i].store(ctx, prog,
1441 xfb_prog->sh.LinkedTransformFeedback,
1442 num_buffers, num_buffers, num_outputs,
1443 NULL, has_xfb_qualifiers))
1444 return false;
1445
1446 buffers |= 1 << num_buffers;
1447 num_buffers++;
1448 }
1449 }
1450 else {
1451 /* GL_INVERLEAVED_ATTRIBS */
1452 int buffer_stream_id = -1;
1453 unsigned buffer =
1454 num_tfeedback_decls ? tfeedback_decls[0].get_buffer() : 0;
1455 bool explicit_stride[MAX_FEEDBACK_BUFFERS] = { false };
1456
1457 /* Apply any xfb_stride global qualifiers */
1458 if (has_xfb_qualifiers) {
1459 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1460 if (prog->TransformFeedback.BufferStride[j]) {
1461 explicit_stride[j] = true;
1462 xfb_prog->sh.LinkedTransformFeedback->Buffers[j].Stride =
1463 prog->TransformFeedback.BufferStride[j] / 4;
1464 }
1465 }
1466 }
1467
1468 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1469 if (has_xfb_qualifiers &&
1470 buffer != tfeedback_decls[i].get_buffer()) {
1471 /* we have moved to the next buffer so reset stream id */
1472 buffer_stream_id = -1;
1473 num_buffers++;
1474 }
1475
1476 if (tfeedback_decls[i].is_next_buffer_separator()) {
1477 if (!tfeedback_decls[i].store(ctx, prog,
1478 xfb_prog->sh.LinkedTransformFeedback,
1479 buffer, num_buffers, num_outputs,
1480 explicit_stride, has_xfb_qualifiers))
1481 return false;
1482 num_buffers++;
1483 buffer_stream_id = -1;
1484 continue;
1485 }
1486
1487 if (has_xfb_qualifiers) {
1488 buffer = tfeedback_decls[i].get_buffer();
1489 } else {
1490 buffer = num_buffers;
1491 }
1492
1493 if (tfeedback_decls[i].is_varying()) {
1494 if (buffer_stream_id == -1) {
1495 /* First varying writing to this buffer: remember its stream */
1496 buffer_stream_id = (int) tfeedback_decls[i].get_stream_id();
1497
1498 /* Only mark a buffer as active when there is a varying
1499 * attached to it. This behaviour is based on a revised version
1500 * of section 13.2.2 of the GL 4.6 spec.
1501 */
1502 buffers |= 1 << buffer;
1503 } else if (buffer_stream_id !=
1504 (int) tfeedback_decls[i].get_stream_id()) {
1505 /* Varying writes to the same buffer from a different stream */
1506 linker_error(prog,
1507 "Transform feedback can't capture varyings belonging "
1508 "to different vertex streams in a single buffer. "
1509 "Varying %s writes to buffer from stream %u, other "
1510 "varyings in the same buffer write from stream %u.",
1511 tfeedback_decls[i].name(),
1512 tfeedback_decls[i].get_stream_id(),
1513 buffer_stream_id);
1514 return false;
1515 }
1516 }
1517
1518 if (!tfeedback_decls[i].store(ctx, prog,
1519 xfb_prog->sh.LinkedTransformFeedback,
1520 buffer, num_buffers, num_outputs,
1521 explicit_stride, has_xfb_qualifiers))
1522 return false;
1523 }
1524 }
1525
1526 assert(xfb_prog->sh.LinkedTransformFeedback->NumOutputs == num_outputs);
1527
1528 xfb_prog->sh.LinkedTransformFeedback->ActiveBuffers = buffers;
1529 return true;
1530 }
1531
1532 namespace {
1533
1534 /**
1535 * Data structure recording the relationship between outputs of one shader
1536 * stage (the "producer") and inputs of another (the "consumer").
1537 */
1538 class varying_matches
1539 {
1540 public:
1541 varying_matches(bool disable_varying_packing, bool xfb_enabled,
1542 bool enhanced_layouts_enabled,
1543 gl_shader_stage producer_stage,
1544 gl_shader_stage consumer_stage);
1545 ~varying_matches();
1546 void record(ir_variable *producer_var, ir_variable *consumer_var);
1547 unsigned assign_locations(struct gl_shader_program *prog,
1548 uint8_t components[],
1549 uint64_t reserved_slots);
1550 void store_locations() const;
1551
1552 private:
1553 bool is_varying_packing_safe(const glsl_type *type,
1554 const ir_variable *var) const;
1555
1556 /**
1557 * If true, this driver disables varying packing, so all varyings need to
1558 * be aligned on slot boundaries, and take up a number of slots equal to
1559 * their number of matrix columns times their array size.
1560 *
1561 * Packing may also be disabled because our current packing method is not
1562 * safe in SSO or versions of OpenGL where interpolation qualifiers are not
1563 * guaranteed to match across stages.
1564 */
1565 const bool disable_varying_packing;
1566
1567 /**
1568 * If true, this driver has transform feedback enabled. The transform
1569 * feedback code requires at least some packing be done even when varying
1570 * packing is disabled, fortunately where transform feedback requires
1571 * packing it's safe to override the disabled setting. See
1572 * is_varying_packing_safe().
1573 */
1574 const bool xfb_enabled;
1575
1576 const bool enhanced_layouts_enabled;
1577
1578 /**
1579 * Enum representing the order in which varyings are packed within a
1580 * packing class.
1581 *
1582 * Currently we pack vec4's first, then vec2's, then scalar values, then
1583 * vec3's. This order ensures that the only vectors that are at risk of
1584 * having to be "double parked" (split between two adjacent varying slots)
1585 * are the vec3's.
1586 */
1587 enum packing_order_enum {
1588 PACKING_ORDER_VEC4,
1589 PACKING_ORDER_VEC2,
1590 PACKING_ORDER_SCALAR,
1591 PACKING_ORDER_VEC3,
1592 };
1593
1594 static unsigned compute_packing_class(const ir_variable *var);
1595 static packing_order_enum compute_packing_order(const ir_variable *var);
1596 static int match_comparator(const void *x_generic, const void *y_generic);
1597 static int xfb_comparator(const void *x_generic, const void *y_generic);
1598
1599 /**
1600 * Structure recording the relationship between a single producer output
1601 * and a single consumer input.
1602 */
1603 struct match {
1604 /**
1605 * Packing class for this varying, computed by compute_packing_class().
1606 */
1607 unsigned packing_class;
1608
1609 /**
1610 * Packing order for this varying, computed by compute_packing_order().
1611 */
1612 packing_order_enum packing_order;
1613 unsigned num_components;
1614
1615 /**
1616 * The output variable in the producer stage.
1617 */
1618 ir_variable *producer_var;
1619
1620 /**
1621 * The input variable in the consumer stage.
1622 */
1623 ir_variable *consumer_var;
1624
1625 /**
1626 * The location which has been assigned for this varying. This is
1627 * expressed in multiples of a float, with the first generic varying
1628 * (i.e. the one referred to by VARYING_SLOT_VAR0) represented by the
1629 * value 0.
1630 */
1631 unsigned generic_location;
1632 } *matches;
1633
1634 /**
1635 * The number of elements in the \c matches array that are currently in
1636 * use.
1637 */
1638 unsigned num_matches;
1639
1640 /**
1641 * The number of elements that were set aside for the \c matches array when
1642 * it was allocated.
1643 */
1644 unsigned matches_capacity;
1645
1646 gl_shader_stage producer_stage;
1647 gl_shader_stage consumer_stage;
1648 };
1649
1650 } /* anonymous namespace */
1651
1652 varying_matches::varying_matches(bool disable_varying_packing,
1653 bool xfb_enabled,
1654 bool enhanced_layouts_enabled,
1655 gl_shader_stage producer_stage,
1656 gl_shader_stage consumer_stage)
1657 : disable_varying_packing(disable_varying_packing),
1658 xfb_enabled(xfb_enabled),
1659 enhanced_layouts_enabled(enhanced_layouts_enabled),
1660 producer_stage(producer_stage),
1661 consumer_stage(consumer_stage)
1662 {
1663 /* Note: this initial capacity is rather arbitrarily chosen to be large
1664 * enough for many cases without wasting an unreasonable amount of space.
1665 * varying_matches::record() will resize the array if there are more than
1666 * this number of varyings.
1667 */
1668 this->matches_capacity = 8;
1669 this->matches = (match *)
1670 malloc(sizeof(*this->matches) * this->matches_capacity);
1671 this->num_matches = 0;
1672 }
1673
1674
1675 varying_matches::~varying_matches()
1676 {
1677 free(this->matches);
1678 }
1679
1680
1681 /**
1682 * Packing is always safe on individual arrays, structures, and matrices. It
1683 * is also safe if the varying is only used for transform feedback.
1684 */
1685 bool
1686 varying_matches::is_varying_packing_safe(const glsl_type *type,
1687 const ir_variable *var) const
1688 {
1689 if (consumer_stage == MESA_SHADER_TESS_EVAL ||
1690 consumer_stage == MESA_SHADER_TESS_CTRL ||
1691 producer_stage == MESA_SHADER_TESS_CTRL)
1692 return false;
1693
1694 return xfb_enabled && (type->is_array() || type->is_struct() ||
1695 type->is_matrix() || var->data.is_xfb_only);
1696 }
1697
1698
1699 /**
1700 * Record the given producer/consumer variable pair in the list of variables
1701 * that should later be assigned locations.
1702 *
1703 * It is permissible for \c consumer_var to be NULL (this happens if a
1704 * variable is output by the producer and consumed by transform feedback, but
1705 * not consumed by the consumer).
1706 *
1707 * If \c producer_var has already been paired up with a consumer_var, or
1708 * producer_var is part of fixed pipeline functionality (and hence already has
1709 * a location assigned), this function has no effect.
1710 *
1711 * Note: as a side effect this function may change the interpolation type of
1712 * \c producer_var, but only when the change couldn't possibly affect
1713 * rendering.
1714 */
1715 void
1716 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
1717 {
1718 assert(producer_var != NULL || consumer_var != NULL);
1719
1720 if ((producer_var && (!producer_var->data.is_unmatched_generic_inout ||
1721 producer_var->data.explicit_location)) ||
1722 (consumer_var && (!consumer_var->data.is_unmatched_generic_inout ||
1723 consumer_var->data.explicit_location))) {
1724 /* Either a location already exists for this variable (since it is part
1725 * of fixed functionality), or it has already been recorded as part of a
1726 * previous match.
1727 */
1728 return;
1729 }
1730
1731 bool needs_flat_qualifier = consumer_var == NULL &&
1732 (producer_var->type->contains_integer() ||
1733 producer_var->type->contains_double());
1734
1735 if (!disable_varying_packing &&
1736 (needs_flat_qualifier ||
1737 (consumer_stage != MESA_SHADER_NONE && consumer_stage != MESA_SHADER_FRAGMENT))) {
1738 /* Since this varying is not being consumed by the fragment shader, its
1739 * interpolation type varying cannot possibly affect rendering.
1740 * Also, this variable is non-flat and is (or contains) an integer
1741 * or a double.
1742 * If the consumer stage is unknown, don't modify the interpolation
1743 * type as it could affect rendering later with separate shaders.
1744 *
1745 * lower_packed_varyings requires all integer varyings to flat,
1746 * regardless of where they appear. We can trivially satisfy that
1747 * requirement by changing the interpolation type to flat here.
1748 */
1749 if (producer_var) {
1750 producer_var->data.centroid = false;
1751 producer_var->data.sample = false;
1752 producer_var->data.interpolation = INTERP_MODE_FLAT;
1753 }
1754
1755 if (consumer_var) {
1756 consumer_var->data.centroid = false;
1757 consumer_var->data.sample = false;
1758 consumer_var->data.interpolation = INTERP_MODE_FLAT;
1759 }
1760 }
1761
1762 if (this->num_matches == this->matches_capacity) {
1763 this->matches_capacity *= 2;
1764 this->matches = (match *)
1765 realloc(this->matches,
1766 sizeof(*this->matches) * this->matches_capacity);
1767 }
1768
1769 /* We must use the consumer to compute the packing class because in GL4.4+
1770 * there is no guarantee interpolation qualifiers will match across stages.
1771 *
1772 * From Section 4.5 (Interpolation Qualifiers) of the GLSL 4.30 spec:
1773 *
1774 * "The type and presence of interpolation qualifiers of variables with
1775 * the same name declared in all linked shaders for the same cross-stage
1776 * interface must match, otherwise the link command will fail.
1777 *
1778 * When comparing an output from one stage to an input of a subsequent
1779 * stage, the input and output don't match if their interpolation
1780 * qualifiers (or lack thereof) are not the same."
1781 *
1782 * This text was also in at least revison 7 of the 4.40 spec but is no
1783 * longer in revision 9 and not in the 4.50 spec.
1784 */
1785 const ir_variable *const var = (consumer_var != NULL)
1786 ? consumer_var : producer_var;
1787 const gl_shader_stage stage = (consumer_var != NULL)
1788 ? consumer_stage : producer_stage;
1789 const glsl_type *type = get_varying_type(var, stage);
1790
1791 if (producer_var && consumer_var &&
1792 consumer_var->data.must_be_shader_input) {
1793 producer_var->data.must_be_shader_input = 1;
1794 }
1795
1796 this->matches[this->num_matches].packing_class
1797 = this->compute_packing_class(var);
1798 this->matches[this->num_matches].packing_order
1799 = this->compute_packing_order(var);
1800 if ((this->disable_varying_packing && !is_varying_packing_safe(type, var)) ||
1801 var->data.must_be_shader_input) {
1802 unsigned slots = type->count_attribute_slots(false);
1803 this->matches[this->num_matches].num_components = slots * 4;
1804 } else {
1805 this->matches[this->num_matches].num_components
1806 = type->component_slots();
1807 }
1808
1809 this->matches[this->num_matches].producer_var = producer_var;
1810 this->matches[this->num_matches].consumer_var = consumer_var;
1811 this->num_matches++;
1812 if (producer_var)
1813 producer_var->data.is_unmatched_generic_inout = 0;
1814 if (consumer_var)
1815 consumer_var->data.is_unmatched_generic_inout = 0;
1816 }
1817
1818
1819 /**
1820 * Choose locations for all of the variable matches that were previously
1821 * passed to varying_matches::record().
1822 * \param components returns array[slot] of number of components used
1823 * per slot (1, 2, 3 or 4)
1824 * \param reserved_slots bitmask indicating which varying slots are already
1825 * allocated
1826 * \return number of slots (4-element vectors) allocated
1827 */
1828 unsigned
1829 varying_matches::assign_locations(struct gl_shader_program *prog,
1830 uint8_t components[],
1831 uint64_t reserved_slots)
1832 {
1833 /* If packing has been disabled then we cannot safely sort the varyings by
1834 * class as it may mean we are using a version of OpenGL where
1835 * interpolation qualifiers are not guaranteed to be matching across
1836 * shaders, sorting in this case could result in mismatching shader
1837 * interfaces.
1838 * When packing is disabled the sort orders varyings used by transform
1839 * feedback first, but also depends on *undefined behaviour* of qsort to
1840 * reverse the order of the varyings. See: xfb_comparator().
1841 */
1842 if (!this->disable_varying_packing) {
1843 /* Sort varying matches into an order that makes them easy to pack. */
1844 qsort(this->matches, this->num_matches, sizeof(*this->matches),
1845 &varying_matches::match_comparator);
1846 } else {
1847 /* Only sort varyings that are only used by transform feedback. */
1848 qsort(this->matches, this->num_matches, sizeof(*this->matches),
1849 &varying_matches::xfb_comparator);
1850 }
1851
1852 unsigned generic_location = 0;
1853 unsigned generic_patch_location = MAX_VARYING*4;
1854 bool previous_var_xfb_only = false;
1855 unsigned previous_packing_class = ~0u;
1856
1857 /* For tranform feedback separate mode, we know the number of attributes
1858 * is <= the number of buffers. So packing isn't critical. In fact,
1859 * packing vec3 attributes can cause trouble because splitting a vec3
1860 * effectively creates an additional transform feedback output. The
1861 * extra TFB output may exceed device driver limits.
1862 */
1863 const bool dont_pack_vec3 =
1864 (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1865 prog->TransformFeedback.NumVarying > 0);
1866
1867 for (unsigned i = 0; i < this->num_matches; i++) {
1868 unsigned *location = &generic_location;
1869 const ir_variable *var;
1870 const glsl_type *type;
1871 bool is_vertex_input = false;
1872
1873 if (matches[i].consumer_var) {
1874 var = matches[i].consumer_var;
1875 type = get_varying_type(var, consumer_stage);
1876 if (consumer_stage == MESA_SHADER_VERTEX)
1877 is_vertex_input = true;
1878 } else {
1879 var = matches[i].producer_var;
1880 type = get_varying_type(var, producer_stage);
1881 }
1882
1883 if (var->data.patch)
1884 location = &generic_patch_location;
1885
1886 /* Advance to the next slot if this varying has a different packing
1887 * class than the previous one, and we're not already on a slot
1888 * boundary.
1889 *
1890 * Also advance to the next slot if packing is disabled. This makes sure
1891 * we don't assign varyings the same locations which is possible
1892 * because we still pack individual arrays, records and matrices even
1893 * when packing is disabled. Note we don't advance to the next slot if
1894 * we can pack varyings together that are only used for transform
1895 * feedback.
1896 */
1897 if (var->data.must_be_shader_input ||
1898 (this->disable_varying_packing &&
1899 !(previous_var_xfb_only && var->data.is_xfb_only)) ||
1900 (previous_packing_class != this->matches[i].packing_class) ||
1901 (this->matches[i].packing_order == PACKING_ORDER_VEC3 &&
1902 dont_pack_vec3)) {
1903 *location = ALIGN(*location, 4);
1904 }
1905
1906 previous_var_xfb_only = var->data.is_xfb_only;
1907 previous_packing_class = this->matches[i].packing_class;
1908
1909 /* The number of components taken up by this variable. For vertex shader
1910 * inputs, we use the number of slots * 4, as they have different
1911 * counting rules.
1912 */
1913 unsigned num_components = is_vertex_input ?
1914 type->count_attribute_slots(is_vertex_input) * 4 :
1915 this->matches[i].num_components;
1916
1917 /* The last slot for this variable, inclusive. */
1918 unsigned slot_end = *location + num_components - 1;
1919
1920 /* FIXME: We could be smarter in the below code and loop back over
1921 * trying to fill any locations that we skipped because we couldn't pack
1922 * the varying between an explicit location. For now just let the user
1923 * hit the linking error if we run out of room and suggest they use
1924 * explicit locations.
1925 */
1926 while (slot_end < MAX_VARYING * 4u) {
1927 const unsigned slots = (slot_end / 4u) - (*location / 4u) + 1;
1928 const uint64_t slot_mask = ((1ull << slots) - 1) << (*location / 4u);
1929
1930 assert(slots > 0);
1931
1932 if ((reserved_slots & slot_mask) == 0) {
1933 break;
1934 }
1935
1936 *location = ALIGN(*location + 1, 4);
1937 slot_end = *location + num_components - 1;
1938 }
1939
1940 if (!var->data.patch && slot_end >= MAX_VARYING * 4u) {
1941 linker_error(prog, "insufficient contiguous locations available for "
1942 "%s it is possible an array or struct could not be "
1943 "packed between varyings with explicit locations. Try "
1944 "using an explicit location for arrays and structs.",
1945 var->name);
1946 }
1947
1948 if (slot_end < MAX_VARYINGS_INCL_PATCH * 4u) {
1949 for (unsigned j = *location / 4u; j < slot_end / 4u; j++)
1950 components[j] = 4;
1951 components[slot_end / 4u] = (slot_end & 3) + 1;
1952 }
1953
1954 this->matches[i].generic_location = *location;
1955
1956 *location = slot_end + 1;
1957 }
1958
1959 return (generic_location + 3) / 4;
1960 }
1961
1962
1963 /**
1964 * Update the producer and consumer shaders to reflect the locations
1965 * assignments that were made by varying_matches::assign_locations().
1966 */
1967 void
1968 varying_matches::store_locations() const
1969 {
1970 /* Check is location needs to be packed with lower_packed_varyings() or if
1971 * we can just use ARB_enhanced_layouts packing.
1972 */
1973 bool pack_loc[MAX_VARYINGS_INCL_PATCH] = { 0 };
1974 const glsl_type *loc_type[MAX_VARYINGS_INCL_PATCH][4] = { {NULL, NULL} };
1975
1976 for (unsigned i = 0; i < this->num_matches; i++) {
1977 ir_variable *producer_var = this->matches[i].producer_var;
1978 ir_variable *consumer_var = this->matches[i].consumer_var;
1979 unsigned generic_location = this->matches[i].generic_location;
1980 unsigned slot = generic_location / 4;
1981 unsigned offset = generic_location % 4;
1982
1983 if (producer_var) {
1984 producer_var->data.location = VARYING_SLOT_VAR0 + slot;
1985 producer_var->data.location_frac = offset;
1986 }
1987
1988 if (consumer_var) {
1989 assert(consumer_var->data.location == -1);
1990 consumer_var->data.location = VARYING_SLOT_VAR0 + slot;
1991 consumer_var->data.location_frac = offset;
1992 }
1993
1994 /* Find locations suitable for native packing via
1995 * ARB_enhanced_layouts.
1996 */
1997 if (producer_var && consumer_var) {
1998 if (enhanced_layouts_enabled) {
1999 const glsl_type *type =
2000 get_varying_type(producer_var, producer_stage);
2001 if (type->is_array() || type->is_matrix() || type->is_struct() ||
2002 type->is_double()) {
2003 unsigned comp_slots = type->component_slots() + offset;
2004 unsigned slots = comp_slots / 4;
2005 if (comp_slots % 4)
2006 slots += 1;
2007
2008 for (unsigned j = 0; j < slots; j++) {
2009 pack_loc[slot + j] = true;
2010 }
2011 } else if (offset + type->vector_elements > 4) {
2012 pack_loc[slot] = true;
2013 pack_loc[slot + 1] = true;
2014 } else {
2015 loc_type[slot][offset] = type;
2016 }
2017 }
2018 }
2019 }
2020
2021 /* Attempt to use ARB_enhanced_layouts for more efficient packing if
2022 * suitable.
2023 */
2024 if (enhanced_layouts_enabled) {
2025 for (unsigned i = 0; i < this->num_matches; i++) {
2026 ir_variable *producer_var = this->matches[i].producer_var;
2027 ir_variable *consumer_var = this->matches[i].consumer_var;
2028 unsigned generic_location = this->matches[i].generic_location;
2029 unsigned slot = generic_location / 4;
2030
2031 if (pack_loc[slot] || !producer_var || !consumer_var)
2032 continue;
2033
2034 const glsl_type *type =
2035 get_varying_type(producer_var, producer_stage);
2036 bool type_match = true;
2037 for (unsigned j = 0; j < 4; j++) {
2038 if (loc_type[slot][j]) {
2039 if (type->base_type != loc_type[slot][j]->base_type)
2040 type_match = false;
2041 }
2042 }
2043
2044 if (type_match) {
2045 producer_var->data.explicit_location = 1;
2046 consumer_var->data.explicit_location = 1;
2047 producer_var->data.explicit_component = 1;
2048 consumer_var->data.explicit_component = 1;
2049 }
2050 }
2051 }
2052 }
2053
2054
2055 /**
2056 * Compute the "packing class" of the given varying. This is an unsigned
2057 * integer with the property that two variables in the same packing class can
2058 * be safely backed into the same vec4.
2059 */
2060 unsigned
2061 varying_matches::compute_packing_class(const ir_variable *var)
2062 {
2063 /* Without help from the back-end, there is no way to pack together
2064 * variables with different interpolation types, because
2065 * lower_packed_varyings must choose exactly one interpolation type for
2066 * each packed varying it creates.
2067 *
2068 * However, we can safely pack together floats, ints, and uints, because:
2069 *
2070 * - varyings of base type "int" and "uint" must use the "flat"
2071 * interpolation type, which can only occur in GLSL 1.30 and above.
2072 *
2073 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
2074 * can store flat floats as ints without losing any information (using
2075 * the ir_unop_bitcast_* opcodes).
2076 *
2077 * Therefore, the packing class depends only on the interpolation type.
2078 */
2079 const unsigned interp = var->is_interpolation_flat()
2080 ? unsigned(INTERP_MODE_FLAT) : var->data.interpolation;
2081
2082 assert(interp < (1 << 3));
2083
2084 const unsigned packing_class = (interp << 0) |
2085 (var->data.centroid << 3) |
2086 (var->data.sample << 4) |
2087 (var->data.patch << 5) |
2088 (var->data.must_be_shader_input << 6);
2089
2090 return packing_class;
2091 }
2092
2093
2094 /**
2095 * Compute the "packing order" of the given varying. This is a sort key we
2096 * use to determine when to attempt to pack the given varying relative to
2097 * other varyings in the same packing class.
2098 */
2099 varying_matches::packing_order_enum
2100 varying_matches::compute_packing_order(const ir_variable *var)
2101 {
2102 const glsl_type *element_type = var->type;
2103
2104 while (element_type->is_array()) {
2105 element_type = element_type->fields.array;
2106 }
2107
2108 switch (element_type->component_slots() % 4) {
2109 case 1: return PACKING_ORDER_SCALAR;
2110 case 2: return PACKING_ORDER_VEC2;
2111 case 3: return PACKING_ORDER_VEC3;
2112 case 0: return PACKING_ORDER_VEC4;
2113 default:
2114 assert(!"Unexpected value of vector_elements");
2115 return PACKING_ORDER_VEC4;
2116 }
2117 }
2118
2119
2120 /**
2121 * Comparison function passed to qsort() to sort varyings by packing_class and
2122 * then by packing_order.
2123 */
2124 int
2125 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
2126 {
2127 const match *x = (const match *) x_generic;
2128 const match *y = (const match *) y_generic;
2129
2130 if (x->packing_class != y->packing_class)
2131 return x->packing_class - y->packing_class;
2132 return x->packing_order - y->packing_order;
2133 }
2134
2135
2136 /**
2137 * Comparison function passed to qsort() to sort varyings used only by
2138 * transform feedback when packing of other varyings is disabled.
2139 */
2140 int
2141 varying_matches::xfb_comparator(const void *x_generic, const void *y_generic)
2142 {
2143 const match *x = (const match *) x_generic;
2144
2145 if (x->producer_var != NULL && x->producer_var->data.is_xfb_only)
2146 return match_comparator(x_generic, y_generic);
2147
2148 /* FIXME: When the comparator returns 0 it means the elements being
2149 * compared are equivalent. However the qsort documentation says:
2150 *
2151 * "The order of equivalent elements is undefined."
2152 *
2153 * In practice the sort ends up reversing the order of the varyings which
2154 * means locations are also assigned in this reversed order and happens to
2155 * be what we want. This is also whats happening in
2156 * varying_matches::match_comparator().
2157 */
2158 return 0;
2159 }
2160
2161
2162 /**
2163 * Is the given variable a varying variable to be counted against the
2164 * limit in ctx->Const.MaxVarying?
2165 * This includes variables such as texcoords, colors and generic
2166 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
2167 */
2168 static bool
2169 var_counts_against_varying_limit(gl_shader_stage stage, const ir_variable *var)
2170 {
2171 /* Only fragment shaders will take a varying variable as an input */
2172 if (stage == MESA_SHADER_FRAGMENT &&
2173 var->data.mode == ir_var_shader_in) {
2174 switch (var->data.location) {
2175 case VARYING_SLOT_POS:
2176 case VARYING_SLOT_FACE:
2177 case VARYING_SLOT_PNTC:
2178 return false;
2179 default:
2180 return true;
2181 }
2182 }
2183 return false;
2184 }
2185
2186
2187 /**
2188 * Visitor class that generates tfeedback_candidate structs describing all
2189 * possible targets of transform feedback.
2190 *
2191 * tfeedback_candidate structs are stored in the hash table
2192 * tfeedback_candidates, which is passed to the constructor. This hash table
2193 * maps varying names to instances of the tfeedback_candidate struct.
2194 */
2195 class tfeedback_candidate_generator : public program_resource_visitor
2196 {
2197 public:
2198 tfeedback_candidate_generator(void *mem_ctx,
2199 hash_table *tfeedback_candidates,
2200 gl_shader_stage stage)
2201 : mem_ctx(mem_ctx),
2202 tfeedback_candidates(tfeedback_candidates),
2203 stage(stage),
2204 toplevel_var(NULL),
2205 varying_floats(0)
2206 {
2207 }
2208
2209 void process(ir_variable *var)
2210 {
2211 /* All named varying interface blocks should be flattened by now */
2212 assert(!var->is_interface_instance());
2213 assert(var->data.mode == ir_var_shader_out);
2214
2215 this->toplevel_var = var;
2216 this->varying_floats = 0;
2217 const glsl_type *t =
2218 var->data.from_named_ifc_block ? var->get_interface_type() : var->type;
2219 if (!var->data.patch && stage == MESA_SHADER_TESS_CTRL) {
2220 assert(t->is_array());
2221 t = t->fields.array;
2222 }
2223 program_resource_visitor::process(var, t, false);
2224 }
2225
2226 private:
2227 virtual void visit_field(const glsl_type *type, const char *name,
2228 bool /* row_major */,
2229 const glsl_type * /* record_type */,
2230 const enum glsl_interface_packing,
2231 bool /* last_field */)
2232 {
2233 assert(!type->without_array()->is_struct());
2234 assert(!type->without_array()->is_interface());
2235
2236 tfeedback_candidate *candidate
2237 = rzalloc(this->mem_ctx, tfeedback_candidate);
2238 candidate->toplevel_var = this->toplevel_var;
2239 candidate->type = type;
2240 candidate->offset = this->varying_floats;
2241 _mesa_hash_table_insert(this->tfeedback_candidates,
2242 ralloc_strdup(this->mem_ctx, name),
2243 candidate);
2244 this->varying_floats += type->component_slots();
2245 }
2246
2247 /**
2248 * Memory context used to allocate hash table keys and values.
2249 */
2250 void * const mem_ctx;
2251
2252 /**
2253 * Hash table in which tfeedback_candidate objects should be stored.
2254 */
2255 hash_table * const tfeedback_candidates;
2256
2257 gl_shader_stage stage;
2258
2259 /**
2260 * Pointer to the toplevel variable that is being traversed.
2261 */
2262 ir_variable *toplevel_var;
2263
2264 /**
2265 * Total number of varying floats that have been visited so far. This is
2266 * used to determine the offset to each varying within the toplevel
2267 * variable.
2268 */
2269 unsigned varying_floats;
2270 };
2271
2272
2273 namespace linker {
2274
2275 void
2276 populate_consumer_input_sets(void *mem_ctx, exec_list *ir,
2277 hash_table *consumer_inputs,
2278 hash_table *consumer_interface_inputs,
2279 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
2280 {
2281 memset(consumer_inputs_with_locations,
2282 0,
2283 sizeof(consumer_inputs_with_locations[0]) * VARYING_SLOT_TESS_MAX);
2284
2285 foreach_in_list(ir_instruction, node, ir) {
2286 ir_variable *const input_var = node->as_variable();
2287
2288 if (input_var != NULL && input_var->data.mode == ir_var_shader_in) {
2289 /* All interface blocks should have been lowered by this point */
2290 assert(!input_var->type->is_interface());
2291
2292 if (input_var->data.explicit_location) {
2293 /* assign_varying_locations only cares about finding the
2294 * ir_variable at the start of a contiguous location block.
2295 *
2296 * - For !producer, consumer_inputs_with_locations isn't used.
2297 *
2298 * - For !consumer, consumer_inputs_with_locations is empty.
2299 *
2300 * For consumer && producer, if you were trying to set some
2301 * ir_variable to the middle of a location block on the other side
2302 * of producer/consumer, cross_validate_outputs_to_inputs() should
2303 * be link-erroring due to either type mismatch or location
2304 * overlaps. If the variables do match up, then they've got a
2305 * matching data.location and you only looked at
2306 * consumer_inputs_with_locations[var->data.location], not any
2307 * following entries for the array/structure.
2308 */
2309 consumer_inputs_with_locations[input_var->data.location] =
2310 input_var;
2311 } else if (input_var->get_interface_type() != NULL) {
2312 char *const iface_field_name =
2313 ralloc_asprintf(mem_ctx, "%s.%s",
2314 input_var->get_interface_type()->without_array()->name,
2315 input_var->name);
2316 _mesa_hash_table_insert(consumer_interface_inputs,
2317 iface_field_name, input_var);
2318 } else {
2319 _mesa_hash_table_insert(consumer_inputs,
2320 ralloc_strdup(mem_ctx, input_var->name),
2321 input_var);
2322 }
2323 }
2324 }
2325 }
2326
2327 /**
2328 * Find a variable from the consumer that "matches" the specified variable
2329 *
2330 * This function only finds inputs with names that match. There is no
2331 * validation (here) that the types, etc. are compatible.
2332 */
2333 ir_variable *
2334 get_matching_input(void *mem_ctx,
2335 const ir_variable *output_var,
2336 hash_table *consumer_inputs,
2337 hash_table *consumer_interface_inputs,
2338 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
2339 {
2340 ir_variable *input_var;
2341
2342 if (output_var->data.explicit_location) {
2343 input_var = consumer_inputs_with_locations[output_var->data.location];
2344 } else if (output_var->get_interface_type() != NULL) {
2345 char *const iface_field_name =
2346 ralloc_asprintf(mem_ctx, "%s.%s",
2347 output_var->get_interface_type()->without_array()->name,
2348 output_var->name);
2349 hash_entry *entry = _mesa_hash_table_search(consumer_interface_inputs, iface_field_name);
2350 input_var = entry ? (ir_variable *) entry->data : NULL;
2351 } else {
2352 hash_entry *entry = _mesa_hash_table_search(consumer_inputs, output_var->name);
2353 input_var = entry ? (ir_variable *) entry->data : NULL;
2354 }
2355
2356 return (input_var == NULL || input_var->data.mode != ir_var_shader_in)
2357 ? NULL : input_var;
2358 }
2359
2360 }
2361
2362 static int
2363 io_variable_cmp(const void *_a, const void *_b)
2364 {
2365 const ir_variable *const a = *(const ir_variable **) _a;
2366 const ir_variable *const b = *(const ir_variable **) _b;
2367
2368 if (a->data.explicit_location && b->data.explicit_location)
2369 return b->data.location - a->data.location;
2370
2371 if (a->data.explicit_location && !b->data.explicit_location)
2372 return 1;
2373
2374 if (!a->data.explicit_location && b->data.explicit_location)
2375 return -1;
2376
2377 return -strcmp(a->name, b->name);
2378 }
2379
2380 /**
2381 * Sort the shader IO variables into canonical order
2382 */
2383 static void
2384 canonicalize_shader_io(exec_list *ir, enum ir_variable_mode io_mode)
2385 {
2386 ir_variable *var_table[MAX_PROGRAM_OUTPUTS * 4];
2387 unsigned num_variables = 0;
2388
2389 foreach_in_list(ir_instruction, node, ir) {
2390 ir_variable *const var = node->as_variable();
2391
2392 if (var == NULL || var->data.mode != io_mode)
2393 continue;
2394
2395 /* If we have already encountered more I/O variables that could
2396 * successfully link, bail.
2397 */
2398 if (num_variables == ARRAY_SIZE(var_table))
2399 return;
2400
2401 var_table[num_variables++] = var;
2402 }
2403
2404 if (num_variables == 0)
2405 return;
2406
2407 /* Sort the list in reverse order (io_variable_cmp handles this). Later
2408 * we're going to push the variables on to the IR list as a stack, so we
2409 * want the last variable (in canonical order) to be first in the list.
2410 */
2411 qsort(var_table, num_variables, sizeof(var_table[0]), io_variable_cmp);
2412
2413 /* Remove the variable from it's current location in the IR, and put it at
2414 * the front.
2415 */
2416 for (unsigned i = 0; i < num_variables; i++) {
2417 var_table[i]->remove();
2418 ir->push_head(var_table[i]);
2419 }
2420 }
2421
2422 /**
2423 * Generate a bitfield map of the explicit locations for shader varyings.
2424 *
2425 * Note: For Tessellation shaders we are sitting right on the limits of the
2426 * 64 bit map. Per-vertex and per-patch both have separate location domains
2427 * with a max of MAX_VARYING.
2428 */
2429 static uint64_t
2430 reserved_varying_slot(struct gl_linked_shader *stage,
2431 ir_variable_mode io_mode)
2432 {
2433 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
2434 /* Avoid an overflow of the returned value */
2435 assert(MAX_VARYINGS_INCL_PATCH <= 64);
2436
2437 uint64_t slots = 0;
2438 int var_slot;
2439
2440 if (!stage)
2441 return slots;
2442
2443 foreach_in_list(ir_instruction, node, stage->ir) {
2444 ir_variable *const var = node->as_variable();
2445
2446 if (var == NULL || var->data.mode != io_mode ||
2447 !var->data.explicit_location ||
2448 var->data.location < VARYING_SLOT_VAR0)
2449 continue;
2450
2451 var_slot = var->data.location - VARYING_SLOT_VAR0;
2452
2453 unsigned num_elements = get_varying_type(var, stage->Stage)
2454 ->count_attribute_slots(io_mode == ir_var_shader_in &&
2455 stage->Stage == MESA_SHADER_VERTEX);
2456 for (unsigned i = 0; i < num_elements; i++) {
2457 if (var_slot >= 0 && var_slot < MAX_VARYINGS_INCL_PATCH)
2458 slots |= UINT64_C(1) << var_slot;
2459 var_slot += 1;
2460 }
2461 }
2462
2463 return slots;
2464 }
2465
2466
2467 /**
2468 * Assign locations for all variables that are produced in one pipeline stage
2469 * (the "producer") and consumed in the next stage (the "consumer").
2470 *
2471 * Variables produced by the producer may also be consumed by transform
2472 * feedback.
2473 *
2474 * \param num_tfeedback_decls is the number of declarations indicating
2475 * variables that may be consumed by transform feedback.
2476 *
2477 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
2478 * representing the result of parsing the strings passed to
2479 * glTransformFeedbackVaryings(). assign_location() will be called for
2480 * each of these objects that matches one of the outputs of the
2481 * producer.
2482 *
2483 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
2484 * be NULL. In this case, varying locations are assigned solely based on the
2485 * requirements of transform feedback.
2486 */
2487 static bool
2488 assign_varying_locations(struct gl_context *ctx,
2489 void *mem_ctx,
2490 struct gl_shader_program *prog,
2491 gl_linked_shader *producer,
2492 gl_linked_shader *consumer,
2493 unsigned num_tfeedback_decls,
2494 tfeedback_decl *tfeedback_decls,
2495 const uint64_t reserved_slots)
2496 {
2497 /* Tessellation shaders treat inputs and outputs as shared memory and can
2498 * access inputs and outputs of other invocations.
2499 * Therefore, they can't be lowered to temps easily (and definitely not
2500 * efficiently).
2501 */
2502 bool unpackable_tess =
2503 (consumer && consumer->Stage == MESA_SHADER_TESS_EVAL) ||
2504 (consumer && consumer->Stage == MESA_SHADER_TESS_CTRL) ||
2505 (producer && producer->Stage == MESA_SHADER_TESS_CTRL);
2506
2507 /* Transform feedback code assumes varying arrays are packed, so if the
2508 * driver has disabled varying packing, make sure to at least enable
2509 * packing required by transform feedback.
2510 */
2511 bool xfb_enabled =
2512 ctx->Extensions.EXT_transform_feedback && !unpackable_tess;
2513
2514 /* Disable packing on outward facing interfaces for SSO because in ES we
2515 * need to retain the unpacked varying information for draw time
2516 * validation.
2517 *
2518 * Packing is still enabled on individual arrays, structs, and matrices as
2519 * these are required by the transform feedback code and it is still safe
2520 * to do so. We also enable packing when a varying is only used for
2521 * transform feedback and its not a SSO.
2522 */
2523 bool disable_varying_packing =
2524 ctx->Const.DisableVaryingPacking || unpackable_tess;
2525 if (prog->SeparateShader && (producer == NULL || consumer == NULL))
2526 disable_varying_packing = true;
2527
2528 varying_matches matches(disable_varying_packing, xfb_enabled,
2529 ctx->Extensions.ARB_enhanced_layouts,
2530 producer ? producer->Stage : MESA_SHADER_NONE,
2531 consumer ? consumer->Stage : MESA_SHADER_NONE);
2532 hash_table *tfeedback_candidates =
2533 _mesa_hash_table_create(NULL, _mesa_key_hash_string,
2534 _mesa_key_string_equal);
2535 hash_table *consumer_inputs =
2536 _mesa_hash_table_create(NULL, _mesa_key_hash_string,
2537 _mesa_key_string_equal);
2538 hash_table *consumer_interface_inputs =
2539 _mesa_hash_table_create(NULL, _mesa_key_hash_string,
2540 _mesa_key_string_equal);
2541 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX] = {
2542 NULL,
2543 };
2544
2545 unsigned consumer_vertices = 0;
2546 if (consumer && consumer->Stage == MESA_SHADER_GEOMETRY)
2547 consumer_vertices = prog->Geom.VerticesIn;
2548
2549 /* Operate in a total of four passes.
2550 *
2551 * 1. Sort inputs / outputs into a canonical order. This is necessary so
2552 * that inputs / outputs of separable shaders will be assigned
2553 * predictable locations regardless of the order in which declarations
2554 * appeared in the shader source.
2555 *
2556 * 2. Assign locations for any matching inputs and outputs.
2557 *
2558 * 3. Mark output variables in the producer that do not have locations as
2559 * not being outputs. This lets the optimizer eliminate them.
2560 *
2561 * 4. Mark input variables in the consumer that do not have locations as
2562 * not being inputs. This lets the optimizer eliminate them.
2563 */
2564 if (consumer)
2565 canonicalize_shader_io(consumer->ir, ir_var_shader_in);
2566
2567 if (producer)
2568 canonicalize_shader_io(producer->ir, ir_var_shader_out);
2569
2570 if (consumer)
2571 linker::populate_consumer_input_sets(mem_ctx, consumer->ir,
2572 consumer_inputs,
2573 consumer_interface_inputs,
2574 consumer_inputs_with_locations);
2575
2576 if (producer) {
2577 foreach_in_list(ir_instruction, node, producer->ir) {
2578 ir_variable *const output_var = node->as_variable();
2579
2580 if (output_var == NULL || output_var->data.mode != ir_var_shader_out)
2581 continue;
2582
2583 /* Only geometry shaders can use non-zero streams */
2584 assert(output_var->data.stream == 0 ||
2585 (output_var->data.stream < MAX_VERTEX_STREAMS &&
2586 producer->Stage == MESA_SHADER_GEOMETRY));
2587
2588 if (num_tfeedback_decls > 0) {
2589 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates, producer->Stage);
2590 /* From OpenGL 4.6 (Core Profile) spec, section 11.1.2.1
2591 * ("Vertex Shader Variables / Output Variables")
2592 *
2593 * "Each program object can specify a set of output variables from
2594 * one shader to be recorded in transform feedback mode (see
2595 * section 13.3). The variables that can be recorded are those
2596 * emitted by the first active shader, in order, from the
2597 * following list:
2598 *
2599 * * geometry shader
2600 * * tessellation evaluation shader
2601 * * tessellation control shader
2602 * * vertex shader"
2603 *
2604 * But on OpenGL ES 3.2, section 11.1.2.1 ("Vertex Shader
2605 * Variables / Output Variables") tessellation control shader is
2606 * not included in the stages list.
2607 */
2608 if (!prog->IsES || producer->Stage != MESA_SHADER_TESS_CTRL) {
2609 g.process(output_var);
2610 }
2611 }
2612
2613 ir_variable *const input_var =
2614 linker::get_matching_input(mem_ctx, output_var, consumer_inputs,
2615 consumer_interface_inputs,
2616 consumer_inputs_with_locations);
2617
2618 /* If a matching input variable was found, add this output (and the
2619 * input) to the set. If this is a separable program and there is no
2620 * consumer stage, add the output.
2621 *
2622 * Always add TCS outputs. They are shared by all invocations
2623 * within a patch and can be used as shared memory.
2624 */
2625 if (input_var || (prog->SeparateShader && consumer == NULL) ||
2626 producer->Stage == MESA_SHADER_TESS_CTRL) {
2627 matches.record(output_var, input_var);
2628 }
2629
2630 /* Only stream 0 outputs can be consumed in the next stage */
2631 if (input_var && output_var->data.stream != 0) {
2632 linker_error(prog, "output %s is assigned to stream=%d but "
2633 "is linked to an input, which requires stream=0",
2634 output_var->name, output_var->data.stream);
2635 return false;
2636 }
2637 }
2638 } else {
2639 /* If there's no producer stage, then this must be a separable program.
2640 * For example, we may have a program that has just a fragment shader.
2641 * Later this program will be used with some arbitrary vertex (or
2642 * geometry) shader program. This means that locations must be assigned
2643 * for all the inputs.
2644 */
2645 foreach_in_list(ir_instruction, node, consumer->ir) {
2646 ir_variable *const input_var = node->as_variable();
2647 if (input_var && input_var->data.mode == ir_var_shader_in) {
2648 matches.record(NULL, input_var);
2649 }
2650 }
2651 }
2652
2653 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2654 if (!tfeedback_decls[i].is_varying())
2655 continue;
2656
2657 const tfeedback_candidate *matched_candidate
2658 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
2659
2660 if (matched_candidate == NULL) {
2661 _mesa_hash_table_destroy(tfeedback_candidates, NULL);
2662 return false;
2663 }
2664
2665 /* Mark xfb varyings as always active */
2666 matched_candidate->toplevel_var->data.always_active_io = 1;
2667
2668 /* Mark any corresponding inputs as always active also. We must do this
2669 * because we have a NIR pass that lowers vectors to scalars and another
2670 * that removes unused varyings.
2671 * We don't split varyings marked as always active because there is no
2672 * point in doing so. This means we need to mark both sides of the
2673 * interface as always active otherwise we will have a mismatch and
2674 * start removing things we shouldn't.
2675 */
2676 ir_variable *const input_var =
2677 linker::get_matching_input(mem_ctx, matched_candidate->toplevel_var,
2678 consumer_inputs,
2679 consumer_interface_inputs,
2680 consumer_inputs_with_locations);
2681 if (input_var)
2682 input_var->data.always_active_io = 1;
2683
2684 if (matched_candidate->toplevel_var->data.is_unmatched_generic_inout) {
2685 matched_candidate->toplevel_var->data.is_xfb_only = 1;
2686 matches.record(matched_candidate->toplevel_var, NULL);
2687 }
2688 }
2689
2690 _mesa_hash_table_destroy(consumer_inputs, NULL);
2691 _mesa_hash_table_destroy(consumer_interface_inputs, NULL);
2692
2693 uint8_t components[MAX_VARYINGS_INCL_PATCH] = {0};
2694 const unsigned slots_used = matches.assign_locations(
2695 prog, components, reserved_slots);
2696 matches.store_locations();
2697
2698 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2699 if (tfeedback_decls[i].is_varying()) {
2700 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
2701 _mesa_hash_table_destroy(tfeedback_candidates, NULL);
2702 return false;
2703 }
2704 }
2705 }
2706 _mesa_hash_table_destroy(tfeedback_candidates, NULL);
2707
2708 if (consumer && producer) {
2709 foreach_in_list(ir_instruction, node, consumer->ir) {
2710 ir_variable *const var = node->as_variable();
2711
2712 if (var && var->data.mode == ir_var_shader_in &&
2713 var->data.is_unmatched_generic_inout) {
2714 if (!prog->IsES && prog->data->Version <= 120) {
2715 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
2716 *
2717 * Only those varying variables used (i.e. read) in
2718 * the fragment shader executable must be written to
2719 * by the vertex shader executable; declaring
2720 * superfluous varying variables in a vertex shader is
2721 * permissible.
2722 *
2723 * We interpret this text as meaning that the VS must
2724 * write the variable for the FS to read it. See
2725 * "glsl1-varying read but not written" in piglit.
2726 */
2727 linker_error(prog, "%s shader varying %s not written "
2728 "by %s shader\n.",
2729 _mesa_shader_stage_to_string(consumer->Stage),
2730 var->name,
2731 _mesa_shader_stage_to_string(producer->Stage));
2732 } else {
2733 linker_warning(prog, "%s shader varying %s not written "
2734 "by %s shader\n.",
2735 _mesa_shader_stage_to_string(consumer->Stage),
2736 var->name,
2737 _mesa_shader_stage_to_string(producer->Stage));
2738 }
2739 }
2740 }
2741
2742 /* Now that validation is done its safe to remove unused varyings. As
2743 * we have both a producer and consumer its safe to remove unused
2744 * varyings even if the program is a SSO because the stages are being
2745 * linked together i.e. we have a multi-stage SSO.
2746 */
2747 remove_unused_shader_inputs_and_outputs(false, producer,
2748 ir_var_shader_out);
2749 remove_unused_shader_inputs_and_outputs(false, consumer,
2750 ir_var_shader_in);
2751 }
2752
2753 if (producer) {
2754 lower_packed_varyings(mem_ctx, slots_used, components, ir_var_shader_out,
2755 0, producer, disable_varying_packing,
2756 xfb_enabled);
2757 }
2758
2759 if (consumer) {
2760 lower_packed_varyings(mem_ctx, slots_used, components, ir_var_shader_in,
2761 consumer_vertices, consumer,
2762 disable_varying_packing, xfb_enabled);
2763 }
2764
2765 return true;
2766 }
2767
2768 static bool
2769 check_against_output_limit(struct gl_context *ctx,
2770 struct gl_shader_program *prog,
2771 gl_linked_shader *producer,
2772 unsigned num_explicit_locations)
2773 {
2774 unsigned output_vectors = num_explicit_locations;
2775
2776 foreach_in_list(ir_instruction, node, producer->ir) {
2777 ir_variable *const var = node->as_variable();
2778
2779 if (var && !var->data.explicit_location &&
2780 var->data.mode == ir_var_shader_out &&
2781 var_counts_against_varying_limit(producer->Stage, var)) {
2782 /* outputs for fragment shader can't be doubles */
2783 output_vectors += var->type->count_attribute_slots(false);
2784 }
2785 }
2786
2787 assert(producer->Stage != MESA_SHADER_FRAGMENT);
2788 unsigned max_output_components =
2789 ctx->Const.Program[producer->Stage].MaxOutputComponents;
2790
2791 const unsigned output_components = output_vectors * 4;
2792 if (output_components > max_output_components) {
2793 if (ctx->API == API_OPENGLES2 || prog->IsES)
2794 linker_error(prog, "%s shader uses too many output vectors "
2795 "(%u > %u)\n",
2796 _mesa_shader_stage_to_string(producer->Stage),
2797 output_vectors,
2798 max_output_components / 4);
2799 else
2800 linker_error(prog, "%s shader uses too many output components "
2801 "(%u > %u)\n",
2802 _mesa_shader_stage_to_string(producer->Stage),
2803 output_components,
2804 max_output_components);
2805
2806 return false;
2807 }
2808
2809 return true;
2810 }
2811
2812 static bool
2813 check_against_input_limit(struct gl_context *ctx,
2814 struct gl_shader_program *prog,
2815 gl_linked_shader *consumer,
2816 unsigned num_explicit_locations)
2817 {
2818 unsigned input_vectors = num_explicit_locations;
2819
2820 foreach_in_list(ir_instruction, node, consumer->ir) {
2821 ir_variable *const var = node->as_variable();
2822
2823 if (var && !var->data.explicit_location &&
2824 var->data.mode == ir_var_shader_in &&
2825 var_counts_against_varying_limit(consumer->Stage, var)) {
2826 /* vertex inputs aren't varying counted */
2827 input_vectors += var->type->count_attribute_slots(false);
2828 }
2829 }
2830
2831 assert(consumer->Stage != MESA_SHADER_VERTEX);
2832 unsigned max_input_components =
2833 ctx->Const.Program[consumer->Stage].MaxInputComponents;
2834
2835 const unsigned input_components = input_vectors * 4;
2836 if (input_components > max_input_components) {
2837 if (ctx->API == API_OPENGLES2 || prog->IsES)
2838 linker_error(prog, "%s shader uses too many input vectors "
2839 "(%u > %u)\n",
2840 _mesa_shader_stage_to_string(consumer->Stage),
2841 input_vectors,
2842 max_input_components / 4);
2843 else
2844 linker_error(prog, "%s shader uses too many input components "
2845 "(%u > %u)\n",
2846 _mesa_shader_stage_to_string(consumer->Stage),
2847 input_components,
2848 max_input_components);
2849
2850 return false;
2851 }
2852
2853 return true;
2854 }
2855
2856 bool
2857 link_varyings(struct gl_shader_program *prog, unsigned first, unsigned last,
2858 struct gl_context *ctx, void *mem_ctx)
2859 {
2860 bool has_xfb_qualifiers = false;
2861 unsigned num_tfeedback_decls = 0;
2862 char **varying_names = NULL;
2863 tfeedback_decl *tfeedback_decls = NULL;
2864
2865 /* From the ARB_enhanced_layouts spec:
2866 *
2867 * "If the shader used to record output variables for transform feedback
2868 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
2869 * qualifiers, the values specified by TransformFeedbackVaryings are
2870 * ignored, and the set of variables captured for transform feedback is
2871 * instead derived from the specified layout qualifiers."
2872 */
2873 for (int i = MESA_SHADER_FRAGMENT - 1; i >= 0; i--) {
2874 /* Find last stage before fragment shader */
2875 if (prog->_LinkedShaders[i]) {
2876 has_xfb_qualifiers =
2877 process_xfb_layout_qualifiers(mem_ctx, prog->_LinkedShaders[i],
2878 prog, &num_tfeedback_decls,
2879 &varying_names);
2880 break;
2881 }
2882 }
2883
2884 if (!has_xfb_qualifiers) {
2885 num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2886 varying_names = prog->TransformFeedback.VaryingNames;
2887 }
2888
2889 if (num_tfeedback_decls != 0) {
2890 /* From GL_EXT_transform_feedback:
2891 * A program will fail to link if:
2892 *
2893 * * the <count> specified by TransformFeedbackVaryingsEXT is
2894 * non-zero, but the program object has no vertex or geometry
2895 * shader;
2896 */
2897 if (first >= MESA_SHADER_FRAGMENT) {
2898 linker_error(prog, "Transform feedback varyings specified, but "
2899 "no vertex, tessellation, or geometry shader is "
2900 "present.\n");
2901 return false;
2902 }
2903
2904 tfeedback_decls = rzalloc_array(mem_ctx, tfeedback_decl,
2905 num_tfeedback_decls);
2906 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2907 varying_names, tfeedback_decls))
2908 return false;
2909 }
2910
2911 /* If there is no fragment shader we need to set transform feedback.
2912 *
2913 * For SSO we also need to assign output locations. We assign them here
2914 * because we need to do it for both single stage programs and multi stage
2915 * programs.
2916 */
2917 if (last < MESA_SHADER_FRAGMENT &&
2918 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
2919 const uint64_t reserved_out_slots =
2920 reserved_varying_slot(prog->_LinkedShaders[last], ir_var_shader_out);
2921 if (!assign_varying_locations(ctx, mem_ctx, prog,
2922 prog->_LinkedShaders[last], NULL,
2923 num_tfeedback_decls, tfeedback_decls,
2924 reserved_out_slots))
2925 return false;
2926 }
2927
2928 if (last <= MESA_SHADER_FRAGMENT) {
2929 /* Remove unused varyings from the first/last stage unless SSO */
2930 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
2931 prog->_LinkedShaders[first],
2932 ir_var_shader_in);
2933 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
2934 prog->_LinkedShaders[last],
2935 ir_var_shader_out);
2936
2937 /* If the program is made up of only a single stage */
2938 if (first == last) {
2939 gl_linked_shader *const sh = prog->_LinkedShaders[last];
2940
2941 do_dead_builtin_varyings(ctx, NULL, sh, 0, NULL);
2942 do_dead_builtin_varyings(ctx, sh, NULL, num_tfeedback_decls,
2943 tfeedback_decls);
2944
2945 if (prog->SeparateShader) {
2946 const uint64_t reserved_slots =
2947 reserved_varying_slot(sh, ir_var_shader_in);
2948
2949 /* Assign input locations for SSO, output locations are already
2950 * assigned.
2951 */
2952 if (!assign_varying_locations(ctx, mem_ctx, prog,
2953 NULL /* producer */,
2954 sh /* consumer */,
2955 0 /* num_tfeedback_decls */,
2956 NULL /* tfeedback_decls */,
2957 reserved_slots))
2958 return false;
2959 }
2960 } else {
2961 /* Linking the stages in the opposite order (from fragment to vertex)
2962 * ensures that inter-shader outputs written to in an earlier stage
2963 * are eliminated if they are (transitively) not used in a later
2964 * stage.
2965 */
2966 int next = last;
2967 for (int i = next - 1; i >= 0; i--) {
2968 if (prog->_LinkedShaders[i] == NULL && i != 0)
2969 continue;
2970
2971 gl_linked_shader *const sh_i = prog->_LinkedShaders[i];
2972 gl_linked_shader *const sh_next = prog->_LinkedShaders[next];
2973
2974 const uint64_t reserved_out_slots =
2975 reserved_varying_slot(sh_i, ir_var_shader_out);
2976 const uint64_t reserved_in_slots =
2977 reserved_varying_slot(sh_next, ir_var_shader_in);
2978
2979 do_dead_builtin_varyings(ctx, sh_i, sh_next,
2980 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2981 tfeedback_decls);
2982
2983 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2984 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2985 tfeedback_decls,
2986 reserved_out_slots | reserved_in_slots))
2987 return false;
2988
2989 /* This must be done after all dead varyings are eliminated. */
2990 if (sh_i != NULL) {
2991 unsigned slots_used = util_bitcount64(reserved_out_slots);
2992 if (!check_against_output_limit(ctx, prog, sh_i, slots_used)) {
2993 return false;
2994 }
2995 }
2996
2997 unsigned slots_used = util_bitcount64(reserved_in_slots);
2998 if (!check_against_input_limit(ctx, prog, sh_next, slots_used))
2999 return false;
3000
3001 next = i;
3002 }
3003 }
3004 }
3005
3006 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls,
3007 has_xfb_qualifiers))
3008 return false;
3009
3010 return true;
3011 }