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