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