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