blob: c5c8c9cdd6382fc2b5d1eb6a2110d5353dd5b362 [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
Chia-I Wubfd7c9a2010-08-23 17:51:42 +080075#include "main/core.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070076#include "glsl_symbol_table.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070077#include "ir.h"
78#include "program.h"
Aras Pranckevicius31747152010-07-29 12:40:49 +030079#include "program/hash_table.h"
Ian Romanick8fe8a812010-07-13 17:36:13 -070080#include "linker.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070081#include "ir_optimization.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
Eric Anholt18a60232010-08-23 11:29:25 -0700106 virtual ir_visitor_status visit_enter(ir_call *ir)
107 {
108 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
109 foreach_iter(exec_list_iterator, iter, *ir) {
110 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
111 ir_variable *sig_param = (ir_variable *)sig_iter.get();
112
113 if (sig_param->mode == ir_var_out ||
114 sig_param->mode == ir_var_inout) {
115 ir_variable *var = param_rval->variable_referenced();
116 if (var && strcmp(name, var->name) == 0) {
117 found = true;
118 return visit_stop;
119 }
120 }
121 sig_iter.next();
122 }
123
124 return visit_continue_with_parent;
125 }
126
Ian Romanick832dfa52010-06-17 15:04:20 -0700127 bool variable_found()
128 {
129 return found;
130 }
131
132private:
133 const char *name; /**< Find writes to a variable with this name. */
134 bool found; /**< Was a write to the variable found? */
135};
136
Ian Romanickc93b8f12010-06-17 15:20:22 -0700137
Ian Romanickc33e78f2010-08-13 12:30:41 -0700138/**
139 * Visitor that determines whether or not a variable is ever read.
140 */
141class find_deref_visitor : public ir_hierarchical_visitor {
142public:
143 find_deref_visitor(const char *name)
144 : name(name), found(false)
145 {
146 /* empty */
147 }
148
149 virtual ir_visitor_status visit(ir_dereference_variable *ir)
150 {
151 if (strcmp(this->name, ir->var->name) == 0) {
152 this->found = true;
153 return visit_stop;
154 }
155
156 return visit_continue;
157 }
158
159 bool variable_found() const
160 {
161 return this->found;
162 }
163
164private:
165 const char *name; /**< Find writes to a variable with this name. */
166 bool found; /**< Was a write to the variable found? */
167};
168
169
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700170void
Eric Anholt849e1812010-06-30 11:49:17 -0700171linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700172{
173 va_list ap;
174
175 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
176 va_start(ap, fmt);
177 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
178 va_end(ap);
179}
180
181
182void
Eric Anholt16b68b12010-06-30 11:05:43 -0700183invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700184 int generic_base)
185{
Eric Anholt16b68b12010-06-30 11:05:43 -0700186 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700187 ir_variable *const var = ((ir_instruction *) node)->as_variable();
188
189 if ((var == NULL) || (var->mode != (unsigned) mode))
190 continue;
191
192 /* Only assign locations for generic attributes / varyings / etc.
193 */
194 if (var->location >= generic_base)
195 var->location = -1;
196 }
197}
198
199
Ian Romanickc93b8f12010-06-17 15:20:22 -0700200/**
Ian Romanick69846702010-06-22 17:29:19 -0700201 * Determine the number of attribute slots required for a particular type
202 *
203 * This code is here because it implements the language rules of a specific
204 * GLSL version. Since it's a property of the language and not a property of
205 * types in general, it doesn't really belong in glsl_type.
206 */
207unsigned
208count_attribute_slots(const glsl_type *t)
209{
210 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
211 *
212 * "A scalar input counts the same amount against this limit as a vec4,
213 * so applications may want to consider packing groups of four
214 * unrelated float inputs together into a vector to better utilize the
215 * capabilities of the underlying hardware. A matrix input will use up
216 * multiple locations. The number of locations used will equal the
217 * number of columns in the matrix."
218 *
219 * The spec does not explicitly say how arrays are counted. However, it
220 * should be safe to assume the total number of slots consumed by an array
221 * is the number of entries in the array multiplied by the number of slots
222 * consumed by a single element of the array.
223 */
224
225 if (t->is_array())
226 return t->array_size() * count_attribute_slots(t->element_type());
227
228 if (t->is_matrix())
229 return t->matrix_columns;
230
231 return 1;
232}
233
234
235/**
Ian Romanickc93b8f12010-06-17 15:20:22 -0700236 * Verify that a vertex shader executable meets all semantic requirements
237 *
238 * \param shader Vertex shader executable to be verified
239 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700240bool
Eric Anholt849e1812010-06-30 11:49:17 -0700241validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700242 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700243{
244 if (shader == NULL)
245 return true;
246
Ian Romanick832dfa52010-06-17 15:04:20 -0700247 find_assignment_visitor find("gl_Position");
Eric Anholt16b68b12010-06-30 11:05:43 -0700248 find.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700249 if (!find.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700250 linker_error_printf(prog,
251 "vertex shader does not write to `gl_Position'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700252 return false;
253 }
254
255 return true;
256}
257
258
Ian Romanickc93b8f12010-06-17 15:20:22 -0700259/**
260 * Verify that a fragment shader executable meets all semantic requirements
261 *
262 * \param shader Fragment shader executable to be verified
263 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700264bool
Eric Anholt849e1812010-06-30 11:49:17 -0700265validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700266 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700267{
268 if (shader == NULL)
269 return true;
270
Ian Romanick832dfa52010-06-17 15:04:20 -0700271 find_assignment_visitor frag_color("gl_FragColor");
272 find_assignment_visitor frag_data("gl_FragData");
273
Eric Anholt16b68b12010-06-30 11:05:43 -0700274 frag_color.run(shader->ir);
275 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700276
Ian Romanick832dfa52010-06-17 15:04:20 -0700277 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700278 linker_error_printf(prog, "fragment shader writes to both "
279 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700280 return false;
281 }
282
283 return true;
284}
285
286
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700287/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700288 * Generate a string describing the mode of a variable
289 */
290static const char *
291mode_string(const ir_variable *var)
292{
293 switch (var->mode) {
294 case ir_var_auto:
295 return (var->read_only) ? "global constant" : "global variable";
296
297 case ir_var_uniform: return "uniform";
298 case ir_var_in: return "shader input";
299 case ir_var_out: return "shader output";
300 case ir_var_inout: return "shader inout";
Ian Romanick7e2aa912010-07-19 17:12:42 -0700301
302 case ir_var_temporary:
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700303 default:
304 assert(!"Should not get here.");
305 return "invalid variable";
306 }
307}
308
309
310/**
311 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700312 */
313bool
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700314cross_validate_globals(struct gl_shader_program *prog,
315 struct gl_shader **shader_list,
316 unsigned num_shaders,
317 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700318{
319 /* Examine all of the uniforms in all of the shaders and cross validate
320 * them.
321 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700322 glsl_symbol_table variables;
323 for (unsigned i = 0; i < num_shaders; i++) {
324 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700325 ir_variable *const var = ((ir_instruction *) node)->as_variable();
326
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700327 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700328 continue;
329
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700330 if (uniforms_only && (var->mode != ir_var_uniform))
331 continue;
332
Ian Romanick7e2aa912010-07-19 17:12:42 -0700333 /* Don't cross validate temporaries that are at global scope. These
334 * will eventually get pulled into the shaders 'main'.
335 */
336 if (var->mode == ir_var_temporary)
337 continue;
338
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700339 /* If a global with this name has already been seen, verify that the
340 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700341 * initializers, the values of the initializers must be the same.
342 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700343 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700344 if (existing != NULL) {
345 if (var->type != existing->type) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700346 linker_error_printf(prog, "%s `%s' declared as type "
Ian Romanickf36460e2010-06-23 12:07:22 -0700347 "`%s' and type `%s'\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700348 mode_string(var),
Ian Romanickf36460e2010-06-23 12:07:22 -0700349 var->name, var->type->name,
350 existing->type->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700351 return false;
352 }
353
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700354 /* FINISHME: Handle non-constant initializers.
355 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700356 if (var->constant_value != NULL) {
357 if (existing->constant_value != NULL) {
358 if (!var->constant_value->has_value(existing->constant_value)) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700359 linker_error_printf(prog, "initializers for %s "
Ian Romanickf36460e2010-06-23 12:07:22 -0700360 "`%s' have differing values\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700361 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700362 return false;
363 }
364 } else
365 /* If the first-seen instance of a particular uniform did not
366 * have an initializer but a later instance does, copy the
367 * initializer to the version stored in the symbol table.
368 */
Ian Romanickde415b72010-07-14 13:22:12 -0700369 /* FINISHME: This is wrong. The constant_value field should
370 * FINISHME: not be modified! Imagine a case where a shader
371 * FINISHME: without an initializer is linked in two different
372 * FINISHME: programs with shaders that have differing
373 * FINISHME: initializers. Linking with the first will
374 * FINISHME: modify the shader, and linking with the second
375 * FINISHME: will fail.
376 */
Eric Anholt8273bd42010-08-04 12:34:56 -0700377 existing->constant_value =
378 var->constant_value->clone(talloc_parent(existing), NULL);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700379 }
380 } else
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700381 variables.add_variable(var->name, var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700382 }
383 }
384
385 return true;
386}
387
388
Ian Romanick37101922010-06-18 19:02:10 -0700389/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700390 * Perform validation of uniforms used across multiple shader stages
391 */
392bool
393cross_validate_uniforms(struct gl_shader_program *prog)
394{
395 return cross_validate_globals(prog, prog->_LinkedShaders,
396 prog->_NumLinkedShaders, true);
397}
398
399
400/**
Ian Romanick37101922010-06-18 19:02:10 -0700401 * Validate that outputs from one stage match inputs of another
402 */
403bool
Eric Anholt849e1812010-06-30 11:49:17 -0700404cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700405 gl_shader *producer, gl_shader *consumer)
Ian Romanick37101922010-06-18 19:02:10 -0700406{
407 glsl_symbol_table parameters;
408 /* FINISHME: Figure these out dynamically. */
409 const char *const producer_stage = "vertex";
410 const char *const consumer_stage = "fragment";
411
412 /* Find all shader outputs in the "producer" stage.
413 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700414 foreach_list(node, producer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700415 ir_variable *const var = ((ir_instruction *) node)->as_variable();
416
417 /* FINISHME: For geometry shaders, this should also look for inout
418 * FINISHME: variables.
419 */
420 if ((var == NULL) || (var->mode != ir_var_out))
421 continue;
422
423 parameters.add_variable(var->name, var);
424 }
425
426
427 /* Find all shader inputs in the "consumer" stage. Any variables that have
428 * matching outputs already in the symbol table must have the same type and
429 * qualifiers.
430 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700431 foreach_list(node, consumer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700432 ir_variable *const input = ((ir_instruction *) node)->as_variable();
433
434 /* FINISHME: For geometry shaders, this should also look for inout
435 * FINISHME: variables.
436 */
437 if ((input == NULL) || (input->mode != ir_var_in))
438 continue;
439
440 ir_variable *const output = parameters.get_variable(input->name);
441 if (output != NULL) {
442 /* Check that the types match between stages.
443 */
444 if (input->type != output->type) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700445 linker_error_printf(prog,
446 "%s shader output `%s' delcared as "
447 "type `%s', but %s shader input declared "
448 "as type `%s'\n",
449 producer_stage, output->name,
450 output->type->name,
451 consumer_stage, input->type->name);
Ian Romanick37101922010-06-18 19:02:10 -0700452 return false;
453 }
454
455 /* Check that all of the qualifiers match between stages.
456 */
457 if (input->centroid != output->centroid) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700458 linker_error_printf(prog,
459 "%s shader output `%s' %s centroid qualifier, "
460 "but %s shader input %s centroid qualifier\n",
461 producer_stage,
462 output->name,
463 (output->centroid) ? "has" : "lacks",
464 consumer_stage,
465 (input->centroid) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700466 return false;
467 }
468
469 if (input->invariant != output->invariant) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700470 linker_error_printf(prog,
471 "%s shader output `%s' %s invariant qualifier, "
472 "but %s shader input %s invariant qualifier\n",
473 producer_stage,
474 output->name,
475 (output->invariant) ? "has" : "lacks",
476 consumer_stage,
477 (input->invariant) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700478 return false;
479 }
480
481 if (input->interpolation != output->interpolation) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700482 linker_error_printf(prog,
483 "%s shader output `%s' specifies %s "
484 "interpolation qualifier, "
485 "but %s shader input specifies %s "
486 "interpolation qualifier\n",
487 producer_stage,
488 output->name,
489 output->interpolation_string(),
490 consumer_stage,
491 input->interpolation_string());
Ian Romanick37101922010-06-18 19:02:10 -0700492 return false;
493 }
494 }
495 }
496
497 return true;
498}
499
500
Ian Romanick3fb87872010-07-09 14:09:34 -0700501/**
502 * Populates a shaders symbol table with all global declarations
503 */
504static void
505populate_symbol_table(gl_shader *sh)
506{
507 sh->symbols = new(sh) glsl_symbol_table;
508
509 foreach_list(node, sh->ir) {
510 ir_instruction *const inst = (ir_instruction *) node;
511 ir_variable *var;
512 ir_function *func;
513
514 if ((func = inst->as_function()) != NULL) {
515 sh->symbols->add_function(func->name, func);
516 } else if ((var = inst->as_variable()) != NULL) {
517 sh->symbols->add_variable(var->name, var);
518 }
519 }
520}
521
522
523/**
Ian Romanick31a97862010-07-12 18:48:50 -0700524 * Remap variables referenced in an instruction tree
525 *
526 * This is used when instruction trees are cloned from one shader and placed in
527 * another. These trees will contain references to \c ir_variable nodes that
528 * do not exist in the target shader. This function finds these \c ir_variable
529 * references and replaces the references with matching variables in the target
530 * shader.
531 *
532 * If there is no matching variable in the target shader, a clone of the
533 * \c ir_variable is made and added to the target shader. The new variable is
534 * added to \b both the instruction stream and the symbol table.
535 *
536 * \param inst IR tree that is to be processed.
537 * \param symbols Symbol table containing global scope symbols in the
538 * linked shader.
539 * \param instructions Instruction stream where new variable declarations
540 * should be added.
541 */
542void
Eric Anholt8273bd42010-08-04 12:34:56 -0700543remap_variables(ir_instruction *inst, struct gl_shader *target,
544 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700545{
546 class remap_visitor : public ir_hierarchical_visitor {
547 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700548 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700549 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700550 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700551 this->target = target;
552 this->symbols = target->symbols;
553 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700554 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700555 }
556
557 virtual ir_visitor_status visit(ir_dereference_variable *ir)
558 {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700559 if (ir->var->mode == ir_var_temporary) {
560 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
561
562 assert(var != NULL);
563 ir->var = var;
564 return visit_continue;
565 }
566
Ian Romanick31a97862010-07-12 18:48:50 -0700567 ir_variable *const existing =
568 this->symbols->get_variable(ir->var->name);
569 if (existing != NULL)
570 ir->var = existing;
571 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700572 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700573
574 this->symbols->add_variable(copy->name, copy);
575 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700576 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700577 }
578
579 return visit_continue;
580 }
581
582 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700583 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700584 glsl_symbol_table *symbols;
585 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700586 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700587 };
588
Eric Anholt8273bd42010-08-04 12:34:56 -0700589 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700590
591 inst->accept(&v);
592}
593
594
595/**
596 * Move non-declarations from one instruction stream to another
597 *
598 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700599 * 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 -0700600 * pointer) for \c last and \c false for \c make_copies on the first
601 * call. Successive calls pass the return value of the previous call for
602 * \c last and \c true for \c make_copies.
603 *
604 * \param instructions Source instruction stream
605 * \param last Instruction after which new instructions should be
606 * inserted in the target instruction stream
607 * \param make_copies Flag selecting whether instructions in \c instructions
608 * should be copied (via \c ir_instruction::clone) into the
609 * target list or moved.
610 *
611 * \return
612 * The new "last" instruction in the target instruction stream. This pointer
613 * is suitable for use as the \c last parameter of a later call to this
614 * function.
615 */
616exec_node *
617move_non_declarations(exec_list *instructions, exec_node *last,
618 bool make_copies, gl_shader *target)
619{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700620 hash_table *temps = NULL;
621
622 if (make_copies)
623 temps = hash_table_ctor(0, hash_table_pointer_hash,
624 hash_table_pointer_compare);
625
Ian Romanick303c99f2010-07-19 12:34:56 -0700626 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700627 ir_instruction *inst = (ir_instruction *) node;
628
Ian Romanick7e2aa912010-07-19 17:12:42 -0700629 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700630 continue;
631
Ian Romanick7e2aa912010-07-19 17:12:42 -0700632 ir_variable *var = inst->as_variable();
633 if ((var != NULL) && (var->mode != ir_var_temporary))
634 continue;
635
636 assert(inst->as_assignment()
637 || ((var != NULL) && (var->mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700638
639 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700640 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700641
642 if (var != NULL)
643 hash_table_insert(temps, inst, var);
644 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700645 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700646 } else {
647 inst->remove();
648 }
649
650 last->insert_after(inst);
651 last = inst;
652 }
653
Ian Romanick7e2aa912010-07-19 17:12:42 -0700654 if (make_copies)
655 hash_table_dtor(temps);
656
Ian Romanick31a97862010-07-12 18:48:50 -0700657 return last;
658}
659
660/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700661 * Get the function signature for main from a shader
662 */
663static ir_function_signature *
664get_main_function_signature(gl_shader *sh)
665{
666 ir_function *const f = sh->symbols->get_function("main");
667 if (f != NULL) {
668 exec_list void_parameters;
669
670 /* Look for the 'void main()' signature and ensure that it's defined.
671 * This keeps the linker from accidentally pick a shader that just
672 * contains a prototype for main.
673 *
674 * We don't have to check for multiple definitions of main (in multiple
675 * shaders) because that would have already been caught above.
676 */
677 ir_function_signature *sig = f->matching_signature(&void_parameters);
678 if ((sig != NULL) && sig->is_defined) {
679 return sig;
680 }
681 }
682
683 return NULL;
684}
685
686
687/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700688 * Combine a group of shaders for a single stage to generate a linked shader
689 *
690 * \note
691 * If this function is supplied a single shader, it is cloned, and the new
692 * shader is returned.
693 */
694static struct gl_shader *
Eric Anholt5d0f4302010-08-18 12:02:35 -0700695link_intrastage_shaders(GLcontext *ctx,
696 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -0700697 struct gl_shader **shader_list,
698 unsigned num_shaders)
699{
Ian Romanick13f782c2010-06-29 18:53:38 -0700700 /* Check that global variables defined in multiple shaders are consistent.
701 */
702 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
703 return NULL;
704
705 /* Check that there is only a single definition of each function signature
706 * across all shaders.
707 */
708 for (unsigned i = 0; i < (num_shaders - 1); i++) {
709 foreach_list(node, shader_list[i]->ir) {
710 ir_function *const f = ((ir_instruction *) node)->as_function();
711
712 if (f == NULL)
713 continue;
714
715 for (unsigned j = i + 1; j < num_shaders; j++) {
716 ir_function *const other =
717 shader_list[j]->symbols->get_function(f->name);
718
719 /* If the other shader has no function (and therefore no function
720 * signatures) with the same name, skip to the next shader.
721 */
722 if (other == NULL)
723 continue;
724
725 foreach_iter (exec_list_iterator, iter, *f) {
726 ir_function_signature *sig =
727 (ir_function_signature *) iter.get();
728
729 if (!sig->is_defined || sig->is_built_in)
730 continue;
731
732 ir_function_signature *other_sig =
733 other->exact_matching_signature(& sig->parameters);
734
735 if ((other_sig != NULL) && other_sig->is_defined
736 && !other_sig->is_built_in) {
737 linker_error_printf(prog,
738 "function `%s' is multiply defined",
739 f->name);
740 return NULL;
741 }
742 }
743 }
744 }
745 }
746
747 /* Find the shader that defines main, and make a clone of it.
748 *
749 * Starting with the clone, search for undefined references. If one is
750 * found, find the shader that defines it. Clone the reference and add
751 * it to the shader. Repeat until there are no undefined references or
752 * until a reference cannot be resolved.
753 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700754 gl_shader *main = NULL;
755 for (unsigned i = 0; i < num_shaders; i++) {
756 if (get_main_function_signature(shader_list[i]) != NULL) {
757 main = shader_list[i];
758 break;
759 }
760 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700761
Ian Romanick15ce87e2010-07-09 15:28:22 -0700762 if (main == NULL) {
763 linker_error_printf(prog, "%s shader lacks `main'\n",
764 (shader_list[0]->Type == GL_VERTEX_SHADER)
765 ? "vertex" : "fragment");
766 return NULL;
767 }
768
Eric Anholt5d0f4302010-08-18 12:02:35 -0700769 gl_shader *const linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700770 linked->ir = new(linked) exec_list;
Eric Anholt8273bd42010-08-04 12:34:56 -0700771 clone_ir_list(linked, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700772
773 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700774
Ian Romanick31a97862010-07-12 18:48:50 -0700775 /* The a pointer to the main function in the final linked shader (i.e., the
776 * copy of the original shader that contained the main function).
777 */
778 ir_function_signature *const main_sig = get_main_function_signature(linked);
779
780 /* Move any instructions other than variable declarations or function
781 * declarations into main.
782 */
Ian Romanick9303e352010-07-19 12:33:54 -0700783 exec_node *insertion_point =
784 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
785 linked);
786
Ian Romanick31a97862010-07-12 18:48:50 -0700787 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -0700788 if (shader_list[i] == main)
789 continue;
790
Ian Romanick31a97862010-07-12 18:48:50 -0700791 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -0700792 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -0700793 }
794
Ian Romanick13f782c2010-06-29 18:53:38 -0700795 /* Resolve initializers for global variables in the linked shader.
796 */
Ian Romanickd5be2ac2010-07-20 11:29:46 -0700797 unsigned num_linking_shaders = num_shaders;
798 for (unsigned i = 0; i < num_shaders; i++)
799 num_linking_shaders += shader_list[i]->num_builtins_to_link;
800
801 gl_shader **linking_shaders =
802 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
803
804 memcpy(linking_shaders, shader_list,
805 sizeof(linking_shaders[0]) * num_shaders);
806
807 unsigned idx = num_shaders;
808 for (unsigned i = 0; i < num_shaders; i++) {
809 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
810 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
811 idx += shader_list[i]->num_builtins_to_link;
812 }
813
814 assert(idx == num_linking_shaders);
815
816 link_function_calls(prog, linked, linking_shaders, num_linking_shaders);
817
818 free(linking_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -0700819
Ian Romanick3fb87872010-07-09 14:09:34 -0700820 return linked;
821}
822
823
Ian Romanick019a59b2010-06-21 16:10:42 -0700824struct uniform_node {
825 exec_node link;
826 struct gl_uniform *u;
827 unsigned slots;
828};
829
Eric Anholta721abf2010-08-23 10:32:01 -0700830/**
831 * Update the sizes of linked shader uniform arrays to the maximum
832 * array index used.
833 *
834 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
835 *
836 * If one or more elements of an array are active,
837 * GetActiveUniform will return the name of the array in name,
838 * subject to the restrictions listed above. The type of the array
839 * is returned in type. The size parameter contains the highest
840 * array element index used, plus one. The compiler or linker
841 * determines the highest index used. There will be only one
842 * active uniform reported by the GL per uniform array.
843
844 */
845static void
846update_uniform_array_sizes(struct gl_shader_program *prog)
847{
848 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
849 foreach_list(node, prog->_LinkedShaders[i]->ir) {
850 ir_variable *const var = ((ir_instruction *) node)->as_variable();
851
852 if ((var == NULL) || (var->mode != ir_var_uniform) ||
853 !var->type->is_array())
854 continue;
855
856 unsigned int size = var->max_array_access;
857 for (unsigned j = 0; j < prog->_NumLinkedShaders; j++) {
858 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
859 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
860 if (!other_var)
861 continue;
862
863 if (strcmp(var->name, other_var->name) == 0 &&
864 other_var->max_array_access > size) {
865 size = other_var->max_array_access;
866 }
867 }
868 }
869 if (size + 1 != var->type->fields.array->length) {
870 var->type = glsl_type::get_array_instance(var->type->fields.array,
871 size + 1);
872 /* FINISHME: We should update the types of array
873 * dereferences of this variable now.
874 */
875 }
876 }
877 }
878}
879
Ian Romanickabee16e2010-06-21 16:16:05 -0700880void
Eric Anholt849e1812010-06-30 11:49:17 -0700881assign_uniform_locations(struct gl_shader_program *prog)
Ian Romanick019a59b2010-06-21 16:10:42 -0700882{
883 /* */
884 exec_list uniforms;
885 unsigned total_uniforms = 0;
886 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
887 hash_table_string_compare);
888
Eric Anholta721abf2010-08-23 10:32:01 -0700889 update_uniform_array_sizes(prog);
890
Ian Romanickabee16e2010-06-21 16:16:05 -0700891 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700892 unsigned next_position = 0;
893
Eric Anholt16b68b12010-06-30 11:05:43 -0700894 foreach_list(node, prog->_LinkedShaders[i]->ir) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700895 ir_variable *const var = ((ir_instruction *) node)->as_variable();
896
897 if ((var == NULL) || (var->mode != ir_var_uniform))
898 continue;
899
900 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
Eric Anholt8d61a232010-08-05 16:00:46 -0700901 if (vec4_slots == 0) {
902 /* If we've got a sampler or an aggregate of them, the size can
903 * end up zero. Don't allocate any space.
904 */
905 continue;
906 }
Ian Romanick019a59b2010-06-21 16:10:42 -0700907
908 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
909 if (n == NULL) {
910 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
911 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
912 n->slots = vec4_slots;
913
914 n->u[0].Name = strdup(var->name);
915 for (unsigned j = 1; j < vec4_slots; j++)
Eric Anholtf1d5a942010-08-18 17:39:57 -0700916 n->u[j].Name = strdup(var->name);
Ian Romanick019a59b2010-06-21 16:10:42 -0700917
918 hash_table_insert(ht, n, n->u[0].Name);
919 uniforms.push_tail(& n->link);
920 total_uniforms += vec4_slots;
921 }
922
923 if (var->constant_value != NULL)
924 for (unsigned j = 0; j < vec4_slots; j++)
925 n->u[j].Initialized = true;
926
927 var->location = next_position;
928
929 for (unsigned j = 0; j < vec4_slots; j++) {
Ian Romanickabee16e2010-06-21 16:16:05 -0700930 switch (prog->_LinkedShaders[i]->Type) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700931 case GL_VERTEX_SHADER:
932 n->u[j].VertPos = next_position;
933 break;
934 case GL_FRAGMENT_SHADER:
935 n->u[j].FragPos = next_position;
936 break;
937 case GL_GEOMETRY_SHADER:
938 /* FINISHME: Support geometry shaders. */
Ian Romanickabee16e2010-06-21 16:16:05 -0700939 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
Ian Romanick019a59b2010-06-21 16:10:42 -0700940 break;
941 }
942
943 next_position++;
944 }
945 }
946 }
947
948 gl_uniform_list *ul = (gl_uniform_list *)
949 calloc(1, sizeof(gl_uniform_list));
950
951 ul->Size = total_uniforms;
952 ul->NumUniforms = total_uniforms;
953 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
954
955 unsigned idx = 0;
956 uniform_node *next;
957 for (uniform_node *node = (uniform_node *) uniforms.head
958 ; node->link.next != NULL
959 ; node = next) {
960 next = (uniform_node *) node->link.next;
961
962 node->link.remove();
963 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
964 idx += node->slots;
965
966 free(node->u);
967 free(node);
968 }
969
970 hash_table_dtor(ht);
971
Ian Romanickabee16e2010-06-21 16:16:05 -0700972 prog->Uniforms = ul;
Ian Romanick019a59b2010-06-21 16:10:42 -0700973}
974
975
Ian Romanick69846702010-06-22 17:29:19 -0700976/**
977 * Find a contiguous set of available bits in a bitmask
978 *
979 * \param used_mask Bits representing used (1) and unused (0) locations
980 * \param needed_count Number of contiguous bits needed.
981 *
982 * \return
983 * Base location of the available bits on success or -1 on failure.
984 */
985int
986find_available_slots(unsigned used_mask, unsigned needed_count)
987{
988 unsigned needed_mask = (1 << needed_count) - 1;
989 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
990
991 /* The comparison to 32 is redundant, but without it GCC emits "warning:
992 * cannot optimize possibly infinite loops" for the loop below.
993 */
994 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
995 return -1;
996
997 for (int i = 0; i <= max_bit_to_test; i++) {
998 if ((needed_mask & ~used_mask) == needed_mask)
999 return i;
1000
1001 needed_mask <<= 1;
1002 }
1003
1004 return -1;
1005}
1006
1007
1008bool
Eric Anholt849e1812010-06-30 11:49:17 -07001009assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001010{
Ian Romanick9342d262010-06-22 17:41:37 -07001011 /* Mark invalid attribute locations as being used.
1012 */
1013 unsigned used_locations = (max_attribute_index >= 32)
1014 ? ~0 : ~((1 << max_attribute_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001015
Eric Anholt16b68b12010-06-30 11:05:43 -07001016 gl_shader *const sh = prog->_LinkedShaders[0];
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001017 assert(sh->Type == GL_VERTEX_SHADER);
1018
Ian Romanick69846702010-06-22 17:29:19 -07001019 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001020 *
1021 * 1. Invalidate the location assignments for all vertex shader inputs.
1022 *
1023 * 2. Assign locations for inputs that have user-defined (via
1024 * glBindVertexAttribLocation) locatoins.
1025 *
Ian Romanick69846702010-06-22 17:29:19 -07001026 * 3. Sort the attributes without assigned locations by number of slots
1027 * required in decreasing order. Fragmentation caused by attribute
1028 * locations assigned by the application may prevent large attributes
1029 * from having enough contiguous space.
1030 *
1031 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001032 */
1033
1034 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1035
Ian Romanick553dcdc2010-06-23 12:14:02 -07001036 if (prog->Attributes != NULL) {
1037 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001038 ir_variable *const var =
Ian Romanick553dcdc2010-06-23 12:14:02 -07001039 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001040
Ian Romanick69846702010-06-22 17:29:19 -07001041 /* Note: attributes that occupy multiple slots, such as arrays or
1042 * matrices, may appear in the attrib array multiple times.
1043 */
1044 if ((var == NULL) || (var->location != -1))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001045 continue;
1046
Ian Romanick69846702010-06-22 17:29:19 -07001047 /* From page 61 of the OpenGL 4.0 spec:
1048 *
1049 * "LinkProgram will fail if the attribute bindings assigned by
1050 * BindAttribLocation do not leave not enough space to assign a
1051 * location for an active matrix attribute or an active attribute
1052 * array, both of which require multiple contiguous generic
1053 * attributes."
1054 *
1055 * Previous versions of the spec contain similar language but omit the
1056 * bit about attribute arrays.
1057 *
1058 * Page 61 of the OpenGL 4.0 spec also says:
1059 *
1060 * "It is possible for an application to bind more than one
1061 * attribute name to the same location. This is referred to as
1062 * aliasing. This will only work if only one of the aliased
1063 * attributes is active in the executable program, or if no path
1064 * through the shader consumes more than one attribute of a set
1065 * of attributes aliased to the same location. A link error can
1066 * occur if the linker determines that every path through the
1067 * shader consumes multiple aliased attributes, but
1068 * implementations are not required to generate an error in this
1069 * case."
1070 *
1071 * These two paragraphs are either somewhat contradictory, or I don't
1072 * fully understand one or both of them.
1073 */
1074 /* FINISHME: The code as currently written does not support attribute
1075 * FINISHME: location aliasing (see comment above).
1076 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001077 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
Ian Romanick69846702010-06-22 17:29:19 -07001078 const unsigned slots = count_attribute_slots(var->type);
1079
1080 /* Mask representing the contiguous slots that will be used by this
1081 * attribute.
1082 */
1083 const unsigned use_mask = (1 << slots) - 1;
1084
1085 /* Generate a link error if the set of bits requested for this
1086 * attribute overlaps any previously allocated bits.
1087 */
1088 if ((~(use_mask << attr) & used_locations) != used_locations) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001089 linker_error_printf(prog,
1090 "insufficient contiguous attribute locations "
1091 "available for vertex shader input `%s'",
1092 var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001093 return false;
1094 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001095
1096 var->location = VERT_ATTRIB_GENERIC0 + attr;
Ian Romanick69846702010-06-22 17:29:19 -07001097 used_locations |= (use_mask << attr);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001098 }
1099 }
1100
Ian Romanick69846702010-06-22 17:29:19 -07001101 /* Temporary storage for the set of attributes that need locations assigned.
1102 */
1103 struct temp_attr {
1104 unsigned slots;
1105 ir_variable *var;
1106
1107 /* Used below in the call to qsort. */
1108 static int compare(const void *a, const void *b)
1109 {
1110 const temp_attr *const l = (const temp_attr *) a;
1111 const temp_attr *const r = (const temp_attr *) b;
1112
1113 /* Reversed because we want a descending order sort below. */
1114 return r->slots - l->slots;
1115 }
1116 } to_assign[16];
1117
1118 unsigned num_attr = 0;
1119
Eric Anholt16b68b12010-06-30 11:05:43 -07001120 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001121 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1122
1123 if ((var == NULL) || (var->mode != ir_var_in))
1124 continue;
1125
1126 /* The location was explicitly assigned, nothing to do here.
1127 */
1128 if (var->location != -1)
1129 continue;
1130
Ian Romanick69846702010-06-22 17:29:19 -07001131 to_assign[num_attr].slots = count_attribute_slots(var->type);
1132 to_assign[num_attr].var = var;
1133 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001134 }
Ian Romanick69846702010-06-22 17:29:19 -07001135
1136 /* If all of the attributes were assigned locations by the application (or
1137 * are built-in attributes with fixed locations), return early. This should
1138 * be the common case.
1139 */
1140 if (num_attr == 0)
1141 return true;
1142
1143 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1144
Ian Romanick982e3792010-06-29 18:58:20 -07001145 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1146 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1147 * to prevent it from being automatically allocated below.
1148 */
Ian Romanickc33e78f2010-08-13 12:30:41 -07001149 find_deref_visitor find("gl_Vertex");
1150 find.run(sh->ir);
1151 if (find.variable_found())
1152 used_locations |= (1 << 0);
Ian Romanick982e3792010-06-29 18:58:20 -07001153
Ian Romanick69846702010-06-22 17:29:19 -07001154 for (unsigned i = 0; i < num_attr; i++) {
1155 /* Mask representing the contiguous slots that will be used by this
1156 * attribute.
1157 */
1158 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1159
1160 int location = find_available_slots(used_locations, to_assign[i].slots);
1161
1162 if (location < 0) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001163 linker_error_printf(prog,
1164 "insufficient contiguous attribute locations "
1165 "available for vertex shader input `%s'",
1166 to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001167 return false;
1168 }
1169
1170 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1171 used_locations |= (use_mask << location);
1172 }
1173
1174 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001175}
1176
1177
Ian Romanick40e114b2010-08-17 14:55:50 -07001178/**
1179 * Demote shader outputs that are not read to being just plain global variables
1180 */
1181void
1182demote_unread_shader_outputs(gl_shader *sh)
1183{
1184 foreach_list(node, sh->ir) {
1185 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1186
1187 if ((var == NULL) || (var->mode != ir_var_out))
1188 continue;
1189
1190 /* An 'out' variable is only really a shader output if its value is read
1191 * by the following stage.
1192 */
1193 if (var->location == -1) {
1194 var->mode = ir_var_auto;
1195 }
1196 }
1197}
1198
1199
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001200void
Eric Anholtb7062832010-07-28 13:52:23 -07001201assign_varying_locations(struct gl_shader_program *prog,
1202 gl_shader *producer, gl_shader *consumer)
Ian Romanick0e59b262010-06-23 11:23:01 -07001203{
1204 /* FINISHME: Set dynamically when geometry shader support is added. */
1205 unsigned output_index = VERT_RESULT_VAR0;
1206 unsigned input_index = FRAG_ATTRIB_VAR0;
1207
1208 /* Operate in a total of three passes.
1209 *
1210 * 1. Assign locations for any matching inputs and outputs.
1211 *
1212 * 2. Mark output variables in the producer that do not have locations as
1213 * not being outputs. This lets the optimizer eliminate them.
1214 *
1215 * 3. Mark input variables in the consumer that do not have locations as
1216 * not being inputs. This lets the optimizer eliminate them.
1217 */
1218
1219 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1220 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1221
Eric Anholt16b68b12010-06-30 11:05:43 -07001222 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001223 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1224
1225 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1226 || (output_var->location != -1))
1227 continue;
1228
1229 ir_variable *const input_var =
1230 consumer->symbols->get_variable(output_var->name);
1231
1232 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1233 continue;
1234
1235 assert(input_var->location == -1);
1236
1237 /* FINISHME: Location assignment will need some changes when arrays,
1238 * FINISHME: matrices, and structures are allowed as shader inputs /
1239 * FINISHME: outputs.
1240 */
1241 output_var->location = output_index;
1242 input_var->location = input_index;
1243
1244 output_index++;
1245 input_index++;
1246 }
1247
Ian Romanick40e114b2010-08-17 14:55:50 -07001248 demote_unread_shader_outputs(producer);
Ian Romanick0e59b262010-06-23 11:23:01 -07001249
Eric Anholt16b68b12010-06-30 11:05:43 -07001250 foreach_list(node, consumer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001251 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1252
1253 if ((var == NULL) || (var->mode != ir_var_in))
1254 continue;
1255
Eric Anholtb7062832010-07-28 13:52:23 -07001256 if (var->location == -1) {
1257 if (prog->Version <= 120) {
1258 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1259 *
1260 * Only those varying variables used (i.e. read) in
1261 * the fragment shader executable must be written to
1262 * by the vertex shader executable; declaring
1263 * superfluous varying variables in a vertex shader is
1264 * permissible.
1265 *
1266 * We interpret this text as meaning that the VS must
1267 * write the variable for the FS to read it. See
1268 * "glsl1-varying read but not written" in piglit.
1269 */
1270
1271 linker_error_printf(prog, "fragment shader varying %s not written "
1272 "by vertex shader\n.", var->name);
1273 prog->LinkStatus = false;
1274 }
1275
1276 /* An 'in' variable is only really a shader input if its
1277 * value is written by the previous stage.
1278 */
Eric Anholtb7062832010-07-28 13:52:23 -07001279 var->mode = ir_var_auto;
1280 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001281 }
1282}
1283
1284
1285void
Eric Anholt5d0f4302010-08-18 12:02:35 -07001286link_shaders(GLcontext *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07001287{
1288 prog->LinkStatus = false;
1289 prog->Validated = false;
1290 prog->_Used = false;
1291
Ian Romanickf36460e2010-06-23 12:07:22 -07001292 if (prog->InfoLog != NULL)
1293 talloc_free(prog->InfoLog);
1294
1295 prog->InfoLog = talloc_strdup(NULL, "");
1296
Ian Romanick832dfa52010-06-17 15:04:20 -07001297 /* Separate the shaders into groups based on their type.
1298 */
Eric Anholt16b68b12010-06-30 11:05:43 -07001299 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001300 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07001301 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001302 unsigned num_frag_shaders = 0;
1303
Eric Anholt16b68b12010-06-30 11:05:43 -07001304 vert_shader_list = (struct gl_shader **)
1305 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07001306 frag_shader_list = &vert_shader_list[prog->NumShaders];
1307
Ian Romanick25f51d32010-07-16 15:51:50 -07001308 unsigned min_version = UINT_MAX;
1309 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07001310 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07001311 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1312 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1313
Ian Romanick832dfa52010-06-17 15:04:20 -07001314 switch (prog->Shaders[i]->Type) {
1315 case GL_VERTEX_SHADER:
1316 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1317 num_vert_shaders++;
1318 break;
1319 case GL_FRAGMENT_SHADER:
1320 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1321 num_frag_shaders++;
1322 break;
1323 case GL_GEOMETRY_SHADER:
1324 /* FINISHME: Support geometry shaders. */
1325 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1326 break;
1327 }
1328 }
1329
Ian Romanick25f51d32010-07-16 15:51:50 -07001330 /* Previous to GLSL version 1.30, different compilation units could mix and
1331 * match shading language versions. With GLSL 1.30 and later, the versions
1332 * of all shaders must match.
1333 */
1334 assert(min_version >= 110);
1335 assert(max_version <= 130);
1336 if ((max_version >= 130) && (min_version != max_version)) {
1337 linker_error_printf(prog, "all shaders must use same shading "
1338 "language version\n");
1339 goto done;
1340 }
1341
1342 prog->Version = max_version;
1343
Eric Anholt5d0f4302010-08-18 12:02:35 -07001344 for (unsigned int i = 0; i < prog->_NumLinkedShaders; i++) {
1345 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1346 }
1347
Ian Romanickcd6764e2010-07-16 16:00:07 -07001348 /* Link all shaders for a particular stage and validate the result.
1349 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001350 prog->_NumLinkedShaders = 0;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001351 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001352 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001353 link_intrastage_shaders(ctx, prog, vert_shader_list, num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001354
1355 if (sh == NULL)
1356 goto done;
1357
1358 if (!validate_vertex_shader_executable(prog, sh))
1359 goto done;
1360
1361 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001362 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001363 }
1364
1365 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001366 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001367 link_intrastage_shaders(ctx, prog, frag_shader_list, num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001368
1369 if (sh == NULL)
1370 goto done;
1371
1372 if (!validate_fragment_shader_executable(prog, sh))
1373 goto done;
1374
1375 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001376 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001377 }
1378
Ian Romanick3ed850e2010-06-23 12:18:21 -07001379 /* Here begins the inter-stage linking phase. Some initial validation is
1380 * performed, then locations are assigned for uniforms, attributes, and
1381 * varyings.
1382 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001383 if (cross_validate_uniforms(prog)) {
Ian Romanick37101922010-06-18 19:02:10 -07001384 /* Validate the inputs of each stage with the output of the preceeding
1385 * stage.
1386 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001387 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
Ian Romanickf36460e2010-06-23 12:07:22 -07001388 if (!cross_validate_outputs_to_inputs(prog,
1389 prog->_LinkedShaders[i - 1],
Ian Romanickabee16e2010-06-21 16:16:05 -07001390 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001391 goto done;
1392 }
1393
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001394 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001395 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001396
Eric Anholt2f4fe152010-08-10 13:06:49 -07001397 /* Do common optimization before assigning storage for attributes,
1398 * uniforms, and varyings. Later optimization could possibly make
1399 * some of that unused.
1400 */
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001401 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Eric Anholt2f4fe152010-08-10 13:06:49 -07001402 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true))
1403 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001404 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001405
Ian Romanickabee16e2010-06-21 16:16:05 -07001406 assign_uniform_locations(prog);
Ian Romanick13e10e42010-06-21 12:03:24 -07001407
Ian Romanick40e114b2010-08-17 14:55:50 -07001408 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER) {
Ian Romanick9342d262010-06-22 17:41:37 -07001409 /* FINISHME: The value of the max_attribute_index parameter is
1410 * FINISHME: implementation dependent based on the value of
1411 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1412 * FINISHME: at least 16, so hardcode 16 for now.
1413 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001414 if (!assign_attribute_locations(prog, 16))
Ian Romanick69846702010-06-22 17:29:19 -07001415 goto done;
Ian Romanick13e10e42010-06-21 12:03:24 -07001416
Ian Romanick40e114b2010-08-17 14:55:50 -07001417 if (prog->_NumLinkedShaders == 1)
1418 demote_unread_shader_outputs(prog->_LinkedShaders[0]);
1419 }
1420
Ian Romanick0e59b262010-06-23 11:23:01 -07001421 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
Eric Anholtb7062832010-07-28 13:52:23 -07001422 assign_varying_locations(prog,
1423 prog->_LinkedShaders[i - 1],
Ian Romanick0e59b262010-06-23 11:23:01 -07001424 prog->_LinkedShaders[i]);
Ian Romanick13e10e42010-06-21 12:03:24 -07001425
1426 /* FINISHME: Assign fragment shader output locations. */
1427
Ian Romanick832dfa52010-06-17 15:04:20 -07001428done:
1429 free(vert_shader_list);
1430}