linker: Track and validate GLSL versions used in 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 #include <climits>
70
71 extern "C" {
72 #include <talloc.h>
73 }
74
75 #include "main/mtypes.h"
76 #include "main/macros.h"
77 #include "glsl_symbol_table.h"
78 #include "ir.h"
79 #include "program.h"
80 #include "hash_table.h"
81 #include "shader_api.h"
82 #include "linker.h"
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 writes to both "
237 "`gl_FragColor' and `gl_FragData'\n");
238 return false;
239 }
240
241 return true;
242 }
243
244
245 /**
246 * Generate a string describing the mode of a variable
247 */
248 static const char *
249 mode_string(const ir_variable *var)
250 {
251 switch (var->mode) {
252 case ir_var_auto:
253 return (var->read_only) ? "global constant" : "global variable";
254
255 case ir_var_uniform: return "uniform";
256 case ir_var_in: return "shader input";
257 case ir_var_out: return "shader output";
258 case ir_var_inout: return "shader inout";
259 default:
260 assert(!"Should not get here.");
261 return "invalid variable";
262 }
263 }
264
265
266 /**
267 * Perform validation of global variables used across multiple shaders
268 */
269 bool
270 cross_validate_globals(struct gl_shader_program *prog,
271 struct gl_shader **shader_list,
272 unsigned num_shaders,
273 bool uniforms_only)
274 {
275 /* Examine all of the uniforms in all of the shaders and cross validate
276 * them.
277 */
278 glsl_symbol_table variables;
279 for (unsigned i = 0; i < num_shaders; i++) {
280 foreach_list(node, shader_list[i]->ir) {
281 ir_variable *const var = ((ir_instruction *) node)->as_variable();
282
283 if (var == NULL)
284 continue;
285
286 if (uniforms_only && (var->mode != ir_var_uniform))
287 continue;
288
289 /* If a global with this name has already been seen, verify that the
290 * new instance has the same type. In addition, if the globals have
291 * initializers, the values of the initializers must be the same.
292 */
293 ir_variable *const existing = variables.get_variable(var->name);
294 if (existing != NULL) {
295 if (var->type != existing->type) {
296 linker_error_printf(prog, "%s `%s' declared as type "
297 "`%s' and type `%s'\n",
298 mode_string(var),
299 var->name, var->type->name,
300 existing->type->name);
301 return false;
302 }
303
304 /* FINISHME: Handle non-constant initializers.
305 */
306 if (var->constant_value != NULL) {
307 if (existing->constant_value != NULL) {
308 if (!var->constant_value->has_value(existing->constant_value)) {
309 linker_error_printf(prog, "initializers for %s "
310 "`%s' have differing values\n",
311 mode_string(var), var->name);
312 return false;
313 }
314 } else
315 /* If the first-seen instance of a particular uniform did not
316 * have an initializer but a later instance does, copy the
317 * initializer to the version stored in the symbol table.
318 */
319 /* FINISHME: This is wrong. The constant_value field should
320 * FINISHME: not be modified! Imagine a case where a shader
321 * FINISHME: without an initializer is linked in two different
322 * FINISHME: programs with shaders that have differing
323 * FINISHME: initializers. Linking with the first will
324 * FINISHME: modify the shader, and linking with the second
325 * FINISHME: will fail.
326 */
327 existing->constant_value = var->constant_value->clone(NULL);
328 }
329 } else
330 variables.add_variable(var->name, var);
331 }
332 }
333
334 return true;
335 }
336
337
338 /**
339 * Perform validation of uniforms used across multiple shader stages
340 */
341 bool
342 cross_validate_uniforms(struct gl_shader_program *prog)
343 {
344 return cross_validate_globals(prog, prog->_LinkedShaders,
345 prog->_NumLinkedShaders, true);
346 }
347
348
349 /**
350 * Validate that outputs from one stage match inputs of another
351 */
352 bool
353 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
354 gl_shader *producer, gl_shader *consumer)
355 {
356 glsl_symbol_table parameters;
357 /* FINISHME: Figure these out dynamically. */
358 const char *const producer_stage = "vertex";
359 const char *const consumer_stage = "fragment";
360
361 /* Find all shader outputs in the "producer" stage.
362 */
363 foreach_list(node, producer->ir) {
364 ir_variable *const var = ((ir_instruction *) node)->as_variable();
365
366 /* FINISHME: For geometry shaders, this should also look for inout
367 * FINISHME: variables.
368 */
369 if ((var == NULL) || (var->mode != ir_var_out))
370 continue;
371
372 parameters.add_variable(var->name, var);
373 }
374
375
376 /* Find all shader inputs in the "consumer" stage. Any variables that have
377 * matching outputs already in the symbol table must have the same type and
378 * qualifiers.
379 */
380 foreach_list(node, consumer->ir) {
381 ir_variable *const input = ((ir_instruction *) node)->as_variable();
382
383 /* FINISHME: For geometry shaders, this should also look for inout
384 * FINISHME: variables.
385 */
386 if ((input == NULL) || (input->mode != ir_var_in))
387 continue;
388
389 ir_variable *const output = parameters.get_variable(input->name);
390 if (output != NULL) {
391 /* Check that the types match between stages.
392 */
393 if (input->type != output->type) {
394 linker_error_printf(prog,
395 "%s shader output `%s' delcared as "
396 "type `%s', but %s shader input declared "
397 "as type `%s'\n",
398 producer_stage, output->name,
399 output->type->name,
400 consumer_stage, input->type->name);
401 return false;
402 }
403
404 /* Check that all of the qualifiers match between stages.
405 */
406 if (input->centroid != output->centroid) {
407 linker_error_printf(prog,
408 "%s shader output `%s' %s centroid qualifier, "
409 "but %s shader input %s centroid qualifier\n",
410 producer_stage,
411 output->name,
412 (output->centroid) ? "has" : "lacks",
413 consumer_stage,
414 (input->centroid) ? "has" : "lacks");
415 return false;
416 }
417
418 if (input->invariant != output->invariant) {
419 linker_error_printf(prog,
420 "%s shader output `%s' %s invariant qualifier, "
421 "but %s shader input %s invariant qualifier\n",
422 producer_stage,
423 output->name,
424 (output->invariant) ? "has" : "lacks",
425 consumer_stage,
426 (input->invariant) ? "has" : "lacks");
427 return false;
428 }
429
430 if (input->interpolation != output->interpolation) {
431 linker_error_printf(prog,
432 "%s shader output `%s' specifies %s "
433 "interpolation qualifier, "
434 "but %s shader input specifies %s "
435 "interpolation qualifier\n",
436 producer_stage,
437 output->name,
438 output->interpolation_string(),
439 consumer_stage,
440 input->interpolation_string());
441 return false;
442 }
443 }
444 }
445
446 return true;
447 }
448
449
450 /**
451 * Populates a shaders symbol table with all global declarations
452 */
453 static void
454 populate_symbol_table(gl_shader *sh)
455 {
456 sh->symbols = new(sh) glsl_symbol_table;
457
458 foreach_list(node, sh->ir) {
459 ir_instruction *const inst = (ir_instruction *) node;
460 ir_variable *var;
461 ir_function *func;
462
463 if ((func = inst->as_function()) != NULL) {
464 sh->symbols->add_function(func->name, func);
465 } else if ((var = inst->as_variable()) != NULL) {
466 sh->symbols->add_variable(var->name, var);
467 }
468 }
469 }
470
471
472 /**
473 * Remap variables referenced in an instruction tree
474 *
475 * This is used when instruction trees are cloned from one shader and placed in
476 * another. These trees will contain references to \c ir_variable nodes that
477 * do not exist in the target shader. This function finds these \c ir_variable
478 * references and replaces the references with matching variables in the target
479 * shader.
480 *
481 * If there is no matching variable in the target shader, a clone of the
482 * \c ir_variable is made and added to the target shader. The new variable is
483 * added to \b both the instruction stream and the symbol table.
484 *
485 * \param inst IR tree that is to be processed.
486 * \param symbols Symbol table containing global scope symbols in the
487 * linked shader.
488 * \param instructions Instruction stream where new variable declarations
489 * should be added.
490 */
491 void
492 remap_variables(ir_instruction *inst, glsl_symbol_table *symbols,
493 exec_list *instructions)
494 {
495 class remap_visitor : public ir_hierarchical_visitor {
496 public:
497 remap_visitor(glsl_symbol_table *symbols, exec_list *instructions)
498 {
499 this->symbols = symbols;
500 this->instructions = instructions;
501 }
502
503 virtual ir_visitor_status visit(ir_dereference_variable *ir)
504 {
505 ir_variable *const existing =
506 this->symbols->get_variable(ir->var->name);
507 if (existing != NULL)
508 ir->var = existing;
509 else {
510 ir_variable *copy = ir->var->clone(NULL);
511
512 this->symbols->add_variable(copy->name, copy);
513 this->instructions->push_head(copy);
514 }
515
516 return visit_continue;
517 }
518
519 private:
520 glsl_symbol_table *symbols;
521 exec_list *instructions;
522 };
523
524 remap_visitor v(symbols, instructions);
525
526 inst->accept(&v);
527 }
528
529
530 /**
531 * Move non-declarations from one instruction stream to another
532 *
533 * The intended usage pattern of this function is to pass the pointer to the
534 * head sentinal of a list (i.e., a pointer to the list cast to an \c exec_node
535 * pointer) for \c last and \c false for \c make_copies on the first
536 * call. Successive calls pass the return value of the previous call for
537 * \c last and \c true for \c make_copies.
538 *
539 * \param instructions Source instruction stream
540 * \param last Instruction after which new instructions should be
541 * inserted in the target instruction stream
542 * \param make_copies Flag selecting whether instructions in \c instructions
543 * should be copied (via \c ir_instruction::clone) into the
544 * target list or moved.
545 *
546 * \return
547 * The new "last" instruction in the target instruction stream. This pointer
548 * is suitable for use as the \c last parameter of a later call to this
549 * function.
550 */
551 exec_node *
552 move_non_declarations(exec_list *instructions, exec_node *last,
553 bool make_copies, gl_shader *target)
554 {
555 foreach_list_safe(node, instructions) {
556 ir_instruction *inst = (ir_instruction *) node;
557
558 if (inst->as_variable() || inst->as_function())
559 continue;
560
561 assert(inst->as_assignment());
562
563 if (make_copies) {
564 inst = inst->clone(NULL);
565 remap_variables(inst, target->symbols, target->ir);
566 } else {
567 inst->remove();
568 }
569
570 last->insert_after(inst);
571 last = inst;
572 }
573
574 return last;
575 }
576
577 /**
578 * Get the function signature for main from a shader
579 */
580 static ir_function_signature *
581 get_main_function_signature(gl_shader *sh)
582 {
583 ir_function *const f = sh->symbols->get_function("main");
584 if (f != NULL) {
585 exec_list void_parameters;
586
587 /* Look for the 'void main()' signature and ensure that it's defined.
588 * This keeps the linker from accidentally pick a shader that just
589 * contains a prototype for main.
590 *
591 * We don't have to check for multiple definitions of main (in multiple
592 * shaders) because that would have already been caught above.
593 */
594 ir_function_signature *sig = f->matching_signature(&void_parameters);
595 if ((sig != NULL) && sig->is_defined) {
596 return sig;
597 }
598 }
599
600 return NULL;
601 }
602
603
604 /**
605 * Combine a group of shaders for a single stage to generate a linked shader
606 *
607 * \note
608 * If this function is supplied a single shader, it is cloned, and the new
609 * shader is returned.
610 */
611 static struct gl_shader *
612 link_intrastage_shaders(struct gl_shader_program *prog,
613 struct gl_shader **shader_list,
614 unsigned num_shaders)
615 {
616 /* Check that global variables defined in multiple shaders are consistent.
617 */
618 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
619 return NULL;
620
621 /* Check that there is only a single definition of each function signature
622 * across all shaders.
623 */
624 for (unsigned i = 0; i < (num_shaders - 1); i++) {
625 foreach_list(node, shader_list[i]->ir) {
626 ir_function *const f = ((ir_instruction *) node)->as_function();
627
628 if (f == NULL)
629 continue;
630
631 for (unsigned j = i + 1; j < num_shaders; j++) {
632 ir_function *const other =
633 shader_list[j]->symbols->get_function(f->name);
634
635 /* If the other shader has no function (and therefore no function
636 * signatures) with the same name, skip to the next shader.
637 */
638 if (other == NULL)
639 continue;
640
641 foreach_iter (exec_list_iterator, iter, *f) {
642 ir_function_signature *sig =
643 (ir_function_signature *) iter.get();
644
645 if (!sig->is_defined || sig->is_built_in)
646 continue;
647
648 ir_function_signature *other_sig =
649 other->exact_matching_signature(& sig->parameters);
650
651 if ((other_sig != NULL) && other_sig->is_defined
652 && !other_sig->is_built_in) {
653 linker_error_printf(prog,
654 "function `%s' is multiply defined",
655 f->name);
656 return NULL;
657 }
658 }
659 }
660 }
661 }
662
663 /* Find the shader that defines main, and make a clone of it.
664 *
665 * Starting with the clone, search for undefined references. If one is
666 * found, find the shader that defines it. Clone the reference and add
667 * it to the shader. Repeat until there are no undefined references or
668 * until a reference cannot be resolved.
669 */
670 gl_shader *main = NULL;
671 for (unsigned i = 0; i < num_shaders; i++) {
672 if (get_main_function_signature(shader_list[i]) != NULL) {
673 main = shader_list[i];
674 break;
675 }
676 }
677
678 if (main == NULL) {
679 linker_error_printf(prog, "%s shader lacks `main'\n",
680 (shader_list[0]->Type == GL_VERTEX_SHADER)
681 ? "vertex" : "fragment");
682 return NULL;
683 }
684
685 gl_shader *const linked = _mesa_new_shader(NULL, 0, main->Type);
686 linked->ir = new(linked) exec_list;
687 clone_ir_list(linked->ir, main->ir);
688
689 populate_symbol_table(linked);
690
691 /* The a pointer to the main function in the final linked shader (i.e., the
692 * copy of the original shader that contained the main function).
693 */
694 ir_function_signature *const main_sig = get_main_function_signature(linked);
695
696 /* Move any instructions other than variable declarations or function
697 * declarations into main.
698 */
699 exec_node *insertion_point =
700 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
701 linked);
702
703 for (unsigned i = 0; i < num_shaders; i++) {
704 if (shader_list[i] == main)
705 continue;
706
707 insertion_point = move_non_declarations(shader_list[i]->ir,
708 insertion_point, true, linked);
709 }
710
711 /* Resolve initializers for global variables in the linked shader.
712 */
713 link_function_calls(prog, linked, shader_list, num_shaders);
714
715 return linked;
716 }
717
718
719 struct uniform_node {
720 exec_node link;
721 struct gl_uniform *u;
722 unsigned slots;
723 };
724
725 void
726 assign_uniform_locations(struct gl_shader_program *prog)
727 {
728 /* */
729 exec_list uniforms;
730 unsigned total_uniforms = 0;
731 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
732 hash_table_string_compare);
733
734 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
735 unsigned next_position = 0;
736
737 foreach_list(node, prog->_LinkedShaders[i]->ir) {
738 ir_variable *const var = ((ir_instruction *) node)->as_variable();
739
740 if ((var == NULL) || (var->mode != ir_var_uniform))
741 continue;
742
743 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
744 assert(vec4_slots != 0);
745
746 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
747 if (n == NULL) {
748 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
749 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
750 n->slots = vec4_slots;
751
752 n->u[0].Name = strdup(var->name);
753 for (unsigned j = 1; j < vec4_slots; j++)
754 n->u[j].Name = n->u[0].Name;
755
756 hash_table_insert(ht, n, n->u[0].Name);
757 uniforms.push_tail(& n->link);
758 total_uniforms += vec4_slots;
759 }
760
761 if (var->constant_value != NULL)
762 for (unsigned j = 0; j < vec4_slots; j++)
763 n->u[j].Initialized = true;
764
765 var->location = next_position;
766
767 for (unsigned j = 0; j < vec4_slots; j++) {
768 switch (prog->_LinkedShaders[i]->Type) {
769 case GL_VERTEX_SHADER:
770 n->u[j].VertPos = next_position;
771 break;
772 case GL_FRAGMENT_SHADER:
773 n->u[j].FragPos = next_position;
774 break;
775 case GL_GEOMETRY_SHADER:
776 /* FINISHME: Support geometry shaders. */
777 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
778 break;
779 }
780
781 next_position++;
782 }
783 }
784 }
785
786 gl_uniform_list *ul = (gl_uniform_list *)
787 calloc(1, sizeof(gl_uniform_list));
788
789 ul->Size = total_uniforms;
790 ul->NumUniforms = total_uniforms;
791 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
792
793 unsigned idx = 0;
794 uniform_node *next;
795 for (uniform_node *node = (uniform_node *) uniforms.head
796 ; node->link.next != NULL
797 ; node = next) {
798 next = (uniform_node *) node->link.next;
799
800 node->link.remove();
801 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
802 idx += node->slots;
803
804 free(node->u);
805 free(node);
806 }
807
808 hash_table_dtor(ht);
809
810 prog->Uniforms = ul;
811 }
812
813
814 /**
815 * Find a contiguous set of available bits in a bitmask
816 *
817 * \param used_mask Bits representing used (1) and unused (0) locations
818 * \param needed_count Number of contiguous bits needed.
819 *
820 * \return
821 * Base location of the available bits on success or -1 on failure.
822 */
823 int
824 find_available_slots(unsigned used_mask, unsigned needed_count)
825 {
826 unsigned needed_mask = (1 << needed_count) - 1;
827 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
828
829 /* The comparison to 32 is redundant, but without it GCC emits "warning:
830 * cannot optimize possibly infinite loops" for the loop below.
831 */
832 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
833 return -1;
834
835 for (int i = 0; i <= max_bit_to_test; i++) {
836 if ((needed_mask & ~used_mask) == needed_mask)
837 return i;
838
839 needed_mask <<= 1;
840 }
841
842 return -1;
843 }
844
845
846 bool
847 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
848 {
849 /* Mark invalid attribute locations as being used.
850 */
851 unsigned used_locations = (max_attribute_index >= 32)
852 ? ~0 : ~((1 << max_attribute_index) - 1);
853
854 gl_shader *const sh = prog->_LinkedShaders[0];
855 assert(sh->Type == GL_VERTEX_SHADER);
856
857 /* Operate in a total of four passes.
858 *
859 * 1. Invalidate the location assignments for all vertex shader inputs.
860 *
861 * 2. Assign locations for inputs that have user-defined (via
862 * glBindVertexAttribLocation) locatoins.
863 *
864 * 3. Sort the attributes without assigned locations by number of slots
865 * required in decreasing order. Fragmentation caused by attribute
866 * locations assigned by the application may prevent large attributes
867 * from having enough contiguous space.
868 *
869 * 4. Assign locations to any inputs without assigned locations.
870 */
871
872 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
873
874 if (prog->Attributes != NULL) {
875 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
876 ir_variable *const var =
877 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
878
879 /* Note: attributes that occupy multiple slots, such as arrays or
880 * matrices, may appear in the attrib array multiple times.
881 */
882 if ((var == NULL) || (var->location != -1))
883 continue;
884
885 /* From page 61 of the OpenGL 4.0 spec:
886 *
887 * "LinkProgram will fail if the attribute bindings assigned by
888 * BindAttribLocation do not leave not enough space to assign a
889 * location for an active matrix attribute or an active attribute
890 * array, both of which require multiple contiguous generic
891 * attributes."
892 *
893 * Previous versions of the spec contain similar language but omit the
894 * bit about attribute arrays.
895 *
896 * Page 61 of the OpenGL 4.0 spec also says:
897 *
898 * "It is possible for an application to bind more than one
899 * attribute name to the same location. This is referred to as
900 * aliasing. This will only work if only one of the aliased
901 * attributes is active in the executable program, or if no path
902 * through the shader consumes more than one attribute of a set
903 * of attributes aliased to the same location. A link error can
904 * occur if the linker determines that every path through the
905 * shader consumes multiple aliased attributes, but
906 * implementations are not required to generate an error in this
907 * case."
908 *
909 * These two paragraphs are either somewhat contradictory, or I don't
910 * fully understand one or both of them.
911 */
912 /* FINISHME: The code as currently written does not support attribute
913 * FINISHME: location aliasing (see comment above).
914 */
915 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
916 const unsigned slots = count_attribute_slots(var->type);
917
918 /* Mask representing the contiguous slots that will be used by this
919 * attribute.
920 */
921 const unsigned use_mask = (1 << slots) - 1;
922
923 /* Generate a link error if the set of bits requested for this
924 * attribute overlaps any previously allocated bits.
925 */
926 if ((~(use_mask << attr) & used_locations) != used_locations) {
927 linker_error_printf(prog,
928 "insufficient contiguous attribute locations "
929 "available for vertex shader input `%s'",
930 var->name);
931 return false;
932 }
933
934 var->location = VERT_ATTRIB_GENERIC0 + attr;
935 used_locations |= (use_mask << attr);
936 }
937 }
938
939 /* Temporary storage for the set of attributes that need locations assigned.
940 */
941 struct temp_attr {
942 unsigned slots;
943 ir_variable *var;
944
945 /* Used below in the call to qsort. */
946 static int compare(const void *a, const void *b)
947 {
948 const temp_attr *const l = (const temp_attr *) a;
949 const temp_attr *const r = (const temp_attr *) b;
950
951 /* Reversed because we want a descending order sort below. */
952 return r->slots - l->slots;
953 }
954 } to_assign[16];
955
956 unsigned num_attr = 0;
957
958 foreach_list(node, sh->ir) {
959 ir_variable *const var = ((ir_instruction *) node)->as_variable();
960
961 if ((var == NULL) || (var->mode != ir_var_in))
962 continue;
963
964 /* The location was explicitly assigned, nothing to do here.
965 */
966 if (var->location != -1)
967 continue;
968
969 to_assign[num_attr].slots = count_attribute_slots(var->type);
970 to_assign[num_attr].var = var;
971 num_attr++;
972 }
973
974 /* If all of the attributes were assigned locations by the application (or
975 * are built-in attributes with fixed locations), return early. This should
976 * be the common case.
977 */
978 if (num_attr == 0)
979 return true;
980
981 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
982
983 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
984 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
985 * to prevent it from being automatically allocated below.
986 */
987 used_locations |= (1 << 0);
988
989 for (unsigned i = 0; i < num_attr; i++) {
990 /* Mask representing the contiguous slots that will be used by this
991 * attribute.
992 */
993 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
994
995 int location = find_available_slots(used_locations, to_assign[i].slots);
996
997 if (location < 0) {
998 linker_error_printf(prog,
999 "insufficient contiguous attribute locations "
1000 "available for vertex shader input `%s'",
1001 to_assign[i].var->name);
1002 return false;
1003 }
1004
1005 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1006 used_locations |= (use_mask << location);
1007 }
1008
1009 return true;
1010 }
1011
1012
1013 void
1014 assign_varying_locations(gl_shader *producer, gl_shader *consumer)
1015 {
1016 /* FINISHME: Set dynamically when geometry shader support is added. */
1017 unsigned output_index = VERT_RESULT_VAR0;
1018 unsigned input_index = FRAG_ATTRIB_VAR0;
1019
1020 /* Operate in a total of three passes.
1021 *
1022 * 1. Assign locations for any matching inputs and outputs.
1023 *
1024 * 2. Mark output variables in the producer that do not have locations as
1025 * not being outputs. This lets the optimizer eliminate them.
1026 *
1027 * 3. Mark input variables in the consumer that do not have locations as
1028 * not being inputs. This lets the optimizer eliminate them.
1029 */
1030
1031 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1032 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1033
1034 foreach_list(node, producer->ir) {
1035 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1036
1037 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1038 || (output_var->location != -1))
1039 continue;
1040
1041 ir_variable *const input_var =
1042 consumer->symbols->get_variable(output_var->name);
1043
1044 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1045 continue;
1046
1047 assert(input_var->location == -1);
1048
1049 /* FINISHME: Location assignment will need some changes when arrays,
1050 * FINISHME: matrices, and structures are allowed as shader inputs /
1051 * FINISHME: outputs.
1052 */
1053 output_var->location = output_index;
1054 input_var->location = input_index;
1055
1056 output_index++;
1057 input_index++;
1058 }
1059
1060 foreach_list(node, producer->ir) {
1061 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1062
1063 if ((var == NULL) || (var->mode != ir_var_out))
1064 continue;
1065
1066 /* An 'out' variable is only really a shader output if its value is read
1067 * by the following stage.
1068 */
1069 if (var->location == -1) {
1070 var->shader_out = false;
1071 var->mode = ir_var_auto;
1072 }
1073 }
1074
1075 foreach_list(node, consumer->ir) {
1076 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1077
1078 if ((var == NULL) || (var->mode != ir_var_in))
1079 continue;
1080
1081 /* An 'in' variable is only really a shader input if its value is written
1082 * by the previous stage.
1083 */
1084 var->shader_in = (var->location != -1);
1085 }
1086 }
1087
1088
1089 void
1090 link_shaders(struct gl_shader_program *prog)
1091 {
1092 prog->LinkStatus = false;
1093 prog->Validated = false;
1094 prog->_Used = false;
1095
1096 if (prog->InfoLog != NULL)
1097 talloc_free(prog->InfoLog);
1098
1099 prog->InfoLog = talloc_strdup(NULL, "");
1100
1101 /* Separate the shaders into groups based on their type.
1102 */
1103 struct gl_shader **vert_shader_list;
1104 unsigned num_vert_shaders = 0;
1105 struct gl_shader **frag_shader_list;
1106 unsigned num_frag_shaders = 0;
1107
1108 vert_shader_list = (struct gl_shader **)
1109 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1110 frag_shader_list = &vert_shader_list[prog->NumShaders];
1111
1112 unsigned min_version = UINT_MAX;
1113 unsigned max_version = 0;
1114 for (unsigned i = 0; i < prog->NumShaders; i++) {
1115 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1116 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1117
1118 switch (prog->Shaders[i]->Type) {
1119 case GL_VERTEX_SHADER:
1120 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1121 num_vert_shaders++;
1122 break;
1123 case GL_FRAGMENT_SHADER:
1124 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1125 num_frag_shaders++;
1126 break;
1127 case GL_GEOMETRY_SHADER:
1128 /* FINISHME: Support geometry shaders. */
1129 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1130 break;
1131 }
1132 }
1133
1134 /* Previous to GLSL version 1.30, different compilation units could mix and
1135 * match shading language versions. With GLSL 1.30 and later, the versions
1136 * of all shaders must match.
1137 */
1138 assert(min_version >= 110);
1139 assert(max_version <= 130);
1140 if ((max_version >= 130) && (min_version != max_version)) {
1141 linker_error_printf(prog, "all shaders must use same shading "
1142 "language version\n");
1143 goto done;
1144 }
1145
1146 prog->Version = max_version;
1147
1148 /* FINISHME: Implement intra-stage linking. */
1149 prog->_NumLinkedShaders = 0;
1150 if (num_vert_shaders > 0) {
1151 gl_shader *const sh =
1152 link_intrastage_shaders(prog, vert_shader_list, num_vert_shaders);
1153
1154 if (sh == NULL)
1155 goto done;
1156
1157 if (!validate_vertex_shader_executable(prog, sh))
1158 goto done;
1159
1160 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1161 prog->_NumLinkedShaders++;
1162 }
1163
1164 if (num_frag_shaders > 0) {
1165 gl_shader *const sh =
1166 link_intrastage_shaders(prog, frag_shader_list, num_frag_shaders);
1167
1168 if (sh == NULL)
1169 goto done;
1170
1171 if (!validate_fragment_shader_executable(prog, sh))
1172 goto done;
1173
1174 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1175 prog->_NumLinkedShaders++;
1176 }
1177
1178 /* Here begins the inter-stage linking phase. Some initial validation is
1179 * performed, then locations are assigned for uniforms, attributes, and
1180 * varyings.
1181 */
1182 if (cross_validate_uniforms(prog)) {
1183 /* Validate the inputs of each stage with the output of the preceeding
1184 * stage.
1185 */
1186 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
1187 if (!cross_validate_outputs_to_inputs(prog,
1188 prog->_LinkedShaders[i - 1],
1189 prog->_LinkedShaders[i]))
1190 goto done;
1191 }
1192
1193 prog->LinkStatus = true;
1194 }
1195
1196 /* FINISHME: Perform whole-program optimization here. */
1197
1198 assign_uniform_locations(prog);
1199
1200 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
1201 /* FINISHME: The value of the max_attribute_index parameter is
1202 * FINISHME: implementation dependent based on the value of
1203 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1204 * FINISHME: at least 16, so hardcode 16 for now.
1205 */
1206 if (!assign_attribute_locations(prog, 16))
1207 goto done;
1208
1209 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
1210 assign_varying_locations(prog->_LinkedShaders[i - 1],
1211 prog->_LinkedShaders[i]);
1212
1213 /* FINISHME: Assign fragment shader output locations. */
1214
1215 done:
1216 free(vert_shader_list);
1217 }