• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Red Hat
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 
24 #include "st_nir.h"
25 
26 #include "pipe/p_defines.h"
27 #include "pipe/p_screen.h"
28 #include "pipe/p_context.h"
29 
30 #include "program/program.h"
31 #include "program/prog_statevars.h"
32 #include "program/prog_parameter.h"
33 #include "main/context.h"
34 #include "main/mtypes.h"
35 #include "main/errors.h"
36 #include "main/glspirv.h"
37 #include "main/shaderapi.h"
38 #include "main/uniforms.h"
39 
40 #include "main/shaderobj.h"
41 #include "st_context.h"
42 #include "st_program.h"
43 #include "st_shader_cache.h"
44 
45 #include "compiler/nir/nir.h"
46 #include "compiler/nir/nir_builder.h"
47 #include "compiler/glsl_types.h"
48 #include "compiler/glsl/glsl_to_nir.h"
49 #include "compiler/glsl/gl_nir.h"
50 #include "compiler/glsl/gl_nir_linker.h"
51 #include "compiler/glsl/ir.h"
52 #include "compiler/glsl/ir_optimization.h"
53 #include "compiler/glsl/linker_util.h"
54 #include "compiler/glsl/shader_cache.h"
55 #include "compiler/glsl/string_to_uint_map.h"
56 
57 #include "util/log.h"
58 
59 static int
type_size(const struct glsl_type * type)60 type_size(const struct glsl_type *type)
61 {
62    return glsl_count_attribute_slots(type, false);
63 }
64 
65 static int
st_nir_lookup_parameter_index(struct gl_program * prog,nir_variable * var)66 st_nir_lookup_parameter_index(struct gl_program *prog, nir_variable *var)
67 {
68    struct gl_program_parameter_list *params = prog->Parameters;
69 
70    /* Lookup the first parameter that the uniform storage that match the
71     * variable location.
72     */
73    for (unsigned i = 0; i < params->NumParameters; i++) {
74       int index = params->Parameters[i].MainUniformStorageIndex;
75       if (index == var->data.location)
76          return i;
77    }
78 
79    /* TODO: Handle this fallback for SPIR-V.  We need this for GLSL e.g. in
80     * dEQP-GLES2.functional.uniform_api.random.3
81     */
82 
83    /* is there a better way to do this?  If we have something like:
84     *
85     *    struct S {
86     *           float f;
87     *           vec4 v;
88     *    };
89     *    uniform S color;
90     *
91     * Then what we get in prog->Parameters looks like:
92     *
93     *    0: Name=color.f, Type=6, DataType=1406, Size=1
94     *    1: Name=color.v, Type=6, DataType=8b52, Size=4
95     *
96     * So the name doesn't match up and _mesa_lookup_parameter_index()
97     * fails.  In this case just find the first matching "color.*"..
98     *
99     * Note for arrays you could end up w/ color[n].f, for example.
100     */
101    if (!prog->sh.data->spirv) {
102       int namelen = strlen(var->name);
103       for (unsigned i = 0; i < params->NumParameters; i++) {
104          struct gl_program_parameter *p = &params->Parameters[i];
105          if ((strncmp(p->Name, var->name, namelen) == 0) &&
106              ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
107             return i;
108          }
109       }
110    }
111 
112    return -1;
113 }
114 
115 static void
st_nir_assign_uniform_locations(struct gl_context * ctx,struct gl_program * prog,nir_shader * nir)116 st_nir_assign_uniform_locations(struct gl_context *ctx,
117                                 struct gl_program *prog,
118                                 nir_shader *nir)
119 {
120    int shaderidx = 0;
121    int imageidx = 0;
122 
123    nir_foreach_variable_with_modes(uniform, nir, nir_var_uniform |
124                                                  nir_var_image) {
125       int loc;
126 
127       const struct glsl_type *type = glsl_without_array(uniform->type);
128       if (!uniform->data.bindless && (glsl_type_is_sampler(type) || glsl_type_is_image(type))) {
129          if (glsl_type_is_sampler(type)) {
130             loc = shaderidx;
131             shaderidx += type_size(uniform->type);
132          } else {
133             loc = imageidx;
134             imageidx += type_size(uniform->type);
135          }
136       } else if (uniform->state_slots) {
137          const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
138 
139          unsigned comps;
140          if (glsl_type_is_struct_or_ifc(type)) {
141             comps = 4;
142          } else {
143             comps = glsl_get_vector_elements(type);
144          }
145 
146          if (ctx->Const.PackedDriverUniformStorage) {
147             loc = _mesa_add_sized_state_reference(prog->Parameters,
148                                                   stateTokens, comps, false);
149             loc = prog->Parameters->Parameters[loc].ValueOffset;
150          } else {
151             loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
152          }
153       } else {
154          loc = st_nir_lookup_parameter_index(prog, uniform);
155 
156          /* We need to check that loc is not -1 here before accessing the
157           * array. It can be negative for example when we have a struct that
158           * only contains opaque types.
159           */
160          if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
161             loc = prog->Parameters->Parameters[loc].ValueOffset;
162          }
163       }
164 
165       uniform->data.driver_location = loc;
166    }
167 }
168 
169 static bool
def_is_64bit(nir_def * def,void * state)170 def_is_64bit(nir_def *def, void *state)
171 {
172    bool *lower = (bool *)state;
173    if (def && (def->bit_size == 64)) {
174       *lower = true;
175       return false;
176    }
177    return true;
178 }
179 
180 static bool
src_is_64bit(nir_src * src,void * state)181 src_is_64bit(nir_src *src, void *state)
182 {
183    bool *lower = (bool *)state;
184    if (src && (nir_src_bit_size(*src) == 64)) {
185       *lower = true;
186       return false;
187    }
188    return true;
189 }
190 
191 static bool
filter_64_bit_instr(const nir_instr * const_instr,UNUSED const void * data)192 filter_64_bit_instr(const nir_instr *const_instr, UNUSED const void *data)
193 {
194    bool lower = false;
195    /* lower_alu_to_scalar required nir_instr to be const, but nir_foreach_*
196     * doesn't have const variants, so do the ugly const_cast here. */
197    nir_instr *instr = const_cast<nir_instr *>(const_instr);
198 
199    nir_foreach_def(instr, def_is_64bit, &lower);
200    if (lower)
201       return true;
202    nir_foreach_src(instr, src_is_64bit, &lower);
203    return lower;
204 }
205 
206 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
207  * info on varyings, etc after NIR link time opts have been applied.
208  */
209 static char *
st_glsl_to_nir_post_opts(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program)210 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
211                          struct gl_shader_program *shader_program)
212 {
213    nir_shader *nir = prog->nir;
214    struct pipe_screen *screen = st->screen;
215 
216    /* Make a pass over the IR to add state references for any built-in
217     * uniforms that are used.  This has to be done now (during linking).
218     * Code generation doesn't happen until the first time this shader is
219     * used for rendering.  Waiting until then to generate the parameters is
220     * too late.  At that point, the values for the built-in uniforms won't
221     * get sent to the shader.
222     */
223    nir_foreach_uniform_variable(var, nir) {
224       const nir_state_slot *const slots = var->state_slots;
225       if (slots != NULL) {
226          const struct glsl_type *type = glsl_without_array(var->type);
227          for (unsigned int i = 0; i < var->num_state_slots; i++) {
228             unsigned comps;
229             if (glsl_type_is_struct_or_ifc(type)) {
230                comps = _mesa_program_state_value_size(slots[i].tokens);
231             } else {
232                comps = glsl_get_vector_elements(type);
233             }
234 
235             if (st->ctx->Const.PackedDriverUniformStorage) {
236                _mesa_add_sized_state_reference(prog->Parameters,
237                                                slots[i].tokens,
238                                                comps, false);
239             } else {
240                _mesa_add_state_reference(prog->Parameters,
241                                          slots[i].tokens);
242             }
243          }
244       }
245    }
246 
247    /* Avoid reallocation of the program parameter list, because the uniform
248     * storage is only associated with the original parameter list.
249     * This should be enough for Bitmap and DrawPixels constants.
250     */
251    _mesa_ensure_and_associate_uniform_storage(st->ctx, shader_program, prog, 28);
252 
253    /* None of the builtins being lowered here can be produced by SPIR-V.  See
254     * _mesa_builtin_uniform_desc. Also drivers that support packed uniform
255     * storage don't need to lower builtins.
256     */
257    if (!shader_program->data->spirv &&
258        !st->ctx->Const.PackedDriverUniformStorage)
259       NIR_PASS(_, nir, st_nir_lower_builtin);
260 
261    if (!screen->caps.nir_atomics_as_deref)
262       NIR_PASS(_, nir, gl_nir_lower_atomics, shader_program, true);
263 
264    NIR_PASS(_, nir, nir_opt_intrinsics);
265 
266    /* Lower 64-bit ops. */
267    if (nir->options->lower_int64_options ||
268        nir->options->lower_doubles_options) {
269       bool lowered_64bit_ops = false;
270       bool revectorize = false;
271 
272       if (nir->options->lower_doubles_options) {
273          /* nir_lower_doubles is not prepared for vector ops, so if the backend doesn't
274           * request lower_alu_to_scalar until now, lower all 64 bit ops, and try to
275           * vectorize them afterwards again */
276          if (!nir->options->lower_to_scalar) {
277             NIR_PASS(revectorize, nir, nir_lower_alu_to_scalar, filter_64_bit_instr, nullptr);
278             NIR_PASS(revectorize, nir, nir_lower_phis_to_scalar, false);
279          }
280          /* doubles lowering requires frexp to be lowered first if it will be,
281           * since the pass generates other 64-bit ops.  Most backends lower
282           * frexp, and using doubles is rare, and using frexp is even more rare
283           * (no instances in shader-db), so we're not too worried about
284           * accidentally lowering a 32-bit frexp here.
285           */
286          NIR_PASS(lowered_64bit_ops, nir, nir_lower_frexp);
287 
288          NIR_PASS(lowered_64bit_ops, nir, nir_lower_doubles,
289                   st->ctx->SoftFP64, nir->options->lower_doubles_options);
290       }
291       if (nir->options->lower_int64_options)
292          NIR_PASS(lowered_64bit_ops, nir, nir_lower_int64);
293 
294       if (revectorize && !nir->options->vectorize_vec2_16bit)
295          NIR_PASS(_, nir, nir_opt_vectorize, nullptr, nullptr);
296 
297       if (revectorize || lowered_64bit_ops)
298          gl_nir_opts(nir);
299    }
300 
301    nir_variable_mode mask =
302       nir_var_shader_in | nir_var_shader_out | nir_var_function_temp;
303    nir_remove_dead_variables(nir, mask, NULL);
304 
305    if (!st->has_hw_atomics && !screen->caps.nir_atomics_as_deref) {
306       unsigned align_offset_state = 0;
307       if (st->ctx->Const.ShaderStorageBufferOffsetAlignment > 4) {
308          struct gl_program_parameter_list *params = prog->Parameters;
309          for (unsigned i = 0; i < shader_program->data->NumAtomicBuffers; i++) {
310             gl_state_index16 state[STATE_LENGTH] = { STATE_ATOMIC_COUNTER_OFFSET, (short)shader_program->data->AtomicBuffers[i].Binding };
311             _mesa_add_state_reference(params, state);
312          }
313          align_offset_state = STATE_ATOMIC_COUNTER_OFFSET;
314       }
315       NIR_PASS(_, nir, nir_lower_atomics_to_ssbo, align_offset_state);
316    }
317 
318    st_set_prog_affected_state_flags(prog);
319    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
320 
321    char *msg = NULL;
322    if (st->allow_st_finalize_nir_twice) {
323       st_serialize_base_nir(prog, nir);
324       st_finalize_nir(st, prog, shader_program, nir, true, false);
325 
326       if (screen->finalize_nir)
327          msg = screen->finalize_nir(screen, nir);
328    }
329 
330    if (st->ctx->_Shader->Flags & GLSL_DUMP) {
331       _mesa_log("\n");
332       _mesa_log("NIR IR for linked %s program %d:\n",
333              _mesa_shader_stage_to_string(prog->info.stage),
334              shader_program->Name);
335       nir_print_shader(nir, mesa_log_get_file());
336       _mesa_log("\n\n");
337    }
338 
339    return msg;
340 }
341 
342 extern "C" {
343 
344 bool
st_nir_lower_wpos_ytransform(struct nir_shader * nir,struct gl_program * prog,struct pipe_screen * pscreen)345 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
346                              struct gl_program *prog,
347                              struct pipe_screen *pscreen)
348 {
349    bool progress = false;
350 
351    if (nir->info.stage != MESA_SHADER_FRAGMENT) {
352       nir_shader_preserve_all_metadata(nir);
353       return progress;
354    }
355 
356    static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
357       STATE_FB_WPOS_Y_TRANSFORM
358    };
359    nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
360 
361    memcpy(wpos_options.state_tokens, wposTransformState,
362           sizeof(wpos_options.state_tokens));
363    wpos_options.fs_coord_origin_upper_left =
364       pscreen->caps.fs_coord_origin_upper_left;
365    wpos_options.fs_coord_origin_lower_left =
366       pscreen->caps.fs_coord_origin_lower_left;
367    wpos_options.fs_coord_pixel_center_integer =
368       pscreen->caps.fs_coord_pixel_center_integer;
369    wpos_options.fs_coord_pixel_center_half_integer =
370       pscreen->caps.fs_coord_pixel_center_half_integer;
371 
372    if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
373       _mesa_add_state_reference(prog->Parameters, wposTransformState);
374       progress = true;
375    }
376 
377    static const gl_state_index16 pntcTransformState[STATE_LENGTH] = {
378       STATE_FB_PNTC_Y_TRANSFORM
379    };
380 
381    if (nir_lower_pntc_ytransform(nir, &pntcTransformState)) {
382       _mesa_add_state_reference(prog->Parameters, pntcTransformState);
383       progress = true;
384    }
385 
386    return progress;
387 }
388 
389 static bool
st_link_glsl_to_nir(struct gl_context * ctx,struct gl_shader_program * shader_program)390 st_link_glsl_to_nir(struct gl_context *ctx,
391                     struct gl_shader_program *shader_program)
392 {
393    struct st_context *st = st_context(ctx);
394    struct gl_linked_shader *linked_shader[MESA_SHADER_STAGES];
395    unsigned num_shaders = 0;
396 
397    /* Return early if we are loading the shader from on-disk cache */
398    if (st_load_nir_from_disk_cache(ctx, shader_program)) {
399       return GL_TRUE;
400    }
401 
402    MESA_TRACE_FUNC();
403 
404    assert(shader_program->data->LinkStatus);
405 
406    if (!shader_program->data->spirv) {
407       if (!gl_nir_link_glsl(ctx, shader_program))
408          return GL_FALSE;
409    }
410 
411    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
412       if (shader_program->_LinkedShaders[i])
413          linked_shader[num_shaders++] = shader_program->_LinkedShaders[i];
414    }
415 
416    for (unsigned i = 0; i < num_shaders; i++) {
417       struct gl_linked_shader *shader = linked_shader[i];
418       const nir_shader_compiler_options *options =
419          st->ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions;
420       struct gl_program *prog = shader->Program;
421 
422       shader->Program->info.separate_shader = shader_program->SeparateShader;
423       prog->state.type = PIPE_SHADER_IR_NIR;
424 
425       if (shader_program->data->spirv) {
426          /* Parameters will be filled during NIR linking. */
427          prog->Parameters = _mesa_new_parameter_list();
428          prog->shader_program = shader_program;
429 
430          assert(!prog->nir);
431          prog->nir = _mesa_spirv_to_nir(ctx, shader_program, shader->Stage, options);
432       } else {
433          assert(prog->nir);
434          prog->nir->info.name =
435             ralloc_asprintf(shader, "GLSL%d", shader_program->Name);
436          if (shader_program->Label)
437             prog->nir->info.label = ralloc_strdup(shader, shader_program->Label);
438       }
439 
440       nir_shader_gather_info(prog->nir, nir_shader_get_entrypoint(prog->nir));
441       if (!st->ctx->SoftFP64 && ((prog->nir->info.bit_sizes_int | prog->nir->info.bit_sizes_float) & 64) &&
442           (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
443 
444          /* It's not possible to use float64 on GLSL ES, so don't bother trying to
445           * build the support code.  The support code depends on higher versions of
446           * desktop GLSL, so it will fail to compile (below) anyway.
447           */
448          if (_mesa_is_desktop_gl(st->ctx) && st->ctx->Const.GLSLVersion >= 400)
449             st->ctx->SoftFP64 = glsl_float64_funcs_to_nir(st->ctx, options);
450       }
451    }
452 
453    if (shader_program->data->spirv) {
454       static const gl_nir_linker_options opts = {
455          true /*fill_parameters */
456       };
457       if (!gl_nir_link_spirv(&ctx->Const, &ctx->Extensions, shader_program,
458                              &opts))
459          return GL_FALSE;
460    }
461 
462    for (unsigned i = 0; i < num_shaders; i++) {
463       struct gl_program *prog = linked_shader[i]->Program;
464       prog->ExternalSamplersUsed = gl_external_samplers(prog);
465       _mesa_update_shader_textures_used(shader_program, prog);
466    }
467 
468    nir_build_program_resource_list(&ctx->Const, shader_program,
469                                    shader_program->data->spirv);
470 
471    for (unsigned i = 0; i < num_shaders; i++) {
472       struct gl_linked_shader *shader = linked_shader[i];
473       nir_shader *nir = shader->Program->nir;
474       gl_shader_stage stage = shader->Stage;
475       const struct gl_shader_compiler_options *options =
476             &ctx->Const.ShaderCompilerOptions[stage];
477 
478       /* Since IO is lowered, we won't need the IO variables from now on.
479        * nir_build_program_resource_list was the last pass that needed them.
480        */
481       NIR_PASS_V(nir, nir_remove_dead_variables,
482                  nir_var_shader_in | nir_var_shader_out, NULL);
483 
484       /* If there are forms of indirect addressing that the driver
485        * cannot handle, perform the lowering pass.
486        */
487       if (options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
488          nir_variable_mode mode = (nir_variable_mode)0;
489 
490          mode |= options->EmitNoIndirectTemp ?
491             nir_var_function_temp : (nir_variable_mode)0;
492          mode |= options->EmitNoIndirectUniform ?
493             nir_var_uniform | nir_var_mem_ubo | nir_var_mem_ssbo :
494             (nir_variable_mode)0;
495 
496          if (mode)
497             nir_lower_indirect_derefs(nir, mode, UINT32_MAX);
498       }
499 
500       /* This needs to run after the initial pass of nir_lower_vars_to_ssa, so
501        * that the buffer indices are constants in nir where they where
502        * constants in GLSL. */
503       NIR_PASS(_, nir, gl_nir_lower_buffers, shader_program);
504 
505       NIR_PASS(_, nir, st_nir_lower_wpos_ytransform, shader->Program,
506                st->screen);
507 
508       /* needed to lower base_workgroup_id and base_global_invocation_id */
509       struct nir_lower_compute_system_values_options cs_options = {};
510       NIR_PASS(_, nir, nir_lower_system_values);
511       NIR_PASS(_, nir, nir_lower_compute_system_values, &cs_options);
512    }
513 
514    struct shader_info *prev_info = NULL;
515 
516    for (unsigned i = 0; i < num_shaders; i++) {
517       struct gl_linked_shader *shader = linked_shader[i];
518       struct shader_info *info = &shader->Program->nir->info;
519 
520       char *msg = st_glsl_to_nir_post_opts(st, shader->Program, shader_program);
521       if (msg) {
522          linker_error(shader_program, msg);
523          return false;
524       }
525 
526       if (prev_info &&
527           ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->unify_interfaces) {
528          prev_info->outputs_written |= info->inputs_read &
529             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
530          info->inputs_read |= prev_info->outputs_written &
531             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
532 
533          prev_info->patch_outputs_written |= info->patch_inputs_read;
534          info->patch_inputs_read |= prev_info->patch_outputs_written;
535       }
536       prev_info = info;
537    }
538 
539    /* Get TCS and TES shader info. */
540    struct shader_info *tcs_info = NULL, *tes_info = NULL;
541 
542    for (unsigned i = 0; i < num_shaders; i++) {
543       struct gl_linked_shader *shader = linked_shader[i];
544       struct shader_info *info = &shader->Program->nir->info;
545 
546       if (info->stage == MESA_SHADER_TESS_CTRL)
547          tcs_info = info;
548       else if (info->stage == MESA_SHADER_TESS_EVAL)
549          tes_info = info;
550    }
551 
552    /* Copy some fields from TES to TCS shader info because some drivers
553     * (radeonsi) need them in TCS.
554     */
555    if (tcs_info && tes_info) {
556       tcs_info->tess._primitive_mode = tes_info->tess._primitive_mode;
557       tcs_info->tess.spacing = tes_info->tess.spacing;
558    }
559 
560    for (unsigned i = 0; i < num_shaders; i++) {
561       struct gl_linked_shader *shader = linked_shader[i];
562       struct gl_program *prog = shader->Program;
563 
564       /* Make sure that prog->info is in sync with nir->info, but st/mesa
565        * expects some of the values to be from before lowering.
566        */
567       shader_info old_info = prog->info;
568       prog->info = prog->nir->info;
569       prog->info.name = old_info.name;
570       prog->info.label = old_info.label;
571       prog->info.num_ssbos = old_info.num_ssbos;
572       prog->info.num_ubos = old_info.num_ubos;
573       prog->info.num_abos = old_info.num_abos;
574 
575       if (prog->info.stage == MESA_SHADER_VERTEX) {
576          prog->info.inputs_read = prog->nir->info.inputs_read;
577          prog->DualSlotInputs = prog->nir->info.dual_slot_inputs;
578 
579          /* Initialize st_vertex_program members. */
580          st_prepare_vertex_program(prog);
581       }
582 
583       /* Get pipe_stream_output_info. */
584       if (shader->Stage == MESA_SHADER_VERTEX ||
585           shader->Stage == MESA_SHADER_TESS_EVAL ||
586           shader->Stage == MESA_SHADER_GEOMETRY)
587          st_translate_stream_output_info(prog);
588 
589       st_store_nir_in_disk_cache(st, prog);
590 
591       st_release_variants(st, prog);
592       char *error = st_finalize_program(st, prog, true);
593 
594       if (error) {
595          linker_error(shader_program, error);
596          free(error);
597          return false;
598       }
599    }
600 
601    struct pipe_context *pctx = st_context(ctx)->pipe;
602    if (pctx->link_shader) {
603       void *driver_handles[PIPE_SHADER_TYPES];
604       memset(driver_handles, 0, sizeof(driver_handles));
605 
606       for (uint32_t i = 0; i < MESA_SHADER_STAGES; ++i) {
607          struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
608          if (shader) {
609             struct gl_program *p = shader->Program;
610             if (p && p->variants) {
611                enum pipe_shader_type type = pipe_shader_type_from_mesa(shader->Stage);
612                driver_handles[type] = p->variants->driver_shader;
613             }
614          }
615       }
616 
617       pctx->link_shader(pctx, driver_handles);
618    }
619 
620    return true;
621 }
622 
623 void
st_nir_lower_samplers(struct pipe_screen * screen,nir_shader * nir,struct gl_shader_program * shader_program,struct gl_program * prog)624 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
625                       struct gl_shader_program *shader_program,
626                       struct gl_program *prog)
627 {
628    if (screen->caps.nir_samplers_as_deref)
629       NIR_PASS(_, nir, gl_nir_lower_samplers_as_deref, shader_program);
630    else
631       NIR_PASS(_, nir, gl_nir_lower_samplers, shader_program);
632 
633    if (prog) {
634       BITSET_COPY(prog->info.textures_used, nir->info.textures_used);
635       BITSET_COPY(prog->info.textures_used_by_txf, nir->info.textures_used_by_txf);
636       BITSET_COPY(prog->info.samplers_used, nir->info.samplers_used);
637       BITSET_COPY(prog->info.images_used, nir->info.images_used);
638       BITSET_COPY(prog->info.image_buffers, nir->info.image_buffers);
639       BITSET_COPY(prog->info.msaa_images, nir->info.msaa_images);
640    }
641 }
642 
643 static int
st_packed_uniforms_type_size(const struct glsl_type * type,bool bindless)644 st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
645 {
646    return glsl_count_dword_slots(type, bindless);
647 }
648 
649 static int
st_unpacked_uniforms_type_size(const struct glsl_type * type,bool bindless)650 st_unpacked_uniforms_type_size(const struct glsl_type *type, bool bindless)
651 {
652    return glsl_count_vec4_slots(type, false, bindless);
653 }
654 
655 void
st_nir_lower_uniforms(struct st_context * st,nir_shader * nir)656 st_nir_lower_uniforms(struct st_context *st, nir_shader *nir)
657 {
658    if (st->ctx->Const.PackedDriverUniformStorage) {
659       NIR_PASS(_, nir, nir_lower_io, nir_var_uniform,
660                  st_packed_uniforms_type_size,
661                  (nir_lower_io_options)0);
662    } else {
663       NIR_PASS(_, nir, nir_lower_io, nir_var_uniform,
664                  st_unpacked_uniforms_type_size,
665                  (nir_lower_io_options)0);
666    }
667 
668    if (nir->options->lower_uniforms_to_ubo)
669       NIR_PASS(_, nir, nir_lower_uniforms_to_ubo,
670                  st->ctx->Const.PackedDriverUniformStorage,
671                  !st->ctx->Const.NativeIntegers);
672 }
673 
674 /* Last third of preparing nir from glsl, which happens after shader
675  * variant lowering.
676  */
677 void
st_finalize_nir(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,nir_shader * nir,bool is_before_variants,bool is_draw_shader)678 st_finalize_nir(struct st_context *st, struct gl_program *prog,
679                 struct gl_shader_program *shader_program, nir_shader *nir,
680                 bool is_before_variants, bool is_draw_shader)
681 {
682    struct pipe_screen *screen = st->screen;
683 
684    MESA_TRACE_FUNC();
685 
686    const bool lower_tg4_offsets =
687       !is_draw_shader && !st->screen->caps.texture_gather_offsets;
688 
689    if (!is_draw_shader && (st->lower_rect_tex || lower_tg4_offsets)) {
690       struct nir_lower_tex_options opts = {0};
691       opts.lower_rect = !!st->lower_rect_tex;
692       opts.lower_tg4_offsets = lower_tg4_offsets;
693 
694       NIR_PASS(_, nir, nir_lower_tex, &opts);
695    }
696 
697    st_nir_assign_uniform_locations(st->ctx, prog, nir);
698 
699    /* Set num_uniforms in number of attribute slots (vec4s) */
700    nir->num_uniforms = DIV_ROUND_UP(prog->Parameters->NumParameterValues, 4);
701 
702    st_nir_lower_uniforms(st, nir);
703 
704    if (!is_draw_shader && is_before_variants && nir->options->lower_uniforms_to_ubo) {
705       /* This must be done after uniforms are lowered to UBO and all
706        * nir_var_uniform variables are removed from NIR to prevent conflicts
707        * between state parameter merging and shader variant generation.
708        */
709       _mesa_optimize_state_parameters(&st->ctx->Const, prog->Parameters);
710    }
711 
712    st_nir_lower_samplers(screen, nir, shader_program, prog);
713    if (!is_draw_shader && !screen->caps.nir_images_as_deref)
714       NIR_PASS(_, nir, gl_nir_lower_images, false);
715 }
716 
717 /**
718  * Link a GLSL shader program.  Called via glLinkProgram().
719  */
720 void
st_link_shader(struct gl_context * ctx,struct gl_shader_program * prog)721 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
722 {
723    unsigned int i;
724    bool spirv = false;
725 
726    MESA_TRACE_FUNC();
727 
728    _mesa_clear_shader_program_data(ctx, prog);
729 
730    prog->data = _mesa_create_shader_program_data();
731 
732    prog->data->LinkStatus = LINKING_SUCCESS;
733 
734    for (i = 0; i < prog->NumShaders; i++) {
735       if (!prog->Shaders[i]->CompileStatus) {
736 	 linker_error(prog, "linking with uncompiled/unspecialized shader");
737       }
738 
739       if (!i) {
740          spirv = (prog->Shaders[i]->spirv_data != NULL);
741       } else if (spirv && !prog->Shaders[i]->spirv_data) {
742          /* The GL_ARB_gl_spirv spec adds a new bullet point to the list of
743           * reasons LinkProgram can fail:
744           *
745           *    "All the shader objects attached to <program> do not have the
746           *     same value for the SPIR_V_BINARY_ARB state."
747           */
748          linker_error(prog,
749                       "not all attached shaders have the same "
750                       "SPIR_V_BINARY_ARB state");
751       }
752    }
753    prog->data->spirv = spirv;
754 
755    if (prog->data->LinkStatus) {
756       if (!spirv) {
757          link_shaders_init(ctx, prog);
758 
759 #ifdef ENABLE_SHADER_CACHE
760          shader_cache_read_program_metadata(ctx, prog);
761 #endif
762       } else
763          _mesa_spirv_link_shaders(ctx, prog);
764    }
765 
766    /* If LinkStatus is LINKING_SUCCESS, then reset sampler validated to true.
767     * Validation happens via the LinkShader call below. If LinkStatus is
768     * LINKING_SKIPPED, then SamplersValidated will have been restored from the
769     * shader cache.
770     */
771    if (prog->data->LinkStatus == LINKING_SUCCESS) {
772       prog->SamplersValidated = GL_TRUE;
773    }
774 
775    if (prog->data->LinkStatus && !st_link_glsl_to_nir(ctx, prog)) {
776       prog->data->LinkStatus = LINKING_FAILURE;
777    }
778 
779    if (prog->data->LinkStatus != LINKING_FAILURE)
780       _mesa_create_program_resource_hash(prog);
781 
782    /* Return early if we are loading the shader from on-disk cache */
783    if (prog->data->LinkStatus == LINKING_SKIPPED)
784       return;
785 
786    if (ctx->_Shader->Flags & GLSL_DUMP) {
787       if (!prog->data->LinkStatus) {
788 	 fprintf(stderr, "GLSL shader program %d failed to link\n", prog->Name);
789       }
790 
791       if (prog->data->InfoLog && prog->data->InfoLog[0] != 0) {
792 	 fprintf(stderr, "GLSL shader program %d info log:\n", prog->Name);
793          fprintf(stderr, "%s\n", prog->data->InfoLog);
794       }
795    }
796 
797 #ifdef ENABLE_SHADER_CACHE
798    if (prog->data->LinkStatus)
799       shader_cache_write_program_metadata(ctx, prog);
800 #endif
801 }
802 
803 } /* extern "C" */
804