glsl: pass disable_varying_packing bool to the lowering pass
[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/mtypes.h"
33 #include "glsl_symbol_table.h"
34 #include "glsl_parser_extras.h"
35 #include "ir_optimization.h"
36 #include "linker.h"
37 #include "link_varyings.h"
38 #include "main/macros.h"
39 #include "program/hash_table.h"
40 #include "program.h"
41
42
43 /**
44 * Get the varying type stripped of the outermost array if we're processing
45 * a stage whose varyings are arrays indexed by a vertex number (such as
46 * geometry shader inputs).
47 */
48 static const glsl_type *
49 get_varying_type(const ir_variable *var, gl_shader_stage stage)
50 {
51 const glsl_type *type = var->type;
52
53 if (!var->data.patch &&
54 ((var->data.mode == ir_var_shader_out &&
55 stage == MESA_SHADER_TESS_CTRL) ||
56 (var->data.mode == ir_var_shader_in &&
57 (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL ||
58 stage == MESA_SHADER_GEOMETRY)))) {
59 assert(type->is_array());
60 type = type->fields.array;
61 }
62
63 return type;
64 }
65
66 /**
67 * Validate the types and qualifiers of an output from one stage against the
68 * matching input to another stage.
69 */
70 static void
71 cross_validate_types_and_qualifiers(struct gl_shader_program *prog,
72 const ir_variable *input,
73 const ir_variable *output,
74 gl_shader_stage consumer_stage,
75 gl_shader_stage producer_stage)
76 {
77 /* Check that the types match between stages.
78 */
79 const glsl_type *type_to_match = input->type;
80
81 /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
82 const bool extra_array_level = (producer_stage == MESA_SHADER_VERTEX &&
83 consumer_stage != MESA_SHADER_FRAGMENT) ||
84 consumer_stage == MESA_SHADER_GEOMETRY;
85 if (extra_array_level) {
86 assert(type_to_match->is_array());
87 type_to_match = type_to_match->fields.array;
88 }
89
90 if (type_to_match != output->type) {
91 /* There is a bit of a special case for gl_TexCoord. This
92 * built-in is unsized by default. Applications that variable
93 * access it must redeclare it with a size. There is some
94 * language in the GLSL spec that implies the fragment shader
95 * and vertex shader do not have to agree on this size. Other
96 * driver behave this way, and one or two applications seem to
97 * rely on it.
98 *
99 * Neither declaration needs to be modified here because the array
100 * sizes are fixed later when update_array_sizes is called.
101 *
102 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
103 *
104 * "Unlike user-defined varying variables, the built-in
105 * varying variables don't have a strict one-to-one
106 * correspondence between the vertex language and the
107 * fragment language."
108 */
109 if (!output->type->is_array() || !is_gl_identifier(output->name)) {
110 linker_error(prog,
111 "%s shader output `%s' declared as type `%s', "
112 "but %s shader input declared as type `%s'\n",
113 _mesa_shader_stage_to_string(producer_stage),
114 output->name,
115 output->type->name,
116 _mesa_shader_stage_to_string(consumer_stage),
117 input->type->name);
118 return;
119 }
120 }
121
122 /* Check that all of the qualifiers match between stages.
123 */
124 if (input->data.centroid != output->data.centroid) {
125 linker_error(prog,
126 "%s shader output `%s' %s centroid qualifier, "
127 "but %s shader input %s centroid qualifier\n",
128 _mesa_shader_stage_to_string(producer_stage),
129 output->name,
130 (output->data.centroid) ? "has" : "lacks",
131 _mesa_shader_stage_to_string(consumer_stage),
132 (input->data.centroid) ? "has" : "lacks");
133 return;
134 }
135
136 if (input->data.sample != output->data.sample) {
137 linker_error(prog,
138 "%s shader output `%s' %s sample qualifier, "
139 "but %s shader input %s sample qualifier\n",
140 _mesa_shader_stage_to_string(producer_stage),
141 output->name,
142 (output->data.sample) ? "has" : "lacks",
143 _mesa_shader_stage_to_string(consumer_stage),
144 (input->data.sample) ? "has" : "lacks");
145 return;
146 }
147
148 if (input->data.patch != output->data.patch) {
149 linker_error(prog,
150 "%s shader output `%s' %s patch qualifier, "
151 "but %s shader input %s patch qualifier\n",
152 _mesa_shader_stage_to_string(producer_stage),
153 output->name,
154 (output->data.patch) ? "has" : "lacks",
155 _mesa_shader_stage_to_string(consumer_stage),
156 (input->data.patch) ? "has" : "lacks");
157 return;
158 }
159
160 if (!prog->IsES && input->data.invariant != output->data.invariant) {
161 linker_error(prog,
162 "%s shader output `%s' %s invariant qualifier, "
163 "but %s shader input %s invariant qualifier\n",
164 _mesa_shader_stage_to_string(producer_stage),
165 output->name,
166 (output->data.invariant) ? "has" : "lacks",
167 _mesa_shader_stage_to_string(consumer_stage),
168 (input->data.invariant) ? "has" : "lacks");
169 return;
170 }
171
172 /* GLSL >= 4.40 removes text requiring interpolation qualifiers
173 * to match cross stage, they must only match within the same stage.
174 *
175 * From page 84 (page 90 of the PDF) of the GLSL 4.40 spec:
176 *
177 * "It is a link-time error if, within the same stage, the interpolation
178 * qualifiers of variables of the same name do not match.
179 *
180 */
181 if (input->data.interpolation != output->data.interpolation &&
182 prog->Version < 440) {
183 linker_error(prog,
184 "%s shader output `%s' specifies %s "
185 "interpolation qualifier, "
186 "but %s shader input specifies %s "
187 "interpolation qualifier\n",
188 _mesa_shader_stage_to_string(producer_stage),
189 output->name,
190 interpolation_string(output->data.interpolation),
191 _mesa_shader_stage_to_string(consumer_stage),
192 interpolation_string(input->data.interpolation));
193 return;
194 }
195 }
196
197 /**
198 * Validate front and back color outputs against single color input
199 */
200 static void
201 cross_validate_front_and_back_color(struct gl_shader_program *prog,
202 const ir_variable *input,
203 const ir_variable *front_color,
204 const ir_variable *back_color,
205 gl_shader_stage consumer_stage,
206 gl_shader_stage producer_stage)
207 {
208 if (front_color != NULL && front_color->data.assigned)
209 cross_validate_types_and_qualifiers(prog, input, front_color,
210 consumer_stage, producer_stage);
211
212 if (back_color != NULL && back_color->data.assigned)
213 cross_validate_types_and_qualifiers(prog, input, back_color,
214 consumer_stage, producer_stage);
215 }
216
217 /**
218 * Validate that outputs from one stage match inputs of another
219 */
220 void
221 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
222 gl_shader *producer, gl_shader *consumer)
223 {
224 glsl_symbol_table parameters;
225 ir_variable *explicit_locations[MAX_VARYING] = { NULL, };
226
227 /* Find all shader outputs in the "producer" stage.
228 */
229 foreach_in_list(ir_instruction, node, producer->ir) {
230 ir_variable *const var = node->as_variable();
231
232 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
233 continue;
234
235 if (!var->data.explicit_location
236 || var->data.location < VARYING_SLOT_VAR0)
237 parameters.add_variable(var);
238 else {
239 /* User-defined varyings with explicit locations are handled
240 * differently because they do not need to have matching names.
241 */
242 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
243
244 if (explicit_locations[idx] != NULL) {
245 linker_error(prog,
246 "%s shader has multiple outputs explicitly "
247 "assigned to location %d\n",
248 _mesa_shader_stage_to_string(producer->Stage),
249 idx);
250 return;
251 }
252
253 explicit_locations[idx] = var;
254 }
255 }
256
257
258 /* Find all shader inputs in the "consumer" stage. Any variables that have
259 * matching outputs already in the symbol table must have the same type and
260 * qualifiers.
261 *
262 * Exception: if the consumer is the geometry shader, then the inputs
263 * should be arrays and the type of the array element should match the type
264 * of the corresponding producer output.
265 */
266 foreach_in_list(ir_instruction, node, consumer->ir) {
267 ir_variable *const input = node->as_variable();
268
269 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
270 continue;
271
272 if (strcmp(input->name, "gl_Color") == 0 && input->data.used) {
273 const ir_variable *const front_color =
274 parameters.get_variable("gl_FrontColor");
275
276 const ir_variable *const back_color =
277 parameters.get_variable("gl_BackColor");
278
279 cross_validate_front_and_back_color(prog, input,
280 front_color, back_color,
281 consumer->Stage, producer->Stage);
282 } else if (strcmp(input->name, "gl_SecondaryColor") == 0 && input->data.used) {
283 const ir_variable *const front_color =
284 parameters.get_variable("gl_FrontSecondaryColor");
285
286 const ir_variable *const back_color =
287 parameters.get_variable("gl_BackSecondaryColor");
288
289 cross_validate_front_and_back_color(prog, input,
290 front_color, back_color,
291 consumer->Stage, producer->Stage);
292 } else {
293 /* The rules for connecting inputs and outputs change in the presence
294 * of explicit locations. In this case, we no longer care about the
295 * names of the variables. Instead, we care only about the
296 * explicitly assigned location.
297 */
298 ir_variable *output = NULL;
299 if (input->data.explicit_location
300 && input->data.location >= VARYING_SLOT_VAR0) {
301 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0];
302
303 if (output == NULL) {
304 linker_error(prog,
305 "%s shader input `%s' with explicit location "
306 "has no matching output\n",
307 _mesa_shader_stage_to_string(consumer->Stage),
308 input->name);
309 }
310 } else {
311 output = parameters.get_variable(input->name);
312 }
313
314 if (output != NULL) {
315 /* Interface blocks have their own validation elsewhere so don't
316 * try validating them here.
317 */
318 if (!(input->get_interface_type() &&
319 output->get_interface_type()))
320 cross_validate_types_and_qualifiers(prog, input, output,
321 consumer->Stage,
322 producer->Stage);
323 } else {
324 /* Check for input vars with unmatched output vars in prev stage
325 * taking into account that interface blocks could have a matching
326 * output but with different name, so we ignore them.
327 */
328 assert(!input->data.assigned);
329 if (input->data.used && !input->get_interface_type() &&
330 !input->data.explicit_location && !prog->SeparateShader)
331 linker_error(prog,
332 "%s shader input `%s' "
333 "has no matching output in the previous stage\n",
334 _mesa_shader_stage_to_string(consumer->Stage),
335 input->name);
336 }
337 }
338 }
339 }
340
341 /**
342 * Demote shader inputs and outputs that are not used in other stages, and
343 * remove them via dead code elimination.
344 */
345 void
346 remove_unused_shader_inputs_and_outputs(bool is_separate_shader_object,
347 gl_shader *sh,
348 enum ir_variable_mode mode)
349 {
350 if (is_separate_shader_object)
351 return;
352
353 foreach_in_list(ir_instruction, node, sh->ir) {
354 ir_variable *const var = node->as_variable();
355
356 if ((var == NULL) || (var->data.mode != int(mode)))
357 continue;
358
359 /* A shader 'in' or 'out' variable is only really an input or output if
360 * its value is used by other shader stages. This will cause the
361 * variable to have a location assigned.
362 */
363 if (var->data.is_unmatched_generic_inout) {
364 assert(var->data.mode != ir_var_temporary);
365 var->data.mode = ir_var_auto;
366 }
367 }
368
369 /* Eliminate code that is now dead due to unused inputs/outputs being
370 * demoted.
371 */
372 while (do_dead_code(sh->ir, false))
373 ;
374
375 }
376
377 /**
378 * Initialize this object based on a string that was passed to
379 * glTransformFeedbackVaryings.
380 *
381 * If the input is mal-formed, this call still succeeds, but it sets
382 * this->var_name to a mal-formed input, so tfeedback_decl::find_output_var()
383 * will fail to find any matching variable.
384 */
385 void
386 tfeedback_decl::init(struct gl_context *ctx, const void *mem_ctx,
387 const char *input)
388 {
389 /* We don't have to be pedantic about what is a valid GLSL variable name,
390 * because any variable with an invalid name can't exist in the IR anyway.
391 */
392
393 this->location = -1;
394 this->orig_name = input;
395 this->lowered_builtin_array_variable = none;
396 this->skip_components = 0;
397 this->next_buffer_separator = false;
398 this->matched_candidate = NULL;
399 this->stream_id = 0;
400
401 if (ctx->Extensions.ARB_transform_feedback3) {
402 /* Parse gl_NextBuffer. */
403 if (strcmp(input, "gl_NextBuffer") == 0) {
404 this->next_buffer_separator = true;
405 return;
406 }
407
408 /* Parse gl_SkipComponents. */
409 if (strcmp(input, "gl_SkipComponents1") == 0)
410 this->skip_components = 1;
411 else if (strcmp(input, "gl_SkipComponents2") == 0)
412 this->skip_components = 2;
413 else if (strcmp(input, "gl_SkipComponents3") == 0)
414 this->skip_components = 3;
415 else if (strcmp(input, "gl_SkipComponents4") == 0)
416 this->skip_components = 4;
417
418 if (this->skip_components)
419 return;
420 }
421
422 /* Parse a declaration. */
423 const char *base_name_end;
424 long subscript = parse_program_resource_name(input, &base_name_end);
425 this->var_name = ralloc_strndup(mem_ctx, input, base_name_end - input);
426 if (this->var_name == NULL) {
427 _mesa_error_no_memory(__func__);
428 return;
429 }
430
431 if (subscript >= 0) {
432 this->array_subscript = subscript;
433 this->is_subscripted = true;
434 } else {
435 this->is_subscripted = false;
436 }
437
438 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
439 * class must behave specially to account for the fact that gl_ClipDistance
440 * is converted from a float[8] to a vec4[2].
441 */
442 if (ctx->Const.ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
443 strcmp(this->var_name, "gl_ClipDistance") == 0) {
444 this->lowered_builtin_array_variable = clip_distance;
445 }
446
447 if (ctx->Const.LowerTessLevel &&
448 (strcmp(this->var_name, "gl_TessLevelOuter") == 0))
449 this->lowered_builtin_array_variable = tess_level_outer;
450 if (ctx->Const.LowerTessLevel &&
451 (strcmp(this->var_name, "gl_TessLevelInner") == 0))
452 this->lowered_builtin_array_variable = tess_level_inner;
453 }
454
455
456 /**
457 * Determine whether two tfeedback_decl objects refer to the same variable and
458 * array index (if applicable).
459 */
460 bool
461 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
462 {
463 assert(x.is_varying() && y.is_varying());
464
465 if (strcmp(x.var_name, y.var_name) != 0)
466 return false;
467 if (x.is_subscripted != y.is_subscripted)
468 return false;
469 if (x.is_subscripted && x.array_subscript != y.array_subscript)
470 return false;
471 return true;
472 }
473
474
475 /**
476 * Assign a location and stream ID for this tfeedback_decl object based on the
477 * transform feedback candidate found by find_candidate.
478 *
479 * If an error occurs, the error is reported through linker_error() and false
480 * is returned.
481 */
482 bool
483 tfeedback_decl::assign_location(struct gl_context *ctx,
484 struct gl_shader_program *prog)
485 {
486 assert(this->is_varying());
487
488 unsigned fine_location
489 = this->matched_candidate->toplevel_var->data.location * 4
490 + this->matched_candidate->toplevel_var->data.location_frac
491 + this->matched_candidate->offset;
492
493 if (this->matched_candidate->type->is_array()) {
494 /* Array variable */
495 const unsigned matrix_cols =
496 this->matched_candidate->type->fields.array->matrix_columns;
497 const unsigned vector_elements =
498 this->matched_candidate->type->fields.array->vector_elements;
499 const unsigned dmul =
500 this->matched_candidate->type->fields.array->is_double() ? 2 : 1;
501 unsigned actual_array_size;
502 switch (this->lowered_builtin_array_variable) {
503 case clip_distance:
504 actual_array_size = prog->LastClipDistanceArraySize;
505 break;
506 case tess_level_outer:
507 actual_array_size = 4;
508 break;
509 case tess_level_inner:
510 actual_array_size = 2;
511 break;
512 case none:
513 default:
514 actual_array_size = this->matched_candidate->type->array_size();
515 break;
516 }
517
518 if (this->is_subscripted) {
519 /* Check array bounds. */
520 if (this->array_subscript >= actual_array_size) {
521 linker_error(prog, "Transform feedback varying %s has index "
522 "%i, but the array size is %u.",
523 this->orig_name, this->array_subscript,
524 actual_array_size);
525 return false;
526 }
527 unsigned array_elem_size = this->lowered_builtin_array_variable ?
528 1 : vector_elements * matrix_cols * dmul;
529 fine_location += array_elem_size * this->array_subscript;
530 this->size = 1;
531 } else {
532 this->size = actual_array_size;
533 }
534 this->vector_elements = vector_elements;
535 this->matrix_columns = matrix_cols;
536 if (this->lowered_builtin_array_variable)
537 this->type = GL_FLOAT;
538 else
539 this->type = this->matched_candidate->type->fields.array->gl_type;
540 } else {
541 /* Regular variable (scalar, vector, or matrix) */
542 if (this->is_subscripted) {
543 linker_error(prog, "Transform feedback varying %s requested, "
544 "but %s is not an array.",
545 this->orig_name, this->var_name);
546 return false;
547 }
548 this->size = 1;
549 this->vector_elements = this->matched_candidate->type->vector_elements;
550 this->matrix_columns = this->matched_candidate->type->matrix_columns;
551 this->type = this->matched_candidate->type->gl_type;
552 }
553 this->location = fine_location / 4;
554 this->location_frac = fine_location % 4;
555
556 /* From GL_EXT_transform_feedback:
557 * A program will fail to link if:
558 *
559 * * the total number of components to capture in any varying
560 * variable in <varyings> is greater than the constant
561 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
562 * buffer mode is SEPARATE_ATTRIBS_EXT;
563 */
564 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
565 this->num_components() >
566 ctx->Const.MaxTransformFeedbackSeparateComponents) {
567 linker_error(prog, "Transform feedback varying %s exceeds "
568 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
569 this->orig_name);
570 return false;
571 }
572
573 /* Only transform feedback varyings can be assigned to non-zero streams,
574 * so assign the stream id here.
575 */
576 this->stream_id = this->matched_candidate->toplevel_var->data.stream;
577
578 return true;
579 }
580
581
582 unsigned
583 tfeedback_decl::get_num_outputs() const
584 {
585 if (!this->is_varying()) {
586 return 0;
587 }
588 return (this->num_components() + this->location_frac + 3)/4;
589 }
590
591
592 /**
593 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
594 *
595 * If an error occurs, the error is reported through linker_error() and false
596 * is returned.
597 */
598 bool
599 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
600 struct gl_transform_feedback_info *info,
601 unsigned buffer, const unsigned max_outputs) const
602 {
603 assert(!this->next_buffer_separator);
604
605 /* Handle gl_SkipComponents. */
606 if (this->skip_components) {
607 info->BufferStride[buffer] += this->skip_components;
608 return true;
609 }
610
611 /* From GL_EXT_transform_feedback:
612 * A program will fail to link if:
613 *
614 * * the total number of components to capture is greater than
615 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
616 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
617 */
618 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
619 info->BufferStride[buffer] + this->num_components() >
620 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
621 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
622 "limit has been exceeded.");
623 return false;
624 }
625
626 unsigned location = this->location;
627 unsigned location_frac = this->location_frac;
628 unsigned num_components = this->num_components();
629 while (num_components > 0) {
630 unsigned output_size = MIN2(num_components, 4 - location_frac);
631 assert(info->NumOutputs < max_outputs);
632 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
633 info->Outputs[info->NumOutputs].OutputRegister = location;
634 info->Outputs[info->NumOutputs].NumComponents = output_size;
635 info->Outputs[info->NumOutputs].StreamId = stream_id;
636 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
637 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
638 ++info->NumOutputs;
639 info->BufferStride[buffer] += output_size;
640 info->BufferStream[buffer] = this->stream_id;
641 num_components -= output_size;
642 location++;
643 location_frac = 0;
644 }
645
646 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
647 info->Varyings[info->NumVarying].Type = this->type;
648 info->Varyings[info->NumVarying].Size = this->size;
649 info->NumVarying++;
650
651 return true;
652 }
653
654
655 const tfeedback_candidate *
656 tfeedback_decl::find_candidate(gl_shader_program *prog,
657 hash_table *tfeedback_candidates)
658 {
659 const char *name = this->var_name;
660 switch (this->lowered_builtin_array_variable) {
661 case none:
662 name = this->var_name;
663 break;
664 case clip_distance:
665 name = "gl_ClipDistanceMESA";
666 break;
667 case tess_level_outer:
668 name = "gl_TessLevelOuterMESA";
669 break;
670 case tess_level_inner:
671 name = "gl_TessLevelInnerMESA";
672 break;
673 }
674 this->matched_candidate = (const tfeedback_candidate *)
675 hash_table_find(tfeedback_candidates, name);
676 if (!this->matched_candidate) {
677 /* From GL_EXT_transform_feedback:
678 * A program will fail to link if:
679 *
680 * * any variable name specified in the <varyings> array is not
681 * declared as an output in the geometry shader (if present) or
682 * the vertex shader (if no geometry shader is present);
683 */
684 linker_error(prog, "Transform feedback varying %s undeclared.",
685 this->orig_name);
686 }
687 return this->matched_candidate;
688 }
689
690
691 /**
692 * Parse all the transform feedback declarations that were passed to
693 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
694 *
695 * If an error occurs, the error is reported through linker_error() and false
696 * is returned.
697 */
698 bool
699 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
700 const void *mem_ctx, unsigned num_names,
701 char **varying_names, tfeedback_decl *decls)
702 {
703 for (unsigned i = 0; i < num_names; ++i) {
704 decls[i].init(ctx, mem_ctx, varying_names[i]);
705
706 if (!decls[i].is_varying())
707 continue;
708
709 /* From GL_EXT_transform_feedback:
710 * A program will fail to link if:
711 *
712 * * any two entries in the <varyings> array specify the same varying
713 * variable;
714 *
715 * We interpret this to mean "any two entries in the <varyings> array
716 * specify the same varying variable and array index", since transform
717 * feedback of arrays would be useless otherwise.
718 */
719 for (unsigned j = 0; j < i; ++j) {
720 if (!decls[j].is_varying())
721 continue;
722
723 if (tfeedback_decl::is_same(decls[i], decls[j])) {
724 linker_error(prog, "Transform feedback varying %s specified "
725 "more than once.", varying_names[i]);
726 return false;
727 }
728 }
729 }
730 return true;
731 }
732
733
734 /**
735 * Store transform feedback location assignments into
736 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
737 *
738 * If an error occurs, the error is reported through linker_error() and false
739 * is returned.
740 */
741 bool
742 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
743 unsigned num_tfeedback_decls,
744 tfeedback_decl *tfeedback_decls)
745 {
746 bool separate_attribs_mode =
747 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
748
749 ralloc_free(prog->LinkedTransformFeedback.Varyings);
750 ralloc_free(prog->LinkedTransformFeedback.Outputs);
751
752 memset(&prog->LinkedTransformFeedback, 0,
753 sizeof(prog->LinkedTransformFeedback));
754
755 prog->LinkedTransformFeedback.Varyings =
756 rzalloc_array(prog,
757 struct gl_transform_feedback_varying_info,
758 num_tfeedback_decls);
759
760 unsigned num_outputs = 0;
761 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
762 num_outputs += tfeedback_decls[i].get_num_outputs();
763
764 prog->LinkedTransformFeedback.Outputs =
765 rzalloc_array(prog,
766 struct gl_transform_feedback_output,
767 num_outputs);
768
769 unsigned num_buffers = 0;
770
771 if (separate_attribs_mode) {
772 /* GL_SEPARATE_ATTRIBS */
773 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
774 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
775 num_buffers, num_outputs))
776 return false;
777
778 num_buffers++;
779 }
780 }
781 else {
782 /* GL_INVERLEAVED_ATTRIBS */
783 int buffer_stream_id = -1;
784 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
785 if (tfeedback_decls[i].is_next_buffer_separator()) {
786 num_buffers++;
787 buffer_stream_id = -1;
788 continue;
789 } else if (buffer_stream_id == -1) {
790 /* First varying writing to this buffer: remember its stream */
791 buffer_stream_id = (int) tfeedback_decls[i].get_stream_id();
792 } else if (buffer_stream_id !=
793 (int) tfeedback_decls[i].get_stream_id()) {
794 /* Varying writes to the same buffer from a different stream */
795 linker_error(prog,
796 "Transform feedback can't capture varyings belonging "
797 "to different vertex streams in a single buffer. "
798 "Varying %s writes to buffer from stream %u, other "
799 "varyings in the same buffer write from stream %u.",
800 tfeedback_decls[i].name(),
801 tfeedback_decls[i].get_stream_id(),
802 buffer_stream_id);
803 return false;
804 }
805
806 if (!tfeedback_decls[i].store(ctx, prog,
807 &prog->LinkedTransformFeedback,
808 num_buffers, num_outputs))
809 return false;
810 }
811 num_buffers++;
812 }
813
814 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
815
816 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
817 return true;
818 }
819
820 namespace {
821
822 /**
823 * Data structure recording the relationship between outputs of one shader
824 * stage (the "producer") and inputs of another (the "consumer").
825 */
826 class varying_matches
827 {
828 public:
829 varying_matches(bool disable_varying_packing,
830 gl_shader_stage producer_stage,
831 gl_shader_stage consumer_stage);
832 ~varying_matches();
833 void record(ir_variable *producer_var, ir_variable *consumer_var);
834 unsigned assign_locations(struct gl_shader_program *prog,
835 uint64_t reserved_slots, bool separate_shader);
836 void store_locations() const;
837
838 private:
839 /**
840 * If true, this driver disables varying packing, so all varyings need to
841 * be aligned on slot boundaries, and take up a number of slots equal to
842 * their number of matrix columns times their array size.
843 */
844 const bool disable_varying_packing;
845
846 /**
847 * Enum representing the order in which varyings are packed within a
848 * packing class.
849 *
850 * Currently we pack vec4's first, then vec2's, then scalar values, then
851 * vec3's. This order ensures that the only vectors that are at risk of
852 * having to be "double parked" (split between two adjacent varying slots)
853 * are the vec3's.
854 */
855 enum packing_order_enum {
856 PACKING_ORDER_VEC4,
857 PACKING_ORDER_VEC2,
858 PACKING_ORDER_SCALAR,
859 PACKING_ORDER_VEC3,
860 };
861
862 static unsigned compute_packing_class(const ir_variable *var);
863 static packing_order_enum compute_packing_order(const ir_variable *var);
864 static int match_comparator(const void *x_generic, const void *y_generic);
865
866 /**
867 * Structure recording the relationship between a single producer output
868 * and a single consumer input.
869 */
870 struct match {
871 /**
872 * Packing class for this varying, computed by compute_packing_class().
873 */
874 unsigned packing_class;
875
876 /**
877 * Packing order for this varying, computed by compute_packing_order().
878 */
879 packing_order_enum packing_order;
880 unsigned num_components;
881
882 /**
883 * The output variable in the producer stage.
884 */
885 ir_variable *producer_var;
886
887 /**
888 * The input variable in the consumer stage.
889 */
890 ir_variable *consumer_var;
891
892 /**
893 * The location which has been assigned for this varying. This is
894 * expressed in multiples of a float, with the first generic varying
895 * (i.e. the one referred to by VARYING_SLOT_VAR0) represented by the
896 * value 0.
897 */
898 unsigned generic_location;
899 } *matches;
900
901 /**
902 * The number of elements in the \c matches array that are currently in
903 * use.
904 */
905 unsigned num_matches;
906
907 /**
908 * The number of elements that were set aside for the \c matches array when
909 * it was allocated.
910 */
911 unsigned matches_capacity;
912
913 gl_shader_stage producer_stage;
914 gl_shader_stage consumer_stage;
915 };
916
917 } /* anonymous namespace */
918
919 varying_matches::varying_matches(bool disable_varying_packing,
920 gl_shader_stage producer_stage,
921 gl_shader_stage consumer_stage)
922 : disable_varying_packing(disable_varying_packing),
923 producer_stage(producer_stage),
924 consumer_stage(consumer_stage)
925 {
926 /* Note: this initial capacity is rather arbitrarily chosen to be large
927 * enough for many cases without wasting an unreasonable amount of space.
928 * varying_matches::record() will resize the array if there are more than
929 * this number of varyings.
930 */
931 this->matches_capacity = 8;
932 this->matches = (match *)
933 malloc(sizeof(*this->matches) * this->matches_capacity);
934 this->num_matches = 0;
935 }
936
937
938 varying_matches::~varying_matches()
939 {
940 free(this->matches);
941 }
942
943
944 /**
945 * Record the given producer/consumer variable pair in the list of variables
946 * that should later be assigned locations.
947 *
948 * It is permissible for \c consumer_var to be NULL (this happens if a
949 * variable is output by the producer and consumed by transform feedback, but
950 * not consumed by the consumer).
951 *
952 * If \c producer_var has already been paired up with a consumer_var, or
953 * producer_var is part of fixed pipeline functionality (and hence already has
954 * a location assigned), this function has no effect.
955 *
956 * Note: as a side effect this function may change the interpolation type of
957 * \c producer_var, but only when the change couldn't possibly affect
958 * rendering.
959 */
960 void
961 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
962 {
963 assert(producer_var != NULL || consumer_var != NULL);
964
965 if ((producer_var && (!producer_var->data.is_unmatched_generic_inout ||
966 producer_var->data.explicit_location)) ||
967 (consumer_var && (!consumer_var->data.is_unmatched_generic_inout ||
968 consumer_var->data.explicit_location))) {
969 /* Either a location already exists for this variable (since it is part
970 * of fixed functionality), or it has already been recorded as part of a
971 * previous match.
972 */
973 return;
974 }
975
976 bool needs_flat_qualifier = consumer_var == NULL &&
977 (producer_var->type->contains_integer() ||
978 producer_var->type->contains_double());
979
980 if (needs_flat_qualifier ||
981 (consumer_stage != -1 && consumer_stage != MESA_SHADER_FRAGMENT)) {
982 /* Since this varying is not being consumed by the fragment shader, its
983 * interpolation type varying cannot possibly affect rendering.
984 * Also, this variable is non-flat and is (or contains) an integer
985 * or a double.
986 * If the consumer stage is unknown, don't modify the interpolation
987 * type as it could affect rendering later with separate shaders.
988 *
989 * lower_packed_varyings requires all integer varyings to flat,
990 * regardless of where they appear. We can trivially satisfy that
991 * requirement by changing the interpolation type to flat here.
992 */
993 if (producer_var) {
994 producer_var->data.centroid = false;
995 producer_var->data.sample = false;
996 producer_var->data.interpolation = INTERP_QUALIFIER_FLAT;
997 }
998
999 if (consumer_var) {
1000 consumer_var->data.centroid = false;
1001 consumer_var->data.sample = false;
1002 consumer_var->data.interpolation = INTERP_QUALIFIER_FLAT;
1003 }
1004 }
1005
1006 if (this->num_matches == this->matches_capacity) {
1007 this->matches_capacity *= 2;
1008 this->matches = (match *)
1009 realloc(this->matches,
1010 sizeof(*this->matches) * this->matches_capacity);
1011 }
1012
1013 const ir_variable *const var = (producer_var != NULL)
1014 ? producer_var : consumer_var;
1015 const gl_shader_stage stage = (producer_var != NULL)
1016 ? producer_stage : consumer_stage;
1017 const glsl_type *type = get_varying_type(var, stage);
1018
1019 this->matches[this->num_matches].packing_class
1020 = this->compute_packing_class(var);
1021 this->matches[this->num_matches].packing_order
1022 = this->compute_packing_order(var);
1023 if (this->disable_varying_packing) {
1024 unsigned slots = type->count_attribute_slots(false);
1025 this->matches[this->num_matches].num_components = slots * 4;
1026 } else {
1027 this->matches[this->num_matches].num_components
1028 = type->component_slots();
1029 }
1030 this->matches[this->num_matches].producer_var = producer_var;
1031 this->matches[this->num_matches].consumer_var = consumer_var;
1032 this->num_matches++;
1033 if (producer_var)
1034 producer_var->data.is_unmatched_generic_inout = 0;
1035 if (consumer_var)
1036 consumer_var->data.is_unmatched_generic_inout = 0;
1037 }
1038
1039
1040 /**
1041 * Choose locations for all of the variable matches that were previously
1042 * passed to varying_matches::record().
1043 */
1044 unsigned
1045 varying_matches::assign_locations(struct gl_shader_program *prog,
1046 uint64_t reserved_slots,
1047 bool separate_shader)
1048 {
1049 /* We disable varying sorting for separate shader programs for the
1050 * following reasons:
1051 *
1052 * 1/ All programs must sort the code in the same order to guarantee the
1053 * interface matching. However varying_matches::record() will change the
1054 * interpolation qualifier of some stages.
1055 *
1056 * 2/ GLSL version 4.50 removes the matching constrain on the interpolation
1057 * qualifier.
1058 *
1059 * From Section 4.5 (Interpolation Qualifiers) of the GLSL 4.40 spec:
1060 *
1061 * "The type and presence of interpolation qualifiers of variables with
1062 * the same name declared in all linked shaders for the same cross-stage
1063 * interface must match, otherwise the link command will fail.
1064 *
1065 * When comparing an output from one stage to an input of a subsequent
1066 * stage, the input and output don't match if their interpolation
1067 * qualifiers (or lack thereof) are not the same."
1068 *
1069 * "It is a link-time error if, within the same stage, the interpolation
1070 * qualifiers of variables of the same name do not match."
1071 */
1072 if (!separate_shader) {
1073 /* Sort varying matches into an order that makes them easy to pack. */
1074 qsort(this->matches, this->num_matches, sizeof(*this->matches),
1075 &varying_matches::match_comparator);
1076 }
1077
1078 unsigned generic_location = 0;
1079 unsigned generic_patch_location = MAX_VARYING*4;
1080
1081 for (unsigned i = 0; i < this->num_matches; i++) {
1082 unsigned *location = &generic_location;
1083
1084 const ir_variable *var;
1085 const glsl_type *type;
1086 bool is_vertex_input = false;
1087 if (matches[i].consumer_var) {
1088 var = matches[i].consumer_var;
1089 type = get_varying_type(var, consumer_stage);
1090 if (consumer_stage == MESA_SHADER_VERTEX)
1091 is_vertex_input = true;
1092 } else {
1093 var = matches[i].producer_var;
1094 type = get_varying_type(var, producer_stage);
1095 }
1096
1097 if (var->data.patch)
1098 location = &generic_patch_location;
1099
1100 /* Advance to the next slot if this varying has a different packing
1101 * class than the previous one, and we're not already on a slot
1102 * boundary.
1103 */
1104 if (i > 0 &&
1105 this->matches[i - 1].packing_class
1106 != this->matches[i].packing_class) {
1107 *location = ALIGN(*location, 4);
1108 }
1109
1110 unsigned num_elements = type->count_attribute_slots(is_vertex_input);
1111 unsigned slot_end = this->disable_varying_packing ? 4 :
1112 type->without_array()->vector_elements;
1113 slot_end += *location - 1;
1114
1115 /* FIXME: We could be smarter in the below code and loop back over
1116 * trying to fill any locations that we skipped because we couldn't pack
1117 * the varying between an explicit location. For now just let the user
1118 * hit the linking error if we run out of room and suggest they use
1119 * explicit locations.
1120 */
1121 for (unsigned j = 0; j < num_elements; j++) {
1122 while ((slot_end < MAX_VARYING * 4u) &&
1123 ((reserved_slots & (UINT64_C(1) << *location / 4u) ||
1124 (reserved_slots & (UINT64_C(1) << slot_end / 4u))))) {
1125
1126 *location = ALIGN(*location + 1, 4);
1127 slot_end = *location;
1128
1129 /* reset the counter and try again */
1130 j = 0;
1131 }
1132
1133 /* Increase the slot to make sure there is enough room for next
1134 * array element.
1135 */
1136 if (this->disable_varying_packing)
1137 slot_end += 4;
1138 else
1139 slot_end += type->without_array()->vector_elements;
1140 }
1141
1142 if (!var->data.patch && *location >= MAX_VARYING * 4u) {
1143 linker_error(prog, "insufficient contiguous locations available for "
1144 "%s it is possible an array or struct could not be "
1145 "packed between varyings with explicit locations. Try "
1146 "using an explicit location for arrays and structs.",
1147 var->name);
1148 }
1149
1150 this->matches[i].generic_location = *location;
1151
1152 *location += this->matches[i].num_components;
1153 }
1154
1155 return (generic_location + 3) / 4;
1156 }
1157
1158
1159 /**
1160 * Update the producer and consumer shaders to reflect the locations
1161 * assignments that were made by varying_matches::assign_locations().
1162 */
1163 void
1164 varying_matches::store_locations() const
1165 {
1166 for (unsigned i = 0; i < this->num_matches; i++) {
1167 ir_variable *producer_var = this->matches[i].producer_var;
1168 ir_variable *consumer_var = this->matches[i].consumer_var;
1169 unsigned generic_location = this->matches[i].generic_location;
1170 unsigned slot = generic_location / 4;
1171 unsigned offset = generic_location % 4;
1172
1173 if (producer_var) {
1174 producer_var->data.location = VARYING_SLOT_VAR0 + slot;
1175 producer_var->data.location_frac = offset;
1176 }
1177
1178 if (consumer_var) {
1179 assert(consumer_var->data.location == -1);
1180 consumer_var->data.location = VARYING_SLOT_VAR0 + slot;
1181 consumer_var->data.location_frac = offset;
1182 }
1183 }
1184 }
1185
1186
1187 /**
1188 * Compute the "packing class" of the given varying. This is an unsigned
1189 * integer with the property that two variables in the same packing class can
1190 * be safely backed into the same vec4.
1191 */
1192 unsigned
1193 varying_matches::compute_packing_class(const ir_variable *var)
1194 {
1195 /* Without help from the back-end, there is no way to pack together
1196 * variables with different interpolation types, because
1197 * lower_packed_varyings must choose exactly one interpolation type for
1198 * each packed varying it creates.
1199 *
1200 * However, we can safely pack together floats, ints, and uints, because:
1201 *
1202 * - varyings of base type "int" and "uint" must use the "flat"
1203 * interpolation type, which can only occur in GLSL 1.30 and above.
1204 *
1205 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
1206 * can store flat floats as ints without losing any information (using
1207 * the ir_unop_bitcast_* opcodes).
1208 *
1209 * Therefore, the packing class depends only on the interpolation type.
1210 */
1211 unsigned packing_class = var->data.centroid | (var->data.sample << 1) |
1212 (var->data.patch << 2);
1213 packing_class *= 4;
1214 packing_class += var->data.interpolation;
1215 return packing_class;
1216 }
1217
1218
1219 /**
1220 * Compute the "packing order" of the given varying. This is a sort key we
1221 * use to determine when to attempt to pack the given varying relative to
1222 * other varyings in the same packing class.
1223 */
1224 varying_matches::packing_order_enum
1225 varying_matches::compute_packing_order(const ir_variable *var)
1226 {
1227 const glsl_type *element_type = var->type;
1228
1229 while (element_type->base_type == GLSL_TYPE_ARRAY) {
1230 element_type = element_type->fields.array;
1231 }
1232
1233 switch (element_type->component_slots() % 4) {
1234 case 1: return PACKING_ORDER_SCALAR;
1235 case 2: return PACKING_ORDER_VEC2;
1236 case 3: return PACKING_ORDER_VEC3;
1237 case 0: return PACKING_ORDER_VEC4;
1238 default:
1239 assert(!"Unexpected value of vector_elements");
1240 return PACKING_ORDER_VEC4;
1241 }
1242 }
1243
1244
1245 /**
1246 * Comparison function passed to qsort() to sort varyings by packing_class and
1247 * then by packing_order.
1248 */
1249 int
1250 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
1251 {
1252 const match *x = (const match *) x_generic;
1253 const match *y = (const match *) y_generic;
1254
1255 if (x->packing_class != y->packing_class)
1256 return x->packing_class - y->packing_class;
1257 return x->packing_order - y->packing_order;
1258 }
1259
1260
1261 /**
1262 * Is the given variable a varying variable to be counted against the
1263 * limit in ctx->Const.MaxVarying?
1264 * This includes variables such as texcoords, colors and generic
1265 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
1266 */
1267 static bool
1268 var_counts_against_varying_limit(gl_shader_stage stage, const ir_variable *var)
1269 {
1270 /* Only fragment shaders will take a varying variable as an input */
1271 if (stage == MESA_SHADER_FRAGMENT &&
1272 var->data.mode == ir_var_shader_in) {
1273 switch (var->data.location) {
1274 case VARYING_SLOT_POS:
1275 case VARYING_SLOT_FACE:
1276 case VARYING_SLOT_PNTC:
1277 return false;
1278 default:
1279 return true;
1280 }
1281 }
1282 return false;
1283 }
1284
1285
1286 /**
1287 * Visitor class that generates tfeedback_candidate structs describing all
1288 * possible targets of transform feedback.
1289 *
1290 * tfeedback_candidate structs are stored in the hash table
1291 * tfeedback_candidates, which is passed to the constructor. This hash table
1292 * maps varying names to instances of the tfeedback_candidate struct.
1293 */
1294 class tfeedback_candidate_generator : public program_resource_visitor
1295 {
1296 public:
1297 tfeedback_candidate_generator(void *mem_ctx,
1298 hash_table *tfeedback_candidates)
1299 : mem_ctx(mem_ctx),
1300 tfeedback_candidates(tfeedback_candidates),
1301 toplevel_var(NULL),
1302 varying_floats(0)
1303 {
1304 }
1305
1306 void process(ir_variable *var)
1307 {
1308 /* All named varying interface blocks should be flattened by now */
1309 assert(!var->is_interface_instance());
1310
1311 this->toplevel_var = var;
1312 this->varying_floats = 0;
1313 program_resource_visitor::process(var);
1314 }
1315
1316 private:
1317 virtual void visit_field(const glsl_type *type, const char *name,
1318 bool row_major)
1319 {
1320 assert(!type->without_array()->is_record());
1321 assert(!type->without_array()->is_interface());
1322
1323 (void) row_major;
1324
1325 tfeedback_candidate *candidate
1326 = rzalloc(this->mem_ctx, tfeedback_candidate);
1327 candidate->toplevel_var = this->toplevel_var;
1328 candidate->type = type;
1329 candidate->offset = this->varying_floats;
1330 hash_table_insert(this->tfeedback_candidates, candidate,
1331 ralloc_strdup(this->mem_ctx, name));
1332 this->varying_floats += type->component_slots();
1333 }
1334
1335 /**
1336 * Memory context used to allocate hash table keys and values.
1337 */
1338 void * const mem_ctx;
1339
1340 /**
1341 * Hash table in which tfeedback_candidate objects should be stored.
1342 */
1343 hash_table * const tfeedback_candidates;
1344
1345 /**
1346 * Pointer to the toplevel variable that is being traversed.
1347 */
1348 ir_variable *toplevel_var;
1349
1350 /**
1351 * Total number of varying floats that have been visited so far. This is
1352 * used to determine the offset to each varying within the toplevel
1353 * variable.
1354 */
1355 unsigned varying_floats;
1356 };
1357
1358
1359 namespace linker {
1360
1361 void
1362 populate_consumer_input_sets(void *mem_ctx, exec_list *ir,
1363 hash_table *consumer_inputs,
1364 hash_table *consumer_interface_inputs,
1365 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
1366 {
1367 memset(consumer_inputs_with_locations,
1368 0,
1369 sizeof(consumer_inputs_with_locations[0]) * VARYING_SLOT_TESS_MAX);
1370
1371 foreach_in_list(ir_instruction, node, ir) {
1372 ir_variable *const input_var = node->as_variable();
1373
1374 if ((input_var != NULL) && (input_var->data.mode == ir_var_shader_in)) {
1375 /* All interface blocks should have been lowered by this point */
1376 assert(!input_var->type->is_interface());
1377
1378 if (input_var->data.explicit_location) {
1379 /* assign_varying_locations only cares about finding the
1380 * ir_variable at the start of a contiguous location block.
1381 *
1382 * - For !producer, consumer_inputs_with_locations isn't used.
1383 *
1384 * - For !consumer, consumer_inputs_with_locations is empty.
1385 *
1386 * For consumer && producer, if you were trying to set some
1387 * ir_variable to the middle of a location block on the other side
1388 * of producer/consumer, cross_validate_outputs_to_inputs() should
1389 * be link-erroring due to either type mismatch or location
1390 * overlaps. If the variables do match up, then they've got a
1391 * matching data.location and you only looked at
1392 * consumer_inputs_with_locations[var->data.location], not any
1393 * following entries for the array/structure.
1394 */
1395 consumer_inputs_with_locations[input_var->data.location] =
1396 input_var;
1397 } else if (input_var->get_interface_type() != NULL) {
1398 char *const iface_field_name =
1399 ralloc_asprintf(mem_ctx, "%s.%s",
1400 input_var->get_interface_type()->name,
1401 input_var->name);
1402 hash_table_insert(consumer_interface_inputs, input_var,
1403 iface_field_name);
1404 } else {
1405 hash_table_insert(consumer_inputs, input_var,
1406 ralloc_strdup(mem_ctx, input_var->name));
1407 }
1408 }
1409 }
1410 }
1411
1412 /**
1413 * Find a variable from the consumer that "matches" the specified variable
1414 *
1415 * This function only finds inputs with names that match. There is no
1416 * validation (here) that the types, etc. are compatible.
1417 */
1418 ir_variable *
1419 get_matching_input(void *mem_ctx,
1420 const ir_variable *output_var,
1421 hash_table *consumer_inputs,
1422 hash_table *consumer_interface_inputs,
1423 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
1424 {
1425 ir_variable *input_var;
1426
1427 if (output_var->data.explicit_location) {
1428 input_var = consumer_inputs_with_locations[output_var->data.location];
1429 } else if (output_var->get_interface_type() != NULL) {
1430 char *const iface_field_name =
1431 ralloc_asprintf(mem_ctx, "%s.%s",
1432 output_var->get_interface_type()->name,
1433 output_var->name);
1434 input_var =
1435 (ir_variable *) hash_table_find(consumer_interface_inputs,
1436 iface_field_name);
1437 } else {
1438 input_var =
1439 (ir_variable *) hash_table_find(consumer_inputs, output_var->name);
1440 }
1441
1442 return (input_var == NULL || input_var->data.mode != ir_var_shader_in)
1443 ? NULL : input_var;
1444 }
1445
1446 }
1447
1448 static int
1449 io_variable_cmp(const void *_a, const void *_b)
1450 {
1451 const ir_variable *const a = *(const ir_variable **) _a;
1452 const ir_variable *const b = *(const ir_variable **) _b;
1453
1454 if (a->data.explicit_location && b->data.explicit_location)
1455 return b->data.location - a->data.location;
1456
1457 if (a->data.explicit_location && !b->data.explicit_location)
1458 return 1;
1459
1460 if (!a->data.explicit_location && b->data.explicit_location)
1461 return -1;
1462
1463 return -strcmp(a->name, b->name);
1464 }
1465
1466 /**
1467 * Sort the shader IO variables into canonical order
1468 */
1469 static void
1470 canonicalize_shader_io(exec_list *ir, enum ir_variable_mode io_mode)
1471 {
1472 ir_variable *var_table[MAX_PROGRAM_OUTPUTS * 4];
1473 unsigned num_variables = 0;
1474
1475 foreach_in_list(ir_instruction, node, ir) {
1476 ir_variable *const var = node->as_variable();
1477
1478 if (var == NULL || var->data.mode != io_mode)
1479 continue;
1480
1481 /* If we have already encountered more I/O variables that could
1482 * successfully link, bail.
1483 */
1484 if (num_variables == ARRAY_SIZE(var_table))
1485 return;
1486
1487 var_table[num_variables++] = var;
1488 }
1489
1490 if (num_variables == 0)
1491 return;
1492
1493 /* Sort the list in reverse order (io_variable_cmp handles this). Later
1494 * we're going to push the variables on to the IR list as a stack, so we
1495 * want the last variable (in canonical order) to be first in the list.
1496 */
1497 qsort(var_table, num_variables, sizeof(var_table[0]), io_variable_cmp);
1498
1499 /* Remove the variable from it's current location in the IR, and put it at
1500 * the front.
1501 */
1502 for (unsigned i = 0; i < num_variables; i++) {
1503 var_table[i]->remove();
1504 ir->push_head(var_table[i]);
1505 }
1506 }
1507
1508 /**
1509 * Generate a bitfield map of the explicit locations for shader varyings.
1510 *
1511 * In theory a 32 bits value will be enough but a 64 bits value is future proof.
1512 */
1513 uint64_t
1514 reserved_varying_slot(struct gl_shader *stage, ir_variable_mode io_mode)
1515 {
1516 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
1517 assert(MAX_VARYING <= 64); /* avoid an overflow of the returned value */
1518
1519 uint64_t slots = 0;
1520 int var_slot;
1521
1522 if (!stage)
1523 return slots;
1524
1525 foreach_in_list(ir_instruction, node, stage->ir) {
1526 ir_variable *const var = node->as_variable();
1527
1528 if (var == NULL || var->data.mode != io_mode ||
1529 !var->data.explicit_location ||
1530 var->data.location < VARYING_SLOT_VAR0)
1531 continue;
1532
1533 var_slot = var->data.location - VARYING_SLOT_VAR0;
1534
1535 unsigned num_elements = get_varying_type(var, stage->Stage)
1536 ->count_attribute_slots(stage->Stage == MESA_SHADER_VERTEX);
1537 for (unsigned i = 0; i < num_elements; i++) {
1538 if (var_slot >= 0 && var_slot < MAX_VARYING)
1539 slots |= UINT64_C(1) << var_slot;
1540 var_slot += 1;
1541 }
1542 }
1543
1544 return slots;
1545 }
1546
1547
1548 /**
1549 * Assign locations for all variables that are produced in one pipeline stage
1550 * (the "producer") and consumed in the next stage (the "consumer").
1551 *
1552 * Variables produced by the producer may also be consumed by transform
1553 * feedback.
1554 *
1555 * \param num_tfeedback_decls is the number of declarations indicating
1556 * variables that may be consumed by transform feedback.
1557 *
1558 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1559 * representing the result of parsing the strings passed to
1560 * glTransformFeedbackVaryings(). assign_location() will be called for
1561 * each of these objects that matches one of the outputs of the
1562 * producer.
1563 *
1564 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1565 * be NULL. In this case, varying locations are assigned solely based on the
1566 * requirements of transform feedback.
1567 */
1568 bool
1569 assign_varying_locations(struct gl_context *ctx,
1570 void *mem_ctx,
1571 struct gl_shader_program *prog,
1572 gl_shader *producer, gl_shader *consumer,
1573 unsigned num_tfeedback_decls,
1574 tfeedback_decl *tfeedback_decls)
1575 {
1576 if (ctx->Const.DisableVaryingPacking) {
1577 /* Transform feedback code assumes varyings are packed, so if the driver
1578 * has disabled varying packing, make sure it does not support transform
1579 * feedback.
1580 */
1581 assert(!ctx->Extensions.EXT_transform_feedback);
1582 }
1583
1584 /* Tessellation shaders treat inputs and outputs as shared memory and can
1585 * access inputs and outputs of other invocations.
1586 * Therefore, they can't be lowered to temps easily (and definitely not
1587 * efficiently).
1588 */
1589 bool disable_varying_packing =
1590 ctx->Const.DisableVaryingPacking ||
1591 (consumer && consumer->Stage == MESA_SHADER_TESS_EVAL) ||
1592 (consumer && consumer->Stage == MESA_SHADER_TESS_CTRL) ||
1593 (producer && producer->Stage == MESA_SHADER_TESS_CTRL);
1594
1595 varying_matches matches(disable_varying_packing,
1596 producer ? producer->Stage : (gl_shader_stage)-1,
1597 consumer ? consumer->Stage : (gl_shader_stage)-1);
1598 hash_table *tfeedback_candidates
1599 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1600 hash_table *consumer_inputs
1601 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1602 hash_table *consumer_interface_inputs
1603 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1604 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX] = {
1605 NULL,
1606 };
1607
1608 unsigned consumer_vertices = 0;
1609 if (consumer && consumer->Stage == MESA_SHADER_GEOMETRY)
1610 consumer_vertices = prog->Geom.VerticesIn;
1611
1612 /* Operate in a total of four passes.
1613 *
1614 * 1. Sort inputs / outputs into a canonical order. This is necessary so
1615 * that inputs / outputs of separable shaders will be assigned
1616 * predictable locations regardless of the order in which declarations
1617 * appeared in the shader source.
1618 *
1619 * 2. Assign locations for any matching inputs and outputs.
1620 *
1621 * 3. Mark output variables in the producer that do not have locations as
1622 * not being outputs. This lets the optimizer eliminate them.
1623 *
1624 * 4. Mark input variables in the consumer that do not have locations as
1625 * not being inputs. This lets the optimizer eliminate them.
1626 */
1627 if (consumer)
1628 canonicalize_shader_io(consumer->ir, ir_var_shader_in);
1629
1630 if (producer)
1631 canonicalize_shader_io(producer->ir, ir_var_shader_out);
1632
1633 if (consumer)
1634 linker::populate_consumer_input_sets(mem_ctx, consumer->ir,
1635 consumer_inputs,
1636 consumer_interface_inputs,
1637 consumer_inputs_with_locations);
1638
1639 if (producer) {
1640 foreach_in_list(ir_instruction, node, producer->ir) {
1641 ir_variable *const output_var = node->as_variable();
1642
1643 if ((output_var == NULL) ||
1644 (output_var->data.mode != ir_var_shader_out))
1645 continue;
1646
1647 /* Only geometry shaders can use non-zero streams */
1648 assert(output_var->data.stream == 0 ||
1649 (output_var->data.stream < MAX_VERTEX_STREAMS &&
1650 producer->Stage == MESA_SHADER_GEOMETRY));
1651
1652 if (num_tfeedback_decls > 0) {
1653 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates);
1654 g.process(output_var);
1655 }
1656
1657 ir_variable *const input_var =
1658 linker::get_matching_input(mem_ctx, output_var, consumer_inputs,
1659 consumer_interface_inputs,
1660 consumer_inputs_with_locations);
1661
1662 /* If a matching input variable was found, add this ouptut (and the
1663 * input) to the set. If this is a separable program and there is no
1664 * consumer stage, add the output.
1665 *
1666 * Always add TCS outputs. They are shared by all invocations
1667 * within a patch and can be used as shared memory.
1668 */
1669 if (input_var || (prog->SeparateShader && consumer == NULL) ||
1670 producer->Type == GL_TESS_CONTROL_SHADER) {
1671 matches.record(output_var, input_var);
1672 }
1673
1674 /* Only stream 0 outputs can be consumed in the next stage */
1675 if (input_var && output_var->data.stream != 0) {
1676 linker_error(prog, "output %s is assigned to stream=%d but "
1677 "is linked to an input, which requires stream=0",
1678 output_var->name, output_var->data.stream);
1679 return false;
1680 }
1681 }
1682 } else {
1683 /* If there's no producer stage, then this must be a separable program.
1684 * For example, we may have a program that has just a fragment shader.
1685 * Later this program will be used with some arbitrary vertex (or
1686 * geometry) shader program. This means that locations must be assigned
1687 * for all the inputs.
1688 */
1689 foreach_in_list(ir_instruction, node, consumer->ir) {
1690 ir_variable *const input_var = node->as_variable();
1691
1692 if ((input_var == NULL) ||
1693 (input_var->data.mode != ir_var_shader_in))
1694 continue;
1695
1696 matches.record(NULL, input_var);
1697 }
1698 }
1699
1700 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1701 if (!tfeedback_decls[i].is_varying())
1702 continue;
1703
1704 const tfeedback_candidate *matched_candidate
1705 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
1706
1707 if (matched_candidate == NULL) {
1708 hash_table_dtor(tfeedback_candidates);
1709 hash_table_dtor(consumer_inputs);
1710 hash_table_dtor(consumer_interface_inputs);
1711 return false;
1712 }
1713
1714 if (matched_candidate->toplevel_var->data.is_unmatched_generic_inout)
1715 matches.record(matched_candidate->toplevel_var, NULL);
1716 }
1717
1718 const uint64_t reserved_slots =
1719 reserved_varying_slot(producer, ir_var_shader_out) |
1720 reserved_varying_slot(consumer, ir_var_shader_in);
1721
1722 const unsigned slots_used = matches.assign_locations(prog, reserved_slots,
1723 prog->SeparateShader);
1724 matches.store_locations();
1725
1726 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1727 if (!tfeedback_decls[i].is_varying())
1728 continue;
1729
1730 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
1731 hash_table_dtor(tfeedback_candidates);
1732 hash_table_dtor(consumer_inputs);
1733 hash_table_dtor(consumer_interface_inputs);
1734 return false;
1735 }
1736 }
1737
1738 hash_table_dtor(tfeedback_candidates);
1739 hash_table_dtor(consumer_inputs);
1740 hash_table_dtor(consumer_interface_inputs);
1741
1742 if (consumer && producer) {
1743 foreach_in_list(ir_instruction, node, consumer->ir) {
1744 ir_variable *const var = node->as_variable();
1745
1746 if (var && var->data.mode == ir_var_shader_in &&
1747 var->data.is_unmatched_generic_inout) {
1748 if (!prog->IsES && prog->Version <= 120) {
1749 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1750 *
1751 * Only those varying variables used (i.e. read) in
1752 * the fragment shader executable must be written to
1753 * by the vertex shader executable; declaring
1754 * superfluous varying variables in a vertex shader is
1755 * permissible.
1756 *
1757 * We interpret this text as meaning that the VS must
1758 * write the variable for the FS to read it. See
1759 * "glsl1-varying read but not written" in piglit.
1760 */
1761 linker_error(prog, "%s shader varying %s not written "
1762 "by %s shader\n.",
1763 _mesa_shader_stage_to_string(consumer->Stage),
1764 var->name,
1765 _mesa_shader_stage_to_string(producer->Stage));
1766 } else {
1767 linker_warning(prog, "%s shader varying %s not written "
1768 "by %s shader\n.",
1769 _mesa_shader_stage_to_string(consumer->Stage),
1770 var->name,
1771 _mesa_shader_stage_to_string(producer->Stage));
1772 }
1773 }
1774 }
1775
1776 /* Now that validation is done its safe to remove unused varyings. As
1777 * we have both a producer and consumer its safe to remove unused
1778 * varyings even if the program is a SSO because the stages are being
1779 * linked together i.e. we have a multi-stage SSO.
1780 */
1781 remove_unused_shader_inputs_and_outputs(false, producer,
1782 ir_var_shader_out);
1783 remove_unused_shader_inputs_and_outputs(false, consumer,
1784 ir_var_shader_in);
1785 }
1786
1787 if (producer) {
1788 lower_packed_varyings(mem_ctx, slots_used, ir_var_shader_out,
1789 0, producer, disable_varying_packing);
1790 }
1791
1792 if (consumer) {
1793 lower_packed_varyings(mem_ctx, slots_used, ir_var_shader_in,
1794 consumer_vertices, consumer,
1795 disable_varying_packing);
1796 }
1797
1798 return true;
1799 }
1800
1801 bool
1802 check_against_output_limit(struct gl_context *ctx,
1803 struct gl_shader_program *prog,
1804 gl_shader *producer)
1805 {
1806 unsigned output_vectors = 0;
1807
1808 foreach_in_list(ir_instruction, node, producer->ir) {
1809 ir_variable *const var = node->as_variable();
1810
1811 if (var && var->data.mode == ir_var_shader_out &&
1812 var_counts_against_varying_limit(producer->Stage, var)) {
1813 /* outputs for fragment shader can't be doubles */
1814 output_vectors += var->type->count_attribute_slots(false);
1815 }
1816 }
1817
1818 assert(producer->Stage != MESA_SHADER_FRAGMENT);
1819 unsigned max_output_components =
1820 ctx->Const.Program[producer->Stage].MaxOutputComponents;
1821
1822 const unsigned output_components = output_vectors * 4;
1823 if (output_components > max_output_components) {
1824 if (ctx->API == API_OPENGLES2 || prog->IsES)
1825 linker_error(prog, "%s shader uses too many output vectors "
1826 "(%u > %u)\n",
1827 _mesa_shader_stage_to_string(producer->Stage),
1828 output_vectors,
1829 max_output_components / 4);
1830 else
1831 linker_error(prog, "%s shader uses too many output components "
1832 "(%u > %u)\n",
1833 _mesa_shader_stage_to_string(producer->Stage),
1834 output_components,
1835 max_output_components);
1836
1837 return false;
1838 }
1839
1840 return true;
1841 }
1842
1843 bool
1844 check_against_input_limit(struct gl_context *ctx,
1845 struct gl_shader_program *prog,
1846 gl_shader *consumer)
1847 {
1848 unsigned input_vectors = 0;
1849
1850 foreach_in_list(ir_instruction, node, consumer->ir) {
1851 ir_variable *const var = node->as_variable();
1852
1853 if (var && var->data.mode == ir_var_shader_in &&
1854 var_counts_against_varying_limit(consumer->Stage, var)) {
1855 /* vertex inputs aren't varying counted */
1856 input_vectors += var->type->count_attribute_slots(false);
1857 }
1858 }
1859
1860 assert(consumer->Stage != MESA_SHADER_VERTEX);
1861 unsigned max_input_components =
1862 ctx->Const.Program[consumer->Stage].MaxInputComponents;
1863
1864 const unsigned input_components = input_vectors * 4;
1865 if (input_components > max_input_components) {
1866 if (ctx->API == API_OPENGLES2 || prog->IsES)
1867 linker_error(prog, "%s shader uses too many input vectors "
1868 "(%u > %u)\n",
1869 _mesa_shader_stage_to_string(consumer->Stage),
1870 input_vectors,
1871 max_input_components / 4);
1872 else
1873 linker_error(prog, "%s shader uses too many input components "
1874 "(%u > %u)\n",
1875 _mesa_shader_stage_to_string(consumer->Stage),
1876 input_components,
1877 max_input_components);
1878
1879 return false;
1880 }
1881
1882 return true;
1883 }