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