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