blob: 11deeed5930e6a2a9ff5df160c8637d79c7c5d27 [file] [log] [blame]
Ian Romanick832dfa52010-06-17 15:04:20 -07001/*
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>
Ian Romanickf36460e2010-06-23 12:07:22 -070068#include <cstdarg>
69
70extern "C" {
71#include <talloc.h>
72}
Ian Romanick832dfa52010-06-17 15:04:20 -070073
Ian Romanick0ad22cd2010-06-21 17:18:31 -070074#include "main/mtypes.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070075#include "glsl_symbol_table.h"
76#include "glsl_parser_extras.h"
77#include "ir.h"
Ian Romanick019a59b2010-06-21 16:10:42 -070078#include "ir_optimization.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070079#include "program.h"
Ian Romanick019a59b2010-06-21 16:10:42 -070080#include "hash_table.h"
Ian Romanick3fb87872010-07-09 14:09:34 -070081#include "shader_api.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070082
83/**
84 * Visitor that determines whether or not a variable is ever written.
85 */
86class find_assignment_visitor : public ir_hierarchical_visitor {
87public:
88 find_assignment_visitor(const char *name)
89 : name(name), found(false)
90 {
91 /* empty */
92 }
93
94 virtual ir_visitor_status visit_enter(ir_assignment *ir)
95 {
96 ir_variable *const var = ir->lhs->variable_referenced();
97
98 if (strcmp(name, var->name) == 0) {
99 found = true;
100 return visit_stop;
101 }
102
103 return visit_continue_with_parent;
104 }
105
106 bool variable_found()
107 {
108 return found;
109 }
110
111private:
112 const char *name; /**< Find writes to a variable with this name. */
113 bool found; /**< Was a write to the variable found? */
114};
115
Ian Romanickc93b8f12010-06-17 15:20:22 -0700116
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700117void
Eric Anholt849e1812010-06-30 11:49:17 -0700118linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700119{
120 va_list ap;
121
122 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
123 va_start(ap, fmt);
124 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
125 va_end(ap);
126}
127
128
129void
Eric Anholt16b68b12010-06-30 11:05:43 -0700130invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700131 int generic_base)
132{
Eric Anholt16b68b12010-06-30 11:05:43 -0700133 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700134 ir_variable *const var = ((ir_instruction *) node)->as_variable();
135
136 if ((var == NULL) || (var->mode != (unsigned) mode))
137 continue;
138
139 /* Only assign locations for generic attributes / varyings / etc.
140 */
141 if (var->location >= generic_base)
142 var->location = -1;
143 }
144}
145
146
Ian Romanickc93b8f12010-06-17 15:20:22 -0700147/**
Ian Romanick69846702010-06-22 17:29:19 -0700148 * Determine the number of attribute slots required for a particular type
149 *
150 * This code is here because it implements the language rules of a specific
151 * GLSL version. Since it's a property of the language and not a property of
152 * types in general, it doesn't really belong in glsl_type.
153 */
154unsigned
155count_attribute_slots(const glsl_type *t)
156{
157 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
158 *
159 * "A scalar input counts the same amount against this limit as a vec4,
160 * so applications may want to consider packing groups of four
161 * unrelated float inputs together into a vector to better utilize the
162 * capabilities of the underlying hardware. A matrix input will use up
163 * multiple locations. The number of locations used will equal the
164 * number of columns in the matrix."
165 *
166 * The spec does not explicitly say how arrays are counted. However, it
167 * should be safe to assume the total number of slots consumed by an array
168 * is the number of entries in the array multiplied by the number of slots
169 * consumed by a single element of the array.
170 */
171
172 if (t->is_array())
173 return t->array_size() * count_attribute_slots(t->element_type());
174
175 if (t->is_matrix())
176 return t->matrix_columns;
177
178 return 1;
179}
180
181
182/**
Ian Romanickc93b8f12010-06-17 15:20:22 -0700183 * Verify that a vertex shader executable meets all semantic requirements
184 *
185 * \param shader Vertex shader executable to be verified
186 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700187bool
Eric Anholt849e1812010-06-30 11:49:17 -0700188validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700189 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700190{
191 if (shader == NULL)
192 return true;
193
194 if (!shader->symbols->get_function("main")) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700195 linker_error_printf(prog, "vertex shader lacks `main'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700196 return false;
197 }
198
199 find_assignment_visitor find("gl_Position");
Eric Anholt16b68b12010-06-30 11:05:43 -0700200 find.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700201 if (!find.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700202 linker_error_printf(prog,
203 "vertex shader does not write to `gl_Position'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700204 return false;
205 }
206
207 return true;
208}
209
210
Ian Romanickc93b8f12010-06-17 15:20:22 -0700211/**
212 * Verify that a fragment shader executable meets all semantic requirements
213 *
214 * \param shader Fragment shader executable to be verified
215 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700216bool
Eric Anholt849e1812010-06-30 11:49:17 -0700217validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700218 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700219{
220 if (shader == NULL)
221 return true;
222
223 if (!shader->symbols->get_function("main")) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700224 linker_error_printf(prog, "fragment shader lacks `main'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700225 return false;
226 }
227
228 find_assignment_visitor frag_color("gl_FragColor");
229 find_assignment_visitor frag_data("gl_FragData");
230
Eric Anholt16b68b12010-06-30 11:05:43 -0700231 frag_color.run(shader->ir);
232 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700233
Ian Romanick832dfa52010-06-17 15:04:20 -0700234 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700235 linker_error_printf(prog, "fragment shader writes to both "
236 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700237 return false;
238 }
239
240 return true;
241}
242
243
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700244/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700245 * Generate a string describing the mode of a variable
246 */
247static const char *
248mode_string(const ir_variable *var)
249{
250 switch (var->mode) {
251 case ir_var_auto:
252 return (var->read_only) ? "global constant" : "global variable";
253
254 case ir_var_uniform: return "uniform";
255 case ir_var_in: return "shader input";
256 case ir_var_out: return "shader output";
257 case ir_var_inout: return "shader inout";
258 default:
259 assert(!"Should not get here.");
260 return "invalid variable";
261 }
262}
263
264
265/**
266 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700267 */
268bool
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700269cross_validate_globals(struct gl_shader_program *prog,
270 struct gl_shader **shader_list,
271 unsigned num_shaders,
272 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700273{
274 /* Examine all of the uniforms in all of the shaders and cross validate
275 * them.
276 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700277 glsl_symbol_table variables;
278 for (unsigned i = 0; i < num_shaders; i++) {
279 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700280 ir_variable *const var = ((ir_instruction *) node)->as_variable();
281
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700282 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700283 continue;
284
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700285 if (uniforms_only && (var->mode != ir_var_uniform))
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
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700290 * initializers, the values of the initializers must be the same.
291 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700292 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700293 if (existing != NULL) {
294 if (var->type != existing->type) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700295 linker_error_printf(prog, "%s `%s' declared as type "
Ian Romanickf36460e2010-06-23 12:07:22 -0700296 "`%s' and type `%s'\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700297 mode_string(var),
Ian Romanickf36460e2010-06-23 12:07:22 -0700298 var->name, var->type->name,
299 existing->type->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700300 return false;
301 }
302
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700303 /* FINISHME: Handle non-constant initializers.
304 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700305 if (var->constant_value != NULL) {
306 if (existing->constant_value != NULL) {
307 if (!var->constant_value->has_value(existing->constant_value)) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700308 linker_error_printf(prog, "initializers for %s "
Ian Romanickf36460e2010-06-23 12:07:22 -0700309 "`%s' have differing values\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700310 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700311 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 */
Eric Anholt4b6fd392010-06-23 11:37:12 -0700318 existing->constant_value =
319 (ir_constant *)var->constant_value->clone(NULL);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700320 }
321 } else
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700322 variables.add_variable(var->name, var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700323 }
324 }
325
326 return true;
327}
328
329
Ian Romanick37101922010-06-18 19:02:10 -0700330/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700331 * Perform validation of uniforms used across multiple shader stages
332 */
333bool
334cross_validate_uniforms(struct gl_shader_program *prog)
335{
336 return cross_validate_globals(prog, prog->_LinkedShaders,
337 prog->_NumLinkedShaders, true);
338}
339
340
341/**
Ian Romanick37101922010-06-18 19:02:10 -0700342 * Validate that outputs from one stage match inputs of another
343 */
344bool
Eric Anholt849e1812010-06-30 11:49:17 -0700345cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700346 gl_shader *producer, gl_shader *consumer)
Ian Romanick37101922010-06-18 19:02:10 -0700347{
348 glsl_symbol_table parameters;
349 /* FINISHME: Figure these out dynamically. */
350 const char *const producer_stage = "vertex";
351 const char *const consumer_stage = "fragment";
352
353 /* Find all shader outputs in the "producer" stage.
354 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700355 foreach_list(node, producer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700356 ir_variable *const var = ((ir_instruction *) node)->as_variable();
357
358 /* FINISHME: For geometry shaders, this should also look for inout
359 * FINISHME: variables.
360 */
361 if ((var == NULL) || (var->mode != ir_var_out))
362 continue;
363
364 parameters.add_variable(var->name, var);
365 }
366
367
368 /* Find all shader inputs in the "consumer" stage. Any variables that have
369 * matching outputs already in the symbol table must have the same type and
370 * qualifiers.
371 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700372 foreach_list(node, consumer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700373 ir_variable *const input = ((ir_instruction *) node)->as_variable();
374
375 /* FINISHME: For geometry shaders, this should also look for inout
376 * FINISHME: variables.
377 */
378 if ((input == NULL) || (input->mode != ir_var_in))
379 continue;
380
381 ir_variable *const output = parameters.get_variable(input->name);
382 if (output != NULL) {
383 /* Check that the types match between stages.
384 */
385 if (input->type != output->type) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700386 linker_error_printf(prog,
387 "%s shader output `%s' delcared as "
388 "type `%s', but %s shader input declared "
389 "as type `%s'\n",
390 producer_stage, output->name,
391 output->type->name,
392 consumer_stage, input->type->name);
Ian Romanick37101922010-06-18 19:02:10 -0700393 return false;
394 }
395
396 /* Check that all of the qualifiers match between stages.
397 */
398 if (input->centroid != output->centroid) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700399 linker_error_printf(prog,
400 "%s shader output `%s' %s centroid qualifier, "
401 "but %s shader input %s centroid qualifier\n",
402 producer_stage,
403 output->name,
404 (output->centroid) ? "has" : "lacks",
405 consumer_stage,
406 (input->centroid) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700407 return false;
408 }
409
410 if (input->invariant != output->invariant) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700411 linker_error_printf(prog,
412 "%s shader output `%s' %s invariant qualifier, "
413 "but %s shader input %s invariant qualifier\n",
414 producer_stage,
415 output->name,
416 (output->invariant) ? "has" : "lacks",
417 consumer_stage,
418 (input->invariant) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700419 return false;
420 }
421
422 if (input->interpolation != output->interpolation) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700423 linker_error_printf(prog,
424 "%s shader output `%s' specifies %s "
425 "interpolation qualifier, "
426 "but %s shader input specifies %s "
427 "interpolation qualifier\n",
428 producer_stage,
429 output->name,
430 output->interpolation_string(),
431 consumer_stage,
432 input->interpolation_string());
Ian Romanick37101922010-06-18 19:02:10 -0700433 return false;
434 }
435 }
436 }
437
438 return true;
439}
440
441
Ian Romanick3fb87872010-07-09 14:09:34 -0700442/**
443 * Populates a shaders symbol table with all global declarations
444 */
445static void
446populate_symbol_table(gl_shader *sh)
447{
448 sh->symbols = new(sh) glsl_symbol_table;
449
450 foreach_list(node, sh->ir) {
451 ir_instruction *const inst = (ir_instruction *) node;
452 ir_variable *var;
453 ir_function *func;
454
455 if ((func = inst->as_function()) != NULL) {
456 sh->symbols->add_function(func->name, func);
457 } else if ((var = inst->as_variable()) != NULL) {
458 sh->symbols->add_variable(var->name, var);
459 }
460 }
461}
462
463
464/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700465 * Get the function signature for main from a shader
466 */
467static ir_function_signature *
468get_main_function_signature(gl_shader *sh)
469{
470 ir_function *const f = sh->symbols->get_function("main");
471 if (f != NULL) {
472 exec_list void_parameters;
473
474 /* Look for the 'void main()' signature and ensure that it's defined.
475 * This keeps the linker from accidentally pick a shader that just
476 * contains a prototype for main.
477 *
478 * We don't have to check for multiple definitions of main (in multiple
479 * shaders) because that would have already been caught above.
480 */
481 ir_function_signature *sig = f->matching_signature(&void_parameters);
482 if ((sig != NULL) && sig->is_defined) {
483 return sig;
484 }
485 }
486
487 return NULL;
488}
489
490
491/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700492 * Combine a group of shaders for a single stage to generate a linked shader
493 *
494 * \note
495 * If this function is supplied a single shader, it is cloned, and the new
496 * shader is returned.
497 */
498static struct gl_shader *
499link_intrastage_shaders(struct gl_shader_program *prog,
500 struct gl_shader **shader_list,
501 unsigned num_shaders)
502{
Ian Romanick13f782c2010-06-29 18:53:38 -0700503 /* Check that global variables defined in multiple shaders are consistent.
504 */
505 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
506 return NULL;
507
508 /* Check that there is only a single definition of each function signature
509 * across all shaders.
510 */
511 for (unsigned i = 0; i < (num_shaders - 1); i++) {
512 foreach_list(node, shader_list[i]->ir) {
513 ir_function *const f = ((ir_instruction *) node)->as_function();
514
515 if (f == NULL)
516 continue;
517
518 for (unsigned j = i + 1; j < num_shaders; j++) {
519 ir_function *const other =
520 shader_list[j]->symbols->get_function(f->name);
521
522 /* If the other shader has no function (and therefore no function
523 * signatures) with the same name, skip to the next shader.
524 */
525 if (other == NULL)
526 continue;
527
528 foreach_iter (exec_list_iterator, iter, *f) {
529 ir_function_signature *sig =
530 (ir_function_signature *) iter.get();
531
532 if (!sig->is_defined || sig->is_built_in)
533 continue;
534
535 ir_function_signature *other_sig =
536 other->exact_matching_signature(& sig->parameters);
537
538 if ((other_sig != NULL) && other_sig->is_defined
539 && !other_sig->is_built_in) {
540 linker_error_printf(prog,
541 "function `%s' is multiply defined",
542 f->name);
543 return NULL;
544 }
545 }
546 }
547 }
548 }
549
550 /* Find the shader that defines main, and make a clone of it.
551 *
552 * Starting with the clone, search for undefined references. If one is
553 * found, find the shader that defines it. Clone the reference and add
554 * it to the shader. Repeat until there are no undefined references or
555 * until a reference cannot be resolved.
556 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700557 gl_shader *main = NULL;
558 for (unsigned i = 0; i < num_shaders; i++) {
559 if (get_main_function_signature(shader_list[i]) != NULL) {
560 main = shader_list[i];
561 break;
562 }
563 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700564
Ian Romanick15ce87e2010-07-09 15:28:22 -0700565 if (main == NULL) {
566 linker_error_printf(prog, "%s shader lacks `main'\n",
567 (shader_list[0]->Type == GL_VERTEX_SHADER)
568 ? "vertex" : "fragment");
569 return NULL;
570 }
571
572 gl_shader *const linked = _mesa_new_shader(NULL, 0, main->Type);
573 linked->ir = new(linked) exec_list;
574 clone_ir_list(linked->ir, main->ir);
575
576 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700577
578 /* Resolve initializers for global variables in the linked shader.
579 */
Ian Romanick3fb87872010-07-09 14:09:34 -0700580
Ian Romanick3fb87872010-07-09 14:09:34 -0700581 return linked;
582}
583
584
Ian Romanick019a59b2010-06-21 16:10:42 -0700585struct uniform_node {
586 exec_node link;
587 struct gl_uniform *u;
588 unsigned slots;
589};
590
Ian Romanickabee16e2010-06-21 16:16:05 -0700591void
Eric Anholt849e1812010-06-30 11:49:17 -0700592assign_uniform_locations(struct gl_shader_program *prog)
Ian Romanick019a59b2010-06-21 16:10:42 -0700593{
594 /* */
595 exec_list uniforms;
596 unsigned total_uniforms = 0;
597 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
598 hash_table_string_compare);
599
Ian Romanickabee16e2010-06-21 16:16:05 -0700600 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700601 unsigned next_position = 0;
602
Eric Anholt16b68b12010-06-30 11:05:43 -0700603 foreach_list(node, prog->_LinkedShaders[i]->ir) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700604 ir_variable *const var = ((ir_instruction *) node)->as_variable();
605
606 if ((var == NULL) || (var->mode != ir_var_uniform))
607 continue;
608
609 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
610 assert(vec4_slots != 0);
611
612 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
613 if (n == NULL) {
614 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
615 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
616 n->slots = vec4_slots;
617
618 n->u[0].Name = strdup(var->name);
619 for (unsigned j = 1; j < vec4_slots; j++)
620 n->u[j].Name = n->u[0].Name;
621
622 hash_table_insert(ht, n, n->u[0].Name);
623 uniforms.push_tail(& n->link);
624 total_uniforms += vec4_slots;
625 }
626
627 if (var->constant_value != NULL)
628 for (unsigned j = 0; j < vec4_slots; j++)
629 n->u[j].Initialized = true;
630
631 var->location = next_position;
632
633 for (unsigned j = 0; j < vec4_slots; j++) {
Ian Romanickabee16e2010-06-21 16:16:05 -0700634 switch (prog->_LinkedShaders[i]->Type) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700635 case GL_VERTEX_SHADER:
636 n->u[j].VertPos = next_position;
637 break;
638 case GL_FRAGMENT_SHADER:
639 n->u[j].FragPos = next_position;
640 break;
641 case GL_GEOMETRY_SHADER:
642 /* FINISHME: Support geometry shaders. */
Ian Romanickabee16e2010-06-21 16:16:05 -0700643 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
Ian Romanick019a59b2010-06-21 16:10:42 -0700644 break;
645 }
646
647 next_position++;
648 }
649 }
650 }
651
652 gl_uniform_list *ul = (gl_uniform_list *)
653 calloc(1, sizeof(gl_uniform_list));
654
655 ul->Size = total_uniforms;
656 ul->NumUniforms = total_uniforms;
657 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
658
659 unsigned idx = 0;
660 uniform_node *next;
661 for (uniform_node *node = (uniform_node *) uniforms.head
662 ; node->link.next != NULL
663 ; node = next) {
664 next = (uniform_node *) node->link.next;
665
666 node->link.remove();
667 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
668 idx += node->slots;
669
670 free(node->u);
671 free(node);
672 }
673
674 hash_table_dtor(ht);
675
Ian Romanickabee16e2010-06-21 16:16:05 -0700676 prog->Uniforms = ul;
Ian Romanick019a59b2010-06-21 16:10:42 -0700677}
678
679
Ian Romanick69846702010-06-22 17:29:19 -0700680/**
681 * Find a contiguous set of available bits in a bitmask
682 *
683 * \param used_mask Bits representing used (1) and unused (0) locations
684 * \param needed_count Number of contiguous bits needed.
685 *
686 * \return
687 * Base location of the available bits on success or -1 on failure.
688 */
689int
690find_available_slots(unsigned used_mask, unsigned needed_count)
691{
692 unsigned needed_mask = (1 << needed_count) - 1;
693 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
694
695 /* The comparison to 32 is redundant, but without it GCC emits "warning:
696 * cannot optimize possibly infinite loops" for the loop below.
697 */
698 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
699 return -1;
700
701 for (int i = 0; i <= max_bit_to_test; i++) {
702 if ((needed_mask & ~used_mask) == needed_mask)
703 return i;
704
705 needed_mask <<= 1;
706 }
707
708 return -1;
709}
710
711
712bool
Eric Anholt849e1812010-06-30 11:49:17 -0700713assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700714{
Ian Romanick9342d262010-06-22 17:41:37 -0700715 /* Mark invalid attribute locations as being used.
716 */
717 unsigned used_locations = (max_attribute_index >= 32)
718 ? ~0 : ~((1 << max_attribute_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700719
Eric Anholt16b68b12010-06-30 11:05:43 -0700720 gl_shader *const sh = prog->_LinkedShaders[0];
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700721 assert(sh->Type == GL_VERTEX_SHADER);
722
Ian Romanick69846702010-06-22 17:29:19 -0700723 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700724 *
725 * 1. Invalidate the location assignments for all vertex shader inputs.
726 *
727 * 2. Assign locations for inputs that have user-defined (via
728 * glBindVertexAttribLocation) locatoins.
729 *
Ian Romanick69846702010-06-22 17:29:19 -0700730 * 3. Sort the attributes without assigned locations by number of slots
731 * required in decreasing order. Fragmentation caused by attribute
732 * locations assigned by the application may prevent large attributes
733 * from having enough contiguous space.
734 *
735 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700736 */
737
738 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
739
Ian Romanick553dcdc2010-06-23 12:14:02 -0700740 if (prog->Attributes != NULL) {
741 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700742 ir_variable *const var =
Ian Romanick553dcdc2010-06-23 12:14:02 -0700743 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700744
Ian Romanick69846702010-06-22 17:29:19 -0700745 /* Note: attributes that occupy multiple slots, such as arrays or
746 * matrices, may appear in the attrib array multiple times.
747 */
748 if ((var == NULL) || (var->location != -1))
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700749 continue;
750
Ian Romanick69846702010-06-22 17:29:19 -0700751 /* From page 61 of the OpenGL 4.0 spec:
752 *
753 * "LinkProgram will fail if the attribute bindings assigned by
754 * BindAttribLocation do not leave not enough space to assign a
755 * location for an active matrix attribute or an active attribute
756 * array, both of which require multiple contiguous generic
757 * attributes."
758 *
759 * Previous versions of the spec contain similar language but omit the
760 * bit about attribute arrays.
761 *
762 * Page 61 of the OpenGL 4.0 spec also says:
763 *
764 * "It is possible for an application to bind more than one
765 * attribute name to the same location. This is referred to as
766 * aliasing. This will only work if only one of the aliased
767 * attributes is active in the executable program, or if no path
768 * through the shader consumes more than one attribute of a set
769 * of attributes aliased to the same location. A link error can
770 * occur if the linker determines that every path through the
771 * shader consumes multiple aliased attributes, but
772 * implementations are not required to generate an error in this
773 * case."
774 *
775 * These two paragraphs are either somewhat contradictory, or I don't
776 * fully understand one or both of them.
777 */
778 /* FINISHME: The code as currently written does not support attribute
779 * FINISHME: location aliasing (see comment above).
780 */
Ian Romanick553dcdc2010-06-23 12:14:02 -0700781 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
Ian Romanick69846702010-06-22 17:29:19 -0700782 const unsigned slots = count_attribute_slots(var->type);
783
784 /* Mask representing the contiguous slots that will be used by this
785 * attribute.
786 */
787 const unsigned use_mask = (1 << slots) - 1;
788
789 /* Generate a link error if the set of bits requested for this
790 * attribute overlaps any previously allocated bits.
791 */
792 if ((~(use_mask << attr) & used_locations) != used_locations) {
Ian Romanick553dcdc2010-06-23 12:14:02 -0700793 linker_error_printf(prog,
794 "insufficient contiguous attribute locations "
795 "available for vertex shader input `%s'",
796 var->name);
Ian Romanick69846702010-06-22 17:29:19 -0700797 return false;
798 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700799
800 var->location = VERT_ATTRIB_GENERIC0 + attr;
Ian Romanick69846702010-06-22 17:29:19 -0700801 used_locations |= (use_mask << attr);
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700802 }
803 }
804
Ian Romanick69846702010-06-22 17:29:19 -0700805 /* Temporary storage for the set of attributes that need locations assigned.
806 */
807 struct temp_attr {
808 unsigned slots;
809 ir_variable *var;
810
811 /* Used below in the call to qsort. */
812 static int compare(const void *a, const void *b)
813 {
814 const temp_attr *const l = (const temp_attr *) a;
815 const temp_attr *const r = (const temp_attr *) b;
816
817 /* Reversed because we want a descending order sort below. */
818 return r->slots - l->slots;
819 }
820 } to_assign[16];
821
822 unsigned num_attr = 0;
823
Eric Anholt16b68b12010-06-30 11:05:43 -0700824 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700825 ir_variable *const var = ((ir_instruction *) node)->as_variable();
826
827 if ((var == NULL) || (var->mode != ir_var_in))
828 continue;
829
830 /* The location was explicitly assigned, nothing to do here.
831 */
832 if (var->location != -1)
833 continue;
834
Ian Romanick69846702010-06-22 17:29:19 -0700835 to_assign[num_attr].slots = count_attribute_slots(var->type);
836 to_assign[num_attr].var = var;
837 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700838 }
Ian Romanick69846702010-06-22 17:29:19 -0700839
840 /* If all of the attributes were assigned locations by the application (or
841 * are built-in attributes with fixed locations), return early. This should
842 * be the common case.
843 */
844 if (num_attr == 0)
845 return true;
846
847 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
848
Ian Romanick982e3792010-06-29 18:58:20 -0700849 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
850 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
851 * to prevent it from being automatically allocated below.
852 */
Ian Romanick35c89202010-07-07 16:28:39 -0700853 used_locations |= (1 << 0);
Ian Romanick982e3792010-06-29 18:58:20 -0700854
Ian Romanick69846702010-06-22 17:29:19 -0700855 for (unsigned i = 0; i < num_attr; i++) {
856 /* Mask representing the contiguous slots that will be used by this
857 * attribute.
858 */
859 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
860
861 int location = find_available_slots(used_locations, to_assign[i].slots);
862
863 if (location < 0) {
Ian Romanick553dcdc2010-06-23 12:14:02 -0700864 linker_error_printf(prog,
865 "insufficient contiguous attribute locations "
866 "available for vertex shader input `%s'",
867 to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -0700868 return false;
869 }
870
871 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
872 used_locations |= (use_mask << location);
873 }
874
875 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700876}
877
878
879void
Eric Anholt16b68b12010-06-30 11:05:43 -0700880assign_varying_locations(gl_shader *producer, gl_shader *consumer)
Ian Romanick0e59b262010-06-23 11:23:01 -0700881{
882 /* FINISHME: Set dynamically when geometry shader support is added. */
883 unsigned output_index = VERT_RESULT_VAR0;
884 unsigned input_index = FRAG_ATTRIB_VAR0;
885
886 /* Operate in a total of three passes.
887 *
888 * 1. Assign locations for any matching inputs and outputs.
889 *
890 * 2. Mark output variables in the producer that do not have locations as
891 * not being outputs. This lets the optimizer eliminate them.
892 *
893 * 3. Mark input variables in the consumer that do not have locations as
894 * not being inputs. This lets the optimizer eliminate them.
895 */
896
897 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
898 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
899
Eric Anholt16b68b12010-06-30 11:05:43 -0700900 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -0700901 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
902
903 if ((output_var == NULL) || (output_var->mode != ir_var_out)
904 || (output_var->location != -1))
905 continue;
906
907 ir_variable *const input_var =
908 consumer->symbols->get_variable(output_var->name);
909
910 if ((input_var == NULL) || (input_var->mode != ir_var_in))
911 continue;
912
913 assert(input_var->location == -1);
914
915 /* FINISHME: Location assignment will need some changes when arrays,
916 * FINISHME: matrices, and structures are allowed as shader inputs /
917 * FINISHME: outputs.
918 */
919 output_var->location = output_index;
920 input_var->location = input_index;
921
922 output_index++;
923 input_index++;
924 }
925
Eric Anholt16b68b12010-06-30 11:05:43 -0700926 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -0700927 ir_variable *const var = ((ir_instruction *) node)->as_variable();
928
929 if ((var == NULL) || (var->mode != ir_var_out))
930 continue;
931
932 /* An 'out' variable is only really a shader output if its value is read
933 * by the following stage.
934 */
935 var->shader_out = (var->location != -1);
936 }
937
Eric Anholt16b68b12010-06-30 11:05:43 -0700938 foreach_list(node, consumer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -0700939 ir_variable *const var = ((ir_instruction *) node)->as_variable();
940
941 if ((var == NULL) || (var->mode != ir_var_in))
942 continue;
943
944 /* An 'in' variable is only really a shader input if its value is written
945 * by the previous stage.
946 */
947 var->shader_in = (var->location != -1);
948 }
949}
950
951
952void
Eric Anholt849e1812010-06-30 11:49:17 -0700953link_shaders(struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -0700954{
955 prog->LinkStatus = false;
956 prog->Validated = false;
957 prog->_Used = false;
958
Ian Romanickf36460e2010-06-23 12:07:22 -0700959 if (prog->InfoLog != NULL)
960 talloc_free(prog->InfoLog);
961
962 prog->InfoLog = talloc_strdup(NULL, "");
963
Ian Romanick832dfa52010-06-17 15:04:20 -0700964 /* Separate the shaders into groups based on their type.
965 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700966 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -0700967 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -0700968 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -0700969 unsigned num_frag_shaders = 0;
970
Eric Anholt16b68b12010-06-30 11:05:43 -0700971 vert_shader_list = (struct gl_shader **)
972 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -0700973 frag_shader_list = &vert_shader_list[prog->NumShaders];
974
975 for (unsigned i = 0; i < prog->NumShaders; i++) {
976 switch (prog->Shaders[i]->Type) {
977 case GL_VERTEX_SHADER:
978 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
979 num_vert_shaders++;
980 break;
981 case GL_FRAGMENT_SHADER:
982 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
983 num_frag_shaders++;
984 break;
985 case GL_GEOMETRY_SHADER:
986 /* FINISHME: Support geometry shaders. */
987 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
988 break;
989 }
990 }
991
992 /* FINISHME: Implement intra-stage linking. */
Ian Romanickabee16e2010-06-21 16:16:05 -0700993 prog->_NumLinkedShaders = 0;
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700994 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -0700995 gl_shader *const sh =
996 link_intrastage_shaders(prog, vert_shader_list, num_vert_shaders);
997
998 if (sh == NULL)
999 goto done;
1000
1001 if (!validate_vertex_shader_executable(prog, sh))
1002 goto done;
1003
1004 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001005 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001006 }
1007
1008 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001009 gl_shader *const sh =
1010 link_intrastage_shaders(prog, frag_shader_list, num_frag_shaders);
1011
1012 if (sh == NULL)
1013 goto done;
1014
1015 if (!validate_fragment_shader_executable(prog, sh))
1016 goto done;
1017
1018 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001019 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001020 }
1021
Ian Romanick3ed850e2010-06-23 12:18:21 -07001022 /* Here begins the inter-stage linking phase. Some initial validation is
1023 * performed, then locations are assigned for uniforms, attributes, and
1024 * varyings.
1025 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001026 if (cross_validate_uniforms(prog)) {
Ian Romanick37101922010-06-18 19:02:10 -07001027 /* Validate the inputs of each stage with the output of the preceeding
1028 * stage.
1029 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001030 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
Ian Romanickf36460e2010-06-23 12:07:22 -07001031 if (!cross_validate_outputs_to_inputs(prog,
1032 prog->_LinkedShaders[i - 1],
Ian Romanickabee16e2010-06-21 16:16:05 -07001033 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001034 goto done;
1035 }
1036
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001037 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001038 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001039
Ian Romanick13e10e42010-06-21 12:03:24 -07001040 /* FINISHME: Perform whole-program optimization here. */
1041
Ian Romanickabee16e2010-06-21 16:16:05 -07001042 assign_uniform_locations(prog);
Ian Romanick13e10e42010-06-21 12:03:24 -07001043
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001044 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
Ian Romanick9342d262010-06-22 17:41:37 -07001045 /* FINISHME: The value of the max_attribute_index parameter is
1046 * FINISHME: implementation dependent based on the value of
1047 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1048 * FINISHME: at least 16, so hardcode 16 for now.
1049 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001050 if (!assign_attribute_locations(prog, 16))
Ian Romanick69846702010-06-22 17:29:19 -07001051 goto done;
Ian Romanick13e10e42010-06-21 12:03:24 -07001052
Ian Romanick0e59b262010-06-23 11:23:01 -07001053 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
1054 assign_varying_locations(prog->_LinkedShaders[i - 1],
1055 prog->_LinkedShaders[i]);
Ian Romanick13e10e42010-06-21 12:03:24 -07001056
1057 /* FINISHME: Assign fragment shader output locations. */
1058
Ian Romanick832dfa52010-06-17 15:04:20 -07001059done:
1060 free(vert_shader_list);
1061}