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