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