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