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