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