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