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