Merge branch 'mesa_7_5_branch' into mesa_7_6_branch
[mesa.git] / src / mesa / shader / slang / slang_link.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.3
4 *
5 * Copyright (C) 2008 Brian Paul All Rights Reserved.
6 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file slang_link.c
28 * GLSL linker
29 * \author Brian Paul
30 */
31
32 #include "main/imports.h"
33 #include "main/context.h"
34 #include "main/hash.h"
35 #include "main/macros.h"
36 #include "shader/program.h"
37 #include "shader/prog_instruction.h"
38 #include "shader/prog_parameter.h"
39 #include "shader/prog_print.h"
40 #include "shader/prog_statevars.h"
41 #include "shader/prog_uniform.h"
42 #include "shader/shader_api.h"
43 #include "slang_builtin.h"
44 #include "slang_link.h"
45
46
47 /** cast wrapper */
48 static struct gl_vertex_program *
49 vertex_program(struct gl_program *prog)
50 {
51 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
52 return (struct gl_vertex_program *) prog;
53 }
54
55
56 /** cast wrapper */
57 static struct gl_fragment_program *
58 fragment_program(struct gl_program *prog)
59 {
60 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
61 return (struct gl_fragment_program *) prog;
62 }
63
64
65 /**
66 * Record a linking error.
67 */
68 static void
69 link_error(struct gl_shader_program *shProg, const char *msg)
70 {
71 if (shProg->InfoLog) {
72 _mesa_free(shProg->InfoLog);
73 }
74 shProg->InfoLog = _mesa_strdup(msg);
75 shProg->LinkStatus = GL_FALSE;
76 }
77
78
79
80 /**
81 * Check if the given bit is either set or clear in both bitfields.
82 */
83 static GLboolean
84 bits_agree(GLbitfield flags1, GLbitfield flags2, GLbitfield bit)
85 {
86 return (flags1 & bit) == (flags2 & bit);
87 }
88
89
90 /**
91 * Linking varying vars involves rearranging varying vars so that the
92 * vertex program's output varyings matches the order of the fragment
93 * program's input varyings.
94 * We'll then rewrite instructions to replace PROGRAM_VARYING with either
95 * PROGRAM_INPUT or PROGRAM_OUTPUT depending on whether it's a vertex or
96 * fragment shader.
97 * This is also where we set program Input/OutputFlags to indicate
98 * which inputs are centroid-sampled, invariant, etc.
99 */
100 static GLboolean
101 link_varying_vars(GLcontext *ctx,
102 struct gl_shader_program *shProg, struct gl_program *prog)
103 {
104 GLuint *map, i, firstVarying, newFile;
105 GLbitfield *inOutFlags;
106
107 map = (GLuint *) malloc(prog->Varying->NumParameters * sizeof(GLuint));
108 if (!map)
109 return GL_FALSE;
110
111 /* Varying variables are treated like other vertex program outputs
112 * (and like other fragment program inputs). The position of the
113 * first varying differs for vertex/fragment programs...
114 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
115 */
116 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
117 firstVarying = VERT_RESULT_VAR0;
118 newFile = PROGRAM_OUTPUT;
119 inOutFlags = prog->OutputFlags;
120 }
121 else {
122 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
123 firstVarying = FRAG_ATTRIB_VAR0;
124 newFile = PROGRAM_INPUT;
125 inOutFlags = prog->InputFlags;
126 }
127
128 for (i = 0; i < prog->Varying->NumParameters; i++) {
129 /* see if this varying is in the linked varying list */
130 const struct gl_program_parameter *var = prog->Varying->Parameters + i;
131 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
132 if (j >= 0) {
133 /* varying is already in list, do some error checking */
134 const struct gl_program_parameter *v =
135 &shProg->Varying->Parameters[j];
136 if (var->Size != v->Size) {
137 link_error(shProg, "mismatched varying variable types");
138 return GL_FALSE;
139 }
140 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_CENTROID)) {
141 char msg[100];
142 _mesa_snprintf(msg, sizeof(msg),
143 "centroid modifier mismatch for '%s'", var->Name);
144 link_error(shProg, msg);
145 return GL_FALSE;
146 }
147 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_INVARIANT)) {
148 char msg[100];
149 _mesa_snprintf(msg, sizeof(msg),
150 "invariant modifier mismatch for '%s'", var->Name);
151 link_error(shProg, msg);
152 return GL_FALSE;
153 }
154 }
155 else {
156 /* not already in linked list */
157 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size,
158 var->Flags);
159 }
160
161 if (shProg->Varying->NumParameters > ctx->Const.MaxVarying) {
162 link_error(shProg, "Too many varying variables");
163 return GL_FALSE;
164 }
165
166 /* Map varying[i] to varying[j].
167 * Note: the loop here takes care of arrays or large (sz>4) vars.
168 */
169 {
170 GLint sz = var->Size;
171 while (sz > 0) {
172 inOutFlags[firstVarying + j] = var->Flags;
173 /*printf("Link varying from %d to %d\n", i, j);*/
174 map[i++] = j++;
175 sz -= 4;
176 }
177 i--; /* go back one */
178 }
179 }
180
181
182 /* OK, now scan the program/shader instructions looking for varying vars,
183 * replacing the old index with the new index.
184 */
185 for (i = 0; i < prog->NumInstructions; i++) {
186 struct prog_instruction *inst = prog->Instructions + i;
187 GLuint j;
188
189 if (inst->DstReg.File == PROGRAM_VARYING) {
190 inst->DstReg.File = newFile;
191 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
192 }
193
194 for (j = 0; j < 3; j++) {
195 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
196 inst->SrcReg[j].File = newFile;
197 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
198 }
199 }
200 }
201
202 free(map);
203
204 /* these will get recomputed before linking is completed */
205 prog->InputsRead = 0x0;
206 prog->OutputsWritten = 0x0;
207
208 return GL_TRUE;
209 }
210
211
212 /**
213 * Build the shProg->Uniforms list.
214 * This is basically a list/index of all uniforms found in either/both of
215 * the vertex and fragment shaders.
216 *
217 * About uniforms:
218 * Each uniform has two indexes, one that points into the vertex
219 * program's parameter array and another that points into the fragment
220 * program's parameter array. When the user changes a uniform's value
221 * we have to change the value in the vertex and/or fragment program's
222 * parameter array.
223 *
224 * This function will be called twice to set up the two uniform->parameter
225 * mappings.
226 *
227 * If a uniform is only present in the vertex program OR fragment program
228 * then the fragment/vertex parameter index, respectively, will be -1.
229 */
230 static GLboolean
231 link_uniform_vars(GLcontext *ctx,
232 struct gl_shader_program *shProg,
233 struct gl_program *prog,
234 GLuint *numSamplers)
235 {
236 GLuint samplerMap[200]; /* max number of samplers declared, not used */
237 GLuint i;
238
239 for (i = 0; i < prog->Parameters->NumParameters; i++) {
240 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
241
242 /*
243 * XXX FIX NEEDED HERE
244 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
245 * For example, modelview matrix, light pos, etc.
246 * Also, we need to update the state-var name-generator code to
247 * generate GLSL-style names, like "gl_LightSource[0].position".
248 * Furthermore, we'll need to fix the state-var's size/datatype info.
249 */
250
251 if ((p->Type == PROGRAM_UNIFORM || p->Type == PROGRAM_SAMPLER)
252 && p->Used) {
253 /* add this uniform, indexing into the target's Parameters list */
254 struct gl_uniform *uniform =
255 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
256 if (uniform)
257 uniform->Initialized = p->Initialized;
258 }
259
260 /* The samplerMap[] table we build here is used to remap/re-index
261 * sampler references by TEX instructions.
262 */
263 if (p->Type == PROGRAM_SAMPLER && p->Used) {
264 /* Allocate a new sampler index */
265 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
266 GLuint newSampNum = *numSamplers;
267 if (newSampNum >= ctx->Const.MaxTextureImageUnits) {
268 char s[100];
269 _mesa_sprintf(s, "Too many texture samplers (%u, max is %u)",
270 newSampNum, ctx->Const.MaxTextureImageUnits);
271 link_error(shProg, s);
272 return GL_FALSE;
273 }
274 /* save old->new mapping in the table */
275 if (oldSampNum < Elements(samplerMap))
276 samplerMap[oldSampNum] = newSampNum;
277 /* update parameter's sampler index */
278 prog->Parameters->ParameterValues[i][0] = (GLfloat) newSampNum;
279 (*numSamplers)++;
280 }
281 }
282
283 /* OK, now scan the program/shader instructions looking for texture
284 * instructions using sampler vars. Replace old sampler indexes with
285 * new ones.
286 */
287 prog->SamplersUsed = 0x0;
288 for (i = 0; i < prog->NumInstructions; i++) {
289 struct prog_instruction *inst = prog->Instructions + i;
290 if (_mesa_is_tex_instruction(inst->Opcode)) {
291 /* here, inst->TexSrcUnit is really the sampler unit */
292 const GLint oldSampNum = inst->TexSrcUnit;
293
294 #if 0
295 printf("====== remap sampler from %d to %d\n",
296 inst->TexSrcUnit, samplerMap[ inst->TexSrcUnit ]);
297 #endif
298
299 if (oldSampNum < Elements(samplerMap)) {
300 const GLuint newSampNum = samplerMap[oldSampNum];
301 inst->TexSrcUnit = newSampNum;
302 prog->SamplerTargets[newSampNum] = inst->TexSrcTarget;
303 prog->SamplersUsed |= (1 << newSampNum);
304 if (inst->TexShadow) {
305 prog->ShadowSamplers |= (1 << newSampNum);
306 }
307 }
308 }
309 }
310
311 return GL_TRUE;
312 }
313
314
315 /**
316 * Resolve binding of generic vertex attributes.
317 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
318 * allocate a generic vertex attribute for "foobar" and plug that value into
319 * the vertex program instructions.
320 * But if the user called glBindAttributeLocation(), those bindings will
321 * have priority.
322 */
323 static GLboolean
324 _slang_resolve_attributes(struct gl_shader_program *shProg,
325 const struct gl_program *origProg,
326 struct gl_program *linkedProg)
327 {
328 GLint attribMap[MAX_VERTEX_GENERIC_ATTRIBS];
329 GLuint i, j;
330 GLbitfield usedAttributes; /* generics only, not legacy attributes */
331 GLbitfield inputsRead = 0x0;
332
333 assert(origProg != linkedProg);
334 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
335 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
336
337 if (!shProg->Attributes)
338 shProg->Attributes = _mesa_new_parameter_list();
339
340 if (linkedProg->Attributes) {
341 _mesa_free_parameter_list(linkedProg->Attributes);
342 }
343 linkedProg->Attributes = _mesa_new_parameter_list();
344
345
346 /* Build a bitmask indicating which attribute indexes have been
347 * explicitly bound by the user with glBindAttributeLocation().
348 */
349 usedAttributes = 0x0;
350 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
351 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
352 usedAttributes |= (1 << attr);
353 }
354
355 /* If gl_Vertex is used, that actually counts against the limit
356 * on generic vertex attributes. This avoids the ambiguity of
357 * whether glVertexAttrib4fv(0, v) sets legacy attribute 0 (vert pos)
358 * or generic attribute[0]. If gl_Vertex is used, we want the former.
359 */
360 if (origProg->InputsRead & VERT_BIT_POS) {
361 usedAttributes |= 0x1;
362 }
363
364 /* initialize the generic attribute map entries to -1 */
365 for (i = 0; i < MAX_VERTEX_GENERIC_ATTRIBS; i++) {
366 attribMap[i] = -1;
367 }
368
369 /*
370 * Scan program for generic attribute references
371 */
372 for (i = 0; i < linkedProg->NumInstructions; i++) {
373 struct prog_instruction *inst = linkedProg->Instructions + i;
374 for (j = 0; j < 3; j++) {
375 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
376 inputsRead |= (1 << inst->SrcReg[j].Index);
377 }
378
379 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
380 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
381 /*
382 * OK, we've found a generic vertex attribute reference.
383 */
384 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
385
386 GLint attr = attribMap[k];
387
388 if (attr < 0) {
389 /* Need to figure out attribute mapping now.
390 */
391 const char *name = origProg->Attributes->Parameters[k].Name;
392 const GLint size = origProg->Attributes->Parameters[k].Size;
393 const GLenum type =origProg->Attributes->Parameters[k].DataType;
394 GLint index;
395
396 /* See if there's a user-defined attribute binding for
397 * this name.
398 */
399 index = _mesa_lookup_parameter_index(shProg->Attributes,
400 -1, name);
401 if (index >= 0) {
402 /* Found a user-defined binding */
403 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
404 }
405 else {
406 /* No user-defined binding, choose our own attribute number.
407 * Start at 1 since generic attribute 0 always aliases
408 * glVertex/position.
409 */
410 for (attr = 0; attr < MAX_VERTEX_GENERIC_ATTRIBS; attr++) {
411 if (((1 << attr) & usedAttributes) == 0)
412 break;
413 }
414 if (attr == MAX_VERTEX_GENERIC_ATTRIBS) {
415 link_error(shProg, "Too many vertex attributes");
416 return GL_FALSE;
417 }
418
419 /* mark this attribute as used */
420 usedAttributes |= (1 << attr);
421 }
422
423 attribMap[k] = attr;
424
425 /* Save the final name->attrib binding so it can be queried
426 * with glGetAttributeLocation().
427 */
428 _mesa_add_attribute(linkedProg->Attributes, name,
429 size, type, attr);
430 }
431
432 assert(attr >= 0);
433
434 /* update the instruction's src reg */
435 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
436 }
437 }
438 }
439
440 /* Handle pre-defined attributes here (gl_Vertex, gl_Normal, etc).
441 * When the user queries the active attributes we need to include both
442 * the user-defined attributes and the built-in ones.
443 */
444 for (i = VERT_ATTRIB_POS; i < VERT_ATTRIB_GENERIC0; i++) {
445 if (inputsRead & (1 << i)) {
446 _mesa_add_attribute(linkedProg->Attributes,
447 _slang_vert_attrib_name(i),
448 4, /* size in floats */
449 _slang_vert_attrib_type(i),
450 -1 /* attrib/input */);
451 }
452 }
453
454 return GL_TRUE;
455 }
456
457
458 /**
459 * Scan program instructions to update the program's NumTemporaries field.
460 * Note: this implemenation relies on the code generator allocating
461 * temps in increasing order (0, 1, 2, ... ).
462 */
463 static void
464 _slang_count_temporaries(struct gl_program *prog)
465 {
466 GLuint i, j;
467 GLint maxIndex = -1;
468
469 for (i = 0; i < prog->NumInstructions; i++) {
470 const struct prog_instruction *inst = prog->Instructions + i;
471 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
472 for (j = 0; j < numSrc; j++) {
473 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
474 if (maxIndex < inst->SrcReg[j].Index)
475 maxIndex = inst->SrcReg[j].Index;
476 }
477 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
478 if (maxIndex < (GLint) inst->DstReg.Index)
479 maxIndex = inst->DstReg.Index;
480 }
481 }
482 }
483
484 prog->NumTemporaries = (GLuint) (maxIndex + 1);
485 }
486
487
488 /**
489 * Scan program instructions to update the program's InputsRead and
490 * OutputsWritten fields.
491 */
492 static void
493 _slang_update_inputs_outputs(struct gl_program *prog)
494 {
495 GLuint i, j;
496 GLuint maxAddrReg = 0;
497
498 prog->InputsRead = 0x0;
499 prog->OutputsWritten = 0x0;
500
501 for (i = 0; i < prog->NumInstructions; i++) {
502 const struct prog_instruction *inst = prog->Instructions + i;
503 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
504 for (j = 0; j < numSrc; j++) {
505 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
506 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
507 }
508 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
509 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
510 }
511 }
512
513 if (inst->DstReg.File == PROGRAM_OUTPUT) {
514 prog->OutputsWritten |= 1 << inst->DstReg.Index;
515 if (inst->DstReg.RelAddr) {
516 /* If the output attribute is indexed with relative addressing
517 * we know that it must be a varying or texcoord such as
518 * gl_TexCoord[i] = v; In this case, mark all the texcoords
519 * or varying outputs as being written. It's not an error if
520 * a vertex shader writes varying vars that aren't used by the
521 * fragment shader. But it is an error for a fragment shader
522 * to use varyings that are not written by the vertex shader.
523 */
524 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
525 if (inst->DstReg.Index == VERT_RESULT_TEX0) {
526 /* mark all texcoord outputs as written */
527 const GLbitfield mask =
528 ((1 << MAX_TEXTURE_COORD_UNITS) - 1) << VERT_RESULT_TEX0;
529 prog->OutputsWritten |= mask;
530 }
531 else if (inst->DstReg.Index == VERT_RESULT_VAR0) {
532 /* mark all generic varying outputs as written */
533 const GLbitfield mask =
534 ((1 << MAX_VARYING) - 1) << VERT_RESULT_VAR0;
535 prog->OutputsWritten |= mask;
536 }
537 }
538 }
539 }
540 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
541 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
542 }
543 }
544 prog->NumAddressRegs = maxAddrReg;
545 }
546
547
548
549 /**
550 * Remove extra #version directives from the concatenated source string.
551 * Disable the extra ones by converting first two chars to //, a comment.
552 * This is a bit of hack to work around a preprocessor bug that only
553 * allows one #version directive per source.
554 */
555 static void
556 remove_extra_version_directives(GLchar *source)
557 {
558 GLuint verCount = 0;
559 while (1) {
560 char *ver = _mesa_strstr(source, "#version");
561 if (ver) {
562 verCount++;
563 if (verCount > 1) {
564 ver[0] = '/';
565 ver[1] = '/';
566 }
567 source += 8;
568 }
569 else {
570 break;
571 }
572 }
573 }
574
575
576
577 /**
578 * Return a new shader whose source code is the concatenation of
579 * all the shader sources of the given type.
580 */
581 static struct gl_shader *
582 concat_shaders(struct gl_shader_program *shProg, GLenum shaderType)
583 {
584 struct gl_shader *newShader;
585 const struct gl_shader *firstShader = NULL;
586 GLuint shaderLengths[100];
587 GLchar *source;
588 GLuint totalLen = 0, len = 0;
589 GLuint i;
590
591 /* compute total size of new shader source code */
592 for (i = 0; i < shProg->NumShaders; i++) {
593 const struct gl_shader *shader = shProg->Shaders[i];
594 if (shader->Type == shaderType) {
595 shaderLengths[i] = _mesa_strlen(shader->Source);
596 totalLen += shaderLengths[i];
597 if (!firstShader)
598 firstShader = shader;
599 }
600 }
601
602 if (totalLen == 0)
603 return NULL;
604
605 source = (GLchar *) _mesa_malloc(totalLen + 1);
606 if (!source)
607 return NULL;
608
609 /* concatenate shaders */
610 for (i = 0; i < shProg->NumShaders; i++) {
611 const struct gl_shader *shader = shProg->Shaders[i];
612 if (shader->Type == shaderType) {
613 _mesa_memcpy(source + len, shader->Source, shaderLengths[i]);
614 len += shaderLengths[i];
615 }
616 }
617 source[len] = '\0';
618 /*
619 _mesa_printf("---NEW CONCATENATED SHADER---:\n%s\n------------\n", source);
620 */
621
622 remove_extra_version_directives(source);
623
624 newShader = CALLOC_STRUCT(gl_shader);
625 newShader->Type = shaderType;
626 newShader->Source = source;
627 newShader->Pragmas = firstShader->Pragmas;
628
629 return newShader;
630 }
631
632
633 /**
634 * Search the shader program's list of shaders to find the one that
635 * defines main().
636 * This will involve shader concatenation and recompilation if needed.
637 */
638 static struct gl_shader *
639 get_main_shader(GLcontext *ctx,
640 struct gl_shader_program *shProg, GLenum type)
641 {
642 struct gl_shader *shader = NULL;
643 GLuint i;
644
645 /*
646 * Look for a shader that defines main() and has no unresolved references.
647 */
648 for (i = 0; i < shProg->NumShaders; i++) {
649 shader = shProg->Shaders[i];
650 if (shader->Type == type &&
651 shader->Main &&
652 !shader->UnresolvedRefs) {
653 /* All set! */
654 return shader;
655 }
656 }
657
658 /*
659 * There must have been unresolved references during the original
660 * compilation. Try concatenating all the shaders of the given type
661 * and recompile that.
662 */
663 shader = concat_shaders(shProg, type);
664
665 if (shader) {
666 _slang_compile(ctx, shader);
667
668 /* Finally, check if recompiling failed */
669 if (!shader->CompileStatus ||
670 !shader->Main ||
671 shader->UnresolvedRefs) {
672 link_error(shProg, "Unresolved symbols");
673 return NULL;
674 }
675 }
676
677 return shader;
678 }
679
680
681 /**
682 * Shader linker. Currently:
683 *
684 * 1. The last attached vertex shader and fragment shader are linked.
685 * 2. Varying vars in the two shaders are combined so their locations
686 * agree between the vertex and fragment stages. They're treated as
687 * vertex program output attribs and as fragment program input attribs.
688 * 3. The vertex and fragment programs are cloned and modified to update
689 * src/dst register references so they use the new, linked varying
690 * storage locations.
691 */
692 void
693 _slang_link(GLcontext *ctx,
694 GLhandleARB programObj,
695 struct gl_shader_program *shProg)
696 {
697 const struct gl_vertex_program *vertProg = NULL;
698 const struct gl_fragment_program *fragProg = NULL;
699 GLuint numSamplers = 0;
700 GLuint i;
701
702 _mesa_clear_shader_program_data(ctx, shProg);
703
704 /* Initialize LinkStatus to "success". Will be cleared if error. */
705 shProg->LinkStatus = GL_TRUE;
706
707 /* check that all programs compiled successfully */
708 for (i = 0; i < shProg->NumShaders; i++) {
709 if (!shProg->Shaders[i]->CompileStatus) {
710 link_error(shProg, "linking with uncompiled shader\n");
711 return;
712 }
713 }
714
715 shProg->Uniforms = _mesa_new_uniform_list();
716 shProg->Varying = _mesa_new_parameter_list();
717
718 /*
719 * Find the vertex and fragment shaders which define main()
720 */
721 {
722 struct gl_shader *vertShader, *fragShader;
723 vertShader = get_main_shader(ctx, shProg, GL_VERTEX_SHADER);
724 fragShader = get_main_shader(ctx, shProg, GL_FRAGMENT_SHADER);
725 if (vertShader)
726 vertProg = vertex_program(vertShader->Program);
727 if (fragShader)
728 fragProg = fragment_program(fragShader->Program);
729 if (!shProg->LinkStatus)
730 return;
731 }
732
733 #if FEATURE_es2_glsl
734 /* must have both a vertex and fragment program for ES2 */
735 if (!vertProg) {
736 link_error(shProg, "missing vertex shader\n");
737 return;
738 }
739 if (!fragProg) {
740 link_error(shProg, "missing fragment shader\n");
741 return;
742 }
743 #endif
744
745 /*
746 * Make copies of the vertex/fragment programs now since we'll be
747 * changing src/dst registers after merging the uniforms and varying vars.
748 */
749 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
750 if (vertProg) {
751 struct gl_vertex_program *linked_vprog =
752 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
753 shProg->VertexProgram = linked_vprog; /* refcount OK */
754 /* vertex program ID not significant; just set Id for debugging purposes */
755 shProg->VertexProgram->Base.Id = shProg->Name;
756 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
757 }
758
759 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
760 if (fragProg) {
761 struct gl_fragment_program *linked_fprog =
762 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
763 shProg->FragmentProgram = linked_fprog; /* refcount OK */
764 /* vertex program ID not significant; just set Id for debugging purposes */
765 shProg->FragmentProgram->Base.Id = shProg->Name;
766 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
767 }
768
769 /* link varying vars */
770 if (shProg->VertexProgram) {
771 if (!link_varying_vars(ctx, shProg, &shProg->VertexProgram->Base))
772 return;
773 }
774 if (shProg->FragmentProgram) {
775 if (!link_varying_vars(ctx, shProg, &shProg->FragmentProgram->Base))
776 return;
777 }
778
779 /* link uniform vars */
780 if (shProg->VertexProgram) {
781 if (!link_uniform_vars(ctx, shProg, &shProg->VertexProgram->Base,
782 &numSamplers)) {
783 return;
784 }
785 }
786 if (shProg->FragmentProgram) {
787 if (!link_uniform_vars(ctx, shProg, &shProg->FragmentProgram->Base,
788 &numSamplers)) {
789 return;
790 }
791 }
792
793 /*_mesa_print_uniforms(shProg->Uniforms);*/
794
795 if (shProg->VertexProgram) {
796 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
797 &shProg->VertexProgram->Base)) {
798 return;
799 }
800 }
801
802 if (shProg->VertexProgram) {
803 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
804 _slang_count_temporaries(&shProg->VertexProgram->Base);
805 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
806 /* the vertex program did not compute a vertex position */
807 link_error(shProg,
808 "gl_Position was not written by vertex shader\n");
809 return;
810 }
811 }
812 if (shProg->FragmentProgram) {
813 _slang_count_temporaries(&shProg->FragmentProgram->Base);
814 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
815 }
816
817 /* Check that all the varying vars needed by the fragment shader are
818 * actually produced by the vertex shader.
819 */
820 if (shProg->FragmentProgram) {
821 const GLbitfield varyingRead
822 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
823 const GLbitfield varyingWritten = shProg->VertexProgram ?
824 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
825 if ((varyingRead & varyingWritten) != varyingRead) {
826 link_error(shProg,
827 "Fragment program using varying vars not written by vertex shader\n");
828 return;
829 }
830 }
831
832 /* check that gl_FragColor and gl_FragData are not both written to */
833 if (shProg->FragmentProgram) {
834 GLbitfield outputsWritten = shProg->FragmentProgram->Base.OutputsWritten;
835 if ((outputsWritten & ((1 << FRAG_RESULT_COLOR))) &&
836 (outputsWritten >= (1 << FRAG_RESULT_DATA0))) {
837 link_error(shProg, "Fragment program cannot write both gl_FragColor"
838 " and gl_FragData[].\n");
839 return;
840 }
841 }
842
843
844 if (fragProg && shProg->FragmentProgram) {
845 /* Compute initial program's TexturesUsed info */
846 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
847
848 /* notify driver that a new fragment program has been compiled/linked */
849 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
850 &shProg->FragmentProgram->Base);
851 if (ctx->Shader.Flags & GLSL_DUMP) {
852 _mesa_printf("Mesa pre-link fragment program:\n");
853 _mesa_print_program(&fragProg->Base);
854 _mesa_print_program_parameters(ctx, &fragProg->Base);
855
856 _mesa_printf("Mesa post-link fragment program:\n");
857 _mesa_print_program(&shProg->FragmentProgram->Base);
858 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
859 }
860 }
861
862 if (vertProg && shProg->VertexProgram) {
863 /* Compute initial program's TexturesUsed info */
864 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
865
866 /* notify driver that a new vertex program has been compiled/linked */
867 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
868 &shProg->VertexProgram->Base);
869 if (ctx->Shader.Flags & GLSL_DUMP) {
870 _mesa_printf("Mesa pre-link vertex program:\n");
871 _mesa_print_program(&vertProg->Base);
872 _mesa_print_program_parameters(ctx, &vertProg->Base);
873
874 _mesa_printf("Mesa post-link vertex program:\n");
875 _mesa_print_program(&shProg->VertexProgram->Base);
876 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
877 }
878 }
879
880 /* Debug: */
881 if (0) {
882 if (shProg->VertexProgram)
883 _mesa_postprocess_program(ctx, &shProg->VertexProgram->Base);
884 if (shProg->FragmentProgram)
885 _mesa_postprocess_program(ctx, &shProg->FragmentProgram->Base);
886 }
887
888 if (ctx->Shader.Flags & GLSL_DUMP) {
889 _mesa_printf("Varying vars:\n");
890 _mesa_print_parameter_list(shProg->Varying);
891 if (shProg->InfoLog) {
892 _mesa_printf("Info Log: %s\n", shProg->InfoLog);
893 }
894 }
895
896 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
897 }
898