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