blob: 38d19c4c71148efb6b7c0c0e80f80ab6f7552b9f [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>
Ian Romanick25f51d32010-07-16 15:51:50 -070069#include <climits>
Ian Romanickf36460e2010-06-23 12:07:22 -070070
71extern "C" {
72#include <talloc.h>
73}
Ian Romanick832dfa52010-06-17 15:04:20 -070074
Ian Romanick45d97dd2010-08-16 13:59:34 -070075#include "main/compiler.h"
Ian Romanick0ad22cd2010-06-21 17:18:31 -070076#include "main/mtypes.h"
Ian Romanick25f51d32010-07-16 15:51:50 -070077#include "main/macros.h"
Eric Anholtafe125e2010-07-26 17:47:59 -070078#include "main/shaderobj.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070079#include "glsl_symbol_table.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070080#include "ir.h"
81#include "program.h"
Aras Pranckevicius31747152010-07-29 12:40:49 +030082#include "program/hash_table.h"
Ian Romanick8fe8a812010-07-13 17:36:13 -070083#include "linker.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070084#include "ir_optimization.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070085
86/**
87 * Visitor that determines whether or not a variable is ever written.
88 */
89class find_assignment_visitor : public ir_hierarchical_visitor {
90public:
91 find_assignment_visitor(const char *name)
92 : name(name), found(false)
93 {
94 /* empty */
95 }
96
97 virtual ir_visitor_status visit_enter(ir_assignment *ir)
98 {
99 ir_variable *const var = ir->lhs->variable_referenced();
100
101 if (strcmp(name, var->name) == 0) {
102 found = true;
103 return visit_stop;
104 }
105
106 return visit_continue_with_parent;
107 }
108
Eric Anholt18a60232010-08-23 11:29:25 -0700109 virtual ir_visitor_status visit_enter(ir_call *ir)
110 {
111 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
112 foreach_iter(exec_list_iterator, iter, *ir) {
113 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
114 ir_variable *sig_param = (ir_variable *)sig_iter.get();
115
116 if (sig_param->mode == ir_var_out ||
117 sig_param->mode == ir_var_inout) {
118 ir_variable *var = param_rval->variable_referenced();
119 if (var && strcmp(name, var->name) == 0) {
120 found = true;
121 return visit_stop;
122 }
123 }
124 sig_iter.next();
125 }
126
127 return visit_continue_with_parent;
128 }
129
Ian Romanick832dfa52010-06-17 15:04:20 -0700130 bool variable_found()
131 {
132 return found;
133 }
134
135private:
136 const char *name; /**< Find writes to a variable with this name. */
137 bool found; /**< Was a write to the variable found? */
138};
139
Ian Romanickc93b8f12010-06-17 15:20:22 -0700140
Ian Romanickc33e78f2010-08-13 12:30:41 -0700141/**
142 * Visitor that determines whether or not a variable is ever read.
143 */
144class find_deref_visitor : public ir_hierarchical_visitor {
145public:
146 find_deref_visitor(const char *name)
147 : name(name), found(false)
148 {
149 /* empty */
150 }
151
152 virtual ir_visitor_status visit(ir_dereference_variable *ir)
153 {
154 if (strcmp(this->name, ir->var->name) == 0) {
155 this->found = true;
156 return visit_stop;
157 }
158
159 return visit_continue;
160 }
161
162 bool variable_found() const
163 {
164 return this->found;
165 }
166
167private:
168 const char *name; /**< Find writes to a variable with this name. */
169 bool found; /**< Was a write to the variable found? */
170};
171
172
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700173void
Eric Anholt849e1812010-06-30 11:49:17 -0700174linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700175{
176 va_list ap;
177
178 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
179 va_start(ap, fmt);
180 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
181 va_end(ap);
182}
183
184
185void
Eric Anholt16b68b12010-06-30 11:05:43 -0700186invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700187 int generic_base)
188{
Eric Anholt16b68b12010-06-30 11:05:43 -0700189 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700190 ir_variable *const var = ((ir_instruction *) node)->as_variable();
191
192 if ((var == NULL) || (var->mode != (unsigned) mode))
193 continue;
194
195 /* Only assign locations for generic attributes / varyings / etc.
196 */
197 if (var->location >= generic_base)
198 var->location = -1;
199 }
200}
201
202
Ian Romanickc93b8f12010-06-17 15:20:22 -0700203/**
Ian Romanick69846702010-06-22 17:29:19 -0700204 * Determine the number of attribute slots required for a particular type
205 *
206 * This code is here because it implements the language rules of a specific
207 * GLSL version. Since it's a property of the language and not a property of
208 * types in general, it doesn't really belong in glsl_type.
209 */
210unsigned
211count_attribute_slots(const glsl_type *t)
212{
213 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
214 *
215 * "A scalar input counts the same amount against this limit as a vec4,
216 * so applications may want to consider packing groups of four
217 * unrelated float inputs together into a vector to better utilize the
218 * capabilities of the underlying hardware. A matrix input will use up
219 * multiple locations. The number of locations used will equal the
220 * number of columns in the matrix."
221 *
222 * The spec does not explicitly say how arrays are counted. However, it
223 * should be safe to assume the total number of slots consumed by an array
224 * is the number of entries in the array multiplied by the number of slots
225 * consumed by a single element of the array.
226 */
227
228 if (t->is_array())
229 return t->array_size() * count_attribute_slots(t->element_type());
230
231 if (t->is_matrix())
232 return t->matrix_columns;
233
234 return 1;
235}
236
237
238/**
Ian Romanickc93b8f12010-06-17 15:20:22 -0700239 * Verify that a vertex shader executable meets all semantic requirements
240 *
241 * \param shader Vertex shader executable to be verified
242 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700243bool
Eric Anholt849e1812010-06-30 11:49:17 -0700244validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700245 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700246{
247 if (shader == NULL)
248 return true;
249
Ian Romanick832dfa52010-06-17 15:04:20 -0700250 find_assignment_visitor find("gl_Position");
Eric Anholt16b68b12010-06-30 11:05:43 -0700251 find.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700252 if (!find.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700253 linker_error_printf(prog,
254 "vertex shader does not write to `gl_Position'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700255 return false;
256 }
257
258 return true;
259}
260
261
Ian Romanickc93b8f12010-06-17 15:20:22 -0700262/**
263 * Verify that a fragment shader executable meets all semantic requirements
264 *
265 * \param shader Fragment shader executable to be verified
266 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700267bool
Eric Anholt849e1812010-06-30 11:49:17 -0700268validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700269 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700270{
271 if (shader == NULL)
272 return true;
273
Ian Romanick832dfa52010-06-17 15:04:20 -0700274 find_assignment_visitor frag_color("gl_FragColor");
275 find_assignment_visitor frag_data("gl_FragData");
276
Eric Anholt16b68b12010-06-30 11:05:43 -0700277 frag_color.run(shader->ir);
278 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700279
Ian Romanick832dfa52010-06-17 15:04:20 -0700280 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700281 linker_error_printf(prog, "fragment shader writes to both "
282 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700283 return false;
284 }
285
286 return true;
287}
288
289
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700290/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700291 * Generate a string describing the mode of a variable
292 */
293static const char *
294mode_string(const ir_variable *var)
295{
296 switch (var->mode) {
297 case ir_var_auto:
298 return (var->read_only) ? "global constant" : "global variable";
299
300 case ir_var_uniform: return "uniform";
301 case ir_var_in: return "shader input";
302 case ir_var_out: return "shader output";
303 case ir_var_inout: return "shader inout";
Ian Romanick7e2aa912010-07-19 17:12:42 -0700304
305 case ir_var_temporary:
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700306 default:
307 assert(!"Should not get here.");
308 return "invalid variable";
309 }
310}
311
312
313/**
314 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700315 */
316bool
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700317cross_validate_globals(struct gl_shader_program *prog,
318 struct gl_shader **shader_list,
319 unsigned num_shaders,
320 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700321{
322 /* Examine all of the uniforms in all of the shaders and cross validate
323 * them.
324 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700325 glsl_symbol_table variables;
326 for (unsigned i = 0; i < num_shaders; i++) {
327 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700328 ir_variable *const var = ((ir_instruction *) node)->as_variable();
329
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700330 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700331 continue;
332
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700333 if (uniforms_only && (var->mode != ir_var_uniform))
334 continue;
335
Ian Romanick7e2aa912010-07-19 17:12:42 -0700336 /* Don't cross validate temporaries that are at global scope. These
337 * will eventually get pulled into the shaders 'main'.
338 */
339 if (var->mode == ir_var_temporary)
340 continue;
341
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700342 /* If a global with this name has already been seen, verify that the
343 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700344 * initializers, the values of the initializers must be the same.
345 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700346 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700347 if (existing != NULL) {
348 if (var->type != existing->type) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700349 linker_error_printf(prog, "%s `%s' declared as type "
Ian Romanickf36460e2010-06-23 12:07:22 -0700350 "`%s' and type `%s'\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700351 mode_string(var),
Ian Romanickf36460e2010-06-23 12:07:22 -0700352 var->name, var->type->name,
353 existing->type->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700354 return false;
355 }
356
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700357 /* FINISHME: Handle non-constant initializers.
358 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700359 if (var->constant_value != NULL) {
360 if (existing->constant_value != NULL) {
361 if (!var->constant_value->has_value(existing->constant_value)) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700362 linker_error_printf(prog, "initializers for %s "
Ian Romanickf36460e2010-06-23 12:07:22 -0700363 "`%s' have differing values\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700364 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700365 return false;
366 }
367 } else
368 /* If the first-seen instance of a particular uniform did not
369 * have an initializer but a later instance does, copy the
370 * initializer to the version stored in the symbol table.
371 */
Ian Romanickde415b72010-07-14 13:22:12 -0700372 /* FINISHME: This is wrong. The constant_value field should
373 * FINISHME: not be modified! Imagine a case where a shader
374 * FINISHME: without an initializer is linked in two different
375 * FINISHME: programs with shaders that have differing
376 * FINISHME: initializers. Linking with the first will
377 * FINISHME: modify the shader, and linking with the second
378 * FINISHME: will fail.
379 */
Eric Anholt8273bd42010-08-04 12:34:56 -0700380 existing->constant_value =
381 var->constant_value->clone(talloc_parent(existing), NULL);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700382 }
383 } else
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700384 variables.add_variable(var->name, var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700385 }
386 }
387
388 return true;
389}
390
391
Ian Romanick37101922010-06-18 19:02:10 -0700392/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700393 * Perform validation of uniforms used across multiple shader stages
394 */
395bool
396cross_validate_uniforms(struct gl_shader_program *prog)
397{
398 return cross_validate_globals(prog, prog->_LinkedShaders,
399 prog->_NumLinkedShaders, true);
400}
401
402
403/**
Ian Romanick37101922010-06-18 19:02:10 -0700404 * Validate that outputs from one stage match inputs of another
405 */
406bool
Eric Anholt849e1812010-06-30 11:49:17 -0700407cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700408 gl_shader *producer, gl_shader *consumer)
Ian Romanick37101922010-06-18 19:02:10 -0700409{
410 glsl_symbol_table parameters;
411 /* FINISHME: Figure these out dynamically. */
412 const char *const producer_stage = "vertex";
413 const char *const consumer_stage = "fragment";
414
415 /* Find all shader outputs in the "producer" stage.
416 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700417 foreach_list(node, producer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700418 ir_variable *const var = ((ir_instruction *) node)->as_variable();
419
420 /* FINISHME: For geometry shaders, this should also look for inout
421 * FINISHME: variables.
422 */
423 if ((var == NULL) || (var->mode != ir_var_out))
424 continue;
425
426 parameters.add_variable(var->name, var);
427 }
428
429
430 /* Find all shader inputs in the "consumer" stage. Any variables that have
431 * matching outputs already in the symbol table must have the same type and
432 * qualifiers.
433 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700434 foreach_list(node, consumer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700435 ir_variable *const input = ((ir_instruction *) node)->as_variable();
436
437 /* FINISHME: For geometry shaders, this should also look for inout
438 * FINISHME: variables.
439 */
440 if ((input == NULL) || (input->mode != ir_var_in))
441 continue;
442
443 ir_variable *const output = parameters.get_variable(input->name);
444 if (output != NULL) {
445 /* Check that the types match between stages.
446 */
447 if (input->type != output->type) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700448 linker_error_printf(prog,
449 "%s shader output `%s' delcared as "
450 "type `%s', but %s shader input declared "
451 "as type `%s'\n",
452 producer_stage, output->name,
453 output->type->name,
454 consumer_stage, input->type->name);
Ian Romanick37101922010-06-18 19:02:10 -0700455 return false;
456 }
457
458 /* Check that all of the qualifiers match between stages.
459 */
460 if (input->centroid != output->centroid) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700461 linker_error_printf(prog,
462 "%s shader output `%s' %s centroid qualifier, "
463 "but %s shader input %s centroid qualifier\n",
464 producer_stage,
465 output->name,
466 (output->centroid) ? "has" : "lacks",
467 consumer_stage,
468 (input->centroid) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700469 return false;
470 }
471
472 if (input->invariant != output->invariant) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700473 linker_error_printf(prog,
474 "%s shader output `%s' %s invariant qualifier, "
475 "but %s shader input %s invariant qualifier\n",
476 producer_stage,
477 output->name,
478 (output->invariant) ? "has" : "lacks",
479 consumer_stage,
480 (input->invariant) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700481 return false;
482 }
483
484 if (input->interpolation != output->interpolation) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700485 linker_error_printf(prog,
486 "%s shader output `%s' specifies %s "
487 "interpolation qualifier, "
488 "but %s shader input specifies %s "
489 "interpolation qualifier\n",
490 producer_stage,
491 output->name,
492 output->interpolation_string(),
493 consumer_stage,
494 input->interpolation_string());
Ian Romanick37101922010-06-18 19:02:10 -0700495 return false;
496 }
497 }
498 }
499
500 return true;
501}
502
503
Ian Romanick3fb87872010-07-09 14:09:34 -0700504/**
505 * Populates a shaders symbol table with all global declarations
506 */
507static void
508populate_symbol_table(gl_shader *sh)
509{
510 sh->symbols = new(sh) glsl_symbol_table;
511
512 foreach_list(node, sh->ir) {
513 ir_instruction *const inst = (ir_instruction *) node;
514 ir_variable *var;
515 ir_function *func;
516
517 if ((func = inst->as_function()) != NULL) {
518 sh->symbols->add_function(func->name, func);
519 } else if ((var = inst->as_variable()) != NULL) {
520 sh->symbols->add_variable(var->name, var);
521 }
522 }
523}
524
525
526/**
Ian Romanick31a97862010-07-12 18:48:50 -0700527 * Remap variables referenced in an instruction tree
528 *
529 * This is used when instruction trees are cloned from one shader and placed in
530 * another. These trees will contain references to \c ir_variable nodes that
531 * do not exist in the target shader. This function finds these \c ir_variable
532 * references and replaces the references with matching variables in the target
533 * shader.
534 *
535 * If there is no matching variable in the target shader, a clone of the
536 * \c ir_variable is made and added to the target shader. The new variable is
537 * added to \b both the instruction stream and the symbol table.
538 *
539 * \param inst IR tree that is to be processed.
540 * \param symbols Symbol table containing global scope symbols in the
541 * linked shader.
542 * \param instructions Instruction stream where new variable declarations
543 * should be added.
544 */
545void
Eric Anholt8273bd42010-08-04 12:34:56 -0700546remap_variables(ir_instruction *inst, struct gl_shader *target,
547 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700548{
549 class remap_visitor : public ir_hierarchical_visitor {
550 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700551 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700552 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700553 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700554 this->target = target;
555 this->symbols = target->symbols;
556 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700557 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700558 }
559
560 virtual ir_visitor_status visit(ir_dereference_variable *ir)
561 {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700562 if (ir->var->mode == ir_var_temporary) {
563 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
564
565 assert(var != NULL);
566 ir->var = var;
567 return visit_continue;
568 }
569
Ian Romanick31a97862010-07-12 18:48:50 -0700570 ir_variable *const existing =
571 this->symbols->get_variable(ir->var->name);
572 if (existing != NULL)
573 ir->var = existing;
574 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700575 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700576
577 this->symbols->add_variable(copy->name, copy);
578 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700579 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700580 }
581
582 return visit_continue;
583 }
584
585 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700586 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700587 glsl_symbol_table *symbols;
588 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700589 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700590 };
591
Eric Anholt8273bd42010-08-04 12:34:56 -0700592 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700593
594 inst->accept(&v);
595}
596
597
598/**
599 * Move non-declarations from one instruction stream to another
600 *
601 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700602 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
Ian Romanick31a97862010-07-12 18:48:50 -0700603 * pointer) for \c last and \c false for \c make_copies on the first
604 * call. Successive calls pass the return value of the previous call for
605 * \c last and \c true for \c make_copies.
606 *
607 * \param instructions Source instruction stream
608 * \param last Instruction after which new instructions should be
609 * inserted in the target instruction stream
610 * \param make_copies Flag selecting whether instructions in \c instructions
611 * should be copied (via \c ir_instruction::clone) into the
612 * target list or moved.
613 *
614 * \return
615 * The new "last" instruction in the target instruction stream. This pointer
616 * is suitable for use as the \c last parameter of a later call to this
617 * function.
618 */
619exec_node *
620move_non_declarations(exec_list *instructions, exec_node *last,
621 bool make_copies, gl_shader *target)
622{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700623 hash_table *temps = NULL;
624
625 if (make_copies)
626 temps = hash_table_ctor(0, hash_table_pointer_hash,
627 hash_table_pointer_compare);
628
Ian Romanick303c99f2010-07-19 12:34:56 -0700629 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700630 ir_instruction *inst = (ir_instruction *) node;
631
Ian Romanick7e2aa912010-07-19 17:12:42 -0700632 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700633 continue;
634
Ian Romanick7e2aa912010-07-19 17:12:42 -0700635 ir_variable *var = inst->as_variable();
636 if ((var != NULL) && (var->mode != ir_var_temporary))
637 continue;
638
639 assert(inst->as_assignment()
640 || ((var != NULL) && (var->mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700641
642 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700643 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700644
645 if (var != NULL)
646 hash_table_insert(temps, inst, var);
647 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700648 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700649 } else {
650 inst->remove();
651 }
652
653 last->insert_after(inst);
654 last = inst;
655 }
656
Ian Romanick7e2aa912010-07-19 17:12:42 -0700657 if (make_copies)
658 hash_table_dtor(temps);
659
Ian Romanick31a97862010-07-12 18:48:50 -0700660 return last;
661}
662
663/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700664 * Get the function signature for main from a shader
665 */
666static ir_function_signature *
667get_main_function_signature(gl_shader *sh)
668{
669 ir_function *const f = sh->symbols->get_function("main");
670 if (f != NULL) {
671 exec_list void_parameters;
672
673 /* Look for the 'void main()' signature and ensure that it's defined.
674 * This keeps the linker from accidentally pick a shader that just
675 * contains a prototype for main.
676 *
677 * We don't have to check for multiple definitions of main (in multiple
678 * shaders) because that would have already been caught above.
679 */
680 ir_function_signature *sig = f->matching_signature(&void_parameters);
681 if ((sig != NULL) && sig->is_defined) {
682 return sig;
683 }
684 }
685
686 return NULL;
687}
688
689
690/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700691 * Combine a group of shaders for a single stage to generate a linked shader
692 *
693 * \note
694 * If this function is supplied a single shader, it is cloned, and the new
695 * shader is returned.
696 */
697static struct gl_shader *
Eric Anholt5d0f4302010-08-18 12:02:35 -0700698link_intrastage_shaders(GLcontext *ctx,
699 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -0700700 struct gl_shader **shader_list,
701 unsigned num_shaders)
702{
Ian Romanick13f782c2010-06-29 18:53:38 -0700703 /* Check that global variables defined in multiple shaders are consistent.
704 */
705 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
706 return NULL;
707
708 /* Check that there is only a single definition of each function signature
709 * across all shaders.
710 */
711 for (unsigned i = 0; i < (num_shaders - 1); i++) {
712 foreach_list(node, shader_list[i]->ir) {
713 ir_function *const f = ((ir_instruction *) node)->as_function();
714
715 if (f == NULL)
716 continue;
717
718 for (unsigned j = i + 1; j < num_shaders; j++) {
719 ir_function *const other =
720 shader_list[j]->symbols->get_function(f->name);
721
722 /* If the other shader has no function (and therefore no function
723 * signatures) with the same name, skip to the next shader.
724 */
725 if (other == NULL)
726 continue;
727
728 foreach_iter (exec_list_iterator, iter, *f) {
729 ir_function_signature *sig =
730 (ir_function_signature *) iter.get();
731
732 if (!sig->is_defined || sig->is_built_in)
733 continue;
734
735 ir_function_signature *other_sig =
736 other->exact_matching_signature(& sig->parameters);
737
738 if ((other_sig != NULL) && other_sig->is_defined
739 && !other_sig->is_built_in) {
740 linker_error_printf(prog,
741 "function `%s' is multiply defined",
742 f->name);
743 return NULL;
744 }
745 }
746 }
747 }
748 }
749
750 /* Find the shader that defines main, and make a clone of it.
751 *
752 * Starting with the clone, search for undefined references. If one is
753 * found, find the shader that defines it. Clone the reference and add
754 * it to the shader. Repeat until there are no undefined references or
755 * until a reference cannot be resolved.
756 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700757 gl_shader *main = NULL;
758 for (unsigned i = 0; i < num_shaders; i++) {
759 if (get_main_function_signature(shader_list[i]) != NULL) {
760 main = shader_list[i];
761 break;
762 }
763 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700764
Ian Romanick15ce87e2010-07-09 15:28:22 -0700765 if (main == NULL) {
766 linker_error_printf(prog, "%s shader lacks `main'\n",
767 (shader_list[0]->Type == GL_VERTEX_SHADER)
768 ? "vertex" : "fragment");
769 return NULL;
770 }
771
Eric Anholt5d0f4302010-08-18 12:02:35 -0700772 gl_shader *const linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700773 linked->ir = new(linked) exec_list;
Eric Anholt8273bd42010-08-04 12:34:56 -0700774 clone_ir_list(linked, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700775
776 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700777
Ian Romanick31a97862010-07-12 18:48:50 -0700778 /* The a pointer to the main function in the final linked shader (i.e., the
779 * copy of the original shader that contained the main function).
780 */
781 ir_function_signature *const main_sig = get_main_function_signature(linked);
782
783 /* Move any instructions other than variable declarations or function
784 * declarations into main.
785 */
Ian Romanick9303e352010-07-19 12:33:54 -0700786 exec_node *insertion_point =
787 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
788 linked);
789
Ian Romanick31a97862010-07-12 18:48:50 -0700790 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -0700791 if (shader_list[i] == main)
792 continue;
793
Ian Romanick31a97862010-07-12 18:48:50 -0700794 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -0700795 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -0700796 }
797
Ian Romanick13f782c2010-06-29 18:53:38 -0700798 /* Resolve initializers for global variables in the linked shader.
799 */
Ian Romanickd5be2ac2010-07-20 11:29:46 -0700800 unsigned num_linking_shaders = num_shaders;
801 for (unsigned i = 0; i < num_shaders; i++)
802 num_linking_shaders += shader_list[i]->num_builtins_to_link;
803
804 gl_shader **linking_shaders =
805 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
806
807 memcpy(linking_shaders, shader_list,
808 sizeof(linking_shaders[0]) * num_shaders);
809
810 unsigned idx = num_shaders;
811 for (unsigned i = 0; i < num_shaders; i++) {
812 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
813 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
814 idx += shader_list[i]->num_builtins_to_link;
815 }
816
817 assert(idx == num_linking_shaders);
818
819 link_function_calls(prog, linked, linking_shaders, num_linking_shaders);
820
821 free(linking_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -0700822
Ian Romanick3fb87872010-07-09 14:09:34 -0700823 return linked;
824}
825
826
Ian Romanick019a59b2010-06-21 16:10:42 -0700827struct uniform_node {
828 exec_node link;
829 struct gl_uniform *u;
830 unsigned slots;
831};
832
Eric Anholta721abf2010-08-23 10:32:01 -0700833/**
834 * Update the sizes of linked shader uniform arrays to the maximum
835 * array index used.
836 *
837 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
838 *
839 * If one or more elements of an array are active,
840 * GetActiveUniform will return the name of the array in name,
841 * subject to the restrictions listed above. The type of the array
842 * is returned in type. The size parameter contains the highest
843 * array element index used, plus one. The compiler or linker
844 * determines the highest index used. There will be only one
845 * active uniform reported by the GL per uniform array.
846
847 */
848static void
849update_uniform_array_sizes(struct gl_shader_program *prog)
850{
851 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
852 foreach_list(node, prog->_LinkedShaders[i]->ir) {
853 ir_variable *const var = ((ir_instruction *) node)->as_variable();
854
855 if ((var == NULL) || (var->mode != ir_var_uniform) ||
856 !var->type->is_array())
857 continue;
858
859 unsigned int size = var->max_array_access;
860 for (unsigned j = 0; j < prog->_NumLinkedShaders; j++) {
861 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
862 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
863 if (!other_var)
864 continue;
865
866 if (strcmp(var->name, other_var->name) == 0 &&
867 other_var->max_array_access > size) {
868 size = other_var->max_array_access;
869 }
870 }
871 }
872 if (size + 1 != var->type->fields.array->length) {
873 var->type = glsl_type::get_array_instance(var->type->fields.array,
874 size + 1);
875 /* FINISHME: We should update the types of array
876 * dereferences of this variable now.
877 */
878 }
879 }
880 }
881}
882
Ian Romanickabee16e2010-06-21 16:16:05 -0700883void
Eric Anholt849e1812010-06-30 11:49:17 -0700884assign_uniform_locations(struct gl_shader_program *prog)
Ian Romanick019a59b2010-06-21 16:10:42 -0700885{
886 /* */
887 exec_list uniforms;
888 unsigned total_uniforms = 0;
889 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
890 hash_table_string_compare);
891
Eric Anholta721abf2010-08-23 10:32:01 -0700892 update_uniform_array_sizes(prog);
893
Ian Romanickabee16e2010-06-21 16:16:05 -0700894 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700895 unsigned next_position = 0;
896
Eric Anholt16b68b12010-06-30 11:05:43 -0700897 foreach_list(node, prog->_LinkedShaders[i]->ir) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700898 ir_variable *const var = ((ir_instruction *) node)->as_variable();
899
900 if ((var == NULL) || (var->mode != ir_var_uniform))
901 continue;
902
903 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
Eric Anholt8d61a232010-08-05 16:00:46 -0700904 if (vec4_slots == 0) {
905 /* If we've got a sampler or an aggregate of them, the size can
906 * end up zero. Don't allocate any space.
907 */
908 continue;
909 }
Ian Romanick019a59b2010-06-21 16:10:42 -0700910
911 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
912 if (n == NULL) {
913 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
914 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
915 n->slots = vec4_slots;
916
917 n->u[0].Name = strdup(var->name);
918 for (unsigned j = 1; j < vec4_slots; j++)
Eric Anholtf1d5a942010-08-18 17:39:57 -0700919 n->u[j].Name = strdup(var->name);
Ian Romanick019a59b2010-06-21 16:10:42 -0700920
921 hash_table_insert(ht, n, n->u[0].Name);
922 uniforms.push_tail(& n->link);
923 total_uniforms += vec4_slots;
924 }
925
926 if (var->constant_value != NULL)
927 for (unsigned j = 0; j < vec4_slots; j++)
928 n->u[j].Initialized = true;
929
930 var->location = next_position;
931
932 for (unsigned j = 0; j < vec4_slots; j++) {
Ian Romanickabee16e2010-06-21 16:16:05 -0700933 switch (prog->_LinkedShaders[i]->Type) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700934 case GL_VERTEX_SHADER:
935 n->u[j].VertPos = next_position;
936 break;
937 case GL_FRAGMENT_SHADER:
938 n->u[j].FragPos = next_position;
939 break;
940 case GL_GEOMETRY_SHADER:
941 /* FINISHME: Support geometry shaders. */
Ian Romanickabee16e2010-06-21 16:16:05 -0700942 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
Ian Romanick019a59b2010-06-21 16:10:42 -0700943 break;
944 }
945
946 next_position++;
947 }
948 }
949 }
950
951 gl_uniform_list *ul = (gl_uniform_list *)
952 calloc(1, sizeof(gl_uniform_list));
953
954 ul->Size = total_uniforms;
955 ul->NumUniforms = total_uniforms;
956 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
957
958 unsigned idx = 0;
959 uniform_node *next;
960 for (uniform_node *node = (uniform_node *) uniforms.head
961 ; node->link.next != NULL
962 ; node = next) {
963 next = (uniform_node *) node->link.next;
964
965 node->link.remove();
966 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
967 idx += node->slots;
968
969 free(node->u);
970 free(node);
971 }
972
973 hash_table_dtor(ht);
974
Ian Romanickabee16e2010-06-21 16:16:05 -0700975 prog->Uniforms = ul;
Ian Romanick019a59b2010-06-21 16:10:42 -0700976}
977
978
Ian Romanick69846702010-06-22 17:29:19 -0700979/**
980 * Find a contiguous set of available bits in a bitmask
981 *
982 * \param used_mask Bits representing used (1) and unused (0) locations
983 * \param needed_count Number of contiguous bits needed.
984 *
985 * \return
986 * Base location of the available bits on success or -1 on failure.
987 */
988int
989find_available_slots(unsigned used_mask, unsigned needed_count)
990{
991 unsigned needed_mask = (1 << needed_count) - 1;
992 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
993
994 /* The comparison to 32 is redundant, but without it GCC emits "warning:
995 * cannot optimize possibly infinite loops" for the loop below.
996 */
997 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
998 return -1;
999
1000 for (int i = 0; i <= max_bit_to_test; i++) {
1001 if ((needed_mask & ~used_mask) == needed_mask)
1002 return i;
1003
1004 needed_mask <<= 1;
1005 }
1006
1007 return -1;
1008}
1009
1010
1011bool
Eric Anholt849e1812010-06-30 11:49:17 -07001012assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001013{
Ian Romanick9342d262010-06-22 17:41:37 -07001014 /* Mark invalid attribute locations as being used.
1015 */
1016 unsigned used_locations = (max_attribute_index >= 32)
1017 ? ~0 : ~((1 << max_attribute_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001018
Eric Anholt16b68b12010-06-30 11:05:43 -07001019 gl_shader *const sh = prog->_LinkedShaders[0];
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001020 assert(sh->Type == GL_VERTEX_SHADER);
1021
Ian Romanick69846702010-06-22 17:29:19 -07001022 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001023 *
1024 * 1. Invalidate the location assignments for all vertex shader inputs.
1025 *
1026 * 2. Assign locations for inputs that have user-defined (via
1027 * glBindVertexAttribLocation) locatoins.
1028 *
Ian Romanick69846702010-06-22 17:29:19 -07001029 * 3. Sort the attributes without assigned locations by number of slots
1030 * required in decreasing order. Fragmentation caused by attribute
1031 * locations assigned by the application may prevent large attributes
1032 * from having enough contiguous space.
1033 *
1034 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001035 */
1036
1037 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1038
Ian Romanick553dcdc2010-06-23 12:14:02 -07001039 if (prog->Attributes != NULL) {
1040 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001041 ir_variable *const var =
Ian Romanick553dcdc2010-06-23 12:14:02 -07001042 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001043
Ian Romanick69846702010-06-22 17:29:19 -07001044 /* Note: attributes that occupy multiple slots, such as arrays or
1045 * matrices, may appear in the attrib array multiple times.
1046 */
1047 if ((var == NULL) || (var->location != -1))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001048 continue;
1049
Ian Romanick69846702010-06-22 17:29:19 -07001050 /* From page 61 of the OpenGL 4.0 spec:
1051 *
1052 * "LinkProgram will fail if the attribute bindings assigned by
1053 * BindAttribLocation do not leave not enough space to assign a
1054 * location for an active matrix attribute or an active attribute
1055 * array, both of which require multiple contiguous generic
1056 * attributes."
1057 *
1058 * Previous versions of the spec contain similar language but omit the
1059 * bit about attribute arrays.
1060 *
1061 * Page 61 of the OpenGL 4.0 spec also says:
1062 *
1063 * "It is possible for an application to bind more than one
1064 * attribute name to the same location. This is referred to as
1065 * aliasing. This will only work if only one of the aliased
1066 * attributes is active in the executable program, or if no path
1067 * through the shader consumes more than one attribute of a set
1068 * of attributes aliased to the same location. A link error can
1069 * occur if the linker determines that every path through the
1070 * shader consumes multiple aliased attributes, but
1071 * implementations are not required to generate an error in this
1072 * case."
1073 *
1074 * These two paragraphs are either somewhat contradictory, or I don't
1075 * fully understand one or both of them.
1076 */
1077 /* FINISHME: The code as currently written does not support attribute
1078 * FINISHME: location aliasing (see comment above).
1079 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001080 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
Ian Romanick69846702010-06-22 17:29:19 -07001081 const unsigned slots = count_attribute_slots(var->type);
1082
1083 /* Mask representing the contiguous slots that will be used by this
1084 * attribute.
1085 */
1086 const unsigned use_mask = (1 << slots) - 1;
1087
1088 /* Generate a link error if the set of bits requested for this
1089 * attribute overlaps any previously allocated bits.
1090 */
1091 if ((~(use_mask << attr) & used_locations) != used_locations) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001092 linker_error_printf(prog,
1093 "insufficient contiguous attribute locations "
1094 "available for vertex shader input `%s'",
1095 var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001096 return false;
1097 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001098
1099 var->location = VERT_ATTRIB_GENERIC0 + attr;
Ian Romanick69846702010-06-22 17:29:19 -07001100 used_locations |= (use_mask << attr);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001101 }
1102 }
1103
Ian Romanick69846702010-06-22 17:29:19 -07001104 /* Temporary storage for the set of attributes that need locations assigned.
1105 */
1106 struct temp_attr {
1107 unsigned slots;
1108 ir_variable *var;
1109
1110 /* Used below in the call to qsort. */
1111 static int compare(const void *a, const void *b)
1112 {
1113 const temp_attr *const l = (const temp_attr *) a;
1114 const temp_attr *const r = (const temp_attr *) b;
1115
1116 /* Reversed because we want a descending order sort below. */
1117 return r->slots - l->slots;
1118 }
1119 } to_assign[16];
1120
1121 unsigned num_attr = 0;
1122
Eric Anholt16b68b12010-06-30 11:05:43 -07001123 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001124 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1125
1126 if ((var == NULL) || (var->mode != ir_var_in))
1127 continue;
1128
1129 /* The location was explicitly assigned, nothing to do here.
1130 */
1131 if (var->location != -1)
1132 continue;
1133
Ian Romanick69846702010-06-22 17:29:19 -07001134 to_assign[num_attr].slots = count_attribute_slots(var->type);
1135 to_assign[num_attr].var = var;
1136 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001137 }
Ian Romanick69846702010-06-22 17:29:19 -07001138
1139 /* If all of the attributes were assigned locations by the application (or
1140 * are built-in attributes with fixed locations), return early. This should
1141 * be the common case.
1142 */
1143 if (num_attr == 0)
1144 return true;
1145
1146 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1147
Ian Romanick982e3792010-06-29 18:58:20 -07001148 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1149 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1150 * to prevent it from being automatically allocated below.
1151 */
Ian Romanickc33e78f2010-08-13 12:30:41 -07001152 find_deref_visitor find("gl_Vertex");
1153 find.run(sh->ir);
1154 if (find.variable_found())
1155 used_locations |= (1 << 0);
Ian Romanick982e3792010-06-29 18:58:20 -07001156
Ian Romanick69846702010-06-22 17:29:19 -07001157 for (unsigned i = 0; i < num_attr; i++) {
1158 /* Mask representing the contiguous slots that will be used by this
1159 * attribute.
1160 */
1161 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1162
1163 int location = find_available_slots(used_locations, to_assign[i].slots);
1164
1165 if (location < 0) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001166 linker_error_printf(prog,
1167 "insufficient contiguous attribute locations "
1168 "available for vertex shader input `%s'",
1169 to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001170 return false;
1171 }
1172
1173 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1174 used_locations |= (use_mask << location);
1175 }
1176
1177 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001178}
1179
1180
Ian Romanick40e114b2010-08-17 14:55:50 -07001181/**
1182 * Demote shader outputs that are not read to being just plain global variables
1183 */
1184void
1185demote_unread_shader_outputs(gl_shader *sh)
1186{
1187 foreach_list(node, sh->ir) {
1188 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1189
1190 if ((var == NULL) || (var->mode != ir_var_out))
1191 continue;
1192
1193 /* An 'out' variable is only really a shader output if its value is read
1194 * by the following stage.
1195 */
1196 if (var->location == -1) {
1197 var->mode = ir_var_auto;
1198 }
1199 }
1200}
1201
1202
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001203void
Eric Anholtb7062832010-07-28 13:52:23 -07001204assign_varying_locations(struct gl_shader_program *prog,
1205 gl_shader *producer, gl_shader *consumer)
Ian Romanick0e59b262010-06-23 11:23:01 -07001206{
1207 /* FINISHME: Set dynamically when geometry shader support is added. */
1208 unsigned output_index = VERT_RESULT_VAR0;
1209 unsigned input_index = FRAG_ATTRIB_VAR0;
1210
1211 /* Operate in a total of three passes.
1212 *
1213 * 1. Assign locations for any matching inputs and outputs.
1214 *
1215 * 2. Mark output variables in the producer that do not have locations as
1216 * not being outputs. This lets the optimizer eliminate them.
1217 *
1218 * 3. Mark input variables in the consumer that do not have locations as
1219 * not being inputs. This lets the optimizer eliminate them.
1220 */
1221
1222 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1223 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1224
Eric Anholt16b68b12010-06-30 11:05:43 -07001225 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001226 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1227
1228 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1229 || (output_var->location != -1))
1230 continue;
1231
1232 ir_variable *const input_var =
1233 consumer->symbols->get_variable(output_var->name);
1234
1235 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1236 continue;
1237
1238 assert(input_var->location == -1);
1239
1240 /* FINISHME: Location assignment will need some changes when arrays,
1241 * FINISHME: matrices, and structures are allowed as shader inputs /
1242 * FINISHME: outputs.
1243 */
1244 output_var->location = output_index;
1245 input_var->location = input_index;
1246
1247 output_index++;
1248 input_index++;
1249 }
1250
Ian Romanick40e114b2010-08-17 14:55:50 -07001251 demote_unread_shader_outputs(producer);
Ian Romanick0e59b262010-06-23 11:23:01 -07001252
Eric Anholt16b68b12010-06-30 11:05:43 -07001253 foreach_list(node, consumer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001254 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1255
1256 if ((var == NULL) || (var->mode != ir_var_in))
1257 continue;
1258
Eric Anholtb7062832010-07-28 13:52:23 -07001259 if (var->location == -1) {
1260 if (prog->Version <= 120) {
1261 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1262 *
1263 * Only those varying variables used (i.e. read) in
1264 * the fragment shader executable must be written to
1265 * by the vertex shader executable; declaring
1266 * superfluous varying variables in a vertex shader is
1267 * permissible.
1268 *
1269 * We interpret this text as meaning that the VS must
1270 * write the variable for the FS to read it. See
1271 * "glsl1-varying read but not written" in piglit.
1272 */
1273
1274 linker_error_printf(prog, "fragment shader varying %s not written "
1275 "by vertex shader\n.", var->name);
1276 prog->LinkStatus = false;
1277 }
1278
1279 /* An 'in' variable is only really a shader input if its
1280 * value is written by the previous stage.
1281 */
Eric Anholtb7062832010-07-28 13:52:23 -07001282 var->mode = ir_var_auto;
1283 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001284 }
1285}
1286
1287
1288void
Eric Anholt5d0f4302010-08-18 12:02:35 -07001289link_shaders(GLcontext *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07001290{
1291 prog->LinkStatus = false;
1292 prog->Validated = false;
1293 prog->_Used = false;
1294
Ian Romanickf36460e2010-06-23 12:07:22 -07001295 if (prog->InfoLog != NULL)
1296 talloc_free(prog->InfoLog);
1297
1298 prog->InfoLog = talloc_strdup(NULL, "");
1299
Ian Romanick832dfa52010-06-17 15:04:20 -07001300 /* Separate the shaders into groups based on their type.
1301 */
Eric Anholt16b68b12010-06-30 11:05:43 -07001302 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001303 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07001304 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001305 unsigned num_frag_shaders = 0;
1306
Eric Anholt16b68b12010-06-30 11:05:43 -07001307 vert_shader_list = (struct gl_shader **)
1308 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07001309 frag_shader_list = &vert_shader_list[prog->NumShaders];
1310
Ian Romanick25f51d32010-07-16 15:51:50 -07001311 unsigned min_version = UINT_MAX;
1312 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07001313 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07001314 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1315 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1316
Ian Romanick832dfa52010-06-17 15:04:20 -07001317 switch (prog->Shaders[i]->Type) {
1318 case GL_VERTEX_SHADER:
1319 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1320 num_vert_shaders++;
1321 break;
1322 case GL_FRAGMENT_SHADER:
1323 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1324 num_frag_shaders++;
1325 break;
1326 case GL_GEOMETRY_SHADER:
1327 /* FINISHME: Support geometry shaders. */
1328 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1329 break;
1330 }
1331 }
1332
Ian Romanick25f51d32010-07-16 15:51:50 -07001333 /* Previous to GLSL version 1.30, different compilation units could mix and
1334 * match shading language versions. With GLSL 1.30 and later, the versions
1335 * of all shaders must match.
1336 */
1337 assert(min_version >= 110);
1338 assert(max_version <= 130);
1339 if ((max_version >= 130) && (min_version != max_version)) {
1340 linker_error_printf(prog, "all shaders must use same shading "
1341 "language version\n");
1342 goto done;
1343 }
1344
1345 prog->Version = max_version;
1346
Eric Anholt5d0f4302010-08-18 12:02:35 -07001347 for (unsigned int i = 0; i < prog->_NumLinkedShaders; i++) {
1348 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1349 }
1350
Ian Romanickcd6764e2010-07-16 16:00:07 -07001351 /* Link all shaders for a particular stage and validate the result.
1352 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001353 prog->_NumLinkedShaders = 0;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001354 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001355 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001356 link_intrastage_shaders(ctx, prog, vert_shader_list, num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001357
1358 if (sh == NULL)
1359 goto done;
1360
1361 if (!validate_vertex_shader_executable(prog, sh))
1362 goto done;
1363
1364 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001365 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001366 }
1367
1368 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001369 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001370 link_intrastage_shaders(ctx, prog, frag_shader_list, num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001371
1372 if (sh == NULL)
1373 goto done;
1374
1375 if (!validate_fragment_shader_executable(prog, sh))
1376 goto done;
1377
1378 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001379 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001380 }
1381
Ian Romanick3ed850e2010-06-23 12:18:21 -07001382 /* Here begins the inter-stage linking phase. Some initial validation is
1383 * performed, then locations are assigned for uniforms, attributes, and
1384 * varyings.
1385 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001386 if (cross_validate_uniforms(prog)) {
Ian Romanick37101922010-06-18 19:02:10 -07001387 /* Validate the inputs of each stage with the output of the preceeding
1388 * stage.
1389 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001390 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
Ian Romanickf36460e2010-06-23 12:07:22 -07001391 if (!cross_validate_outputs_to_inputs(prog,
1392 prog->_LinkedShaders[i - 1],
Ian Romanickabee16e2010-06-21 16:16:05 -07001393 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001394 goto done;
1395 }
1396
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001397 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001398 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001399
Eric Anholt2f4fe152010-08-10 13:06:49 -07001400 /* Do common optimization before assigning storage for attributes,
1401 * uniforms, and varyings. Later optimization could possibly make
1402 * some of that unused.
1403 */
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001404 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Eric Anholt2f4fe152010-08-10 13:06:49 -07001405 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true))
1406 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001407 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001408
Ian Romanickabee16e2010-06-21 16:16:05 -07001409 assign_uniform_locations(prog);
Ian Romanick13e10e42010-06-21 12:03:24 -07001410
Ian Romanick40e114b2010-08-17 14:55:50 -07001411 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER) {
Ian Romanick9342d262010-06-22 17:41:37 -07001412 /* FINISHME: The value of the max_attribute_index parameter is
1413 * FINISHME: implementation dependent based on the value of
1414 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1415 * FINISHME: at least 16, so hardcode 16 for now.
1416 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001417 if (!assign_attribute_locations(prog, 16))
Ian Romanick69846702010-06-22 17:29:19 -07001418 goto done;
Ian Romanick13e10e42010-06-21 12:03:24 -07001419
Ian Romanick40e114b2010-08-17 14:55:50 -07001420 if (prog->_NumLinkedShaders == 1)
1421 demote_unread_shader_outputs(prog->_LinkedShaders[0]);
1422 }
1423
Ian Romanick0e59b262010-06-23 11:23:01 -07001424 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
Eric Anholtb7062832010-07-28 13:52:23 -07001425 assign_varying_locations(prog,
1426 prog->_LinkedShaders[i - 1],
Ian Romanick0e59b262010-06-23 11:23:01 -07001427 prog->_LinkedShaders[i]);
Ian Romanick13e10e42010-06-21 12:03:24 -07001428
1429 /* FINISHME: Assign fragment shader output locations. */
1430
Ian Romanick832dfa52010-06-17 15:04:20 -07001431done:
1432 free(vert_shader_list);
1433}