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