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