blob: 56e0bfd2386e945cab5b4501a8c3cf4f732bf84f [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 Romanicka2711d62010-08-29 22:07:49 -0700346 /* Consider the types to be "the same" if both types are arrays
347 * of the same type and one of the arrays is implicitly sized.
348 * In addition, set the type of the linked variable to the
349 * explicitly sized array.
350 */
351 if (var->type->is_array()
352 && existing->type->is_array()
353 && (var->type->fields.array == existing->type->fields.array)
354 && ((var->type->length == 0)
355 || (existing->type->length == 0))) {
356 if (existing->type->length == 0)
357 existing->type = var->type;
358 } else {
359 linker_error_printf(prog, "%s `%s' declared as type "
360 "`%s' and type `%s'\n",
361 mode_string(var),
362 var->name, var->type->name,
363 existing->type->name);
364 return false;
365 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700366 }
367
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700368 /* FINISHME: Handle non-constant initializers.
369 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700370 if (var->constant_value != NULL) {
371 if (existing->constant_value != NULL) {
372 if (!var->constant_value->has_value(existing->constant_value)) {
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700373 linker_error_printf(prog, "initializers for %s "
Ian Romanickf36460e2010-06-23 12:07:22 -0700374 "`%s' have differing values\n",
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700375 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700376 return false;
377 }
378 } else
379 /* If the first-seen instance of a particular uniform did not
380 * have an initializer but a later instance does, copy the
381 * initializer to the version stored in the symbol table.
382 */
Ian Romanickde415b72010-07-14 13:22:12 -0700383 /* FINISHME: This is wrong. The constant_value field should
384 * FINISHME: not be modified! Imagine a case where a shader
385 * FINISHME: without an initializer is linked in two different
386 * FINISHME: programs with shaders that have differing
387 * FINISHME: initializers. Linking with the first will
388 * FINISHME: modify the shader, and linking with the second
389 * FINISHME: will fail.
390 */
Eric Anholt8273bd42010-08-04 12:34:56 -0700391 existing->constant_value =
392 var->constant_value->clone(talloc_parent(existing), NULL);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700393 }
394 } else
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700395 variables.add_variable(var->name, var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700396 }
397 }
398
399 return true;
400}
401
402
Ian Romanick37101922010-06-18 19:02:10 -0700403/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700404 * Perform validation of uniforms used across multiple shader stages
405 */
406bool
407cross_validate_uniforms(struct gl_shader_program *prog)
408{
409 return cross_validate_globals(prog, prog->_LinkedShaders,
410 prog->_NumLinkedShaders, true);
411}
412
413
414/**
Ian Romanick37101922010-06-18 19:02:10 -0700415 * Validate that outputs from one stage match inputs of another
416 */
417bool
Eric Anholt849e1812010-06-30 11:49:17 -0700418cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700419 gl_shader *producer, gl_shader *consumer)
Ian Romanick37101922010-06-18 19:02:10 -0700420{
421 glsl_symbol_table parameters;
422 /* FINISHME: Figure these out dynamically. */
423 const char *const producer_stage = "vertex";
424 const char *const consumer_stage = "fragment";
425
426 /* Find all shader outputs in the "producer" stage.
427 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700428 foreach_list(node, producer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700429 ir_variable *const var = ((ir_instruction *) node)->as_variable();
430
431 /* FINISHME: For geometry shaders, this should also look for inout
432 * FINISHME: variables.
433 */
434 if ((var == NULL) || (var->mode != ir_var_out))
435 continue;
436
437 parameters.add_variable(var->name, var);
438 }
439
440
441 /* Find all shader inputs in the "consumer" stage. Any variables that have
442 * matching outputs already in the symbol table must have the same type and
443 * qualifiers.
444 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700445 foreach_list(node, consumer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700446 ir_variable *const input = ((ir_instruction *) node)->as_variable();
447
448 /* FINISHME: For geometry shaders, this should also look for inout
449 * FINISHME: variables.
450 */
451 if ((input == NULL) || (input->mode != ir_var_in))
452 continue;
453
454 ir_variable *const output = parameters.get_variable(input->name);
455 if (output != NULL) {
456 /* Check that the types match between stages.
457 */
458 if (input->type != output->type) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700459 linker_error_printf(prog,
460 "%s shader output `%s' delcared as "
461 "type `%s', but %s shader input declared "
462 "as type `%s'\n",
463 producer_stage, output->name,
464 output->type->name,
465 consumer_stage, input->type->name);
Ian Romanick37101922010-06-18 19:02:10 -0700466 return false;
467 }
468
469 /* Check that all of the qualifiers match between stages.
470 */
471 if (input->centroid != output->centroid) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700472 linker_error_printf(prog,
473 "%s shader output `%s' %s centroid qualifier, "
474 "but %s shader input %s centroid qualifier\n",
475 producer_stage,
476 output->name,
477 (output->centroid) ? "has" : "lacks",
478 consumer_stage,
479 (input->centroid) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700480 return false;
481 }
482
483 if (input->invariant != output->invariant) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700484 linker_error_printf(prog,
485 "%s shader output `%s' %s invariant qualifier, "
486 "but %s shader input %s invariant qualifier\n",
487 producer_stage,
488 output->name,
489 (output->invariant) ? "has" : "lacks",
490 consumer_stage,
491 (input->invariant) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700492 return false;
493 }
494
495 if (input->interpolation != output->interpolation) {
Ian Romanickf36460e2010-06-23 12:07:22 -0700496 linker_error_printf(prog,
497 "%s shader output `%s' specifies %s "
498 "interpolation qualifier, "
499 "but %s shader input specifies %s "
500 "interpolation qualifier\n",
501 producer_stage,
502 output->name,
503 output->interpolation_string(),
504 consumer_stage,
505 input->interpolation_string());
Ian Romanick37101922010-06-18 19:02:10 -0700506 return false;
507 }
508 }
509 }
510
511 return true;
512}
513
514
Ian Romanick3fb87872010-07-09 14:09:34 -0700515/**
516 * Populates a shaders symbol table with all global declarations
517 */
518static void
519populate_symbol_table(gl_shader *sh)
520{
521 sh->symbols = new(sh) glsl_symbol_table;
522
523 foreach_list(node, sh->ir) {
524 ir_instruction *const inst = (ir_instruction *) node;
525 ir_variable *var;
526 ir_function *func;
527
528 if ((func = inst->as_function()) != NULL) {
529 sh->symbols->add_function(func->name, func);
530 } else if ((var = inst->as_variable()) != NULL) {
531 sh->symbols->add_variable(var->name, var);
532 }
533 }
534}
535
536
537/**
Ian Romanick31a97862010-07-12 18:48:50 -0700538 * Remap variables referenced in an instruction tree
539 *
540 * This is used when instruction trees are cloned from one shader and placed in
541 * another. These trees will contain references to \c ir_variable nodes that
542 * do not exist in the target shader. This function finds these \c ir_variable
543 * references and replaces the references with matching variables in the target
544 * shader.
545 *
546 * If there is no matching variable in the target shader, a clone of the
547 * \c ir_variable is made and added to the target shader. The new variable is
548 * added to \b both the instruction stream and the symbol table.
549 *
550 * \param inst IR tree that is to be processed.
551 * \param symbols Symbol table containing global scope symbols in the
552 * linked shader.
553 * \param instructions Instruction stream where new variable declarations
554 * should be added.
555 */
556void
Eric Anholt8273bd42010-08-04 12:34:56 -0700557remap_variables(ir_instruction *inst, struct gl_shader *target,
558 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700559{
560 class remap_visitor : public ir_hierarchical_visitor {
561 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700562 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700563 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700564 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700565 this->target = target;
566 this->symbols = target->symbols;
567 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700568 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700569 }
570
571 virtual ir_visitor_status visit(ir_dereference_variable *ir)
572 {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700573 if (ir->var->mode == ir_var_temporary) {
574 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
575
576 assert(var != NULL);
577 ir->var = var;
578 return visit_continue;
579 }
580
Ian Romanick31a97862010-07-12 18:48:50 -0700581 ir_variable *const existing =
582 this->symbols->get_variable(ir->var->name);
583 if (existing != NULL)
584 ir->var = existing;
585 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700586 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700587
588 this->symbols->add_variable(copy->name, copy);
589 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700590 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700591 }
592
593 return visit_continue;
594 }
595
596 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700597 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700598 glsl_symbol_table *symbols;
599 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700600 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700601 };
602
Eric Anholt8273bd42010-08-04 12:34:56 -0700603 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700604
605 inst->accept(&v);
606}
607
608
609/**
610 * Move non-declarations from one instruction stream to another
611 *
612 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700613 * 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 -0700614 * pointer) for \c last and \c false for \c make_copies on the first
615 * call. Successive calls pass the return value of the previous call for
616 * \c last and \c true for \c make_copies.
617 *
618 * \param instructions Source instruction stream
619 * \param last Instruction after which new instructions should be
620 * inserted in the target instruction stream
621 * \param make_copies Flag selecting whether instructions in \c instructions
622 * should be copied (via \c ir_instruction::clone) into the
623 * target list or moved.
624 *
625 * \return
626 * The new "last" instruction in the target instruction stream. This pointer
627 * is suitable for use as the \c last parameter of a later call to this
628 * function.
629 */
630exec_node *
631move_non_declarations(exec_list *instructions, exec_node *last,
632 bool make_copies, gl_shader *target)
633{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700634 hash_table *temps = NULL;
635
636 if (make_copies)
637 temps = hash_table_ctor(0, hash_table_pointer_hash,
638 hash_table_pointer_compare);
639
Ian Romanick303c99f2010-07-19 12:34:56 -0700640 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700641 ir_instruction *inst = (ir_instruction *) node;
642
Ian Romanick7e2aa912010-07-19 17:12:42 -0700643 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700644 continue;
645
Ian Romanick7e2aa912010-07-19 17:12:42 -0700646 ir_variable *var = inst->as_variable();
647 if ((var != NULL) && (var->mode != ir_var_temporary))
648 continue;
649
650 assert(inst->as_assignment()
651 || ((var != NULL) && (var->mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700652
653 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700654 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700655
656 if (var != NULL)
657 hash_table_insert(temps, inst, var);
658 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700659 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700660 } else {
661 inst->remove();
662 }
663
664 last->insert_after(inst);
665 last = inst;
666 }
667
Ian Romanick7e2aa912010-07-19 17:12:42 -0700668 if (make_copies)
669 hash_table_dtor(temps);
670
Ian Romanick31a97862010-07-12 18:48:50 -0700671 return last;
672}
673
674/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700675 * Get the function signature for main from a shader
676 */
677static ir_function_signature *
678get_main_function_signature(gl_shader *sh)
679{
680 ir_function *const f = sh->symbols->get_function("main");
681 if (f != NULL) {
682 exec_list void_parameters;
683
684 /* Look for the 'void main()' signature and ensure that it's defined.
685 * This keeps the linker from accidentally pick a shader that just
686 * contains a prototype for main.
687 *
688 * We don't have to check for multiple definitions of main (in multiple
689 * shaders) because that would have already been caught above.
690 */
691 ir_function_signature *sig = f->matching_signature(&void_parameters);
692 if ((sig != NULL) && sig->is_defined) {
693 return sig;
694 }
695 }
696
697 return NULL;
698}
699
700
701/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700702 * Combine a group of shaders for a single stage to generate a linked shader
703 *
704 * \note
705 * If this function is supplied a single shader, it is cloned, and the new
706 * shader is returned.
707 */
708static struct gl_shader *
Eric Anholt5d0f4302010-08-18 12:02:35 -0700709link_intrastage_shaders(GLcontext *ctx,
710 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -0700711 struct gl_shader **shader_list,
712 unsigned num_shaders)
713{
Ian Romanick13f782c2010-06-29 18:53:38 -0700714 /* Check that global variables defined in multiple shaders are consistent.
715 */
716 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
717 return NULL;
718
719 /* Check that there is only a single definition of each function signature
720 * across all shaders.
721 */
722 for (unsigned i = 0; i < (num_shaders - 1); i++) {
723 foreach_list(node, shader_list[i]->ir) {
724 ir_function *const f = ((ir_instruction *) node)->as_function();
725
726 if (f == NULL)
727 continue;
728
729 for (unsigned j = i + 1; j < num_shaders; j++) {
730 ir_function *const other =
731 shader_list[j]->symbols->get_function(f->name);
732
733 /* If the other shader has no function (and therefore no function
734 * signatures) with the same name, skip to the next shader.
735 */
736 if (other == NULL)
737 continue;
738
739 foreach_iter (exec_list_iterator, iter, *f) {
740 ir_function_signature *sig =
741 (ir_function_signature *) iter.get();
742
Kenneth Graunkeb6f15862010-08-20 20:04:39 -0700743 if (!sig->is_defined || f->is_builtin)
Ian Romanick13f782c2010-06-29 18:53:38 -0700744 continue;
745
746 ir_function_signature *other_sig =
747 other->exact_matching_signature(& sig->parameters);
748
749 if ((other_sig != NULL) && other_sig->is_defined
Kenneth Graunkeb6f15862010-08-20 20:04:39 -0700750 && !other_sig->function()->is_builtin) {
Ian Romanick13f782c2010-06-29 18:53:38 -0700751 linker_error_printf(prog,
752 "function `%s' is multiply defined",
753 f->name);
754 return NULL;
755 }
756 }
757 }
758 }
759 }
760
761 /* Find the shader that defines main, and make a clone of it.
762 *
763 * Starting with the clone, search for undefined references. If one is
764 * found, find the shader that defines it. Clone the reference and add
765 * it to the shader. Repeat until there are no undefined references or
766 * until a reference cannot be resolved.
767 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700768 gl_shader *main = NULL;
769 for (unsigned i = 0; i < num_shaders; i++) {
770 if (get_main_function_signature(shader_list[i]) != NULL) {
771 main = shader_list[i];
772 break;
773 }
774 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700775
Ian Romanick15ce87e2010-07-09 15:28:22 -0700776 if (main == NULL) {
777 linker_error_printf(prog, "%s shader lacks `main'\n",
778 (shader_list[0]->Type == GL_VERTEX_SHADER)
779 ? "vertex" : "fragment");
780 return NULL;
781 }
782
Eric Anholt5d0f4302010-08-18 12:02:35 -0700783 gl_shader *const linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700784 linked->ir = new(linked) exec_list;
Eric Anholt8273bd42010-08-04 12:34:56 -0700785 clone_ir_list(linked, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700786
787 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700788
Ian Romanick31a97862010-07-12 18:48:50 -0700789 /* The a pointer to the main function in the final linked shader (i.e., the
790 * copy of the original shader that contained the main function).
791 */
792 ir_function_signature *const main_sig = get_main_function_signature(linked);
793
794 /* Move any instructions other than variable declarations or function
795 * declarations into main.
796 */
Ian Romanick9303e352010-07-19 12:33:54 -0700797 exec_node *insertion_point =
798 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
799 linked);
800
Ian Romanick31a97862010-07-12 18:48:50 -0700801 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -0700802 if (shader_list[i] == main)
803 continue;
804
Ian Romanick31a97862010-07-12 18:48:50 -0700805 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -0700806 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -0700807 }
808
Ian Romanick13f782c2010-06-29 18:53:38 -0700809 /* Resolve initializers for global variables in the linked shader.
810 */
Ian Romanickd5be2ac2010-07-20 11:29:46 -0700811 unsigned num_linking_shaders = num_shaders;
812 for (unsigned i = 0; i < num_shaders; i++)
813 num_linking_shaders += shader_list[i]->num_builtins_to_link;
814
815 gl_shader **linking_shaders =
816 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
817
818 memcpy(linking_shaders, shader_list,
819 sizeof(linking_shaders[0]) * num_shaders);
820
821 unsigned idx = num_shaders;
822 for (unsigned i = 0; i < num_shaders; i++) {
823 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
824 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
825 idx += shader_list[i]->num_builtins_to_link;
826 }
827
828 assert(idx == num_linking_shaders);
829
830 link_function_calls(prog, linked, linking_shaders, num_linking_shaders);
831
832 free(linking_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -0700833
Ian Romanick3fb87872010-07-09 14:09:34 -0700834 return linked;
835}
836
837
Ian Romanick019a59b2010-06-21 16:10:42 -0700838struct uniform_node {
839 exec_node link;
840 struct gl_uniform *u;
841 unsigned slots;
842};
843
Eric Anholta721abf2010-08-23 10:32:01 -0700844/**
845 * Update the sizes of linked shader uniform arrays to the maximum
846 * array index used.
847 *
848 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
849 *
850 * If one or more elements of an array are active,
851 * GetActiveUniform will return the name of the array in name,
852 * subject to the restrictions listed above. The type of the array
853 * is returned in type. The size parameter contains the highest
854 * array element index used, plus one. The compiler or linker
855 * determines the highest index used. There will be only one
856 * active uniform reported by the GL per uniform array.
857
858 */
859static void
860update_uniform_array_sizes(struct gl_shader_program *prog)
861{
862 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
863 foreach_list(node, prog->_LinkedShaders[i]->ir) {
864 ir_variable *const var = ((ir_instruction *) node)->as_variable();
865
866 if ((var == NULL) || (var->mode != ir_var_uniform) ||
867 !var->type->is_array())
868 continue;
869
870 unsigned int size = var->max_array_access;
871 for (unsigned j = 0; j < prog->_NumLinkedShaders; j++) {
872 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
873 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
874 if (!other_var)
875 continue;
876
877 if (strcmp(var->name, other_var->name) == 0 &&
878 other_var->max_array_access > size) {
879 size = other_var->max_array_access;
880 }
881 }
882 }
883 if (size + 1 != var->type->fields.array->length) {
884 var->type = glsl_type::get_array_instance(var->type->fields.array,
885 size + 1);
886 /* FINISHME: We should update the types of array
887 * dereferences of this variable now.
888 */
889 }
890 }
891 }
892}
893
Eric Anholt45388b52010-08-24 13:51:35 -0700894static void
895add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
896 const char *name, const glsl_type *type, GLenum shader_type,
897 unsigned *next_shader_pos, unsigned *total_uniforms)
898{
899 if (type->is_record()) {
900 for (unsigned int i = 0; i < type->length; i++) {
901 const glsl_type *field_type = type->fields.structure[i].type;
902 char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
903 type->fields.structure[i].name);
904
905 add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
906 shader_type, next_shader_pos, total_uniforms);
907 }
908 } else {
909 uniform_node *n = (uniform_node *) hash_table_find(ht, name);
910 unsigned int vec4_slots;
911 const glsl_type *array_elem_type = NULL;
912
913 if (type->is_array()) {
914 array_elem_type = type->fields.array;
915 /* Array of structures. */
916 if (array_elem_type->is_record()) {
917 for (unsigned int i = 0; i < type->length; i++) {
918 char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
919 add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
920 shader_type, next_shader_pos, total_uniforms);
921 }
922 return;
923 }
924 }
925
926 /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
927 * vectors to vec4 slots.
928 */
929 if (type->is_array()) {
930 if (array_elem_type->is_sampler())
931 vec4_slots = type->length;
932 else
933 vec4_slots = type->length * array_elem_type->matrix_columns;
934 } else if (type->is_sampler()) {
935 vec4_slots = 1;
936 } else {
937 vec4_slots = type->matrix_columns;
938 }
939
940 if (n == NULL) {
941 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
942 n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
943 n->slots = vec4_slots;
944
945 n->u->Name = strdup(name);
Eric Anholt0924ba02010-08-24 14:27:27 -0700946 n->u->Type = type;
Eric Anholt45388b52010-08-24 13:51:35 -0700947 n->u->VertPos = -1;
948 n->u->FragPos = -1;
949 n->u->GeomPos = -1;
950 (*total_uniforms)++;
951
952 hash_table_insert(ht, n, name);
953 uniforms->push_tail(& n->link);
954 }
955
956 switch (shader_type) {
957 case GL_VERTEX_SHADER:
958 n->u->VertPos = *next_shader_pos;
959 break;
960 case GL_FRAGMENT_SHADER:
961 n->u->FragPos = *next_shader_pos;
962 break;
963 case GL_GEOMETRY_SHADER:
964 n->u->GeomPos = *next_shader_pos;
965 break;
966 }
967
968 (*next_shader_pos) += vec4_slots;
969 }
970}
971
Ian Romanickabee16e2010-06-21 16:16:05 -0700972void
Eric Anholt849e1812010-06-30 11:49:17 -0700973assign_uniform_locations(struct gl_shader_program *prog)
Ian Romanick019a59b2010-06-21 16:10:42 -0700974{
975 /* */
976 exec_list uniforms;
977 unsigned total_uniforms = 0;
978 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
979 hash_table_string_compare);
Eric Anholt45388b52010-08-24 13:51:35 -0700980 void *mem_ctx = talloc_new(NULL);
Ian Romanick019a59b2010-06-21 16:10:42 -0700981
Eric Anholta721abf2010-08-23 10:32:01 -0700982 update_uniform_array_sizes(prog);
983
Ian Romanickabee16e2010-06-21 16:16:05 -0700984 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700985 unsigned next_position = 0;
986
Eric Anholt16b68b12010-06-30 11:05:43 -0700987 foreach_list(node, prog->_LinkedShaders[i]->ir) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700988 ir_variable *const var = ((ir_instruction *) node)->as_variable();
989
990 if ((var == NULL) || (var->mode != ir_var_uniform))
991 continue;
992
Eric Anholt45388b52010-08-24 13:51:35 -0700993 if (strncmp(var->name, "gl_", 3) == 0) {
994 /* At the moment, we don't allocate uniform locations for
995 * builtin uniforms. It's permitted by spec, and we'll
996 * likely switch to doing that at some point, but not yet.
Eric Anholt8d61a232010-08-05 16:00:46 -0700997 */
998 continue;
999 }
Ian Romanick019a59b2010-06-21 16:10:42 -07001000
Ian Romanick019a59b2010-06-21 16:10:42 -07001001 var->location = next_position;
Eric Anholt45388b52010-08-24 13:51:35 -07001002 add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
1003 prog->_LinkedShaders[i]->Type,
1004 &next_position, &total_uniforms);
Ian Romanick019a59b2010-06-21 16:10:42 -07001005 }
1006 }
1007
Eric Anholt45388b52010-08-24 13:51:35 -07001008 talloc_free(mem_ctx);
1009
Ian Romanick019a59b2010-06-21 16:10:42 -07001010 gl_uniform_list *ul = (gl_uniform_list *)
1011 calloc(1, sizeof(gl_uniform_list));
1012
1013 ul->Size = total_uniforms;
1014 ul->NumUniforms = total_uniforms;
1015 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
1016
1017 unsigned idx = 0;
1018 uniform_node *next;
1019 for (uniform_node *node = (uniform_node *) uniforms.head
1020 ; node->link.next != NULL
1021 ; node = next) {
1022 next = (uniform_node *) node->link.next;
1023
1024 node->link.remove();
Eric Anholt45388b52010-08-24 13:51:35 -07001025 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
1026 idx++;
Ian Romanick019a59b2010-06-21 16:10:42 -07001027
1028 free(node->u);
1029 free(node);
1030 }
1031
1032 hash_table_dtor(ht);
1033
Ian Romanickabee16e2010-06-21 16:16:05 -07001034 prog->Uniforms = ul;
Ian Romanick019a59b2010-06-21 16:10:42 -07001035}
1036
1037
Ian Romanick69846702010-06-22 17:29:19 -07001038/**
1039 * Find a contiguous set of available bits in a bitmask
1040 *
1041 * \param used_mask Bits representing used (1) and unused (0) locations
1042 * \param needed_count Number of contiguous bits needed.
1043 *
1044 * \return
1045 * Base location of the available bits on success or -1 on failure.
1046 */
1047int
1048find_available_slots(unsigned used_mask, unsigned needed_count)
1049{
1050 unsigned needed_mask = (1 << needed_count) - 1;
1051 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1052
1053 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1054 * cannot optimize possibly infinite loops" for the loop below.
1055 */
1056 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1057 return -1;
1058
1059 for (int i = 0; i <= max_bit_to_test; i++) {
1060 if ((needed_mask & ~used_mask) == needed_mask)
1061 return i;
1062
1063 needed_mask <<= 1;
1064 }
1065
1066 return -1;
1067}
1068
1069
1070bool
Eric Anholt849e1812010-06-30 11:49:17 -07001071assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001072{
Ian Romanick9342d262010-06-22 17:41:37 -07001073 /* Mark invalid attribute locations as being used.
1074 */
1075 unsigned used_locations = (max_attribute_index >= 32)
1076 ? ~0 : ~((1 << max_attribute_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001077
Eric Anholt16b68b12010-06-30 11:05:43 -07001078 gl_shader *const sh = prog->_LinkedShaders[0];
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001079 assert(sh->Type == GL_VERTEX_SHADER);
1080
Ian Romanick69846702010-06-22 17:29:19 -07001081 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001082 *
1083 * 1. Invalidate the location assignments for all vertex shader inputs.
1084 *
1085 * 2. Assign locations for inputs that have user-defined (via
1086 * glBindVertexAttribLocation) locatoins.
1087 *
Ian Romanick69846702010-06-22 17:29:19 -07001088 * 3. Sort the attributes without assigned locations by number of slots
1089 * required in decreasing order. Fragmentation caused by attribute
1090 * locations assigned by the application may prevent large attributes
1091 * from having enough contiguous space.
1092 *
1093 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001094 */
1095
1096 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1097
Ian Romanick553dcdc2010-06-23 12:14:02 -07001098 if (prog->Attributes != NULL) {
1099 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001100 ir_variable *const var =
Ian Romanick553dcdc2010-06-23 12:14:02 -07001101 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001102
Ian Romanick69846702010-06-22 17:29:19 -07001103 /* Note: attributes that occupy multiple slots, such as arrays or
1104 * matrices, may appear in the attrib array multiple times.
1105 */
1106 if ((var == NULL) || (var->location != -1))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001107 continue;
1108
Ian Romanick69846702010-06-22 17:29:19 -07001109 /* From page 61 of the OpenGL 4.0 spec:
1110 *
1111 * "LinkProgram will fail if the attribute bindings assigned by
1112 * BindAttribLocation do not leave not enough space to assign a
1113 * location for an active matrix attribute or an active attribute
1114 * array, both of which require multiple contiguous generic
1115 * attributes."
1116 *
1117 * Previous versions of the spec contain similar language but omit the
1118 * bit about attribute arrays.
1119 *
1120 * Page 61 of the OpenGL 4.0 spec also says:
1121 *
1122 * "It is possible for an application to bind more than one
1123 * attribute name to the same location. This is referred to as
1124 * aliasing. This will only work if only one of the aliased
1125 * attributes is active in the executable program, or if no path
1126 * through the shader consumes more than one attribute of a set
1127 * of attributes aliased to the same location. A link error can
1128 * occur if the linker determines that every path through the
1129 * shader consumes multiple aliased attributes, but
1130 * implementations are not required to generate an error in this
1131 * case."
1132 *
1133 * These two paragraphs are either somewhat contradictory, or I don't
1134 * fully understand one or both of them.
1135 */
1136 /* FINISHME: The code as currently written does not support attribute
1137 * FINISHME: location aliasing (see comment above).
1138 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001139 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
Ian Romanick69846702010-06-22 17:29:19 -07001140 const unsigned slots = count_attribute_slots(var->type);
1141
1142 /* Mask representing the contiguous slots that will be used by this
1143 * attribute.
1144 */
1145 const unsigned use_mask = (1 << slots) - 1;
1146
1147 /* Generate a link error if the set of bits requested for this
1148 * attribute overlaps any previously allocated bits.
1149 */
1150 if ((~(use_mask << attr) & used_locations) != used_locations) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001151 linker_error_printf(prog,
1152 "insufficient contiguous attribute locations "
1153 "available for vertex shader input `%s'",
1154 var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001155 return false;
1156 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001157
1158 var->location = VERT_ATTRIB_GENERIC0 + attr;
Ian Romanick69846702010-06-22 17:29:19 -07001159 used_locations |= (use_mask << attr);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001160 }
1161 }
1162
Ian Romanick69846702010-06-22 17:29:19 -07001163 /* Temporary storage for the set of attributes that need locations assigned.
1164 */
1165 struct temp_attr {
1166 unsigned slots;
1167 ir_variable *var;
1168
1169 /* Used below in the call to qsort. */
1170 static int compare(const void *a, const void *b)
1171 {
1172 const temp_attr *const l = (const temp_attr *) a;
1173 const temp_attr *const r = (const temp_attr *) b;
1174
1175 /* Reversed because we want a descending order sort below. */
1176 return r->slots - l->slots;
1177 }
1178 } to_assign[16];
1179
1180 unsigned num_attr = 0;
1181
Eric Anholt16b68b12010-06-30 11:05:43 -07001182 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001183 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1184
1185 if ((var == NULL) || (var->mode != ir_var_in))
1186 continue;
1187
1188 /* The location was explicitly assigned, nothing to do here.
1189 */
1190 if (var->location != -1)
1191 continue;
1192
Ian Romanick69846702010-06-22 17:29:19 -07001193 to_assign[num_attr].slots = count_attribute_slots(var->type);
1194 to_assign[num_attr].var = var;
1195 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001196 }
Ian Romanick69846702010-06-22 17:29:19 -07001197
1198 /* If all of the attributes were assigned locations by the application (or
1199 * are built-in attributes with fixed locations), return early. This should
1200 * be the common case.
1201 */
1202 if (num_attr == 0)
1203 return true;
1204
1205 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1206
Ian Romanick982e3792010-06-29 18:58:20 -07001207 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1208 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1209 * to prevent it from being automatically allocated below.
1210 */
Ian Romanickc33e78f2010-08-13 12:30:41 -07001211 find_deref_visitor find("gl_Vertex");
1212 find.run(sh->ir);
1213 if (find.variable_found())
1214 used_locations |= (1 << 0);
Ian Romanick982e3792010-06-29 18:58:20 -07001215
Ian Romanick69846702010-06-22 17:29:19 -07001216 for (unsigned i = 0; i < num_attr; i++) {
1217 /* Mask representing the contiguous slots that will be used by this
1218 * attribute.
1219 */
1220 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1221
1222 int location = find_available_slots(used_locations, to_assign[i].slots);
1223
1224 if (location < 0) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001225 linker_error_printf(prog,
1226 "insufficient contiguous attribute locations "
1227 "available for vertex shader input `%s'",
1228 to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001229 return false;
1230 }
1231
1232 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1233 used_locations |= (use_mask << location);
1234 }
1235
1236 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001237}
1238
1239
Ian Romanick40e114b2010-08-17 14:55:50 -07001240/**
1241 * Demote shader outputs that are not read to being just plain global variables
1242 */
1243void
1244demote_unread_shader_outputs(gl_shader *sh)
1245{
1246 foreach_list(node, sh->ir) {
1247 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1248
1249 if ((var == NULL) || (var->mode != ir_var_out))
1250 continue;
1251
1252 /* An 'out' variable is only really a shader output if its value is read
1253 * by the following stage.
1254 */
1255 if (var->location == -1) {
1256 var->mode = ir_var_auto;
1257 }
1258 }
1259}
1260
1261
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001262void
Eric Anholtb7062832010-07-28 13:52:23 -07001263assign_varying_locations(struct gl_shader_program *prog,
1264 gl_shader *producer, gl_shader *consumer)
Ian Romanick0e59b262010-06-23 11:23:01 -07001265{
1266 /* FINISHME: Set dynamically when geometry shader support is added. */
1267 unsigned output_index = VERT_RESULT_VAR0;
1268 unsigned input_index = FRAG_ATTRIB_VAR0;
1269
1270 /* Operate in a total of three passes.
1271 *
1272 * 1. Assign locations for any matching inputs and outputs.
1273 *
1274 * 2. Mark output variables in the producer that do not have locations as
1275 * not being outputs. This lets the optimizer eliminate them.
1276 *
1277 * 3. Mark input variables in the consumer that do not have locations as
1278 * not being inputs. This lets the optimizer eliminate them.
1279 */
1280
1281 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1282 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1283
Eric Anholt16b68b12010-06-30 11:05:43 -07001284 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001285 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1286
1287 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1288 || (output_var->location != -1))
1289 continue;
1290
1291 ir_variable *const input_var =
1292 consumer->symbols->get_variable(output_var->name);
1293
1294 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1295 continue;
1296
1297 assert(input_var->location == -1);
1298
1299 /* FINISHME: Location assignment will need some changes when arrays,
1300 * FINISHME: matrices, and structures are allowed as shader inputs /
1301 * FINISHME: outputs.
1302 */
1303 output_var->location = output_index;
1304 input_var->location = input_index;
1305
1306 output_index++;
1307 input_index++;
1308 }
1309
Ian Romanick40e114b2010-08-17 14:55:50 -07001310 demote_unread_shader_outputs(producer);
Ian Romanick0e59b262010-06-23 11:23:01 -07001311
Eric Anholt16b68b12010-06-30 11:05:43 -07001312 foreach_list(node, consumer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001313 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1314
1315 if ((var == NULL) || (var->mode != ir_var_in))
1316 continue;
1317
Eric Anholtb7062832010-07-28 13:52:23 -07001318 if (var->location == -1) {
1319 if (prog->Version <= 120) {
1320 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1321 *
1322 * Only those varying variables used (i.e. read) in
1323 * the fragment shader executable must be written to
1324 * by the vertex shader executable; declaring
1325 * superfluous varying variables in a vertex shader is
1326 * permissible.
1327 *
1328 * We interpret this text as meaning that the VS must
1329 * write the variable for the FS to read it. See
1330 * "glsl1-varying read but not written" in piglit.
1331 */
1332
1333 linker_error_printf(prog, "fragment shader varying %s not written "
1334 "by vertex shader\n.", var->name);
1335 prog->LinkStatus = false;
1336 }
1337
1338 /* An 'in' variable is only really a shader input if its
1339 * value is written by the previous stage.
1340 */
Eric Anholtb7062832010-07-28 13:52:23 -07001341 var->mode = ir_var_auto;
1342 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001343 }
1344}
1345
1346
1347void
Eric Anholt5d0f4302010-08-18 12:02:35 -07001348link_shaders(GLcontext *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07001349{
1350 prog->LinkStatus = false;
1351 prog->Validated = false;
1352 prog->_Used = false;
1353
Ian Romanickf36460e2010-06-23 12:07:22 -07001354 if (prog->InfoLog != NULL)
1355 talloc_free(prog->InfoLog);
1356
1357 prog->InfoLog = talloc_strdup(NULL, "");
1358
Ian Romanick832dfa52010-06-17 15:04:20 -07001359 /* Separate the shaders into groups based on their type.
1360 */
Eric Anholt16b68b12010-06-30 11:05:43 -07001361 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001362 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07001363 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001364 unsigned num_frag_shaders = 0;
1365
Eric Anholt16b68b12010-06-30 11:05:43 -07001366 vert_shader_list = (struct gl_shader **)
1367 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07001368 frag_shader_list = &vert_shader_list[prog->NumShaders];
1369
Ian Romanick25f51d32010-07-16 15:51:50 -07001370 unsigned min_version = UINT_MAX;
1371 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07001372 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07001373 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1374 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1375
Ian Romanick832dfa52010-06-17 15:04:20 -07001376 switch (prog->Shaders[i]->Type) {
1377 case GL_VERTEX_SHADER:
1378 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1379 num_vert_shaders++;
1380 break;
1381 case GL_FRAGMENT_SHADER:
1382 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1383 num_frag_shaders++;
1384 break;
1385 case GL_GEOMETRY_SHADER:
1386 /* FINISHME: Support geometry shaders. */
1387 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1388 break;
1389 }
1390 }
1391
Ian Romanick25f51d32010-07-16 15:51:50 -07001392 /* Previous to GLSL version 1.30, different compilation units could mix and
1393 * match shading language versions. With GLSL 1.30 and later, the versions
1394 * of all shaders must match.
1395 */
1396 assert(min_version >= 110);
1397 assert(max_version <= 130);
1398 if ((max_version >= 130) && (min_version != max_version)) {
1399 linker_error_printf(prog, "all shaders must use same shading "
1400 "language version\n");
1401 goto done;
1402 }
1403
1404 prog->Version = max_version;
1405
Eric Anholt5d0f4302010-08-18 12:02:35 -07001406 for (unsigned int i = 0; i < prog->_NumLinkedShaders; i++) {
1407 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1408 }
1409
Ian Romanickcd6764e2010-07-16 16:00:07 -07001410 /* Link all shaders for a particular stage and validate the result.
1411 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001412 prog->_NumLinkedShaders = 0;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001413 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001414 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001415 link_intrastage_shaders(ctx, prog, vert_shader_list, num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001416
1417 if (sh == NULL)
1418 goto done;
1419
1420 if (!validate_vertex_shader_executable(prog, sh))
1421 goto done;
1422
1423 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001424 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001425 }
1426
1427 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001428 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001429 link_intrastage_shaders(ctx, prog, frag_shader_list, num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001430
1431 if (sh == NULL)
1432 goto done;
1433
1434 if (!validate_fragment_shader_executable(prog, sh))
1435 goto done;
1436
1437 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001438 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001439 }
1440
Ian Romanick3ed850e2010-06-23 12:18:21 -07001441 /* Here begins the inter-stage linking phase. Some initial validation is
1442 * performed, then locations are assigned for uniforms, attributes, and
1443 * varyings.
1444 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001445 if (cross_validate_uniforms(prog)) {
Ian Romanick37101922010-06-18 19:02:10 -07001446 /* Validate the inputs of each stage with the output of the preceeding
1447 * stage.
1448 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001449 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
Ian Romanickf36460e2010-06-23 12:07:22 -07001450 if (!cross_validate_outputs_to_inputs(prog,
1451 prog->_LinkedShaders[i - 1],
Ian Romanickabee16e2010-06-21 16:16:05 -07001452 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001453 goto done;
1454 }
1455
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001456 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001457 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001458
Eric Anholt2f4fe152010-08-10 13:06:49 -07001459 /* Do common optimization before assigning storage for attributes,
1460 * uniforms, and varyings. Later optimization could possibly make
1461 * some of that unused.
1462 */
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001463 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Eric Anholt2f4fe152010-08-10 13:06:49 -07001464 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true))
1465 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001466 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001467
Ian Romanickabee16e2010-06-21 16:16:05 -07001468 assign_uniform_locations(prog);
Ian Romanick13e10e42010-06-21 12:03:24 -07001469
Ian Romanick40e114b2010-08-17 14:55:50 -07001470 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER) {
Ian Romanick9342d262010-06-22 17:41:37 -07001471 /* FINISHME: The value of the max_attribute_index parameter is
1472 * FINISHME: implementation dependent based on the value of
1473 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1474 * FINISHME: at least 16, so hardcode 16 for now.
1475 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001476 if (!assign_attribute_locations(prog, 16))
Ian Romanick69846702010-06-22 17:29:19 -07001477 goto done;
Ian Romanick13e10e42010-06-21 12:03:24 -07001478
Ian Romanick40e114b2010-08-17 14:55:50 -07001479 if (prog->_NumLinkedShaders == 1)
1480 demote_unread_shader_outputs(prog->_LinkedShaders[0]);
1481 }
1482
Ian Romanick0e59b262010-06-23 11:23:01 -07001483 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
Eric Anholtb7062832010-07-28 13:52:23 -07001484 assign_varying_locations(prog,
1485 prog->_LinkedShaders[i - 1],
Ian Romanick0e59b262010-06-23 11:23:01 -07001486 prog->_LinkedShaders[i]);
Ian Romanick13e10e42010-06-21 12:03:24 -07001487
1488 /* FINISHME: Assign fragment shader output locations. */
1489
Ian Romanick832dfa52010-06-17 15:04:20 -07001490done:
1491 free(vert_shader_list);
1492}