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