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