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