mesa: Include mfeatures.h in program.c.
[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 /* If this fails, increase prog_instruction::TexSrcUnit size */
75 ASSERT(MAX_TEXTURE_UNITS < (1 << 5));
76
77 /* If this fails, increase prog_instruction::TexSrcTarget size */
78 ASSERT(NUM_TEXTURE_TARGETS < (1 << 3));
79
80 ctx->Program.ErrorPos = -1;
81 ctx->Program.ErrorString = _mesa_strdup("");
82
83 #if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program
84 ctx->VertexProgram.Enabled = GL_FALSE;
85 #if FEATURE_es2_glsl
86 ctx->VertexProgram.PointSizeEnabled =
87 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
88 #else
89 ctx->VertexProgram.PointSizeEnabled = GL_FALSE;
90 #endif
91 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
92 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
93 ctx->Shared->DefaultVertexProgram);
94 assert(ctx->VertexProgram.Current);
95 for (i = 0; i < MAX_NV_VERTEX_PROGRAM_PARAMS / 4; i++) {
96 ctx->VertexProgram.TrackMatrix[i] = GL_NONE;
97 ctx->VertexProgram.TrackMatrixTransform[i] = GL_IDENTITY_NV;
98 }
99 ctx->VertexProgram.Cache = _mesa_new_program_cache();
100 #endif
101
102 #if FEATURE_NV_fragment_program || FEATURE_ARB_fragment_program
103 ctx->FragmentProgram.Enabled = GL_FALSE;
104 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
105 ctx->Shared->DefaultFragmentProgram);
106 assert(ctx->FragmentProgram.Current);
107 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
108 #endif
109
110 #if FEATURE_ARB_geometry_shader4
111 ctx->GeometryProgram.Enabled = GL_FALSE;
112 /* right now by default we don't have a geometry program */
113 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
114 NULL);
115 ctx->GeometryProgram.Cache = _mesa_new_program_cache();
116 #endif
117
118 /* XXX probably move this stuff */
119 #if FEATURE_ATI_fragment_shader
120 ctx->ATIFragmentShader.Enabled = GL_FALSE;
121 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
122 assert(ctx->ATIFragmentShader.Current);
123 ctx->ATIFragmentShader.Current->RefCount++;
124 #endif
125 }
126
127
128 /**
129 * Free a context's vertex/fragment program state
130 */
131 void
132 _mesa_free_program_data(struct gl_context *ctx)
133 {
134 #if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program
135 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
136 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
137 #endif
138 #if FEATURE_NV_fragment_program || FEATURE_ARB_fragment_program
139 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
140 _mesa_delete_program_cache(ctx, ctx->FragmentProgram.Cache);
141 #endif
142 #if FEATURE_ARB_geometry_shader4
143 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current, NULL);
144 _mesa_delete_program_cache(ctx, ctx->GeometryProgram.Cache);
145 #endif
146 /* XXX probably move this stuff */
147 #if FEATURE_ATI_fragment_shader
148 if (ctx->ATIFragmentShader.Current) {
149 ctx->ATIFragmentShader.Current->RefCount--;
150 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
151 free(ctx->ATIFragmentShader.Current);
152 }
153 }
154 #endif
155 free((void *) ctx->Program.ErrorString);
156 }
157
158
159 /**
160 * Update the default program objects in the given context to reference those
161 * specified in the shared state and release those referencing the old
162 * shared state.
163 */
164 void
165 _mesa_update_default_objects_program(struct gl_context *ctx)
166 {
167 #if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program
168 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
169 (struct gl_vertex_program *)
170 ctx->Shared->DefaultVertexProgram);
171 assert(ctx->VertexProgram.Current);
172 #endif
173
174 #if FEATURE_NV_fragment_program || FEATURE_ARB_fragment_program
175 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
176 (struct gl_fragment_program *)
177 ctx->Shared->DefaultFragmentProgram);
178 assert(ctx->FragmentProgram.Current);
179 #endif
180
181 #if FEATURE_ARB_geometry_shader4
182 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
183 (struct gl_geometry_program *)
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 _mesa_free_instructions(prog->Instructions, prog->NumInstructions);
389
390 if (prog->Parameters) {
391 _mesa_free_parameter_list(prog->Parameters);
392 }
393 if (prog->Varying) {
394 _mesa_free_parameter_list(prog->Varying);
395 }
396 if (prog->Attributes) {
397 _mesa_free_parameter_list(prog->Attributes);
398 }
399
400 free(prog);
401 }
402
403
404 /**
405 * Return the gl_program object for a given ID.
406 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
407 * casts elsewhere.
408 */
409 struct gl_program *
410 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
411 {
412 if (id)
413 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
414 else
415 return NULL;
416 }
417
418
419 /**
420 * Reference counting for vertex/fragment programs
421 */
422 void
423 _mesa_reference_program(struct gl_context *ctx,
424 struct gl_program **ptr,
425 struct gl_program *prog)
426 {
427 assert(ptr);
428 if (*ptr && prog) {
429 /* sanity check */
430 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
431 ASSERT(prog->Target == GL_VERTEX_PROGRAM_ARB);
432 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
433 ASSERT(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
434 prog->Target == GL_FRAGMENT_PROGRAM_NV);
435 else if ((*ptr)->Target == MESA_GEOMETRY_PROGRAM)
436 ASSERT(prog->Target == MESA_GEOMETRY_PROGRAM);
437 }
438 if (*ptr == prog) {
439 return; /* no change */
440 }
441 if (*ptr) {
442 GLboolean deleteFlag;
443
444 /*_glthread_LOCK_MUTEX((*ptr)->Mutex);*/
445 #if 0
446 printf("Program %p ID=%u Target=%s Refcount-- to %d\n",
447 *ptr, (*ptr)->Id,
448 ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
449 ((*ptr)->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
450 (*ptr)->RefCount - 1);
451 #endif
452 ASSERT((*ptr)->RefCount > 0);
453 (*ptr)->RefCount--;
454
455 deleteFlag = ((*ptr)->RefCount == 0);
456 /*_glthread_UNLOCK_MUTEX((*ptr)->Mutex);*/
457
458 if (deleteFlag) {
459 ASSERT(ctx);
460 ctx->Driver.DeleteProgram(ctx, *ptr);
461 }
462
463 *ptr = NULL;
464 }
465
466 assert(!*ptr);
467 if (prog) {
468 /*_glthread_LOCK_MUTEX(prog->Mutex);*/
469 prog->RefCount++;
470 #if 0
471 printf("Program %p ID=%u Target=%s Refcount++ to %d\n",
472 prog, prog->Id,
473 (prog->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
474 (prog->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
475 prog->RefCount);
476 #endif
477 /*_glthread_UNLOCK_MUTEX(prog->Mutex);*/
478 }
479
480 *ptr = prog;
481 }
482
483
484 /**
485 * Return a copy of a program.
486 * XXX Problem here if the program object is actually OO-derivation
487 * made by a device driver.
488 */
489 struct gl_program *
490 _mesa_clone_program(struct gl_context *ctx, const struct gl_program *prog)
491 {
492 struct gl_program *clone;
493
494 clone = ctx->Driver.NewProgram(ctx, prog->Target, prog->Id);
495 if (!clone)
496 return NULL;
497
498 assert(clone->Target == prog->Target);
499 assert(clone->RefCount == 1);
500
501 clone->String = (GLubyte *) _mesa_strdup((char *) prog->String);
502 clone->Format = prog->Format;
503 clone->Instructions = _mesa_alloc_instructions(prog->NumInstructions);
504 if (!clone->Instructions) {
505 _mesa_reference_program(ctx, &clone, NULL);
506 return NULL;
507 }
508 _mesa_copy_instructions(clone->Instructions, prog->Instructions,
509 prog->NumInstructions);
510 clone->InputsRead = prog->InputsRead;
511 clone->OutputsWritten = prog->OutputsWritten;
512 clone->SamplersUsed = prog->SamplersUsed;
513 clone->ShadowSamplers = prog->ShadowSamplers;
514 memcpy(clone->TexturesUsed, prog->TexturesUsed, sizeof(prog->TexturesUsed));
515
516 if (prog->Parameters)
517 clone->Parameters = _mesa_clone_parameter_list(prog->Parameters);
518 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
519 if (prog->Varying)
520 clone->Varying = _mesa_clone_parameter_list(prog->Varying);
521 if (prog->Attributes)
522 clone->Attributes = _mesa_clone_parameter_list(prog->Attributes);
523 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
524 clone->IndirectRegisterFiles = prog->IndirectRegisterFiles;
525 clone->NumInstructions = prog->NumInstructions;
526 clone->NumTemporaries = prog->NumTemporaries;
527 clone->NumParameters = prog->NumParameters;
528 clone->NumAttributes = prog->NumAttributes;
529 clone->NumAddressRegs = prog->NumAddressRegs;
530 clone->NumNativeInstructions = prog->NumNativeInstructions;
531 clone->NumNativeTemporaries = prog->NumNativeTemporaries;
532 clone->NumNativeParameters = prog->NumNativeParameters;
533 clone->NumNativeAttributes = prog->NumNativeAttributes;
534 clone->NumNativeAddressRegs = prog->NumNativeAddressRegs;
535 clone->NumAluInstructions = prog->NumAluInstructions;
536 clone->NumTexInstructions = prog->NumTexInstructions;
537 clone->NumTexIndirections = prog->NumTexIndirections;
538 clone->NumNativeAluInstructions = prog->NumNativeAluInstructions;
539 clone->NumNativeTexInstructions = prog->NumNativeTexInstructions;
540 clone->NumNativeTexIndirections = prog->NumNativeTexIndirections;
541
542 switch (prog->Target) {
543 case GL_VERTEX_PROGRAM_ARB:
544 {
545 const struct gl_vertex_program *vp
546 = (const struct gl_vertex_program *) prog;
547 struct gl_vertex_program *vpc = (struct gl_vertex_program *) clone;
548 vpc->IsPositionInvariant = vp->IsPositionInvariant;
549 vpc->IsNVProgram = vp->IsNVProgram;
550 }
551 break;
552 case GL_FRAGMENT_PROGRAM_ARB:
553 {
554 const struct gl_fragment_program *fp
555 = (const struct gl_fragment_program *) prog;
556 struct gl_fragment_program *fpc = (struct gl_fragment_program *) clone;
557 fpc->FogOption = fp->FogOption;
558 fpc->UsesKill = fp->UsesKill;
559 fpc->OriginUpperLeft = fp->OriginUpperLeft;
560 fpc->PixelCenterInteger = fp->PixelCenterInteger;
561 }
562 break;
563 case MESA_GEOMETRY_PROGRAM:
564 {
565 const struct gl_geometry_program *gp
566 = (const struct gl_geometry_program *) prog;
567 struct gl_geometry_program *gpc = (struct gl_geometry_program *) clone;
568 gpc->VerticesOut = gp->VerticesOut;
569 gpc->InputType = gp->InputType;
570 gpc->OutputType = gp->OutputType;
571 }
572 break;
573 default:
574 _mesa_problem(NULL, "Unexpected target in _mesa_clone_program");
575 }
576
577 return clone;
578 }
579
580
581 /**
582 * Insert 'count' NOP instructions at 'start' in the given program.
583 * Adjust branch targets accordingly.
584 */
585 GLboolean
586 _mesa_insert_instructions(struct gl_program *prog, GLuint start, GLuint count)
587 {
588 const GLuint origLen = prog->NumInstructions;
589 const GLuint newLen = origLen + count;
590 struct prog_instruction *newInst;
591 GLuint i;
592
593 /* adjust branches */
594 for (i = 0; i < prog->NumInstructions; i++) {
595 struct prog_instruction *inst = prog->Instructions + i;
596 if (inst->BranchTarget > 0) {
597 if ((GLuint)inst->BranchTarget >= start) {
598 inst->BranchTarget += count;
599 }
600 }
601 }
602
603 /* Alloc storage for new instructions */
604 newInst = _mesa_alloc_instructions(newLen);
605 if (!newInst) {
606 return GL_FALSE;
607 }
608
609 /* Copy 'start' instructions into new instruction buffer */
610 _mesa_copy_instructions(newInst, prog->Instructions, start);
611
612 /* init the new instructions */
613 _mesa_init_instructions(newInst + start, count);
614
615 /* Copy the remaining/tail instructions to new inst buffer */
616 _mesa_copy_instructions(newInst + start + count,
617 prog->Instructions + start,
618 origLen - start);
619
620 /* free old instructions */
621 _mesa_free_instructions(prog->Instructions, origLen);
622
623 /* install new instructions */
624 prog->Instructions = newInst;
625 prog->NumInstructions = newLen;
626
627 return GL_TRUE;
628 }
629
630 /**
631 * Delete 'count' instructions at 'start' in the given program.
632 * Adjust branch targets accordingly.
633 */
634 GLboolean
635 _mesa_delete_instructions(struct gl_program *prog, GLuint start, GLuint count)
636 {
637 const GLuint origLen = prog->NumInstructions;
638 const GLuint newLen = origLen - count;
639 struct prog_instruction *newInst;
640 GLuint i;
641
642 /* adjust branches */
643 for (i = 0; i < prog->NumInstructions; i++) {
644 struct prog_instruction *inst = prog->Instructions + i;
645 if (inst->BranchTarget > 0) {
646 if (inst->BranchTarget > (GLint) start) {
647 inst->BranchTarget -= count;
648 }
649 }
650 }
651
652 /* Alloc storage for new instructions */
653 newInst = _mesa_alloc_instructions(newLen);
654 if (!newInst) {
655 return GL_FALSE;
656 }
657
658 /* Copy 'start' instructions into new instruction buffer */
659 _mesa_copy_instructions(newInst, prog->Instructions, start);
660
661 /* Copy the remaining/tail instructions to new inst buffer */
662 _mesa_copy_instructions(newInst + start,
663 prog->Instructions + start + count,
664 newLen - start);
665
666 /* free old instructions */
667 _mesa_free_instructions(prog->Instructions, origLen);
668
669 /* install new instructions */
670 prog->Instructions = newInst;
671 prog->NumInstructions = newLen;
672
673 return GL_TRUE;
674 }
675
676
677 /**
678 * Search instructions for registers that match (oldFile, oldIndex),
679 * replacing them with (newFile, newIndex).
680 */
681 static void
682 replace_registers(struct prog_instruction *inst, GLuint numInst,
683 GLuint oldFile, GLuint oldIndex,
684 GLuint newFile, GLuint newIndex)
685 {
686 GLuint i, j;
687 for (i = 0; i < numInst; i++) {
688 /* src regs */
689 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
690 if (inst[i].SrcReg[j].File == oldFile &&
691 inst[i].SrcReg[j].Index == oldIndex) {
692 inst[i].SrcReg[j].File = newFile;
693 inst[i].SrcReg[j].Index = newIndex;
694 }
695 }
696 /* dst reg */
697 if (inst[i].DstReg.File == oldFile && inst[i].DstReg.Index == oldIndex) {
698 inst[i].DstReg.File = newFile;
699 inst[i].DstReg.Index = newIndex;
700 }
701 }
702 }
703
704
705 /**
706 * Search instructions for references to program parameters. When found,
707 * increment the parameter index by 'offset'.
708 * Used when combining programs.
709 */
710 static void
711 adjust_param_indexes(struct prog_instruction *inst, GLuint numInst,
712 GLuint offset)
713 {
714 GLuint i, j;
715 for (i = 0; i < numInst; i++) {
716 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
717 GLuint f = inst[i].SrcReg[j].File;
718 if (f == PROGRAM_CONSTANT ||
719 f == PROGRAM_UNIFORM ||
720 f == PROGRAM_STATE_VAR) {
721 inst[i].SrcReg[j].Index += offset;
722 }
723 }
724 }
725 }
726
727
728 /**
729 * Combine two programs into one. Fix instructions so the outputs of
730 * the first program go to the inputs of the second program.
731 */
732 struct gl_program *
733 _mesa_combine_programs(struct gl_context *ctx,
734 const struct gl_program *progA,
735 const struct gl_program *progB)
736 {
737 struct prog_instruction *newInst;
738 struct gl_program *newProg;
739 const GLuint lenA = progA->NumInstructions - 1; /* omit END instr */
740 const GLuint lenB = progB->NumInstructions;
741 const GLuint numParamsA = _mesa_num_parameters(progA->Parameters);
742 const GLuint newLength = lenA + lenB;
743 GLboolean usedTemps[MAX_PROGRAM_TEMPS];
744 GLuint firstTemp = 0;
745 GLbitfield inputsB;
746 GLuint i;
747
748 ASSERT(progA->Target == progB->Target);
749
750 newInst = _mesa_alloc_instructions(newLength);
751 if (!newInst)
752 return GL_FALSE;
753
754 _mesa_copy_instructions(newInst, progA->Instructions, lenA);
755 _mesa_copy_instructions(newInst + lenA, progB->Instructions, lenB);
756
757 /* adjust branch / instruction addresses for B's instructions */
758 for (i = 0; i < lenB; i++) {
759 newInst[lenA + i].BranchTarget += lenA;
760 }
761
762 newProg = ctx->Driver.NewProgram(ctx, progA->Target, 0);
763 newProg->Instructions = newInst;
764 newProg->NumInstructions = newLength;
765
766 /* find used temp regs (we may need new temps below) */
767 _mesa_find_used_registers(newProg, PROGRAM_TEMPORARY,
768 usedTemps, MAX_PROGRAM_TEMPS);
769
770 if (newProg->Target == GL_FRAGMENT_PROGRAM_ARB) {
771 struct gl_fragment_program *fprogA, *fprogB, *newFprog;
772 GLbitfield progB_inputsRead = progB->InputsRead;
773 GLint progB_colorFile, progB_colorIndex;
774
775 fprogA = (struct gl_fragment_program *) progA;
776 fprogB = (struct gl_fragment_program *) progB;
777 newFprog = (struct gl_fragment_program *) newProg;
778
779 newFprog->UsesKill = fprogA->UsesKill || fprogB->UsesKill;
780
781 /* We'll do a search and replace for instances
782 * of progB_colorFile/progB_colorIndex below...
783 */
784 progB_colorFile = PROGRAM_INPUT;
785 progB_colorIndex = FRAG_ATTRIB_COL0;
786
787 /*
788 * The fragment program may get color from a state var rather than
789 * a fragment input (vertex output) if it's constant.
790 * See the texenvprogram.c code.
791 * So, search the program's parameter list now to see if the program
792 * gets color from a state var instead of a conventional fragment
793 * input register.
794 */
795 for (i = 0; i < progB->Parameters->NumParameters; i++) {
796 struct gl_program_parameter *p = &progB->Parameters->Parameters[i];
797 if (p->Type == PROGRAM_STATE_VAR &&
798 p->StateIndexes[0] == STATE_INTERNAL &&
799 p->StateIndexes[1] == STATE_CURRENT_ATTRIB &&
800 (int) p->StateIndexes[2] == (int) VERT_ATTRIB_COLOR0) {
801 progB_inputsRead |= FRAG_BIT_COL0;
802 progB_colorFile = PROGRAM_STATE_VAR;
803 progB_colorIndex = i;
804 break;
805 }
806 }
807
808 /* Connect color outputs of fprogA to color inputs of fprogB, via a
809 * new temporary register.
810 */
811 if ((progA->OutputsWritten & (1 << FRAG_RESULT_COLOR)) &&
812 (progB_inputsRead & FRAG_BIT_COL0)) {
813 GLint tempReg = _mesa_find_free_register(usedTemps, MAX_PROGRAM_TEMPS,
814 firstTemp);
815 if (tempReg < 0) {
816 _mesa_problem(ctx, "No free temp regs found in "
817 "_mesa_combine_programs(), using 31");
818 tempReg = 31;
819 }
820 firstTemp = tempReg + 1;
821
822 /* replace writes to result.color[0] with tempReg */
823 replace_registers(newInst, lenA,
824 PROGRAM_OUTPUT, FRAG_RESULT_COLOR,
825 PROGRAM_TEMPORARY, tempReg);
826 /* replace reads from the input color with tempReg */
827 replace_registers(newInst + lenA, lenB,
828 progB_colorFile, progB_colorIndex, /* search for */
829 PROGRAM_TEMPORARY, tempReg /* replace with */ );
830 }
831
832 /* compute combined program's InputsRead */
833 inputsB = progB_inputsRead;
834 if (progA->OutputsWritten & (1 << FRAG_RESULT_COLOR)) {
835 inputsB &= ~(1 << FRAG_ATTRIB_COL0);
836 }
837 newProg->InputsRead = progA->InputsRead | inputsB;
838 newProg->OutputsWritten = progB->OutputsWritten;
839 newProg->SamplersUsed = progA->SamplersUsed | progB->SamplersUsed;
840 }
841 else {
842 /* vertex program */
843 assert(0); /* XXX todo */
844 }
845
846 /*
847 * Merge parameters (uniforms, constants, etc)
848 */
849 newProg->Parameters = _mesa_combine_parameter_lists(progA->Parameters,
850 progB->Parameters);
851
852 adjust_param_indexes(newInst + lenA, lenB, numParamsA);
853
854
855 return newProg;
856 }
857
858
859 /**
860 * Populate the 'used' array with flags indicating which registers (TEMPs,
861 * INPUTs, OUTPUTs, etc, are used by the given program.
862 * \param file type of register to scan for
863 * \param used returns true/false flags for in use / free
864 * \param usedSize size of the 'used' array
865 */
866 void
867 _mesa_find_used_registers(const struct gl_program *prog,
868 gl_register_file file,
869 GLboolean used[], GLuint usedSize)
870 {
871 GLuint i, j;
872
873 memset(used, 0, usedSize);
874
875 for (i = 0; i < prog->NumInstructions; i++) {
876 const struct prog_instruction *inst = prog->Instructions + i;
877 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
878
879 if (inst->DstReg.File == file) {
880 ASSERT(inst->DstReg.Index < usedSize);
881 if(inst->DstReg.Index < usedSize)
882 used[inst->DstReg.Index] = GL_TRUE;
883 }
884
885 for (j = 0; j < n; j++) {
886 if (inst->SrcReg[j].File == file) {
887 ASSERT(inst->SrcReg[j].Index < usedSize);
888 if(inst->SrcReg[j].Index < usedSize)
889 used[inst->SrcReg[j].Index] = GL_TRUE;
890 }
891 }
892 }
893 }
894
895
896 /**
897 * Scan the given 'used' register flag array for the first entry
898 * that's >= firstReg.
899 * \param used vector of flags indicating registers in use (as returned
900 * by _mesa_find_used_registers())
901 * \param usedSize size of the 'used' array
902 * \param firstReg first register to start searching at
903 * \return index of unused register, or -1 if none.
904 */
905 GLint
906 _mesa_find_free_register(const GLboolean used[],
907 GLuint usedSize, GLuint firstReg)
908 {
909 GLuint i;
910
911 assert(firstReg < usedSize);
912
913 for (i = firstReg; i < usedSize; i++)
914 if (!used[i])
915 return i;
916
917 return -1;
918 }
919
920
921
922 /**
923 * Check if the given register index is valid (doesn't exceed implementation-
924 * dependent limits).
925 * \return GL_TRUE if OK, GL_FALSE if bad index
926 */
927 GLboolean
928 _mesa_valid_register_index(const struct gl_context *ctx,
929 gl_shader_type shaderType,
930 gl_register_file file, GLint index)
931 {
932 const struct gl_program_constants *c;
933
934 switch (shaderType) {
935 case MESA_SHADER_VERTEX:
936 c = &ctx->Const.VertexProgram;
937 break;
938 case MESA_SHADER_FRAGMENT:
939 c = &ctx->Const.FragmentProgram;
940 break;
941 case MESA_SHADER_GEOMETRY:
942 c = &ctx->Const.GeometryProgram;
943 break;
944 default:
945 _mesa_problem(ctx,
946 "unexpected shader type in _mesa_valid_register_index()");
947 return GL_FALSE;
948 }
949
950 switch (file) {
951 case PROGRAM_UNDEFINED:
952 return GL_TRUE; /* XXX or maybe false? */
953
954 case PROGRAM_TEMPORARY:
955 return index >= 0 && index < c->MaxTemps;
956
957 case PROGRAM_ENV_PARAM:
958 return index >= 0 && index < c->MaxEnvParams;
959
960 case PROGRAM_LOCAL_PARAM:
961 return index >= 0 && index < c->MaxLocalParams;
962
963 case PROGRAM_NAMED_PARAM:
964 return index >= 0 && index < c->MaxParameters;
965
966 case PROGRAM_UNIFORM:
967 case PROGRAM_STATE_VAR:
968 /* aka constant buffer */
969 return index >= 0 && index < c->MaxUniformComponents / 4;
970
971 case PROGRAM_CONSTANT:
972 /* constant buffer w/ possible relative negative addressing */
973 return (index > (int) c->MaxUniformComponents / -4 &&
974 index < c->MaxUniformComponents / 4);
975
976 case PROGRAM_INPUT:
977 if (index < 0)
978 return GL_FALSE;
979
980 switch (shaderType) {
981 case MESA_SHADER_VERTEX:
982 return index < VERT_ATTRIB_GENERIC0 + c->MaxAttribs;
983 case MESA_SHADER_FRAGMENT:
984 return index < FRAG_ATTRIB_VAR0 + ctx->Const.MaxVarying;
985 case MESA_SHADER_GEOMETRY:
986 return index < GEOM_ATTRIB_VAR0 + ctx->Const.MaxVarying;
987 default:
988 return GL_FALSE;
989 }
990
991 case PROGRAM_OUTPUT:
992 if (index < 0)
993 return GL_FALSE;
994
995 switch (shaderType) {
996 case MESA_SHADER_VERTEX:
997 return index < VERT_RESULT_VAR0 + ctx->Const.MaxVarying;
998 case MESA_SHADER_FRAGMENT:
999 return index < FRAG_RESULT_DATA0 + ctx->Const.MaxDrawBuffers;
1000 case MESA_SHADER_GEOMETRY:
1001 return index < GEOM_RESULT_VAR0 + ctx->Const.MaxVarying;
1002 default:
1003 return GL_FALSE;
1004 }
1005
1006 case PROGRAM_ADDRESS:
1007 return index >= 0 && index < c->MaxAddressRegs;
1008
1009 default:
1010 _mesa_problem(ctx,
1011 "unexpected register file in _mesa_valid_register_index()");
1012 return GL_FALSE;
1013 }
1014 }
1015
1016
1017
1018 /**
1019 * "Post-process" a GPU program. This is intended to be used for debugging.
1020 * Example actions include no-op'ing instructions or changing instruction
1021 * behaviour.
1022 */
1023 void
1024 _mesa_postprocess_program(struct gl_context *ctx, struct gl_program *prog)
1025 {
1026 static const GLfloat white[4] = { 0.5, 0.5, 0.5, 0.5 };
1027 GLuint i;
1028 GLuint whiteSwizzle;
1029 GLint whiteIndex = _mesa_add_unnamed_constant(prog->Parameters,
1030 white, 4, &whiteSwizzle);
1031
1032 (void) whiteIndex;
1033
1034 for (i = 0; i < prog->NumInstructions; i++) {
1035 struct prog_instruction *inst = prog->Instructions + i;
1036 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
1037
1038 (void) n;
1039
1040 if (_mesa_is_tex_instruction(inst->Opcode)) {
1041 #if 0
1042 /* replace TEX/TXP/TXB with MOV */
1043 inst->Opcode = OPCODE_MOV;
1044 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1045 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1046 inst->SrcReg[0].Negate = NEGATE_NONE;
1047 #endif
1048
1049 #if 0
1050 /* disable shadow texture mode */
1051 inst->TexShadow = 0;
1052 #endif
1053 }
1054
1055 if (inst->Opcode == OPCODE_TXP) {
1056 #if 0
1057 inst->Opcode = OPCODE_MOV;
1058 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1059 inst->SrcReg[0].File = PROGRAM_CONSTANT;
1060 inst->SrcReg[0].Index = whiteIndex;
1061 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1062 inst->SrcReg[0].Negate = NEGATE_NONE;
1063 #endif
1064 #if 0
1065 inst->TexShadow = 0;
1066 #endif
1067 #if 0
1068 inst->Opcode = OPCODE_TEX;
1069 inst->TexShadow = 0;
1070 #endif
1071 }
1072
1073 }
1074 }