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