mesa: Handle FEATURE_es2_glsl differences at runtime too
[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 _mesa_snprintf(s, sizeof(s),
374 "Too many texture samplers (%u, max is %u)",
375 newSampNum, ctx->Const.MaxTextureImageUnits);
376 link_error(shProg, s);
377 return GL_FALSE;
378 }
379 /* save old->new mapping in the table */
380 if (oldSampNum < Elements(samplerMap))
381 samplerMap[oldSampNum] = newSampNum;
382 /* update parameter's sampler index */
383 prog->Parameters->ParameterValues[i][0] = (GLfloat) newSampNum;
384 (*numSamplers)++;
385 }
386 }
387
388 /* OK, now scan the program/shader instructions looking for texture
389 * instructions using sampler vars. Replace old sampler indexes with
390 * new ones.
391 */
392 prog->SamplersUsed = 0x0;
393 for (i = 0; i < prog->NumInstructions; i++) {
394 struct prog_instruction *inst = prog->Instructions + i;
395 if (_mesa_is_tex_instruction(inst->Opcode)) {
396 /* here, inst->TexSrcUnit is really the sampler unit */
397 const GLint oldSampNum = inst->TexSrcUnit;
398
399 #if 0
400 printf("====== remap sampler from %d to %d\n",
401 inst->TexSrcUnit, samplerMap[ inst->TexSrcUnit ]);
402 #endif
403
404 if (oldSampNum < Elements(samplerMap)) {
405 const GLuint newSampNum = samplerMap[oldSampNum];
406 inst->TexSrcUnit = newSampNum;
407 prog->SamplerTargets[newSampNum] = inst->TexSrcTarget;
408 prog->SamplersUsed |= (1 << newSampNum);
409 if (inst->TexShadow) {
410 prog->ShadowSamplers |= (1 << newSampNum);
411 }
412 }
413 }
414 }
415
416 return GL_TRUE;
417 }
418
419
420 /**
421 * Resolve binding of generic vertex attributes.
422 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
423 * allocate a generic vertex attribute for "foobar" and plug that value into
424 * the vertex program instructions.
425 * But if the user called glBindAttributeLocation(), those bindings will
426 * have priority.
427 */
428 static GLboolean
429 _slang_resolve_attributes(struct gl_shader_program *shProg,
430 const struct gl_program *origProg,
431 struct gl_program *linkedProg)
432 {
433 GLint attribMap[MAX_VERTEX_GENERIC_ATTRIBS];
434 GLuint i, j;
435 GLbitfield usedAttributes; /* generics only, not legacy attributes */
436 GLbitfield inputsRead = 0x0;
437
438 assert(origProg != linkedProg);
439 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
440 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
441
442 if (!shProg->Attributes)
443 shProg->Attributes = _mesa_new_parameter_list();
444
445 if (linkedProg->Attributes) {
446 _mesa_free_parameter_list(linkedProg->Attributes);
447 }
448 linkedProg->Attributes = _mesa_new_parameter_list();
449
450
451 /* Build a bitmask indicating which attribute indexes have been
452 * explicitly bound by the user with glBindAttributeLocation().
453 */
454 usedAttributes = 0x0;
455 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
456 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
457 usedAttributes |= (1 << attr);
458 }
459
460 /* If gl_Vertex is used, that actually counts against the limit
461 * on generic vertex attributes. This avoids the ambiguity of
462 * whether glVertexAttrib4fv(0, v) sets legacy attribute 0 (vert pos)
463 * or generic attribute[0]. If gl_Vertex is used, we want the former.
464 */
465 if (origProg->InputsRead & VERT_BIT_POS) {
466 usedAttributes |= 0x1;
467 }
468
469 /* initialize the generic attribute map entries to -1 */
470 for (i = 0; i < MAX_VERTEX_GENERIC_ATTRIBS; i++) {
471 attribMap[i] = -1;
472 }
473
474 /*
475 * Scan program for generic attribute references
476 */
477 for (i = 0; i < linkedProg->NumInstructions; i++) {
478 struct prog_instruction *inst = linkedProg->Instructions + i;
479 for (j = 0; j < 3; j++) {
480 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
481 inputsRead |= (1 << inst->SrcReg[j].Index);
482 }
483
484 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
485 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
486 /*
487 * OK, we've found a generic vertex attribute reference.
488 */
489 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
490
491 GLint attr = attribMap[k];
492
493 if (attr < 0) {
494 /* Need to figure out attribute mapping now.
495 */
496 const char *name = origProg->Attributes->Parameters[k].Name;
497 const GLint size = origProg->Attributes->Parameters[k].Size;
498 const GLenum type =origProg->Attributes->Parameters[k].DataType;
499 GLint index;
500
501 /* See if there's a user-defined attribute binding for
502 * this name.
503 */
504 index = _mesa_lookup_parameter_index(shProg->Attributes,
505 -1, name);
506 if (index >= 0) {
507 /* Found a user-defined binding */
508 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
509 }
510 else {
511 /* No user-defined binding, choose our own attribute number.
512 * Start at 1 since generic attribute 0 always aliases
513 * glVertex/position.
514 */
515 for (attr = 0; attr < MAX_VERTEX_GENERIC_ATTRIBS; attr++) {
516 if (((1 << attr) & usedAttributes) == 0)
517 break;
518 }
519 if (attr == MAX_VERTEX_GENERIC_ATTRIBS) {
520 link_error(shProg, "Too many vertex attributes");
521 return GL_FALSE;
522 }
523
524 /* mark this attribute as used */
525 usedAttributes |= (1 << attr);
526 }
527
528 attribMap[k] = attr;
529
530 /* Save the final name->attrib binding so it can be queried
531 * with glGetAttributeLocation().
532 */
533 _mesa_add_attribute(linkedProg->Attributes, name,
534 size, type, attr);
535 }
536
537 assert(attr >= 0);
538
539 /* update the instruction's src reg */
540 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
541 }
542 }
543 }
544
545 /* Handle pre-defined attributes here (gl_Vertex, gl_Normal, etc).
546 * When the user queries the active attributes we need to include both
547 * the user-defined attributes and the built-in ones.
548 */
549 for (i = VERT_ATTRIB_POS; i < VERT_ATTRIB_GENERIC0; i++) {
550 if (inputsRead & (1 << i)) {
551 _mesa_add_attribute(linkedProg->Attributes,
552 _slang_vert_attrib_name(i),
553 4, /* size in floats */
554 _slang_vert_attrib_type(i),
555 -1 /* attrib/input */);
556 }
557 }
558
559 return GL_TRUE;
560 }
561
562
563 /**
564 * Scan program instructions to update the program's NumTemporaries field.
565 * Note: this implemenation relies on the code generator allocating
566 * temps in increasing order (0, 1, 2, ... ).
567 */
568 static void
569 _slang_count_temporaries(struct gl_program *prog)
570 {
571 GLuint i, j;
572 GLint maxIndex = -1;
573
574 for (i = 0; i < prog->NumInstructions; i++) {
575 const struct prog_instruction *inst = prog->Instructions + i;
576 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
577 for (j = 0; j < numSrc; j++) {
578 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
579 if (maxIndex < inst->SrcReg[j].Index)
580 maxIndex = inst->SrcReg[j].Index;
581 }
582 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
583 if (maxIndex < (GLint) inst->DstReg.Index)
584 maxIndex = inst->DstReg.Index;
585 }
586 }
587 }
588
589 prog->NumTemporaries = (GLuint) (maxIndex + 1);
590 }
591
592
593 /**
594 * Scan program instructions to update the program's InputsRead and
595 * OutputsWritten fields.
596 */
597 static void
598 _slang_update_inputs_outputs(struct gl_program *prog)
599 {
600 GLuint i, j;
601 GLuint maxAddrReg = 0;
602
603 prog->InputsRead = 0x0;
604 prog->OutputsWritten = 0x0;
605
606 for (i = 0; i < prog->NumInstructions; i++) {
607 const struct prog_instruction *inst = prog->Instructions + i;
608 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
609 for (j = 0; j < numSrc; j++) {
610 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
611 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
612 }
613 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
614 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
615 }
616 }
617
618 if (inst->DstReg.File == PROGRAM_OUTPUT) {
619 prog->OutputsWritten |= BITFIELD64_BIT(inst->DstReg.Index);
620 if (inst->DstReg.RelAddr) {
621 /* If the output attribute is indexed with relative addressing
622 * we know that it must be a varying or texcoord such as
623 * gl_TexCoord[i] = v; In this case, mark all the texcoords
624 * or varying outputs as being written. It's not an error if
625 * a vertex shader writes varying vars that aren't used by the
626 * fragment shader. But it is an error for a fragment shader
627 * to use varyings that are not written by the vertex shader.
628 */
629 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
630 if (inst->DstReg.Index == VERT_RESULT_TEX0) {
631 /* mark all texcoord outputs as written */
632 const GLbitfield64 mask =
633 BITFIELD64_RANGE(VERT_RESULT_TEX0,
634 (VERT_RESULT_TEX0
635 + MAX_TEXTURE_COORD_UNITS - 1));
636 prog->OutputsWritten |= mask;
637 }
638 else if (inst->DstReg.Index == VERT_RESULT_VAR0) {
639 /* mark all generic varying outputs as written */
640 const GLbitfield64 mask =
641 BITFIELD64_RANGE(VERT_RESULT_VAR0,
642 (VERT_RESULT_VAR0 + MAX_VARYING - 1));
643 prog->OutputsWritten |= mask;
644 }
645 }
646 }
647 }
648 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
649 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
650 }
651 }
652 prog->NumAddressRegs = maxAddrReg;
653 }
654
655
656
657 /**
658 * Remove extra #version directives from the concatenated source string.
659 * Disable the extra ones by converting first two chars to //, a comment.
660 * This is a bit of hack to work around a preprocessor bug that only
661 * allows one #version directive per source.
662 */
663 static void
664 remove_extra_version_directives(GLchar *source)
665 {
666 GLuint verCount = 0;
667 while (1) {
668 char *ver = strstr(source, "#version");
669 if (ver) {
670 verCount++;
671 if (verCount > 1) {
672 ver[0] = '/';
673 ver[1] = '/';
674 }
675 source += 8;
676 }
677 else {
678 break;
679 }
680 }
681 }
682
683
684
685 /**
686 * Return a new shader whose source code is the concatenation of
687 * all the shader sources of the given type.
688 */
689 static struct gl_shader *
690 concat_shaders(struct gl_shader_program *shProg, GLenum shaderType)
691 {
692 struct gl_shader *newShader;
693 const struct gl_shader *firstShader = NULL;
694 GLuint *shaderLengths;
695 GLchar *source;
696 GLuint totalLen = 0, len = 0;
697 GLuint i;
698
699 shaderLengths = (GLuint *)malloc(shProg->NumShaders * sizeof(GLuint));
700 if (!shaderLengths) {
701 return NULL;
702 }
703
704 /* compute total size of new shader source code */
705 for (i = 0; i < shProg->NumShaders; i++) {
706 const struct gl_shader *shader = shProg->Shaders[i];
707 if (shader->Type == shaderType) {
708 shaderLengths[i] = strlen(shader->Source);
709 totalLen += shaderLengths[i];
710 if (!firstShader)
711 firstShader = shader;
712 }
713 }
714
715 if (totalLen == 0) {
716 free(shaderLengths);
717 return NULL;
718 }
719
720 source = (GLchar *) malloc(totalLen + 1);
721 if (!source) {
722 free(shaderLengths);
723 return NULL;
724 }
725
726 /* concatenate shaders */
727 for (i = 0; i < shProg->NumShaders; i++) {
728 const struct gl_shader *shader = shProg->Shaders[i];
729 if (shader->Type == shaderType) {
730 memcpy(source + len, shader->Source, shaderLengths[i]);
731 len += shaderLengths[i];
732 }
733 }
734 source[len] = '\0';
735 /*
736 printf("---NEW CONCATENATED SHADER---:\n%s\n------------\n", source);
737 */
738
739 free(shaderLengths);
740
741 remove_extra_version_directives(source);
742
743 newShader = CALLOC_STRUCT(gl_shader);
744 if (!newShader) {
745 free(source);
746 return NULL;
747 }
748
749 newShader->Type = shaderType;
750 newShader->Source = source;
751 newShader->Pragmas = firstShader->Pragmas;
752
753 return newShader;
754 }
755
756
757 /**
758 * Search the shader program's list of shaders to find the one that
759 * defines main().
760 * This will involve shader concatenation and recompilation if needed.
761 */
762 static struct gl_shader *
763 get_main_shader(GLcontext *ctx,
764 struct gl_shader_program *shProg, GLenum type)
765 {
766 struct gl_shader *shader = NULL;
767 GLuint i;
768
769 /*
770 * Look for a shader that defines main() and has no unresolved references.
771 */
772 for (i = 0; i < shProg->NumShaders; i++) {
773 shader = shProg->Shaders[i];
774 if (shader->Type == type &&
775 shader->Main &&
776 !shader->UnresolvedRefs) {
777 /* All set! */
778 return shader;
779 }
780 }
781
782 /*
783 * There must have been unresolved references during the original
784 * compilation. Try concatenating all the shaders of the given type
785 * and recompile that.
786 */
787 shader = concat_shaders(shProg, type);
788
789 if (shader) {
790 _slang_compile(ctx, shader);
791
792 /* Finally, check if recompiling failed */
793 if (!shader->CompileStatus ||
794 !shader->Main ||
795 shader->UnresolvedRefs) {
796 link_error(shProg, "Unresolved symbols");
797 _mesa_free_shader(ctx, shader);
798 return NULL;
799 }
800 }
801
802 return shader;
803 }
804
805
806 /**
807 * Shader linker. Currently:
808 *
809 * 1. The last attached vertex shader and fragment shader are linked.
810 * 2. Varying vars in the two shaders are combined so their locations
811 * agree between the vertex and fragment stages. They're treated as
812 * vertex program output attribs and as fragment program input attribs.
813 * 3. The vertex and fragment programs are cloned and modified to update
814 * src/dst register references so they use the new, linked varying
815 * storage locations.
816 */
817 void
818 _slang_link(GLcontext *ctx,
819 GLhandleARB programObj,
820 struct gl_shader_program *shProg)
821 {
822 const struct gl_vertex_program *vertProg = NULL;
823 const struct gl_fragment_program *fragProg = NULL;
824 GLboolean vertNotify = GL_TRUE, fragNotify = GL_TRUE;
825 GLuint numSamplers = 0;
826 GLuint i;
827
828 _mesa_clear_shader_program_data(ctx, shProg);
829
830 /* Initialize LinkStatus to "success". Will be cleared if error. */
831 shProg->LinkStatus = GL_TRUE;
832
833 /* check that all programs compiled successfully */
834 for (i = 0; i < shProg->NumShaders; i++) {
835 if (!shProg->Shaders[i]->CompileStatus) {
836 link_error(shProg, "linking with uncompiled shader\n");
837 return;
838 }
839 }
840
841 shProg->Uniforms = _mesa_new_uniform_list();
842 shProg->Varying = _mesa_new_parameter_list();
843
844 /*
845 * Find the vertex and fragment shaders which define main()
846 */
847 {
848 struct gl_shader *vertShader, *fragShader;
849 vertShader = get_main_shader(ctx, shProg, GL_VERTEX_SHADER);
850 fragShader = get_main_shader(ctx, shProg, GL_FRAGMENT_SHADER);
851 if (vertShader)
852 vertProg = vertex_program(vertShader->Program);
853 if (fragShader)
854 fragProg = fragment_program(fragShader->Program);
855 if (!shProg->LinkStatus)
856 return;
857 }
858
859 #if FEATURE_es2_glsl
860 /* must have both a vertex and fragment program for ES2 */
861 if (ctx->API == API_OPENGLES2) {
862 if (!vertProg) {
863 link_error(shProg, "missing vertex shader\n");
864 return;
865 }
866 if (!fragProg) {
867 link_error(shProg, "missing fragment shader\n");
868 return;
869 }
870 }
871 #endif
872
873 /*
874 * Make copies of the vertex/fragment programs now since we'll be
875 * changing src/dst registers after merging the uniforms and varying vars.
876 */
877 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
878 if (vertProg) {
879 struct gl_vertex_program *linked_vprog =
880 _mesa_clone_vertex_program(ctx, vertProg);
881 shProg->VertexProgram = linked_vprog; /* refcount OK */
882 /* vertex program ID not significant; just set Id for debugging purposes */
883 shProg->VertexProgram->Base.Id = shProg->Name;
884 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
885 }
886
887 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
888 if (fragProg) {
889 struct gl_fragment_program *linked_fprog =
890 _mesa_clone_fragment_program(ctx, fragProg);
891 shProg->FragmentProgram = linked_fprog; /* refcount OK */
892 /* vertex program ID not significant; just set Id for debugging purposes */
893 shProg->FragmentProgram->Base.Id = shProg->Name;
894 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
895 }
896
897 /* link varying vars */
898 if (shProg->VertexProgram) {
899 if (!link_varying_vars(ctx, shProg, &shProg->VertexProgram->Base))
900 return;
901 }
902 if (shProg->FragmentProgram) {
903 if (!link_varying_vars(ctx, shProg, &shProg->FragmentProgram->Base))
904 return;
905 }
906
907 /* link uniform vars */
908 if (shProg->VertexProgram) {
909 if (!link_uniform_vars(ctx, shProg, &shProg->VertexProgram->Base,
910 &numSamplers)) {
911 return;
912 }
913 }
914 if (shProg->FragmentProgram) {
915 if (!link_uniform_vars(ctx, shProg, &shProg->FragmentProgram->Base,
916 &numSamplers)) {
917 return;
918 }
919 }
920
921 /*_mesa_print_uniforms(shProg->Uniforms);*/
922
923 if (shProg->VertexProgram) {
924 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
925 &shProg->VertexProgram->Base)) {
926 return;
927 }
928 }
929
930 if (shProg->VertexProgram) {
931 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
932 _slang_count_temporaries(&shProg->VertexProgram->Base);
933 if (!(shProg->VertexProgram->Base.OutputsWritten
934 & BITFIELD64_BIT(VERT_RESULT_HPOS))) {
935 /* the vertex program did not compute a vertex position */
936 link_error(shProg,
937 "gl_Position was not written by vertex shader\n");
938 return;
939 }
940 }
941 if (shProg->FragmentProgram) {
942 _slang_count_temporaries(&shProg->FragmentProgram->Base);
943 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
944 }
945
946 /* Check that all the varying vars needed by the fragment shader are
947 * actually produced by the vertex shader.
948 */
949 if (shProg->FragmentProgram) {
950 const GLbitfield varyingRead
951 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
952 const GLbitfield64 varyingWritten = shProg->VertexProgram ?
953 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
954 if ((varyingRead & varyingWritten) != varyingRead) {
955 link_error(shProg,
956 "Fragment program using varying vars not written by vertex shader\n");
957 return;
958 }
959 }
960
961 /* check that gl_FragColor and gl_FragData are not both written to */
962 if (shProg->FragmentProgram) {
963 const GLbitfield64 outputsWritten =
964 shProg->FragmentProgram->Base.OutputsWritten;
965 if ((outputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) &&
966 (outputsWritten >= BITFIELD64_BIT(FRAG_RESULT_DATA0))) {
967 link_error(shProg, "Fragment program cannot write both gl_FragColor"
968 " and gl_FragData[].\n");
969 return;
970 }
971 }
972
973 update_varying_var_list(ctx, shProg);
974
975 /* checks related to transform feedback */
976 if (!link_transform_feedback(ctx, shProg)) {
977 return;
978 }
979
980 if (fragProg && shProg->FragmentProgram) {
981 /* Compute initial program's TexturesUsed info */
982 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
983
984 /* notify driver that a new fragment program has been compiled/linked */
985 vertNotify = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
986 &shProg->FragmentProgram->Base);
987 if (ctx->Shader.Flags & GLSL_DUMP) {
988 printf("Mesa pre-link fragment program:\n");
989 _mesa_print_program(&fragProg->Base);
990 _mesa_print_program_parameters(ctx, &fragProg->Base);
991
992 printf("Mesa post-link fragment program:\n");
993 _mesa_print_program(&shProg->FragmentProgram->Base);
994 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
995 }
996 }
997
998 if (vertProg && shProg->VertexProgram) {
999 /* Compute initial program's TexturesUsed info */
1000 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
1001
1002 /* notify driver that a new vertex program has been compiled/linked */
1003 fragNotify = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
1004 &shProg->VertexProgram->Base);
1005 if (ctx->Shader.Flags & GLSL_DUMP) {
1006 printf("Mesa pre-link vertex program:\n");
1007 _mesa_print_program(&vertProg->Base);
1008 _mesa_print_program_parameters(ctx, &vertProg->Base);
1009
1010 printf("Mesa post-link vertex program:\n");
1011 _mesa_print_program(&shProg->VertexProgram->Base);
1012 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
1013 }
1014 }
1015
1016 /* Debug: */
1017 if (0) {
1018 if (shProg->VertexProgram)
1019 _mesa_postprocess_program(ctx, &shProg->VertexProgram->Base);
1020 if (shProg->FragmentProgram)
1021 _mesa_postprocess_program(ctx, &shProg->FragmentProgram->Base);
1022 }
1023
1024 if (ctx->Shader.Flags & GLSL_DUMP) {
1025 printf("Varying vars:\n");
1026 _mesa_print_parameter_list(shProg->Varying);
1027 if (shProg->InfoLog) {
1028 printf("Info Log: %s\n", shProg->InfoLog);
1029 }
1030 }
1031
1032 if (!vertNotify || !fragNotify) {
1033 /* driver rejected one/both of the vertex/fragment programs */
1034 if (!shProg->InfoLog) {
1035 link_error(shProg,
1036 "Vertex and/or fragment program rejected by driver\n");
1037 }
1038 }
1039 else {
1040 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
1041 }
1042 }
1043