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