mesa: Remove support for GL_VERTEX_STATE_PROGRAMs and their execution.
[mesa.git] / src / mesa / program / program.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 6.5.3
4 *
5 * Copyright (C) 1999-2007 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 program.c
27 * Vertex and fragment program support functions.
28 * \author Brian Paul
29 */
30
31
32 #include "main/glheader.h"
33 #include "main/context.h"
34 #include "main/hash.h"
35 #include "main/mfeatures.h"
36 #include "program.h"
37 #include "prog_cache.h"
38 #include "prog_parameter.h"
39 #include "prog_instruction.h"
40
41
42 /**
43 * A pointer to this dummy program is put into the hash table when
44 * glGenPrograms is called.
45 */
46 struct gl_program _mesa_DummyProgram;
47
48
49 /**
50 * Init context's vertex/fragment program state
51 */
52 void
53 _mesa_init_program(struct gl_context *ctx)
54 {
55 /*
56 * If this assertion fails, we need to increase the field
57 * size for register indexes (see INST_INDEX_BITS).
58 */
59 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents / 4
60 <= (1 << INST_INDEX_BITS));
61 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents / 4
62 <= (1 << INST_INDEX_BITS));
63
64 ASSERT(ctx->Const.VertexProgram.MaxTemps <= (1 << INST_INDEX_BITS));
65 ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
66 ASSERT(ctx->Const.FragmentProgram.MaxTemps <= (1 << INST_INDEX_BITS));
67 ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
68
69 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
70 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
71
72 ASSERT(ctx->Const.VertexProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
73 ASSERT(ctx->Const.FragmentProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
74
75 /* If this fails, increase prog_instruction::TexSrcUnit size */
76 ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
77
78 /* If this fails, increase prog_instruction::TexSrcTarget size */
79 ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
80
81 ctx->Program.ErrorPos = -1;
82 ctx->Program.ErrorString = _mesa_strdup("");
83
84 ctx->VertexProgram.Enabled = GL_FALSE;
85 ctx->VertexProgram.PointSizeEnabled =
86 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
87 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
88 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
89 ctx->Shared->DefaultVertexProgram);
90 assert(ctx->VertexProgram.Current);
91 ctx->VertexProgram.Cache = _mesa_new_program_cache();
92
93 ctx->FragmentProgram.Enabled = GL_FALSE;
94 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
95 ctx->Shared->DefaultFragmentProgram);
96 assert(ctx->FragmentProgram.Current);
97 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
98
99 ctx->GeometryProgram.Enabled = GL_FALSE;
100 /* right now by default we don't have a geometry program */
101 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
102 NULL);
103 ctx->GeometryProgram.Cache = _mesa_new_program_cache();
104
105 /* XXX probably move this stuff */
106 ctx->ATIFragmentShader.Enabled = GL_FALSE;
107 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
108 assert(ctx->ATIFragmentShader.Current);
109 ctx->ATIFragmentShader.Current->RefCount++;
110 }
111
112
113 /**
114 * Free a context's vertex/fragment program state
115 */
116 void
117 _mesa_free_program_data(struct gl_context *ctx)
118 {
119 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
120 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
121 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
122 _mesa_delete_shader_cache(ctx, ctx->FragmentProgram.Cache);
123 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current, NULL);
124 _mesa_delete_program_cache(ctx, ctx->GeometryProgram.Cache);
125
126 /* XXX probably move this stuff */
127 if (ctx->ATIFragmentShader.Current) {
128 ctx->ATIFragmentShader.Current->RefCount--;
129 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
130 free(ctx->ATIFragmentShader.Current);
131 }
132 }
133
134 free((void *) ctx->Program.ErrorString);
135 }
136
137
138 /**
139 * Update the default program objects in the given context to reference those
140 * specified in the shared state and release those referencing the old
141 * shared state.
142 */
143 void
144 _mesa_update_default_objects_program(struct gl_context *ctx)
145 {
146 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
147 ctx->Shared->DefaultVertexProgram);
148 assert(ctx->VertexProgram.Current);
149
150 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
151 ctx->Shared->DefaultFragmentProgram);
152 assert(ctx->FragmentProgram.Current);
153
154 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
155 ctx->Shared->DefaultGeometryProgram);
156
157 /* XXX probably move this stuff */
158 if (ctx->ATIFragmentShader.Current) {
159 ctx->ATIFragmentShader.Current->RefCount--;
160 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
161 free(ctx->ATIFragmentShader.Current);
162 }
163 }
164 ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
165 assert(ctx->ATIFragmentShader.Current);
166 ctx->ATIFragmentShader.Current->RefCount++;
167 }
168
169
170 /**
171 * Set the vertex/fragment program error state (position and error string).
172 * This is generally called from within the parsers.
173 */
174 void
175 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
176 {
177 ctx->Program.ErrorPos = pos;
178 free((void *) ctx->Program.ErrorString);
179 if (!string)
180 string = "";
181 ctx->Program.ErrorString = _mesa_strdup(string);
182 }
183
184
185 /**
186 * Find the line number and column for 'pos' within 'string'.
187 * Return a copy of the line which contains 'pos'. Free the line with
188 * free().
189 * \param string the program string
190 * \param pos the position within the string
191 * \param line returns the line number corresponding to 'pos'.
192 * \param col returns the column number corresponding to 'pos'.
193 * \return copy of the line containing 'pos'.
194 */
195 const GLubyte *
196 _mesa_find_line_column(const GLubyte *string, const GLubyte *pos,
197 GLint *line, GLint *col)
198 {
199 const GLubyte *lineStart = string;
200 const GLubyte *p = string;
201 GLubyte *s;
202 int len;
203
204 *line = 1;
205
206 while (p != pos) {
207 if (*p == (GLubyte) '\n') {
208 (*line)++;
209 lineStart = p + 1;
210 }
211 p++;
212 }
213
214 *col = (pos - lineStart) + 1;
215
216 /* return copy of this line */
217 while (*p != 0 && *p != '\n')
218 p++;
219 len = p - lineStart;
220 s = malloc(len + 1);
221 memcpy(s, lineStart, len);
222 s[len] = 0;
223
224 return s;
225 }
226
227
228 /**
229 * Initialize a new vertex/fragment program object.
230 */
231 static struct gl_program *
232 _mesa_init_program_struct( struct gl_context *ctx, struct gl_program *prog,
233 GLenum target, GLuint id)
234 {
235 (void) ctx;
236 if (prog) {
237 GLuint i;
238 memset(prog, 0, sizeof(*prog));
239 prog->Id = id;
240 prog->Target = target;
241 prog->Resident = GL_TRUE;
242 prog->RefCount = 1;
243 prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
244
245 /* default mapping from samplers to texture units */
246 for (i = 0; i < MAX_SAMPLERS; i++)
247 prog->SamplerUnits[i] = i;
248 }
249
250 return prog;
251 }
252
253
254 /**
255 * Initialize a new fragment program object.
256 */
257 struct gl_program *
258 _mesa_init_fragment_program( struct gl_context *ctx, struct gl_fragment_program *prog,
259 GLenum target, GLuint id)
260 {
261 if (prog)
262 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
263 else
264 return NULL;
265 }
266
267
268 /**
269 * Initialize a new vertex program object.
270 */
271 struct gl_program *
272 _mesa_init_vertex_program( struct gl_context *ctx, struct gl_vertex_program *prog,
273 GLenum target, GLuint id)
274 {
275 if (prog)
276 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
277 else
278 return NULL;
279 }
280
281
282 /**
283 * Initialize a new geometry program object.
284 */
285 struct gl_program *
286 _mesa_init_geometry_program( struct gl_context *ctx, struct gl_geometry_program *prog,
287 GLenum target, GLuint id)
288 {
289 if (prog)
290 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
291 else
292 return NULL;
293 }
294
295
296 /**
297 * Allocate and initialize a new fragment/vertex program object but
298 * don't put it into the program hash table. Called via
299 * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a
300 * device driver function to implement OO deriviation with additional
301 * types not understood by this function.
302 *
303 * \param ctx context
304 * \param id program id/number
305 * \param target program target/type
306 * \return pointer to new program object
307 */
308 struct gl_program *
309 _mesa_new_program(struct gl_context *ctx, GLenum target, GLuint id)
310 {
311 struct gl_program *prog;
312 switch (target) {
313 case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */
314 prog = _mesa_init_vertex_program(ctx, CALLOC_STRUCT(gl_vertex_program),
315 target, id );
316 break;
317 case GL_FRAGMENT_PROGRAM_NV:
318 case GL_FRAGMENT_PROGRAM_ARB:
319 prog =_mesa_init_fragment_program(ctx,
320 CALLOC_STRUCT(gl_fragment_program),
321 target, id );
322 break;
323 case MESA_GEOMETRY_PROGRAM:
324 prog = _mesa_init_geometry_program(ctx,
325 CALLOC_STRUCT(gl_geometry_program),
326 target, id);
327 break;
328 default:
329 _mesa_problem(ctx, "bad target in _mesa_new_program");
330 prog = NULL;
331 }
332 return prog;
333 }
334
335
336 /**
337 * Delete a program and remove it from the hash table, ignoring the
338 * reference count.
339 * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation)
340 * by a device driver function.
341 */
342 void
343 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
344 {
345 (void) ctx;
346 ASSERT(prog);
347 ASSERT(prog->RefCount==0);
348
349 if (prog == &_mesa_DummyProgram)
350 return;
351
352 free(prog->String);
353
354 if (prog->Instructions) {
355 _mesa_free_instructions(prog->Instructions, prog->NumInstructions);
356 }
357 if (prog->Parameters) {
358 _mesa_free_parameter_list(prog->Parameters);
359 }
360
361 free(prog);
362 }
363
364
365 /**
366 * Return the gl_program object for a given ID.
367 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
368 * casts elsewhere.
369 */
370 struct gl_program *
371 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
372 {
373 if (id)
374 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
375 else
376 return NULL;
377 }
378
379
380 /**
381 * Reference counting for vertex/fragment programs
382 * This is normally only called from the _mesa_reference_program() macro
383 * when there's a real pointer change.
384 */
385 void
386 _mesa_reference_program_(struct gl_context *ctx,
387 struct gl_program **ptr,
388 struct gl_program *prog)
389 {
390 #ifndef NDEBUG
391 assert(ptr);
392 if (*ptr && prog) {
393 /* sanity check */
394 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
395 ASSERT(prog->Target == GL_VERTEX_PROGRAM_ARB);
396 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
397 ASSERT(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
398 prog->Target == GL_FRAGMENT_PROGRAM_NV);
399 else if ((*ptr)->Target == MESA_GEOMETRY_PROGRAM)
400 ASSERT(prog->Target == MESA_GEOMETRY_PROGRAM);
401 }
402 #endif
403
404 if (*ptr) {
405 GLboolean deleteFlag;
406
407 /*_glthread_LOCK_MUTEX((*ptr)->Mutex);*/
408 #if 0
409 printf("Program %p ID=%u Target=%s Refcount-- to %d\n",
410 *ptr, (*ptr)->Id,
411 ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
412 ((*ptr)->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
413 (*ptr)->RefCount - 1);
414 #endif
415 ASSERT((*ptr)->RefCount > 0);
416 (*ptr)->RefCount--;
417
418 deleteFlag = ((*ptr)->RefCount == 0);
419 /*_glthread_UNLOCK_MUTEX((*ptr)->Mutex);*/
420
421 if (deleteFlag) {
422 ASSERT(ctx);
423 ctx->Driver.DeleteProgram(ctx, *ptr);
424 }
425
426 *ptr = NULL;
427 }
428
429 assert(!*ptr);
430 if (prog) {
431 /*_glthread_LOCK_MUTEX(prog->Mutex);*/
432 prog->RefCount++;
433 #if 0
434 printf("Program %p ID=%u Target=%s Refcount++ to %d\n",
435 prog, prog->Id,
436 (prog->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
437 (prog->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
438 prog->RefCount);
439 #endif
440 /*_glthread_UNLOCK_MUTEX(prog->Mutex);*/
441 }
442
443 *ptr = prog;
444 }
445
446
447 /**
448 * Return a copy of a program.
449 * XXX Problem here if the program object is actually OO-derivation
450 * made by a device driver.
451 */
452 struct gl_program *
453 _mesa_clone_program(struct gl_context *ctx, const struct gl_program *prog)
454 {
455 struct gl_program *clone;
456
457 clone = ctx->Driver.NewProgram(ctx, prog->Target, prog->Id);
458 if (!clone)
459 return NULL;
460
461 assert(clone->Target == prog->Target);
462 assert(clone->RefCount == 1);
463
464 clone->String = (GLubyte *) _mesa_strdup((char *) prog->String);
465 clone->Format = prog->Format;
466 clone->Instructions = _mesa_alloc_instructions(prog->NumInstructions);
467 if (!clone->Instructions) {
468 _mesa_reference_program(ctx, &clone, NULL);
469 return NULL;
470 }
471 _mesa_copy_instructions(clone->Instructions, prog->Instructions,
472 prog->NumInstructions);
473 clone->InputsRead = prog->InputsRead;
474 clone->OutputsWritten = prog->OutputsWritten;
475 clone->SamplersUsed = prog->SamplersUsed;
476 clone->ShadowSamplers = prog->ShadowSamplers;
477 memcpy(clone->TexturesUsed, prog->TexturesUsed, sizeof(prog->TexturesUsed));
478
479 if (prog->Parameters)
480 clone->Parameters = _mesa_clone_parameter_list(prog->Parameters);
481 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
482 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
483 clone->IndirectRegisterFiles = prog->IndirectRegisterFiles;
484 clone->NumInstructions = prog->NumInstructions;
485 clone->NumTemporaries = prog->NumTemporaries;
486 clone->NumParameters = prog->NumParameters;
487 clone->NumAttributes = prog->NumAttributes;
488 clone->NumAddressRegs = prog->NumAddressRegs;
489 clone->NumNativeInstructions = prog->NumNativeInstructions;
490 clone->NumNativeTemporaries = prog->NumNativeTemporaries;
491 clone->NumNativeParameters = prog->NumNativeParameters;
492 clone->NumNativeAttributes = prog->NumNativeAttributes;
493 clone->NumNativeAddressRegs = prog->NumNativeAddressRegs;
494 clone->NumAluInstructions = prog->NumAluInstructions;
495 clone->NumTexInstructions = prog->NumTexInstructions;
496 clone->NumTexIndirections = prog->NumTexIndirections;
497 clone->NumNativeAluInstructions = prog->NumNativeAluInstructions;
498 clone->NumNativeTexInstructions = prog->NumNativeTexInstructions;
499 clone->NumNativeTexIndirections = prog->NumNativeTexIndirections;
500
501 switch (prog->Target) {
502 case GL_VERTEX_PROGRAM_ARB:
503 {
504 const struct gl_vertex_program *vp = gl_vertex_program_const(prog);
505 struct gl_vertex_program *vpc = gl_vertex_program(clone);
506 vpc->IsPositionInvariant = vp->IsPositionInvariant;
507 vpc->IsNVProgram = vp->IsNVProgram;
508 }
509 break;
510 case GL_FRAGMENT_PROGRAM_ARB:
511 {
512 const struct gl_fragment_program *fp = gl_fragment_program_const(prog);
513 struct gl_fragment_program *fpc = gl_fragment_program(clone);
514 fpc->UsesKill = fp->UsesKill;
515 fpc->UsesDFdy = fp->UsesDFdy;
516 fpc->OriginUpperLeft = fp->OriginUpperLeft;
517 fpc->PixelCenterInteger = fp->PixelCenterInteger;
518 }
519 break;
520 case MESA_GEOMETRY_PROGRAM:
521 {
522 const struct gl_geometry_program *gp = gl_geometry_program_const(prog);
523 struct gl_geometry_program *gpc = gl_geometry_program(clone);
524 gpc->VerticesOut = gp->VerticesOut;
525 gpc->InputType = gp->InputType;
526 gpc->OutputType = gp->OutputType;
527 }
528 break;
529 default:
530 _mesa_problem(NULL, "Unexpected target in _mesa_clone_program");
531 }
532
533 return clone;
534 }
535
536
537 /**
538 * Insert 'count' NOP instructions at 'start' in the given program.
539 * Adjust branch targets accordingly.
540 */
541 GLboolean
542 _mesa_insert_instructions(struct gl_program *prog, GLuint start, GLuint count)
543 {
544 const GLuint origLen = prog->NumInstructions;
545 const GLuint newLen = origLen + count;
546 struct prog_instruction *newInst;
547 GLuint i;
548
549 /* adjust branches */
550 for (i = 0; i < prog->NumInstructions; i++) {
551 struct prog_instruction *inst = prog->Instructions + i;
552 if (inst->BranchTarget > 0) {
553 if ((GLuint)inst->BranchTarget >= start) {
554 inst->BranchTarget += count;
555 }
556 }
557 }
558
559 /* Alloc storage for new instructions */
560 newInst = _mesa_alloc_instructions(newLen);
561 if (!newInst) {
562 return GL_FALSE;
563 }
564
565 /* Copy 'start' instructions into new instruction buffer */
566 _mesa_copy_instructions(newInst, prog->Instructions, start);
567
568 /* init the new instructions */
569 _mesa_init_instructions(newInst + start, count);
570
571 /* Copy the remaining/tail instructions to new inst buffer */
572 _mesa_copy_instructions(newInst + start + count,
573 prog->Instructions + start,
574 origLen - start);
575
576 /* free old instructions */
577 _mesa_free_instructions(prog->Instructions, origLen);
578
579 /* install new instructions */
580 prog->Instructions = newInst;
581 prog->NumInstructions = newLen;
582
583 return GL_TRUE;
584 }
585
586 /**
587 * Delete 'count' instructions at 'start' in the given program.
588 * Adjust branch targets accordingly.
589 */
590 GLboolean
591 _mesa_delete_instructions(struct gl_program *prog, GLuint start, GLuint count)
592 {
593 const GLuint origLen = prog->NumInstructions;
594 const GLuint newLen = origLen - count;
595 struct prog_instruction *newInst;
596 GLuint i;
597
598 /* adjust branches */
599 for (i = 0; i < prog->NumInstructions; i++) {
600 struct prog_instruction *inst = prog->Instructions + i;
601 if (inst->BranchTarget > 0) {
602 if (inst->BranchTarget > (GLint) start) {
603 inst->BranchTarget -= count;
604 }
605 }
606 }
607
608 /* Alloc storage for new instructions */
609 newInst = _mesa_alloc_instructions(newLen);
610 if (!newInst) {
611 return GL_FALSE;
612 }
613
614 /* Copy 'start' instructions into new instruction buffer */
615 _mesa_copy_instructions(newInst, prog->Instructions, start);
616
617 /* Copy the remaining/tail instructions to new inst buffer */
618 _mesa_copy_instructions(newInst + start,
619 prog->Instructions + start + count,
620 newLen - start);
621
622 /* free old instructions */
623 _mesa_free_instructions(prog->Instructions, origLen);
624
625 /* install new instructions */
626 prog->Instructions = newInst;
627 prog->NumInstructions = newLen;
628
629 return GL_TRUE;
630 }
631
632
633 /**
634 * Search instructions for registers that match (oldFile, oldIndex),
635 * replacing them with (newFile, newIndex).
636 */
637 static void
638 replace_registers(struct prog_instruction *inst, GLuint numInst,
639 GLuint oldFile, GLuint oldIndex,
640 GLuint newFile, GLuint newIndex)
641 {
642 GLuint i, j;
643 for (i = 0; i < numInst; i++) {
644 /* src regs */
645 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
646 if (inst[i].SrcReg[j].File == oldFile &&
647 inst[i].SrcReg[j].Index == oldIndex) {
648 inst[i].SrcReg[j].File = newFile;
649 inst[i].SrcReg[j].Index = newIndex;
650 }
651 }
652 /* dst reg */
653 if (inst[i].DstReg.File == oldFile && inst[i].DstReg.Index == oldIndex) {
654 inst[i].DstReg.File = newFile;
655 inst[i].DstReg.Index = newIndex;
656 }
657 }
658 }
659
660
661 /**
662 * Search instructions for references to program parameters. When found,
663 * increment the parameter index by 'offset'.
664 * Used when combining programs.
665 */
666 static void
667 adjust_param_indexes(struct prog_instruction *inst, GLuint numInst,
668 GLuint offset)
669 {
670 GLuint i, j;
671 for (i = 0; i < numInst; i++) {
672 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
673 GLuint f = inst[i].SrcReg[j].File;
674 if (f == PROGRAM_CONSTANT ||
675 f == PROGRAM_UNIFORM ||
676 f == PROGRAM_STATE_VAR) {
677 inst[i].SrcReg[j].Index += offset;
678 }
679 }
680 }
681 }
682
683
684 /**
685 * Combine two programs into one. Fix instructions so the outputs of
686 * the first program go to the inputs of the second program.
687 */
688 struct gl_program *
689 _mesa_combine_programs(struct gl_context *ctx,
690 const struct gl_program *progA,
691 const struct gl_program *progB)
692 {
693 struct prog_instruction *newInst;
694 struct gl_program *newProg;
695 const GLuint lenA = progA->NumInstructions - 1; /* omit END instr */
696 const GLuint lenB = progB->NumInstructions;
697 const GLuint numParamsA = _mesa_num_parameters(progA->Parameters);
698 const GLuint newLength = lenA + lenB;
699 GLboolean usedTemps[MAX_PROGRAM_TEMPS];
700 GLuint firstTemp = 0;
701 GLbitfield inputsB;
702 GLuint i;
703
704 ASSERT(progA->Target == progB->Target);
705
706 newInst = _mesa_alloc_instructions(newLength);
707 if (!newInst)
708 return GL_FALSE;
709
710 _mesa_copy_instructions(newInst, progA->Instructions, lenA);
711 _mesa_copy_instructions(newInst + lenA, progB->Instructions, lenB);
712
713 /* adjust branch / instruction addresses for B's instructions */
714 for (i = 0; i < lenB; i++) {
715 newInst[lenA + i].BranchTarget += lenA;
716 }
717
718 newProg = ctx->Driver.NewProgram(ctx, progA->Target, 0);
719 newProg->Instructions = newInst;
720 newProg->NumInstructions = newLength;
721
722 /* find used temp regs (we may need new temps below) */
723 _mesa_find_used_registers(newProg, PROGRAM_TEMPORARY,
724 usedTemps, MAX_PROGRAM_TEMPS);
725
726 if (newProg->Target == GL_FRAGMENT_PROGRAM_ARB) {
727 const struct gl_fragment_program *fprogA, *fprogB;
728 struct gl_fragment_program *newFprog;
729 GLbitfield progB_inputsRead = progB->InputsRead;
730 GLint progB_colorFile, progB_colorIndex;
731
732 fprogA = gl_fragment_program_const(progA);
733 fprogB = gl_fragment_program_const(progB);
734 newFprog = gl_fragment_program(newProg);
735
736 newFprog->UsesKill = fprogA->UsesKill || fprogB->UsesKill;
737 newFprog->UsesDFdy = fprogA->UsesDFdy || fprogB->UsesDFdy;
738
739 /* We'll do a search and replace for instances
740 * of progB_colorFile/progB_colorIndex below...
741 */
742 progB_colorFile = PROGRAM_INPUT;
743 progB_colorIndex = FRAG_ATTRIB_COL0;
744
745 /*
746 * The fragment program may get color from a state var rather than
747 * a fragment input (vertex output) if it's constant.
748 * See the texenvprogram.c code.
749 * So, search the program's parameter list now to see if the program
750 * gets color from a state var instead of a conventional fragment
751 * input register.
752 */
753 for (i = 0; i < progB->Parameters->NumParameters; i++) {
754 struct gl_program_parameter *p = &progB->Parameters->Parameters[i];
755 if (p->Type == PROGRAM_STATE_VAR &&
756 p->StateIndexes[0] == STATE_INTERNAL &&
757 p->StateIndexes[1] == STATE_CURRENT_ATTRIB &&
758 (int) p->StateIndexes[2] == (int) VERT_ATTRIB_COLOR0) {
759 progB_inputsRead |= FRAG_BIT_COL0;
760 progB_colorFile = PROGRAM_STATE_VAR;
761 progB_colorIndex = i;
762 break;
763 }
764 }
765
766 /* Connect color outputs of fprogA to color inputs of fprogB, via a
767 * new temporary register.
768 */
769 if ((progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) &&
770 (progB_inputsRead & FRAG_BIT_COL0)) {
771 GLint tempReg = _mesa_find_free_register(usedTemps, MAX_PROGRAM_TEMPS,
772 firstTemp);
773 if (tempReg < 0) {
774 _mesa_problem(ctx, "No free temp regs found in "
775 "_mesa_combine_programs(), using 31");
776 tempReg = 31;
777 }
778 firstTemp = tempReg + 1;
779
780 /* replace writes to result.color[0] with tempReg */
781 replace_registers(newInst, lenA,
782 PROGRAM_OUTPUT, FRAG_RESULT_COLOR,
783 PROGRAM_TEMPORARY, tempReg);
784 /* replace reads from the input color with tempReg */
785 replace_registers(newInst + lenA, lenB,
786 progB_colorFile, progB_colorIndex, /* search for */
787 PROGRAM_TEMPORARY, tempReg /* replace with */ );
788 }
789
790 /* compute combined program's InputsRead */
791 inputsB = progB_inputsRead;
792 if (progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) {
793 inputsB &= ~(1 << FRAG_ATTRIB_COL0);
794 }
795 newProg->InputsRead = progA->InputsRead | inputsB;
796 newProg->OutputsWritten = progB->OutputsWritten;
797 newProg->SamplersUsed = progA->SamplersUsed | progB->SamplersUsed;
798 }
799 else {
800 /* vertex program */
801 assert(0); /* XXX todo */
802 }
803
804 /*
805 * Merge parameters (uniforms, constants, etc)
806 */
807 newProg->Parameters = _mesa_combine_parameter_lists(progA->Parameters,
808 progB->Parameters);
809
810 adjust_param_indexes(newInst + lenA, lenB, numParamsA);
811
812
813 return newProg;
814 }
815
816
817 /**
818 * Populate the 'used' array with flags indicating which registers (TEMPs,
819 * INPUTs, OUTPUTs, etc, are used by the given program.
820 * \param file type of register to scan for
821 * \param used returns true/false flags for in use / free
822 * \param usedSize size of the 'used' array
823 */
824 void
825 _mesa_find_used_registers(const struct gl_program *prog,
826 gl_register_file file,
827 GLboolean used[], GLuint usedSize)
828 {
829 GLuint i, j;
830
831 memset(used, 0, usedSize);
832
833 for (i = 0; i < prog->NumInstructions; i++) {
834 const struct prog_instruction *inst = prog->Instructions + i;
835 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
836
837 if (inst->DstReg.File == file) {
838 ASSERT(inst->DstReg.Index < usedSize);
839 if(inst->DstReg.Index < usedSize)
840 used[inst->DstReg.Index] = GL_TRUE;
841 }
842
843 for (j = 0; j < n; j++) {
844 if (inst->SrcReg[j].File == file) {
845 ASSERT(inst->SrcReg[j].Index < usedSize);
846 if(inst->SrcReg[j].Index < usedSize)
847 used[inst->SrcReg[j].Index] = GL_TRUE;
848 }
849 }
850 }
851 }
852
853
854 /**
855 * Scan the given 'used' register flag array for the first entry
856 * that's >= firstReg.
857 * \param used vector of flags indicating registers in use (as returned
858 * by _mesa_find_used_registers())
859 * \param usedSize size of the 'used' array
860 * \param firstReg first register to start searching at
861 * \return index of unused register, or -1 if none.
862 */
863 GLint
864 _mesa_find_free_register(const GLboolean used[],
865 GLuint usedSize, GLuint firstReg)
866 {
867 GLuint i;
868
869 assert(firstReg < usedSize);
870
871 for (i = firstReg; i < usedSize; i++)
872 if (!used[i])
873 return i;
874
875 return -1;
876 }
877
878
879
880 /**
881 * Check if the given register index is valid (doesn't exceed implementation-
882 * dependent limits).
883 * \return GL_TRUE if OK, GL_FALSE if bad index
884 */
885 GLboolean
886 _mesa_valid_register_index(const struct gl_context *ctx,
887 gl_shader_type shaderType,
888 gl_register_file file, GLint index)
889 {
890 const struct gl_program_constants *c;
891
892 switch (shaderType) {
893 case MESA_SHADER_VERTEX:
894 c = &ctx->Const.VertexProgram;
895 break;
896 case MESA_SHADER_FRAGMENT:
897 c = &ctx->Const.FragmentProgram;
898 break;
899 case MESA_SHADER_GEOMETRY:
900 c = &ctx->Const.GeometryProgram;
901 break;
902 default:
903 _mesa_problem(ctx,
904 "unexpected shader type in _mesa_valid_register_index()");
905 return GL_FALSE;
906 }
907
908 switch (file) {
909 case PROGRAM_UNDEFINED:
910 return GL_TRUE; /* XXX or maybe false? */
911
912 case PROGRAM_TEMPORARY:
913 return index >= 0 && index < c->MaxTemps;
914
915 case PROGRAM_ENV_PARAM:
916 return index >= 0 && index < c->MaxEnvParams;
917
918 case PROGRAM_LOCAL_PARAM:
919 return index >= 0 && index < c->MaxLocalParams;
920
921 case PROGRAM_NAMED_PARAM:
922 return index >= 0 && index < c->MaxParameters;
923
924 case PROGRAM_UNIFORM:
925 case PROGRAM_STATE_VAR:
926 /* aka constant buffer */
927 return index >= 0 && index < c->MaxUniformComponents / 4;
928
929 case PROGRAM_CONSTANT:
930 /* constant buffer w/ possible relative negative addressing */
931 return (index > (int) c->MaxUniformComponents / -4 &&
932 index < c->MaxUniformComponents / 4);
933
934 case PROGRAM_INPUT:
935 if (index < 0)
936 return GL_FALSE;
937
938 switch (shaderType) {
939 case MESA_SHADER_VERTEX:
940 return index < VERT_ATTRIB_GENERIC0 + c->MaxAttribs;
941 case MESA_SHADER_FRAGMENT:
942 return index < FRAG_ATTRIB_VAR0 + ctx->Const.MaxVarying;
943 case MESA_SHADER_GEOMETRY:
944 return index < GEOM_ATTRIB_VAR0 + ctx->Const.MaxVarying;
945 default:
946 return GL_FALSE;
947 }
948
949 case PROGRAM_OUTPUT:
950 if (index < 0)
951 return GL_FALSE;
952
953 switch (shaderType) {
954 case MESA_SHADER_VERTEX:
955 return index < VERT_RESULT_VAR0 + ctx->Const.MaxVarying;
956 case MESA_SHADER_FRAGMENT:
957 return index < FRAG_RESULT_DATA0 + ctx->Const.MaxDrawBuffers;
958 case MESA_SHADER_GEOMETRY:
959 return index < GEOM_RESULT_VAR0 + ctx->Const.MaxVarying;
960 default:
961 return GL_FALSE;
962 }
963
964 case PROGRAM_ADDRESS:
965 return index >= 0 && index < c->MaxAddressRegs;
966
967 default:
968 _mesa_problem(ctx,
969 "unexpected register file in _mesa_valid_register_index()");
970 return GL_FALSE;
971 }
972 }
973
974
975
976 /**
977 * "Post-process" a GPU program. This is intended to be used for debugging.
978 * Example actions include no-op'ing instructions or changing instruction
979 * behaviour.
980 */
981 void
982 _mesa_postprocess_program(struct gl_context *ctx, struct gl_program *prog)
983 {
984 static const GLfloat white[4] = { 0.5, 0.5, 0.5, 0.5 };
985 GLuint i;
986 GLuint whiteSwizzle;
987 GLint whiteIndex = _mesa_add_unnamed_constant(prog->Parameters,
988 (gl_constant_value *) white,
989 4, &whiteSwizzle);
990
991 (void) whiteIndex;
992
993 for (i = 0; i < prog->NumInstructions; i++) {
994 struct prog_instruction *inst = prog->Instructions + i;
995 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
996
997 (void) n;
998
999 if (_mesa_is_tex_instruction(inst->Opcode)) {
1000 #if 0
1001 /* replace TEX/TXP/TXB with MOV */
1002 inst->Opcode = OPCODE_MOV;
1003 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1004 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1005 inst->SrcReg[0].Negate = NEGATE_NONE;
1006 #endif
1007
1008 #if 0
1009 /* disable shadow texture mode */
1010 inst->TexShadow = 0;
1011 #endif
1012 }
1013
1014 if (inst->Opcode == OPCODE_TXP) {
1015 #if 0
1016 inst->Opcode = OPCODE_MOV;
1017 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1018 inst->SrcReg[0].File = PROGRAM_CONSTANT;
1019 inst->SrcReg[0].Index = whiteIndex;
1020 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1021 inst->SrcReg[0].Negate = NEGATE_NONE;
1022 #endif
1023 #if 0
1024 inst->TexShadow = 0;
1025 #endif
1026 #if 0
1027 inst->Opcode = OPCODE_TEX;
1028 inst->TexShadow = 0;
1029 #endif
1030 }
1031
1032 }
1033 }