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