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