blob: 3de069b53123bdbc69a7f2e68f16438b280ee0da [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
Kenneth Graunkeb6f15862010-08-20 20:04:39 -0700729 if (!sig->is_defined || f->is_builtin)
Ian Romanick13f782c2010-06-29 18:53:38 -0700730 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
Kenneth Graunkeb6f15862010-08-20 20:04:39 -0700736 && !other_sig->function()->is_builtin) {
Ian Romanick13f782c2010-06-29 18:53:38 -0700737 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
Eric Anholt45388b52010-08-24 13:51:35 -0700880static void
881add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
882 const char *name, const glsl_type *type, GLenum shader_type,
883 unsigned *next_shader_pos, unsigned *total_uniforms)
884{
885 if (type->is_record()) {
886 for (unsigned int i = 0; i < type->length; i++) {
887 const glsl_type *field_type = type->fields.structure[i].type;
888 char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
889 type->fields.structure[i].name);
890
891 add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
892 shader_type, next_shader_pos, total_uniforms);
893 }
894 } else {
895 uniform_node *n = (uniform_node *) hash_table_find(ht, name);
896 unsigned int vec4_slots;
897 const glsl_type *array_elem_type = NULL;
898
899 if (type->is_array()) {
900 array_elem_type = type->fields.array;
901 /* Array of structures. */
902 if (array_elem_type->is_record()) {
903 for (unsigned int i = 0; i < type->length; i++) {
904 char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
905 add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
906 shader_type, next_shader_pos, total_uniforms);
907 }
908 return;
909 }
910 }
911
912 /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
913 * vectors to vec4 slots.
914 */
915 if (type->is_array()) {
916 if (array_elem_type->is_sampler())
917 vec4_slots = type->length;
918 else
919 vec4_slots = type->length * array_elem_type->matrix_columns;
920 } else if (type->is_sampler()) {
921 vec4_slots = 1;
922 } else {
923 vec4_slots = type->matrix_columns;
924 }
925
926 if (n == NULL) {
927 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
928 n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
929 n->slots = vec4_slots;
930
931 n->u->Name = strdup(name);
Eric Anholt0924ba02010-08-24 14:27:27 -0700932 n->u->Type = type;
Eric Anholt45388b52010-08-24 13:51:35 -0700933 n->u->VertPos = -1;
934 n->u->FragPos = -1;
935 n->u->GeomPos = -1;
936 (*total_uniforms)++;
937
938 hash_table_insert(ht, n, name);
939 uniforms->push_tail(& n->link);
940 }
941
942 switch (shader_type) {
943 case GL_VERTEX_SHADER:
944 n->u->VertPos = *next_shader_pos;
945 break;
946 case GL_FRAGMENT_SHADER:
947 n->u->FragPos = *next_shader_pos;
948 break;
949 case GL_GEOMETRY_SHADER:
950 n->u->GeomPos = *next_shader_pos;
951 break;
952 }
953
954 (*next_shader_pos) += vec4_slots;
955 }
956}
957
Ian Romanickabee16e2010-06-21 16:16:05 -0700958void
Eric Anholt849e1812010-06-30 11:49:17 -0700959assign_uniform_locations(struct gl_shader_program *prog)
Ian Romanick019a59b2010-06-21 16:10:42 -0700960{
961 /* */
962 exec_list uniforms;
963 unsigned total_uniforms = 0;
964 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
965 hash_table_string_compare);
Eric Anholt45388b52010-08-24 13:51:35 -0700966 void *mem_ctx = talloc_new(NULL);
Ian Romanick019a59b2010-06-21 16:10:42 -0700967
Eric Anholta721abf2010-08-23 10:32:01 -0700968 update_uniform_array_sizes(prog);
969
Ian Romanickabee16e2010-06-21 16:16:05 -0700970 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700971 unsigned next_position = 0;
972
Eric Anholt16b68b12010-06-30 11:05:43 -0700973 foreach_list(node, prog->_LinkedShaders[i]->ir) {
Ian Romanick019a59b2010-06-21 16:10:42 -0700974 ir_variable *const var = ((ir_instruction *) node)->as_variable();
975
976 if ((var == NULL) || (var->mode != ir_var_uniform))
977 continue;
978
Eric Anholt45388b52010-08-24 13:51:35 -0700979 if (strncmp(var->name, "gl_", 3) == 0) {
980 /* At the moment, we don't allocate uniform locations for
981 * builtin uniforms. It's permitted by spec, and we'll
982 * likely switch to doing that at some point, but not yet.
Eric Anholt8d61a232010-08-05 16:00:46 -0700983 */
984 continue;
985 }
Ian Romanick019a59b2010-06-21 16:10:42 -0700986
Ian Romanick019a59b2010-06-21 16:10:42 -0700987 var->location = next_position;
Eric Anholt45388b52010-08-24 13:51:35 -0700988 add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
989 prog->_LinkedShaders[i]->Type,
990 &next_position, &total_uniforms);
Ian Romanick019a59b2010-06-21 16:10:42 -0700991 }
992 }
993
Eric Anholt45388b52010-08-24 13:51:35 -0700994 talloc_free(mem_ctx);
995
Ian Romanick019a59b2010-06-21 16:10:42 -0700996 gl_uniform_list *ul = (gl_uniform_list *)
997 calloc(1, sizeof(gl_uniform_list));
998
999 ul->Size = total_uniforms;
1000 ul->NumUniforms = total_uniforms;
1001 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
1002
1003 unsigned idx = 0;
1004 uniform_node *next;
1005 for (uniform_node *node = (uniform_node *) uniforms.head
1006 ; node->link.next != NULL
1007 ; node = next) {
1008 next = (uniform_node *) node->link.next;
1009
1010 node->link.remove();
Eric Anholt45388b52010-08-24 13:51:35 -07001011 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
1012 idx++;
Ian Romanick019a59b2010-06-21 16:10:42 -07001013
1014 free(node->u);
1015 free(node);
1016 }
1017
1018 hash_table_dtor(ht);
1019
Ian Romanickabee16e2010-06-21 16:16:05 -07001020 prog->Uniforms = ul;
Ian Romanick019a59b2010-06-21 16:10:42 -07001021}
1022
1023
Ian Romanick69846702010-06-22 17:29:19 -07001024/**
1025 * Find a contiguous set of available bits in a bitmask
1026 *
1027 * \param used_mask Bits representing used (1) and unused (0) locations
1028 * \param needed_count Number of contiguous bits needed.
1029 *
1030 * \return
1031 * Base location of the available bits on success or -1 on failure.
1032 */
1033int
1034find_available_slots(unsigned used_mask, unsigned needed_count)
1035{
1036 unsigned needed_mask = (1 << needed_count) - 1;
1037 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1038
1039 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1040 * cannot optimize possibly infinite loops" for the loop below.
1041 */
1042 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1043 return -1;
1044
1045 for (int i = 0; i <= max_bit_to_test; i++) {
1046 if ((needed_mask & ~used_mask) == needed_mask)
1047 return i;
1048
1049 needed_mask <<= 1;
1050 }
1051
1052 return -1;
1053}
1054
1055
1056bool
Eric Anholt849e1812010-06-30 11:49:17 -07001057assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001058{
Ian Romanick9342d262010-06-22 17:41:37 -07001059 /* Mark invalid attribute locations as being used.
1060 */
1061 unsigned used_locations = (max_attribute_index >= 32)
1062 ? ~0 : ~((1 << max_attribute_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001063
Eric Anholt16b68b12010-06-30 11:05:43 -07001064 gl_shader *const sh = prog->_LinkedShaders[0];
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001065 assert(sh->Type == GL_VERTEX_SHADER);
1066
Ian Romanick69846702010-06-22 17:29:19 -07001067 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001068 *
1069 * 1. Invalidate the location assignments for all vertex shader inputs.
1070 *
1071 * 2. Assign locations for inputs that have user-defined (via
1072 * glBindVertexAttribLocation) locatoins.
1073 *
Ian Romanick69846702010-06-22 17:29:19 -07001074 * 3. Sort the attributes without assigned locations by number of slots
1075 * required in decreasing order. Fragmentation caused by attribute
1076 * locations assigned by the application may prevent large attributes
1077 * from having enough contiguous space.
1078 *
1079 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001080 */
1081
1082 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
1083
Ian Romanick553dcdc2010-06-23 12:14:02 -07001084 if (prog->Attributes != NULL) {
1085 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001086 ir_variable *const var =
Ian Romanick553dcdc2010-06-23 12:14:02 -07001087 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001088
Ian Romanick69846702010-06-22 17:29:19 -07001089 /* Note: attributes that occupy multiple slots, such as arrays or
1090 * matrices, may appear in the attrib array multiple times.
1091 */
1092 if ((var == NULL) || (var->location != -1))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001093 continue;
1094
Ian Romanick69846702010-06-22 17:29:19 -07001095 /* From page 61 of the OpenGL 4.0 spec:
1096 *
1097 * "LinkProgram will fail if the attribute bindings assigned by
1098 * BindAttribLocation do not leave not enough space to assign a
1099 * location for an active matrix attribute or an active attribute
1100 * array, both of which require multiple contiguous generic
1101 * attributes."
1102 *
1103 * Previous versions of the spec contain similar language but omit the
1104 * bit about attribute arrays.
1105 *
1106 * Page 61 of the OpenGL 4.0 spec also says:
1107 *
1108 * "It is possible for an application to bind more than one
1109 * attribute name to the same location. This is referred to as
1110 * aliasing. This will only work if only one of the aliased
1111 * attributes is active in the executable program, or if no path
1112 * through the shader consumes more than one attribute of a set
1113 * of attributes aliased to the same location. A link error can
1114 * occur if the linker determines that every path through the
1115 * shader consumes multiple aliased attributes, but
1116 * implementations are not required to generate an error in this
1117 * case."
1118 *
1119 * These two paragraphs are either somewhat contradictory, or I don't
1120 * fully understand one or both of them.
1121 */
1122 /* FINISHME: The code as currently written does not support attribute
1123 * FINISHME: location aliasing (see comment above).
1124 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001125 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
Ian Romanick69846702010-06-22 17:29:19 -07001126 const unsigned slots = count_attribute_slots(var->type);
1127
1128 /* Mask representing the contiguous slots that will be used by this
1129 * attribute.
1130 */
1131 const unsigned use_mask = (1 << slots) - 1;
1132
1133 /* Generate a link error if the set of bits requested for this
1134 * attribute overlaps any previously allocated bits.
1135 */
1136 if ((~(use_mask << attr) & used_locations) != used_locations) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001137 linker_error_printf(prog,
1138 "insufficient contiguous attribute locations "
1139 "available for vertex shader input `%s'",
1140 var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001141 return false;
1142 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001143
1144 var->location = VERT_ATTRIB_GENERIC0 + attr;
Ian Romanick69846702010-06-22 17:29:19 -07001145 used_locations |= (use_mask << attr);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001146 }
1147 }
1148
Ian Romanick69846702010-06-22 17:29:19 -07001149 /* Temporary storage for the set of attributes that need locations assigned.
1150 */
1151 struct temp_attr {
1152 unsigned slots;
1153 ir_variable *var;
1154
1155 /* Used below in the call to qsort. */
1156 static int compare(const void *a, const void *b)
1157 {
1158 const temp_attr *const l = (const temp_attr *) a;
1159 const temp_attr *const r = (const temp_attr *) b;
1160
1161 /* Reversed because we want a descending order sort below. */
1162 return r->slots - l->slots;
1163 }
1164 } to_assign[16];
1165
1166 unsigned num_attr = 0;
1167
Eric Anholt16b68b12010-06-30 11:05:43 -07001168 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001169 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1170
1171 if ((var == NULL) || (var->mode != ir_var_in))
1172 continue;
1173
1174 /* The location was explicitly assigned, nothing to do here.
1175 */
1176 if (var->location != -1)
1177 continue;
1178
Ian Romanick69846702010-06-22 17:29:19 -07001179 to_assign[num_attr].slots = count_attribute_slots(var->type);
1180 to_assign[num_attr].var = var;
1181 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001182 }
Ian Romanick69846702010-06-22 17:29:19 -07001183
1184 /* If all of the attributes were assigned locations by the application (or
1185 * are built-in attributes with fixed locations), return early. This should
1186 * be the common case.
1187 */
1188 if (num_attr == 0)
1189 return true;
1190
1191 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1192
Ian Romanick982e3792010-06-29 18:58:20 -07001193 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1194 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1195 * to prevent it from being automatically allocated below.
1196 */
Ian Romanickc33e78f2010-08-13 12:30:41 -07001197 find_deref_visitor find("gl_Vertex");
1198 find.run(sh->ir);
1199 if (find.variable_found())
1200 used_locations |= (1 << 0);
Ian Romanick982e3792010-06-29 18:58:20 -07001201
Ian Romanick69846702010-06-22 17:29:19 -07001202 for (unsigned i = 0; i < num_attr; i++) {
1203 /* Mask representing the contiguous slots that will be used by this
1204 * attribute.
1205 */
1206 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1207
1208 int location = find_available_slots(used_locations, to_assign[i].slots);
1209
1210 if (location < 0) {
Ian Romanick553dcdc2010-06-23 12:14:02 -07001211 linker_error_printf(prog,
1212 "insufficient contiguous attribute locations "
1213 "available for vertex shader input `%s'",
1214 to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001215 return false;
1216 }
1217
1218 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
1219 used_locations |= (use_mask << location);
1220 }
1221
1222 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001223}
1224
1225
Ian Romanick40e114b2010-08-17 14:55:50 -07001226/**
1227 * Demote shader outputs that are not read to being just plain global variables
1228 */
1229void
1230demote_unread_shader_outputs(gl_shader *sh)
1231{
1232 foreach_list(node, sh->ir) {
1233 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1234
1235 if ((var == NULL) || (var->mode != ir_var_out))
1236 continue;
1237
1238 /* An 'out' variable is only really a shader output if its value is read
1239 * by the following stage.
1240 */
1241 if (var->location == -1) {
1242 var->mode = ir_var_auto;
1243 }
1244 }
1245}
1246
1247
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001248void
Eric Anholtb7062832010-07-28 13:52:23 -07001249assign_varying_locations(struct gl_shader_program *prog,
1250 gl_shader *producer, gl_shader *consumer)
Ian Romanick0e59b262010-06-23 11:23:01 -07001251{
1252 /* FINISHME: Set dynamically when geometry shader support is added. */
1253 unsigned output_index = VERT_RESULT_VAR0;
1254 unsigned input_index = FRAG_ATTRIB_VAR0;
1255
1256 /* Operate in a total of three passes.
1257 *
1258 * 1. Assign locations for any matching inputs and outputs.
1259 *
1260 * 2. Mark output variables in the producer that do not have locations as
1261 * not being outputs. This lets the optimizer eliminate them.
1262 *
1263 * 3. Mark input variables in the consumer that do not have locations as
1264 * not being inputs. This lets the optimizer eliminate them.
1265 */
1266
1267 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1268 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1269
Eric Anholt16b68b12010-06-30 11:05:43 -07001270 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001271 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1272
1273 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1274 || (output_var->location != -1))
1275 continue;
1276
1277 ir_variable *const input_var =
1278 consumer->symbols->get_variable(output_var->name);
1279
1280 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1281 continue;
1282
1283 assert(input_var->location == -1);
1284
1285 /* FINISHME: Location assignment will need some changes when arrays,
1286 * FINISHME: matrices, and structures are allowed as shader inputs /
1287 * FINISHME: outputs.
1288 */
1289 output_var->location = output_index;
1290 input_var->location = input_index;
1291
1292 output_index++;
1293 input_index++;
1294 }
1295
Ian Romanick40e114b2010-08-17 14:55:50 -07001296 demote_unread_shader_outputs(producer);
Ian Romanick0e59b262010-06-23 11:23:01 -07001297
Eric Anholt16b68b12010-06-30 11:05:43 -07001298 foreach_list(node, consumer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001299 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1300
1301 if ((var == NULL) || (var->mode != ir_var_in))
1302 continue;
1303
Eric Anholtb7062832010-07-28 13:52:23 -07001304 if (var->location == -1) {
1305 if (prog->Version <= 120) {
1306 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1307 *
1308 * Only those varying variables used (i.e. read) in
1309 * the fragment shader executable must be written to
1310 * by the vertex shader executable; declaring
1311 * superfluous varying variables in a vertex shader is
1312 * permissible.
1313 *
1314 * We interpret this text as meaning that the VS must
1315 * write the variable for the FS to read it. See
1316 * "glsl1-varying read but not written" in piglit.
1317 */
1318
1319 linker_error_printf(prog, "fragment shader varying %s not written "
1320 "by vertex shader\n.", var->name);
1321 prog->LinkStatus = false;
1322 }
1323
1324 /* An 'in' variable is only really a shader input if its
1325 * value is written by the previous stage.
1326 */
Eric Anholtb7062832010-07-28 13:52:23 -07001327 var->mode = ir_var_auto;
1328 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001329 }
1330}
1331
1332
1333void
Eric Anholt5d0f4302010-08-18 12:02:35 -07001334link_shaders(GLcontext *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07001335{
1336 prog->LinkStatus = false;
1337 prog->Validated = false;
1338 prog->_Used = false;
1339
Ian Romanickf36460e2010-06-23 12:07:22 -07001340 if (prog->InfoLog != NULL)
1341 talloc_free(prog->InfoLog);
1342
1343 prog->InfoLog = talloc_strdup(NULL, "");
1344
Ian Romanick832dfa52010-06-17 15:04:20 -07001345 /* Separate the shaders into groups based on their type.
1346 */
Eric Anholt16b68b12010-06-30 11:05:43 -07001347 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001348 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07001349 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001350 unsigned num_frag_shaders = 0;
1351
Eric Anholt16b68b12010-06-30 11:05:43 -07001352 vert_shader_list = (struct gl_shader **)
1353 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07001354 frag_shader_list = &vert_shader_list[prog->NumShaders];
1355
Ian Romanick25f51d32010-07-16 15:51:50 -07001356 unsigned min_version = UINT_MAX;
1357 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07001358 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07001359 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1360 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1361
Ian Romanick832dfa52010-06-17 15:04:20 -07001362 switch (prog->Shaders[i]->Type) {
1363 case GL_VERTEX_SHADER:
1364 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1365 num_vert_shaders++;
1366 break;
1367 case GL_FRAGMENT_SHADER:
1368 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1369 num_frag_shaders++;
1370 break;
1371 case GL_GEOMETRY_SHADER:
1372 /* FINISHME: Support geometry shaders. */
1373 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1374 break;
1375 }
1376 }
1377
Ian Romanick25f51d32010-07-16 15:51:50 -07001378 /* Previous to GLSL version 1.30, different compilation units could mix and
1379 * match shading language versions. With GLSL 1.30 and later, the versions
1380 * of all shaders must match.
1381 */
1382 assert(min_version >= 110);
1383 assert(max_version <= 130);
1384 if ((max_version >= 130) && (min_version != max_version)) {
1385 linker_error_printf(prog, "all shaders must use same shading "
1386 "language version\n");
1387 goto done;
1388 }
1389
1390 prog->Version = max_version;
1391
Eric Anholt5d0f4302010-08-18 12:02:35 -07001392 for (unsigned int i = 0; i < prog->_NumLinkedShaders; i++) {
1393 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1394 }
1395
Ian Romanickcd6764e2010-07-16 16:00:07 -07001396 /* Link all shaders for a particular stage and validate the result.
1397 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001398 prog->_NumLinkedShaders = 0;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001399 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001400 gl_shader *const sh =
Eric Anholt5d0f4302010-08-18 12:02:35 -07001401 link_intrastage_shaders(ctx, prog, vert_shader_list, num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001402
1403 if (sh == NULL)
1404 goto done;
1405
1406 if (!validate_vertex_shader_executable(prog, sh))
1407 goto done;
1408
1409 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
Ian Romanickabee16e2010-06-21 16:16:05 -07001410 prog->_NumLinkedShaders++;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001411 }
1412
1413 if (num_frag_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, frag_shader_list, num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001416
1417 if (sh == NULL)
1418 goto done;
1419
1420 if (!validate_fragment_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
Ian Romanick3ed850e2010-06-23 12:18:21 -07001427 /* Here begins the inter-stage linking phase. Some initial validation is
1428 * performed, then locations are assigned for uniforms, attributes, and
1429 * varyings.
1430 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001431 if (cross_validate_uniforms(prog)) {
Ian Romanick37101922010-06-18 19:02:10 -07001432 /* Validate the inputs of each stage with the output of the preceeding
1433 * stage.
1434 */
Ian Romanickabee16e2010-06-21 16:16:05 -07001435 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
Ian Romanickf36460e2010-06-23 12:07:22 -07001436 if (!cross_validate_outputs_to_inputs(prog,
1437 prog->_LinkedShaders[i - 1],
Ian Romanickabee16e2010-06-21 16:16:05 -07001438 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001439 goto done;
1440 }
1441
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001442 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001443 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001444
Eric Anholt2f4fe152010-08-10 13:06:49 -07001445 /* Do common optimization before assigning storage for attributes,
1446 * uniforms, and varyings. Later optimization could possibly make
1447 * some of that unused.
1448 */
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001449 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
Eric Anholt2f4fe152010-08-10 13:06:49 -07001450 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true))
1451 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001452 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001453
Ian Romanickabee16e2010-06-21 16:16:05 -07001454 assign_uniform_locations(prog);
Ian Romanick13e10e42010-06-21 12:03:24 -07001455
Ian Romanick40e114b2010-08-17 14:55:50 -07001456 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER) {
Ian Romanick9342d262010-06-22 17:41:37 -07001457 /* FINISHME: The value of the max_attribute_index parameter is
1458 * FINISHME: implementation dependent based on the value of
1459 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1460 * FINISHME: at least 16, so hardcode 16 for now.
1461 */
Ian Romanick553dcdc2010-06-23 12:14:02 -07001462 if (!assign_attribute_locations(prog, 16))
Ian Romanick69846702010-06-22 17:29:19 -07001463 goto done;
Ian Romanick13e10e42010-06-21 12:03:24 -07001464
Ian Romanick40e114b2010-08-17 14:55:50 -07001465 if (prog->_NumLinkedShaders == 1)
1466 demote_unread_shader_outputs(prog->_LinkedShaders[0]);
1467 }
1468
Ian Romanick0e59b262010-06-23 11:23:01 -07001469 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
Eric Anholtb7062832010-07-28 13:52:23 -07001470 assign_varying_locations(prog,
1471 prog->_LinkedShaders[i - 1],
Ian Romanick0e59b262010-06-23 11:23:01 -07001472 prog->_LinkedShaders[i]);
Ian Romanick13e10e42010-06-21 12:03:24 -07001473
1474 /* FINISHME: Assign fragment shader output locations. */
1475
Ian Romanick832dfa52010-06-17 15:04:20 -07001476done:
1477 free(vert_shader_list);
1478}