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