panfrost: fix undefined value access on mir_set_intr_mask()
[mesa.git] / src / panfrost / midgard / midgard_compile.c
1 /*
2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
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 <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/mman.h>
27 #include <fcntl.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <err.h>
32
33 #include "main/mtypes.h"
34 #include "compiler/glsl/glsl_to_nir.h"
35 #include "compiler/nir_types.h"
36 #include "compiler/nir/nir_builder.h"
37 #include "util/half_float.h"
38 #include "util/u_math.h"
39 #include "util/u_debug.h"
40 #include "util/u_dynarray.h"
41 #include "util/list.h"
42 #include "main/mtypes.h"
43
44 #include "midgard.h"
45 #include "midgard_nir.h"
46 #include "midgard_compile.h"
47 #include "midgard_ops.h"
48 #include "helpers.h"
49 #include "compiler.h"
50 #include "midgard_quirks.h"
51 #include "panfrost-quirks.h"
52 #include "panfrost/util/pan_lower_framebuffer.h"
53
54 #include "disassemble.h"
55
56 static const struct debug_named_value debug_options[] = {
57 {"msgs", MIDGARD_DBG_MSGS, "Print debug messages"},
58 {"shaders", MIDGARD_DBG_SHADERS, "Dump shaders in NIR and MIR"},
59 {"shaderdb", MIDGARD_DBG_SHADERDB, "Prints shader-db statistics"},
60 DEBUG_NAMED_VALUE_END
61 };
62
63 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG", debug_options, 0)
64
65 unsigned SHADER_DB_COUNT = 0;
66
67 int midgard_debug = 0;
68
69 #define DBG(fmt, ...) \
70 do { if (midgard_debug & MIDGARD_DBG_MSGS) \
71 fprintf(stderr, "%s:%d: "fmt, \
72 __FUNCTION__, __LINE__, ##__VA_ARGS__); } while (0)
73 static midgard_block *
74 create_empty_block(compiler_context *ctx)
75 {
76 midgard_block *blk = rzalloc(ctx, midgard_block);
77
78 blk->base.predecessors = _mesa_set_create(blk,
79 _mesa_hash_pointer,
80 _mesa_key_pointer_equal);
81
82 blk->base.name = ctx->block_source_count++;
83
84 return blk;
85 }
86
87 static void
88 schedule_barrier(compiler_context *ctx)
89 {
90 midgard_block *temp = ctx->after_block;
91 ctx->after_block = create_empty_block(ctx);
92 ctx->block_count++;
93 list_addtail(&ctx->after_block->base.link, &ctx->blocks);
94 list_inithead(&ctx->after_block->base.instructions);
95 pan_block_add_successor(&ctx->current_block->base, &ctx->after_block->base);
96 ctx->current_block = ctx->after_block;
97 ctx->after_block = temp;
98 }
99
100 /* Helpers to generate midgard_instruction's using macro magic, since every
101 * driver seems to do it that way */
102
103 #define EMIT(op, ...) emit_mir_instruction(ctx, v_##op(__VA_ARGS__));
104
105 #define M_LOAD_STORE(name, store, T) \
106 static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
107 midgard_instruction i = { \
108 .type = TAG_LOAD_STORE_4, \
109 .mask = 0xF, \
110 .dest = ~0, \
111 .src = { ~0, ~0, ~0, ~0 }, \
112 .swizzle = SWIZZLE_IDENTITY_4, \
113 .op = midgard_op_##name, \
114 .load_store = { \
115 .address = address \
116 } \
117 }; \
118 \
119 if (store) { \
120 i.src[0] = ssa; \
121 i.src_types[0] = T; \
122 i.dest_type = T; \
123 } else { \
124 i.dest = ssa; \
125 i.dest_type = T; \
126 } \
127 return i; \
128 }
129
130 #define M_LOAD(name, T) M_LOAD_STORE(name, false, T)
131 #define M_STORE(name, T) M_LOAD_STORE(name, true, T)
132
133 M_LOAD(ld_attr_32, nir_type_uint32);
134 M_LOAD(ld_vary_32, nir_type_uint32);
135 M_LOAD(ld_ubo_int4, nir_type_uint32);
136 M_LOAD(ld_int4, nir_type_uint32);
137 M_STORE(st_int4, nir_type_uint32);
138 M_LOAD(ld_color_buffer_32u, nir_type_uint32);
139 M_LOAD(ld_color_buffer_as_fp16, nir_type_float16);
140 M_LOAD(ld_color_buffer_as_fp32, nir_type_float32);
141 M_STORE(st_vary_32, nir_type_uint32);
142 M_LOAD(ld_cubemap_coords, nir_type_uint32);
143 M_LOAD(ld_compute_id, nir_type_uint32);
144
145 static midgard_instruction
146 v_branch(bool conditional, bool invert)
147 {
148 midgard_instruction ins = {
149 .type = TAG_ALU_4,
150 .unit = ALU_ENAB_BRANCH,
151 .compact_branch = true,
152 .branch = {
153 .conditional = conditional,
154 .invert_conditional = invert
155 },
156 .dest = ~0,
157 .src = { ~0, ~0, ~0, ~0 },
158 };
159
160 return ins;
161 }
162
163 static void
164 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
165 {
166 ins->has_constants = true;
167 memcpy(&ins->constants, constants, 16);
168 }
169
170 static int
171 glsl_type_size(const struct glsl_type *type, bool bindless)
172 {
173 return glsl_count_attribute_slots(type, false);
174 }
175
176 /* Lower fdot2 to a vector multiplication followed by channel addition */
177 static void
178 midgard_nir_lower_fdot2_body(nir_builder *b, nir_alu_instr *alu)
179 {
180 if (alu->op != nir_op_fdot2)
181 return;
182
183 b->cursor = nir_before_instr(&alu->instr);
184
185 nir_ssa_def *src0 = nir_ssa_for_alu_src(b, alu, 0);
186 nir_ssa_def *src1 = nir_ssa_for_alu_src(b, alu, 1);
187
188 nir_ssa_def *product = nir_fmul(b, src0, src1);
189
190 nir_ssa_def *sum = nir_fadd(b,
191 nir_channel(b, product, 0),
192 nir_channel(b, product, 1));
193
194 /* Replace the fdot2 with this sum */
195 nir_ssa_def_rewrite_uses(&alu->dest.dest.ssa, nir_src_for_ssa(sum));
196 }
197
198 static bool
199 midgard_nir_lower_fdot2(nir_shader *shader)
200 {
201 bool progress = false;
202
203 nir_foreach_function(function, shader) {
204 if (!function->impl) continue;
205
206 nir_builder _b;
207 nir_builder *b = &_b;
208 nir_builder_init(b, function->impl);
209
210 nir_foreach_block(block, function->impl) {
211 nir_foreach_instr_safe(instr, block) {
212 if (instr->type != nir_instr_type_alu) continue;
213
214 nir_alu_instr *alu = nir_instr_as_alu(instr);
215 midgard_nir_lower_fdot2_body(b, alu);
216
217 progress |= true;
218 }
219 }
220
221 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
222
223 }
224
225 return progress;
226 }
227
228 static const nir_variable *
229 search_var(nir_shader *nir, nir_variable_mode mode, unsigned driver_loc)
230 {
231 nir_foreach_variable_with_modes(var, nir, mode) {
232 if (var->data.driver_location == driver_loc)
233 return var;
234 }
235
236 return NULL;
237 }
238
239 /* Midgard can write all of color, depth and stencil in a single writeout
240 * operation, so we merge depth/stencil stores with color stores.
241 * If there are no color stores, we add a write to the "depth RT".
242 */
243 static bool
244 midgard_nir_lower_zs_store(nir_shader *nir)
245 {
246 if (nir->info.stage != MESA_SHADER_FRAGMENT)
247 return false;
248
249 nir_variable *z_var = NULL, *s_var = NULL;
250
251 nir_foreach_shader_out_variable(var, nir) {
252 if (var->data.location == FRAG_RESULT_DEPTH)
253 z_var = var;
254 else if (var->data.location == FRAG_RESULT_STENCIL)
255 s_var = var;
256 }
257
258 if (!z_var && !s_var)
259 return false;
260
261 bool progress = false;
262
263 nir_foreach_function(function, nir) {
264 if (!function->impl) continue;
265
266 nir_intrinsic_instr *z_store = NULL, *s_store = NULL;
267
268 nir_foreach_block(block, function->impl) {
269 nir_foreach_instr_safe(instr, block) {
270 if (instr->type != nir_instr_type_intrinsic)
271 continue;
272
273 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
274 if (intr->intrinsic != nir_intrinsic_store_output)
275 continue;
276
277 if (z_var && nir_intrinsic_base(intr) == z_var->data.driver_location) {
278 assert(!z_store);
279 z_store = intr;
280 }
281
282 if (s_var && nir_intrinsic_base(intr) == s_var->data.driver_location) {
283 assert(!s_store);
284 s_store = intr;
285 }
286 }
287 }
288
289 if (!z_store && !s_store) continue;
290
291 bool replaced = false;
292
293 nir_foreach_block(block, function->impl) {
294 nir_foreach_instr_safe(instr, block) {
295 if (instr->type != nir_instr_type_intrinsic)
296 continue;
297
298 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
299 if (intr->intrinsic != nir_intrinsic_store_output)
300 continue;
301
302 const nir_variable *var = search_var(nir, nir_var_shader_out, nir_intrinsic_base(intr));
303 assert(var);
304
305 if (var->data.location != FRAG_RESULT_COLOR &&
306 var->data.location < FRAG_RESULT_DATA0)
307 continue;
308
309 if (var->data.index)
310 continue;
311
312 assert(nir_src_is_const(intr->src[1]) && "no indirect outputs");
313
314 nir_builder b;
315 nir_builder_init(&b, function->impl);
316
317 assert(!z_store || z_store->instr.block == instr->block);
318 assert(!s_store || s_store->instr.block == instr->block);
319 b.cursor = nir_after_block_before_jump(instr->block);
320
321 nir_intrinsic_instr *combined_store;
322 combined_store = nir_intrinsic_instr_create(b.shader, nir_intrinsic_store_combined_output_pan);
323
324 combined_store->num_components = intr->src[0].ssa->num_components;
325
326 nir_intrinsic_set_base(combined_store, nir_intrinsic_base(intr));
327
328 unsigned writeout = PAN_WRITEOUT_C;
329 if (z_store)
330 writeout |= PAN_WRITEOUT_Z;
331 if (s_store)
332 writeout |= PAN_WRITEOUT_S;
333
334 nir_intrinsic_set_component(combined_store, writeout);
335
336 struct nir_ssa_def *zero = nir_imm_int(&b, 0);
337
338 struct nir_ssa_def *src[4] = {
339 intr->src[0].ssa,
340 intr->src[1].ssa,
341 z_store ? z_store->src[0].ssa : zero,
342 s_store ? s_store->src[0].ssa : zero,
343 };
344
345 for (int i = 0; i < 4; ++i)
346 combined_store->src[i] = nir_src_for_ssa(src[i]);
347
348 nir_builder_instr_insert(&b, &combined_store->instr);
349
350 nir_instr_remove(instr);
351
352 replaced = true;
353 }
354 }
355
356 /* Insert a store to the depth RT (0xff) if needed */
357 if (!replaced) {
358 nir_builder b;
359 nir_builder_init(&b, function->impl);
360
361 nir_block *block = NULL;
362 if (z_store && s_store)
363 assert(z_store->instr.block == s_store->instr.block);
364
365 if (z_store)
366 block = z_store->instr.block;
367 else
368 block = s_store->instr.block;
369
370 b.cursor = nir_after_block_before_jump(block);
371
372 nir_intrinsic_instr *combined_store;
373 combined_store = nir_intrinsic_instr_create(b.shader, nir_intrinsic_store_combined_output_pan);
374
375 combined_store->num_components = 4;
376
377 unsigned base;
378 if (z_store)
379 base = nir_intrinsic_base(z_store);
380 else
381 base = nir_intrinsic_base(s_store);
382 nir_intrinsic_set_base(combined_store, base);
383
384 unsigned writeout = 0;
385 if (z_store)
386 writeout |= PAN_WRITEOUT_Z;
387 if (s_store)
388 writeout |= PAN_WRITEOUT_S;
389
390 nir_intrinsic_set_component(combined_store, writeout);
391
392 struct nir_ssa_def *zero = nir_imm_int(&b, 0);
393
394 struct nir_ssa_def *src[4] = {
395 nir_imm_vec4(&b, 0, 0, 0, 0),
396 zero,
397 z_store ? z_store->src[0].ssa : zero,
398 s_store ? s_store->src[0].ssa : zero,
399 };
400
401 for (int i = 0; i < 4; ++i)
402 combined_store->src[i] = nir_src_for_ssa(src[i]);
403
404 nir_builder_instr_insert(&b, &combined_store->instr);
405 }
406
407 if (z_store)
408 nir_instr_remove(&z_store->instr);
409
410 if (s_store)
411 nir_instr_remove(&s_store->instr);
412
413 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
414 progress = true;
415 }
416
417 return progress;
418 }
419
420 /* Real writeout stores, which break execution, need to be moved to after
421 * dual-source stores, which are just standard register writes. */
422 static bool
423 midgard_nir_reorder_writeout(nir_shader *nir)
424 {
425 bool progress = false;
426
427 nir_foreach_function(function, nir) {
428 if (!function->impl) continue;
429
430 nir_foreach_block(block, function->impl) {
431 nir_instr *last_writeout = NULL;
432
433 nir_foreach_instr_reverse_safe(instr, block) {
434 if (instr->type != nir_instr_type_intrinsic)
435 continue;
436
437 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
438 if (intr->intrinsic != nir_intrinsic_store_output)
439 continue;
440
441 const nir_variable *var = search_var(nir, nir_var_shader_out, nir_intrinsic_base(intr));
442
443 if (var->data.index) {
444 if (!last_writeout)
445 last_writeout = instr;
446 continue;
447 }
448
449 if (!last_writeout)
450 continue;
451
452 /* This is a real store, so move it to after dual-source stores */
453 exec_node_remove(&instr->node);
454 exec_node_insert_after(&last_writeout->node, &instr->node);
455
456 progress = true;
457 }
458 }
459 }
460
461 return progress;
462 }
463
464 static bool
465 mdg_is_64(const nir_instr *instr, const void *_unused)
466 {
467 const nir_alu_instr *alu = nir_instr_as_alu(instr);
468
469 if (nir_dest_bit_size(alu->dest.dest) == 64)
470 return true;
471
472 switch (alu->op) {
473 case nir_op_umul_high:
474 case nir_op_imul_high:
475 return true;
476 default:
477 return false;
478 }
479 }
480
481 /* Flushes undefined values to zero */
482
483 static void
484 optimise_nir(nir_shader *nir, unsigned quirks, bool is_blend)
485 {
486 bool progress;
487 unsigned lower_flrp =
488 (nir->options->lower_flrp16 ? 16 : 0) |
489 (nir->options->lower_flrp32 ? 32 : 0) |
490 (nir->options->lower_flrp64 ? 64 : 0);
491
492 NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
493 NIR_PASS(progress, nir, nir_lower_idiv, nir_lower_idiv_fast);
494
495 nir_lower_tex_options lower_tex_options = {
496 .lower_txs_lod = true,
497 .lower_txp = ~0,
498 .lower_tex_without_implicit_lod =
499 (quirks & MIDGARD_EXPLICIT_LOD),
500 .lower_tg4_broadcom_swizzle = true,
501
502 /* TODO: we have native gradient.. */
503 .lower_txd = true,
504 };
505
506 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_options);
507
508 /* Must lower fdot2 after tex is lowered */
509 NIR_PASS(progress, nir, midgard_nir_lower_fdot2);
510
511 /* T720 is broken. */
512
513 if (quirks & MIDGARD_BROKEN_LOD)
514 NIR_PASS_V(nir, midgard_nir_lod_errata);
515
516 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_early);
517
518 do {
519 progress = false;
520
521 NIR_PASS(progress, nir, nir_lower_var_copies);
522 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
523
524 NIR_PASS(progress, nir, nir_copy_prop);
525 NIR_PASS(progress, nir, nir_opt_remove_phis);
526 NIR_PASS(progress, nir, nir_opt_dce);
527 NIR_PASS(progress, nir, nir_opt_dead_cf);
528 NIR_PASS(progress, nir, nir_opt_cse);
529 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
530 NIR_PASS(progress, nir, nir_opt_algebraic);
531 NIR_PASS(progress, nir, nir_opt_constant_folding);
532
533 if (lower_flrp != 0) {
534 bool lower_flrp_progress = false;
535 NIR_PASS(lower_flrp_progress,
536 nir,
537 nir_lower_flrp,
538 lower_flrp,
539 false /* always_precise */,
540 nir->options->lower_ffma);
541 if (lower_flrp_progress) {
542 NIR_PASS(progress, nir,
543 nir_opt_constant_folding);
544 progress = true;
545 }
546
547 /* Nothing should rematerialize any flrps, so we only
548 * need to do this lowering once.
549 */
550 lower_flrp = 0;
551 }
552
553 NIR_PASS(progress, nir, nir_opt_undef);
554 NIR_PASS(progress, nir, nir_undef_to_zero);
555
556 NIR_PASS(progress, nir, nir_opt_loop_unroll,
557 nir_var_shader_in |
558 nir_var_shader_out |
559 nir_var_function_temp);
560
561 NIR_PASS(progress, nir, nir_opt_vectorize);
562 } while (progress);
563
564 NIR_PASS_V(nir, nir_lower_alu_to_scalar, mdg_is_64, NULL);
565
566 /* Run after opts so it can hit more */
567 if (!is_blend)
568 NIR_PASS(progress, nir, nir_fuse_io_16);
569
570 /* Must be run at the end to prevent creation of fsin/fcos ops */
571 NIR_PASS(progress, nir, midgard_nir_scale_trig);
572
573 do {
574 progress = false;
575
576 NIR_PASS(progress, nir, nir_opt_dce);
577 NIR_PASS(progress, nir, nir_opt_algebraic);
578 NIR_PASS(progress, nir, nir_opt_constant_folding);
579 NIR_PASS(progress, nir, nir_copy_prop);
580 } while (progress);
581
582 NIR_PASS(progress, nir, nir_opt_algebraic_late);
583 NIR_PASS(progress, nir, nir_opt_algebraic_distribute_src_mods);
584
585 /* We implement booleans as 32-bit 0/~0 */
586 NIR_PASS(progress, nir, nir_lower_bool_to_int32);
587
588 /* Now that booleans are lowered, we can run out late opts */
589 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
590 NIR_PASS(progress, nir, midgard_nir_cancel_inot);
591
592 NIR_PASS(progress, nir, nir_copy_prop);
593 NIR_PASS(progress, nir, nir_opt_dce);
594
595 /* Take us out of SSA */
596 NIR_PASS(progress, nir, nir_lower_locals_to_regs);
597 NIR_PASS(progress, nir, nir_convert_from_ssa, true);
598
599 /* We are a vector architecture; write combine where possible */
600 NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
601 NIR_PASS(progress, nir, nir_lower_vec_to_movs);
602
603 NIR_PASS(progress, nir, nir_opt_dce);
604 }
605
606 /* Do not actually emit a load; instead, cache the constant for inlining */
607
608 static void
609 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
610 {
611 nir_ssa_def def = instr->def;
612
613 midgard_constants *consts = rzalloc(NULL, midgard_constants);
614
615 assert(instr->def.num_components * instr->def.bit_size <= sizeof(*consts) * 8);
616
617 #define RAW_CONST_COPY(bits) \
618 nir_const_value_to_array(consts->u##bits, instr->value, \
619 instr->def.num_components, u##bits)
620
621 switch (instr->def.bit_size) {
622 case 64:
623 RAW_CONST_COPY(64);
624 break;
625 case 32:
626 RAW_CONST_COPY(32);
627 break;
628 case 16:
629 RAW_CONST_COPY(16);
630 break;
631 case 8:
632 RAW_CONST_COPY(8);
633 break;
634 default:
635 unreachable("Invalid bit_size for load_const instruction\n");
636 }
637
638 /* Shifted for SSA, +1 for off-by-one */
639 _mesa_hash_table_u64_insert(ctx->ssa_constants, (def.index << 1) + 1, consts);
640 }
641
642 /* Normally constants are embedded implicitly, but for I/O and such we have to
643 * explicitly emit a move with the constant source */
644
645 static void
646 emit_explicit_constant(compiler_context *ctx, unsigned node, unsigned to)
647 {
648 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, node + 1);
649
650 if (constant_value) {
651 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), to);
652 attach_constants(ctx, &ins, constant_value, node + 1);
653 emit_mir_instruction(ctx, ins);
654 }
655 }
656
657 static bool
658 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
659 {
660 unsigned comp = src->swizzle[0];
661
662 for (unsigned c = 1; c < nr_components; ++c) {
663 if (src->swizzle[c] != comp)
664 return true;
665 }
666
667 return false;
668 }
669
670 #define ALU_CASE(nir, _op) \
671 case nir_op_##nir: \
672 op = midgard_alu_op_##_op; \
673 assert(src_bitsize == dst_bitsize); \
674 break;
675
676 #define ALU_CASE_RTZ(nir, _op) \
677 case nir_op_##nir: \
678 op = midgard_alu_op_##_op; \
679 roundmode = MIDGARD_RTZ; \
680 break;
681
682 #define ALU_CHECK_CMP(sext) \
683 assert(src_bitsize == 16 || src_bitsize == 32); \
684 assert(dst_bitsize == 16 || dst_bitsize == 32); \
685
686 #define ALU_CASE_BCAST(nir, _op, count) \
687 case nir_op_##nir: \
688 op = midgard_alu_op_##_op; \
689 broadcast_swizzle = count; \
690 ALU_CHECK_CMP(true); \
691 break;
692
693 #define ALU_CASE_CMP(nir, _op, sext) \
694 case nir_op_##nir: \
695 op = midgard_alu_op_##_op; \
696 ALU_CHECK_CMP(sext); \
697 break;
698
699 /* Compare mir_lower_invert */
700 static bool
701 nir_accepts_inot(nir_op op, unsigned src)
702 {
703 switch (op) {
704 case nir_op_ior:
705 case nir_op_iand: /* TODO: b2f16 */
706 case nir_op_ixor:
707 return true;
708 case nir_op_b32csel:
709 /* Only the condition */
710 return (src == 0);
711 default:
712 return false;
713 }
714 }
715
716 static bool
717 mir_accept_dest_mod(compiler_context *ctx, nir_dest **dest, nir_op op)
718 {
719 if (pan_has_dest_mod(dest, op)) {
720 assert((*dest)->is_ssa);
721 BITSET_SET(ctx->already_emitted, (*dest)->ssa.index);
722 return true;
723 }
724
725 return false;
726 }
727
728 /* Look for floating point mods. We have the mods fsat, fsat_signed,
729 * and fpos. We also have the relations (note 3 * 2 = 6 cases):
730 *
731 * fsat_signed(fpos(x)) = fsat(x)
732 * fsat_signed(fsat(x)) = fsat(x)
733 * fpos(fsat_signed(x)) = fsat(x)
734 * fpos(fsat(x)) = fsat(x)
735 * fsat(fsat_signed(x)) = fsat(x)
736 * fsat(fpos(x)) = fsat(x)
737 *
738 * So by cases any composition of output modifiers is equivalent to
739 * fsat alone.
740 */
741 static unsigned
742 mir_determine_float_outmod(compiler_context *ctx, nir_dest **dest, unsigned prior_outmod)
743 {
744 bool fpos = mir_accept_dest_mod(ctx, dest, nir_op_fclamp_pos);
745 bool fsat = mir_accept_dest_mod(ctx, dest, nir_op_fsat);
746 bool ssat = mir_accept_dest_mod(ctx, dest, nir_op_fsat_signed);
747 bool prior = (prior_outmod != midgard_outmod_none);
748 int count = (int) prior + (int) fpos + (int) ssat + (int) fsat;
749
750 return ((count > 1) || fsat) ? midgard_outmod_sat :
751 fpos ? midgard_outmod_pos :
752 ssat ? midgard_outmod_sat_signed :
753 prior_outmod;
754 }
755
756 static void
757 mir_copy_src(midgard_instruction *ins, nir_alu_instr *instr, unsigned i, unsigned to, bool *abs, bool *neg, bool *not, enum midgard_roundmode *roundmode, bool is_int, unsigned bcast_count)
758 {
759 nir_alu_src src = instr->src[i];
760
761 if (!is_int) {
762 if (pan_has_source_mod(&src, nir_op_fneg))
763 *neg = !(*neg);
764
765 if (pan_has_source_mod(&src, nir_op_fabs))
766 *abs = true;
767 }
768
769 if (nir_accepts_inot(instr->op, i) && pan_has_source_mod(&src, nir_op_inot))
770 *not = true;
771
772 if (roundmode) {
773 if (pan_has_source_mod(&src, nir_op_fround_even))
774 *roundmode = MIDGARD_RTE;
775
776 if (pan_has_source_mod(&src, nir_op_ftrunc))
777 *roundmode = MIDGARD_RTZ;
778
779 if (pan_has_source_mod(&src, nir_op_ffloor))
780 *roundmode = MIDGARD_RTN;
781
782 if (pan_has_source_mod(&src, nir_op_fceil))
783 *roundmode = MIDGARD_RTP;
784 }
785
786 unsigned bits = nir_src_bit_size(src.src);
787
788 ins->src[to] = nir_src_index(NULL, &src.src);
789 ins->src_types[to] = nir_op_infos[instr->op].input_types[i] | bits;
790
791 for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
792 ins->swizzle[to][c] = src.swizzle[
793 (!bcast_count || c < bcast_count) ? c :
794 (bcast_count - 1)];
795 }
796 }
797
798 /* Midgard features both fcsel and icsel, depending on whether you want int or
799 * float modifiers. NIR's csel is typeless, so we want a heuristic to guess if
800 * we should emit an int or float csel depending on what modifiers could be
801 * placed. In the absense of modifiers, this is probably arbitrary. */
802
803 static bool
804 mir_is_bcsel_float(nir_alu_instr *instr)
805 {
806 nir_op intmods[] = {
807 nir_op_i2i8, nir_op_i2i16,
808 nir_op_i2i32, nir_op_i2i64
809 };
810
811 nir_op floatmods[] = {
812 nir_op_fabs, nir_op_fneg,
813 nir_op_f2f16, nir_op_f2f32,
814 nir_op_f2f64
815 };
816
817 nir_op floatdestmods[] = {
818 nir_op_fsat, nir_op_fsat_signed, nir_op_fclamp_pos,
819 nir_op_f2f16, nir_op_f2f32
820 };
821
822 signed score = 0;
823
824 for (unsigned i = 1; i < 3; ++i) {
825 nir_alu_src s = instr->src[i];
826 for (unsigned q = 0; q < ARRAY_SIZE(intmods); ++q) {
827 if (pan_has_source_mod(&s, intmods[q]))
828 score--;
829 }
830 }
831
832 for (unsigned i = 1; i < 3; ++i) {
833 nir_alu_src s = instr->src[i];
834 for (unsigned q = 0; q < ARRAY_SIZE(floatmods); ++q) {
835 if (pan_has_source_mod(&s, floatmods[q]))
836 score++;
837 }
838 }
839
840 for (unsigned q = 0; q < ARRAY_SIZE(floatdestmods); ++q) {
841 nir_dest *dest = &instr->dest.dest;
842 if (pan_has_dest_mod(&dest, floatdestmods[q]))
843 score++;
844 }
845
846 return (score > 0);
847 }
848
849 static void
850 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
851 {
852 nir_dest *dest = &instr->dest.dest;
853
854 if (dest->is_ssa && BITSET_TEST(ctx->already_emitted, dest->ssa.index))
855 return;
856
857 /* Derivatives end up emitted on the texture pipe, not the ALUs. This
858 * is handled elsewhere */
859
860 if (instr->op == nir_op_fddx || instr->op == nir_op_fddy) {
861 midgard_emit_derivatives(ctx, instr);
862 return;
863 }
864
865 bool is_ssa = dest->is_ssa;
866
867 unsigned nr_components = nir_dest_num_components(*dest);
868 unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
869 unsigned op = 0;
870
871 /* Number of components valid to check for the instruction (the rest
872 * will be forced to the last), or 0 to use as-is. Relevant as
873 * ball-type instructions have a channel count in NIR but are all vec4
874 * in Midgard */
875
876 unsigned broadcast_swizzle = 0;
877
878 /* Should we swap arguments? */
879 bool flip_src12 = false;
880
881 ASSERTED unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
882 ASSERTED unsigned dst_bitsize = nir_dest_bit_size(*dest);
883
884 enum midgard_roundmode roundmode = MIDGARD_RTE;
885
886 switch (instr->op) {
887 ALU_CASE(fadd, fadd);
888 ALU_CASE(fmul, fmul);
889 ALU_CASE(fmin, fmin);
890 ALU_CASE(fmax, fmax);
891 ALU_CASE(imin, imin);
892 ALU_CASE(imax, imax);
893 ALU_CASE(umin, umin);
894 ALU_CASE(umax, umax);
895 ALU_CASE(ffloor, ffloor);
896 ALU_CASE(fround_even, froundeven);
897 ALU_CASE(ftrunc, ftrunc);
898 ALU_CASE(fceil, fceil);
899 ALU_CASE(fdot3, fdot3);
900 ALU_CASE(fdot4, fdot4);
901 ALU_CASE(iadd, iadd);
902 ALU_CASE(isub, isub);
903 ALU_CASE(imul, imul);
904 ALU_CASE(imul_high, imul);
905 ALU_CASE(umul_high, imul);
906
907 /* Zero shoved as second-arg */
908 ALU_CASE(iabs, iabsdiff);
909
910 ALU_CASE(mov, imov);
911
912 ALU_CASE_CMP(feq32, feq, false);
913 ALU_CASE_CMP(fneu32, fne, false);
914 ALU_CASE_CMP(flt32, flt, false);
915 ALU_CASE_CMP(ieq32, ieq, true);
916 ALU_CASE_CMP(ine32, ine, true);
917 ALU_CASE_CMP(ilt32, ilt, true);
918 ALU_CASE_CMP(ult32, ult, false);
919
920 /* We don't have a native b2f32 instruction. Instead, like many
921 * GPUs, we exploit booleans as 0/~0 for false/true, and
922 * correspondingly AND
923 * by 1.0 to do the type conversion. For the moment, prime us
924 * to emit:
925 *
926 * iand [whatever], #0
927 *
928 * At the end of emit_alu (as MIR), we'll fix-up the constant
929 */
930
931 ALU_CASE_CMP(b2f32, iand, true);
932 ALU_CASE_CMP(b2f16, iand, true);
933 ALU_CASE_CMP(b2i32, iand, true);
934
935 /* Likewise, we don't have a dedicated f2b32 instruction, but
936 * we can do a "not equal to 0.0" test. */
937
938 ALU_CASE_CMP(f2b32, fne, false);
939 ALU_CASE_CMP(i2b32, ine, true);
940
941 ALU_CASE(frcp, frcp);
942 ALU_CASE(frsq, frsqrt);
943 ALU_CASE(fsqrt, fsqrt);
944 ALU_CASE(fexp2, fexp2);
945 ALU_CASE(flog2, flog2);
946
947 ALU_CASE_RTZ(f2i64, f2i_rte);
948 ALU_CASE_RTZ(f2u64, f2u_rte);
949 ALU_CASE_RTZ(i2f64, i2f_rte);
950 ALU_CASE_RTZ(u2f64, u2f_rte);
951
952 ALU_CASE_RTZ(f2i32, f2i_rte);
953 ALU_CASE_RTZ(f2u32, f2u_rte);
954 ALU_CASE_RTZ(i2f32, i2f_rte);
955 ALU_CASE_RTZ(u2f32, u2f_rte);
956
957 ALU_CASE_RTZ(f2i8, f2i_rte);
958 ALU_CASE_RTZ(f2u8, f2u_rte);
959
960 ALU_CASE_RTZ(f2i16, f2i_rte);
961 ALU_CASE_RTZ(f2u16, f2u_rte);
962 ALU_CASE_RTZ(i2f16, i2f_rte);
963 ALU_CASE_RTZ(u2f16, u2f_rte);
964
965 ALU_CASE(fsin, fsin);
966 ALU_CASE(fcos, fcos);
967
968 /* We'll get 0 in the second arg, so:
969 * ~a = ~(a | 0) = nor(a, 0) */
970 ALU_CASE(inot, inor);
971 ALU_CASE(iand, iand);
972 ALU_CASE(ior, ior);
973 ALU_CASE(ixor, ixor);
974 ALU_CASE(ishl, ishl);
975 ALU_CASE(ishr, iasr);
976 ALU_CASE(ushr, ilsr);
977
978 ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
979 ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
980 ALU_CASE_CMP(b32all_fequal4, fball_eq, true);
981
982 ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
983 ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
984 ALU_CASE_CMP(b32any_fnequal4, fbany_neq, true);
985
986 ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
987 ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
988 ALU_CASE_CMP(b32all_iequal4, iball_eq, true);
989
990 ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
991 ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
992 ALU_CASE_CMP(b32any_inequal4, ibany_neq, true);
993
994 /* Source mods will be shoved in later */
995 ALU_CASE(fabs, fmov);
996 ALU_CASE(fneg, fmov);
997 ALU_CASE(fsat, fmov);
998 ALU_CASE(fsat_signed, fmov);
999 ALU_CASE(fclamp_pos, fmov);
1000
1001 /* For size conversion, we use a move. Ideally though we would squash
1002 * these ops together; maybe that has to happen after in NIR as part of
1003 * propagation...? An earlier algebraic pass ensured we step down by
1004 * only / exactly one size. If stepping down, we use a dest override to
1005 * reduce the size; if stepping up, we use a larger-sized move with a
1006 * half source and a sign/zero-extension modifier */
1007
1008 case nir_op_i2i8:
1009 case nir_op_i2i16:
1010 case nir_op_i2i32:
1011 case nir_op_i2i64:
1012 case nir_op_u2u8:
1013 case nir_op_u2u16:
1014 case nir_op_u2u32:
1015 case nir_op_u2u64:
1016 case nir_op_f2f16:
1017 case nir_op_f2f32:
1018 case nir_op_f2f64: {
1019 if (instr->op == nir_op_f2f16 || instr->op == nir_op_f2f32 ||
1020 instr->op == nir_op_f2f64)
1021 op = midgard_alu_op_fmov;
1022 else
1023 op = midgard_alu_op_imov;
1024
1025 break;
1026 }
1027
1028 /* For greater-or-equal, we lower to less-or-equal and flip the
1029 * arguments */
1030
1031 case nir_op_fge:
1032 case nir_op_fge32:
1033 case nir_op_ige32:
1034 case nir_op_uge32: {
1035 op =
1036 instr->op == nir_op_fge ? midgard_alu_op_fle :
1037 instr->op == nir_op_fge32 ? midgard_alu_op_fle :
1038 instr->op == nir_op_ige32 ? midgard_alu_op_ile :
1039 instr->op == nir_op_uge32 ? midgard_alu_op_ule :
1040 0;
1041
1042 flip_src12 = true;
1043 ALU_CHECK_CMP(false);
1044 break;
1045 }
1046
1047 case nir_op_b32csel: {
1048 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
1049 bool is_float = mir_is_bcsel_float(instr);
1050 op = is_float ?
1051 (mixed ? midgard_alu_op_fcsel_v : midgard_alu_op_fcsel) :
1052 (mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel);
1053
1054 break;
1055 }
1056
1057 case nir_op_unpack_32_2x16:
1058 case nir_op_unpack_32_4x8:
1059 case nir_op_pack_32_2x16:
1060 case nir_op_pack_32_4x8: {
1061 op = midgard_alu_op_imov;
1062 break;
1063 }
1064
1065 default:
1066 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
1067 assert(0);
1068 return;
1069 }
1070
1071 /* Promote imov to fmov if it might help inline a constant */
1072 if (op == midgard_alu_op_imov && nir_src_is_const(instr->src[0].src)
1073 && nir_src_bit_size(instr->src[0].src) == 32
1074 && nir_is_same_comp_swizzle(instr->src[0].swizzle,
1075 nir_src_num_components(instr->src[0].src))) {
1076 op = midgard_alu_op_fmov;
1077 }
1078
1079 /* Midgard can perform certain modifiers on output of an ALU op */
1080
1081 unsigned outmod = 0;
1082 bool is_int = midgard_is_integer_op(op);
1083
1084 if (instr->op == nir_op_umul_high || instr->op == nir_op_imul_high) {
1085 outmod = midgard_outmod_int_high;
1086 } else if (midgard_is_integer_out_op(op)) {
1087 outmod = midgard_outmod_int_wrap;
1088 } else if (instr->op == nir_op_fsat) {
1089 outmod = midgard_outmod_sat;
1090 } else if (instr->op == nir_op_fsat_signed) {
1091 outmod = midgard_outmod_sat_signed;
1092 } else if (instr->op == nir_op_fclamp_pos) {
1093 outmod = midgard_outmod_pos;
1094 }
1095
1096 /* Fetch unit, quirks, etc information */
1097 unsigned opcode_props = alu_opcode_props[op].props;
1098 bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
1099
1100 if (!midgard_is_integer_out_op(op)) {
1101 outmod = mir_determine_float_outmod(ctx, &dest, outmod);
1102 }
1103
1104 midgard_instruction ins = {
1105 .type = TAG_ALU_4,
1106 .dest = nir_dest_index(dest),
1107 .dest_type = nir_op_infos[instr->op].output_type
1108 | nir_dest_bit_size(*dest),
1109 .roundmode = roundmode,
1110 };
1111
1112 enum midgard_roundmode *roundptr = (opcode_props & MIDGARD_ROUNDS) ?
1113 &ins.roundmode : NULL;
1114
1115 for (unsigned i = nr_inputs; i < ARRAY_SIZE(ins.src); ++i)
1116 ins.src[i] = ~0;
1117
1118 if (quirk_flipped_r24) {
1119 ins.src[0] = ~0;
1120 mir_copy_src(&ins, instr, 0, 1, &ins.src_abs[1], &ins.src_neg[1], &ins.src_invert[1], roundptr, is_int, broadcast_swizzle);
1121 } else {
1122 for (unsigned i = 0; i < nr_inputs; ++i) {
1123 unsigned to = i;
1124
1125 if (instr->op == nir_op_b32csel) {
1126 /* The condition is the first argument; move
1127 * the other arguments up one to be a binary
1128 * instruction for Midgard with the condition
1129 * last */
1130
1131 if (i == 0)
1132 to = 2;
1133 else if (flip_src12)
1134 to = 2 - i;
1135 else
1136 to = i - 1;
1137 } else if (flip_src12) {
1138 to = 1 - to;
1139 }
1140
1141 mir_copy_src(&ins, instr, i, to, &ins.src_abs[to], &ins.src_neg[to], &ins.src_invert[to], roundptr, is_int, broadcast_swizzle);
1142
1143 /* (!c) ? a : b = c ? b : a */
1144 if (instr->op == nir_op_b32csel && ins.src_invert[2]) {
1145 ins.src_invert[2] = false;
1146 flip_src12 ^= true;
1147 }
1148 }
1149 }
1150
1151 if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
1152 /* Lowered to move */
1153 if (instr->op == nir_op_fneg)
1154 ins.src_neg[1] ^= true;
1155
1156 if (instr->op == nir_op_fabs)
1157 ins.src_abs[1] = true;
1158 }
1159
1160 ins.mask = mask_of(nr_components);
1161
1162 /* Apply writemask if non-SSA, keeping in mind that we can't write to
1163 * components that don't exist. Note modifier => SSA => !reg => no
1164 * writemask, so we don't have to worry about writemasks here.*/
1165
1166 if (!is_ssa)
1167 ins.mask &= instr->dest.write_mask;
1168
1169 ins.op = op;
1170 ins.outmod = outmod;
1171
1172 /* Late fixup for emulated instructions */
1173
1174 if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
1175 /* Presently, our second argument is an inline #0 constant.
1176 * Switch over to an embedded 1.0 constant (that can't fit
1177 * inline, since we're 32-bit, not 16-bit like the inline
1178 * constants) */
1179
1180 ins.has_inline_constant = false;
1181 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1182 ins.src_types[1] = nir_type_float32;
1183 ins.has_constants = true;
1184
1185 if (instr->op == nir_op_b2f32)
1186 ins.constants.f32[0] = 1.0f;
1187 else
1188 ins.constants.i32[0] = 1;
1189
1190 for (unsigned c = 0; c < 16; ++c)
1191 ins.swizzle[1][c] = 0;
1192 } else if (instr->op == nir_op_b2f16) {
1193 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1194 ins.src_types[1] = nir_type_float16;
1195 ins.has_constants = true;
1196 ins.constants.i16[0] = _mesa_float_to_half(1.0);
1197
1198 for (unsigned c = 0; c < 16; ++c)
1199 ins.swizzle[1][c] = 0;
1200 } else if (nr_inputs == 1 && !quirk_flipped_r24) {
1201 /* Lots of instructions need a 0 plonked in */
1202 ins.has_inline_constant = false;
1203 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1204 ins.src_types[1] = ins.src_types[0];
1205 ins.has_constants = true;
1206 ins.constants.u32[0] = 0;
1207
1208 for (unsigned c = 0; c < 16; ++c)
1209 ins.swizzle[1][c] = 0;
1210 } else if (instr->op == nir_op_pack_32_2x16) {
1211 ins.dest_type = nir_type_uint16;
1212 ins.mask = mask_of(nr_components * 2);
1213 ins.is_pack = true;
1214 } else if (instr->op == nir_op_pack_32_4x8) {
1215 ins.dest_type = nir_type_uint8;
1216 ins.mask = mask_of(nr_components * 4);
1217 ins.is_pack = true;
1218 } else if (instr->op == nir_op_unpack_32_2x16) {
1219 ins.dest_type = nir_type_uint32;
1220 ins.mask = mask_of(nr_components >> 1);
1221 ins.is_pack = true;
1222 } else if (instr->op == nir_op_unpack_32_4x8) {
1223 ins.dest_type = nir_type_uint32;
1224 ins.mask = mask_of(nr_components >> 2);
1225 ins.is_pack = true;
1226 }
1227
1228 if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
1229 /* To avoid duplicating the lookup tables (probably), true LUT
1230 * instructions can only operate as if they were scalars. Lower
1231 * them here by changing the component. */
1232
1233 unsigned orig_mask = ins.mask;
1234
1235 unsigned swizzle_back[MIR_VEC_COMPONENTS];
1236 memcpy(&swizzle_back, ins.swizzle[0], sizeof(swizzle_back));
1237
1238 midgard_instruction ins_split[MIR_VEC_COMPONENTS];
1239 unsigned ins_count = 0;
1240
1241 for (int i = 0; i < nr_components; ++i) {
1242 /* Mask the associated component, dropping the
1243 * instruction if needed */
1244
1245 ins.mask = 1 << i;
1246 ins.mask &= orig_mask;
1247
1248 for (unsigned j = 0; j < ins_count; ++j) {
1249 if (swizzle_back[i] == ins_split[j].swizzle[0][0]) {
1250 ins_split[j].mask |= ins.mask;
1251 ins.mask = 0;
1252 break;
1253 }
1254 }
1255
1256 if (!ins.mask)
1257 continue;
1258
1259 for (unsigned j = 0; j < MIR_VEC_COMPONENTS; ++j)
1260 ins.swizzle[0][j] = swizzle_back[i]; /* Pull from the correct component */
1261
1262 ins_split[ins_count] = ins;
1263
1264 ++ins_count;
1265 }
1266
1267 for (unsigned i = 0; i < ins_count; ++i) {
1268 emit_mir_instruction(ctx, ins_split[i]);
1269 }
1270 } else {
1271 emit_mir_instruction(ctx, ins);
1272 }
1273 }
1274
1275 #undef ALU_CASE
1276
1277 static void
1278 mir_set_intr_mask(nir_instr *instr, midgard_instruction *ins, bool is_read)
1279 {
1280 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1281 unsigned nir_mask = 0;
1282 unsigned dsize = 0;
1283
1284 if (is_read) {
1285 nir_mask = mask_of(nir_intrinsic_dest_components(intr));
1286 dsize = nir_dest_bit_size(intr->dest);
1287 } else {
1288 nir_mask = nir_intrinsic_write_mask(intr);
1289 dsize = 32;
1290 }
1291
1292 /* Once we have the NIR mask, we need to normalize to work in 32-bit space */
1293 unsigned bytemask = pan_to_bytemask(dsize, nir_mask);
1294 ins->dest_type = nir_type_uint | dsize;
1295 mir_set_bytemask(ins, bytemask);
1296 }
1297
1298 /* Uniforms and UBOs use a shared code path, as uniforms are just (slightly
1299 * optimized) versions of UBO #0 */
1300
1301 static midgard_instruction *
1302 emit_ubo_read(
1303 compiler_context *ctx,
1304 nir_instr *instr,
1305 unsigned dest,
1306 unsigned offset,
1307 nir_src *indirect_offset,
1308 unsigned indirect_shift,
1309 unsigned index)
1310 {
1311 /* TODO: half-floats */
1312
1313 midgard_instruction ins = m_ld_ubo_int4(dest, 0);
1314 ins.constants.u32[0] = offset;
1315
1316 if (instr->type == nir_instr_type_intrinsic)
1317 mir_set_intr_mask(instr, &ins, true);
1318
1319 if (indirect_offset) {
1320 ins.src[2] = nir_src_index(ctx, indirect_offset);
1321 ins.src_types[2] = nir_type_uint32;
1322 ins.load_store.arg_2 = (indirect_shift << 5);
1323
1324 /* X component for the whole swizzle to prevent register
1325 * pressure from ballooning from the extra components */
1326 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[2]); ++i)
1327 ins.swizzle[2][i] = 0;
1328 } else {
1329 ins.load_store.arg_2 = 0x1E;
1330 }
1331
1332 ins.load_store.arg_1 = index;
1333
1334 return emit_mir_instruction(ctx, ins);
1335 }
1336
1337 /* Globals are like UBOs if you squint. And shared memory is like globals if
1338 * you squint even harder */
1339
1340 static void
1341 emit_global(
1342 compiler_context *ctx,
1343 nir_instr *instr,
1344 bool is_read,
1345 unsigned srcdest,
1346 nir_src *offset,
1347 bool is_shared)
1348 {
1349 /* TODO: types */
1350
1351 midgard_instruction ins;
1352
1353 if (is_read)
1354 ins = m_ld_int4(srcdest, 0);
1355 else
1356 ins = m_st_int4(srcdest, 0);
1357
1358 mir_set_offset(ctx, &ins, offset, is_shared);
1359 mir_set_intr_mask(instr, &ins, is_read);
1360
1361 /* Set a valid swizzle for masked out components */
1362 assert(ins.mask);
1363 unsigned first_component = __builtin_ffs(ins.mask) - 1;
1364
1365 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i) {
1366 if (!(ins.mask & (1 << i)))
1367 ins.swizzle[0][i] = first_component;
1368 }
1369
1370 emit_mir_instruction(ctx, ins);
1371 }
1372
1373 static void
1374 emit_varying_read(
1375 compiler_context *ctx,
1376 unsigned dest, unsigned offset,
1377 unsigned nr_comp, unsigned component,
1378 nir_src *indirect_offset, nir_alu_type type, bool flat)
1379 {
1380 /* XXX: Half-floats? */
1381 /* TODO: swizzle, mask */
1382
1383 midgard_instruction ins = m_ld_vary_32(dest, offset);
1384 ins.mask = mask_of(nr_comp);
1385 ins.dest_type = type;
1386
1387 if (type == nir_type_float16) {
1388 /* Ensure we are aligned so we can pack it later */
1389 ins.mask = mask_of(ALIGN_POT(nr_comp, 2));
1390 }
1391
1392 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i)
1393 ins.swizzle[0][i] = MIN2(i + component, COMPONENT_W);
1394
1395 midgard_varying_parameter p = {
1396 .is_varying = 1,
1397 .interpolation = midgard_interp_default,
1398 .flat = flat,
1399 };
1400
1401 unsigned u;
1402 memcpy(&u, &p, sizeof(p));
1403 ins.load_store.varying_parameters = u;
1404
1405 if (indirect_offset) {
1406 ins.src[2] = nir_src_index(ctx, indirect_offset);
1407 ins.src_types[2] = nir_type_uint32;
1408 } else
1409 ins.load_store.arg_2 = 0x1E;
1410
1411 ins.load_store.arg_1 = 0x9E;
1412
1413 /* Use the type appropriate load */
1414 switch (type) {
1415 case nir_type_uint32:
1416 case nir_type_bool32:
1417 ins.op = midgard_op_ld_vary_32u;
1418 break;
1419 case nir_type_int32:
1420 ins.op = midgard_op_ld_vary_32i;
1421 break;
1422 case nir_type_float32:
1423 ins.op = midgard_op_ld_vary_32;
1424 break;
1425 case nir_type_float16:
1426 ins.op = midgard_op_ld_vary_16;
1427 break;
1428 default:
1429 unreachable("Attempted to load unknown type");
1430 break;
1431 }
1432
1433 emit_mir_instruction(ctx, ins);
1434 }
1435
1436 static void
1437 emit_attr_read(
1438 compiler_context *ctx,
1439 unsigned dest, unsigned offset,
1440 unsigned nr_comp, nir_alu_type t)
1441 {
1442 midgard_instruction ins = m_ld_attr_32(dest, offset);
1443 ins.load_store.arg_1 = 0x1E;
1444 ins.load_store.arg_2 = 0x1E;
1445 ins.mask = mask_of(nr_comp);
1446
1447 /* Use the type appropriate load */
1448 switch (t) {
1449 case nir_type_uint:
1450 case nir_type_bool:
1451 ins.op = midgard_op_ld_attr_32u;
1452 break;
1453 case nir_type_int:
1454 ins.op = midgard_op_ld_attr_32i;
1455 break;
1456 case nir_type_float:
1457 ins.op = midgard_op_ld_attr_32;
1458 break;
1459 default:
1460 unreachable("Attempted to load unknown type");
1461 break;
1462 }
1463
1464 emit_mir_instruction(ctx, ins);
1465 }
1466
1467 static void
1468 emit_sysval_read(compiler_context *ctx, nir_instr *instr,
1469 unsigned nr_components, unsigned offset)
1470 {
1471 nir_dest nir_dest;
1472
1473 /* Figure out which uniform this is */
1474 int sysval = panfrost_sysval_for_instr(instr, &nir_dest);
1475 void *val = _mesa_hash_table_u64_search(ctx->sysvals.sysval_to_id, sysval);
1476
1477 unsigned dest = nir_dest_index(&nir_dest);
1478
1479 /* Sysvals are prefix uniforms */
1480 unsigned uniform = ((uintptr_t) val) - 1;
1481
1482 /* Emit the read itself -- this is never indirect */
1483 midgard_instruction *ins =
1484 emit_ubo_read(ctx, instr, dest, (uniform * 16) + offset, NULL, 0, 0);
1485
1486 ins->mask = mask_of(nr_components);
1487 }
1488
1489 static unsigned
1490 compute_builtin_arg(nir_op op)
1491 {
1492 switch (op) {
1493 case nir_intrinsic_load_work_group_id:
1494 return 0x14;
1495 case nir_intrinsic_load_local_invocation_id:
1496 return 0x10;
1497 default:
1498 unreachable("Invalid compute paramater loaded");
1499 }
1500 }
1501
1502 static void
1503 emit_fragment_store(compiler_context *ctx, unsigned src, unsigned src_z, unsigned src_s, enum midgard_rt_id rt)
1504 {
1505 assert(rt < ARRAY_SIZE(ctx->writeout_branch));
1506
1507 midgard_instruction *br = ctx->writeout_branch[rt];
1508
1509 assert(!br);
1510
1511 emit_explicit_constant(ctx, src, src);
1512
1513 struct midgard_instruction ins =
1514 v_branch(false, false);
1515
1516 bool depth_only = (rt == MIDGARD_ZS_RT);
1517
1518 ins.writeout = depth_only ? 0 : PAN_WRITEOUT_C;
1519
1520 /* Add dependencies */
1521 ins.src[0] = src;
1522 ins.src_types[0] = nir_type_uint32;
1523 ins.constants.u32[0] = depth_only ? 0xFF : (rt - MIDGARD_COLOR_RT0) * 0x100;
1524 for (int i = 0; i < 4; ++i)
1525 ins.swizzle[0][i] = i;
1526
1527 if (~src_z) {
1528 emit_explicit_constant(ctx, src_z, src_z);
1529 ins.src[2] = src_z;
1530 ins.src_types[2] = nir_type_uint32;
1531 ins.writeout |= PAN_WRITEOUT_Z;
1532 }
1533 if (~src_s) {
1534 emit_explicit_constant(ctx, src_s, src_s);
1535 ins.src[3] = src_s;
1536 ins.src_types[3] = nir_type_uint32;
1537 ins.writeout |= PAN_WRITEOUT_S;
1538 }
1539
1540 /* Emit the branch */
1541 br = emit_mir_instruction(ctx, ins);
1542 schedule_barrier(ctx);
1543 ctx->writeout_branch[rt] = br;
1544
1545 /* Push our current location = current block count - 1 = where we'll
1546 * jump to. Maybe a bit too clever for my own good */
1547
1548 br->branch.target_block = ctx->block_count - 1;
1549 }
1550
1551 static void
1552 emit_compute_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1553 {
1554 unsigned reg = nir_dest_index(&instr->dest);
1555 midgard_instruction ins = m_ld_compute_id(reg, 0);
1556 ins.mask = mask_of(3);
1557 ins.swizzle[0][3] = COMPONENT_X; /* xyzx */
1558 ins.load_store.arg_1 = compute_builtin_arg(instr->intrinsic);
1559 emit_mir_instruction(ctx, ins);
1560 }
1561
1562 static unsigned
1563 vertex_builtin_arg(nir_op op)
1564 {
1565 switch (op) {
1566 case nir_intrinsic_load_vertex_id:
1567 return PAN_VERTEX_ID;
1568 case nir_intrinsic_load_instance_id:
1569 return PAN_INSTANCE_ID;
1570 default:
1571 unreachable("Invalid vertex builtin");
1572 }
1573 }
1574
1575 static void
1576 emit_vertex_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1577 {
1578 unsigned reg = nir_dest_index(&instr->dest);
1579 emit_attr_read(ctx, reg, vertex_builtin_arg(instr->intrinsic), 1, nir_type_int);
1580 }
1581
1582 static void
1583 emit_special(compiler_context *ctx, nir_intrinsic_instr *instr, unsigned idx)
1584 {
1585 unsigned reg = nir_dest_index(&instr->dest);
1586
1587 midgard_instruction ld = m_ld_color_buffer_32u(reg, 0);
1588 ld.op = midgard_op_ld_color_buffer_32u_old;
1589 ld.load_store.address = idx;
1590 ld.load_store.arg_2 = 0x1E;
1591
1592 for (int i = 0; i < 4; ++i)
1593 ld.swizzle[0][i] = COMPONENT_X;
1594
1595 emit_mir_instruction(ctx, ld);
1596 }
1597
1598 static void
1599 emit_control_barrier(compiler_context *ctx)
1600 {
1601 midgard_instruction ins = {
1602 .type = TAG_TEXTURE_4,
1603 .dest = ~0,
1604 .src = { ~0, ~0, ~0, ~0 },
1605 .op = TEXTURE_OP_BARRIER,
1606 };
1607
1608 emit_mir_instruction(ctx, ins);
1609 }
1610
1611 static unsigned
1612 mir_get_branch_cond(nir_src *src, bool *invert)
1613 {
1614 /* Wrap it. No swizzle since it's a scalar */
1615
1616 nir_alu_src alu = {
1617 .src = *src
1618 };
1619
1620 *invert = pan_has_source_mod(&alu, nir_op_inot);
1621 return nir_src_index(NULL, &alu.src);
1622 }
1623
1624 static uint8_t
1625 output_load_rt_addr(compiler_context *ctx, nir_intrinsic_instr *instr)
1626 {
1627 if (ctx->is_blend)
1628 return ctx->blend_rt;
1629
1630 const nir_variable *var;
1631 var = search_var(ctx->nir, nir_var_shader_out, nir_intrinsic_base(instr));
1632 assert(var);
1633
1634 unsigned loc = var->data.location;
1635
1636 if (loc == FRAG_RESULT_COLOR)
1637 loc = FRAG_RESULT_DATA0;
1638
1639 if (loc >= FRAG_RESULT_DATA0)
1640 return loc - FRAG_RESULT_DATA0;
1641
1642 if (loc == FRAG_RESULT_DEPTH)
1643 return 0x1F;
1644 if (loc == FRAG_RESULT_STENCIL)
1645 return 0x1E;
1646
1647 unreachable("Invalid RT to load from");
1648 }
1649
1650 static void
1651 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1652 {
1653 unsigned offset = 0, reg;
1654
1655 switch (instr->intrinsic) {
1656 case nir_intrinsic_discard_if:
1657 case nir_intrinsic_discard: {
1658 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1659 struct midgard_instruction discard = v_branch(conditional, false);
1660 discard.branch.target_type = TARGET_DISCARD;
1661
1662 if (conditional) {
1663 discard.src[0] = mir_get_branch_cond(&instr->src[0],
1664 &discard.branch.invert_conditional);
1665 discard.src_types[0] = nir_type_uint32;
1666 }
1667
1668 emit_mir_instruction(ctx, discard);
1669 schedule_barrier(ctx);
1670
1671 break;
1672 }
1673
1674 case nir_intrinsic_load_uniform:
1675 case nir_intrinsic_load_ubo:
1676 case nir_intrinsic_load_global:
1677 case nir_intrinsic_load_shared:
1678 case nir_intrinsic_load_input:
1679 case nir_intrinsic_load_interpolated_input: {
1680 bool is_uniform = instr->intrinsic == nir_intrinsic_load_uniform;
1681 bool is_ubo = instr->intrinsic == nir_intrinsic_load_ubo;
1682 bool is_global = instr->intrinsic == nir_intrinsic_load_global;
1683 bool is_shared = instr->intrinsic == nir_intrinsic_load_shared;
1684 bool is_flat = instr->intrinsic == nir_intrinsic_load_input;
1685 bool is_interp = instr->intrinsic == nir_intrinsic_load_interpolated_input;
1686
1687 /* Get the base type of the intrinsic */
1688 /* TODO: Infer type? Does it matter? */
1689 nir_alu_type t =
1690 (is_ubo || is_global || is_shared) ? nir_type_uint :
1691 (is_interp) ? nir_type_float :
1692 nir_intrinsic_type(instr);
1693
1694 t = nir_alu_type_get_base_type(t);
1695
1696 if (!(is_ubo || is_global)) {
1697 offset = nir_intrinsic_base(instr);
1698 }
1699
1700 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1701
1702 nir_src *src_offset = nir_get_io_offset_src(instr);
1703
1704 bool direct = nir_src_is_const(*src_offset);
1705 nir_src *indirect_offset = direct ? NULL : src_offset;
1706
1707 if (direct)
1708 offset += nir_src_as_uint(*src_offset);
1709
1710 /* We may need to apply a fractional offset */
1711 int component = (is_flat || is_interp) ?
1712 nir_intrinsic_component(instr) : 0;
1713 reg = nir_dest_index(&instr->dest);
1714
1715 if (is_uniform && !ctx->is_blend) {
1716 emit_ubo_read(ctx, &instr->instr, reg, (ctx->sysvals.sysval_count + offset) * 16, indirect_offset, 4, 0);
1717 } else if (is_ubo) {
1718 nir_src index = instr->src[0];
1719
1720 /* TODO: Is indirect block number possible? */
1721 assert(nir_src_is_const(index));
1722
1723 uint32_t uindex = nir_src_as_uint(index) + 1;
1724 emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0, uindex);
1725 } else if (is_global || is_shared) {
1726 emit_global(ctx, &instr->instr, true, reg, src_offset, is_shared);
1727 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->is_blend) {
1728 emit_varying_read(ctx, reg, offset, nr_comp, component, indirect_offset, t | nir_dest_bit_size(instr->dest), is_flat);
1729 } else if (ctx->is_blend) {
1730 /* ctx->blend_input will be precoloured to r0/r2, where
1731 * the input is preloaded */
1732
1733 unsigned *input = offset ? &ctx->blend_src1 : &ctx->blend_input;
1734
1735 if (*input == ~0)
1736 *input = reg;
1737 else
1738 emit_mir_instruction(ctx, v_mov(*input, reg));
1739 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1740 emit_attr_read(ctx, reg, offset, nr_comp, t);
1741 } else {
1742 DBG("Unknown load\n");
1743 assert(0);
1744 }
1745
1746 break;
1747 }
1748
1749 /* Artefact of load_interpolated_input. TODO: other barycentric modes */
1750 case nir_intrinsic_load_barycentric_pixel:
1751 case nir_intrinsic_load_barycentric_centroid:
1752 break;
1753
1754 /* Reads 128-bit value raw off the tilebuffer during blending, tasty */
1755
1756 case nir_intrinsic_load_raw_output_pan: {
1757 reg = nir_dest_index(&instr->dest);
1758
1759 /* T720 and below use different blend opcodes with slightly
1760 * different semantics than T760 and up */
1761
1762 midgard_instruction ld = m_ld_color_buffer_32u(reg, 0);
1763
1764 ld.load_store.arg_2 = output_load_rt_addr(ctx, instr);
1765
1766 if (nir_src_is_const(instr->src[0])) {
1767 ld.load_store.arg_1 = nir_src_as_uint(instr->src[0]);
1768 } else {
1769 ld.load_store.varying_parameters = 2;
1770 ld.src[1] = nir_src_index(ctx, &instr->src[0]);
1771 ld.src_types[1] = nir_type_int32;
1772 }
1773
1774 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1775 ld.op = midgard_op_ld_color_buffer_32u_old;
1776 ld.load_store.address = 16;
1777 ld.load_store.arg_2 = 0x1E;
1778 }
1779
1780 emit_mir_instruction(ctx, ld);
1781 break;
1782 }
1783
1784 case nir_intrinsic_load_output: {
1785 reg = nir_dest_index(&instr->dest);
1786
1787 unsigned bits = nir_dest_bit_size(instr->dest);
1788
1789 midgard_instruction ld;
1790 if (bits == 16)
1791 ld = m_ld_color_buffer_as_fp16(reg, 0);
1792 else
1793 ld = m_ld_color_buffer_as_fp32(reg, 0);
1794
1795 ld.load_store.arg_2 = output_load_rt_addr(ctx, instr);
1796
1797 for (unsigned c = 4; c < 16; ++c)
1798 ld.swizzle[0][c] = 0;
1799
1800 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1801 if (bits == 16)
1802 ld.op = midgard_op_ld_color_buffer_as_fp16_old;
1803 else
1804 ld.op = midgard_op_ld_color_buffer_as_fp32_old;
1805 ld.load_store.address = 1;
1806 ld.load_store.arg_2 = 0x1E;
1807 }
1808
1809 emit_mir_instruction(ctx, ld);
1810 break;
1811 }
1812
1813 case nir_intrinsic_load_blend_const_color_rgba: {
1814 assert(ctx->is_blend);
1815 reg = nir_dest_index(&instr->dest);
1816
1817 /* Blend constants are embedded directly in the shader and
1818 * patched in, so we use some magic routing */
1819
1820 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), reg);
1821 ins.has_constants = true;
1822 ins.has_blend_constant = true;
1823 emit_mir_instruction(ctx, ins);
1824 break;
1825 }
1826
1827 case nir_intrinsic_store_output:
1828 case nir_intrinsic_store_combined_output_pan:
1829 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1830
1831 offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1832
1833 reg = nir_src_index(ctx, &instr->src[0]);
1834
1835 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1836 bool combined = instr->intrinsic ==
1837 nir_intrinsic_store_combined_output_pan;
1838
1839 const nir_variable *var;
1840 var = search_var(ctx->nir, nir_var_shader_out,
1841 nir_intrinsic_base(instr));
1842 assert(var);
1843
1844 /* Dual-source blend writeout is done by leaving the
1845 * value in r2 for the blend shader to use. */
1846 if (var->data.index) {
1847 if (instr->src[0].is_ssa) {
1848 emit_explicit_constant(ctx, reg, reg);
1849
1850 unsigned out = make_compiler_temp(ctx);
1851
1852 midgard_instruction ins = v_mov(reg, out);
1853 emit_mir_instruction(ctx, ins);
1854
1855 ctx->blend_src1 = out;
1856 } else {
1857 ctx->blend_src1 = reg;
1858 }
1859
1860 break;
1861 }
1862
1863 enum midgard_rt_id rt;
1864 if (var->data.location == FRAG_RESULT_COLOR)
1865 rt = MIDGARD_COLOR_RT0;
1866 else if (var->data.location >= FRAG_RESULT_DATA0)
1867 rt = MIDGARD_COLOR_RT0 + var->data.location -
1868 FRAG_RESULT_DATA0;
1869 else if (combined)
1870 rt = MIDGARD_ZS_RT;
1871 else
1872 unreachable("bad rt");
1873
1874 unsigned reg_z = ~0, reg_s = ~0;
1875 if (combined) {
1876 unsigned writeout = nir_intrinsic_component(instr);
1877 if (writeout & PAN_WRITEOUT_Z)
1878 reg_z = nir_src_index(ctx, &instr->src[2]);
1879 if (writeout & PAN_WRITEOUT_S)
1880 reg_s = nir_src_index(ctx, &instr->src[3]);
1881 }
1882
1883 emit_fragment_store(ctx, reg, reg_z, reg_s, rt);
1884 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1885 assert(instr->intrinsic == nir_intrinsic_store_output);
1886
1887 /* We should have been vectorized, though we don't
1888 * currently check that st_vary is emitted only once
1889 * per slot (this is relevant, since there's not a mask
1890 * parameter available on the store [set to 0 by the
1891 * blob]). We do respect the component by adjusting the
1892 * swizzle. If this is a constant source, we'll need to
1893 * emit that explicitly. */
1894
1895 emit_explicit_constant(ctx, reg, reg);
1896
1897 unsigned dst_component = nir_intrinsic_component(instr);
1898 unsigned nr_comp = nir_src_num_components(instr->src[0]);
1899
1900 midgard_instruction st = m_st_vary_32(reg, offset);
1901 st.load_store.arg_1 = 0x9E;
1902 st.load_store.arg_2 = 0x1E;
1903
1904 switch (nir_alu_type_get_base_type(nir_intrinsic_type(instr))) {
1905 case nir_type_uint:
1906 case nir_type_bool:
1907 st.op = midgard_op_st_vary_32u;
1908 break;
1909 case nir_type_int:
1910 st.op = midgard_op_st_vary_32i;
1911 break;
1912 case nir_type_float:
1913 st.op = midgard_op_st_vary_32;
1914 break;
1915 default:
1916 unreachable("Attempted to store unknown type");
1917 break;
1918 }
1919
1920 /* nir_intrinsic_component(store_intr) encodes the
1921 * destination component start. Source component offset
1922 * adjustment is taken care of in
1923 * install_registers_instr(), when offset_swizzle() is
1924 * called.
1925 */
1926 unsigned src_component = COMPONENT_X;
1927
1928 assert(nr_comp > 0);
1929 for (unsigned i = 0; i < ARRAY_SIZE(st.swizzle); ++i) {
1930 st.swizzle[0][i] = src_component;
1931 if (i >= dst_component && i < dst_component + nr_comp - 1)
1932 src_component++;
1933 }
1934
1935 emit_mir_instruction(ctx, st);
1936 } else {
1937 DBG("Unknown store\n");
1938 assert(0);
1939 }
1940
1941 break;
1942
1943 /* Special case of store_output for lowered blend shaders */
1944 case nir_intrinsic_store_raw_output_pan:
1945 assert (ctx->stage == MESA_SHADER_FRAGMENT);
1946 reg = nir_src_index(ctx, &instr->src[0]);
1947 emit_fragment_store(ctx, reg, ~0, ~0, ctx->blend_rt);
1948 break;
1949
1950 case nir_intrinsic_store_global:
1951 case nir_intrinsic_store_shared:
1952 reg = nir_src_index(ctx, &instr->src[0]);
1953 emit_explicit_constant(ctx, reg, reg);
1954
1955 emit_global(ctx, &instr->instr, false, reg, &instr->src[1], instr->intrinsic == nir_intrinsic_store_shared);
1956 break;
1957
1958 case nir_intrinsic_load_ssbo_address:
1959 emit_sysval_read(ctx, &instr->instr, 1, 0);
1960 break;
1961
1962 case nir_intrinsic_get_buffer_size:
1963 emit_sysval_read(ctx, &instr->instr, 1, 8);
1964 break;
1965
1966 case nir_intrinsic_load_viewport_scale:
1967 case nir_intrinsic_load_viewport_offset:
1968 case nir_intrinsic_load_num_work_groups:
1969 case nir_intrinsic_load_sampler_lod_parameters_pan:
1970 emit_sysval_read(ctx, &instr->instr, 3, 0);
1971 break;
1972
1973 case nir_intrinsic_load_work_group_id:
1974 case nir_intrinsic_load_local_invocation_id:
1975 emit_compute_builtin(ctx, instr);
1976 break;
1977
1978 case nir_intrinsic_load_vertex_id:
1979 case nir_intrinsic_load_instance_id:
1980 emit_vertex_builtin(ctx, instr);
1981 break;
1982
1983 case nir_intrinsic_load_sample_mask_in:
1984 emit_special(ctx, instr, 96);
1985 break;
1986
1987 case nir_intrinsic_load_sample_id:
1988 emit_special(ctx, instr, 97);
1989 break;
1990
1991 case nir_intrinsic_memory_barrier_buffer:
1992 case nir_intrinsic_memory_barrier_shared:
1993 break;
1994
1995 case nir_intrinsic_control_barrier:
1996 schedule_barrier(ctx);
1997 emit_control_barrier(ctx);
1998 schedule_barrier(ctx);
1999 break;
2000
2001 default:
2002 fprintf(stderr, "Unhandled intrinsic %s\n", nir_intrinsic_infos[instr->intrinsic].name);
2003 assert(0);
2004 break;
2005 }
2006 }
2007
2008 /* Returns dimension with 0 special casing cubemaps */
2009 static unsigned
2010 midgard_tex_format(enum glsl_sampler_dim dim)
2011 {
2012 switch (dim) {
2013 case GLSL_SAMPLER_DIM_1D:
2014 case GLSL_SAMPLER_DIM_BUF:
2015 return 1;
2016
2017 case GLSL_SAMPLER_DIM_2D:
2018 case GLSL_SAMPLER_DIM_MS:
2019 case GLSL_SAMPLER_DIM_EXTERNAL:
2020 case GLSL_SAMPLER_DIM_RECT:
2021 return 2;
2022
2023 case GLSL_SAMPLER_DIM_3D:
2024 return 3;
2025
2026 case GLSL_SAMPLER_DIM_CUBE:
2027 return 0;
2028
2029 default:
2030 DBG("Unknown sampler dim type\n");
2031 assert(0);
2032 return 0;
2033 }
2034 }
2035
2036 /* Tries to attach an explicit LOD or bias as a constant. Returns whether this
2037 * was successful */
2038
2039 static bool
2040 pan_attach_constant_bias(
2041 compiler_context *ctx,
2042 nir_src lod,
2043 midgard_texture_word *word)
2044 {
2045 /* To attach as constant, it has to *be* constant */
2046
2047 if (!nir_src_is_const(lod))
2048 return false;
2049
2050 float f = nir_src_as_float(lod);
2051
2052 /* Break into fixed-point */
2053 signed lod_int = f;
2054 float lod_frac = f - lod_int;
2055
2056 /* Carry over negative fractions */
2057 if (lod_frac < 0.0) {
2058 lod_int--;
2059 lod_frac += 1.0;
2060 }
2061
2062 /* Encode */
2063 word->bias = float_to_ubyte(lod_frac);
2064 word->bias_int = lod_int;
2065
2066 return true;
2067 }
2068
2069 static enum mali_texture_mode
2070 mdg_texture_mode(nir_tex_instr *instr)
2071 {
2072 if (instr->op == nir_texop_tg4 && instr->is_shadow)
2073 return TEXTURE_GATHER_SHADOW;
2074 else if (instr->op == nir_texop_tg4)
2075 return TEXTURE_GATHER_X + instr->component;
2076 else if (instr->is_shadow)
2077 return TEXTURE_SHADOW;
2078 else
2079 return TEXTURE_NORMAL;
2080 }
2081
2082 static void
2083 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
2084 unsigned midgard_texop)
2085 {
2086 /* TODO */
2087 //assert (!instr->sampler);
2088
2089 nir_dest *dest = &instr->dest;
2090
2091 int texture_index = instr->texture_index;
2092 int sampler_index = texture_index;
2093
2094 nir_alu_type dest_base = nir_alu_type_get_base_type(instr->dest_type);
2095 nir_alu_type dest_type = dest_base | nir_dest_bit_size(*dest);
2096
2097 /* texture instructions support float outmods */
2098 unsigned outmod = midgard_outmod_none;
2099 if (dest_base == nir_type_float) {
2100 outmod = mir_determine_float_outmod(ctx, &dest, 0);
2101 }
2102
2103 midgard_instruction ins = {
2104 .type = TAG_TEXTURE_4,
2105 .mask = 0xF,
2106 .dest = nir_dest_index(dest),
2107 .src = { ~0, ~0, ~0, ~0 },
2108 .dest_type = dest_type,
2109 .swizzle = SWIZZLE_IDENTITY_4,
2110 .outmod = outmod,
2111 .op = midgard_texop,
2112 .texture = {
2113 .format = midgard_tex_format(instr->sampler_dim),
2114 .texture_handle = texture_index,
2115 .sampler_handle = sampler_index,
2116 .mode = mdg_texture_mode(instr)
2117 }
2118 };
2119
2120 if (instr->is_shadow && !instr->is_new_style_shadow && instr->op != nir_texop_tg4)
2121 for (int i = 0; i < 4; ++i)
2122 ins.swizzle[0][i] = COMPONENT_X;
2123
2124 /* We may need a temporary for the coordinate */
2125
2126 bool needs_temp_coord =
2127 (midgard_texop == TEXTURE_OP_TEXEL_FETCH) ||
2128 (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) ||
2129 (instr->is_shadow);
2130
2131 unsigned coords = needs_temp_coord ? make_compiler_temp_reg(ctx) : 0;
2132
2133 for (unsigned i = 0; i < instr->num_srcs; ++i) {
2134 int index = nir_src_index(ctx, &instr->src[i].src);
2135 unsigned nr_components = nir_src_num_components(instr->src[i].src);
2136 unsigned sz = nir_src_bit_size(instr->src[i].src);
2137 nir_alu_type T = nir_tex_instr_src_type(instr, i) | sz;
2138
2139 switch (instr->src[i].src_type) {
2140 case nir_tex_src_coord: {
2141 emit_explicit_constant(ctx, index, index);
2142
2143 unsigned coord_mask = mask_of(instr->coord_components);
2144
2145 bool flip_zw = (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) && (coord_mask & (1 << COMPONENT_Z));
2146
2147 if (flip_zw)
2148 coord_mask ^= ((1 << COMPONENT_Z) | (1 << COMPONENT_W));
2149
2150 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
2151 /* texelFetch is undefined on samplerCube */
2152 assert(midgard_texop != TEXTURE_OP_TEXEL_FETCH);
2153
2154 /* For cubemaps, we use a special ld/st op to
2155 * select the face and copy the xy into the
2156 * texture register */
2157
2158 midgard_instruction ld = m_ld_cubemap_coords(coords, 0);
2159 ld.src[1] = index;
2160 ld.src_types[1] = T;
2161 ld.mask = 0x3; /* xy */
2162 ld.load_store.arg_1 = 0x20;
2163 ld.swizzle[1][3] = COMPONENT_X;
2164 emit_mir_instruction(ctx, ld);
2165
2166 /* xyzw -> xyxx */
2167 ins.swizzle[1][2] = instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
2168 ins.swizzle[1][3] = COMPONENT_X;
2169 } else if (needs_temp_coord) {
2170 /* mov coord_temp, coords */
2171 midgard_instruction mov = v_mov(index, coords);
2172 mov.mask = coord_mask;
2173
2174 if (flip_zw)
2175 mov.swizzle[1][COMPONENT_W] = COMPONENT_Z;
2176
2177 emit_mir_instruction(ctx, mov);
2178 } else {
2179 coords = index;
2180 }
2181
2182 ins.src[1] = coords;
2183 ins.src_types[1] = T;
2184
2185 /* Texelfetch coordinates uses all four elements
2186 * (xyz/index) regardless of texture dimensionality,
2187 * which means it's necessary to zero the unused
2188 * components to keep everything happy */
2189
2190 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
2191 /* mov index.zw, #0, or generalized */
2192 midgard_instruction mov =
2193 v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), coords);
2194 mov.has_constants = true;
2195 mov.mask = coord_mask ^ 0xF;
2196 emit_mir_instruction(ctx, mov);
2197 }
2198
2199 if (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) {
2200 /* Array component in w but NIR wants it in z,
2201 * but if we have a temp coord we already fixed
2202 * that up */
2203
2204 if (nr_components == 3) {
2205 ins.swizzle[1][2] = COMPONENT_Z;
2206 ins.swizzle[1][3] = needs_temp_coord ? COMPONENT_W : COMPONENT_Z;
2207 } else if (nr_components == 2) {
2208 ins.swizzle[1][2] =
2209 instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
2210 ins.swizzle[1][3] = COMPONENT_X;
2211 } else
2212 unreachable("Invalid texture 2D components");
2213 }
2214
2215 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
2216 /* We zeroed */
2217 ins.swizzle[1][2] = COMPONENT_Z;
2218 ins.swizzle[1][3] = COMPONENT_W;
2219 }
2220
2221 break;
2222 }
2223
2224 case nir_tex_src_bias:
2225 case nir_tex_src_lod: {
2226 /* Try as a constant if we can */
2227
2228 bool is_txf = midgard_texop == TEXTURE_OP_TEXEL_FETCH;
2229 if (!is_txf && pan_attach_constant_bias(ctx, instr->src[i].src, &ins.texture))
2230 break;
2231
2232 ins.texture.lod_register = true;
2233 ins.src[2] = index;
2234 ins.src_types[2] = T;
2235
2236 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2237 ins.swizzle[2][c] = COMPONENT_X;
2238
2239 emit_explicit_constant(ctx, index, index);
2240
2241 break;
2242 };
2243
2244 case nir_tex_src_offset: {
2245 ins.texture.offset_register = true;
2246 ins.src[3] = index;
2247 ins.src_types[3] = T;
2248
2249 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2250 ins.swizzle[3][c] = (c > COMPONENT_Z) ? 0 : c;
2251
2252 emit_explicit_constant(ctx, index, index);
2253 break;
2254 };
2255
2256 case nir_tex_src_comparator:
2257 case nir_tex_src_ms_index: {
2258 unsigned comp = COMPONENT_Z;
2259
2260 /* mov coord_temp.foo, coords */
2261 midgard_instruction mov = v_mov(index, coords);
2262 mov.mask = 1 << comp;
2263
2264 for (unsigned i = 0; i < MIR_VEC_COMPONENTS; ++i)
2265 mov.swizzle[1][i] = COMPONENT_X;
2266
2267 emit_mir_instruction(ctx, mov);
2268 break;
2269 }
2270
2271 default: {
2272 fprintf(stderr, "Unknown texture source type: %d\n", instr->src[i].src_type);
2273 assert(0);
2274 }
2275 }
2276 }
2277
2278 emit_mir_instruction(ctx, ins);
2279 }
2280
2281 static void
2282 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
2283 {
2284 switch (instr->op) {
2285 case nir_texop_tex:
2286 case nir_texop_txb:
2287 emit_texop_native(ctx, instr, TEXTURE_OP_NORMAL);
2288 break;
2289 case nir_texop_txl:
2290 case nir_texop_tg4:
2291 emit_texop_native(ctx, instr, TEXTURE_OP_LOD);
2292 break;
2293 case nir_texop_txf:
2294 case nir_texop_txf_ms:
2295 emit_texop_native(ctx, instr, TEXTURE_OP_TEXEL_FETCH);
2296 break;
2297 case nir_texop_txs:
2298 emit_sysval_read(ctx, &instr->instr, 4, 0);
2299 break;
2300 default: {
2301 fprintf(stderr, "Unhandled texture op: %d\n", instr->op);
2302 assert(0);
2303 }
2304 }
2305 }
2306
2307 static void
2308 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
2309 {
2310 switch (instr->type) {
2311 case nir_jump_break: {
2312 /* Emit a branch out of the loop */
2313 struct midgard_instruction br = v_branch(false, false);
2314 br.branch.target_type = TARGET_BREAK;
2315 br.branch.target_break = ctx->current_loop_depth;
2316 emit_mir_instruction(ctx, br);
2317 break;
2318 }
2319
2320 default:
2321 DBG("Unknown jump type %d\n", instr->type);
2322 break;
2323 }
2324 }
2325
2326 static void
2327 emit_instr(compiler_context *ctx, struct nir_instr *instr)
2328 {
2329 switch (instr->type) {
2330 case nir_instr_type_load_const:
2331 emit_load_const(ctx, nir_instr_as_load_const(instr));
2332 break;
2333
2334 case nir_instr_type_intrinsic:
2335 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
2336 break;
2337
2338 case nir_instr_type_alu:
2339 emit_alu(ctx, nir_instr_as_alu(instr));
2340 break;
2341
2342 case nir_instr_type_tex:
2343 emit_tex(ctx, nir_instr_as_tex(instr));
2344 break;
2345
2346 case nir_instr_type_jump:
2347 emit_jump(ctx, nir_instr_as_jump(instr));
2348 break;
2349
2350 case nir_instr_type_ssa_undef:
2351 /* Spurious */
2352 break;
2353
2354 default:
2355 DBG("Unhandled instruction type\n");
2356 break;
2357 }
2358 }
2359
2360
2361 /* ALU instructions can inline or embed constants, which decreases register
2362 * pressure and saves space. */
2363
2364 #define CONDITIONAL_ATTACH(idx) { \
2365 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[idx] + 1); \
2366 \
2367 if (entry) { \
2368 attach_constants(ctx, alu, entry, alu->src[idx] + 1); \
2369 alu->src[idx] = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
2370 } \
2371 }
2372
2373 static void
2374 inline_alu_constants(compiler_context *ctx, midgard_block *block)
2375 {
2376 mir_foreach_instr_in_block(block, alu) {
2377 /* Other instructions cannot inline constants */
2378 if (alu->type != TAG_ALU_4) continue;
2379 if (alu->compact_branch) continue;
2380
2381 /* If there is already a constant here, we can do nothing */
2382 if (alu->has_constants) continue;
2383
2384 CONDITIONAL_ATTACH(0);
2385
2386 if (!alu->has_constants) {
2387 CONDITIONAL_ATTACH(1)
2388 } else if (!alu->inline_constant) {
2389 /* Corner case: _two_ vec4 constants, for instance with a
2390 * csel. For this case, we can only use a constant
2391 * register for one, we'll have to emit a move for the
2392 * other. */
2393
2394 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[1] + 1);
2395 unsigned scratch = make_compiler_temp(ctx);
2396
2397 if (entry) {
2398 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), scratch);
2399 attach_constants(ctx, &ins, entry, alu->src[1] + 1);
2400
2401 /* Set the source */
2402 alu->src[1] = scratch;
2403
2404 /* Inject us -before- the last instruction which set r31 */
2405 mir_insert_instruction_before(ctx, mir_prev_op(alu), ins);
2406 }
2407 }
2408 }
2409 }
2410
2411 unsigned
2412 max_bitsize_for_alu(midgard_instruction *ins)
2413 {
2414 unsigned max_bitsize = 0;
2415 for (int i = 0; i < MIR_SRC_COUNT; i++) {
2416 if (ins->src[i] == ~0) continue;
2417 unsigned src_bitsize = nir_alu_type_get_type_size(ins->src_types[i]);
2418 max_bitsize = MAX2(src_bitsize, max_bitsize);
2419 }
2420 unsigned dst_bitsize = nir_alu_type_get_type_size(ins->dest_type);
2421 max_bitsize = MAX2(dst_bitsize, max_bitsize);
2422
2423 /* We don't have fp16 LUTs, so we'll want to emit code like:
2424 *
2425 * vlut.fsinr hr0, hr0
2426 *
2427 * where both input and output are 16-bit but the operation is carried
2428 * out in 32-bit
2429 */
2430
2431 switch (ins->op) {
2432 case midgard_alu_op_fsqrt:
2433 case midgard_alu_op_frcp:
2434 case midgard_alu_op_frsqrt:
2435 case midgard_alu_op_fsin:
2436 case midgard_alu_op_fcos:
2437 case midgard_alu_op_fexp2:
2438 case midgard_alu_op_flog2:
2439 max_bitsize = MAX2(max_bitsize, 32);
2440 break;
2441
2442 default:
2443 break;
2444 }
2445
2446 /* High implies computing at a higher bitsize, e.g umul_high of 32-bit
2447 * requires computing at 64-bit */
2448 if (midgard_is_integer_out_op(ins->op) && ins->outmod == midgard_outmod_int_high) {
2449 max_bitsize *= 2;
2450 assert(max_bitsize <= 64);
2451 }
2452
2453 return max_bitsize;
2454 }
2455
2456 midgard_reg_mode
2457 reg_mode_for_bitsize(unsigned bitsize)
2458 {
2459 switch (bitsize) {
2460 /* use 16 pipe for 8 since we don't support vec16 yet */
2461 case 8:
2462 case 16:
2463 return midgard_reg_mode_16;
2464 case 32:
2465 return midgard_reg_mode_32;
2466 case 64:
2467 return midgard_reg_mode_64;
2468 default:
2469 unreachable("invalid bit size");
2470 }
2471 }
2472
2473 /* Midgard supports two types of constants, embedded constants (128-bit) and
2474 * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2475 * constants can be demoted to inline constants, for space savings and
2476 * sometimes a performance boost */
2477
2478 static void
2479 embedded_to_inline_constant(compiler_context *ctx, midgard_block *block)
2480 {
2481 mir_foreach_instr_in_block(block, ins) {
2482 if (!ins->has_constants) continue;
2483 if (ins->has_inline_constant) continue;
2484
2485 /* Blend constants must not be inlined by definition */
2486 if (ins->has_blend_constant) continue;
2487
2488 unsigned max_bitsize = max_bitsize_for_alu(ins);
2489
2490 /* We can inline 32-bit (sometimes) or 16-bit (usually) */
2491 bool is_16 = max_bitsize == 16;
2492 bool is_32 = max_bitsize == 32;
2493
2494 if (!(is_16 || is_32))
2495 continue;
2496
2497 /* src1 cannot be an inline constant due to encoding
2498 * restrictions. So, if possible we try to flip the arguments
2499 * in that case */
2500
2501 int op = ins->op;
2502
2503 if (ins->src[0] == SSA_FIXED_REGISTER(REGISTER_CONSTANT) &&
2504 alu_opcode_props[op].props & OP_COMMUTES) {
2505 mir_flip(ins);
2506 }
2507
2508 if (ins->src[1] == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2509 /* Component is from the swizzle. Take a nonzero component */
2510 assert(ins->mask);
2511 unsigned first_comp = ffs(ins->mask) - 1;
2512 unsigned component = ins->swizzle[1][first_comp];
2513
2514 /* Scale constant appropriately, if we can legally */
2515 int16_t scaled_constant = 0;
2516
2517 if (is_16) {
2518 scaled_constant = ins->constants.u16[component];
2519 } else if (midgard_is_integer_op(op)) {
2520 scaled_constant = ins->constants.u32[component];
2521
2522 /* Constant overflow after resize */
2523 if (scaled_constant != ins->constants.u32[component])
2524 continue;
2525 } else {
2526 float original = ins->constants.f32[component];
2527 scaled_constant = _mesa_float_to_half(original);
2528
2529 /* Check for loss of precision. If this is
2530 * mediump, we don't care, but for a highp
2531 * shader, we need to pay attention. NIR
2532 * doesn't yet tell us which mode we're in!
2533 * Practically this prevents most constants
2534 * from being inlined, sadly. */
2535
2536 float fp32 = _mesa_half_to_float(scaled_constant);
2537
2538 if (fp32 != original)
2539 continue;
2540 }
2541
2542 /* Should've been const folded */
2543 if (ins->src_abs[1] || ins->src_neg[1])
2544 continue;
2545
2546 /* Make sure that the constant is not itself a vector
2547 * by checking if all accessed values are the same. */
2548
2549 const midgard_constants *cons = &ins->constants;
2550 uint32_t value = is_16 ? cons->u16[component] : cons->u32[component];
2551
2552 bool is_vector = false;
2553 unsigned mask = effective_writemask(ins->op, ins->mask);
2554
2555 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c) {
2556 /* We only care if this component is actually used */
2557 if (!(mask & (1 << c)))
2558 continue;
2559
2560 uint32_t test = is_16 ?
2561 cons->u16[ins->swizzle[1][c]] :
2562 cons->u32[ins->swizzle[1][c]];
2563
2564 if (test != value) {
2565 is_vector = true;
2566 break;
2567 }
2568 }
2569
2570 if (is_vector)
2571 continue;
2572
2573 /* Get rid of the embedded constant */
2574 ins->has_constants = false;
2575 ins->src[1] = ~0;
2576 ins->has_inline_constant = true;
2577 ins->inline_constant = scaled_constant;
2578 }
2579 }
2580 }
2581
2582 /* Dead code elimination for branches at the end of a block - only one branch
2583 * per block is legal semantically */
2584
2585 static void
2586 midgard_cull_dead_branch(compiler_context *ctx, midgard_block *block)
2587 {
2588 bool branched = false;
2589
2590 mir_foreach_instr_in_block_safe(block, ins) {
2591 if (!midgard_is_branch_unit(ins->unit)) continue;
2592
2593 if (branched)
2594 mir_remove_instruction(ins);
2595
2596 branched = true;
2597 }
2598 }
2599
2600 /* We want to force the invert on AND/OR to the second slot to legalize into
2601 * iandnot/iornot. The relevant patterns are for AND (and OR respectively)
2602 *
2603 * ~a & #b = ~a & ~(#~b)
2604 * ~a & b = b & ~a
2605 */
2606
2607 static void
2608 midgard_legalize_invert(compiler_context *ctx, midgard_block *block)
2609 {
2610 mir_foreach_instr_in_block(block, ins) {
2611 if (ins->type != TAG_ALU_4) continue;
2612
2613 if (ins->op != midgard_alu_op_iand &&
2614 ins->op != midgard_alu_op_ior) continue;
2615
2616 if (ins->src_invert[1] || !ins->src_invert[0]) continue;
2617
2618 if (ins->has_inline_constant) {
2619 /* ~(#~a) = ~(~#a) = a, so valid, and forces both
2620 * inverts on */
2621 ins->inline_constant = ~ins->inline_constant;
2622 ins->src_invert[1] = true;
2623 } else {
2624 /* Flip to the right invert order. Note
2625 * has_inline_constant false by assumption on the
2626 * branch, so flipping makes sense. */
2627 mir_flip(ins);
2628 }
2629 }
2630 }
2631
2632 static unsigned
2633 emit_fragment_epilogue(compiler_context *ctx, unsigned rt)
2634 {
2635 /* Loop to ourselves */
2636 midgard_instruction *br = ctx->writeout_branch[rt];
2637 struct midgard_instruction ins = v_branch(false, false);
2638 ins.writeout = br->writeout;
2639 ins.branch.target_block = ctx->block_count - 1;
2640 ins.constants.u32[0] = br->constants.u32[0];
2641 memcpy(&ins.src_types, &br->src_types, sizeof(ins.src_types));
2642 emit_mir_instruction(ctx, ins);
2643
2644 ctx->current_block->epilogue = true;
2645 schedule_barrier(ctx);
2646 return ins.branch.target_block;
2647 }
2648
2649 static midgard_block *
2650 emit_block_init(compiler_context *ctx)
2651 {
2652 midgard_block *this_block = ctx->after_block;
2653 ctx->after_block = NULL;
2654
2655 if (!this_block)
2656 this_block = create_empty_block(ctx);
2657
2658 list_addtail(&this_block->base.link, &ctx->blocks);
2659
2660 this_block->scheduled = false;
2661 ++ctx->block_count;
2662
2663 /* Set up current block */
2664 list_inithead(&this_block->base.instructions);
2665 ctx->current_block = this_block;
2666
2667 return this_block;
2668 }
2669
2670 static midgard_block *
2671 emit_block(compiler_context *ctx, nir_block *block)
2672 {
2673 midgard_block *this_block = emit_block_init(ctx);
2674
2675 nir_foreach_instr(instr, block) {
2676 emit_instr(ctx, instr);
2677 ++ctx->instruction_count;
2678 }
2679
2680 return this_block;
2681 }
2682
2683 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2684
2685 static void
2686 emit_if(struct compiler_context *ctx, nir_if *nif)
2687 {
2688 midgard_block *before_block = ctx->current_block;
2689
2690 /* Speculatively emit the branch, but we can't fill it in until later */
2691 bool inv = false;
2692 EMIT(branch, true, true);
2693 midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2694 then_branch->src[0] = mir_get_branch_cond(&nif->condition, &inv);
2695 then_branch->src_types[0] = nir_type_uint32;
2696 then_branch->branch.invert_conditional = !inv;
2697
2698 /* Emit the two subblocks. */
2699 midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2700 midgard_block *end_then_block = ctx->current_block;
2701
2702 /* Emit a jump from the end of the then block to the end of the else */
2703 EMIT(branch, false, false);
2704 midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2705
2706 /* Emit second block, and check if it's empty */
2707
2708 int else_idx = ctx->block_count;
2709 int count_in = ctx->instruction_count;
2710 midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2711 midgard_block *end_else_block = ctx->current_block;
2712 int after_else_idx = ctx->block_count;
2713
2714 /* Now that we have the subblocks emitted, fix up the branches */
2715
2716 assert(then_block);
2717 assert(else_block);
2718
2719 if (ctx->instruction_count == count_in) {
2720 /* The else block is empty, so don't emit an exit jump */
2721 mir_remove_instruction(then_exit);
2722 then_branch->branch.target_block = after_else_idx;
2723 } else {
2724 then_branch->branch.target_block = else_idx;
2725 then_exit->branch.target_block = after_else_idx;
2726 }
2727
2728 /* Wire up the successors */
2729
2730 ctx->after_block = create_empty_block(ctx);
2731
2732 pan_block_add_successor(&before_block->base, &then_block->base);
2733 pan_block_add_successor(&before_block->base, &else_block->base);
2734
2735 pan_block_add_successor(&end_then_block->base, &ctx->after_block->base);
2736 pan_block_add_successor(&end_else_block->base, &ctx->after_block->base);
2737 }
2738
2739 static void
2740 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2741 {
2742 /* Remember where we are */
2743 midgard_block *start_block = ctx->current_block;
2744
2745 /* Allocate a loop number, growing the current inner loop depth */
2746 int loop_idx = ++ctx->current_loop_depth;
2747
2748 /* Get index from before the body so we can loop back later */
2749 int start_idx = ctx->block_count;
2750
2751 /* Emit the body itself */
2752 midgard_block *loop_block = emit_cf_list(ctx, &nloop->body);
2753
2754 /* Branch back to loop back */
2755 struct midgard_instruction br_back = v_branch(false, false);
2756 br_back.branch.target_block = start_idx;
2757 emit_mir_instruction(ctx, br_back);
2758
2759 /* Mark down that branch in the graph. */
2760 pan_block_add_successor(&start_block->base, &loop_block->base);
2761 pan_block_add_successor(&ctx->current_block->base, &loop_block->base);
2762
2763 /* Find the index of the block about to follow us (note: we don't add
2764 * one; blocks are 0-indexed so we get a fencepost problem) */
2765 int break_block_idx = ctx->block_count;
2766
2767 /* Fix up the break statements we emitted to point to the right place,
2768 * now that we can allocate a block number for them */
2769 ctx->after_block = create_empty_block(ctx);
2770
2771 mir_foreach_block_from(ctx, start_block, _block) {
2772 mir_foreach_instr_in_block(((midgard_block *) _block), ins) {
2773 if (ins->type != TAG_ALU_4) continue;
2774 if (!ins->compact_branch) continue;
2775
2776 /* We found a branch -- check the type to see if we need to do anything */
2777 if (ins->branch.target_type != TARGET_BREAK) continue;
2778
2779 /* It's a break! Check if it's our break */
2780 if (ins->branch.target_break != loop_idx) continue;
2781
2782 /* Okay, cool, we're breaking out of this loop.
2783 * Rewrite from a break to a goto */
2784
2785 ins->branch.target_type = TARGET_GOTO;
2786 ins->branch.target_block = break_block_idx;
2787
2788 pan_block_add_successor(_block, &ctx->after_block->base);
2789 }
2790 }
2791
2792 /* Now that we've finished emitting the loop, free up the depth again
2793 * so we play nice with recursion amid nested loops */
2794 --ctx->current_loop_depth;
2795
2796 /* Dump loop stats */
2797 ++ctx->loop_count;
2798 }
2799
2800 static midgard_block *
2801 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
2802 {
2803 midgard_block *start_block = NULL;
2804
2805 foreach_list_typed(nir_cf_node, node, node, list) {
2806 switch (node->type) {
2807 case nir_cf_node_block: {
2808 midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
2809
2810 if (!start_block)
2811 start_block = block;
2812
2813 break;
2814 }
2815
2816 case nir_cf_node_if:
2817 emit_if(ctx, nir_cf_node_as_if(node));
2818 break;
2819
2820 case nir_cf_node_loop:
2821 emit_loop(ctx, nir_cf_node_as_loop(node));
2822 break;
2823
2824 case nir_cf_node_function:
2825 assert(0);
2826 break;
2827 }
2828 }
2829
2830 return start_block;
2831 }
2832
2833 /* Due to lookahead, we need to report the first tag executed in the command
2834 * stream and in branch targets. An initial block might be empty, so iterate
2835 * until we find one that 'works' */
2836
2837 unsigned
2838 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
2839 {
2840 midgard_block *initial_block = mir_get_block(ctx, block_idx);
2841
2842 mir_foreach_block_from(ctx, initial_block, _v) {
2843 midgard_block *v = (midgard_block *) _v;
2844 if (v->quadword_count) {
2845 midgard_bundle *initial_bundle =
2846 util_dynarray_element(&v->bundles, midgard_bundle, 0);
2847
2848 return initial_bundle->tag;
2849 }
2850 }
2851
2852 /* Default to a tag 1 which will break from the shader, in case we jump
2853 * to the exit block (i.e. `return` in a compute shader) */
2854
2855 return 1;
2856 }
2857
2858 /* For each fragment writeout instruction, generate a writeout loop to
2859 * associate with it */
2860
2861 static void
2862 mir_add_writeout_loops(compiler_context *ctx)
2863 {
2864 for (unsigned rt = 0; rt < ARRAY_SIZE(ctx->writeout_branch); ++rt) {
2865 midgard_instruction *br = ctx->writeout_branch[rt];
2866 if (!br) continue;
2867
2868 unsigned popped = br->branch.target_block;
2869 pan_block_add_successor(&(mir_get_block(ctx, popped - 1)->base), &ctx->current_block->base);
2870 br->branch.target_block = emit_fragment_epilogue(ctx, rt);
2871 br->branch.target_type = TARGET_GOTO;
2872
2873 /* If we have more RTs, we'll need to restore back after our
2874 * loop terminates */
2875
2876 if ((rt + 1) < ARRAY_SIZE(ctx->writeout_branch) && ctx->writeout_branch[rt + 1]) {
2877 midgard_instruction uncond = v_branch(false, false);
2878 uncond.branch.target_block = popped;
2879 uncond.branch.target_type = TARGET_GOTO;
2880 emit_mir_instruction(ctx, uncond);
2881 pan_block_add_successor(&ctx->current_block->base, &(mir_get_block(ctx, popped)->base));
2882 schedule_barrier(ctx);
2883 } else {
2884 /* We're last, so we can terminate here */
2885 br->last_writeout = true;
2886 }
2887 }
2888 }
2889
2890 int
2891 midgard_compile_shader_nir(nir_shader *nir, panfrost_program *program, bool is_blend, unsigned blend_rt, unsigned gpu_id, bool shaderdb, bool silent)
2892 {
2893 struct util_dynarray *compiled = &program->compiled;
2894
2895 midgard_debug = debug_get_option_midgard_debug();
2896
2897 /* TODO: Bound against what? */
2898 compiler_context *ctx = rzalloc(NULL, compiler_context);
2899
2900 ctx->nir = nir;
2901 ctx->stage = nir->info.stage;
2902 ctx->is_blend = is_blend;
2903 ctx->blend_rt = MIDGARD_COLOR_RT0 + blend_rt;
2904 ctx->blend_input = ~0;
2905 ctx->blend_src1 = ~0;
2906 ctx->quirks = midgard_get_quirks(gpu_id);
2907
2908 /* Start off with a safe cutoff, allowing usage of all 16 work
2909 * registers. Later, we'll promote uniform reads to uniform registers
2910 * if we determine it is beneficial to do so */
2911 ctx->uniform_cutoff = 8;
2912
2913 /* Initialize at a global (not block) level hash tables */
2914
2915 ctx->ssa_constants = _mesa_hash_table_u64_create(NULL);
2916
2917 /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
2918 * (so we don't accidentally duplicate the epilogue since mesa/st has
2919 * messed with our I/O quite a bit already) */
2920
2921 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2922
2923 if (ctx->stage == MESA_SHADER_VERTEX) {
2924 NIR_PASS_V(nir, nir_lower_viewport_transform);
2925 NIR_PASS_V(nir, nir_lower_point_size, 1.0, 1024.0);
2926 }
2927
2928 NIR_PASS_V(nir, nir_lower_var_copies);
2929 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2930 NIR_PASS_V(nir, nir_split_var_copies);
2931 NIR_PASS_V(nir, nir_lower_var_copies);
2932 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
2933 NIR_PASS_V(nir, nir_lower_var_copies);
2934 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2935
2936 unsigned pan_quirks = panfrost_get_quirks(gpu_id);
2937 NIR_PASS_V(nir, pan_lower_framebuffer,
2938 program->rt_formats, is_blend, pan_quirks);
2939
2940 NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
2941 glsl_type_size, 0);
2942 NIR_PASS_V(nir, nir_lower_ssbo);
2943 NIR_PASS_V(nir, midgard_nir_lower_zs_store);
2944
2945 /* Optimisation passes */
2946
2947 optimise_nir(nir, ctx->quirks, is_blend);
2948
2949 NIR_PASS_V(nir, midgard_nir_reorder_writeout);
2950
2951 if ((midgard_debug & MIDGARD_DBG_SHADERS) && !silent) {
2952 nir_print_shader(nir, stdout);
2953 }
2954
2955 /* Assign sysvals and counts, now that we're sure
2956 * (post-optimisation) */
2957
2958 panfrost_nir_assign_sysvals(&ctx->sysvals, ctx, nir);
2959 program->sysval_count = ctx->sysvals.sysval_count;
2960 memcpy(program->sysvals, ctx->sysvals.sysvals, sizeof(ctx->sysvals.sysvals[0]) * ctx->sysvals.sysval_count);
2961
2962 nir_foreach_function(func, nir) {
2963 if (!func->impl)
2964 continue;
2965
2966 list_inithead(&ctx->blocks);
2967 ctx->block_count = 0;
2968 ctx->func = func;
2969 ctx->already_emitted = calloc(BITSET_WORDS(func->impl->ssa_alloc), sizeof(BITSET_WORD));
2970
2971 if (nir->info.outputs_read && !is_blend) {
2972 emit_block_init(ctx);
2973
2974 struct midgard_instruction wait = v_branch(false, false);
2975 wait.branch.target_type = TARGET_TILEBUF_WAIT;
2976
2977 emit_mir_instruction(ctx, wait);
2978
2979 ++ctx->instruction_count;
2980 }
2981
2982 emit_cf_list(ctx, &func->impl->body);
2983 free(ctx->already_emitted);
2984 break; /* TODO: Multi-function shaders */
2985 }
2986
2987 util_dynarray_init(compiled, NULL);
2988
2989 /* Per-block lowering before opts */
2990
2991 mir_foreach_block(ctx, _block) {
2992 midgard_block *block = (midgard_block *) _block;
2993 inline_alu_constants(ctx, block);
2994 embedded_to_inline_constant(ctx, block);
2995 }
2996 /* MIR-level optimizations */
2997
2998 bool progress = false;
2999
3000 do {
3001 progress = false;
3002 progress |= midgard_opt_dead_code_eliminate(ctx);
3003
3004 mir_foreach_block(ctx, _block) {
3005 midgard_block *block = (midgard_block *) _block;
3006 progress |= midgard_opt_copy_prop(ctx, block);
3007 progress |= midgard_opt_combine_projection(ctx, block);
3008 progress |= midgard_opt_varying_projection(ctx, block);
3009 }
3010 } while (progress);
3011
3012 mir_foreach_block(ctx, _block) {
3013 midgard_block *block = (midgard_block *) _block;
3014 midgard_lower_derivatives(ctx, block);
3015 midgard_legalize_invert(ctx, block);
3016 midgard_cull_dead_branch(ctx, block);
3017 }
3018
3019 if (ctx->stage == MESA_SHADER_FRAGMENT)
3020 mir_add_writeout_loops(ctx);
3021
3022 /* Analyze now that the code is known but before scheduling creates
3023 * pipeline registers which are harder to track */
3024 mir_analyze_helper_terminate(ctx);
3025 mir_analyze_helper_requirements(ctx);
3026
3027 /* Schedule! */
3028 midgard_schedule_program(ctx);
3029 mir_ra(ctx);
3030
3031 /* Emit flat binary from the instruction arrays. Iterate each block in
3032 * sequence. Save instruction boundaries such that lookahead tags can
3033 * be assigned easily */
3034
3035 /* Cache _all_ bundles in source order for lookahead across failed branches */
3036
3037 int bundle_count = 0;
3038 mir_foreach_block(ctx, _block) {
3039 midgard_block *block = (midgard_block *) _block;
3040 bundle_count += block->bundles.size / sizeof(midgard_bundle);
3041 }
3042 midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
3043 int bundle_idx = 0;
3044 mir_foreach_block(ctx, _block) {
3045 midgard_block *block = (midgard_block *) _block;
3046 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3047 source_order_bundles[bundle_idx++] = bundle;
3048 }
3049 }
3050
3051 int current_bundle = 0;
3052
3053 /* Midgard prefetches instruction types, so during emission we
3054 * need to lookahead. Unless this is the last instruction, in
3055 * which we return 1. */
3056
3057 mir_foreach_block(ctx, _block) {
3058 midgard_block *block = (midgard_block *) _block;
3059 mir_foreach_bundle_in_block(block, bundle) {
3060 int lookahead = 1;
3061
3062 if (!bundle->last_writeout && (current_bundle + 1 < bundle_count))
3063 lookahead = source_order_bundles[current_bundle + 1]->tag;
3064
3065 emit_binary_bundle(ctx, block, bundle, compiled, lookahead);
3066 ++current_bundle;
3067 }
3068
3069 /* TODO: Free deeper */
3070 //util_dynarray_fini(&block->instructions);
3071 }
3072
3073 free(source_order_bundles);
3074
3075 /* Report the very first tag executed */
3076 program->first_tag = midgard_get_first_tag_from_block(ctx, 0);
3077
3078 /* Deal with off-by-one related to the fencepost problem */
3079 program->work_register_count = ctx->work_registers + 1;
3080 program->uniform_cutoff = ctx->uniform_cutoff;
3081
3082 program->blend_patch_offset = ctx->blend_constant_offset;
3083 program->tls_size = ctx->tls_size;
3084
3085 if ((midgard_debug & MIDGARD_DBG_SHADERS) && !silent)
3086 disassemble_midgard(stdout, program->compiled.data, program->compiled.size, gpu_id, ctx->stage);
3087
3088 if ((midgard_debug & MIDGARD_DBG_SHADERDB || shaderdb) && !silent) {
3089 unsigned nr_bundles = 0, nr_ins = 0;
3090
3091 /* Count instructions and bundles */
3092
3093 mir_foreach_block(ctx, _block) {
3094 midgard_block *block = (midgard_block *) _block;
3095 nr_bundles += util_dynarray_num_elements(
3096 &block->bundles, midgard_bundle);
3097
3098 mir_foreach_bundle_in_block(block, bun)
3099 nr_ins += bun->instruction_count;
3100 }
3101