glsl: Validate qualifiers on VS color outputs with FS color inputs
[mesa.git] / src / 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 * Validate the types and qualifiers of an output from one stage against the
45 * matching input to another stage.
46 */
47 static void
48 cross_validate_types_and_qualifiers(struct gl_shader_program *prog,
49 const ir_variable *input,
50 const ir_variable *output,
51 GLenum consumer_type,
52 GLenum producer_type)
53 {
54 /* Check that the types match between stages.
55 */
56 const glsl_type *type_to_match = input->type;
57 if (consumer_type == GL_GEOMETRY_SHADER) {
58 assert(type_to_match->is_array()); /* Enforced by ast_to_hir */
59 type_to_match = type_to_match->element_type();
60 }
61 if (type_to_match != output->type) {
62 /* There is a bit of a special case for gl_TexCoord. This
63 * built-in is unsized by default. Applications that variable
64 * access it must redeclare it with a size. There is some
65 * language in the GLSL spec that implies the fragment shader
66 * and vertex shader do not have to agree on this size. Other
67 * driver behave this way, and one or two applications seem to
68 * rely on it.
69 *
70 * Neither declaration needs to be modified here because the array
71 * sizes are fixed later when update_array_sizes is called.
72 *
73 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
74 *
75 * "Unlike user-defined varying variables, the built-in
76 * varying variables don't have a strict one-to-one
77 * correspondence between the vertex language and the
78 * fragment language."
79 */
80 if (!output->type->is_array()
81 || (strncmp("gl_", output->name, 3) != 0)) {
82 linker_error(prog,
83 "%s shader output `%s' declared as type `%s', "
84 "but %s shader input declared as type `%s'\n",
85 _mesa_glsl_shader_target_name(producer_type),
86 output->name,
87 output->type->name,
88 _mesa_glsl_shader_target_name(consumer_type),
89 input->type->name);
90 return;
91 }
92 }
93
94 /* Check that all of the qualifiers match between stages.
95 */
96 if (input->centroid != output->centroid) {
97 linker_error(prog,
98 "%s shader output `%s' %s centroid qualifier, "
99 "but %s shader input %s centroid qualifier\n",
100 _mesa_glsl_shader_target_name(producer_type),
101 output->name,
102 (output->centroid) ? "has" : "lacks",
103 _mesa_glsl_shader_target_name(consumer_type),
104 (input->centroid) ? "has" : "lacks");
105 return;
106 }
107
108 if (input->invariant != output->invariant) {
109 linker_error(prog,
110 "%s shader output `%s' %s invariant qualifier, "
111 "but %s shader input %s invariant qualifier\n",
112 _mesa_glsl_shader_target_name(producer_type),
113 output->name,
114 (output->invariant) ? "has" : "lacks",
115 _mesa_glsl_shader_target_name(consumer_type),
116 (input->invariant) ? "has" : "lacks");
117 return;
118 }
119
120 if (input->interpolation != output->interpolation) {
121 linker_error(prog,
122 "%s shader output `%s' specifies %s "
123 "interpolation qualifier, "
124 "but %s shader input specifies %s "
125 "interpolation qualifier\n",
126 _mesa_glsl_shader_target_name(producer_type),
127 output->name,
128 output->interpolation_string(),
129 _mesa_glsl_shader_target_name(consumer_type),
130 input->interpolation_string());
131 return;
132 }
133 }
134
135 /**
136 * Validate front and back color outputs against single color input
137 */
138 static void
139 cross_validate_front_and_back_color(struct gl_shader_program *prog,
140 const ir_variable *input,
141 const ir_variable *front_color,
142 const ir_variable *back_color,
143 GLenum consumer_type,
144 GLenum producer_type)
145 {
146 if (front_color != NULL && front_color->assigned)
147 cross_validate_types_and_qualifiers(prog, input, front_color,
148 consumer_type, producer_type);
149
150 if (back_color != NULL && back_color->assigned)
151 cross_validate_types_and_qualifiers(prog, input, back_color,
152 consumer_type, producer_type);
153 }
154
155 /**
156 * Validate that outputs from one stage match inputs of another
157 */
158 void
159 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
160 gl_shader *producer, gl_shader *consumer)
161 {
162 glsl_symbol_table parameters;
163
164 /* Find all shader outputs in the "producer" stage.
165 */
166 foreach_list(node, producer->ir) {
167 ir_variable *const var = ((ir_instruction *) node)->as_variable();
168
169 if ((var == NULL) || (var->mode != ir_var_shader_out))
170 continue;
171
172 parameters.add_variable(var);
173 }
174
175
176 /* Find all shader inputs in the "consumer" stage. Any variables that have
177 * matching outputs already in the symbol table must have the same type and
178 * qualifiers.
179 *
180 * Exception: if the consumer is the geometry shader, then the inputs
181 * should be arrays and the type of the array element should match the type
182 * of the corresponding producer output.
183 */
184 foreach_list(node, consumer->ir) {
185 ir_variable *const input = ((ir_instruction *) node)->as_variable();
186
187 if ((input == NULL) || (input->mode != ir_var_shader_in))
188 continue;
189
190 if (strcmp(input->name, "gl_Color") == 0 && input->used) {
191 const ir_variable *const front_color =
192 parameters.get_variable("gl_FrontColor");
193
194 const ir_variable *const back_color =
195 parameters.get_variable("gl_BackColor");
196
197 cross_validate_front_and_back_color(prog, input,
198 front_color, back_color,
199 consumer->Type, producer->Type);
200 } else if (strcmp(input->name, "gl_SecondaryColor") == 0 && input->used) {
201 const ir_variable *const front_color =
202 parameters.get_variable("gl_FrontSecondaryColor");
203
204 const ir_variable *const back_color =
205 parameters.get_variable("gl_BackSecondaryColor");
206
207 cross_validate_front_and_back_color(prog, input,
208 front_color, back_color,
209 consumer->Type, producer->Type);
210 } else {
211 ir_variable *const output = parameters.get_variable(input->name);
212 if (output != NULL) {
213 cross_validate_types_and_qualifiers(prog, input, output,
214 consumer->Type, producer->Type);
215 }
216 }
217 }
218 }
219
220
221 /**
222 * Initialize this object based on a string that was passed to
223 * glTransformFeedbackVaryings.
224 *
225 * If the input is mal-formed, this call still succeeds, but it sets
226 * this->var_name to a mal-formed input, so tfeedback_decl::find_output_var()
227 * will fail to find any matching variable.
228 */
229 void
230 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
231 const void *mem_ctx, const char *input)
232 {
233 /* We don't have to be pedantic about what is a valid GLSL variable name,
234 * because any variable with an invalid name can't exist in the IR anyway.
235 */
236
237 this->location = -1;
238 this->orig_name = input;
239 this->is_clip_distance_mesa = false;
240 this->skip_components = 0;
241 this->next_buffer_separator = false;
242 this->matched_candidate = NULL;
243
244 if (ctx->Extensions.ARB_transform_feedback3) {
245 /* Parse gl_NextBuffer. */
246 if (strcmp(input, "gl_NextBuffer") == 0) {
247 this->next_buffer_separator = true;
248 return;
249 }
250
251 /* Parse gl_SkipComponents. */
252 if (strcmp(input, "gl_SkipComponents1") == 0)
253 this->skip_components = 1;
254 else if (strcmp(input, "gl_SkipComponents2") == 0)
255 this->skip_components = 2;
256 else if (strcmp(input, "gl_SkipComponents3") == 0)
257 this->skip_components = 3;
258 else if (strcmp(input, "gl_SkipComponents4") == 0)
259 this->skip_components = 4;
260
261 if (this->skip_components)
262 return;
263 }
264
265 /* Parse a declaration. */
266 const char *base_name_end;
267 long subscript = parse_program_resource_name(input, &base_name_end);
268 this->var_name = ralloc_strndup(mem_ctx, input, base_name_end - input);
269 if (subscript >= 0) {
270 this->array_subscript = subscript;
271 this->is_subscripted = true;
272 } else {
273 this->is_subscripted = false;
274 }
275
276 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
277 * class must behave specially to account for the fact that gl_ClipDistance
278 * is converted from a float[8] to a vec4[2].
279 */
280 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
281 strcmp(this->var_name, "gl_ClipDistance") == 0) {
282 this->is_clip_distance_mesa = true;
283 }
284 }
285
286
287 /**
288 * Determine whether two tfeedback_decl objects refer to the same variable and
289 * array index (if applicable).
290 */
291 bool
292 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
293 {
294 assert(x.is_varying() && y.is_varying());
295
296 if (strcmp(x.var_name, y.var_name) != 0)
297 return false;
298 if (x.is_subscripted != y.is_subscripted)
299 return false;
300 if (x.is_subscripted && x.array_subscript != y.array_subscript)
301 return false;
302 return true;
303 }
304
305
306 /**
307 * Assign a location for this tfeedback_decl object based on the transform
308 * feedback candidate found by find_candidate.
309 *
310 * If an error occurs, the error is reported through linker_error() and false
311 * is returned.
312 */
313 bool
314 tfeedback_decl::assign_location(struct gl_context *ctx,
315 struct gl_shader_program *prog)
316 {
317 assert(this->is_varying());
318
319 unsigned fine_location
320 = this->matched_candidate->toplevel_var->location * 4
321 + this->matched_candidate->toplevel_var->location_frac
322 + this->matched_candidate->offset;
323
324 if (this->matched_candidate->type->is_array()) {
325 /* Array variable */
326 const unsigned matrix_cols =
327 this->matched_candidate->type->fields.array->matrix_columns;
328 const unsigned vector_elements =
329 this->matched_candidate->type->fields.array->vector_elements;
330 unsigned actual_array_size = this->is_clip_distance_mesa ?
331 prog->Vert.ClipDistanceArraySize :
332 this->matched_candidate->type->array_size();
333
334 if (this->is_subscripted) {
335 /* Check array bounds. */
336 if (this->array_subscript >= actual_array_size) {
337 linker_error(prog, "Transform feedback varying %s has index "
338 "%i, but the array size is %u.",
339 this->orig_name, this->array_subscript,
340 actual_array_size);
341 return false;
342 }
343 unsigned array_elem_size = this->is_clip_distance_mesa ?
344 1 : vector_elements * matrix_cols;
345 fine_location += array_elem_size * this->array_subscript;
346 this->size = 1;
347 } else {
348 this->size = actual_array_size;
349 }
350 this->vector_elements = vector_elements;
351 this->matrix_columns = matrix_cols;
352 if (this->is_clip_distance_mesa)
353 this->type = GL_FLOAT;
354 else
355 this->type = this->matched_candidate->type->fields.array->gl_type;
356 } else {
357 /* Regular variable (scalar, vector, or matrix) */
358 if (this->is_subscripted) {
359 linker_error(prog, "Transform feedback varying %s requested, "
360 "but %s is not an array.",
361 this->orig_name, this->var_name);
362 return false;
363 }
364 this->size = 1;
365 this->vector_elements = this->matched_candidate->type->vector_elements;
366 this->matrix_columns = this->matched_candidate->type->matrix_columns;
367 this->type = this->matched_candidate->type->gl_type;
368 }
369 this->location = fine_location / 4;
370 this->location_frac = fine_location % 4;
371
372 /* From GL_EXT_transform_feedback:
373 * A program will fail to link if:
374 *
375 * * the total number of components to capture in any varying
376 * variable in <varyings> is greater than the constant
377 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
378 * buffer mode is SEPARATE_ATTRIBS_EXT;
379 */
380 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
381 this->num_components() >
382 ctx->Const.MaxTransformFeedbackSeparateComponents) {
383 linker_error(prog, "Transform feedback varying %s exceeds "
384 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
385 this->orig_name);
386 return false;
387 }
388
389 return true;
390 }
391
392
393 unsigned
394 tfeedback_decl::get_num_outputs() const
395 {
396 if (!this->is_varying()) {
397 return 0;
398 }
399
400 return (this->num_components() + this->location_frac + 3)/4;
401 }
402
403
404 /**
405 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
406 *
407 * If an error occurs, the error is reported through linker_error() and false
408 * is returned.
409 */
410 bool
411 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
412 struct gl_transform_feedback_info *info,
413 unsigned buffer, const unsigned max_outputs) const
414 {
415 assert(!this->next_buffer_separator);
416
417 /* Handle gl_SkipComponents. */
418 if (this->skip_components) {
419 info->BufferStride[buffer] += this->skip_components;
420 return true;
421 }
422
423 /* From GL_EXT_transform_feedback:
424 * A program will fail to link if:
425 *
426 * * the total number of components to capture is greater than
427 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
428 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
429 */
430 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
431 info->BufferStride[buffer] + this->num_components() >
432 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
433 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
434 "limit has been exceeded.");
435 return false;
436 }
437
438 unsigned location = this->location;
439 unsigned location_frac = this->location_frac;
440 unsigned num_components = this->num_components();
441 while (num_components > 0) {
442 unsigned output_size = MIN2(num_components, 4 - location_frac);
443 assert(info->NumOutputs < max_outputs);
444 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
445 info->Outputs[info->NumOutputs].OutputRegister = location;
446 info->Outputs[info->NumOutputs].NumComponents = output_size;
447 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
448 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
449 ++info->NumOutputs;
450 info->BufferStride[buffer] += output_size;
451 num_components -= output_size;
452 location++;
453 location_frac = 0;
454 }
455
456 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
457 info->Varyings[info->NumVarying].Type = this->type;
458 info->Varyings[info->NumVarying].Size = this->size;
459 info->NumVarying++;
460
461 return true;
462 }
463
464
465 const tfeedback_candidate *
466 tfeedback_decl::find_candidate(gl_shader_program *prog,
467 hash_table *tfeedback_candidates)
468 {
469 const char *name = this->is_clip_distance_mesa
470 ? "gl_ClipDistanceMESA" : this->var_name;
471 this->matched_candidate = (const tfeedback_candidate *)
472 hash_table_find(tfeedback_candidates, name);
473 if (!this->matched_candidate) {
474 /* From GL_EXT_transform_feedback:
475 * A program will fail to link if:
476 *
477 * * any variable name specified in the <varyings> array is not
478 * declared as an output in the geometry shader (if present) or
479 * the vertex shader (if no geometry shader is present);
480 */
481 linker_error(prog, "Transform feedback varying %s undeclared.",
482 this->orig_name);
483 }
484 return this->matched_candidate;
485 }
486
487
488 /**
489 * Parse all the transform feedback declarations that were passed to
490 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
491 *
492 * If an error occurs, the error is reported through linker_error() and false
493 * is returned.
494 */
495 bool
496 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
497 const void *mem_ctx, unsigned num_names,
498 char **varying_names, tfeedback_decl *decls)
499 {
500 for (unsigned i = 0; i < num_names; ++i) {
501 decls[i].init(ctx, prog, mem_ctx, varying_names[i]);
502
503 if (!decls[i].is_varying())
504 continue;
505
506 /* From GL_EXT_transform_feedback:
507 * A program will fail to link if:
508 *
509 * * any two entries in the <varyings> array specify the same varying
510 * variable;
511 *
512 * We interpret this to mean "any two entries in the <varyings> array
513 * specify the same varying variable and array index", since transform
514 * feedback of arrays would be useless otherwise.
515 */
516 for (unsigned j = 0; j < i; ++j) {
517 if (!decls[j].is_varying())
518 continue;
519
520 if (tfeedback_decl::is_same(decls[i], decls[j])) {
521 linker_error(prog, "Transform feedback varying %s specified "
522 "more than once.", varying_names[i]);
523 return false;
524 }
525 }
526 }
527 return true;
528 }
529
530
531 /**
532 * Store transform feedback location assignments into
533 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
534 *
535 * If an error occurs, the error is reported through linker_error() and false
536 * is returned.
537 */
538 bool
539 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
540 unsigned num_tfeedback_decls,
541 tfeedback_decl *tfeedback_decls)
542 {
543 bool separate_attribs_mode =
544 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
545
546 ralloc_free(prog->LinkedTransformFeedback.Varyings);
547 ralloc_free(prog->LinkedTransformFeedback.Outputs);
548
549 memset(&prog->LinkedTransformFeedback, 0,
550 sizeof(prog->LinkedTransformFeedback));
551
552 prog->LinkedTransformFeedback.Varyings =
553 rzalloc_array(prog,
554 struct gl_transform_feedback_varying_info,
555 num_tfeedback_decls);
556
557 unsigned num_outputs = 0;
558 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
559 num_outputs += tfeedback_decls[i].get_num_outputs();
560
561 prog->LinkedTransformFeedback.Outputs =
562 rzalloc_array(prog,
563 struct gl_transform_feedback_output,
564 num_outputs);
565
566 unsigned num_buffers = 0;
567
568 if (separate_attribs_mode) {
569 /* GL_SEPARATE_ATTRIBS */
570 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
571 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
572 num_buffers, num_outputs))
573 return false;
574
575 num_buffers++;
576 }
577 }
578 else {
579 /* GL_INVERLEAVED_ATTRIBS */
580 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
581 if (tfeedback_decls[i].is_next_buffer_separator()) {
582 num_buffers++;
583 continue;
584 }
585
586 if (!tfeedback_decls[i].store(ctx, prog,
587 &prog->LinkedTransformFeedback,
588 num_buffers, num_outputs))
589 return false;
590 }
591 num_buffers++;
592 }
593
594 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
595
596 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
597 return true;
598 }
599
600
601 /**
602 * Data structure recording the relationship between outputs of one shader
603 * stage (the "producer") and inputs of another (the "consumer").
604 */
605 class varying_matches
606 {
607 public:
608 varying_matches(bool disable_varying_packing, bool consumer_is_fs);
609 ~varying_matches();
610 void record(ir_variable *producer_var, ir_variable *consumer_var);
611 unsigned assign_locations();
612 void store_locations(unsigned producer_base, unsigned consumer_base) const;
613
614 private:
615 /**
616 * If true, this driver disables varying packing, so all varyings need to
617 * be aligned on slot boundaries, and take up a number of slots equal to
618 * their number of matrix columns times their array size.
619 */
620 const bool disable_varying_packing;
621
622 /**
623 * Enum representing the order in which varyings are packed within a
624 * packing class.
625 *
626 * Currently we pack vec4's first, then vec2's, then scalar values, then
627 * vec3's. This order ensures that the only vectors that are at risk of
628 * having to be "double parked" (split between two adjacent varying slots)
629 * are the vec3's.
630 */
631 enum packing_order_enum {
632 PACKING_ORDER_VEC4,
633 PACKING_ORDER_VEC2,
634 PACKING_ORDER_SCALAR,
635 PACKING_ORDER_VEC3,
636 };
637
638 static unsigned compute_packing_class(ir_variable *var);
639 static packing_order_enum compute_packing_order(ir_variable *var);
640 static int match_comparator(const void *x_generic, const void *y_generic);
641
642 /**
643 * Structure recording the relationship between a single producer output
644 * and a single consumer input.
645 */
646 struct match {
647 /**
648 * Packing class for this varying, computed by compute_packing_class().
649 */
650 unsigned packing_class;
651
652 /**
653 * Packing order for this varying, computed by compute_packing_order().
654 */
655 packing_order_enum packing_order;
656 unsigned num_components;
657
658 /**
659 * The output variable in the producer stage.
660 */
661 ir_variable *producer_var;
662
663 /**
664 * The input variable in the consumer stage.
665 */
666 ir_variable *consumer_var;
667
668 /**
669 * The location which has been assigned for this varying. This is
670 * expressed in multiples of a float, with the first generic varying
671 * (i.e. the one referred to by VARYING_SLOT_VAR0) represented by the
672 * value 0.
673 */
674 unsigned generic_location;
675 } *matches;
676
677 /**
678 * The number of elements in the \c matches array that are currently in
679 * use.
680 */
681 unsigned num_matches;
682
683 /**
684 * The number of elements that were set aside for the \c matches array when
685 * it was allocated.
686 */
687 unsigned matches_capacity;
688
689 const bool consumer_is_fs;
690 };
691
692
693 varying_matches::varying_matches(bool disable_varying_packing,
694 bool consumer_is_fs)
695 : disable_varying_packing(disable_varying_packing),
696 consumer_is_fs(consumer_is_fs)
697 {
698 /* Note: this initial capacity is rather arbitrarily chosen to be large
699 * enough for many cases without wasting an unreasonable amount of space.
700 * varying_matches::record() will resize the array if there are more than
701 * this number of varyings.
702 */
703 this->matches_capacity = 8;
704 this->matches = (match *)
705 malloc(sizeof(*this->matches) * this->matches_capacity);
706 this->num_matches = 0;
707 }
708
709
710 varying_matches::~varying_matches()
711 {
712 free(this->matches);
713 }
714
715
716 /**
717 * Record the given producer/consumer variable pair in the list of variables
718 * that should later be assigned locations.
719 *
720 * It is permissible for \c consumer_var to be NULL (this happens if a
721 * variable is output by the producer and consumed by transform feedback, but
722 * not consumed by the consumer).
723 *
724 * If \c producer_var has already been paired up with a consumer_var, or
725 * producer_var is part of fixed pipeline functionality (and hence already has
726 * a location assigned), this function has no effect.
727 *
728 * Note: as a side effect this function may change the interpolation type of
729 * \c producer_var, but only when the change couldn't possibly affect
730 * rendering.
731 */
732 void
733 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
734 {
735 if (!producer_var->is_unmatched_generic_inout) {
736 /* Either a location already exists for this variable (since it is part
737 * of fixed functionality), or it has already been recorded as part of a
738 * previous match.
739 */
740 return;
741 }
742
743 if ((consumer_var == NULL && producer_var->type->contains_integer()) ||
744 !consumer_is_fs) {
745 /* Since this varying is not being consumed by the fragment shader, its
746 * interpolation type varying cannot possibly affect rendering. Also,
747 * this variable is non-flat and is (or contains) an integer.
748 *
749 * lower_packed_varyings requires all integer varyings to flat,
750 * regardless of where they appear. We can trivially satisfy that
751 * requirement by changing the interpolation type to flat here.
752 */
753 producer_var->centroid = false;
754 producer_var->interpolation = INTERP_QUALIFIER_FLAT;
755
756 if (consumer_var) {
757 consumer_var->centroid = false;
758 consumer_var->interpolation = INTERP_QUALIFIER_FLAT;
759 }
760 }
761
762 if (this->num_matches == this->matches_capacity) {
763 this->matches_capacity *= 2;
764 this->matches = (match *)
765 realloc(this->matches,
766 sizeof(*this->matches) * this->matches_capacity);
767 }
768 this->matches[this->num_matches].packing_class
769 = this->compute_packing_class(producer_var);
770 this->matches[this->num_matches].packing_order
771 = this->compute_packing_order(producer_var);
772 if (this->disable_varying_packing) {
773 unsigned slots = producer_var->type->is_array()
774 ? (producer_var->type->length
775 * producer_var->type->fields.array->matrix_columns)
776 : producer_var->type->matrix_columns;
777 this->matches[this->num_matches].num_components = 4 * slots;
778 } else {
779 this->matches[this->num_matches].num_components
780 = producer_var->type->component_slots();
781 }
782 this->matches[this->num_matches].producer_var = producer_var;
783 this->matches[this->num_matches].consumer_var = consumer_var;
784 this->num_matches++;
785 producer_var->is_unmatched_generic_inout = 0;
786 if (consumer_var)
787 consumer_var->is_unmatched_generic_inout = 0;
788 }
789
790
791 /**
792 * Choose locations for all of the variable matches that were previously
793 * passed to varying_matches::record().
794 */
795 unsigned
796 varying_matches::assign_locations()
797 {
798 /* Sort varying matches into an order that makes them easy to pack. */
799 qsort(this->matches, this->num_matches, sizeof(*this->matches),
800 &varying_matches::match_comparator);
801
802 unsigned generic_location = 0;
803
804 for (unsigned i = 0; i < this->num_matches; i++) {
805 /* Advance to the next slot if this varying has a different packing
806 * class than the previous one, and we're not already on a slot
807 * boundary.
808 */
809 if (i > 0 &&
810 this->matches[i - 1].packing_class
811 != this->matches[i].packing_class) {
812 generic_location = ALIGN(generic_location, 4);
813 }
814
815 this->matches[i].generic_location = generic_location;
816
817 generic_location += this->matches[i].num_components;
818 }
819
820 return (generic_location + 3) / 4;
821 }
822
823
824 /**
825 * Update the producer and consumer shaders to reflect the locations
826 * assignments that were made by varying_matches::assign_locations().
827 */
828 void
829 varying_matches::store_locations(unsigned producer_base,
830 unsigned consumer_base) const
831 {
832 for (unsigned i = 0; i < this->num_matches; i++) {
833 ir_variable *producer_var = this->matches[i].producer_var;
834 ir_variable *consumer_var = this->matches[i].consumer_var;
835 unsigned generic_location = this->matches[i].generic_location;
836 unsigned slot = generic_location / 4;
837 unsigned offset = generic_location % 4;
838
839 producer_var->location = producer_base + slot;
840 producer_var->location_frac = offset;
841 if (consumer_var) {
842 assert(consumer_var->location == -1);
843 consumer_var->location = consumer_base + slot;
844 consumer_var->location_frac = offset;
845 }
846 }
847 }
848
849
850 /**
851 * Compute the "packing class" of the given varying. This is an unsigned
852 * integer with the property that two variables in the same packing class can
853 * be safely backed into the same vec4.
854 */
855 unsigned
856 varying_matches::compute_packing_class(ir_variable *var)
857 {
858 /* Without help from the back-end, there is no way to pack together
859 * variables with different interpolation types, because
860 * lower_packed_varyings must choose exactly one interpolation type for
861 * each packed varying it creates.
862 *
863 * However, we can safely pack together floats, ints, and uints, because:
864 *
865 * - varyings of base type "int" and "uint" must use the "flat"
866 * interpolation type, which can only occur in GLSL 1.30 and above.
867 *
868 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
869 * can store flat floats as ints without losing any information (using
870 * the ir_unop_bitcast_* opcodes).
871 *
872 * Therefore, the packing class depends only on the interpolation type.
873 */
874 unsigned packing_class = var->centroid ? 1 : 0;
875 packing_class *= 4;
876 packing_class += var->interpolation;
877 return packing_class;
878 }
879
880
881 /**
882 * Compute the "packing order" of the given varying. This is a sort key we
883 * use to determine when to attempt to pack the given varying relative to
884 * other varyings in the same packing class.
885 */
886 varying_matches::packing_order_enum
887 varying_matches::compute_packing_order(ir_variable *var)
888 {
889 const glsl_type *element_type = var->type;
890
891 while (element_type->base_type == GLSL_TYPE_ARRAY) {
892 element_type = element_type->fields.array;
893 }
894
895 switch (element_type->component_slots() % 4) {
896 case 1: return PACKING_ORDER_SCALAR;
897 case 2: return PACKING_ORDER_VEC2;
898 case 3: return PACKING_ORDER_VEC3;
899 case 0: return PACKING_ORDER_VEC4;
900 default:
901 assert(!"Unexpected value of vector_elements");
902 return PACKING_ORDER_VEC4;
903 }
904 }
905
906
907 /**
908 * Comparison function passed to qsort() to sort varyings by packing_class and
909 * then by packing_order.
910 */
911 int
912 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
913 {
914 const match *x = (const match *) x_generic;
915 const match *y = (const match *) y_generic;
916
917 if (x->packing_class != y->packing_class)
918 return x->packing_class - y->packing_class;
919 return x->packing_order - y->packing_order;
920 }
921
922
923 /**
924 * Is the given variable a varying variable to be counted against the
925 * limit in ctx->Const.MaxVarying?
926 * This includes variables such as texcoords, colors and generic
927 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
928 */
929 static bool
930 is_varying_var(GLenum shaderType, const ir_variable *var)
931 {
932 /* Only fragment shaders will take a varying variable as an input */
933 if (shaderType == GL_FRAGMENT_SHADER &&
934 var->mode == ir_var_shader_in) {
935 switch (var->location) {
936 case VARYING_SLOT_POS:
937 case VARYING_SLOT_FACE:
938 case VARYING_SLOT_PNTC:
939 return false;
940 default:
941 return true;
942 }
943 }
944 return false;
945 }
946
947
948 /**
949 * Visitor class that generates tfeedback_candidate structs describing all
950 * possible targets of transform feedback.
951 *
952 * tfeedback_candidate structs are stored in the hash table
953 * tfeedback_candidates, which is passed to the constructor. This hash table
954 * maps varying names to instances of the tfeedback_candidate struct.
955 */
956 class tfeedback_candidate_generator : public program_resource_visitor
957 {
958 public:
959 tfeedback_candidate_generator(void *mem_ctx,
960 hash_table *tfeedback_candidates)
961 : mem_ctx(mem_ctx),
962 tfeedback_candidates(tfeedback_candidates),
963 toplevel_var(NULL),
964 varying_floats(0)
965 {
966 }
967
968 void process(ir_variable *var)
969 {
970 this->toplevel_var = var;
971 this->varying_floats = 0;
972 if (var->is_interface_instance())
973 program_resource_visitor::process(var->interface_type,
974 var->interface_type->name);
975 else
976 program_resource_visitor::process(var);
977 }
978
979 private:
980 virtual void visit_field(const glsl_type *type, const char *name,
981 bool row_major)
982 {
983 assert(!type->is_record());
984 assert(!(type->is_array() && type->fields.array->is_record()));
985 assert(!type->is_interface());
986 assert(!(type->is_array() && type->fields.array->is_interface()));
987
988 (void) row_major;
989
990 tfeedback_candidate *candidate
991 = rzalloc(this->mem_ctx, tfeedback_candidate);
992 candidate->toplevel_var = this->toplevel_var;
993 candidate->type = type;
994 candidate->offset = this->varying_floats;
995 hash_table_insert(this->tfeedback_candidates, candidate,
996 ralloc_strdup(this->mem_ctx, name));
997 this->varying_floats += type->component_slots();
998 }
999
1000 /**
1001 * Memory context used to allocate hash table keys and values.
1002 */
1003 void * const mem_ctx;
1004
1005 /**
1006 * Hash table in which tfeedback_candidate objects should be stored.
1007 */
1008 hash_table * const tfeedback_candidates;
1009
1010 /**
1011 * Pointer to the toplevel variable that is being traversed.
1012 */
1013 ir_variable *toplevel_var;
1014
1015 /**
1016 * Total number of varying floats that have been visited so far. This is
1017 * used to determine the offset to each varying within the toplevel
1018 * variable.
1019 */
1020 unsigned varying_floats;
1021 };
1022
1023
1024 /**
1025 * Assign locations for all variables that are produced in one pipeline stage
1026 * (the "producer") and consumed in the next stage (the "consumer").
1027 *
1028 * Variables produced by the producer may also be consumed by transform
1029 * feedback.
1030 *
1031 * \param num_tfeedback_decls is the number of declarations indicating
1032 * variables that may be consumed by transform feedback.
1033 *
1034 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1035 * representing the result of parsing the strings passed to
1036 * glTransformFeedbackVaryings(). assign_location() will be called for
1037 * each of these objects that matches one of the outputs of the
1038 * producer.
1039 *
1040 * \param gs_input_vertices: if \c consumer is a geometry shader, this is the
1041 * number of input vertices it accepts. Otherwise zero.
1042 *
1043 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1044 * be NULL. In this case, varying locations are assigned solely based on the
1045 * requirements of transform feedback.
1046 */
1047 bool
1048 assign_varying_locations(struct gl_context *ctx,
1049 void *mem_ctx,
1050 struct gl_shader_program *prog,
1051 gl_shader *producer, gl_shader *consumer,
1052 unsigned num_tfeedback_decls,
1053 tfeedback_decl *tfeedback_decls,
1054 unsigned gs_input_vertices)
1055 {
1056 const unsigned producer_base = VARYING_SLOT_VAR0;
1057 const unsigned consumer_base = VARYING_SLOT_VAR0;
1058 varying_matches matches(ctx->Const.DisableVaryingPacking,
1059 consumer && consumer->Type == GL_FRAGMENT_SHADER);
1060 hash_table *tfeedback_candidates
1061 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1062 hash_table *consumer_inputs
1063 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1064 hash_table *consumer_interface_inputs
1065 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1066
1067 /* Operate in a total of three passes.
1068 *
1069 * 1. Assign locations for any matching inputs and outputs.
1070 *
1071 * 2. Mark output variables in the producer that do not have locations as
1072 * not being outputs. This lets the optimizer eliminate them.
1073 *
1074 * 3. Mark input variables in the consumer that do not have locations as
1075 * not being inputs. This lets the optimizer eliminate them.
1076 */
1077
1078 if (consumer) {
1079 foreach_list(node, consumer->ir) {
1080 ir_variable *const input_var =
1081 ((ir_instruction *) node)->as_variable();
1082
1083 if ((input_var != NULL) && (input_var->mode == ir_var_shader_in)) {
1084 if (input_var->interface_type != NULL) {
1085 char *const iface_field_name =
1086 ralloc_asprintf(mem_ctx, "%s.%s",
1087 input_var->interface_type->name,
1088 input_var->name);
1089 hash_table_insert(consumer_interface_inputs, input_var,
1090 iface_field_name);
1091 } else {
1092 hash_table_insert(consumer_inputs, input_var,
1093 ralloc_strdup(mem_ctx, input_var->name));
1094 }
1095 }
1096 }
1097 }
1098
1099 foreach_list(node, producer->ir) {
1100 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1101
1102 if ((output_var == NULL) || (output_var->mode != ir_var_shader_out))
1103 continue;
1104
1105 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates);
1106 g.process(output_var);
1107
1108 ir_variable *input_var;
1109 if (output_var->interface_type != NULL) {
1110 char *const iface_field_name =
1111 ralloc_asprintf(mem_ctx, "%s.%s",
1112 output_var->interface_type->name,
1113 output_var->name);
1114 input_var =
1115 (ir_variable *) hash_table_find(consumer_interface_inputs,
1116 iface_field_name);
1117 } else {
1118 input_var =
1119 (ir_variable *) hash_table_find(consumer_inputs, output_var->name);
1120 }
1121
1122 if (input_var && input_var->mode != ir_var_shader_in)
1123 input_var = NULL;
1124
1125 if (input_var) {
1126 matches.record(output_var, input_var);
1127 }
1128 }
1129
1130 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1131 if (!tfeedback_decls[i].is_varying())
1132 continue;
1133
1134 const tfeedback_candidate *matched_candidate
1135 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
1136
1137 if (matched_candidate == NULL) {
1138 hash_table_dtor(tfeedback_candidates);
1139 hash_table_dtor(consumer_inputs);
1140 hash_table_dtor(consumer_interface_inputs);
1141 return false;
1142 }
1143
1144 if (matched_candidate->toplevel_var->is_unmatched_generic_inout)
1145 matches.record(matched_candidate->toplevel_var, NULL);
1146 }
1147
1148 const unsigned slots_used = matches.assign_locations();
1149 matches.store_locations(producer_base, consumer_base);
1150
1151 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1152 if (!tfeedback_decls[i].is_varying())
1153 continue;
1154
1155 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
1156 hash_table_dtor(tfeedback_candidates);
1157 hash_table_dtor(consumer_inputs);
1158 hash_table_dtor(consumer_interface_inputs);
1159 return false;
1160 }
1161 }
1162
1163 hash_table_dtor(tfeedback_candidates);
1164 hash_table_dtor(consumer_inputs);
1165 hash_table_dtor(consumer_interface_inputs);
1166
1167 if (ctx->Const.DisableVaryingPacking) {
1168 /* Transform feedback code assumes varyings are packed, so if the driver
1169 * has disabled varying packing, make sure it does not support transform
1170 * feedback.
1171 */
1172 assert(!ctx->Extensions.EXT_transform_feedback);
1173 } else {
1174 lower_packed_varyings(mem_ctx, producer_base, slots_used,
1175 ir_var_shader_out, 0, producer);
1176 if (consumer) {
1177 lower_packed_varyings(mem_ctx, consumer_base, slots_used,
1178 ir_var_shader_in, gs_input_vertices, consumer);
1179 }
1180 }
1181
1182 if (consumer) {
1183 foreach_list(node, consumer->ir) {
1184 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1185
1186 if (var && var->mode == ir_var_shader_in &&
1187 var->is_unmatched_generic_inout) {
1188 if (prog->Version <= 120) {
1189 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1190 *
1191 * Only those varying variables used (i.e. read) in
1192 * the fragment shader executable must be written to
1193 * by the vertex shader executable; declaring
1194 * superfluous varying variables in a vertex shader is
1195 * permissible.
1196 *
1197 * We interpret this text as meaning that the VS must
1198 * write the variable for the FS to read it. See
1199 * "glsl1-varying read but not written" in piglit.
1200 */
1201
1202 linker_error(prog, "%s shader varying %s not written "
1203 "by %s shader\n.",
1204 _mesa_glsl_shader_target_name(consumer->Type),
1205 var->name,
1206 _mesa_glsl_shader_target_name(producer->Type));
1207 }
1208
1209 /* An 'in' variable is only really a shader input if its
1210 * value is written by the previous stage.
1211 */
1212 var->mode = ir_var_auto;
1213 }
1214 }
1215 }
1216
1217 return true;
1218 }
1219
1220 bool
1221 check_against_varying_limit(struct gl_context *ctx,
1222 struct gl_shader_program *prog,
1223 gl_shader *consumer)
1224 {
1225 unsigned varying_vectors = 0;
1226
1227 foreach_list(node, consumer->ir) {
1228 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1229
1230 if (var && var->mode == ir_var_shader_in &&
1231 is_varying_var(consumer->Type, var)) {
1232 /* The packing rules used for vertex shader inputs are also
1233 * used for fragment shader inputs.
1234 */
1235 varying_vectors += var->type->count_attribute_slots();
1236 }
1237 }
1238
1239 if (ctx->API == API_OPENGLES2 || prog->IsES) {
1240 if (varying_vectors > ctx->Const.MaxVarying) {
1241 linker_error(prog, "shader uses too many varying vectors "
1242 "(%u > %u)\n",
1243 varying_vectors, ctx->Const.MaxVarying);
1244 return false;
1245 }
1246 } else {
1247 const unsigned float_components = varying_vectors * 4;
1248 if (float_components > ctx->Const.MaxVarying * 4) {
1249 linker_error(prog, "shader uses too many varying components "
1250 "(%u > %u)\n",
1251 float_components, ctx->Const.MaxVarying * 4);
1252 return false;
1253 }
1254 }
1255
1256 return true;
1257 }