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