st/glsl_to_nir: fix incorrect arrary 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, unsigned *size)
244 {
245 int max = 0;
246 int shaderidx = 0;
247 int imageidx = 0;
248
249 nir_foreach_variable(uniform, uniform_list) {
250 int loc;
251
252 /*
253 * UBO's have their own address spaces, so don't count them towards the
254 * number of global uniforms
255 */
256 if (uniform->data.mode == nir_var_mem_ubo || uniform->data.mode == nir_var_mem_ssbo)
257 continue;
258
259 const struct glsl_type *type = glsl_without_array(uniform->type);
260 if (!uniform->data.bindless && (type->is_sampler() || type->is_image())) {
261 if (type->is_sampler()) {
262 loc = shaderidx;
263 shaderidx += type_size(uniform->type);
264 } else {
265 loc = imageidx;
266 imageidx += type_size(uniform->type);
267 }
268 } else if (strncmp(uniform->name, "gl_", 3) == 0) {
269 const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
270 /* This state reference has already been setup by ir_to_mesa, but we'll
271 * get the same index back here.
272 */
273
274 unsigned comps;
275 if (glsl_type_is_struct_or_ifc(type)) {
276 comps = 4;
277 } else {
278 comps = glsl_get_vector_elements(type);
279 }
280
281 if (ctx->Const.PackedDriverUniformStorage) {
282 loc = _mesa_add_sized_state_reference(prog->Parameters,
283 stateTokens, comps, false);
284 loc = prog->Parameters->ParameterValueOffset[loc];
285 } else {
286 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
287 }
288 } else {
289 loc = st_nir_lookup_parameter_index(prog->Parameters, uniform->name);
290
291 /* We need to check that loc is not -1 here before accessing the
292 * array. It can be negative for example when we have a struct that
293 * only contains opaque types.
294 */
295 if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
296 loc = prog->Parameters->ParameterValueOffset[loc];
297 }
298 }
299
300 uniform->data.driver_location = loc;
301 max = MAX2(max, loc + type_size(uniform->type));
302 }
303 *size = max;
304 }
305
306 void
307 st_nir_opts(nir_shader *nir, bool scalar)
308 {
309 bool progress;
310 do {
311 progress = false;
312
313 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
314
315 if (scalar) {
316 NIR_PASS_V(nir, nir_lower_alu_to_scalar);
317 NIR_PASS_V(nir, nir_lower_phis_to_scalar);
318 }
319
320 NIR_PASS_V(nir, nir_lower_alu);
321 NIR_PASS_V(nir, nir_lower_pack);
322 NIR_PASS(progress, nir, nir_copy_prop);
323 NIR_PASS(progress, nir, nir_opt_remove_phis);
324 NIR_PASS(progress, nir, nir_opt_dce);
325 if (nir_opt_trivial_continues(nir)) {
326 progress = true;
327 NIR_PASS(progress, nir, nir_copy_prop);
328 NIR_PASS(progress, nir, nir_opt_dce);
329 }
330 NIR_PASS(progress, nir, nir_opt_if);
331 NIR_PASS(progress, nir, nir_opt_dead_cf);
332 NIR_PASS(progress, nir, nir_opt_cse);
333 NIR_PASS(progress, nir, nir_opt_peephole_select, 8, true, true);
334
335 NIR_PASS(progress, nir, nir_opt_algebraic);
336 NIR_PASS(progress, nir, nir_opt_constant_folding);
337
338 NIR_PASS(progress, nir, nir_opt_undef);
339 NIR_PASS(progress, nir, nir_opt_conditional_discard);
340 if (nir->options->max_unroll_iterations) {
341 NIR_PASS(progress, nir, nir_opt_loop_unroll, (nir_variable_mode)0);
342 }
343 } while (progress);
344 }
345
346 /* First third of converting glsl_to_nir.. this leaves things in a pre-
347 * nir_lower_io state, so that shader variants can more easily insert/
348 * replace variables, etc.
349 */
350 static nir_shader *
351 st_glsl_to_nir(struct st_context *st, struct gl_program *prog,
352 struct gl_shader_program *shader_program,
353 gl_shader_stage stage)
354 {
355 const nir_shader_compiler_options *options =
356 st->ctx->Const.ShaderCompilerOptions[prog->info.stage].NirOptions;
357 enum pipe_shader_type type = pipe_shader_type_from_mesa(stage);
358 struct pipe_screen *screen = st->pipe->screen;
359 bool is_scalar = screen->get_shader_param(screen, type, PIPE_SHADER_CAP_SCALAR_ISA);
360 assert(options);
361 bool lower_64bit =
362 options->lower_int64_options || options->lower_doubles_options;
363
364 if (prog->nir)
365 return prog->nir;
366
367 nir_shader *nir = glsl_to_nir(st->ctx, shader_program, stage, options);
368
369 /* Set the next shader stage hint for VS and TES. */
370 if (!nir->info.separate_shader &&
371 (nir->info.stage == MESA_SHADER_VERTEX ||
372 nir->info.stage == MESA_SHADER_TESS_EVAL)) {
373
374 unsigned prev_stages = (1 << (prog->info.stage + 1)) - 1;
375 unsigned stages_mask =
376 ~prev_stages & shader_program->data->linked_stages;
377
378 nir->info.next_stage = stages_mask ?
379 (gl_shader_stage) u_bit_scan(&stages_mask) : MESA_SHADER_FRAGMENT;
380 } else {
381 nir->info.next_stage = MESA_SHADER_FRAGMENT;
382 }
383
384 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
385 nir_shader *softfp64 = NULL;
386 if (nir->info.uses_64bit &&
387 (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
388 softfp64 = glsl_float64_funcs_to_nir(st->ctx, options);
389 ralloc_steal(ralloc_parent(nir), softfp64);
390 }
391
392 nir_variable_mode mask =
393 (nir_variable_mode) (nir_var_shader_in | nir_var_shader_out);
394 nir_remove_dead_variables(nir, mask);
395
396 if (options->lower_all_io_to_temps ||
397 nir->info.stage == MESA_SHADER_VERTEX ||
398 nir->info.stage == MESA_SHADER_GEOMETRY) {
399 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
400 nir_shader_get_entrypoint(nir),
401 true, true);
402 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
403 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
404 nir_shader_get_entrypoint(nir),
405 true, false);
406 }
407
408 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
409 NIR_PASS_V(nir, nir_split_var_copies);
410 NIR_PASS_V(nir, nir_lower_var_copies);
411
412 if (is_scalar) {
413 NIR_PASS_V(nir, nir_lower_alu_to_scalar);
414 }
415
416 st_nir_opts(nir, is_scalar);
417
418 if (lower_64bit) {
419 bool lowered_64bit_ops = false;
420 bool progress = false;
421
422 NIR_PASS_V(nir, nir_opt_algebraic);
423
424 do {
425 progress = false;
426 if (options->lower_int64_options) {
427 NIR_PASS(progress, nir, nir_lower_int64,
428 options->lower_int64_options);
429 }
430 if (options->lower_doubles_options) {
431 NIR_PASS(progress, nir, nir_lower_doubles,
432 softfp64, options->lower_doubles_options);
433 }
434 NIR_PASS(progress, nir, nir_opt_algebraic);
435 lowered_64bit_ops |= progress;
436 } while (progress);
437
438 if (progress)
439 st_nir_opts(nir, is_scalar);
440 }
441
442 return nir;
443 }
444
445 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
446 * info on varyings, etc after NIR link time opts have been applied.
447 */
448 static void
449 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
450 struct gl_shader_program *shader_program)
451 {
452 nir_shader *nir = prog->nir;
453
454 /* Make a pass over the IR to add state references for any built-in
455 * uniforms that are used. This has to be done now (during linking).
456 * Code generation doesn't happen until the first time this shader is
457 * used for rendering. Waiting until then to generate the parameters is
458 * too late. At that point, the values for the built-in uniforms won't
459 * get sent to the shader.
460 */
461 nir_foreach_variable(var, &nir->uniforms) {
462 if (strncmp(var->name, "gl_", 3) == 0) {
463 const nir_state_slot *const slots = var->state_slots;
464 assert(var->state_slots != NULL);
465
466 const struct glsl_type *type = glsl_without_array(var->type);
467 for (unsigned int i = 0; i < var->num_state_slots; i++) {
468 unsigned comps;
469 if (glsl_type_is_struct_or_ifc(type)) {
470 /* Builtin struct require specical handling for now we just
471 * make all members vec4. See st_nir_lower_builtin.
472 */
473 comps = 4;
474 } else {
475 comps = glsl_get_vector_elements(type);
476 }
477
478 if (st->ctx->Const.PackedDriverUniformStorage) {
479 _mesa_add_sized_state_reference(prog->Parameters,
480 slots[i].tokens,
481 comps, false);
482 } else {
483 _mesa_add_state_reference(prog->Parameters,
484 slots[i].tokens);
485 }
486 }
487 }
488 }
489
490 /* Avoid reallocation of the program parameter list, because the uniform
491 * storage is only associated with the original parameter list.
492 * This should be enough for Bitmap and DrawPixels constants.
493 */
494 _mesa_reserve_parameter_storage(prog->Parameters, 8);
495
496 /* This has to be done last. Any operation the can cause
497 * prog->ParameterValues to get reallocated (e.g., anything that adds a
498 * program constant) has to happen before creating this linkage.
499 */
500 _mesa_associate_uniform_storage(st->ctx, shader_program, prog, true);
501
502 st_set_prog_affected_state_flags(prog);
503
504 NIR_PASS_V(nir, st_nir_lower_builtin);
505 NIR_PASS_V(nir, gl_nir_lower_atomics, shader_program, true);
506
507 nir_variable_mode mask = nir_var_function_temp;
508 nir_remove_dead_variables(nir, mask);
509
510 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
511 _mesa_log("\n");
512 _mesa_log("NIR IR for linked %s program %d:\n",
513 _mesa_shader_stage_to_string(prog->info.stage),
514 shader_program->Name);
515 nir_print_shader(nir, _mesa_get_log_file());
516 _mesa_log("\n\n");
517 }
518 }
519
520 /* TODO any better helper somewhere to sort a list? */
521
522 static void
523 insert_sorted(struct exec_list *var_list, nir_variable *new_var)
524 {
525 nir_foreach_variable(var, var_list) {
526 if (var->data.location > new_var->data.location) {
527 exec_node_insert_node_before(&var->node, &new_var->node);
528 return;
529 }
530 }
531 exec_list_push_tail(var_list, &new_var->node);
532 }
533
534 static void
535 sort_varyings(struct exec_list *var_list)
536 {
537 struct exec_list new_list;
538 exec_list_make_empty(&new_list);
539 nir_foreach_variable_safe(var, var_list) {
540 exec_node_remove(&var->node);
541 insert_sorted(&new_list, var);
542 }
543 exec_list_move_nodes_to(&new_list, var_list);
544 }
545
546 static void
547 set_st_program(struct gl_program *prog,
548 struct gl_shader_program *shader_program,
549 nir_shader *nir)
550 {
551 struct st_vertex_program *stvp;
552 struct st_common_program *stp;
553 struct st_fragment_program *stfp;
554 struct st_compute_program *stcp;
555
556 switch (prog->info.stage) {
557 case MESA_SHADER_VERTEX:
558 stvp = (struct st_vertex_program *)prog;
559 stvp->shader_program = shader_program;
560 stvp->tgsi.type = PIPE_SHADER_IR_NIR;
561 stvp->tgsi.ir.nir = nir;
562 break;
563 case MESA_SHADER_GEOMETRY:
564 case MESA_SHADER_TESS_CTRL:
565 case MESA_SHADER_TESS_EVAL:
566 stp = (struct st_common_program *)prog;
567 stp->shader_program = shader_program;
568 stp->tgsi.type = PIPE_SHADER_IR_NIR;
569 stp->tgsi.ir.nir = nir;
570 break;
571 case MESA_SHADER_FRAGMENT:
572 stfp = (struct st_fragment_program *)prog;
573 stfp->shader_program = shader_program;
574 stfp->tgsi.type = PIPE_SHADER_IR_NIR;
575 stfp->tgsi.ir.nir = nir;
576 break;
577 case MESA_SHADER_COMPUTE:
578 stcp = (struct st_compute_program *)prog;
579 stcp->shader_program = shader_program;
580 stcp->tgsi.ir_type = PIPE_SHADER_IR_NIR;
581 stcp->tgsi.prog = nir;
582 break;
583 default:
584 unreachable("unknown shader stage");
585 }
586 }
587
588 static void
589 st_nir_get_mesa_program(struct gl_context *ctx,
590 struct gl_shader_program *shader_program,
591 struct gl_linked_shader *shader)
592 {
593 struct st_context *st = st_context(ctx);
594 struct pipe_screen *pscreen = ctx->st->pipe->screen;
595 struct gl_program *prog;
596
597 validate_ir_tree(shader->ir);
598
599 prog = shader->Program;
600
601 prog->Parameters = _mesa_new_parameter_list();
602
603 _mesa_copy_linked_program_data(shader_program, shader);
604 _mesa_generate_parameters_list_for_uniforms(ctx, shader_program, shader,
605 prog->Parameters);
606
607 /* Remove reads from output registers. */
608 if (!pscreen->get_param(pscreen, PIPE_CAP_TGSI_CAN_READ_OUTPUTS))
609 lower_output_reads(shader->Stage, shader->ir);
610
611 if (ctx->_Shader->Flags & GLSL_DUMP) {
612 _mesa_log("\n");
613 _mesa_log("GLSL IR for linked %s program %d:\n",
614 _mesa_shader_stage_to_string(shader->Stage),
615 shader_program->Name);
616 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
617 _mesa_log("\n\n");
618 }
619
620 prog->ExternalSamplersUsed = gl_external_samplers(prog);
621 _mesa_update_shader_textures_used(shader_program, prog);
622
623 nir_shader *nir = st_glsl_to_nir(st, prog, shader_program, shader->Stage);
624
625 set_st_program(prog, shader_program, nir);
626 prog->nir = nir;
627 }
628
629 static void
630 st_nir_link_shaders(nir_shader **producer, nir_shader **consumer, bool scalar)
631 {
632 if (scalar) {
633 NIR_PASS_V(*producer, nir_lower_io_to_scalar_early, nir_var_shader_out);
634 NIR_PASS_V(*consumer, nir_lower_io_to_scalar_early, nir_var_shader_in);
635 }
636
637 nir_lower_io_arrays_to_elements(*producer, *consumer);
638
639 st_nir_opts(*producer, scalar);
640 st_nir_opts(*consumer, scalar);
641
642 if (nir_link_opt_varyings(*producer, *consumer))
643 st_nir_opts(*consumer, scalar);
644
645 NIR_PASS_V(*producer, nir_remove_dead_variables, nir_var_shader_out);
646 NIR_PASS_V(*consumer, nir_remove_dead_variables, nir_var_shader_in);
647
648 if (nir_remove_unused_varyings(*producer, *consumer)) {
649 NIR_PASS_V(*producer, nir_lower_global_vars_to_local);
650 NIR_PASS_V(*consumer, nir_lower_global_vars_to_local);
651
652 /* The backend might not be able to handle indirects on
653 * temporaries so we need to lower indirects on any of the
654 * varyings we have demoted here.
655 *
656 * TODO: radeonsi shouldn't need to do this, however LLVM isn't
657 * currently smart enough to handle indirects without causing excess
658 * spilling causing the gpu to hang.
659 *
660 * See the following thread for more details of the problem:
661 * https://lists.freedesktop.org/archives/mesa-dev/2017-July/162106.html
662 */
663 nir_variable_mode indirect_mask = nir_var_function_temp;
664
665 NIR_PASS_V(*producer, nir_lower_indirect_derefs, indirect_mask);
666 NIR_PASS_V(*consumer, nir_lower_indirect_derefs, indirect_mask);
667
668 st_nir_opts(*producer, scalar);
669 st_nir_opts(*consumer, scalar);
670
671 /* Lowering indirects can cause varying to become unused.
672 * nir_compact_varyings() depends on all dead varyings being removed so
673 * we need to call nir_remove_dead_variables() again here.
674 */
675 NIR_PASS_V(*producer, nir_remove_dead_variables, nir_var_shader_out);
676 NIR_PASS_V(*consumer, nir_remove_dead_variables, nir_var_shader_in);
677 }
678 }
679
680 static void
681 st_lower_patch_vertices_in(struct gl_shader_program *shader_prog)
682 {
683 struct gl_linked_shader *linked_tcs =
684 shader_prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
685 struct gl_linked_shader *linked_tes =
686 shader_prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
687
688 /* If we have a TCS and TES linked together, lower TES patch vertices. */
689 if (linked_tcs && linked_tes) {
690 nir_shader *tcs_nir = linked_tcs->Program->nir;
691 nir_shader *tes_nir = linked_tes->Program->nir;
692
693 /* The TES input vertex count is the TCS output vertex count,
694 * lower TES gl_PatchVerticesIn to a constant.
695 */
696 uint32_t tes_patch_verts = tcs_nir->info.tess.tcs_vertices_out;
697 NIR_PASS_V(tes_nir, nir_lower_patch_vertices, tes_patch_verts, NULL);
698 }
699 }
700
701 extern "C" {
702
703 void
704 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
705 struct gl_program *prog,
706 struct pipe_screen *pscreen)
707 {
708 if (nir->info.stage != MESA_SHADER_FRAGMENT)
709 return;
710
711 static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
712 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
713 };
714 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
715
716 memcpy(wpos_options.state_tokens, wposTransformState,
717 sizeof(wpos_options.state_tokens));
718 wpos_options.fs_coord_origin_upper_left =
719 pscreen->get_param(pscreen,
720 PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
721 wpos_options.fs_coord_origin_lower_left =
722 pscreen->get_param(pscreen,
723 PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
724 wpos_options.fs_coord_pixel_center_integer =
725 pscreen->get_param(pscreen,
726 PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
727 wpos_options.fs_coord_pixel_center_half_integer =
728 pscreen->get_param(pscreen,
729 PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
730
731 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
732 nir_validate_shader(nir, "after nir_lower_wpos_ytransform");
733 _mesa_add_state_reference(prog->Parameters, wposTransformState);
734 }
735 }
736
737 bool
738 st_link_nir(struct gl_context *ctx,
739 struct gl_shader_program *shader_program)
740 {
741 struct st_context *st = st_context(ctx);
742 struct pipe_screen *screen = st->pipe->screen;
743 bool is_scalar[MESA_SHADER_STAGES];
744
745 unsigned last_stage = 0;
746 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
747 struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
748 if (shader == NULL)
749 continue;
750
751 /* Determine scalar property of each shader stage */
752 enum pipe_shader_type type = pipe_shader_type_from_mesa(shader->Stage);
753 is_scalar[i] = screen->get_shader_param(screen, type,
754 PIPE_SHADER_CAP_SCALAR_ISA);
755
756 st_nir_get_mesa_program(ctx, shader_program, shader);
757 last_stage = i;
758
759 if (is_scalar[i]) {
760 NIR_PASS_V(shader->Program->nir, nir_lower_load_const_to_scalar);
761 }
762 }
763
764 /* Linking the stages in the opposite order (from fragment to vertex)
765 * ensures that inter-shader outputs written to in an earlier stage
766 * are eliminated if they are (transitively) not used in a later
767 * stage.
768 */
769 int next = last_stage;
770 for (int i = next - 1; i >= 0; i--) {
771 struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
772 if (shader == NULL)
773 continue;
774
775 st_nir_link_shaders(&shader->Program->nir,
776 &shader_program->_LinkedShaders[next]->Program->nir,
777 is_scalar[i]);
778 next = i;
779 }
780
781 int prev = -1;
782 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
783 struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
784 if (shader == NULL)
785 continue;
786
787 nir_shader *nir = shader->Program->nir;
788
789 NIR_PASS_V(nir, st_nir_lower_wpos_ytransform, shader->Program,
790 st->pipe->screen);
791
792 NIR_PASS_V(nir, nir_lower_system_values);
793 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
794
795 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
796 shader->Program->info = nir->info;
797 if (i == MESA_SHADER_VERTEX) {
798 /* NIR expands dual-slot inputs out to two locations. We need to
799 * compact things back down GL-style single-slot inputs to avoid
800 * confusing the state tracker.
801 */
802 shader->Program->info.inputs_read =
803 nir_get_single_slot_attribs_mask(nir->info.inputs_read,
804 shader->Program->DualSlotInputs);
805 }
806
807 if (prev != -1) {
808 struct gl_program *prev_shader =
809 shader_program->_LinkedShaders[prev]->Program;
810
811 /* We can't use nir_compact_varyings with transform feedback, since
812 * the pipe_stream_output->output_register field is based on the
813 * pre-compacted driver_locations.
814 */
815 if (!(prev_shader->sh.LinkedTransformFeedback &&
816 prev_shader->sh.LinkedTransformFeedback->NumVarying > 0))
817 nir_compact_varyings(shader_program->_LinkedShaders[prev]->Program->nir,
818 nir, ctx->API != API_OPENGL_COMPAT);
819 }
820 prev = i;
821 }
822
823 st_lower_patch_vertices_in(shader_program);
824
825 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
826 struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
827 if (shader == NULL)
828 continue;
829
830 st_glsl_to_nir_post_opts(st, shader->Program, shader_program);
831
832 assert(shader->Program);
833 if (!ctx->Driver.ProgramStringNotify(ctx,
834 _mesa_shader_stage_to_program(i),
835 shader->Program)) {
836 _mesa_reference_program(ctx, &shader->Program, NULL);
837 return false;
838 }
839
840 nir_sweep(shader->Program->nir);
841 }
842
843 return true;
844 }
845
846 void
847 st_nir_assign_varying_locations(struct st_context *st, nir_shader *nir)
848 {
849 if (nir->info.stage == MESA_SHADER_VERTEX) {
850 /* Needs special handling so drvloc matches the vbo state: */
851 st_nir_assign_vs_in_locations(nir);
852 /* Re-lower global vars, to deal with any dead VS inputs. */
853 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
854
855 sort_varyings(&nir->outputs);
856 st_nir_assign_var_locations(&nir->outputs,
857 &nir->num_outputs,
858 nir->info.stage);
859 st_nir_fixup_varying_slots(st, &nir->outputs);
860 } else if (nir->info.stage == MESA_SHADER_GEOMETRY ||
861 nir->info.stage == MESA_SHADER_TESS_CTRL ||
862 nir->info.stage == MESA_SHADER_TESS_EVAL) {
863 sort_varyings(&nir->inputs);
864 st_nir_assign_var_locations(&nir->inputs,
865 &nir->num_inputs,
866 nir->info.stage);
867 st_nir_fixup_varying_slots(st, &nir->inputs);
868
869 sort_varyings(&nir->outputs);
870 st_nir_assign_var_locations(&nir->outputs,
871 &nir->num_outputs,
872 nir->info.stage);
873 st_nir_fixup_varying_slots(st, &nir->outputs);
874 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
875 sort_varyings(&nir->inputs);
876 st_nir_assign_var_locations(&nir->inputs,
877 &nir->num_inputs,
878 nir->info.stage);
879 st_nir_fixup_varying_slots(st, &nir->inputs);
880 st_nir_assign_var_locations(&nir->outputs,
881 &nir->num_outputs,
882 nir->info.stage);
883 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
884 /* TODO? */
885 } else {
886 unreachable("invalid shader type");
887 }
888 }
889
890 void
891 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
892 struct gl_shader_program *shader_program,
893 struct gl_program *prog)
894 {
895 if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
896 NIR_PASS_V(nir, gl_nir_lower_samplers_as_deref, shader_program);
897 else
898 NIR_PASS_V(nir, gl_nir_lower_samplers, shader_program);
899
900 if (prog) {
901 prog->info.textures_used = nir->info.textures_used;
902 prog->info.textures_used_by_txf = nir->info.textures_used_by_txf;
903 }
904 }
905
906 /* Last third of preparing nir from glsl, which happens after shader
907 * variant lowering.
908 */
909 void
910 st_finalize_nir(struct st_context *st, struct gl_program *prog,
911 struct gl_shader_program *shader_program, nir_shader *nir)
912 {
913 struct pipe_screen *screen = st->pipe->screen;
914 const nir_shader_compiler_options *options =
915 st->ctx->Const.ShaderCompilerOptions[prog->info.stage].NirOptions;
916
917 NIR_PASS_V(nir, nir_split_var_copies);
918 NIR_PASS_V(nir, nir_lower_var_copies);
919 if (options->lower_all_io_to_temps ||
920 nir->info.stage == MESA_SHADER_VERTEX ||
921 nir->info.stage == MESA_SHADER_GEOMETRY) {
922 NIR_PASS_V(nir, nir_lower_io_arrays_to_elements_no_indirects, false);
923 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
924 NIR_PASS_V(nir, nir_lower_io_arrays_to_elements_no_indirects, true);
925 }
926
927 st_nir_assign_varying_locations(st, nir);
928
929 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo,
930 st->ctx->Const.Program[nir->info.stage].MaxAtomicBuffers);
931
932 st_nir_assign_uniform_locations(st->ctx, prog,
933 &nir->uniforms, &nir->num_uniforms);
934
935 if (st->ctx->Const.PackedDriverUniformStorage) {
936 NIR_PASS_V(nir, nir_lower_io, nir_var_uniform, st_glsl_type_dword_size,
937 (nir_lower_io_options)0);
938 NIR_PASS_V(nir, nir_lower_uniforms_to_ubo, 4);
939 }
940
941 st_nir_lower_samplers(screen, nir, shader_program, prog);
942 }
943
944 } /* extern "C" */