st/glsl_to_nir: disable st_nir_lower_builtin() when packing supported
[mesa.git] / src / mesa / state_tracker / st_glsl_to_nir.cpp
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 "program/ir_to_mesa.h"
34 #include "main/context.h"
35 #include "main/mtypes.h"
36 #include "main/errors.h"
37 #include "main/glspirv.h"
38 #include "main/shaderapi.h"
39 #include "main/uniforms.h"
40
41 #include "main/shaderobj.h"
42 #include "st_context.h"
43 #include "st_program.h"
44 #include "st_shader_cache.h"
45
46 #include "compiler/nir/nir.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/string_to_uint_map.h"
54
55 static int
56 type_size(const struct glsl_type *type)
57 {
58 return type->count_attribute_slots(false);
59 }
60
61 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
62 * may need to fix up varying slots so the glsl->nir path is aligned
63 * with the anything->tgsi->nir path.
64 */
65 static void
66 st_nir_fixup_varying_slots(struct st_context *st, struct exec_list *var_list)
67 {
68 if (st->needs_texcoord_semantic)
69 return;
70
71 nir_foreach_variable(var, var_list) {
72 if (var->data.location >= VARYING_SLOT_VAR0) {
73 var->data.location += 9;
74 } else if (var->data.location == VARYING_SLOT_PNTC) {
75 var->data.location = VARYING_SLOT_VAR8;
76 } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
77 (var->data.location <= VARYING_SLOT_TEX7)) {
78 var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
79 }
80 }
81 }
82
83 static void
84 st_shader_gather_info(nir_shader *nir, struct gl_program *prog)
85 {
86 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
87
88 /* Copy the info we just generated back into the gl_program */
89 const char *prog_name = prog->info.name;
90 const char *prog_label = prog->info.label;
91 prog->info = nir->info;
92 prog->info.name = prog_name;
93 prog->info.label = prog_label;
94 }
95
96 /* input location assignment for VS inputs must be handled specially, so
97 * that it is aligned w/ st's vbo state.
98 * (This isn't the case with, for ex, FS inputs, which only need to agree
99 * on varying-slot w/ the VS outputs)
100 */
101 void
102 st_nir_assign_vs_in_locations(struct nir_shader *nir)
103 {
104 if (nir->info.stage != MESA_SHADER_VERTEX)
105 return;
106
107 bool removed_inputs = false;
108
109 nir->num_inputs = util_bitcount64(nir->info.inputs_read);
110 nir_foreach_variable_safe(var, &nir->inputs) {
111 /* NIR already assigns dual-slot inputs to two locations so all we have
112 * to do is compact everything down.
113 */
114 if (nir->info.inputs_read & BITFIELD64_BIT(var->data.location)) {
115 var->data.driver_location =
116 util_bitcount64(nir->info.inputs_read &
117 BITFIELD64_MASK(var->data.location));
118 } else {
119 /* Move unused input variables to the globals list (with no
120 * initialization), to avoid confusing drivers looking through the
121 * inputs array and expecting to find inputs with a driver_location
122 * set.
123 */
124 exec_node_remove(&var->node);
125 var->data.mode = nir_var_shader_temp;
126 exec_list_push_tail(&nir->globals, &var->node);
127 removed_inputs = true;
128 }
129 }
130
131 /* Re-lower global vars, to deal with any dead VS inputs. */
132 if (removed_inputs)
133 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
134 }
135
136 static int
137 st_nir_lookup_parameter_index(struct gl_program *prog, nir_variable *var)
138 {
139 struct gl_program_parameter_list *params = prog->Parameters;
140
141 /* Lookup the first parameter that the uniform storage that match the
142 * variable location.
143 */
144 for (unsigned i = 0; i < params->NumParameters; i++) {
145 int index = params->Parameters[i].MainUniformStorageIndex;
146 if (index == var->data.location)
147 return i;
148 }
149
150 /* TODO: Handle this fallback for SPIR-V. We need this for GLSL e.g. in
151 * dEQP-GLES2.functional.uniform_api.random.3
152 */
153
154 /* is there a better way to do this? If we have something like:
155 *
156 * struct S {
157 * float f;
158 * vec4 v;
159 * };
160 * uniform S color;
161 *
162 * Then what we get in prog->Parameters looks like:
163 *
164 * 0: Name=color.f, Type=6, DataType=1406, Size=1
165 * 1: Name=color.v, Type=6, DataType=8b52, Size=4
166 *
167 * So the name doesn't match up and _mesa_lookup_parameter_index()
168 * fails. In this case just find the first matching "color.*"..
169 *
170 * Note for arrays you could end up w/ color[n].f, for example.
171 *
172 * glsl_to_tgsi works slightly differently in this regard. It is
173 * emitting something more low level, so it just translates the
174 * params list 1:1 to CONST[] regs. Going from GLSL IR to TGSI,
175 * it just calculates the additional offset of struct field members
176 * in glsl_to_tgsi_visitor::visit(ir_dereference_record *ir) or
177 * glsl_to_tgsi_visitor::visit(ir_dereference_array *ir). It never
178 * needs to work backwards to get base var loc from the param-list
179 * which already has them separated out.
180 */
181 if (!prog->sh.data->spirv) {
182 int namelen = strlen(var->name);
183 for (unsigned i = 0; i < params->NumParameters; i++) {
184 struct gl_program_parameter *p = &params->Parameters[i];
185 if ((strncmp(p->Name, var->name, namelen) == 0) &&
186 ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
187 return i;
188 }
189 }
190 }
191
192 return -1;
193 }
194
195 static void
196 st_nir_assign_uniform_locations(struct gl_context *ctx,
197 struct gl_program *prog,
198 struct exec_list *uniform_list)
199 {
200 int shaderidx = 0;
201 int imageidx = 0;
202
203 nir_foreach_variable(uniform, uniform_list) {
204 int loc;
205
206 /*
207 * UBO's have their own address spaces, so don't count them towards the
208 * number of global uniforms
209 */
210 if (uniform->data.mode == nir_var_mem_ubo || uniform->data.mode == nir_var_mem_ssbo)
211 continue;
212
213 const struct glsl_type *type = glsl_without_array(uniform->type);
214 if (!uniform->data.bindless && (type->is_sampler() || type->is_image())) {
215 if (type->is_sampler()) {
216 loc = shaderidx;
217 shaderidx += type_size(uniform->type);
218 } else {
219 loc = imageidx;
220 imageidx += type_size(uniform->type);
221 }
222 } else if (uniform->state_slots) {
223 const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
224 /* This state reference has already been setup by ir_to_mesa, but we'll
225 * get the same index back here.
226 */
227
228 unsigned comps;
229 if (glsl_type_is_struct_or_ifc(type)) {
230 comps = 4;
231 } else {
232 comps = glsl_get_vector_elements(type);
233 }
234
235 if (ctx->Const.PackedDriverUniformStorage) {
236 loc = _mesa_add_sized_state_reference(prog->Parameters,
237 stateTokens, comps, false);
238 loc = prog->Parameters->ParameterValueOffset[loc];
239 } else {
240 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
241 }
242 } else {
243 loc = st_nir_lookup_parameter_index(prog, uniform);
244
245 /* We need to check that loc is not -1 here before accessing the
246 * array. It can be negative for example when we have a struct that
247 * only contains opaque types.
248 */
249 if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
250 loc = prog->Parameters->ParameterValueOffset[loc];
251 }
252 }
253
254 uniform->data.driver_location = loc;
255 }
256 }
257
258 void
259 st_nir_opts(nir_shader *nir)
260 {
261 bool progress;
262
263 do {
264 progress = false;
265
266 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
267
268 /* Linking deals with unused inputs/outputs, but here we can remove
269 * things local to the shader in the hopes that we can cleanup other
270 * things. This pass will also remove variables with only stores, so we
271 * might be able to make progress after it.
272 */
273 NIR_PASS(progress, nir, nir_remove_dead_variables,
274 (nir_variable_mode)(nir_var_function_temp |
275 nir_var_shader_temp |
276 nir_var_mem_shared),
277 NULL);
278
279 NIR_PASS(progress, nir, nir_opt_copy_prop_vars);
280 NIR_PASS(progress, nir, nir_opt_dead_write_vars);
281
282 if (nir->options->lower_to_scalar) {
283 NIR_PASS_V(nir, nir_lower_alu_to_scalar, NULL, NULL);
284 NIR_PASS_V(nir, nir_lower_phis_to_scalar);
285 }
286
287 NIR_PASS_V(nir, nir_lower_alu);
288 NIR_PASS_V(nir, nir_lower_pack);
289 NIR_PASS(progress, nir, nir_copy_prop);
290 NIR_PASS(progress, nir, nir_opt_remove_phis);
291 NIR_PASS(progress, nir, nir_opt_dce);
292 if (nir_opt_trivial_continues(nir)) {
293 progress = true;
294 NIR_PASS(progress, nir, nir_copy_prop);
295 NIR_PASS(progress, nir, nir_opt_dce);
296 }
297 NIR_PASS(progress, nir, nir_opt_if, false);
298 NIR_PASS(progress, nir, nir_opt_dead_cf);
299 NIR_PASS(progress, nir, nir_opt_cse);
300 NIR_PASS(progress, nir, nir_opt_peephole_select, 8, true, true);
301
302 NIR_PASS(progress, nir, nir_opt_algebraic);
303 NIR_PASS(progress, nir, nir_opt_constant_folding);
304
305 if (!nir->info.flrp_lowered) {
306 unsigned lower_flrp =
307 (nir->options->lower_flrp16 ? 16 : 0) |
308 (nir->options->lower_flrp32 ? 32 : 0) |
309 (nir->options->lower_flrp64 ? 64 : 0);
310
311 if (lower_flrp) {
312 bool lower_flrp_progress = false;
313
314 NIR_PASS(lower_flrp_progress, nir, nir_lower_flrp,
315 lower_flrp,
316 false /* always_precise */,
317 nir->options->lower_ffma);
318 if (lower_flrp_progress) {
319 NIR_PASS(progress, nir,
320 nir_opt_constant_folding);
321 progress = true;
322 }
323 }
324
325 /* Nothing should rematerialize any flrps, so we only need to do this
326 * lowering once.
327 */
328 nir->info.flrp_lowered = true;
329 }
330
331 NIR_PASS(progress, nir, nir_opt_undef);
332 NIR_PASS(progress, nir, nir_opt_conditional_discard);
333 if (nir->options->max_unroll_iterations) {
334 NIR_PASS(progress, nir, nir_opt_loop_unroll, (nir_variable_mode)0);
335 }
336 } while (progress);
337 }
338
339 static void
340 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
341 {
342 assert(glsl_type_is_vector_or_scalar(type));
343
344 uint32_t comp_size = glsl_type_is_boolean(type)
345 ? 4 : glsl_get_bit_size(type) / 8;
346 unsigned length = glsl_get_vector_elements(type);
347 *size = comp_size * length,
348 *align = comp_size * (length == 3 ? 4 : length);
349 }
350
351 /* First third of converting glsl_to_nir.. this leaves things in a pre-
352 * nir_lower_io state, so that shader variants can more easily insert/
353 * replace variables, etc.
354 */
355 static void
356 st_nir_preprocess(struct st_context *st, struct gl_program *prog,
357 struct gl_shader_program *shader_program,
358 gl_shader_stage stage)
359 {
360 struct pipe_screen *screen = st->pipe->screen;
361 const nir_shader_compiler_options *options =
362 st->ctx->Const.ShaderCompilerOptions[prog->info.stage].NirOptions;
363 assert(options);
364 nir_shader *nir = prog->nir;
365
366 /* Set the next shader stage hint for VS and TES. */
367 if (!nir->info.separate_shader &&
368 (nir->info.stage == MESA_SHADER_VERTEX ||
369 nir->info.stage == MESA_SHADER_TESS_EVAL)) {
370
371 unsigned prev_stages = (1 << (prog->info.stage + 1)) - 1;
372 unsigned stages_mask =
373 ~prev_stages & shader_program->data->linked_stages;
374
375 nir->info.next_stage = stages_mask ?
376 (gl_shader_stage) u_bit_scan(&stages_mask) : MESA_SHADER_FRAGMENT;
377 } else {
378 nir->info.next_stage = MESA_SHADER_FRAGMENT;
379 }
380
381 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
382 if (!st->ctx->SoftFP64 && nir->info.uses_64bit &&
383 (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
384 st->ctx->SoftFP64 = glsl_float64_funcs_to_nir(st->ctx, options);
385 }
386
387 /* ES has strict SSO validation rules for shader IO matching so we can't
388 * remove dead IO until the resource list has been built. Here we skip
389 * removing them until later. This will potentially make the IO lowering
390 * calls below do a little extra work but should otherwise have no impact.
391 */
392 if (!_mesa_is_gles(st->ctx) || !nir->info.separate_shader) {
393 nir_variable_mode mask =
394 (nir_variable_mode) (nir_var_shader_in | nir_var_shader_out);
395 nir_remove_dead_variables(nir, mask, NULL);
396 }
397
398 if (options->lower_all_io_to_temps ||
399 nir->info.stage == MESA_SHADER_VERTEX ||
400 nir->info.stage == MESA_SHADER_GEOMETRY) {
401 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
402 nir_shader_get_entrypoint(nir),
403 true, true);
404 } else if (nir->info.stage == MESA_SHADER_FRAGMENT ||
405 !screen->get_param(screen, PIPE_CAP_TGSI_CAN_READ_OUTPUTS)) {
406 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
407 nir_shader_get_entrypoint(nir),
408 true, false);
409 }
410
411 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
412 NIR_PASS_V(nir, nir_split_var_copies);
413 NIR_PASS_V(nir, nir_lower_var_copies);
414
415 if (options->lower_to_scalar) {
416 NIR_PASS_V(nir, nir_lower_alu_to_scalar, NULL, NULL);
417 }
418
419 /* before buffers and vars_to_ssa */
420 NIR_PASS_V(nir, gl_nir_lower_images, true);
421
422 /* TODO: Change GLSL to not lower shared memory. */
423 if (prog->nir->info.stage == MESA_SHADER_COMPUTE &&
424 shader_program->data->spirv) {
425 NIR_PASS_V(prog->nir, nir_lower_vars_to_explicit_types,
426 nir_var_mem_shared, shared_type_info);
427 NIR_PASS_V(prog->nir, nir_lower_explicit_io,
428 nir_var_mem_shared, nir_address_format_32bit_offset);
429 }
430
431 /* Do a round of constant folding to clean up address calculations */
432 NIR_PASS_V(nir, nir_opt_constant_folding);
433 }
434
435 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
436 * info on varyings, etc after NIR link time opts have been applied.
437 */
438 static void
439 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
440 struct gl_shader_program *shader_program)
441 {
442 nir_shader *nir = prog->nir;
443
444 /* Make a pass over the IR to add state references for any built-in
445 * uniforms that are used. This has to be done now (during linking).
446 * Code generation doesn't happen until the first time this shader is
447 * used for rendering. Waiting until then to generate the parameters is
448 * too late. At that point, the values for the built-in uniforms won't
449 * get sent to the shader.
450 */
451 nir_foreach_variable(var, &nir->uniforms) {
452 const nir_state_slot *const slots = var->state_slots;
453 if (slots != NULL) {
454 const struct glsl_type *type = glsl_without_array(var->type);
455 for (unsigned int i = 0; i < var->num_state_slots; i++) {
456 unsigned comps;
457 if (glsl_type_is_struct_or_ifc(type)) {
458 comps = _mesa_program_state_value_size(slots[i].tokens);
459 } else {
460 comps = glsl_get_vector_elements(type);
461 }
462
463 if (st->ctx->Const.PackedDriverUniformStorage) {
464 _mesa_add_sized_state_reference(prog->Parameters,
465 slots[i].tokens,
466 comps, false);
467 } else {
468 _mesa_add_state_reference(prog->Parameters,
469 slots[i].tokens);
470 }
471 }
472 }
473 }
474
475 /* Avoid reallocation of the program parameter list, because the uniform
476 * storage is only associated with the original parameter list.
477 * This should be enough for Bitmap and DrawPixels constants.
478 */
479 _mesa_reserve_parameter_storage(prog->Parameters, 8);
480
481 /* This has to be done last. Any operation the can cause
482 * prog->ParameterValues to get reallocated (e.g., anything that adds a
483 * program constant) has to happen before creating this linkage.
484 */
485 _mesa_associate_uniform_storage(st->ctx, shader_program, prog);
486
487 st_set_prog_affected_state_flags(prog);
488
489 /* None of the builtins being lowered here can be produced by SPIR-V. See
490 * _mesa_builtin_uniform_desc. Also drivers that support packed uniform
491 * storage don't need to lower builtins.
492 */
493 if (!shader_program->data->spirv &&
494 !st->ctx->Const.PackedDriverUniformStorage)
495 NIR_PASS_V(nir, st_nir_lower_builtin);
496
497 NIR_PASS_V(nir, gl_nir_lower_atomics, shader_program, true);
498 NIR_PASS_V(nir, nir_opt_intrinsics);
499
500 /* Lower 64-bit ops. */
501 if (nir->options->lower_int64_options ||
502 nir->options->lower_doubles_options) {
503 bool lowered_64bit_ops = false;
504 if (nir->options->lower_doubles_options) {
505 NIR_PASS(lowered_64bit_ops, nir, nir_lower_doubles,
506 st->ctx->SoftFP64, nir->options->lower_doubles_options);
507 }
508 if (nir->options->lower_int64_options) {
509 NIR_PASS(lowered_64bit_ops, nir, nir_lower_int64,
510 nir->options->lower_int64_options);
511 }
512
513 if (lowered_64bit_ops)
514 st_nir_opts(nir);
515 }
516
517 nir_variable_mode mask = (nir_variable_mode)
518 (nir_var_shader_in | nir_var_shader_out | nir_var_function_temp );
519 nir_remove_dead_variables(nir, mask, NULL);
520
521 if (!st->has_hw_atomics)
522 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo);
523
524 st_finalize_nir_before_variants(nir);
525
526 if (st->allow_st_finalize_nir_twice)
527 st_finalize_nir(st, prog, shader_program, nir, true);
528
529 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
530 _mesa_log("\n");
531 _mesa_log("NIR IR for linked %s program %d:\n",
532 _mesa_shader_stage_to_string(prog->info.stage),
533 shader_program->Name);
534 nir_print_shader(nir, _mesa_get_log_file());
535 _mesa_log("\n\n");
536 }
537 }
538
539 static void
540 st_nir_vectorize_io(nir_shader *producer, nir_shader *consumer)
541 {
542 NIR_PASS_V(producer, nir_lower_io_to_vector, nir_var_shader_out);
543 NIR_PASS_V(producer, nir_opt_combine_stores, nir_var_shader_out);
544 NIR_PASS_V(consumer, nir_lower_io_to_vector, nir_var_shader_in);
545
546 if ((producer)->info.stage != MESA_SHADER_TESS_CTRL) {
547 /* Calling lower_io_to_vector creates output variable writes with
548 * write-masks. We only support these for TCS outputs, so for other
549 * stages, we need to call nir_lower_io_to_temporaries to get rid of
550 * them. This, in turn, creates temporary variables and extra
551 * copy_deref intrinsics that we need to clean up.
552 */
553 NIR_PASS_V(producer, nir_lower_io_to_temporaries,
554 nir_shader_get_entrypoint(producer), true, false);
555 NIR_PASS_V(producer, nir_lower_global_vars_to_local);
556 NIR_PASS_V(producer, nir_split_var_copies);
557 NIR_PASS_V(producer, nir_lower_var_copies);
558 }
559 }
560
561 static void
562 st_nir_link_shaders(nir_shader *producer, nir_shader *consumer)
563 {
564 if (producer->options->lower_to_scalar) {
565 NIR_PASS_V(producer, nir_lower_io_to_scalar_early, nir_var_shader_out);
566 NIR_PASS_V(consumer, nir_lower_io_to_scalar_early, nir_var_shader_in);
567 }
568
569 nir_lower_io_arrays_to_elements(producer, consumer);
570
571 st_nir_opts(producer);
572 st_nir_opts(consumer);
573
574 if (nir_link_opt_varyings(producer, consumer))
575 st_nir_opts(consumer);
576
577 NIR_PASS_V(producer, nir_remove_dead_variables, nir_var_shader_out, NULL);
578 NIR_PASS_V(consumer, nir_remove_dead_variables, nir_var_shader_in, NULL);
579
580 if (nir_remove_unused_varyings(producer, consumer)) {
581 NIR_PASS_V(producer, nir_lower_global_vars_to_local);
582 NIR_PASS_V(consumer, nir_lower_global_vars_to_local);
583
584 st_nir_opts(producer);
585 st_nir_opts(consumer);
586
587 /* Optimizations can cause varyings to become unused.
588 * nir_compact_varyings() depends on all dead varyings being removed so
589 * we need to call nir_remove_dead_variables() again here.
590 */
591 NIR_PASS_V(producer, nir_remove_dead_variables, nir_var_shader_out,
592 NULL);
593 NIR_PASS_V(consumer, nir_remove_dead_variables, nir_var_shader_in,
594 NULL);
595 }
596 }
597
598 static void
599 st_lower_patch_vertices_in(struct gl_shader_program *shader_prog)
600 {
601 struct gl_linked_shader *linked_tcs =
602 shader_prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
603 struct gl_linked_shader *linked_tes =
604 shader_prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
605
606 /* If we have a TCS and TES linked together, lower TES patch vertices. */
607 if (linked_tcs && linked_tes) {
608 nir_shader *tcs_nir = linked_tcs->Program->nir;
609 nir_shader *tes_nir = linked_tes->Program->nir;
610
611 /* The TES input vertex count is the TCS output vertex count,
612 * lower TES gl_PatchVerticesIn to a constant.
613 */
614 uint32_t tes_patch_verts = tcs_nir->info.tess.tcs_vertices_out;
615 NIR_PASS_V(tes_nir, nir_lower_patch_vertices, tes_patch_verts, NULL);
616 }
617 }
618
619 extern "C" {
620
621 void
622 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
623 struct gl_program *prog,
624 struct pipe_screen *pscreen)
625 {
626 if (nir->info.stage != MESA_SHADER_FRAGMENT)
627 return;
628
629 static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
630 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
631 };
632 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
633
634 memcpy(wpos_options.state_tokens, wposTransformState,
635 sizeof(wpos_options.state_tokens));
636 wpos_options.fs_coord_origin_upper_left =
637 pscreen->get_param(pscreen,
638 PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
639 wpos_options.fs_coord_origin_lower_left =
640 pscreen->get_param(pscreen,
641 PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
642 wpos_options.fs_coord_pixel_center_integer =
643 pscreen->get_param(pscreen,
644 PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
645 wpos_options.fs_coord_pixel_center_half_integer =
646 pscreen->get_param(pscreen,
647 PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
648
649 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
650 nir_validate_shader(nir, "after nir_lower_wpos_ytransform");
651 _mesa_add_state_reference(prog->Parameters, wposTransformState);
652 }
653 }
654
655 bool
656 st_link_nir(struct gl_context *ctx,
657 struct gl_shader_program *shader_program)
658 {
659 struct st_context *st = st_context(ctx);
660 struct gl_linked_shader *linked_shader[MESA_SHADER_STAGES];
661 unsigned num_shaders = 0;
662
663 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
664 if (shader_program->_LinkedShaders[i])
665 linked_shader[num_shaders++] = shader_program->_LinkedShaders[i];
666 }
667
668 for (unsigned i = 0; i < num_shaders; i++) {
669 struct gl_linked_shader *shader = linked_shader[i];
670 const nir_shader_compiler_options *options =
671 st->ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions;
672 struct gl_program *prog = shader->Program;
673 struct st_program *stp = (struct st_program *)prog;
674
675 _mesa_copy_linked_program_data(shader_program, shader);
676
677 assert(!prog->nir);
678 stp->shader_program = shader_program;
679 stp->state.type = PIPE_SHADER_IR_NIR;
680
681 /* Parameters will be filled during NIR linking. */
682 prog->Parameters = _mesa_new_parameter_list();
683
684 if (shader_program->data->spirv) {
685 prog->nir = _mesa_spirv_to_nir(ctx, shader_program, shader->Stage, options);
686 } else {
687 validate_ir_tree(shader->ir);
688
689 if (ctx->_Shader->Flags & GLSL_DUMP) {
690 _mesa_log("\n");
691 _mesa_log("GLSL IR for linked %s program %d:\n",
692 _mesa_shader_stage_to_string(shader->Stage),
693 shader_program->Name);
694 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
695 _mesa_log("\n\n");
696 }
697
698 prog->nir = glsl_to_nir(st->ctx, shader_program, shader->Stage, options);
699 st_nir_preprocess(st, prog, shader_program, shader->Stage);
700 }
701
702 if (options->lower_to_scalar) {
703 NIR_PASS_V(shader->Program->nir, nir_lower_load_const_to_scalar);
704 }
705 }
706
707 st_lower_patch_vertices_in(shader_program);
708
709 /* For SPIR-V, we have to perform the NIR linking before applying
710 * st_nir_preprocess.
711 */
712 if (shader_program->data->spirv) {
713 static const gl_nir_linker_options opts = {
714 true /*fill_parameters */
715 };
716 if (!gl_nir_link_spirv(ctx, shader_program, &opts))
717 return GL_FALSE;
718
719 nir_build_program_resource_list(ctx, shader_program, true);
720
721 for (unsigned i = 0; i < num_shaders; i++) {
722 struct gl_linked_shader *shader = linked_shader[i];
723 struct gl_program *prog = shader->Program;
724
725 prog->ExternalSamplersUsed = gl_external_samplers(prog);
726 _mesa_update_shader_textures_used(shader_program, prog);
727 st_nir_preprocess(st, prog, shader_program, shader->Stage);
728 }
729 }
730
731 /* Linking the stages in the opposite order (from fragment to vertex)
732 * ensures that inter-shader outputs written to in an earlier stage
733 * are eliminated if they are (transitively) not used in a later
734 * stage.
735 */
736 for (int i = num_shaders - 2; i >= 0; i--) {
737 st_nir_link_shaders(linked_shader[i]->Program->nir,
738 linked_shader[i + 1]->Program->nir);
739 }
740 /* Linking shaders also optimizes them. Separate shaders, compute shaders
741 * and shaders with a fixed-func VS or FS that don't need linking are
742 * optimized here.
743 */
744 if (num_shaders == 1)
745 st_nir_opts(linked_shader[0]->Program->nir);
746
747 if (!shader_program->data->spirv) {
748 if (!gl_nir_link_glsl(ctx, shader_program))
749 return GL_FALSE;
750
751 for (unsigned i = 0; i < num_shaders; i++) {
752 struct gl_program *prog = linked_shader[i]->Program;
753 prog->ExternalSamplersUsed = gl_external_samplers(prog);
754 _mesa_update_shader_textures_used(shader_program, prog);
755 }
756
757 nir_build_program_resource_list(ctx, shader_program, false);
758 }
759
760 for (unsigned i = 0; i < num_shaders; i++) {
761 struct gl_linked_shader *shader = linked_shader[i];
762 nir_shader *nir = shader->Program->nir;
763
764 /* This needs to run after the initial pass of nir_lower_vars_to_ssa, so
765 * that the buffer indices are constants in nir where they where
766 * constants in GLSL. */
767 NIR_PASS_V(nir, gl_nir_lower_buffers, shader_program);
768
769 /* Remap the locations to slots so those requiring two slots will occupy
770 * two locations. For instance, if we have in the IR code a dvec3 attr0 in
771 * location 0 and vec4 attr1 in location 1, in NIR attr0 will use
772 * locations/slots 0 and 1, and attr1 will use location/slot 2
773 */
774 if (nir->info.stage == MESA_SHADER_VERTEX && !shader_program->data->spirv)
775 nir_remap_dual_slot_attributes(nir, &shader->Program->DualSlotInputs);
776
777 NIR_PASS_V(nir, st_nir_lower_wpos_ytransform, shader->Program,
778 st->pipe->screen);
779
780 NIR_PASS_V(nir, nir_lower_system_values);
781 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
782
783 st_shader_gather_info(nir, shader->Program);
784 if (shader->Stage == MESA_SHADER_VERTEX) {
785 /* NIR expands dual-slot inputs out to two locations. We need to
786 * compact things back down GL-style single-slot inputs to avoid
787 * confusing the state tracker.
788 */
789 shader->Program->info.inputs_read =
790 nir_get_single_slot_attribs_mask(nir->info.inputs_read,
791 shader->Program->DualSlotInputs);
792 }
793
794 if (i >= 1) {
795 struct gl_program *prev_shader = linked_shader[i - 1]->Program;
796
797 /* We can't use nir_compact_varyings with transform feedback, since
798 * the pipe_stream_output->output_register field is based on the
799 * pre-compacted driver_locations.
800 */
801 if (!(prev_shader->sh.LinkedTransformFeedback &&
802 prev_shader->sh.LinkedTransformFeedback->NumVarying > 0))
803 nir_compact_varyings(prev_shader->nir,
804 nir, ctx->API != API_OPENGL_COMPAT);
805
806 if (ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->vectorize_io)
807 st_nir_vectorize_io(prev_shader->nir, nir);
808 }
809 }
810
811 struct shader_info *prev_info = NULL;
812
813 for (unsigned i = 0; i < num_shaders; i++) {
814 struct gl_linked_shader *shader = linked_shader[i];
815 struct shader_info *info = &shader->Program->nir->info;
816
817 if (prev_info &&
818 ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->unify_interfaces) {
819 prev_info->outputs_written |= info->inputs_read &
820 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
821 info->inputs_read |= prev_info->outputs_written &
822 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
823
824 prev_info->patch_outputs_written |= info->patch_inputs_read;
825 info->patch_inputs_read |= prev_info->patch_outputs_written;
826 }
827 prev_info = info;
828 }
829
830 for (unsigned i = 0; i < num_shaders; i++) {
831 struct gl_linked_shader *shader = linked_shader[i];
832 struct gl_program *prog = shader->Program;
833 struct st_program *stp = st_program(prog);
834 st_glsl_to_nir_post_opts(st, prog, shader_program);
835
836 /* Initialize st_vertex_program members. */
837 if (shader->Stage == MESA_SHADER_VERTEX)
838 st_prepare_vertex_program(stp);
839
840 /* Get pipe_stream_output_info. */
841 if (shader->Stage == MESA_SHADER_VERTEX ||
842 shader->Stage == MESA_SHADER_TESS_EVAL ||
843 shader->Stage == MESA_SHADER_GEOMETRY)
844 st_translate_stream_output_info(prog);
845
846 st_store_ir_in_disk_cache(st, prog, true);
847
848 st_release_variants(st, stp);
849 st_finalize_program(st, prog);
850
851 /* The GLSL IR won't be needed anymore. */
852 ralloc_free(shader->ir);
853 shader->ir = NULL;
854 }
855
856 return true;
857 }
858
859 void
860 st_nir_assign_varying_locations(struct st_context *st, nir_shader *nir)
861 {
862 if (nir->info.stage == MESA_SHADER_VERTEX) {
863 nir_assign_io_var_locations(&nir->outputs,
864 &nir->num_outputs,
865 nir->info.stage);
866 st_nir_fixup_varying_slots(st, &nir->outputs);
867 } else if (nir->info.stage == MESA_SHADER_GEOMETRY ||
868 nir->info.stage == MESA_SHADER_TESS_CTRL ||
869 nir->info.stage == MESA_SHADER_TESS_EVAL) {
870 nir_assign_io_var_locations(&nir->inputs,
871 &nir->num_inputs,
872 nir->info.stage);
873 st_nir_fixup_varying_slots(st, &nir->inputs);
874
875 nir_assign_io_var_locations(&nir->outputs,
876 &nir->num_outputs,
877 nir->info.stage);
878 st_nir_fixup_varying_slots(st, &nir->outputs);
879 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
880 nir_assign_io_var_locations(&nir->inputs,
881 &nir->num_inputs,
882 nir->info.stage);
883 st_nir_fixup_varying_slots(st, &nir->inputs);
884 nir_assign_io_var_locations(&nir->outputs,
885 &nir->num_outputs,
886 nir->info.stage);
887 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
888 /* TODO? */
889 } else {
890 unreachable("invalid shader type");
891 }
892 }
893
894 void
895 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
896 struct gl_shader_program *shader_program,
897 struct gl_program *prog)
898 {
899 if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
900 NIR_PASS_V(nir, gl_nir_lower_samplers_as_deref, shader_program);
901 else
902 NIR_PASS_V(nir, gl_nir_lower_samplers, shader_program);
903
904 if (prog) {
905 prog->info.textures_used = nir->info.textures_used;
906 prog->info.textures_used_by_txf = nir->info.textures_used_by_txf;
907 prog->info.images_used = nir->info.images_used;
908 }
909 }
910
911 static int
912 st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
913 {
914 return glsl_count_dword_slots(type, bindless);
915 }
916
917 static int
918 st_unpacked_uniforms_type_size(const struct glsl_type *type, bool bindless)
919 {
920 return glsl_count_vec4_slots(type, false, bindless);
921 }
922
923 void
924 st_nir_lower_uniforms(struct st_context *st, nir_shader *nir)
925 {
926 if (st->ctx->Const.PackedDriverUniformStorage) {
927 NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
928 st_packed_uniforms_type_size,
929 (nir_lower_io_options)0);
930 NIR_PASS_V(nir, nir_lower_uniforms_to_ubo, 4);
931 } else {
932 NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
933 st_unpacked_uniforms_type_size,
934 (nir_lower_io_options)0);
935 }
936 }
937
938 /* Last third of preparing nir from glsl, which happens after shader
939 * variant lowering.
940 */
941 void
942 st_finalize_nir(struct st_context *st, struct gl_program *prog,
943 struct gl_shader_program *shader_program,
944 nir_shader *nir, bool finalize_by_driver)
945 {
946 struct pipe_screen *screen = st->pipe->screen;
947
948 NIR_PASS_V(nir, nir_split_var_copies);
949 NIR_PASS_V(nir, nir_lower_var_copies);
950
951 st_nir_assign_varying_locations(st, nir);
952 st_nir_assign_uniform_locations(st->ctx, prog,
953 &nir->uniforms);
954
955 /* Set num_uniforms in number of attribute slots (vec4s) */
956 nir->num_uniforms = DIV_ROUND_UP(prog->Parameters->NumParameterValues, 4);
957
958 st_nir_lower_uniforms(st, nir);
959 st_nir_lower_samplers(screen, nir, shader_program, prog);
960 if (!screen->get_param(screen, PIPE_CAP_NIR_IMAGES_AS_DEREF))
961 NIR_PASS_V(nir, gl_nir_lower_images, false);
962
963 if (finalize_by_driver && screen->finalize_nir)
964 screen->finalize_nir(screen, nir, false);
965 }
966
967 } /* extern "C" */