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