mesa: check that varying variable qualifiers agree
[mesa.git] / src / mesa / shader / slang / slang_link.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.2
4 *
5 * Copyright (C) 2008 Brian Paul All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * \file slang_link.c
27 * GLSL linker
28 * \author Brian Paul
29 */
30
31 #include "main/imports.h"
32 #include "main/context.h"
33 #include "main/hash.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_link.h"
43
44
45 /** cast wrapper */
46 static struct gl_vertex_program *
47 vertex_program(struct gl_program *prog)
48 {
49 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
50 return (struct gl_vertex_program *) prog;
51 }
52
53
54 /** cast wrapper */
55 static struct gl_fragment_program *
56 fragment_program(struct gl_program *prog)
57 {
58 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
59 return (struct gl_fragment_program *) prog;
60 }
61
62
63 /**
64 * Record a linking error.
65 */
66 static void
67 link_error(struct gl_shader_program *shProg, const char *msg)
68 {
69 if (shProg->InfoLog) {
70 _mesa_free(shProg->InfoLog);
71 }
72 shProg->InfoLog = _mesa_strdup(msg);
73 shProg->LinkStatus = GL_FALSE;
74 }
75
76
77
78 /**
79 * Check if the given bit is either set or clear in both bitfields.
80 */
81 static GLboolean
82 bits_agree(GLbitfield flags1, GLbitfield flags2, GLbitfield bit)
83 {
84 return (flags1 & bit) == (flags2 & bit);
85 }
86
87
88 /**
89 * Linking varying vars involves rearranging varying vars so that the
90 * vertex program's output varyings matches the order of the fragment
91 * program's input varyings.
92 */
93 static GLboolean
94 link_varying_vars(struct gl_shader_program *shProg, struct gl_program *prog)
95 {
96 GLuint *map, i, firstVarying, newFile;
97
98 map = (GLuint *) malloc(prog->Varying->NumParameters * sizeof(GLuint));
99 if (!map)
100 return GL_FALSE;
101
102 for (i = 0; i < prog->Varying->NumParameters; i++) {
103 /* see if this varying is in the linked varying list */
104 const struct gl_program_parameter *var = prog->Varying->Parameters + i;
105 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
106 if (j >= 0) {
107 /* varying is already in list, do some error checking */
108 const struct gl_program_parameter *v =
109 &shProg->Varying->Parameters[j];
110 if (var->Size != v->Size) {
111 link_error(shProg, "mismatched varying variable types");
112 return GL_FALSE;
113 }
114 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_CENTROID)) {
115 char msg[100];
116 snprintf(msg, sizeof(msg),
117 "centroid modifier mismatch for '%s'", var->Name);
118 link_error(shProg, msg);
119 return GL_FALSE;
120 }
121 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_INVARIANT)) {
122 char msg[100];
123 snprintf(msg, sizeof(msg),
124 "invariant modifier mismatch for '%s'", var->Name);
125 link_error(shProg, msg);
126 return GL_FALSE;
127 }
128 }
129 else {
130 /* not already in linked list */
131 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size,
132 var->Flags);
133 }
134
135 /* map varying[i] to varying[j].
136 * Note: the loop here takes care of arrays or large (sz>4) vars.
137 */
138 {
139 GLint sz = var->Size;
140 while (sz > 0) {
141 /*printf("Link varying from %d to %d\n", i, j);*/
142 map[i++] = j++;
143 sz -= 4;
144 }
145 i--; /* go back one */
146 }
147 }
148
149
150 /* Varying variables are treated like other vertex program outputs
151 * (and like other fragment program inputs). The position of the
152 * first varying differs for vertex/fragment programs...
153 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
154 */
155 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
156 firstVarying = VERT_RESULT_VAR0;
157 newFile = PROGRAM_OUTPUT;
158 }
159 else {
160 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
161 firstVarying = FRAG_ATTRIB_VAR0;
162 newFile = PROGRAM_INPUT;
163 }
164
165 /* OK, now scan the program/shader instructions looking for varying vars,
166 * replacing the old index with the new index.
167 */
168 for (i = 0; i < prog->NumInstructions; i++) {
169 struct prog_instruction *inst = prog->Instructions + i;
170 GLuint j;
171
172 if (inst->DstReg.File == PROGRAM_VARYING) {
173 inst->DstReg.File = newFile;
174 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
175 }
176
177 for (j = 0; j < 3; j++) {
178 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
179 inst->SrcReg[j].File = newFile;
180 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
181 }
182 }
183 }
184
185 free(map);
186
187 /* these will get recomputed before linking is completed */
188 prog->InputsRead = 0x0;
189 prog->OutputsWritten = 0x0;
190
191 return GL_TRUE;
192 }
193
194
195 /**
196 * Build the shProg->Uniforms list.
197 * This is basically a list/index of all uniforms found in either/both of
198 * the vertex and fragment shaders.
199 */
200 static void
201 link_uniform_vars(struct gl_shader_program *shProg,
202 struct gl_program *prog,
203 GLuint *numSamplers)
204 {
205 GLuint samplerMap[MAX_SAMPLERS];
206 GLuint i;
207
208 for (i = 0; i < prog->Parameters->NumParameters; i++) {
209 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
210
211 /*
212 * XXX FIX NEEDED HERE
213 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
214 * For example, modelview matrix, light pos, etc.
215 * Also, we need to update the state-var name-generator code to
216 * generate GLSL-style names, like "gl_LightSource[0].position".
217 * Furthermore, we'll need to fix the state-var's size/datatype info.
218 */
219
220 if ((p->Type == PROGRAM_UNIFORM && p->Used) ||
221 p->Type == PROGRAM_SAMPLER) {
222 struct gl_uniform *uniform =
223 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
224 if (uniform)
225 uniform->Initialized = p->Initialized;
226 }
227
228 if (p->Type == PROGRAM_SAMPLER) {
229 /* Allocate a new sampler index */
230 GLuint sampNum = *numSamplers;
231 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
232 assert(oldSampNum < MAX_SAMPLERS);
233 samplerMap[oldSampNum] = sampNum;
234 (*numSamplers)++;
235 }
236 }
237
238
239 /* OK, now scan the program/shader instructions looking for sampler vars,
240 * replacing the old index with the new index.
241 */
242 prog->SamplersUsed = 0x0;
243 for (i = 0; i < prog->NumInstructions; i++) {
244 struct prog_instruction *inst = prog->Instructions + i;
245 if (_mesa_is_tex_instruction(inst->Opcode)) {
246 /*
247 printf("====== remap sampler from %d to %d\n",
248 inst->Sampler, map[ inst->Sampler ]);
249 */
250 /* here, texUnit is really samplerUnit */
251 assert(inst->TexSrcUnit < MAX_SAMPLERS);
252 inst->TexSrcUnit = samplerMap[inst->TexSrcUnit];
253 prog->SamplerTargets[inst->TexSrcUnit] = inst->TexSrcTarget;
254 prog->SamplersUsed |= (1 << inst->TexSrcUnit);
255 }
256 }
257
258 }
259
260
261 /**
262 * Resolve binding of generic vertex attributes.
263 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
264 * allocate a generic vertex attribute for "foobar" and plug that value into
265 * the vertex program instructions.
266 * But if the user called glBindAttributeLocation(), those bindings will
267 * have priority.
268 */
269 static GLboolean
270 _slang_resolve_attributes(struct gl_shader_program *shProg,
271 const struct gl_program *origProg,
272 struct gl_program *linkedProg)
273 {
274 GLint attribMap[MAX_VERTEX_ATTRIBS];
275 GLuint i, j;
276 GLbitfield usedAttributes;
277
278 assert(origProg != linkedProg);
279 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
280 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
281
282 if (!shProg->Attributes)
283 shProg->Attributes = _mesa_new_parameter_list();
284
285 if (linkedProg->Attributes) {
286 _mesa_free_parameter_list(linkedProg->Attributes);
287 }
288 linkedProg->Attributes = _mesa_new_parameter_list();
289
290
291 /* Build a bitmask indicating which attribute indexes have been
292 * explicitly bound by the user with glBindAttributeLocation().
293 */
294 usedAttributes = 0x0;
295 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
296 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
297 usedAttributes |= (1 << attr);
298 }
299
300 /* initialize the generic attribute map entries to -1 */
301 for (i = 0; i < MAX_VERTEX_ATTRIBS; i++) {
302 attribMap[i] = -1;
303 }
304
305 /*
306 * Scan program for generic attribute references
307 */
308 for (i = 0; i < linkedProg->NumInstructions; i++) {
309 struct prog_instruction *inst = linkedProg->Instructions + i;
310 for (j = 0; j < 3; j++) {
311 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
312 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
313 /*
314 * OK, we've found a generic vertex attribute reference.
315 */
316 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
317
318 GLint attr = attribMap[k];
319
320 if (attr < 0) {
321 /* Need to figure out attribute mapping now.
322 */
323 const char *name = origProg->Attributes->Parameters[k].Name;
324 const GLint size = origProg->Attributes->Parameters[k].Size;
325 const GLenum type =origProg->Attributes->Parameters[k].DataType;
326 GLint index;
327
328 /* See if there's a user-defined attribute binding for
329 * this name.
330 */
331 index = _mesa_lookup_parameter_index(shProg->Attributes,
332 -1, name);
333 if (index >= 0) {
334 /* Found a user-defined binding */
335 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
336 }
337 else {
338 /* No user-defined binding, choose our own attribute number.
339 * Start at 1 since generic attribute 0 always aliases
340 * glVertex/position.
341 */
342 for (attr = 1; attr < MAX_VERTEX_ATTRIBS; attr++) {
343 if (((1 << attr) & usedAttributes) == 0)
344 break;
345 }
346 if (attr == MAX_VERTEX_ATTRIBS) {
347 link_error(shProg, "Too many vertex attributes");
348 return GL_FALSE;
349 }
350
351 /* mark this attribute as used */
352 usedAttributes |= (1 << attr);
353 }
354
355 attribMap[k] = attr;
356
357 /* Save the final name->attrib binding so it can be queried
358 * with glGetAttributeLocation().
359 */
360 _mesa_add_attribute(linkedProg->Attributes, name,
361 size, type, attr);
362 }
363
364 assert(attr >= 0);
365
366 /* update the instruction's src reg */
367 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
368 }
369 }
370 }
371
372 return GL_TRUE;
373 }
374
375
376 /**
377 * Scan program instructions to update the program's NumTemporaries field.
378 * Note: this implemenation relies on the code generator allocating
379 * temps in increasing order (0, 1, 2, ... ).
380 */
381 static void
382 _slang_count_temporaries(struct gl_program *prog)
383 {
384 GLuint i, j;
385 GLint maxIndex = -1;
386
387 for (i = 0; i < prog->NumInstructions; i++) {
388 const struct prog_instruction *inst = prog->Instructions + i;
389 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
390 for (j = 0; j < numSrc; j++) {
391 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
392 if (maxIndex < inst->SrcReg[j].Index)
393 maxIndex = inst->SrcReg[j].Index;
394 }
395 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
396 if (maxIndex < (GLint) inst->DstReg.Index)
397 maxIndex = inst->DstReg.Index;
398 }
399 }
400 }
401
402 prog->NumTemporaries = (GLuint) (maxIndex + 1);
403 }
404
405
406 /**
407 * Scan program instructions to update the program's InputsRead and
408 * OutputsWritten fields.
409 */
410 static void
411 _slang_update_inputs_outputs(struct gl_program *prog)
412 {
413 GLuint i, j;
414 GLuint maxAddrReg = 0;
415
416 prog->InputsRead = 0x0;
417 prog->OutputsWritten = 0x0;
418
419 for (i = 0; i < prog->NumInstructions; i++) {
420 const struct prog_instruction *inst = prog->Instructions + i;
421 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
422 for (j = 0; j < numSrc; j++) {
423 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
424 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
425 if (prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
426 inst->SrcReg[j].Index == FRAG_ATTRIB_FOGC) {
427 /* The fragment shader FOGC input is used for fog,
428 * front-facing and sprite/point coord.
429 */
430 struct gl_fragment_program *fp = fragment_program(prog);
431 const GLint swz = GET_SWZ(inst->SrcReg[j].Swizzle, 0);
432 if (swz == SWIZZLE_X)
433 fp->UsesFogFragCoord = GL_TRUE;
434 else if (swz == SWIZZLE_Y)
435 fp->UsesFrontFacing = GL_TRUE;
436 else if (swz == SWIZZLE_Z || swz == SWIZZLE_W)
437 fp->UsesPointCoord = GL_TRUE;
438 }
439 }
440 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
441 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
442 }
443 }
444 if (inst->DstReg.File == PROGRAM_OUTPUT) {
445 prog->OutputsWritten |= 1 << inst->DstReg.Index;
446 }
447 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
448 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
449 }
450 }
451 prog->NumAddressRegs = maxAddrReg;
452 }
453
454
455 /**
456 * Shader linker. Currently:
457 *
458 * 1. The last attached vertex shader and fragment shader are linked.
459 * 2. Varying vars in the two shaders are combined so their locations
460 * agree between the vertex and fragment stages. They're treated as
461 * vertex program output attribs and as fragment program input attribs.
462 * 3. The vertex and fragment programs are cloned and modified to update
463 * src/dst register references so they use the new, linked varying
464 * storage locations.
465 */
466 void
467 _slang_link(GLcontext *ctx,
468 GLhandleARB programObj,
469 struct gl_shader_program *shProg)
470 {
471 const struct gl_vertex_program *vertProg;
472 const struct gl_fragment_program *fragProg;
473 GLuint numSamplers = 0;
474 GLuint i;
475
476 _mesa_clear_shader_program_data(ctx, shProg);
477
478 /* check that all programs compiled successfully */
479 for (i = 0; i < shProg->NumShaders; i++) {
480 if (!shProg->Shaders[i]->CompileStatus) {
481 link_error(shProg, "linking with uncompiled shader\n");
482 return;
483 }
484 }
485
486 shProg->Uniforms = _mesa_new_uniform_list();
487 shProg->Varying = _mesa_new_parameter_list();
488
489 /**
490 * Find attached vertex, fragment shaders defining main()
491 */
492 vertProg = NULL;
493 fragProg = NULL;
494 for (i = 0; i < shProg->NumShaders; i++) {
495 struct gl_shader *shader = shProg->Shaders[i];
496 if (shader->Type == GL_VERTEX_SHADER) {
497 if (shader->Main)
498 vertProg = vertex_program(shader->Program);
499 }
500 else if (shader->Type == GL_FRAGMENT_SHADER) {
501 if (shader->Main)
502 fragProg = fragment_program(shader->Program);
503 }
504 else {
505 _mesa_problem(ctx, "unexpected shader target in slang_link()");
506 }
507 }
508
509 #if FEATURE_es2_glsl
510 /* must have both a vertex and fragment program for ES2 */
511 if (!vertProg) {
512 link_error(shProg, "missing vertex shader\n");
513 return;
514 }
515 if (!fragProg) {
516 link_error(shProg, "missing fragment shader\n");
517 return;
518 }
519 #endif
520
521 /*
522 * Make copies of the vertex/fragment programs now since we'll be
523 * changing src/dst registers after merging the uniforms and varying vars.
524 */
525 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
526 if (vertProg) {
527 struct gl_vertex_program *linked_vprog =
528 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
529 shProg->VertexProgram = linked_vprog; /* refcount OK */
530 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
531 }
532
533 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
534 if (fragProg) {
535 struct gl_fragment_program *linked_fprog =
536 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
537 shProg->FragmentProgram = linked_fprog; /* refcount OK */
538 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
539 }
540
541 /* link varying vars */
542 if (shProg->VertexProgram) {
543 if (!link_varying_vars(shProg, &shProg->VertexProgram->Base))
544 return;
545 }
546 if (shProg->FragmentProgram) {
547 if (!link_varying_vars(shProg, &shProg->FragmentProgram->Base))
548 return;
549 }
550
551 /* link uniform vars */
552 if (shProg->VertexProgram)
553 link_uniform_vars(shProg, &shProg->VertexProgram->Base, &numSamplers);
554 if (shProg->FragmentProgram)
555 link_uniform_vars(shProg, &shProg->FragmentProgram->Base, &numSamplers);
556
557 /*_mesa_print_uniforms(shProg->Uniforms);*/
558
559 if (shProg->VertexProgram) {
560 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
561 &shProg->VertexProgram->Base)) {
562 return;
563 }
564 }
565
566 if (shProg->VertexProgram) {
567 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
568 _slang_count_temporaries(&shProg->VertexProgram->Base);
569 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
570 /* the vertex program did not compute a vertex position */
571 link_error(shProg,
572 "gl_Position was not written by vertex shader\n");
573 return;
574 }
575 }
576 if (shProg->FragmentProgram) {
577 _slang_count_temporaries(&shProg->FragmentProgram->Base);
578 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
579 }
580
581 /* Check that all the varying vars needed by the fragment shader are
582 * actually produced by the vertex shader.
583 */
584 if (shProg->FragmentProgram) {
585 const GLbitfield varyingRead
586 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
587 const GLbitfield varyingWritten = shProg->VertexProgram ?
588 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
589 if ((varyingRead & varyingWritten) != varyingRead) {
590 link_error(shProg,
591 "Fragment program using varying vars not written by vertex shader\n");
592 return;
593 }
594 }
595
596
597 if (fragProg && shProg->FragmentProgram) {
598 /* Compute initial program's TexturesUsed info */
599 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
600
601 /* notify driver that a new fragment program has been compiled/linked */
602 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
603 &shProg->FragmentProgram->Base);
604 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
605 printf("Mesa original fragment program:\n");
606 _mesa_print_program(&fragProg->Base);
607 _mesa_print_program_parameters(ctx, &fragProg->Base);
608
609 printf("Mesa post-link fragment program:\n");
610 _mesa_print_program(&shProg->FragmentProgram->Base);
611 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
612 }
613 }
614
615 if (vertProg && shProg->VertexProgram) {
616 /* Compute initial program's TexturesUsed info */
617 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
618
619 /* notify driver that a new vertex program has been compiled/linked */
620 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
621 &shProg->VertexProgram->Base);
622 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
623 printf("Mesa original vertex program:\n");
624 _mesa_print_program(&vertProg->Base);
625 _mesa_print_program_parameters(ctx, &vertProg->Base);
626
627 printf("Mesa post-link vertex program:\n");
628 _mesa_print_program(&shProg->VertexProgram->Base);
629 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
630 }
631 }
632
633 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
634 printf("Varying vars:\n");
635 _mesa_print_parameter_list(shProg->Varying);
636 }
637
638 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
639 }
640