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