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