glsl2: Add constant propagation.
[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 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
797 if (vec4_slots == 0) {
798 /* If we've got a sampler or an aggregate of them, the size can
799 * end up zero. Don't allocate any space.
800 */
801 continue;
802 }
803
804 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
805 if (n == NULL) {
806 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
807 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
808 n->slots = vec4_slots;
809
810 n->u[0].Name = strdup(var->name);
811 for (unsigned j = 1; j < vec4_slots; j++)
812 n->u[j].Name = n->u[0].Name;
813
814 hash_table_insert(ht, n, n->u[0].Name);
815 uniforms.push_tail(& n->link);
816 total_uniforms += vec4_slots;
817 }
818
819 if (var->constant_value != NULL)
820 for (unsigned j = 0; j < vec4_slots; j++)
821 n->u[j].Initialized = true;
822
823 var->location = next_position;
824
825 for (unsigned j = 0; j < vec4_slots; j++) {
826 switch (prog->_LinkedShaders[i]->Type) {
827 case GL_VERTEX_SHADER:
828 n->u[j].VertPos = next_position;
829 break;
830 case GL_FRAGMENT_SHADER:
831 n->u[j].FragPos = next_position;
832 break;
833 case GL_GEOMETRY_SHADER:
834 /* FINISHME: Support geometry shaders. */
835 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
836 break;
837 }
838
839 next_position++;
840 }
841 }
842 }
843
844 gl_uniform_list *ul = (gl_uniform_list *)
845 calloc(1, sizeof(gl_uniform_list));
846
847 ul->Size = total_uniforms;
848 ul->NumUniforms = total_uniforms;
849 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
850
851 unsigned idx = 0;
852 uniform_node *next;
853 for (uniform_node *node = (uniform_node *) uniforms.head
854 ; node->link.next != NULL
855 ; node = next) {
856 next = (uniform_node *) node->link.next;
857
858 node->link.remove();
859 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
860 idx += node->slots;
861
862 free(node->u);
863 free(node);
864 }
865
866 hash_table_dtor(ht);
867
868 prog->Uniforms = ul;
869 }
870
871
872 /**
873 * Find a contiguous set of available bits in a bitmask
874 *
875 * \param used_mask Bits representing used (1) and unused (0) locations
876 * \param needed_count Number of contiguous bits needed.
877 *
878 * \return
879 * Base location of the available bits on success or -1 on failure.
880 */
881 int
882 find_available_slots(unsigned used_mask, unsigned needed_count)
883 {
884 unsigned needed_mask = (1 << needed_count) - 1;
885 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
886
887 /* The comparison to 32 is redundant, but without it GCC emits "warning:
888 * cannot optimize possibly infinite loops" for the loop below.
889 */
890 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
891 return -1;
892
893 for (int i = 0; i <= max_bit_to_test; i++) {
894 if ((needed_mask & ~used_mask) == needed_mask)
895 return i;
896
897 needed_mask <<= 1;
898 }
899
900 return -1;
901 }
902
903
904 bool
905 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
906 {
907 /* Mark invalid attribute locations as being used.
908 */
909 unsigned used_locations = (max_attribute_index >= 32)
910 ? ~0 : ~((1 << max_attribute_index) - 1);
911
912 gl_shader *const sh = prog->_LinkedShaders[0];
913 assert(sh->Type == GL_VERTEX_SHADER);
914
915 /* Operate in a total of four passes.
916 *
917 * 1. Invalidate the location assignments for all vertex shader inputs.
918 *
919 * 2. Assign locations for inputs that have user-defined (via
920 * glBindVertexAttribLocation) locatoins.
921 *
922 * 3. Sort the attributes without assigned locations by number of slots
923 * required in decreasing order. Fragmentation caused by attribute
924 * locations assigned by the application may prevent large attributes
925 * from having enough contiguous space.
926 *
927 * 4. Assign locations to any inputs without assigned locations.
928 */
929
930 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
931
932 if (prog->Attributes != NULL) {
933 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
934 ir_variable *const var =
935 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
936
937 /* Note: attributes that occupy multiple slots, such as arrays or
938 * matrices, may appear in the attrib array multiple times.
939 */
940 if ((var == NULL) || (var->location != -1))
941 continue;
942
943 /* From page 61 of the OpenGL 4.0 spec:
944 *
945 * "LinkProgram will fail if the attribute bindings assigned by
946 * BindAttribLocation do not leave not enough space to assign a
947 * location for an active matrix attribute or an active attribute
948 * array, both of which require multiple contiguous generic
949 * attributes."
950 *
951 * Previous versions of the spec contain similar language but omit the
952 * bit about attribute arrays.
953 *
954 * Page 61 of the OpenGL 4.0 spec also says:
955 *
956 * "It is possible for an application to bind more than one
957 * attribute name to the same location. This is referred to as
958 * aliasing. This will only work if only one of the aliased
959 * attributes is active in the executable program, or if no path
960 * through the shader consumes more than one attribute of a set
961 * of attributes aliased to the same location. A link error can
962 * occur if the linker determines that every path through the
963 * shader consumes multiple aliased attributes, but
964 * implementations are not required to generate an error in this
965 * case."
966 *
967 * These two paragraphs are either somewhat contradictory, or I don't
968 * fully understand one or both of them.
969 */
970 /* FINISHME: The code as currently written does not support attribute
971 * FINISHME: location aliasing (see comment above).
972 */
973 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
974 const unsigned slots = count_attribute_slots(var->type);
975
976 /* Mask representing the contiguous slots that will be used by this
977 * attribute.
978 */
979 const unsigned use_mask = (1 << slots) - 1;
980
981 /* Generate a link error if the set of bits requested for this
982 * attribute overlaps any previously allocated bits.
983 */
984 if ((~(use_mask << attr) & used_locations) != used_locations) {
985 linker_error_printf(prog,
986 "insufficient contiguous attribute locations "
987 "available for vertex shader input `%s'",
988 var->name);
989 return false;
990 }
991
992 var->location = VERT_ATTRIB_GENERIC0 + attr;
993 used_locations |= (use_mask << attr);
994 }
995 }
996
997 /* Temporary storage for the set of attributes that need locations assigned.
998 */
999 struct temp_attr {
1000 unsigned slots;
1001 ir_variable *var;
1002
1003 /* Used below in the call to qsort. */
1004 static int compare(const void *a, const void *b)
1005 {
1006 const temp_attr *const l = (const temp_attr *) a;
1007 const temp_attr *const r = (const temp_attr *) b;
1008
1009 /* Reversed because we want a descending order sort below. */
1010 return r->slots - l->slots;
1011 }
1012 } to_assign[16];
1013
1014 unsigned num_attr = 0;
1015
1016 foreach_list(node, sh->ir) {
1017 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1018
1019 if ((var == NULL) || (var->mode != ir_var_in))
1020 continue;
1021
1022 /* The location was explicitly assigned, nothing to do here.
1023 */
1024 if (var->location != -1)
1025 continue;
1026
1027 to_assign[num_attr].slots = count_attribute_slots(var->type);
1028 to_assign[num_attr].var = var;
1029 num_attr++;
1030 }
1031
1032 /* If all of the attributes were assigned locations by the application (or
1033 * are built-in attributes with fixed locations), return early. This should
1034 * be the common case.
1035 */
1036 if (num_attr == 0)
1037 return true;
1038
1039 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1040
1041 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1042 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1043 * to prevent it from being automatically allocated below.
1044 */
1045 used_locations |= (1 << 0);
1046
1047 for (unsigned i = 0; i < num_attr; i++) {
1048 /* Mask representing the contiguous slots that will be used by this
1049 * attribute.
1050 */
1051 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1052
1053 int location = find_available_slots(used_locations, to_assign[i].slots);
1054
1055 if (location < 0) {
1056 linker_error_printf(prog,
1057 "insufficient contiguous attribute locations "
1058 "available for vertex shader input `%s'",
1059 to_assign[i].var->name);
1060 return false;
1061 }
1062
1063 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1064 used_locations |= (use_mask << location);
1065 }
1066
1067 return true;
1068 }
1069
1070
1071 void
1072 assign_varying_locations(struct gl_shader_program *prog,
1073 gl_shader *producer, gl_shader *consumer)
1074 {
1075 /* FINISHME: Set dynamically when geometry shader support is added. */
1076 unsigned output_index = VERT_RESULT_VAR0;
1077 unsigned input_index = FRAG_ATTRIB_VAR0;
1078
1079 /* Operate in a total of three passes.
1080 *
1081 * 1. Assign locations for any matching inputs and outputs.
1082 *
1083 * 2. Mark output variables in the producer that do not have locations as
1084 * not being outputs. This lets the optimizer eliminate them.
1085 *
1086 * 3. Mark input variables in the consumer that do not have locations as
1087 * not being inputs. This lets the optimizer eliminate them.
1088 */
1089
1090 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1091 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1092
1093 foreach_list(node, producer->ir) {
1094 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1095
1096 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1097 || (output_var->location != -1))
1098 continue;
1099
1100 ir_variable *const input_var =
1101 consumer->symbols->get_variable(output_var->name);
1102
1103 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1104 continue;
1105
1106 assert(input_var->location == -1);
1107
1108 /* FINISHME: Location assignment will need some changes when arrays,
1109 * FINISHME: matrices, and structures are allowed as shader inputs /
1110 * FINISHME: outputs.
1111 */
1112 output_var->location = output_index;
1113 input_var->location = input_index;
1114
1115 output_index++;
1116 input_index++;
1117 }
1118
1119 foreach_list(node, producer->ir) {
1120 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1121
1122 if ((var == NULL) || (var->mode != ir_var_out))
1123 continue;
1124
1125 /* An 'out' variable is only really a shader output if its value is read
1126 * by the following stage.
1127 */
1128 if (var->location == -1) {
1129 var->mode = ir_var_auto;
1130 }
1131 }
1132
1133 foreach_list(node, consumer->ir) {
1134 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1135
1136 if ((var == NULL) || (var->mode != ir_var_in))
1137 continue;
1138
1139 if (var->location == -1) {
1140 if (prog->Version <= 120) {
1141 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1142 *
1143 * Only those varying variables used (i.e. read) in
1144 * the fragment shader executable must be written to
1145 * by the vertex shader executable; declaring
1146 * superfluous varying variables in a vertex shader is
1147 * permissible.
1148 *
1149 * We interpret this text as meaning that the VS must
1150 * write the variable for the FS to read it. See
1151 * "glsl1-varying read but not written" in piglit.
1152 */
1153
1154 linker_error_printf(prog, "fragment shader varying %s not written "
1155 "by vertex shader\n.", var->name);
1156 prog->LinkStatus = false;
1157 }
1158
1159 /* An 'in' variable is only really a shader input if its
1160 * value is written by the previous stage.
1161 */
1162 var->mode = ir_var_auto;
1163 }
1164 }
1165 }
1166
1167
1168 void
1169 link_shaders(struct gl_shader_program *prog)
1170 {
1171 prog->LinkStatus = false;
1172 prog->Validated = false;
1173 prog->_Used = false;
1174
1175 if (prog->InfoLog != NULL)
1176 talloc_free(prog->InfoLog);
1177
1178 prog->InfoLog = talloc_strdup(NULL, "");
1179
1180 /* Separate the shaders into groups based on their type.
1181 */
1182 struct gl_shader **vert_shader_list;
1183 unsigned num_vert_shaders = 0;
1184 struct gl_shader **frag_shader_list;
1185 unsigned num_frag_shaders = 0;
1186
1187 vert_shader_list = (struct gl_shader **)
1188 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1189 frag_shader_list = &vert_shader_list[prog->NumShaders];
1190
1191 unsigned min_version = UINT_MAX;
1192 unsigned max_version = 0;
1193 for (unsigned i = 0; i < prog->NumShaders; i++) {
1194 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1195 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1196
1197 switch (prog->Shaders[i]->Type) {
1198 case GL_VERTEX_SHADER:
1199 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1200 num_vert_shaders++;
1201 break;
1202 case GL_FRAGMENT_SHADER:
1203 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1204 num_frag_shaders++;
1205 break;
1206 case GL_GEOMETRY_SHADER:
1207 /* FINISHME: Support geometry shaders. */
1208 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1209 break;
1210 }
1211 }
1212
1213 /* Previous to GLSL version 1.30, different compilation units could mix and
1214 * match shading language versions. With GLSL 1.30 and later, the versions
1215 * of all shaders must match.
1216 */
1217 assert(min_version >= 110);
1218 assert(max_version <= 130);
1219 if ((max_version >= 130) && (min_version != max_version)) {
1220 linker_error_printf(prog, "all shaders must use same shading "
1221 "language version\n");
1222 goto done;
1223 }
1224
1225 prog->Version = max_version;
1226
1227 /* Link all shaders for a particular stage and validate the result.
1228 */
1229 prog->_NumLinkedShaders = 0;
1230 if (num_vert_shaders > 0) {
1231 gl_shader *const sh =
1232 link_intrastage_shaders(prog, vert_shader_list, num_vert_shaders);
1233
1234 if (sh == NULL)
1235 goto done;
1236
1237 if (!validate_vertex_shader_executable(prog, sh))
1238 goto done;
1239
1240 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1241 prog->_NumLinkedShaders++;
1242 }
1243
1244 if (num_frag_shaders > 0) {
1245 gl_shader *const sh =
1246 link_intrastage_shaders(prog, frag_shader_list, num_frag_shaders);
1247
1248 if (sh == NULL)
1249 goto done;
1250
1251 if (!validate_fragment_shader_executable(prog, sh))
1252 goto done;
1253
1254 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1255 prog->_NumLinkedShaders++;
1256 }
1257
1258 /* Here begins the inter-stage linking phase. Some initial validation is
1259 * performed, then locations are assigned for uniforms, attributes, and
1260 * varyings.
1261 */
1262 if (cross_validate_uniforms(prog)) {
1263 /* Validate the inputs of each stage with the output of the preceeding
1264 * stage.
1265 */
1266 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
1267 if (!cross_validate_outputs_to_inputs(prog,
1268 prog->_LinkedShaders[i - 1],
1269 prog->_LinkedShaders[i]))
1270 goto done;
1271 }
1272
1273 prog->LinkStatus = true;
1274 }
1275
1276 /* FINISHME: Perform whole-program optimization here. */
1277 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
1278 /* Optimization passes */
1279 bool progress;
1280 exec_list *ir = prog->_LinkedShaders[i]->ir;
1281
1282 /* Lowering */
1283 do_mat_op_to_vec(ir);
1284 do_mod_to_fract(ir);
1285 do_div_to_mul_rcp(ir);
1286 do_explog_to_explog2(ir);
1287
1288 do {
1289 progress = false;
1290
1291 progress = do_function_inlining(ir) || progress;
1292 progress = do_dead_functions(ir) || progress;
1293 progress = do_structure_splitting(ir) || progress;
1294 progress = do_if_simplification(ir) || progress;
1295 progress = do_copy_propagation(ir) || progress;
1296 progress = do_dead_code_local(ir) || progress;
1297 progress = do_dead_code(ir) || progress;
1298 progress = do_tree_grafting(ir) || progress;
1299 progress = do_constant_propagation(ir) || progress;
1300 progress = do_constant_variable(ir) || progress;
1301 progress = do_constant_folding(ir) || progress;
1302 progress = do_algebraic(ir) || progress;
1303 progress = do_if_return(ir) || progress;
1304 #if 0
1305 if (ctx->Shader.EmitNoIfs)
1306 progress = do_if_to_cond_assign(ir) || progress;
1307 #endif
1308
1309 progress = do_vec_index_to_swizzle(ir) || progress;
1310 /* Do this one after the previous to let the easier pass handle
1311 * constant vector indexing.
1312 */
1313 progress = do_vec_index_to_cond_assign(ir) || progress;
1314
1315 progress = do_swizzle_swizzle(ir) || progress;
1316 } while (progress);
1317 }
1318
1319 assign_uniform_locations(prog);
1320
1321 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
1322 /* FINISHME: The value of the max_attribute_index parameter is
1323 * FINISHME: implementation dependent based on the value of
1324 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1325 * FINISHME: at least 16, so hardcode 16 for now.
1326 */
1327 if (!assign_attribute_locations(prog, 16))
1328 goto done;
1329
1330 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
1331 assign_varying_locations(prog,
1332 prog->_LinkedShaders[i - 1],
1333 prog->_LinkedShaders[i]);
1334
1335 /* FINISHME: Assign fragment shader output locations. */
1336
1337 done:
1338 free(vert_shader_list);
1339 }