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