ir_structure_splitting: New pass to chop structures into their components.
[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 "main/shaderobj.h"
78 #include "glsl_symbol_table.h"
79 #include "ir.h"
80 #include "program.h"
81 #include "program/hash_table.h"
82 #include "linker.h"
83 #include "ir_optimization.h"
84
85 /**
86 * Visitor that determines whether or not a variable is ever written.
87 */
88 class find_assignment_visitor : public ir_hierarchical_visitor {
89 public:
90 find_assignment_visitor(const char *name)
91 : name(name), found(false)
92 {
93 /* empty */
94 }
95
96 virtual ir_visitor_status visit_enter(ir_assignment *ir)
97 {
98 ir_variable *const var = ir->lhs->variable_referenced();
99
100 if (strcmp(name, var->name) == 0) {
101 found = true;
102 return visit_stop;
103 }
104
105 return visit_continue_with_parent;
106 }
107
108 bool variable_found()
109 {
110 return found;
111 }
112
113 private:
114 const char *name; /**< Find writes to a variable with this name. */
115 bool found; /**< Was a write to the variable found? */
116 };
117
118
119 void
120 linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
121 {
122 va_list ap;
123
124 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
125 va_start(ap, fmt);
126 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
127 va_end(ap);
128 }
129
130
131 void
132 invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
133 int generic_base)
134 {
135 foreach_list(node, sh->ir) {
136 ir_variable *const var = ((ir_instruction *) node)->as_variable();
137
138 if ((var == NULL) || (var->mode != (unsigned) mode))
139 continue;
140
141 /* Only assign locations for generic attributes / varyings / etc.
142 */
143 if (var->location >= generic_base)
144 var->location = -1;
145 }
146 }
147
148
149 /**
150 * Determine the number of attribute slots required for a particular type
151 *
152 * This code is here because it implements the language rules of a specific
153 * GLSL version. Since it's a property of the language and not a property of
154 * types in general, it doesn't really belong in glsl_type.
155 */
156 unsigned
157 count_attribute_slots(const glsl_type *t)
158 {
159 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
160 *
161 * "A scalar input counts the same amount against this limit as a vec4,
162 * so applications may want to consider packing groups of four
163 * unrelated float inputs together into a vector to better utilize the
164 * capabilities of the underlying hardware. A matrix input will use up
165 * multiple locations. The number of locations used will equal the
166 * number of columns in the matrix."
167 *
168 * The spec does not explicitly say how arrays are counted. However, it
169 * should be safe to assume the total number of slots consumed by an array
170 * is the number of entries in the array multiplied by the number of slots
171 * consumed by a single element of the array.
172 */
173
174 if (t->is_array())
175 return t->array_size() * count_attribute_slots(t->element_type());
176
177 if (t->is_matrix())
178 return t->matrix_columns;
179
180 return 1;
181 }
182
183
184 /**
185 * Verify that a vertex shader executable meets all semantic requirements
186 *
187 * \param shader Vertex shader executable to be verified
188 */
189 bool
190 validate_vertex_shader_executable(struct gl_shader_program *prog,
191 struct gl_shader *shader)
192 {
193 if (shader == NULL)
194 return true;
195
196 find_assignment_visitor find("gl_Position");
197 find.run(shader->ir);
198 if (!find.variable_found()) {
199 linker_error_printf(prog,
200 "vertex shader does not write to `gl_Position'\n");
201 return false;
202 }
203
204 return true;
205 }
206
207
208 /**
209 * Verify that a fragment shader executable meets all semantic requirements
210 *
211 * \param shader Fragment shader executable to be verified
212 */
213 bool
214 validate_fragment_shader_executable(struct gl_shader_program *prog,
215 struct gl_shader *shader)
216 {
217 if (shader == NULL)
218 return true;
219
220 find_assignment_visitor frag_color("gl_FragColor");
221 find_assignment_visitor frag_data("gl_FragData");
222
223 frag_color.run(shader->ir);
224 frag_data.run(shader->ir);
225
226 if (frag_color.variable_found() && frag_data.variable_found()) {
227 linker_error_printf(prog, "fragment shader writes to both "
228 "`gl_FragColor' and `gl_FragData'\n");
229 return false;
230 }
231
232 return true;
233 }
234
235
236 /**
237 * Generate a string describing the mode of a variable
238 */
239 static const char *
240 mode_string(const ir_variable *var)
241 {
242 switch (var->mode) {
243 case ir_var_auto:
244 return (var->read_only) ? "global constant" : "global variable";
245
246 case ir_var_uniform: return "uniform";
247 case ir_var_in: return "shader input";
248 case ir_var_out: return "shader output";
249 case ir_var_inout: return "shader inout";
250
251 case ir_var_temporary:
252 default:
253 assert(!"Should not get here.");
254 return "invalid variable";
255 }
256 }
257
258
259 /**
260 * Perform validation of global variables used across multiple shaders
261 */
262 bool
263 cross_validate_globals(struct gl_shader_program *prog,
264 struct gl_shader **shader_list,
265 unsigned num_shaders,
266 bool uniforms_only)
267 {
268 /* Examine all of the uniforms in all of the shaders and cross validate
269 * them.
270 */
271 glsl_symbol_table variables;
272 for (unsigned i = 0; i < num_shaders; i++) {
273 foreach_list(node, shader_list[i]->ir) {
274 ir_variable *const var = ((ir_instruction *) node)->as_variable();
275
276 if (var == NULL)
277 continue;
278
279 if (uniforms_only && (var->mode != ir_var_uniform))
280 continue;
281
282 /* Don't cross validate temporaries that are at global scope. These
283 * will eventually get pulled into the shaders 'main'.
284 */
285 if (var->mode == ir_var_temporary)
286 continue;
287
288 /* If a global with this name has already been seen, verify that the
289 * new instance has the same type. In addition, if the globals have
290 * initializers, the values of the initializers must be the same.
291 */
292 ir_variable *const existing = variables.get_variable(var->name);
293 if (existing != NULL) {
294 if (var->type != existing->type) {
295 linker_error_printf(prog, "%s `%s' declared as type "
296 "`%s' and type `%s'\n",
297 mode_string(var),
298 var->name, var->type->name,
299 existing->type->name);
300 return false;
301 }
302
303 /* FINISHME: Handle non-constant initializers.
304 */
305 if (var->constant_value != NULL) {
306 if (existing->constant_value != NULL) {
307 if (!var->constant_value->has_value(existing->constant_value)) {
308 linker_error_printf(prog, "initializers for %s "
309 "`%s' have differing values\n",
310 mode_string(var), var->name);
311 return false;
312 }
313 } else
314 /* If the first-seen instance of a particular uniform did not
315 * have an initializer but a later instance does, copy the
316 * initializer to the version stored in the symbol table.
317 */
318 /* FINISHME: This is wrong. The constant_value field should
319 * FINISHME: not be modified! Imagine a case where a shader
320 * FINISHME: without an initializer is linked in two different
321 * FINISHME: programs with shaders that have differing
322 * FINISHME: initializers. Linking with the first will
323 * FINISHME: modify the shader, and linking with the second
324 * FINISHME: will fail.
325 */
326 existing->constant_value =
327 var->constant_value->clone(talloc_parent(existing), 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, struct gl_shader *target,
493 hash_table *temps)
494 {
495 class remap_visitor : public ir_hierarchical_visitor {
496 public:
497 remap_visitor(struct gl_shader *target,
498 hash_table *temps)
499 {
500 this->target = target;
501 this->symbols = target->symbols;
502 this->instructions = target->ir;
503 this->temps = temps;
504 }
505
506 virtual ir_visitor_status visit(ir_dereference_variable *ir)
507 {
508 if (ir->var->mode == ir_var_temporary) {
509 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
510
511 assert(var != NULL);
512 ir->var = var;
513 return visit_continue;
514 }
515
516 ir_variable *const existing =
517 this->symbols->get_variable(ir->var->name);
518 if (existing != NULL)
519 ir->var = existing;
520 else {
521 ir_variable *copy = ir->var->clone(this->target, NULL);
522
523 this->symbols->add_variable(copy->name, copy);
524 this->instructions->push_head(copy);
525 ir->var = copy;
526 }
527
528 return visit_continue;
529 }
530
531 private:
532 struct gl_shader *target;
533 glsl_symbol_table *symbols;
534 exec_list *instructions;
535 hash_table *temps;
536 };
537
538 remap_visitor v(target, temps);
539
540 inst->accept(&v);
541 }
542
543
544 /**
545 * Move non-declarations from one instruction stream to another
546 *
547 * The intended usage pattern of this function is to pass the pointer to the
548 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
549 * pointer) for \c last and \c false for \c make_copies on the first
550 * call. Successive calls pass the return value of the previous call for
551 * \c last and \c true for \c make_copies.
552 *
553 * \param instructions Source instruction stream
554 * \param last Instruction after which new instructions should be
555 * inserted in the target instruction stream
556 * \param make_copies Flag selecting whether instructions in \c instructions
557 * should be copied (via \c ir_instruction::clone) into the
558 * target list or moved.
559 *
560 * \return
561 * The new "last" instruction in the target instruction stream. This pointer
562 * is suitable for use as the \c last parameter of a later call to this
563 * function.
564 */
565 exec_node *
566 move_non_declarations(exec_list *instructions, exec_node *last,
567 bool make_copies, gl_shader *target)
568 {
569 hash_table *temps = NULL;
570
571 if (make_copies)
572 temps = hash_table_ctor(0, hash_table_pointer_hash,
573 hash_table_pointer_compare);
574
575 foreach_list_safe(node, instructions) {
576 ir_instruction *inst = (ir_instruction *) node;
577
578 if (inst->as_function())
579 continue;
580
581 ir_variable *var = inst->as_variable();
582 if ((var != NULL) && (var->mode != ir_var_temporary))
583 continue;
584
585 assert(inst->as_assignment()
586 || ((var != NULL) && (var->mode == ir_var_temporary)));
587
588 if (make_copies) {
589 inst = inst->clone(target, NULL);
590
591 if (var != NULL)
592 hash_table_insert(temps, inst, var);
593 else
594 remap_variables(inst, target, temps);
595 } else {
596 inst->remove();
597 }
598
599 last->insert_after(inst);
600 last = inst;
601 }
602
603 if (make_copies)
604 hash_table_dtor(temps);
605
606 return last;
607 }
608
609 /**
610 * Get the function signature for main from a shader
611 */
612 static ir_function_signature *
613 get_main_function_signature(gl_shader *sh)
614 {
615 ir_function *const f = sh->symbols->get_function("main");
616 if (f != NULL) {
617 exec_list void_parameters;
618
619 /* Look for the 'void main()' signature and ensure that it's defined.
620 * This keeps the linker from accidentally pick a shader that just
621 * contains a prototype for main.
622 *
623 * We don't have to check for multiple definitions of main (in multiple
624 * shaders) because that would have already been caught above.
625 */
626 ir_function_signature *sig = f->matching_signature(&void_parameters);
627 if ((sig != NULL) && sig->is_defined) {
628 return sig;
629 }
630 }
631
632 return NULL;
633 }
634
635
636 /**
637 * Combine a group of shaders for a single stage to generate a linked shader
638 *
639 * \note
640 * If this function is supplied a single shader, it is cloned, and the new
641 * shader is returned.
642 */
643 static struct gl_shader *
644 link_intrastage_shaders(struct gl_shader_program *prog,
645 struct gl_shader **shader_list,
646 unsigned num_shaders)
647 {
648 /* Check that global variables defined in multiple shaders are consistent.
649 */
650 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
651 return NULL;
652
653 /* Check that there is only a single definition of each function signature
654 * across all shaders.
655 */
656 for (unsigned i = 0; i < (num_shaders - 1); i++) {
657 foreach_list(node, shader_list[i]->ir) {
658 ir_function *const f = ((ir_instruction *) node)->as_function();
659
660 if (f == NULL)
661 continue;
662
663 for (unsigned j = i + 1; j < num_shaders; j++) {
664 ir_function *const other =
665 shader_list[j]->symbols->get_function(f->name);
666
667 /* If the other shader has no function (and therefore no function
668 * signatures) with the same name, skip to the next shader.
669 */
670 if (other == NULL)
671 continue;
672
673 foreach_iter (exec_list_iterator, iter, *f) {
674 ir_function_signature *sig =
675 (ir_function_signature *) iter.get();
676
677 if (!sig->is_defined || sig->is_built_in)
678 continue;
679
680 ir_function_signature *other_sig =
681 other->exact_matching_signature(& sig->parameters);
682
683 if ((other_sig != NULL) && other_sig->is_defined
684 && !other_sig->is_built_in) {
685 linker_error_printf(prog,
686 "function `%s' is multiply defined",
687 f->name);
688 return NULL;
689 }
690 }
691 }
692 }
693 }
694
695 /* Find the shader that defines main, and make a clone of it.
696 *
697 * Starting with the clone, search for undefined references. If one is
698 * found, find the shader that defines it. Clone the reference and add
699 * it to the shader. Repeat until there are no undefined references or
700 * until a reference cannot be resolved.
701 */
702 gl_shader *main = NULL;
703 for (unsigned i = 0; i < num_shaders; i++) {
704 if (get_main_function_signature(shader_list[i]) != NULL) {
705 main = shader_list[i];
706 break;
707 }
708 }
709
710 if (main == NULL) {
711 linker_error_printf(prog, "%s shader lacks `main'\n",
712 (shader_list[0]->Type == GL_VERTEX_SHADER)
713 ? "vertex" : "fragment");
714 return NULL;
715 }
716
717 gl_shader *const linked = _mesa_new_shader(NULL, 0, main->Type);
718 linked->ir = new(linked) exec_list;
719 clone_ir_list(linked, linked->ir, main->ir);
720
721 populate_symbol_table(linked);
722
723 /* The a pointer to the main function in the final linked shader (i.e., the
724 * copy of the original shader that contained the main function).
725 */
726 ir_function_signature *const main_sig = get_main_function_signature(linked);
727
728 /* Move any instructions other than variable declarations or function
729 * declarations into main.
730 */
731 exec_node *insertion_point =
732 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
733 linked);
734
735 for (unsigned i = 0; i < num_shaders; i++) {
736 if (shader_list[i] == main)
737 continue;
738
739 insertion_point = move_non_declarations(shader_list[i]->ir,
740 insertion_point, true, linked);
741 }
742
743 /* Resolve initializers for global variables in the linked shader.
744 */
745 unsigned num_linking_shaders = num_shaders;
746 for (unsigned i = 0; i < num_shaders; i++)
747 num_linking_shaders += shader_list[i]->num_builtins_to_link;
748
749 gl_shader **linking_shaders =
750 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
751
752 memcpy(linking_shaders, shader_list,
753 sizeof(linking_shaders[0]) * num_shaders);
754
755 unsigned idx = num_shaders;
756 for (unsigned i = 0; i < num_shaders; i++) {
757 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
758 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
759 idx += shader_list[i]->num_builtins_to_link;
760 }
761
762 assert(idx == num_linking_shaders);
763
764 link_function_calls(prog, linked, linking_shaders, num_linking_shaders);
765
766 free(linking_shaders);
767
768 return linked;
769 }
770
771
772 struct uniform_node {
773 exec_node link;
774 struct gl_uniform *u;
775 unsigned slots;
776 };
777
778 void
779 assign_uniform_locations(struct gl_shader_program *prog)
780 {
781 /* */
782 exec_list uniforms;
783 unsigned total_uniforms = 0;
784 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
785 hash_table_string_compare);
786
787 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
788 unsigned next_position = 0;
789
790 foreach_list(node, prog->_LinkedShaders[i]->ir) {
791 ir_variable *const var = ((ir_instruction *) node)->as_variable();
792
793 if ((var == NULL) || (var->mode != ir_var_uniform))
794 continue;
795
796 if (var->type->is_sampler())
797 continue;
798
799 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
800 assert(vec4_slots != 0);
801
802 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
803 if (n == NULL) {
804 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
805 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
806 n->slots = vec4_slots;
807
808 n->u[0].Name = strdup(var->name);
809 for (unsigned j = 1; j < vec4_slots; j++)
810 n->u[j].Name = n->u[0].Name;
811
812 hash_table_insert(ht, n, n->u[0].Name);
813 uniforms.push_tail(& n->link);
814 total_uniforms += vec4_slots;
815 }
816
817 if (var->constant_value != NULL)
818 for (unsigned j = 0; j < vec4_slots; j++)
819 n->u[j].Initialized = true;
820
821 var->location = next_position;
822
823 for (unsigned j = 0; j < vec4_slots; j++) {
824 switch (prog->_LinkedShaders[i]->Type) {
825 case GL_VERTEX_SHADER:
826 n->u[j].VertPos = next_position;
827 break;
828 case GL_FRAGMENT_SHADER:
829 n->u[j].FragPos = next_position;
830 break;
831 case GL_GEOMETRY_SHADER:
832 /* FINISHME: Support geometry shaders. */
833 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
834 break;
835 }
836
837 next_position++;
838 }
839 }
840 }
841
842 gl_uniform_list *ul = (gl_uniform_list *)
843 calloc(1, sizeof(gl_uniform_list));
844
845 ul->Size = total_uniforms;
846 ul->NumUniforms = total_uniforms;
847 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
848
849 unsigned idx = 0;
850 uniform_node *next;
851 for (uniform_node *node = (uniform_node *) uniforms.head
852 ; node->link.next != NULL
853 ; node = next) {
854 next = (uniform_node *) node->link.next;
855
856 node->link.remove();
857 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
858 idx += node->slots;
859
860 free(node->u);
861 free(node);
862 }
863
864 hash_table_dtor(ht);
865
866 prog->Uniforms = ul;
867 }
868
869
870 /**
871 * Find a contiguous set of available bits in a bitmask
872 *
873 * \param used_mask Bits representing used (1) and unused (0) locations
874 * \param needed_count Number of contiguous bits needed.
875 *
876 * \return
877 * Base location of the available bits on success or -1 on failure.
878 */
879 int
880 find_available_slots(unsigned used_mask, unsigned needed_count)
881 {
882 unsigned needed_mask = (1 << needed_count) - 1;
883 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
884
885 /* The comparison to 32 is redundant, but without it GCC emits "warning:
886 * cannot optimize possibly infinite loops" for the loop below.
887 */
888 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
889 return -1;
890
891 for (int i = 0; i <= max_bit_to_test; i++) {
892 if ((needed_mask & ~used_mask) == needed_mask)
893 return i;
894
895 needed_mask <<= 1;
896 }
897
898 return -1;
899 }
900
901
902 bool
903 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
904 {
905 /* Mark invalid attribute locations as being used.
906 */
907 unsigned used_locations = (max_attribute_index >= 32)
908 ? ~0 : ~((1 << max_attribute_index) - 1);
909
910 gl_shader *const sh = prog->_LinkedShaders[0];
911 assert(sh->Type == GL_VERTEX_SHADER);
912
913 /* Operate in a total of four passes.
914 *
915 * 1. Invalidate the location assignments for all vertex shader inputs.
916 *
917 * 2. Assign locations for inputs that have user-defined (via
918 * glBindVertexAttribLocation) locatoins.
919 *
920 * 3. Sort the attributes without assigned locations by number of slots
921 * required in decreasing order. Fragmentation caused by attribute
922 * locations assigned by the application may prevent large attributes
923 * from having enough contiguous space.
924 *
925 * 4. Assign locations to any inputs without assigned locations.
926 */
927
928 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
929
930 if (prog->Attributes != NULL) {
931 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
932 ir_variable *const var =
933 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
934
935 /* Note: attributes that occupy multiple slots, such as arrays or
936 * matrices, may appear in the attrib array multiple times.
937 */
938 if ((var == NULL) || (var->location != -1))
939 continue;
940
941 /* From page 61 of the OpenGL 4.0 spec:
942 *
943 * "LinkProgram will fail if the attribute bindings assigned by
944 * BindAttribLocation do not leave not enough space to assign a
945 * location for an active matrix attribute or an active attribute
946 * array, both of which require multiple contiguous generic
947 * attributes."
948 *
949 * Previous versions of the spec contain similar language but omit the
950 * bit about attribute arrays.
951 *
952 * Page 61 of the OpenGL 4.0 spec also says:
953 *
954 * "It is possible for an application to bind more than one
955 * attribute name to the same location. This is referred to as
956 * aliasing. This will only work if only one of the aliased
957 * attributes is active in the executable program, or if no path
958 * through the shader consumes more than one attribute of a set
959 * of attributes aliased to the same location. A link error can
960 * occur if the linker determines that every path through the
961 * shader consumes multiple aliased attributes, but
962 * implementations are not required to generate an error in this
963 * case."
964 *
965 * These two paragraphs are either somewhat contradictory, or I don't
966 * fully understand one or both of them.
967 */
968 /* FINISHME: The code as currently written does not support attribute
969 * FINISHME: location aliasing (see comment above).
970 */
971 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
972 const unsigned slots = count_attribute_slots(var->type);
973
974 /* Mask representing the contiguous slots that will be used by this
975 * attribute.
976 */
977 const unsigned use_mask = (1 << slots) - 1;
978
979 /* Generate a link error if the set of bits requested for this
980 * attribute overlaps any previously allocated bits.
981 */
982 if ((~(use_mask << attr) & used_locations) != used_locations) {
983 linker_error_printf(prog,
984 "insufficient contiguous attribute locations "
985 "available for vertex shader input `%s'",
986 var->name);
987 return false;
988 }
989
990 var->location = VERT_ATTRIB_GENERIC0 + attr;
991 used_locations |= (use_mask << attr);
992 }
993 }
994
995 /* Temporary storage for the set of attributes that need locations assigned.
996 */
997 struct temp_attr {
998 unsigned slots;
999 ir_variable *var;
1000
1001 /* Used below in the call to qsort. */
1002 static int compare(const void *a, const void *b)
1003 {
1004 const temp_attr *const l = (const temp_attr *) a;
1005 const temp_attr *const r = (const temp_attr *) b;
1006
1007 /* Reversed because we want a descending order sort below. */
1008 return r->slots - l->slots;
1009 }
1010 } to_assign[16];
1011
1012 unsigned num_attr = 0;
1013
1014 foreach_list(node, sh->ir) {
1015 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1016
1017 if ((var == NULL) || (var->mode != ir_var_in))
1018 continue;
1019
1020 /* The location was explicitly assigned, nothing to do here.
1021 */
1022 if (var->location != -1)
1023 continue;
1024
1025 to_assign[num_attr].slots = count_attribute_slots(var->type);
1026 to_assign[num_attr].var = var;
1027 num_attr++;
1028 }
1029
1030 /* If all of the attributes were assigned locations by the application (or
1031 * are built-in attributes with fixed locations), return early. This should
1032 * be the common case.
1033 */
1034 if (num_attr == 0)
1035 return true;
1036
1037 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1038
1039 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1040 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1041 * to prevent it from being automatically allocated below.
1042 */
1043 used_locations |= (1 << 0);
1044
1045 for (unsigned i = 0; i < num_attr; i++) {
1046 /* Mask representing the contiguous slots that will be used by this
1047 * attribute.
1048 */
1049 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1050
1051 int location = find_available_slots(used_locations, to_assign[i].slots);
1052
1053 if (location < 0) {
1054 linker_error_printf(prog,
1055 "insufficient contiguous attribute locations "
1056 "available for vertex shader input `%s'",
1057 to_assign[i].var->name);
1058 return false;
1059 }
1060
1061 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1062 used_locations |= (use_mask << location);
1063 }
1064
1065 return true;
1066 }
1067
1068
1069 void
1070 assign_varying_locations(struct gl_shader_program *prog,
1071 gl_shader *producer, gl_shader *consumer)
1072 {
1073 /* FINISHME: Set dynamically when geometry shader support is added. */
1074 unsigned output_index = VERT_RESULT_VAR0;
1075 unsigned input_index = FRAG_ATTRIB_VAR0;
1076
1077 /* Operate in a total of three passes.
1078 *
1079 * 1. Assign locations for any matching inputs and outputs.
1080 *
1081 * 2. Mark output variables in the producer that do not have locations as
1082 * not being outputs. This lets the optimizer eliminate them.
1083 *
1084 * 3. Mark input variables in the consumer that do not have locations as
1085 * not being inputs. This lets the optimizer eliminate them.
1086 */
1087
1088 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1089 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1090
1091 foreach_list(node, producer->ir) {
1092 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1093
1094 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1095 || (output_var->location != -1))
1096 continue;
1097
1098 ir_variable *const input_var =
1099 consumer->symbols->get_variable(output_var->name);
1100
1101 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1102 continue;
1103
1104 assert(input_var->location == -1);
1105
1106 /* FINISHME: Location assignment will need some changes when arrays,
1107 * FINISHME: matrices, and structures are allowed as shader inputs /
1108 * FINISHME: outputs.
1109 */
1110 output_var->location = output_index;
1111 input_var->location = input_index;
1112
1113 output_index++;
1114 input_index++;
1115 }
1116
1117 foreach_list(node, producer->ir) {
1118 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1119
1120 if ((var == NULL) || (var->mode != ir_var_out))
1121 continue;
1122
1123 /* An 'out' variable is only really a shader output if its value is read
1124 * by the following stage.
1125 */
1126 if (var->location == -1) {
1127 var->mode = ir_var_auto;
1128 }
1129 }
1130
1131 foreach_list(node, consumer->ir) {
1132 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1133
1134 if ((var == NULL) || (var->mode != ir_var_in))
1135 continue;
1136
1137 if (var->location == -1) {
1138 if (prog->Version <= 120) {
1139 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1140 *
1141 * Only those varying variables used (i.e. read) in
1142 * the fragment shader executable must be written to
1143 * by the vertex shader executable; declaring
1144 * superfluous varying variables in a vertex shader is
1145 * permissible.
1146 *
1147 * We interpret this text as meaning that the VS must
1148 * write the variable for the FS to read it. See
1149 * "glsl1-varying read but not written" in piglit.
1150 */
1151
1152 linker_error_printf(prog, "fragment shader varying %s not written "
1153 "by vertex shader\n.", var->name);
1154 prog->LinkStatus = false;
1155 }
1156
1157 /* An 'in' variable is only really a shader input if its
1158 * value is written by the previous stage.
1159 */
1160 var->mode = ir_var_auto;
1161 }
1162 }
1163 }
1164
1165
1166 void
1167 link_shaders(struct gl_shader_program *prog)
1168 {
1169 prog->LinkStatus = false;
1170 prog->Validated = false;
1171 prog->_Used = false;
1172
1173 if (prog->InfoLog != NULL)
1174 talloc_free(prog->InfoLog);
1175
1176 prog->InfoLog = talloc_strdup(NULL, "");
1177
1178 /* Separate the shaders into groups based on their type.
1179 */
1180 struct gl_shader **vert_shader_list;
1181 unsigned num_vert_shaders = 0;
1182 struct gl_shader **frag_shader_list;
1183 unsigned num_frag_shaders = 0;
1184
1185 vert_shader_list = (struct gl_shader **)
1186 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1187 frag_shader_list = &vert_shader_list[prog->NumShaders];
1188
1189 unsigned min_version = UINT_MAX;
1190 unsigned max_version = 0;
1191 for (unsigned i = 0; i < prog->NumShaders; i++) {
1192 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1193 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1194
1195 switch (prog->Shaders[i]->Type) {
1196 case GL_VERTEX_SHADER:
1197 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1198 num_vert_shaders++;
1199 break;
1200 case GL_FRAGMENT_SHADER:
1201 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1202 num_frag_shaders++;
1203 break;
1204 case GL_GEOMETRY_SHADER:
1205 /* FINISHME: Support geometry shaders. */
1206 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1207 break;
1208 }
1209 }
1210
1211 /* Previous to GLSL version 1.30, different compilation units could mix and
1212 * match shading language versions. With GLSL 1.30 and later, the versions
1213 * of all shaders must match.
1214 */
1215 assert(min_version >= 110);
1216 assert(max_version <= 130);
1217 if ((max_version >= 130) && (min_version != max_version)) {
1218 linker_error_printf(prog, "all shaders must use same shading "
1219 "language version\n");
1220 goto done;
1221 }
1222
1223 prog->Version = max_version;
1224
1225 /* Link all shaders for a particular stage and validate the result.
1226 */
1227 prog->_NumLinkedShaders = 0;
1228 if (num_vert_shaders > 0) {
1229 gl_shader *const sh =
1230 link_intrastage_shaders(prog, vert_shader_list, num_vert_shaders);
1231
1232 if (sh == NULL)
1233 goto done;
1234
1235 if (!validate_vertex_shader_executable(prog, sh))
1236 goto done;
1237
1238 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1239 prog->_NumLinkedShaders++;
1240 }
1241
1242 if (num_frag_shaders > 0) {
1243 gl_shader *const sh =
1244 link_intrastage_shaders(prog, frag_shader_list, num_frag_shaders);
1245
1246 if (sh == NULL)
1247 goto done;
1248
1249 if (!validate_fragment_shader_executable(prog, sh))
1250 goto done;
1251
1252 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1253 prog->_NumLinkedShaders++;
1254 }
1255
1256 /* Here begins the inter-stage linking phase. Some initial validation is
1257 * performed, then locations are assigned for uniforms, attributes, and
1258 * varyings.
1259 */
1260 if (cross_validate_uniforms(prog)) {
1261 /* Validate the inputs of each stage with the output of the preceeding
1262 * stage.
1263 */
1264 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
1265 if (!cross_validate_outputs_to_inputs(prog,
1266 prog->_LinkedShaders[i - 1],
1267 prog->_LinkedShaders[i]))
1268 goto done;
1269 }
1270
1271 prog->LinkStatus = true;
1272 }
1273
1274 /* FINISHME: Perform whole-program optimization here. */
1275 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
1276 /* Optimization passes */
1277 bool progress;
1278 exec_list *ir = prog->_LinkedShaders[i]->ir;
1279
1280 /* Lowering */
1281 do_mat_op_to_vec(ir);
1282 do_mod_to_fract(ir);
1283 do_div_to_mul_rcp(ir);
1284
1285 do {
1286 progress = false;
1287
1288 progress = do_function_inlining(ir) || progress;
1289 progress = do_dead_functions(ir) || progress;
1290 progress = do_structure_splitting(ir) || progress;
1291 progress = do_if_simplification(ir) || progress;
1292 progress = do_copy_propagation(ir) || progress;
1293 progress = do_dead_code_local(ir) || progress;
1294 progress = do_dead_code(ir) || progress;
1295 progress = do_tree_grafting(ir) || progress;
1296 progress = do_constant_variable(ir) || progress;
1297 progress = do_constant_folding(ir) || progress;
1298 progress = do_algebraic(ir) || progress;
1299 progress = do_if_return(ir) || progress;
1300 #if 0
1301 if (ctx->Shader.EmitNoIfs)
1302 progress = do_if_to_cond_assign(ir) || progress;
1303 #endif
1304
1305 progress = do_vec_index_to_swizzle(ir) || progress;
1306 /* Do this one after the previous to let the easier pass handle
1307 * constant vector indexing.
1308 */
1309 progress = do_vec_index_to_cond_assign(ir) || progress;
1310
1311 progress = do_swizzle_swizzle(ir) || progress;
1312 } while (progress);
1313 }
1314
1315 assign_uniform_locations(prog);
1316
1317 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
1318 /* FINISHME: The value of the max_attribute_index parameter is
1319 * FINISHME: implementation dependent based on the value of
1320 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1321 * FINISHME: at least 16, so hardcode 16 for now.
1322 */
1323 if (!assign_attribute_locations(prog, 16))
1324 goto done;
1325
1326 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
1327 assign_varying_locations(prog,
1328 prog->_LinkedShaders[i - 1],
1329 prog->_LinkedShaders[i]);
1330
1331 /* FINISHME: Assign fragment shader output locations. */
1332
1333 done:
1334 free(vert_shader_list);
1335 }