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