xref: /aosp_15_r20/external/mesa3d/src/mesa/program/program.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
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 "util/glheader.h"
33 #include "main/context.h"
34 #include "main/framebuffer.h"
35 #include "main/hash.h"
36 #include "main/macros.h"
37 #include "main/shaderobj.h"
38 #include "main/state.h"
39 #include "program.h"
40 #include "prog_cache.h"
41 #include "prog_parameter.h"
42 #include "prog_instruction.h"
43 #include "util/bitscan.h"
44 #include "util/ralloc.h"
45 #include "util/u_atomic.h"
46 
47 #include "state_tracker/st_program.h"
48 #include "state_tracker/st_context.h"
49 
50 /**
51  * A pointer to this dummy program is put into the hash table when
52  * glGenPrograms is called.
53  */
54 struct gl_program _mesa_DummyProgram;
55 
56 
57 /**
58  * Init context's vertex/fragment program state
59  */
60 void
_mesa_init_program(struct gl_context * ctx)61 _mesa_init_program(struct gl_context *ctx)
62 {
63    /*
64     * If this assertion fails, we need to increase the field
65     * size for register indexes (see INST_INDEX_BITS).
66     */
67    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents / 4
68           <= (1 << INST_INDEX_BITS));
69    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents / 4
70           <= (1 << INST_INDEX_BITS));
71 
72    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxTemps <= (1 << INST_INDEX_BITS));
73    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxLocalParams <= (1 << INST_INDEX_BITS));
74    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTemps <= (1 << INST_INDEX_BITS));
75    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxLocalParams <= (1 << INST_INDEX_BITS));
76 
77    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents <= 4 * MAX_UNIFORMS);
78    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents <= 4 * MAX_UNIFORMS);
79 
80    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxAddressOffset <= (1 << INST_INDEX_BITS));
81    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAddressOffset <= (1 << INST_INDEX_BITS));
82 
83    /* If this fails, increase prog_instruction::TexSrcUnit size */
84    STATIC_ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
85 
86    /* If this fails, increase prog_instruction::TexSrcTarget size */
87    STATIC_ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
88 
89    ctx->Program.ErrorPos = -1;
90    ctx->Program.ErrorString = strdup("");
91 
92    ctx->VertexProgram._VaryingInputs = VERT_BIT_ALL;
93    ctx->VertexProgram.Enabled = GL_FALSE;
94    ctx->VertexProgram.PointSizeEnabled =
95       _mesa_is_gles2(ctx) ? GL_TRUE : GL_FALSE;
96    ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
97    _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
98                            ctx->Shared->DefaultVertexProgram);
99    assert(ctx->VertexProgram.Current);
100    ctx->VertexProgram.Cache = _mesa_new_program_cache();
101 
102    ctx->FragmentProgram.Enabled = GL_FALSE;
103    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
104                            ctx->Shared->DefaultFragmentProgram);
105    assert(ctx->FragmentProgram.Current);
106    ctx->FragmentProgram.Cache = _mesa_new_program_cache();
107    _mesa_reset_vertex_processing_mode(ctx);
108 
109    /* XXX probably move this stuff */
110    ctx->ATIFragmentShader.Enabled = GL_FALSE;
111    ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
112    assert(ctx->ATIFragmentShader.Current);
113    ctx->ATIFragmentShader.Current->RefCount++;
114 }
115 
116 
117 /**
118  * Free a context's vertex/fragment program state
119  */
120 void
_mesa_free_program_data(struct gl_context * ctx)121 _mesa_free_program_data(struct gl_context *ctx)
122 {
123    _mesa_reference_program(ctx, &ctx->VertexProgram.Current, NULL);
124    _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
125    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current, NULL);
126    _mesa_delete_program_cache(ctx, ctx->FragmentProgram.Cache);
127 
128    /* XXX probably move this stuff */
129    if (ctx->ATIFragmentShader.Current) {
130       ctx->ATIFragmentShader.Current->RefCount--;
131       if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
132          free(ctx->ATIFragmentShader.Current);
133       }
134    }
135 
136    free((void *) ctx->Program.ErrorString);
137 }
138 
139 
140 /**
141  * Update the default program objects in the given context to reference those
142  * specified in the shared state and release those referencing the old
143  * shared state.
144  */
145 void
_mesa_update_default_objects_program(struct gl_context * ctx)146 _mesa_update_default_objects_program(struct gl_context *ctx)
147 {
148    _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
149                            ctx->Shared->DefaultVertexProgram);
150    assert(ctx->VertexProgram.Current);
151 
152    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
153                             ctx->Shared->DefaultFragmentProgram);
154    assert(ctx->FragmentProgram.Current);
155 
156    /* XXX probably move this stuff */
157    if (ctx->ATIFragmentShader.Current) {
158       ctx->ATIFragmentShader.Current->RefCount--;
159       if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
160          free(ctx->ATIFragmentShader.Current);
161       }
162    }
163    ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
164    assert(ctx->ATIFragmentShader.Current);
165    ctx->ATIFragmentShader.Current->RefCount++;
166 }
167 
168 
169 /**
170  * Set the vertex/fragment program error state (position and error string).
171  * This is generally called from within the parsers.
172  */
173 void
_mesa_set_program_error(struct gl_context * ctx,GLint pos,const char * string)174 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
175 {
176    ctx->Program.ErrorPos = pos;
177    free((void *) ctx->Program.ErrorString);
178    if (!string)
179       string = "";
180    ctx->Program.ErrorString = strdup(string);
181 }
182 
183 
184 /**
185  * Initialize a new gl_program object.
186  */
187 struct gl_program *
_mesa_init_gl_program(struct gl_program * prog,gl_shader_stage stage,GLuint id,bool is_arb_asm)188 _mesa_init_gl_program(struct gl_program *prog, gl_shader_stage stage,
189                       GLuint id, bool is_arb_asm)
190 {
191    if (!prog)
192       return NULL;
193 
194    memset(prog, 0, sizeof(*prog));
195    prog->Id = id;
196    prog->Target = _mesa_shader_stage_to_program(stage);
197    prog->RefCount = 1;
198    prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
199    prog->info.stage = stage;
200    prog->info.use_legacy_math_rules = is_arb_asm;
201 
202    /* Uniforms that lack an initializer in the shader code have an initial
203     * value of zero.  This includes sampler uniforms.
204     *
205     * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
206     *
207     *     "The link time initial value is either the value of the variable's
208     *     initializer, if present, or 0 if no initializer is present. Sampler
209     *     types cannot have initializers."
210     *
211     * So we only initialise ARB assembly style programs.
212     */
213    if (is_arb_asm) {
214       /* default mapping from samplers to texture units */
215       for (unsigned i = 0; i < MAX_SAMPLERS; i++)
216          prog->SamplerUnits[i] = i;
217    }
218 
219    return prog;
220 }
221 
222 struct gl_program *
_mesa_new_program(struct gl_context * ctx,gl_shader_stage stage,GLuint id,bool is_arb_asm)223 _mesa_new_program(struct gl_context *ctx, gl_shader_stage stage, GLuint id,
224                   bool is_arb_asm)
225 {
226    struct gl_program *prog;
227 
228    switch (stage) {
229    case MESA_SHADER_VERTEX:
230       prog = (struct gl_program*)rzalloc(NULL, struct gl_vertex_program);
231       break;
232    default:
233       prog = rzalloc(NULL, struct gl_program);
234       break;
235    }
236 
237    return _mesa_init_gl_program(prog, stage, id, is_arb_asm);
238 }
239 
240 /**
241  * Delete a program and remove it from the hash table, ignoring the
242  * reference count.
243  */
244 void
_mesa_delete_program(struct gl_context * ctx,struct gl_program * prog)245 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
246 {
247    struct st_context *st = st_context(ctx);
248    assert(prog);
249    assert(prog->RefCount==0);
250 
251    st_release_variants(st, prog);
252 
253    free(prog->serialized_nir);
254    free(prog->base_serialized_nir);
255 
256    if (prog == &_mesa_DummyProgram)
257       return;
258 
259    if (prog->Parameters) {
260       _mesa_free_parameter_list(prog->Parameters);
261    }
262 
263    if (prog->nir) {
264       ralloc_free(prog->nir);
265    }
266 
267    if (prog->sh.BindlessSamplers) {
268       ralloc_free(prog->sh.BindlessSamplers);
269    }
270 
271    if (prog->sh.BindlessImages) {
272       ralloc_free(prog->sh.BindlessImages);
273    }
274 
275    if (prog->driver_cache_blob) {
276       ralloc_free(prog->driver_cache_blob);
277    }
278 
279    ralloc_free(prog);
280 }
281 
282 
283 /**
284  * Return the gl_program object for a given ID.
285  * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
286  * casts elsewhere.
287  */
288 struct gl_program *
_mesa_lookup_program(struct gl_context * ctx,GLuint id)289 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
290 {
291    if (id)
292       return (struct gl_program *) _mesa_HashLookup(&ctx->Shared->Programs, id);
293    else
294       return NULL;
295 }
296 
297 
298 /**
299  * Reference counting for vertex/fragment programs
300  * This is normally only called from the _mesa_reference_program() macro
301  * when there's a real pointer change.
302  */
303 void
_mesa_reference_program_(struct gl_context * ctx,struct gl_program ** ptr,struct gl_program * prog)304 _mesa_reference_program_(struct gl_context *ctx,
305                          struct gl_program **ptr,
306                          struct gl_program *prog)
307 {
308 #ifndef NDEBUG
309    assert(ptr);
310    if (*ptr && prog) {
311       /* sanity check */
312       if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
313          assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
314       else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
315          assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
316                 prog->Target == GL_FRAGMENT_PROGRAM_NV);
317       else if ((*ptr)->Target == GL_GEOMETRY_PROGRAM_NV)
318          assert(prog->Target == GL_GEOMETRY_PROGRAM_NV);
319    }
320 #endif
321 
322    if (*ptr) {
323       struct gl_program *oldProg = *ptr;
324 
325       assert(oldProg->RefCount > 0);
326 
327       if (p_atomic_dec_zero(&oldProg->RefCount)) {
328          assert(ctx);
329          _mesa_reference_shader_program_data(&oldProg->sh.data, NULL);
330          _mesa_delete_program(ctx, oldProg);
331       }
332 
333       *ptr = NULL;
334    }
335 
336    assert(!*ptr);
337    if (prog) {
338       p_atomic_inc(&prog->RefCount);
339    }
340 
341    *ptr = prog;
342 }
343 
344 /* Gets the minimum number of shader invocations per fragment.
345  * This function is useful to determine if we need to do per
346  * sample shading or per fragment shading.
347  */
348 GLint
_mesa_get_min_invocations_per_fragment(struct gl_context * ctx,const struct gl_program * prog)349 _mesa_get_min_invocations_per_fragment(struct gl_context *ctx,
350                                        const struct gl_program *prog)
351 {
352    /* From ARB_sample_shading specification:
353     * "Using gl_SampleID in a fragment shader causes the entire shader
354     *  to be evaluated per-sample."
355     *
356     * "Using gl_SamplePosition in a fragment shader causes the entire
357     *  shader to be evaluated per-sample."
358     *
359     * "If MULTISAMPLE or SAMPLE_SHADING_ARB is disabled, sample shading
360     *  has no effect."
361     */
362    if (ctx->Multisample.Enabled) {
363       /* The ARB_gpu_shader5 specification says:
364        *
365        * "Use of the "sample" qualifier on a fragment shader input
366        *  forces per-sample shading"
367        */
368       if (prog->info.fs.uses_sample_qualifier ||
369           BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_ID) ||
370           BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_POS))
371          return MAX2(_mesa_geometric_samples(ctx->DrawBuffer), 1);
372       else if (ctx->Multisample.SampleShading)
373          return MAX2(ceilf(ctx->Multisample.MinSampleShadingValue *
374                           _mesa_geometric_samples(ctx->DrawBuffer)), 1);
375       else
376          return 1;
377    }
378    return 1;
379 }
380 
381 
382 GLbitfield
gl_external_samplers(const struct gl_program * prog)383 gl_external_samplers(const struct gl_program *prog)
384 {
385    GLbitfield external_samplers = 0;
386    GLbitfield mask = prog->SamplersUsed;
387 
388    while (mask) {
389       int idx = u_bit_scan(&mask);
390       if (prog->sh.SamplerTargets[idx] == TEXTURE_EXTERNAL_INDEX)
391          external_samplers |= (1 << idx);
392    }
393 
394    return external_samplers;
395 }
396 
compare_state_var(const void * a1,const void * a2)397 static int compare_state_var(const void *a1, const void *a2)
398 {
399    const struct gl_program_parameter *p1 =
400       (const struct gl_program_parameter *)a1;
401    const struct gl_program_parameter *p2 =
402       (const struct gl_program_parameter *)a2;
403 
404    for (unsigned i = 0; i < STATE_LENGTH; i++) {
405       if (p1->StateIndexes[i] != p2->StateIndexes[i])
406          return p1->StateIndexes[i] - p2->StateIndexes[i];
407    }
408    return 0;
409 }
410 
411 void
_mesa_add_separate_state_parameters(struct gl_program * prog,struct gl_program_parameter_list * state_params)412 _mesa_add_separate_state_parameters(struct gl_program *prog,
413                                     struct gl_program_parameter_list *state_params)
414 {
415    unsigned num_state_params = state_params->NumParameters;
416 
417    if (num_state_params == 0)
418       return;
419 
420    /* All state parameters should be vec4s. */
421    for (unsigned i = 0; i < num_state_params; i++) {
422       assert(state_params->Parameters[i].Type == PROGRAM_STATE_VAR);
423       assert(state_params->Parameters[i].Size == 4);
424       assert(state_params->Parameters[i].ValueOffset == i * 4);
425    }
426 
427    /* Sort state parameters to facilitate better parameter merging. */
428    qsort(state_params->Parameters, num_state_params,
429          sizeof(state_params->Parameters[0]), compare_state_var);
430    unsigned *remap = malloc(num_state_params * sizeof(unsigned));
431 
432    /* Add state parameters to the end of the parameter list. */
433    for (unsigned i = 0; i < num_state_params; i++) {
434       unsigned old_index = state_params->Parameters[i].ValueOffset / 4;
435 
436       remap[old_index] =
437          _mesa_add_parameter(prog->Parameters, PROGRAM_STATE_VAR,
438                              state_params->Parameters[i].Name,
439                              state_params->Parameters[i].Size,
440                              GL_NONE, NULL,
441                              state_params->Parameters[i].StateIndexes,
442                              state_params->Parameters[i].Padded);
443 
444       prog->Parameters->StateFlags |=
445          _mesa_program_state_flags(state_params->Parameters[i].StateIndexes);
446    }
447 
448    /* Fix up state parameter offsets in instructions. */
449    int num_instr = prog->arb.NumInstructions;
450    struct prog_instruction *instrs = prog->arb.Instructions;
451 
452    /* Fix src indices after sorting. */
453    for (unsigned i = 0; i < num_instr; i++) {
454       struct prog_instruction *inst = instrs + i;
455       unsigned num_src = _mesa_num_inst_src_regs(inst->Opcode);
456 
457       for (unsigned j = 0; j < num_src; j++) {
458          if (inst->SrcReg[j].File == PROGRAM_STATE_VAR)
459             inst->SrcReg[j].Index = remap[inst->SrcReg[j].Index];
460       }
461    }
462    free(remap);
463 }
464