linker: Don't dynamically allocate slots for linked shaders
[mesa.git] / src / glsl / linker.cpp
1 /*
2 * Copyright © 2010 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 linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
66 #include <cstdlib>
67 #include <cstdio>
68 #include <cstdarg>
69
70 extern "C" {
71 #include <talloc.h>
72 }
73
74 #include "main/mtypes.h"
75 #include "glsl_symbol_table.h"
76 #include "glsl_parser_extras.h"
77 #include "ir.h"
78 #include "ir_optimization.h"
79 #include "program.h"
80 extern "C" {
81 #include "hash_table.h"
82 }
83
84 /**
85 * Visitor that determines whether or not a variable is ever written.
86 */
87 class find_assignment_visitor : public ir_hierarchical_visitor {
88 public:
89 find_assignment_visitor(const char *name)
90 : name(name), found(false)
91 {
92 /* empty */
93 }
94
95 virtual ir_visitor_status visit_enter(ir_assignment *ir)
96 {
97 ir_variable *const var = ir->lhs->variable_referenced();
98
99 if (strcmp(name, var->name) == 0) {
100 found = true;
101 return visit_stop;
102 }
103
104 return visit_continue_with_parent;
105 }
106
107 bool variable_found()
108 {
109 return found;
110 }
111
112 private:
113 const char *name; /**< Find writes to a variable with this name. */
114 bool found; /**< Was a write to the variable found? */
115 };
116
117
118 void
119 linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
120 {
121 va_list ap;
122
123 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
124 va_start(ap, fmt);
125 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
126 va_end(ap);
127 }
128
129
130 void
131 invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
132 int generic_base)
133 {
134 foreach_list(node, sh->ir) {
135 ir_variable *const var = ((ir_instruction *) node)->as_variable();
136
137 if ((var == NULL) || (var->mode != (unsigned) mode))
138 continue;
139
140 /* Only assign locations for generic attributes / varyings / etc.
141 */
142 if (var->location >= generic_base)
143 var->location = -1;
144 }
145 }
146
147
148 /**
149 * Determine the number of attribute slots required for a particular type
150 *
151 * This code is here because it implements the language rules of a specific
152 * GLSL version. Since it's a property of the language and not a property of
153 * types in general, it doesn't really belong in glsl_type.
154 */
155 unsigned
156 count_attribute_slots(const glsl_type *t)
157 {
158 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
159 *
160 * "A scalar input counts the same amount against this limit as a vec4,
161 * so applications may want to consider packing groups of four
162 * unrelated float inputs together into a vector to better utilize the
163 * capabilities of the underlying hardware. A matrix input will use up
164 * multiple locations. The number of locations used will equal the
165 * number of columns in the matrix."
166 *
167 * The spec does not explicitly say how arrays are counted. However, it
168 * should be safe to assume the total number of slots consumed by an array
169 * is the number of entries in the array multiplied by the number of slots
170 * consumed by a single element of the array.
171 */
172
173 if (t->is_array())
174 return t->array_size() * count_attribute_slots(t->element_type());
175
176 if (t->is_matrix())
177 return t->matrix_columns;
178
179 return 1;
180 }
181
182
183 /**
184 * Verify that a vertex shader executable meets all semantic requirements
185 *
186 * \param shader Vertex shader executable to be verified
187 */
188 bool
189 validate_vertex_shader_executable(struct gl_shader_program *prog,
190 struct gl_shader *shader)
191 {
192 if (shader == NULL)
193 return true;
194
195 if (!shader->symbols->get_function("main")) {
196 linker_error_printf(prog, "vertex shader lacks `main'\n");
197 return false;
198 }
199
200 find_assignment_visitor find("gl_Position");
201 find.run(shader->ir);
202 if (!find.variable_found()) {
203 linker_error_printf(prog,
204 "vertex shader does not write to `gl_Position'\n");
205 return false;
206 }
207
208 return true;
209 }
210
211
212 /**
213 * Verify that a fragment shader executable meets all semantic requirements
214 *
215 * \param shader Fragment shader executable to be verified
216 */
217 bool
218 validate_fragment_shader_executable(struct gl_shader_program *prog,
219 struct gl_shader *shader)
220 {
221 if (shader == NULL)
222 return true;
223
224 if (!shader->symbols->get_function("main")) {
225 linker_error_printf(prog, "fragment shader lacks `main'\n");
226 return false;
227 }
228
229 find_assignment_visitor frag_color("gl_FragColor");
230 find_assignment_visitor frag_data("gl_FragData");
231
232 frag_color.run(shader->ir);
233 frag_data.run(shader->ir);
234
235 if (!frag_color.variable_found() && !frag_data.variable_found()) {
236 linker_error_printf(prog, "fragment shader does not write to "
237 "`gl_FragColor' or `gl_FragData'\n");
238 return false;
239 }
240
241 if (frag_color.variable_found() && frag_data.variable_found()) {
242 linker_error_printf(prog, "fragment shader writes to both "
243 "`gl_FragColor' and `gl_FragData'\n");
244 return false;
245 }
246
247 return true;
248 }
249
250
251 /**
252 * Perform validation of uniforms used across multiple shader stages
253 */
254 bool
255 cross_validate_uniforms(struct gl_shader_program *prog)
256 {
257 /* Examine all of the uniforms in all of the shaders and cross validate
258 * them.
259 */
260 glsl_symbol_table uniforms;
261 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
262 foreach_list(node, prog->_LinkedShaders[i]->ir) {
263 ir_variable *const var = ((ir_instruction *) node)->as_variable();
264
265 if ((var == NULL) || (var->mode != ir_var_uniform))
266 continue;
267
268 /* If a uniform with this name has already been seen, verify that the
269 * new instance has the same type. In addition, if the uniforms have
270 * initializers, the values of the initializers must be the same.
271 */
272 ir_variable *const existing = uniforms.get_variable(var->name);
273 if (existing != NULL) {
274 if (var->type != existing->type) {
275 linker_error_printf(prog, "uniform `%s' declared as type "
276 "`%s' and type `%s'\n",
277 var->name, var->type->name,
278 existing->type->name);
279 return false;
280 }
281
282 if (var->constant_value != NULL) {
283 if (existing->constant_value != NULL) {
284 if (!var->constant_value->has_value(existing->constant_value)) {
285 linker_error_printf(prog, "initializers for uniform "
286 "`%s' have differing values\n",
287 var->name);
288 return false;
289 }
290 } else
291 /* If the first-seen instance of a particular uniform did not
292 * have an initializer but a later instance does, copy the
293 * initializer to the version stored in the symbol table.
294 */
295 existing->constant_value =
296 (ir_constant *)var->constant_value->clone(NULL);
297 }
298 } else
299 uniforms.add_variable(var->name, var);
300 }
301 }
302
303 return true;
304 }
305
306
307 /**
308 * Validate that outputs from one stage match inputs of another
309 */
310 bool
311 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
312 gl_shader *producer, gl_shader *consumer)
313 {
314 glsl_symbol_table parameters;
315 /* FINISHME: Figure these out dynamically. */
316 const char *const producer_stage = "vertex";
317 const char *const consumer_stage = "fragment";
318
319 /* Find all shader outputs in the "producer" stage.
320 */
321 foreach_list(node, producer->ir) {
322 ir_variable *const var = ((ir_instruction *) node)->as_variable();
323
324 /* FINISHME: For geometry shaders, this should also look for inout
325 * FINISHME: variables.
326 */
327 if ((var == NULL) || (var->mode != ir_var_out))
328 continue;
329
330 parameters.add_variable(var->name, var);
331 }
332
333
334 /* Find all shader inputs in the "consumer" stage. Any variables that have
335 * matching outputs already in the symbol table must have the same type and
336 * qualifiers.
337 */
338 foreach_list(node, consumer->ir) {
339 ir_variable *const input = ((ir_instruction *) node)->as_variable();
340
341 /* FINISHME: For geometry shaders, this should also look for inout
342 * FINISHME: variables.
343 */
344 if ((input == NULL) || (input->mode != ir_var_in))
345 continue;
346
347 ir_variable *const output = parameters.get_variable(input->name);
348 if (output != NULL) {
349 /* Check that the types match between stages.
350 */
351 if (input->type != output->type) {
352 linker_error_printf(prog,
353 "%s shader output `%s' delcared as "
354 "type `%s', but %s shader input declared "
355 "as type `%s'\n",
356 producer_stage, output->name,
357 output->type->name,
358 consumer_stage, input->type->name);
359 return false;
360 }
361
362 /* Check that all of the qualifiers match between stages.
363 */
364 if (input->centroid != output->centroid) {
365 linker_error_printf(prog,
366 "%s shader output `%s' %s centroid qualifier, "
367 "but %s shader input %s centroid qualifier\n",
368 producer_stage,
369 output->name,
370 (output->centroid) ? "has" : "lacks",
371 consumer_stage,
372 (input->centroid) ? "has" : "lacks");
373 return false;
374 }
375
376 if (input->invariant != output->invariant) {
377 linker_error_printf(prog,
378 "%s shader output `%s' %s invariant qualifier, "
379 "but %s shader input %s invariant qualifier\n",
380 producer_stage,
381 output->name,
382 (output->invariant) ? "has" : "lacks",
383 consumer_stage,
384 (input->invariant) ? "has" : "lacks");
385 return false;
386 }
387
388 if (input->interpolation != output->interpolation) {
389 linker_error_printf(prog,
390 "%s shader output `%s' specifies %s "
391 "interpolation qualifier, "
392 "but %s shader input specifies %s "
393 "interpolation qualifier\n",
394 producer_stage,
395 output->name,
396 output->interpolation_string(),
397 consumer_stage,
398 input->interpolation_string());
399 return false;
400 }
401 }
402 }
403
404 return true;
405 }
406
407
408 struct uniform_node {
409 exec_node link;
410 struct gl_uniform *u;
411 unsigned slots;
412 };
413
414 void
415 assign_uniform_locations(struct gl_shader_program *prog)
416 {
417 /* */
418 exec_list uniforms;
419 unsigned total_uniforms = 0;
420 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
421 hash_table_string_compare);
422
423 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
424 unsigned next_position = 0;
425
426 foreach_list(node, prog->_LinkedShaders[i]->ir) {
427 ir_variable *const var = ((ir_instruction *) node)->as_variable();
428
429 if ((var == NULL) || (var->mode != ir_var_uniform))
430 continue;
431
432 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
433 assert(vec4_slots != 0);
434
435 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
436 if (n == NULL) {
437 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
438 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
439 n->slots = vec4_slots;
440
441 n->u[0].Name = strdup(var->name);
442 for (unsigned j = 1; j < vec4_slots; j++)
443 n->u[j].Name = n->u[0].Name;
444
445 hash_table_insert(ht, n, n->u[0].Name);
446 uniforms.push_tail(& n->link);
447 total_uniforms += vec4_slots;
448 }
449
450 if (var->constant_value != NULL)
451 for (unsigned j = 0; j < vec4_slots; j++)
452 n->u[j].Initialized = true;
453
454 var->location = next_position;
455
456 for (unsigned j = 0; j < vec4_slots; j++) {
457 switch (prog->_LinkedShaders[i]->Type) {
458 case GL_VERTEX_SHADER:
459 n->u[j].VertPos = next_position;
460 break;
461 case GL_FRAGMENT_SHADER:
462 n->u[j].FragPos = next_position;
463 break;
464 case GL_GEOMETRY_SHADER:
465 /* FINISHME: Support geometry shaders. */
466 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
467 break;
468 }
469
470 next_position++;
471 }
472 }
473 }
474
475 gl_uniform_list *ul = (gl_uniform_list *)
476 calloc(1, sizeof(gl_uniform_list));
477
478 ul->Size = total_uniforms;
479 ul->NumUniforms = total_uniforms;
480 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
481
482 unsigned idx = 0;
483 uniform_node *next;
484 for (uniform_node *node = (uniform_node *) uniforms.head
485 ; node->link.next != NULL
486 ; node = next) {
487 next = (uniform_node *) node->link.next;
488
489 node->link.remove();
490 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
491 idx += node->slots;
492
493 free(node->u);
494 free(node);
495 }
496
497 hash_table_dtor(ht);
498
499 prog->Uniforms = ul;
500 }
501
502
503 /**
504 * Find a contiguous set of available bits in a bitmask
505 *
506 * \param used_mask Bits representing used (1) and unused (0) locations
507 * \param needed_count Number of contiguous bits needed.
508 *
509 * \return
510 * Base location of the available bits on success or -1 on failure.
511 */
512 int
513 find_available_slots(unsigned used_mask, unsigned needed_count)
514 {
515 unsigned needed_mask = (1 << needed_count) - 1;
516 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
517
518 /* The comparison to 32 is redundant, but without it GCC emits "warning:
519 * cannot optimize possibly infinite loops" for the loop below.
520 */
521 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
522 return -1;
523
524 for (int i = 0; i <= max_bit_to_test; i++) {
525 if ((needed_mask & ~used_mask) == needed_mask)
526 return i;
527
528 needed_mask <<= 1;
529 }
530
531 return -1;
532 }
533
534
535 bool
536 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
537 {
538 /* Mark invalid attribute locations as being used.
539 */
540 unsigned used_locations = (max_attribute_index >= 32)
541 ? ~0 : ~((1 << max_attribute_index) - 1);
542
543 gl_shader *const sh = prog->_LinkedShaders[0];
544 assert(sh->Type == GL_VERTEX_SHADER);
545
546 /* Operate in a total of four passes.
547 *
548 * 1. Invalidate the location assignments for all vertex shader inputs.
549 *
550 * 2. Assign locations for inputs that have user-defined (via
551 * glBindVertexAttribLocation) locatoins.
552 *
553 * 3. Sort the attributes without assigned locations by number of slots
554 * required in decreasing order. Fragmentation caused by attribute
555 * locations assigned by the application may prevent large attributes
556 * from having enough contiguous space.
557 *
558 * 4. Assign locations to any inputs without assigned locations.
559 */
560
561 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
562
563 if (prog->Attributes != NULL) {
564 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
565 ir_variable *const var =
566 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
567
568 /* Note: attributes that occupy multiple slots, such as arrays or
569 * matrices, may appear in the attrib array multiple times.
570 */
571 if ((var == NULL) || (var->location != -1))
572 continue;
573
574 /* From page 61 of the OpenGL 4.0 spec:
575 *
576 * "LinkProgram will fail if the attribute bindings assigned by
577 * BindAttribLocation do not leave not enough space to assign a
578 * location for an active matrix attribute or an active attribute
579 * array, both of which require multiple contiguous generic
580 * attributes."
581 *
582 * Previous versions of the spec contain similar language but omit the
583 * bit about attribute arrays.
584 *
585 * Page 61 of the OpenGL 4.0 spec also says:
586 *
587 * "It is possible for an application to bind more than one
588 * attribute name to the same location. This is referred to as
589 * aliasing. This will only work if only one of the aliased
590 * attributes is active in the executable program, or if no path
591 * through the shader consumes more than one attribute of a set
592 * of attributes aliased to the same location. A link error can
593 * occur if the linker determines that every path through the
594 * shader consumes multiple aliased attributes, but
595 * implementations are not required to generate an error in this
596 * case."
597 *
598 * These two paragraphs are either somewhat contradictory, or I don't
599 * fully understand one or both of them.
600 */
601 /* FINISHME: The code as currently written does not support attribute
602 * FINISHME: location aliasing (see comment above).
603 */
604 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
605 const unsigned slots = count_attribute_slots(var->type);
606
607 /* Mask representing the contiguous slots that will be used by this
608 * attribute.
609 */
610 const unsigned use_mask = (1 << slots) - 1;
611
612 /* Generate a link error if the set of bits requested for this
613 * attribute overlaps any previously allocated bits.
614 */
615 if ((~(use_mask << attr) & used_locations) != used_locations) {
616 linker_error_printf(prog,
617 "insufficient contiguous attribute locations "
618 "available for vertex shader input `%s'",
619 var->name);
620 return false;
621 }
622
623 var->location = VERT_ATTRIB_GENERIC0 + attr;
624 used_locations |= (use_mask << attr);
625 }
626 }
627
628 /* Temporary storage for the set of attributes that need locations assigned.
629 */
630 struct temp_attr {
631 unsigned slots;
632 ir_variable *var;
633
634 /* Used below in the call to qsort. */
635 static int compare(const void *a, const void *b)
636 {
637 const temp_attr *const l = (const temp_attr *) a;
638 const temp_attr *const r = (const temp_attr *) b;
639
640 /* Reversed because we want a descending order sort below. */
641 return r->slots - l->slots;
642 }
643 } to_assign[16];
644
645 unsigned num_attr = 0;
646
647 foreach_list(node, sh->ir) {
648 ir_variable *const var = ((ir_instruction *) node)->as_variable();
649
650 if ((var == NULL) || (var->mode != ir_var_in))
651 continue;
652
653 /* The location was explicitly assigned, nothing to do here.
654 */
655 if (var->location != -1)
656 continue;
657
658 to_assign[num_attr].slots = count_attribute_slots(var->type);
659 to_assign[num_attr].var = var;
660 num_attr++;
661 }
662
663 /* If all of the attributes were assigned locations by the application (or
664 * are built-in attributes with fixed locations), return early. This should
665 * be the common case.
666 */
667 if (num_attr == 0)
668 return true;
669
670 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
671
672 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
673 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
674 * to prevent it from being automatically allocated below.
675 */
676 used_locations |= VERT_BIT_GENERIC0;
677
678 for (unsigned i = 0; i < num_attr; i++) {
679 /* Mask representing the contiguous slots that will be used by this
680 * attribute.
681 */
682 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
683
684 int location = find_available_slots(used_locations, to_assign[i].slots);
685
686 if (location < 0) {
687 linker_error_printf(prog,
688 "insufficient contiguous attribute locations "
689 "available for vertex shader input `%s'",
690 to_assign[i].var->name);
691 return false;
692 }
693
694 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
695 used_locations |= (use_mask << location);
696 }
697
698 return true;
699 }
700
701
702 void
703 assign_varying_locations(gl_shader *producer, gl_shader *consumer)
704 {
705 /* FINISHME: Set dynamically when geometry shader support is added. */
706 unsigned output_index = VERT_RESULT_VAR0;
707 unsigned input_index = FRAG_ATTRIB_VAR0;
708
709 /* Operate in a total of three passes.
710 *
711 * 1. Assign locations for any matching inputs and outputs.
712 *
713 * 2. Mark output variables in the producer that do not have locations as
714 * not being outputs. This lets the optimizer eliminate them.
715 *
716 * 3. Mark input variables in the consumer that do not have locations as
717 * not being inputs. This lets the optimizer eliminate them.
718 */
719
720 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
721 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
722
723 foreach_list(node, producer->ir) {
724 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
725
726 if ((output_var == NULL) || (output_var->mode != ir_var_out)
727 || (output_var->location != -1))
728 continue;
729
730 ir_variable *const input_var =
731 consumer->symbols->get_variable(output_var->name);
732
733 if ((input_var == NULL) || (input_var->mode != ir_var_in))
734 continue;
735
736 assert(input_var->location == -1);
737
738 /* FINISHME: Location assignment will need some changes when arrays,
739 * FINISHME: matrices, and structures are allowed as shader inputs /
740 * FINISHME: outputs.
741 */
742 output_var->location = output_index;
743 input_var->location = input_index;
744
745 output_index++;
746 input_index++;
747 }
748
749 foreach_list(node, producer->ir) {
750 ir_variable *const var = ((ir_instruction *) node)->as_variable();
751
752 if ((var == NULL) || (var->mode != ir_var_out))
753 continue;
754
755 /* An 'out' variable is only really a shader output if its value is read
756 * by the following stage.
757 */
758 var->shader_out = (var->location != -1);
759 }
760
761 foreach_list(node, consumer->ir) {
762 ir_variable *const var = ((ir_instruction *) node)->as_variable();
763
764 if ((var == NULL) || (var->mode != ir_var_in))
765 continue;
766
767 /* An 'in' variable is only really a shader input if its value is written
768 * by the previous stage.
769 */
770 var->shader_in = (var->location != -1);
771 }
772 }
773
774
775 void
776 link_shaders(struct gl_shader_program *prog)
777 {
778 prog->LinkStatus = false;
779 prog->Validated = false;
780 prog->_Used = false;
781
782 if (prog->InfoLog != NULL)
783 talloc_free(prog->InfoLog);
784
785 prog->InfoLog = talloc_strdup(NULL, "");
786
787 /* Separate the shaders into groups based on their type.
788 */
789 struct gl_shader **vert_shader_list;
790 unsigned num_vert_shaders = 0;
791 struct gl_shader **frag_shader_list;
792 unsigned num_frag_shaders = 0;
793
794 vert_shader_list = (struct gl_shader **)
795 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
796 frag_shader_list = &vert_shader_list[prog->NumShaders];
797
798 for (unsigned i = 0; i < prog->NumShaders; i++) {
799 switch (prog->Shaders[i]->Type) {
800 case GL_VERTEX_SHADER:
801 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
802 num_vert_shaders++;
803 break;
804 case GL_FRAGMENT_SHADER:
805 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
806 num_frag_shaders++;
807 break;
808 case GL_GEOMETRY_SHADER:
809 /* FINISHME: Support geometry shaders. */
810 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
811 break;
812 }
813 }
814
815 /* FINISHME: Implement intra-stage linking. */
816 assert(num_vert_shaders <= 1);
817 assert(num_frag_shaders <= 1);
818
819 /* Verify that each of the per-target executables is valid.
820 */
821 if (!validate_vertex_shader_executable(prog, vert_shader_list[0])
822 || !validate_fragment_shader_executable(prog, frag_shader_list[0]))
823 goto done;
824
825
826 prog->_NumLinkedShaders = 0;
827
828 if (num_vert_shaders > 0) {
829 prog->_LinkedShaders[prog->_NumLinkedShaders] = vert_shader_list[0];
830 prog->_NumLinkedShaders++;
831 }
832
833 if (num_frag_shaders > 0) {
834 prog->_LinkedShaders[prog->_NumLinkedShaders] = frag_shader_list[0];
835 prog->_NumLinkedShaders++;
836 }
837
838 /* Here begins the inter-stage linking phase. Some initial validation is
839 * performed, then locations are assigned for uniforms, attributes, and
840 * varyings.
841 */
842 if (cross_validate_uniforms(prog)) {
843 /* Validate the inputs of each stage with the output of the preceeding
844 * stage.
845 */
846 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
847 if (!cross_validate_outputs_to_inputs(prog,
848 prog->_LinkedShaders[i - 1],
849 prog->_LinkedShaders[i]))
850 goto done;
851 }
852
853 prog->LinkStatus = true;
854 }
855
856 /* FINISHME: Perform whole-program optimization here. */
857
858 assign_uniform_locations(prog);
859
860 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
861 /* FINISHME: The value of the max_attribute_index parameter is
862 * FINISHME: implementation dependent based on the value of
863 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
864 * FINISHME: at least 16, so hardcode 16 for now.
865 */
866 if (!assign_attribute_locations(prog, 16))
867 goto done;
868
869 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
870 assign_varying_locations(prog->_LinkedShaders[i - 1],
871 prog->_LinkedShaders[i]);
872
873 /* FINISHME: Assign fragment shader output locations. */
874
875 done:
876 free(vert_shader_list);
877 }