34e3440d67d9f0745f56e6dd188e9631ceb31ca8
[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, bool consumer_is_fs);
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 const bool consumer_is_fs;
626 };
627
628
629 varying_matches::varying_matches(bool disable_varying_packing,
630 bool consumer_is_fs)
631 : disable_varying_packing(disable_varying_packing),
632 consumer_is_fs(consumer_is_fs)
633 {
634 /* Note: this initial capacity is rather arbitrarily chosen to be large
635 * enough for many cases without wasting an unreasonable amount of space.
636 * varying_matches::record() will resize the array if there are more than
637 * this number of varyings.
638 */
639 this->matches_capacity = 8;
640 this->matches = (match *)
641 malloc(sizeof(*this->matches) * this->matches_capacity);
642 this->num_matches = 0;
643 }
644
645
646 varying_matches::~varying_matches()
647 {
648 free(this->matches);
649 }
650
651
652 /**
653 * Record the given producer/consumer variable pair in the list of variables
654 * that should later be assigned locations.
655 *
656 * It is permissible for \c consumer_var to be NULL (this happens if a
657 * variable is output by the producer and consumed by transform feedback, but
658 * not consumed by the consumer).
659 *
660 * If \c producer_var has already been paired up with a consumer_var, or
661 * producer_var is part of fixed pipeline functionality (and hence already has
662 * a location assigned), this function has no effect.
663 *
664 * Note: as a side effect this function may change the interpolation type of
665 * \c producer_var, but only when the change couldn't possibly affect
666 * rendering.
667 */
668 void
669 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
670 {
671 if (!producer_var->is_unmatched_generic_inout) {
672 /* Either a location already exists for this variable (since it is part
673 * of fixed functionality), or it has already been recorded as part of a
674 * previous match.
675 */
676 return;
677 }
678
679 if ((consumer_var == NULL && producer_var->type->contains_integer()) ||
680 !consumer_is_fs) {
681 /* Since this varying is not being consumed by the fragment shader, its
682 * interpolation type varying cannot possibly affect rendering. Also,
683 * this variable is non-flat and is (or contains) an integer.
684 *
685 * lower_packed_varyings requires all integer varyings to flat,
686 * regardless of where they appear. We can trivially satisfy that
687 * requirement by changing the interpolation type to flat here.
688 */
689 producer_var->centroid = false;
690 producer_var->interpolation = INTERP_QUALIFIER_FLAT;
691
692 if (consumer_var) {
693 consumer_var->centroid = false;
694 consumer_var->interpolation = INTERP_QUALIFIER_FLAT;
695 }
696 }
697
698 if (this->num_matches == this->matches_capacity) {
699 this->matches_capacity *= 2;
700 this->matches = (match *)
701 realloc(this->matches,
702 sizeof(*this->matches) * this->matches_capacity);
703 }
704 this->matches[this->num_matches].packing_class
705 = this->compute_packing_class(producer_var);
706 this->matches[this->num_matches].packing_order
707 = this->compute_packing_order(producer_var);
708 if (this->disable_varying_packing) {
709 unsigned slots = producer_var->type->is_array()
710 ? (producer_var->type->length
711 * producer_var->type->fields.array->matrix_columns)
712 : producer_var->type->matrix_columns;
713 this->matches[this->num_matches].num_components = 4 * slots;
714 } else {
715 this->matches[this->num_matches].num_components
716 = producer_var->type->component_slots();
717 }
718 this->matches[this->num_matches].producer_var = producer_var;
719 this->matches[this->num_matches].consumer_var = consumer_var;
720 this->num_matches++;
721 producer_var->is_unmatched_generic_inout = 0;
722 if (consumer_var)
723 consumer_var->is_unmatched_generic_inout = 0;
724 }
725
726
727 /**
728 * Choose locations for all of the variable matches that were previously
729 * passed to varying_matches::record().
730 */
731 unsigned
732 varying_matches::assign_locations()
733 {
734 /* Sort varying matches into an order that makes them easy to pack. */
735 qsort(this->matches, this->num_matches, sizeof(*this->matches),
736 &varying_matches::match_comparator);
737
738 unsigned generic_location = 0;
739
740 for (unsigned i = 0; i < this->num_matches; i++) {
741 /* Advance to the next slot if this varying has a different packing
742 * class than the previous one, and we're not already on a slot
743 * boundary.
744 */
745 if (i > 0 &&
746 this->matches[i - 1].packing_class
747 != this->matches[i].packing_class) {
748 generic_location = ALIGN(generic_location, 4);
749 }
750
751 this->matches[i].generic_location = generic_location;
752
753 generic_location += this->matches[i].num_components;
754 }
755
756 return (generic_location + 3) / 4;
757 }
758
759
760 /**
761 * Update the producer and consumer shaders to reflect the locations
762 * assignments that were made by varying_matches::assign_locations().
763 */
764 void
765 varying_matches::store_locations(unsigned producer_base,
766 unsigned consumer_base) const
767 {
768 for (unsigned i = 0; i < this->num_matches; i++) {
769 ir_variable *producer_var = this->matches[i].producer_var;
770 ir_variable *consumer_var = this->matches[i].consumer_var;
771 unsigned generic_location = this->matches[i].generic_location;
772 unsigned slot = generic_location / 4;
773 unsigned offset = generic_location % 4;
774
775 producer_var->location = producer_base + slot;
776 producer_var->location_frac = offset;
777 if (consumer_var) {
778 assert(consumer_var->location == -1);
779 consumer_var->location = consumer_base + slot;
780 consumer_var->location_frac = offset;
781 }
782 }
783 }
784
785
786 /**
787 * Compute the "packing class" of the given varying. This is an unsigned
788 * integer with the property that two variables in the same packing class can
789 * be safely backed into the same vec4.
790 */
791 unsigned
792 varying_matches::compute_packing_class(ir_variable *var)
793 {
794 /* Without help from the back-end, there is no way to pack together
795 * variables with different interpolation types, because
796 * lower_packed_varyings must choose exactly one interpolation type for
797 * each packed varying it creates.
798 *
799 * However, we can safely pack together floats, ints, and uints, because:
800 *
801 * - varyings of base type "int" and "uint" must use the "flat"
802 * interpolation type, which can only occur in GLSL 1.30 and above.
803 *
804 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
805 * can store flat floats as ints without losing any information (using
806 * the ir_unop_bitcast_* opcodes).
807 *
808 * Therefore, the packing class depends only on the interpolation type.
809 */
810 unsigned packing_class = var->centroid ? 1 : 0;
811 packing_class *= 4;
812 packing_class += var->interpolation;
813 return packing_class;
814 }
815
816
817 /**
818 * Compute the "packing order" of the given varying. This is a sort key we
819 * use to determine when to attempt to pack the given varying relative to
820 * other varyings in the same packing class.
821 */
822 varying_matches::packing_order_enum
823 varying_matches::compute_packing_order(ir_variable *var)
824 {
825 const glsl_type *element_type = var->type;
826
827 while (element_type->base_type == GLSL_TYPE_ARRAY) {
828 element_type = element_type->fields.array;
829 }
830
831 switch (element_type->component_slots() % 4) {
832 case 1: return PACKING_ORDER_SCALAR;
833 case 2: return PACKING_ORDER_VEC2;
834 case 3: return PACKING_ORDER_VEC3;
835 case 0: return PACKING_ORDER_VEC4;
836 default:
837 assert(!"Unexpected value of vector_elements");
838 return PACKING_ORDER_VEC4;
839 }
840 }
841
842
843 /**
844 * Comparison function passed to qsort() to sort varyings by packing_class and
845 * then by packing_order.
846 */
847 int
848 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
849 {
850 const match *x = (const match *) x_generic;
851 const match *y = (const match *) y_generic;
852
853 if (x->packing_class != y->packing_class)
854 return x->packing_class - y->packing_class;
855 return x->packing_order - y->packing_order;
856 }
857
858
859 /**
860 * Is the given variable a varying variable to be counted against the
861 * limit in ctx->Const.MaxVarying?
862 * This includes variables such as texcoords, colors and generic
863 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
864 */
865 static bool
866 is_varying_var(GLenum shaderType, const ir_variable *var)
867 {
868 /* Only fragment shaders will take a varying variable as an input */
869 if (shaderType == GL_FRAGMENT_SHADER &&
870 var->mode == ir_var_shader_in) {
871 switch (var->location) {
872 case VARYING_SLOT_POS:
873 case VARYING_SLOT_FACE:
874 case VARYING_SLOT_PNTC:
875 return false;
876 default:
877 return true;
878 }
879 }
880 return false;
881 }
882
883
884 /**
885 * Visitor class that generates tfeedback_candidate structs describing all
886 * possible targets of transform feedback.
887 *
888 * tfeedback_candidate structs are stored in the hash table
889 * tfeedback_candidates, which is passed to the constructor. This hash table
890 * maps varying names to instances of the tfeedback_candidate struct.
891 */
892 class tfeedback_candidate_generator : public program_resource_visitor
893 {
894 public:
895 tfeedback_candidate_generator(void *mem_ctx,
896 hash_table *tfeedback_candidates)
897 : mem_ctx(mem_ctx),
898 tfeedback_candidates(tfeedback_candidates),
899 toplevel_var(NULL),
900 varying_floats(0)
901 {
902 }
903
904 void process(ir_variable *var)
905 {
906 this->toplevel_var = var;
907 this->varying_floats = 0;
908 if (var->is_interface_instance())
909 program_resource_visitor::process(var->interface_type,
910 var->interface_type->name);
911 else
912 program_resource_visitor::process(var);
913 }
914
915 private:
916 virtual void visit_field(const glsl_type *type, const char *name,
917 bool row_major)
918 {
919 assert(!type->is_record());
920 assert(!(type->is_array() && type->fields.array->is_record()));
921 assert(!type->is_interface());
922 assert(!(type->is_array() && type->fields.array->is_interface()));
923
924 (void) row_major;
925
926 tfeedback_candidate *candidate
927 = rzalloc(this->mem_ctx, tfeedback_candidate);
928 candidate->toplevel_var = this->toplevel_var;
929 candidate->type = type;
930 candidate->offset = this->varying_floats;
931 hash_table_insert(this->tfeedback_candidates, candidate,
932 ralloc_strdup(this->mem_ctx, name));
933 this->varying_floats += type->component_slots();
934 }
935
936 /**
937 * Memory context used to allocate hash table keys and values.
938 */
939 void * const mem_ctx;
940
941 /**
942 * Hash table in which tfeedback_candidate objects should be stored.
943 */
944 hash_table * const tfeedback_candidates;
945
946 /**
947 * Pointer to the toplevel variable that is being traversed.
948 */
949 ir_variable *toplevel_var;
950
951 /**
952 * Total number of varying floats that have been visited so far. This is
953 * used to determine the offset to each varying within the toplevel
954 * variable.
955 */
956 unsigned varying_floats;
957 };
958
959
960 /**
961 * Assign locations for all variables that are produced in one pipeline stage
962 * (the "producer") and consumed in the next stage (the "consumer").
963 *
964 * Variables produced by the producer may also be consumed by transform
965 * feedback.
966 *
967 * \param num_tfeedback_decls is the number of declarations indicating
968 * variables that may be consumed by transform feedback.
969 *
970 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
971 * representing the result of parsing the strings passed to
972 * glTransformFeedbackVaryings(). assign_location() will be called for
973 * each of these objects that matches one of the outputs of the
974 * producer.
975 *
976 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
977 * be NULL. In this case, varying locations are assigned solely based on the
978 * requirements of transform feedback.
979 */
980 bool
981 assign_varying_locations(struct gl_context *ctx,
982 void *mem_ctx,
983 struct gl_shader_program *prog,
984 gl_shader *producer, gl_shader *consumer,
985 unsigned num_tfeedback_decls,
986 tfeedback_decl *tfeedback_decls)
987 {
988 const unsigned producer_base = VARYING_SLOT_VAR0;
989 const unsigned consumer_base = VARYING_SLOT_VAR0;
990 varying_matches matches(ctx->Const.DisableVaryingPacking,
991 consumer && consumer->Type == GL_FRAGMENT_SHADER);
992 hash_table *tfeedback_candidates
993 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
994 hash_table *consumer_inputs
995 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
996 hash_table *consumer_interface_inputs
997 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
998
999 /* Operate in a total of three passes.
1000 *
1001 * 1. Assign locations for any matching inputs and outputs.
1002 *
1003 * 2. Mark output variables in the producer that do not have locations as
1004 * not being outputs. This lets the optimizer eliminate them.
1005 *
1006 * 3. Mark input variables in the consumer that do not have locations as
1007 * not being inputs. This lets the optimizer eliminate them.
1008 */
1009
1010 if (consumer) {
1011 foreach_list(node, consumer->ir) {
1012 ir_variable *const input_var =
1013 ((ir_instruction *) node)->as_variable();
1014
1015 if ((input_var != NULL) && (input_var->mode == ir_var_shader_in)) {
1016 if (input_var->interface_type != NULL) {
1017 char *const iface_field_name =
1018 ralloc_asprintf(mem_ctx, "%s.%s",
1019 input_var->interface_type->name,
1020 input_var->name);
1021 hash_table_insert(consumer_interface_inputs, input_var,
1022 iface_field_name);
1023 } else {
1024 hash_table_insert(consumer_inputs, input_var,
1025 ralloc_strdup(mem_ctx, input_var->name));
1026 }
1027 }
1028 }
1029 }
1030
1031 foreach_list(node, producer->ir) {
1032 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1033
1034 if ((output_var == NULL) || (output_var->mode != ir_var_shader_out))
1035 continue;
1036
1037 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates);
1038 g.process(output_var);
1039
1040 ir_variable *input_var;
1041 if (output_var->interface_type != NULL) {
1042 char *const iface_field_name =
1043 ralloc_asprintf(mem_ctx, "%s.%s",
1044 output_var->interface_type->name,
1045 output_var->name);
1046 input_var =
1047 (ir_variable *) hash_table_find(consumer_interface_inputs,
1048 iface_field_name);
1049 } else {
1050 input_var =
1051 (ir_variable *) hash_table_find(consumer_inputs, output_var->name);
1052 }
1053
1054 if (input_var && input_var->mode != ir_var_shader_in)
1055 input_var = NULL;
1056
1057 if (input_var) {
1058 matches.record(output_var, input_var);
1059 }
1060 }
1061
1062 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1063 if (!tfeedback_decls[i].is_varying())
1064 continue;
1065
1066 const tfeedback_candidate *matched_candidate
1067 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
1068
1069 if (matched_candidate == NULL) {
1070 hash_table_dtor(tfeedback_candidates);
1071 hash_table_dtor(consumer_inputs);
1072 hash_table_dtor(consumer_interface_inputs);
1073 return false;
1074 }
1075
1076 if (matched_candidate->toplevel_var->is_unmatched_generic_inout)
1077 matches.record(matched_candidate->toplevel_var, NULL);
1078 }
1079
1080 const unsigned slots_used = matches.assign_locations();
1081 matches.store_locations(producer_base, consumer_base);
1082
1083 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1084 if (!tfeedback_decls[i].is_varying())
1085 continue;
1086
1087 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
1088 hash_table_dtor(tfeedback_candidates);
1089 hash_table_dtor(consumer_inputs);
1090 hash_table_dtor(consumer_interface_inputs);
1091 return false;
1092 }
1093 }
1094
1095 hash_table_dtor(tfeedback_candidates);
1096 hash_table_dtor(consumer_inputs);
1097 hash_table_dtor(consumer_interface_inputs);
1098
1099 if (ctx->Const.DisableVaryingPacking) {
1100 /* Transform feedback code assumes varyings are packed, so if the driver
1101 * has disabled varying packing, make sure it does not support transform
1102 * feedback.
1103 */
1104 assert(!ctx->Extensions.EXT_transform_feedback);
1105 } else {
1106 lower_packed_varyings(mem_ctx, producer_base, slots_used,
1107 ir_var_shader_out, producer);
1108 if (consumer) {
1109 lower_packed_varyings(mem_ctx, consumer_base, slots_used,
1110 ir_var_shader_in, consumer);
1111 }
1112 }
1113
1114 unsigned varying_vectors = 0;
1115
1116 if (consumer) {
1117 foreach_list(node, consumer->ir) {
1118 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1119
1120 if ((var == NULL) || (var->mode != ir_var_shader_in))
1121 continue;
1122
1123 if (var->is_unmatched_generic_inout) {
1124 if (prog->Version <= 120) {
1125 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1126 *
1127 * Only those varying variables used (i.e. read) in
1128 * the fragment shader executable must be written to
1129 * by the vertex shader executable; declaring
1130 * superfluous varying variables in a vertex shader is
1131 * permissible.
1132 *
1133 * We interpret this text as meaning that the VS must
1134 * write the variable for the FS to read it. See
1135 * "glsl1-varying read but not written" in piglit.
1136 */
1137
1138 linker_error(prog, "fragment shader varying %s not written "
1139 "by vertex shader\n.", var->name);
1140 }
1141
1142 /* An 'in' variable is only really a shader input if its
1143 * value is written by the previous stage.
1144 */
1145 var->mode = ir_var_auto;
1146 } else if (is_varying_var(consumer->Type, var)) {
1147 /* The packing rules are used for vertex shader inputs are also
1148 * used for fragment shader inputs.
1149 */
1150 varying_vectors += count_attribute_slots(var->type);
1151 }
1152 }
1153 }
1154
1155 if (ctx->API == API_OPENGLES2 || prog->IsES) {
1156 if (varying_vectors > ctx->Const.MaxVarying) {
1157 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1158 linker_warning(prog, "shader uses too many varying vectors "
1159 "(%u > %u), but the driver will try to optimize "
1160 "them out; this is non-portable out-of-spec "
1161 "behavior\n",
1162 varying_vectors, ctx->Const.MaxVarying);
1163 } else {
1164 linker_error(prog, "shader uses too many varying vectors "
1165 "(%u > %u)\n",
1166 varying_vectors, ctx->Const.MaxVarying);
1167 return false;
1168 }
1169 }
1170 } else {
1171 const unsigned float_components = varying_vectors * 4;
1172 if (float_components > ctx->Const.MaxVarying * 4) {
1173 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1174 linker_warning(prog, "shader uses too many varying components "
1175 "(%u > %u), but the driver will try to optimize "
1176 "them out; this is non-portable out-of-spec "
1177 "behavior\n",
1178 float_components, ctx->Const.MaxVarying * 4);
1179 } else {
1180 linker_error(prog, "shader uses too many varying components "
1181 "(%u > %u)\n",
1182 float_components, ctx->Const.MaxVarying * 4);
1183 return false;
1184 }
1185 }
1186 }
1187
1188 return true;
1189 }