1 /*
2  * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
3  * Copyright (C) 2019-2020 Collabora, Ltd.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/mman.h>
28 #include <fcntl.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <err.h>
33 
34 #include "compiler/glsl/glsl_to_nir.h"
35 #include "compiler/nir_types.h"
36 #include "compiler/nir/nir_builder.h"
37 #include "util/half_float.h"
38 #include "util/u_math.h"
39 #include "util/u_debug.h"
40 #include "util/u_dynarray.h"
41 #include "util/list.h"
42 
43 #include "midgard.h"
44 #include "midgard_nir.h"
45 #include "midgard_compile.h"
46 #include "midgard_ops.h"
47 #include "helpers.h"
48 #include "compiler.h"
49 #include "midgard_quirks.h"
50 #include "panfrost/util/pan_lower_framebuffer.h"
51 
52 #include "disassemble.h"
53 
54 static const struct debug_named_value midgard_debug_options[] = {
55         {"msgs",      MIDGARD_DBG_MSGS,		"Print debug messages"},
56         {"shaders",   MIDGARD_DBG_SHADERS,	"Dump shaders in NIR and MIR"},
57         {"shaderdb",  MIDGARD_DBG_SHADERDB,     "Prints shader-db statistics"},
58         {"inorder",   MIDGARD_DBG_INORDER,      "Disables out-of-order scheduling"},
59         {"verbose",   MIDGARD_DBG_VERBOSE,      "Dump shaders verbosely"},
60         {"internal",  MIDGARD_DBG_INTERNAL,     "Dump internal shaders"},
61         DEBUG_NAMED_VALUE_END
62 };
63 
64 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG", midgard_debug_options, 0)
65 
66 int midgard_debug = 0;
67 
68 #define DBG(fmt, ...) \
69 		do { if (midgard_debug & MIDGARD_DBG_MSGS) \
70 			fprintf(stderr, "%s:%d: "fmt, \
71 				__FUNCTION__, __LINE__, ##__VA_ARGS__); } while (0)
72 static midgard_block *
create_empty_block(compiler_context * ctx)73 create_empty_block(compiler_context *ctx)
74 {
75         midgard_block *blk = rzalloc(ctx, midgard_block);
76 
77         blk->base.predecessors = _mesa_set_create(blk,
78                         _mesa_hash_pointer,
79                         _mesa_key_pointer_equal);
80 
81         blk->base.name = ctx->block_source_count++;
82 
83         return blk;
84 }
85 
86 static void
schedule_barrier(compiler_context * ctx)87 schedule_barrier(compiler_context *ctx)
88 {
89         midgard_block *temp = ctx->after_block;
90         ctx->after_block = create_empty_block(ctx);
91         ctx->block_count++;
92         list_addtail(&ctx->after_block->base.link, &ctx->blocks);
93         list_inithead(&ctx->after_block->base.instructions);
94         pan_block_add_successor(&ctx->current_block->base, &ctx->after_block->base);
95         ctx->current_block = ctx->after_block;
96         ctx->after_block = temp;
97 }
98 
99 /* Helpers to generate midgard_instruction's using macro magic, since every
100  * driver seems to do it that way */
101 
102 #define EMIT(op, ...) emit_mir_instruction(ctx, v_##op(__VA_ARGS__));
103 
104 #define M_LOAD_STORE(name, store, T) \
105 	static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
106 		midgard_instruction i = { \
107 			.type = TAG_LOAD_STORE_4, \
108                         .mask = 0xF, \
109                         .dest = ~0, \
110                         .src = { ~0, ~0, ~0, ~0 }, \
111                         .swizzle = SWIZZLE_IDENTITY_4, \
112                         .op = midgard_op_##name, \
113 			.load_store = { \
114 				.signed_offset = address \
115 			} \
116 		}; \
117                 \
118                 if (store) { \
119                         i.src[0] = ssa; \
120                         i.src_types[0] = T; \
121                         i.dest_type = T; \
122                 } else { \
123                         i.dest = ssa; \
124                         i.dest_type = T; \
125                 } \
126 		return i; \
127 	}
128 
129 #define M_LOAD(name, T) M_LOAD_STORE(name, false, T)
130 #define M_STORE(name, T) M_LOAD_STORE(name, true, T)
131 
132 M_LOAD(ld_attr_32, nir_type_uint32);
133 M_LOAD(ld_vary_32, nir_type_uint32);
134 M_LOAD(ld_ubo_u8, nir_type_uint32); /* mandatory extension to 32-bit */
135 M_LOAD(ld_ubo_u16, nir_type_uint32);
136 M_LOAD(ld_ubo_32, nir_type_uint32);
137 M_LOAD(ld_ubo_64, nir_type_uint32);
138 M_LOAD(ld_ubo_128, nir_type_uint32);
139 M_LOAD(ld_u8, nir_type_uint8);
140 M_LOAD(ld_u16, nir_type_uint16);
141 M_LOAD(ld_32, nir_type_uint32);
142 M_LOAD(ld_64, nir_type_uint32);
143 M_LOAD(ld_128, nir_type_uint32);
144 M_STORE(st_u8, nir_type_uint8);
145 M_STORE(st_u16, nir_type_uint16);
146 M_STORE(st_32, nir_type_uint32);
147 M_STORE(st_64, nir_type_uint32);
148 M_STORE(st_128, nir_type_uint32);
149 M_LOAD(ld_tilebuffer_raw, nir_type_uint32);
150 M_LOAD(ld_tilebuffer_16f, nir_type_float16);
151 M_LOAD(ld_tilebuffer_32f, nir_type_float32);
152 M_STORE(st_vary_32, nir_type_uint32);
153 M_LOAD(ld_cubemap_coords, nir_type_uint32);
154 M_LOAD(ldst_mov, nir_type_uint32);
155 M_LOAD(ld_image_32f, nir_type_float32);
156 M_LOAD(ld_image_16f, nir_type_float16);
157 M_LOAD(ld_image_32u, nir_type_uint32);
158 M_LOAD(ld_image_32i, nir_type_int32);
159 M_STORE(st_image_32f, nir_type_float32);
160 M_STORE(st_image_16f, nir_type_float16);
161 M_STORE(st_image_32u, nir_type_uint32);
162 M_STORE(st_image_32i, nir_type_int32);
163 M_LOAD(lea_image, nir_type_uint64);
164 
165 #define M_IMAGE(op) \
166 static midgard_instruction \
167 op ## _image(nir_alu_type type, unsigned val, unsigned address) \
168 { \
169         switch (type) { \
170         case nir_type_float32: \
171                  return m_ ## op ## _image_32f(val, address); \
172         case nir_type_float16: \
173                  return m_ ## op ## _image_16f(val, address); \
174         case nir_type_uint32: \
175                  return m_ ## op ## _image_32u(val, address); \
176         case nir_type_int32: \
177                  return m_ ## op ## _image_32i(val, address); \
178         default: \
179                  unreachable("Invalid image type"); \
180         } \
181 }
182 
183 M_IMAGE(ld);
184 M_IMAGE(st);
185 
186 static midgard_instruction
v_branch(bool conditional,bool invert)187 v_branch(bool conditional, bool invert)
188 {
189         midgard_instruction ins = {
190                 .type = TAG_ALU_4,
191                 .unit = ALU_ENAB_BRANCH,
192                 .compact_branch = true,
193                 .branch = {
194                         .conditional = conditional,
195                         .invert_conditional = invert
196                 },
197                 .dest = ~0,
198                 .src = { ~0, ~0, ~0, ~0 },
199         };
200 
201         return ins;
202 }
203 
204 static void
attach_constants(compiler_context * ctx,midgard_instruction * ins,void * constants,int name)205 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
206 {
207         ins->has_constants = true;
208         memcpy(&ins->constants, constants, 16);
209 }
210 
211 static int
glsl_type_size(const struct glsl_type * type,bool bindless)212 glsl_type_size(const struct glsl_type *type, bool bindless)
213 {
214         return glsl_count_attribute_slots(type, false);
215 }
216 
217 static bool
midgard_nir_lower_global_load_instr(nir_builder * b,nir_instr * instr,void * data)218 midgard_nir_lower_global_load_instr(nir_builder *b, nir_instr *instr, void *data)
219 {
220         if (instr->type != nir_instr_type_intrinsic)
221                 return false;
222 
223         nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
224         if (intr->intrinsic != nir_intrinsic_load_global &&
225             intr->intrinsic != nir_intrinsic_load_shared)
226                 return false;
227 
228         unsigned compsz = nir_dest_bit_size(intr->dest);
229         unsigned totalsz = compsz * nir_dest_num_components(intr->dest);
230         /* 8, 16, 32, 64 and 128 bit loads don't need to be lowered */
231         if (util_bitcount(totalsz) < 2 && totalsz <= 128)
232                 return false;
233 
234         b->cursor = nir_before_instr(instr);
235 
236         assert(intr->src[0].is_ssa);
237         nir_ssa_def *addr = intr->src[0].ssa;
238 
239         nir_ssa_def *comps[MIR_VEC_COMPONENTS];
240         unsigned ncomps = 0;
241 
242         while (totalsz) {
243                 unsigned loadsz = MIN2(1 << (util_last_bit(totalsz) - 1), 128);
244                 unsigned loadncomps = loadsz / compsz;
245 
246                 nir_ssa_def *load;
247                 if (intr->intrinsic == nir_intrinsic_load_global) {
248                         load = nir_load_global(b, addr, compsz / 8, loadncomps, compsz);
249                 } else {
250                         assert(intr->intrinsic == nir_intrinsic_load_shared);
251                         nir_intrinsic_instr *shared_load =
252                                 nir_intrinsic_instr_create(b->shader, nir_intrinsic_load_shared);
253                         shared_load->num_components = loadncomps;
254                         shared_load->src[0] = nir_src_for_ssa(addr);
255                         nir_intrinsic_set_align(shared_load, compsz / 8, 0);
256                         nir_intrinsic_set_base(shared_load, nir_intrinsic_base(intr));
257                         nir_ssa_dest_init(&shared_load->instr, &shared_load->dest,
258                                           shared_load->num_components, compsz, NULL);
259                         nir_builder_instr_insert(b, &shared_load->instr);
260                         load = &shared_load->dest.ssa;
261                 }
262 
263                 for (unsigned i = 0; i < loadncomps; i++)
264                         comps[ncomps++] = nir_channel(b, load, i);
265 
266                 totalsz -= loadsz;
267                 addr = nir_iadd(b, addr, nir_imm_intN_t(b, loadsz / 8, addr->bit_size));
268         }
269 
270         assert(ncomps == nir_dest_num_components(intr->dest));
271         nir_ssa_def_rewrite_uses(&intr->dest.ssa, nir_vec(b, comps, ncomps));
272 
273         return true;
274 }
275 
276 static bool
midgard_nir_lower_global_load(nir_shader * shader)277 midgard_nir_lower_global_load(nir_shader *shader)
278 {
279         return nir_shader_instructions_pass(shader,
280                                             midgard_nir_lower_global_load_instr,
281                                             nir_metadata_block_index | nir_metadata_dominance,
282                                             NULL);
283 }
284 
285 static bool
mdg_should_scalarize(const nir_instr * instr,const void * _unused)286 mdg_should_scalarize(const nir_instr *instr, const void *_unused)
287 {
288         const nir_alu_instr *alu = nir_instr_as_alu(instr);
289 
290         if (nir_dest_bit_size(alu->dest.dest) == 64)
291                 return true;
292 
293         switch (alu->op) {
294         case nir_op_fdot2:
295         case nir_op_umul_high:
296         case nir_op_imul_high:
297                 return true;
298         default:
299                 return false;
300         }
301 }
302 
303 /* Only vectorize int64 up to vec2 */
304 static bool
midgard_vectorize_filter(const nir_instr * instr,void * data)305 midgard_vectorize_filter(const nir_instr *instr, void *data)
306 {
307         if (instr->type != nir_instr_type_alu)
308                 return true;
309 
310         const nir_alu_instr *alu = nir_instr_as_alu(instr);
311 
312         unsigned num_components = alu->dest.dest.ssa.num_components;
313 
314         int src_bit_size = nir_src_bit_size(alu->src[0].src);
315         int dst_bit_size = nir_dest_bit_size(alu->dest.dest);
316 
317         if (src_bit_size == 64 || dst_bit_size == 64) {
318                 if (num_components > 1)
319                         return false;
320         }
321 
322         return true;
323 }
324 
325 static void
optimise_nir(nir_shader * nir,unsigned quirks,bool is_blend,bool is_blit)326 optimise_nir(nir_shader *nir, unsigned quirks, bool is_blend, bool is_blit)
327 {
328         bool progress;
329         unsigned lower_flrp =
330                 (nir->options->lower_flrp16 ? 16 : 0) |
331                 (nir->options->lower_flrp32 ? 32 : 0) |
332                 (nir->options->lower_flrp64 ? 64 : 0);
333 
334         NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
335         nir_lower_idiv_options idiv_options = {
336                 .imprecise_32bit_lowering = true,
337                 .allow_fp16 = true,
338         };
339         NIR_PASS(progress, nir, nir_lower_idiv, &idiv_options);
340 
341         nir_lower_tex_options lower_tex_options = {
342                 .lower_txs_lod = true,
343                 .lower_txp = ~0,
344                 .lower_tg4_broadcom_swizzle = true,
345                 /* TODO: we have native gradient.. */
346                 .lower_txd = true,
347         };
348 
349         NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_options);
350 
351 
352         /* TEX_GRAD fails to apply sampler descriptor settings on some
353          * implementations, requiring a lowering. However, blit shaders do not
354          * use the affected settings and should skip the workaround.
355          */
356         if ((quirks & MIDGARD_BROKEN_LOD) && !is_blit)
357                 NIR_PASS_V(nir, midgard_nir_lod_errata);
358 
359         /* Midgard image ops coordinates are 16-bit instead of 32-bit */
360         NIR_PASS(progress, nir, midgard_nir_lower_image_bitsize);
361         NIR_PASS(progress, nir, midgard_nir_lower_helper_writes);
362         NIR_PASS(progress, nir, pan_lower_helper_invocation);
363         NIR_PASS(progress, nir, pan_lower_sample_pos);
364 
365         NIR_PASS(progress, nir, midgard_nir_lower_algebraic_early);
366         NIR_PASS_V(nir, nir_lower_alu_to_scalar, mdg_should_scalarize, NULL);
367 
368         do {
369                 progress = false;
370 
371                 NIR_PASS(progress, nir, nir_lower_var_copies);
372                 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
373 
374                 NIR_PASS(progress, nir, nir_copy_prop);
375                 NIR_PASS(progress, nir, nir_opt_remove_phis);
376                 NIR_PASS(progress, nir, nir_opt_dce);
377                 NIR_PASS(progress, nir, nir_opt_dead_cf);
378                 NIR_PASS(progress, nir, nir_opt_cse);
379                 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
380                 NIR_PASS(progress, nir, nir_opt_algebraic);
381                 NIR_PASS(progress, nir, nir_opt_constant_folding);
382 
383                 if (lower_flrp != 0) {
384                         bool lower_flrp_progress = false;
385                         NIR_PASS(lower_flrp_progress,
386                                  nir,
387                                  nir_lower_flrp,
388                                  lower_flrp,
389                                  false /* always_precise */);
390                         if (lower_flrp_progress) {
391                                 NIR_PASS(progress, nir,
392                                          nir_opt_constant_folding);
393                                 progress = true;
394                         }
395 
396                         /* Nothing should rematerialize any flrps, so we only
397                          * need to do this lowering once.
398                          */
399                         lower_flrp = 0;
400                 }
401 
402                 NIR_PASS(progress, nir, nir_opt_undef);
403                 NIR_PASS(progress, nir, nir_lower_undef_to_zero);
404 
405                 NIR_PASS(progress, nir, nir_opt_loop_unroll);
406 
407                 NIR_PASS(progress, nir, nir_opt_vectorize,
408                          midgard_vectorize_filter, NULL);
409         } while (progress);
410 
411         NIR_PASS_V(nir, nir_lower_alu_to_scalar, mdg_should_scalarize, NULL);
412 
413         /* Run after opts so it can hit more */
414         if (!is_blend)
415                 NIR_PASS(progress, nir, nir_fuse_io_16);
416 
417         /* Must be run at the end to prevent creation of fsin/fcos ops */
418         NIR_PASS(progress, nir, midgard_nir_scale_trig);
419 
420         do {
421                 progress = false;
422 
423                 NIR_PASS(progress, nir, nir_opt_dce);
424                 NIR_PASS(progress, nir, nir_opt_algebraic);
425                 NIR_PASS(progress, nir, nir_opt_constant_folding);
426                 NIR_PASS(progress, nir, nir_copy_prop);
427         } while (progress);
428 
429         NIR_PASS(progress, nir, nir_opt_algebraic_late);
430         NIR_PASS(progress, nir, nir_opt_algebraic_distribute_src_mods);
431 
432         /* We implement booleans as 32-bit 0/~0 */
433         NIR_PASS(progress, nir, nir_lower_bool_to_int32);
434 
435         /* Now that booleans are lowered, we can run out late opts */
436         NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
437         NIR_PASS(progress, nir, midgard_nir_cancel_inot);
438 
439         NIR_PASS(progress, nir, nir_copy_prop);
440         NIR_PASS(progress, nir, nir_opt_dce);
441 
442         /* Backend scheduler is purely local, so do some global optimizations
443          * to reduce register pressure. */
444         nir_move_options move_all =
445                 nir_move_const_undef | nir_move_load_ubo | nir_move_load_input |
446                 nir_move_comparisons | nir_move_copies | nir_move_load_ssbo;
447 
448         NIR_PASS_V(nir, nir_opt_sink, move_all);
449         NIR_PASS_V(nir, nir_opt_move, move_all);
450 
451         /* Take us out of SSA */
452         NIR_PASS(progress, nir, nir_lower_locals_to_regs);
453         NIR_PASS(progress, nir, nir_convert_from_ssa, true);
454 
455         /* We are a vector architecture; write combine where possible */
456         NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
457         NIR_PASS(progress, nir, nir_lower_vec_to_movs, NULL, NULL);
458 
459         NIR_PASS(progress, nir, nir_opt_dce);
460 }
461 
462 /* Do not actually emit a load; instead, cache the constant for inlining */
463 
464 static void
emit_load_const(compiler_context * ctx,nir_load_const_instr * instr)465 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
466 {
467         nir_ssa_def def = instr->def;
468 
469         midgard_constants *consts = rzalloc(ctx, midgard_constants);
470 
471         assert(instr->def.num_components * instr->def.bit_size <= sizeof(*consts) * 8);
472 
473 #define RAW_CONST_COPY(bits)                                         \
474         nir_const_value_to_array(consts->u##bits, instr->value,      \
475                                  instr->def.num_components, u##bits)
476 
477         switch (instr->def.bit_size) {
478         case 64:
479                 RAW_CONST_COPY(64);
480                 break;
481         case 32:
482                 RAW_CONST_COPY(32);
483                 break;
484         case 16:
485                 RAW_CONST_COPY(16);
486                 break;
487         case 8:
488                 RAW_CONST_COPY(8);
489                 break;
490         default:
491                 unreachable("Invalid bit_size for load_const instruction\n");
492         }
493 
494         /* Shifted for SSA, +1 for off-by-one */
495         _mesa_hash_table_u64_insert(ctx->ssa_constants, (def.index << 1) + 1, consts);
496 }
497 
498 /* Normally constants are embedded implicitly, but for I/O and such we have to
499  * explicitly emit a move with the constant source */
500 
501 static void
emit_explicit_constant(compiler_context * ctx,unsigned node,unsigned to)502 emit_explicit_constant(compiler_context *ctx, unsigned node, unsigned to)
503 {
504         void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, node + 1);
505 
506         if (constant_value) {
507                 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), to);
508                 attach_constants(ctx, &ins, constant_value, node + 1);
509                 emit_mir_instruction(ctx, ins);
510         }
511 }
512 
513 static bool
nir_is_non_scalar_swizzle(nir_alu_src * src,unsigned nr_components)514 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
515 {
516         unsigned comp = src->swizzle[0];
517 
518         for (unsigned c = 1; c < nr_components; ++c) {
519                 if (src->swizzle[c] != comp)
520                         return true;
521         }
522 
523         return false;
524 }
525 
526 #define ATOMIC_CASE_IMPL(ctx, instr, nir, op, is_shared) \
527         case nir_intrinsic_##nir: \
528                 emit_atomic(ctx, instr, is_shared, midgard_op_##op, ~0); \
529                 break;
530 
531 #define ATOMIC_CASE(ctx, instr, nir, op) \
532         ATOMIC_CASE_IMPL(ctx, instr, shared_atomic_##nir, atomic_##op, true); \
533         ATOMIC_CASE_IMPL(ctx, instr, global_atomic_##nir, atomic_##op, false);
534 
535 #define IMAGE_ATOMIC_CASE(ctx, instr, nir, op) \
536         case nir_intrinsic_image_atomic_##nir: { \
537                 midgard_instruction ins = emit_image_op(ctx, instr, true); \
538                 emit_atomic(ctx, instr, false, midgard_op_atomic_##op, ins.dest); \
539                 break; \
540         }
541 
542 #define ALU_CASE(nir, _op) \
543 	case nir_op_##nir: \
544 		op = midgard_alu_op_##_op; \
545                 assert(src_bitsize == dst_bitsize); \
546 		break;
547 
548 #define ALU_CASE_RTZ(nir, _op) \
549 	case nir_op_##nir: \
550 		op = midgard_alu_op_##_op; \
551                 roundmode = MIDGARD_RTZ; \
552 		break;
553 
554 #define ALU_CHECK_CMP() \
555                 assert(src_bitsize == 16 || src_bitsize == 32 || src_bitsize == 64); \
556                 assert(dst_bitsize == 16 || dst_bitsize == 32); \
557 
558 #define ALU_CASE_BCAST(nir, _op, count) \
559         case nir_op_##nir: \
560                 op = midgard_alu_op_##_op; \
561                 broadcast_swizzle = count; \
562                 ALU_CHECK_CMP(); \
563                 break;
564 
565 #define ALU_CASE_CMP(nir, _op) \
566 	case nir_op_##nir: \
567 		op = midgard_alu_op_##_op; \
568                 ALU_CHECK_CMP(); \
569                 break;
570 
571 /* Compare mir_lower_invert */
572 static bool
nir_accepts_inot(nir_op op,unsigned src)573 nir_accepts_inot(nir_op op, unsigned src)
574 {
575         switch (op) {
576         case nir_op_ior:
577         case nir_op_iand: /* TODO: b2f16 */
578         case nir_op_ixor:
579                 return true;
580         case nir_op_b32csel:
581                 /* Only the condition */
582                 return (src == 0);
583         default:
584                 return false;
585         }
586 }
587 
588 static bool
mir_accept_dest_mod(compiler_context * ctx,nir_dest ** dest,nir_op op)589 mir_accept_dest_mod(compiler_context *ctx, nir_dest **dest, nir_op op)
590 {
591         if (pan_has_dest_mod(dest, op)) {
592                 assert((*dest)->is_ssa);
593                 BITSET_SET(ctx->already_emitted, (*dest)->ssa.index);
594                 return true;
595         }
596 
597         return false;
598 }
599 
600 /* Look for floating point mods. We have the mods clamp_m1_1, clamp_0_1,
601  * and clamp_0_inf. We also have the relations (note 3 * 2 = 6 cases):
602  *
603  * clamp_0_1(clamp_0_inf(x))  = clamp_m1_1(x)
604  * clamp_0_1(clamp_m1_1(x))   = clamp_m1_1(x)
605  * clamp_0_inf(clamp_0_1(x))  = clamp_m1_1(x)
606  * clamp_0_inf(clamp_m1_1(x)) = clamp_m1_1(x)
607  * clamp_m1_1(clamp_0_1(x))   = clamp_m1_1(x)
608  * clamp_m1_1(clamp_0_inf(x)) = clamp_m1_1(x)
609  *
610  * So by cases any composition of output modifiers is equivalent to
611  * clamp_m1_1 alone.
612  */
613 static unsigned
mir_determine_float_outmod(compiler_context * ctx,nir_dest ** dest,unsigned prior_outmod)614 mir_determine_float_outmod(compiler_context *ctx, nir_dest **dest, unsigned prior_outmod)
615 {
616         bool clamp_0_inf = mir_accept_dest_mod(ctx, dest, nir_op_fclamp_pos_mali);
617         bool clamp_0_1 = mir_accept_dest_mod(ctx, dest, nir_op_fsat);
618         bool clamp_m1_1 = mir_accept_dest_mod(ctx, dest, nir_op_fsat_signed_mali);
619         bool prior = (prior_outmod != midgard_outmod_none);
620         int count = (int) prior + (int) clamp_0_inf + (int) clamp_0_1 + (int) clamp_m1_1;
621 
622         return ((count > 1) || clamp_0_1) ?  midgard_outmod_clamp_0_1 :
623                                 clamp_0_inf ? midgard_outmod_clamp_0_inf :
624                                 clamp_m1_1 ?   midgard_outmod_clamp_m1_1 :
625                                 prior_outmod;
626 }
627 
628 static void
mir_copy_src(midgard_instruction * ins,nir_alu_instr * instr,unsigned i,unsigned to,bool * abs,bool * neg,bool * not,enum midgard_roundmode * roundmode,bool is_int,unsigned bcast_count)629 mir_copy_src(midgard_instruction *ins, nir_alu_instr *instr, unsigned i, unsigned to, bool *abs, bool *neg, bool *not, enum midgard_roundmode *roundmode, bool is_int, unsigned bcast_count)
630 {
631         nir_alu_src src = instr->src[i];
632 
633         if (!is_int) {
634                 if (pan_has_source_mod(&src, nir_op_fneg))
635                         *neg = !(*neg);
636 
637                 if (pan_has_source_mod(&src, nir_op_fabs))
638                         *abs = true;
639         }
640 
641         if (nir_accepts_inot(instr->op, i) && pan_has_source_mod(&src, nir_op_inot))
642                 *not = true;
643 
644         if (roundmode) {
645                 if (pan_has_source_mod(&src, nir_op_fround_even))
646                         *roundmode = MIDGARD_RTE;
647 
648                 if (pan_has_source_mod(&src, nir_op_ftrunc))
649                         *roundmode = MIDGARD_RTZ;
650 
651                 if (pan_has_source_mod(&src, nir_op_ffloor))
652                         *roundmode = MIDGARD_RTN;
653 
654                 if (pan_has_source_mod(&src, nir_op_fceil))
655                         *roundmode = MIDGARD_RTP;
656         }
657 
658         unsigned bits = nir_src_bit_size(src.src);
659 
660         ins->src[to] = nir_src_index(NULL, &src.src);
661         ins->src_types[to] = nir_op_infos[instr->op].input_types[i] | bits;
662 
663         for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
664                 ins->swizzle[to][c] = src.swizzle[
665                         (!bcast_count || c < bcast_count) ? c :
666                                 (bcast_count - 1)];
667         }
668 }
669 
670 /* Midgard features both fcsel and icsel, depending on whether you want int or
671  * float modifiers. NIR's csel is typeless, so we want a heuristic to guess if
672  * we should emit an int or float csel depending on what modifiers could be
673  * placed. In the absense of modifiers, this is probably arbitrary. */
674 
675 static bool
mir_is_bcsel_float(nir_alu_instr * instr)676 mir_is_bcsel_float(nir_alu_instr *instr)
677 {
678         nir_op intmods[] = {
679                 nir_op_i2i8, nir_op_i2i16,
680                 nir_op_i2i32, nir_op_i2i64
681         };
682 
683         nir_op floatmods[] = {
684                 nir_op_fabs, nir_op_fneg,
685                 nir_op_f2f16, nir_op_f2f32,
686                 nir_op_f2f64
687         };
688 
689         nir_op floatdestmods[] = {
690                 nir_op_fsat, nir_op_fsat_signed_mali, nir_op_fclamp_pos_mali,
691                 nir_op_f2f16, nir_op_f2f32
692         };
693 
694         signed score = 0;
695 
696         for (unsigned i = 1; i < 3; ++i) {
697                 nir_alu_src s = instr->src[i];
698                 for (unsigned q = 0; q < ARRAY_SIZE(intmods); ++q) {
699                         if (pan_has_source_mod(&s, intmods[q]))
700                                 score--;
701                 }
702         }
703 
704         for (unsigned i = 1; i < 3; ++i) {
705                 nir_alu_src s = instr->src[i];
706                 for (unsigned q = 0; q < ARRAY_SIZE(floatmods); ++q) {
707                         if (pan_has_source_mod(&s, floatmods[q]))
708                                 score++;
709                 }
710         }
711 
712         for (unsigned q = 0; q < ARRAY_SIZE(floatdestmods); ++q) {
713                 nir_dest *dest = &instr->dest.dest;
714                 if (pan_has_dest_mod(&dest, floatdestmods[q]))
715                         score++;
716         }
717 
718         return (score > 0);
719 }
720 
721 static void
emit_alu(compiler_context * ctx,nir_alu_instr * instr)722 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
723 {
724         nir_dest *dest = &instr->dest.dest;
725 
726         if (dest->is_ssa && BITSET_TEST(ctx->already_emitted, dest->ssa.index))
727                 return;
728 
729         /* Derivatives end up emitted on the texture pipe, not the ALUs. This
730          * is handled elsewhere */
731 
732         if (instr->op == nir_op_fddx || instr->op == nir_op_fddy) {
733                 midgard_emit_derivatives(ctx, instr);
734                 return;
735         }
736 
737         bool is_ssa = dest->is_ssa;
738 
739         unsigned nr_components = nir_dest_num_components(*dest);
740         unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
741         unsigned op = 0;
742 
743         /* Number of components valid to check for the instruction (the rest
744          * will be forced to the last), or 0 to use as-is. Relevant as
745          * ball-type instructions have a channel count in NIR but are all vec4
746          * in Midgard */
747 
748         unsigned broadcast_swizzle = 0;
749 
750         /* Should we swap arguments? */
751         bool flip_src12 = false;
752 
753         ASSERTED unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
754         ASSERTED unsigned dst_bitsize = nir_dest_bit_size(*dest);
755 
756         enum midgard_roundmode roundmode = MIDGARD_RTE;
757 
758         switch (instr->op) {
759                 ALU_CASE(fadd, fadd);
760                 ALU_CASE(fmul, fmul);
761                 ALU_CASE(fmin, fmin);
762                 ALU_CASE(fmax, fmax);
763                 ALU_CASE(imin, imin);
764                 ALU_CASE(imax, imax);
765                 ALU_CASE(umin, umin);
766                 ALU_CASE(umax, umax);
767                 ALU_CASE(ffloor, ffloor);
768                 ALU_CASE(fround_even, froundeven);
769                 ALU_CASE(ftrunc, ftrunc);
770                 ALU_CASE(fceil, fceil);
771                 ALU_CASE(fdot3, fdot3);
772                 ALU_CASE(fdot4, fdot4);
773                 ALU_CASE(iadd, iadd);
774                 ALU_CASE(isub, isub);
775                 ALU_CASE(iadd_sat, iaddsat);
776                 ALU_CASE(isub_sat, isubsat);
777                 ALU_CASE(uadd_sat, uaddsat);
778                 ALU_CASE(usub_sat, usubsat);
779                 ALU_CASE(imul, imul);
780                 ALU_CASE(imul_high, imul);
781                 ALU_CASE(umul_high, imul);
782                 ALU_CASE(uclz, iclz);
783 
784                 /* Zero shoved as second-arg */
785                 ALU_CASE(iabs, iabsdiff);
786 
787                 ALU_CASE(uabs_isub, iabsdiff);
788                 ALU_CASE(uabs_usub, uabsdiff);
789 
790                 ALU_CASE(mov, imov);
791 
792                 ALU_CASE_CMP(feq32, feq);
793                 ALU_CASE_CMP(fneu32, fne);
794                 ALU_CASE_CMP(flt32, flt);
795                 ALU_CASE_CMP(ieq32, ieq);
796                 ALU_CASE_CMP(ine32, ine);
797                 ALU_CASE_CMP(ilt32, ilt);
798                 ALU_CASE_CMP(ult32, ult);
799 
800                 /* We don't have a native b2f32 instruction. Instead, like many
801                  * GPUs, we exploit booleans as 0/~0 for false/true, and
802                  * correspondingly AND
803                  * by 1.0 to do the type conversion. For the moment, prime us
804                  * to emit:
805                  *
806                  * iand [whatever], #0
807                  *
808                  * At the end of emit_alu (as MIR), we'll fix-up the constant
809                  */
810 
811                 ALU_CASE_CMP(b2f32, iand);
812                 ALU_CASE_CMP(b2f16, iand);
813                 ALU_CASE_CMP(b2i32, iand);
814 
815                 /* Likewise, we don't have a dedicated f2b32 instruction, but
816                  * we can do a "not equal to 0.0" test. */
817 
818                 ALU_CASE_CMP(f2b32, fne);
819                 ALU_CASE_CMP(i2b32, ine);
820 
821                 ALU_CASE(frcp, frcp);
822                 ALU_CASE(frsq, frsqrt);
823                 ALU_CASE(fsqrt, fsqrt);
824                 ALU_CASE(fexp2, fexp2);
825                 ALU_CASE(flog2, flog2);
826 
827                 ALU_CASE_RTZ(f2i64, f2i_rte);
828                 ALU_CASE_RTZ(f2u64, f2u_rte);
829                 ALU_CASE_RTZ(i2f64, i2f_rte);
830                 ALU_CASE_RTZ(u2f64, u2f_rte);
831 
832                 ALU_CASE_RTZ(f2i32, f2i_rte);
833                 ALU_CASE_RTZ(f2u32, f2u_rte);
834                 ALU_CASE_RTZ(i2f32, i2f_rte);
835                 ALU_CASE_RTZ(u2f32, u2f_rte);
836 
837                 ALU_CASE_RTZ(f2i8, f2i_rte);
838                 ALU_CASE_RTZ(f2u8, f2u_rte);
839 
840                 ALU_CASE_RTZ(f2i16, f2i_rte);
841                 ALU_CASE_RTZ(f2u16, f2u_rte);
842                 ALU_CASE_RTZ(i2f16, i2f_rte);
843                 ALU_CASE_RTZ(u2f16, u2f_rte);
844 
845                 ALU_CASE(fsin, fsinpi);
846                 ALU_CASE(fcos, fcospi);
847 
848                 /* We'll get 0 in the second arg, so:
849                  * ~a = ~(a | 0) = nor(a, 0) */
850                 ALU_CASE(inot, inor);
851                 ALU_CASE(iand, iand);
852                 ALU_CASE(ior, ior);
853                 ALU_CASE(ixor, ixor);
854                 ALU_CASE(ishl, ishl);
855                 ALU_CASE(ishr, iasr);
856                 ALU_CASE(ushr, ilsr);
857 
858                 ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
859                 ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
860                 ALU_CASE_CMP(b32all_fequal4, fball_eq);
861 
862                 ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
863                 ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
864                 ALU_CASE_CMP(b32any_fnequal4, fbany_neq);
865 
866                 ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
867                 ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
868                 ALU_CASE_CMP(b32all_iequal4, iball_eq);
869 
870                 ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
871                 ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
872                 ALU_CASE_CMP(b32any_inequal4, ibany_neq);
873 
874                 /* Source mods will be shoved in later */
875                 ALU_CASE(fabs, fmov);
876                 ALU_CASE(fneg, fmov);
877                 ALU_CASE(fsat, fmov);
878                 ALU_CASE(fsat_signed_mali, fmov);
879                 ALU_CASE(fclamp_pos_mali, fmov);
880 
881         /* For size conversion, we use a move. Ideally though we would squash
882          * these ops together; maybe that has to happen after in NIR as part of
883          * propagation...? An earlier algebraic pass ensured we step down by
884          * only / exactly one size. If stepping down, we use a dest override to
885          * reduce the size; if stepping up, we use a larger-sized move with a
886          * half source and a sign/zero-extension modifier */
887 
888         case nir_op_i2i8:
889         case nir_op_i2i16:
890         case nir_op_i2i32:
891         case nir_op_i2i64:
892         case nir_op_u2u8:
893         case nir_op_u2u16:
894         case nir_op_u2u32:
895         case nir_op_u2u64:
896         case nir_op_f2f16:
897         case nir_op_f2f32:
898         case nir_op_f2f64: {
899                 if (instr->op == nir_op_f2f16 || instr->op == nir_op_f2f32 ||
900                     instr->op == nir_op_f2f64)
901                         op = midgard_alu_op_fmov;
902                 else
903                         op = midgard_alu_op_imov;
904 
905                 break;
906         }
907 
908         /* For greater-or-equal, we lower to less-or-equal and flip the
909          * arguments */
910 
911         case nir_op_fge:
912         case nir_op_fge32:
913         case nir_op_ige32:
914         case nir_op_uge32: {
915                 op =
916                         instr->op == nir_op_fge   ? midgard_alu_op_fle :
917                         instr->op == nir_op_fge32 ? midgard_alu_op_fle :
918                         instr->op == nir_op_ige32 ? midgard_alu_op_ile :
919                         instr->op == nir_op_uge32 ? midgard_alu_op_ule :
920                         0;
921 
922                 flip_src12 = true;
923                 ALU_CHECK_CMP();
924                 break;
925         }
926 
927         case nir_op_b32csel: {
928                 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
929                 bool is_float = mir_is_bcsel_float(instr);
930                 op = is_float ?
931                         (mixed ? midgard_alu_op_fcsel_v : midgard_alu_op_fcsel) :
932                         (mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel);
933 
934                 break;
935         }
936 
937         case nir_op_unpack_32_2x16:
938         case nir_op_unpack_32_4x8:
939         case nir_op_pack_32_2x16:
940         case nir_op_pack_32_4x8: {
941                 op = midgard_alu_op_imov;
942                 break;
943         }
944 
945         default:
946                 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
947                 assert(0);
948                 return;
949         }
950 
951         /* Promote imov to fmov if it might help inline a constant */
952         if (op == midgard_alu_op_imov && nir_src_is_const(instr->src[0].src)
953                         && nir_src_bit_size(instr->src[0].src) == 32
954                         && nir_is_same_comp_swizzle(instr->src[0].swizzle,
955                                 nir_src_num_components(instr->src[0].src))) {
956                 op = midgard_alu_op_fmov;
957         }
958 
959         /* Midgard can perform certain modifiers on output of an ALU op */
960 
961         unsigned outmod = 0;
962         bool is_int = midgard_is_integer_op(op);
963 
964         if (instr->op == nir_op_umul_high || instr->op == nir_op_imul_high) {
965                 outmod = midgard_outmod_keephi;
966         } else if (midgard_is_integer_out_op(op)) {
967                 outmod = midgard_outmod_keeplo;
968         } else if (instr->op == nir_op_fsat) {
969                 outmod = midgard_outmod_clamp_0_1;
970         } else if (instr->op == nir_op_fsat_signed_mali) {
971                 outmod = midgard_outmod_clamp_m1_1;
972         } else if (instr->op == nir_op_fclamp_pos_mali) {
973                 outmod = midgard_outmod_clamp_0_inf;
974         }
975 
976         /* Fetch unit, quirks, etc information */
977         unsigned opcode_props = alu_opcode_props[op].props;
978         bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
979 
980         if (!midgard_is_integer_out_op(op)) {
981                 outmod = mir_determine_float_outmod(ctx, &dest, outmod);
982         }
983 
984         midgard_instruction ins = {
985                 .type = TAG_ALU_4,
986                 .dest = nir_dest_index(dest),
987                 .dest_type = nir_op_infos[instr->op].output_type
988                         | nir_dest_bit_size(*dest),
989                 .roundmode = roundmode,
990         };
991 
992         enum midgard_roundmode *roundptr = (opcode_props & MIDGARD_ROUNDS) ?
993                 &ins.roundmode : NULL;
994 
995         for (unsigned i = nr_inputs; i < ARRAY_SIZE(ins.src); ++i)
996                 ins.src[i] = ~0;
997 
998         if (quirk_flipped_r24) {
999                 ins.src[0] = ~0;
1000                 mir_copy_src(&ins, instr, 0, 1, &ins.src_abs[1], &ins.src_neg[1], &ins.src_invert[1], roundptr, is_int, broadcast_swizzle);
1001         } else {
1002                 for (unsigned i = 0; i < nr_inputs; ++i) {
1003                         unsigned to = i;
1004 
1005                         if (instr->op == nir_op_b32csel) {
1006                                 /* The condition is the first argument; move
1007                                  * the other arguments up one to be a binary
1008                                  * instruction for Midgard with the condition
1009                                  * last */
1010 
1011                                 if (i == 0)
1012                                         to = 2;
1013                                 else if (flip_src12)
1014                                         to = 2 - i;
1015                                 else
1016                                         to = i - 1;
1017                         } else if (flip_src12) {
1018                                 to = 1 - to;
1019                         }
1020 
1021                         mir_copy_src(&ins, instr, i, to, &ins.src_abs[to], &ins.src_neg[to], &ins.src_invert[to], roundptr, is_int, broadcast_swizzle);
1022 
1023                         /* (!c) ? a : b = c ? b : a */
1024                         if (instr->op == nir_op_b32csel && ins.src_invert[2]) {
1025                                 ins.src_invert[2] = false;
1026                                 flip_src12 ^= true;
1027                         }
1028                 }
1029         }
1030 
1031         if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
1032                 /* Lowered to move */
1033                 if (instr->op == nir_op_fneg)
1034                         ins.src_neg[1] ^= true;
1035 
1036                 if (instr->op == nir_op_fabs)
1037                         ins.src_abs[1] = true;
1038         }
1039 
1040         ins.mask = mask_of(nr_components);
1041 
1042         /* Apply writemask if non-SSA, keeping in mind that we can't write to
1043          * components that don't exist. Note modifier => SSA => !reg => no
1044          * writemask, so we don't have to worry about writemasks here.*/
1045 
1046         if (!is_ssa)
1047                 ins.mask &= instr->dest.write_mask;
1048 
1049         ins.op = op;
1050         ins.outmod = outmod;
1051 
1052         /* Late fixup for emulated instructions */
1053 
1054         if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
1055                 /* Presently, our second argument is an inline #0 constant.
1056                  * Switch over to an embedded 1.0 constant (that can't fit
1057                  * inline, since we're 32-bit, not 16-bit like the inline
1058                  * constants) */
1059 
1060                 ins.has_inline_constant = false;
1061                 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1062                 ins.src_types[1] = nir_type_float32;
1063                 ins.has_constants = true;
1064 
1065                 if (instr->op == nir_op_b2f32)
1066                         ins.constants.f32[0] = 1.0f;
1067                 else
1068                         ins.constants.i32[0] = 1;
1069 
1070                 for (unsigned c = 0; c < 16; ++c)
1071                         ins.swizzle[1][c] = 0;
1072         } else if (instr->op == nir_op_b2f16) {
1073                 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1074                 ins.src_types[1] = nir_type_float16;
1075                 ins.has_constants = true;
1076                 ins.constants.i16[0] = _mesa_float_to_half(1.0);
1077 
1078                 for (unsigned c = 0; c < 16; ++c)
1079                         ins.swizzle[1][c] = 0;
1080         } else if (nr_inputs == 1 && !quirk_flipped_r24) {
1081                 /* Lots of instructions need a 0 plonked in */
1082                 ins.has_inline_constant = false;
1083                 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1084                 ins.src_types[1] = ins.src_types[0];
1085                 ins.has_constants = true;
1086                 ins.constants.u32[0] = 0;
1087 
1088                 for (unsigned c = 0; c < 16; ++c)
1089                         ins.swizzle[1][c] = 0;
1090         } else if (instr->op == nir_op_pack_32_2x16) {
1091                 ins.dest_type = nir_type_uint16;
1092                 ins.mask = mask_of(nr_components * 2);
1093                 ins.is_pack = true;
1094         } else if (instr->op == nir_op_pack_32_4x8) {
1095                 ins.dest_type = nir_type_uint8;
1096                 ins.mask = mask_of(nr_components * 4);
1097                 ins.is_pack = true;
1098         } else if (instr->op == nir_op_unpack_32_2x16) {
1099                 ins.dest_type = nir_type_uint32;
1100                 ins.mask = mask_of(nr_components >> 1);
1101                 ins.is_pack = true;
1102         } else if (instr->op == nir_op_unpack_32_4x8) {
1103                 ins.dest_type = nir_type_uint32;
1104                 ins.mask = mask_of(nr_components >> 2);
1105                 ins.is_pack = true;
1106         }
1107 
1108         if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
1109                 /* To avoid duplicating the lookup tables (probably), true LUT
1110                  * instructions can only operate as if they were scalars. Lower
1111                  * them here by changing the component. */
1112 
1113                 unsigned orig_mask = ins.mask;
1114 
1115                 unsigned swizzle_back[MIR_VEC_COMPONENTS];
1116                 memcpy(&swizzle_back, ins.swizzle[0], sizeof(swizzle_back));
1117 
1118                 midgard_instruction ins_split[MIR_VEC_COMPONENTS];
1119                 unsigned ins_count = 0;
1120 
1121                 for (int i = 0; i < nr_components; ++i) {
1122                         /* Mask the associated component, dropping the
1123                          * instruction if needed */
1124 
1125                         ins.mask = 1 << i;
1126                         ins.mask &= orig_mask;
1127 
1128                         for (unsigned j = 0; j < ins_count; ++j) {
1129                                 if (swizzle_back[i] == ins_split[j].swizzle[0][0]) {
1130                                         ins_split[j].mask |= ins.mask;
1131                                         ins.mask = 0;
1132                                         break;
1133                                 }
1134                         }
1135 
1136                         if (!ins.mask)
1137                                 continue;
1138 
1139                         for (unsigned j = 0; j < MIR_VEC_COMPONENTS; ++j)
1140                                 ins.swizzle[0][j] = swizzle_back[i]; /* Pull from the correct component */
1141 
1142                         ins_split[ins_count] = ins;
1143 
1144                         ++ins_count;
1145                 }
1146 
1147                 for (unsigned i = 0; i < ins_count; ++i) {
1148                         emit_mir_instruction(ctx, ins_split[i]);
1149                 }
1150         } else {
1151                 emit_mir_instruction(ctx, ins);
1152         }
1153 }
1154 
1155 #undef ALU_CASE
1156 
1157 static void
mir_set_intr_mask(nir_instr * instr,midgard_instruction * ins,bool is_read)1158 mir_set_intr_mask(nir_instr *instr, midgard_instruction *ins, bool is_read)
1159 {
1160         nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1161         unsigned nir_mask = 0;
1162         unsigned dsize = 0;
1163 
1164         if (is_read) {
1165                 nir_mask = mask_of(nir_intrinsic_dest_components(intr));
1166 
1167                 /* Extension is mandatory for 8/16-bit loads */
1168                 dsize = nir_dest_bit_size(intr->dest) == 64 ? 64 : 32;
1169         } else {
1170                 nir_mask = nir_intrinsic_write_mask(intr);
1171                 dsize = OP_IS_COMMON_STORE(ins->op) ?
1172                         nir_src_bit_size(intr->src[0]) : 32;
1173         }
1174 
1175         /* Once we have the NIR mask, we need to normalize to work in 32-bit space */
1176         unsigned bytemask = pan_to_bytemask(dsize, nir_mask);
1177         ins->dest_type = nir_type_uint | dsize;
1178         mir_set_bytemask(ins, bytemask);
1179 }
1180 
1181 /* Uniforms and UBOs use a shared code path, as uniforms are just (slightly
1182  * optimized) versions of UBO #0 */
1183 
1184 static midgard_instruction *
emit_ubo_read(compiler_context * ctx,nir_instr * instr,unsigned dest,unsigned offset,nir_src * indirect_offset,unsigned indirect_shift,unsigned index,unsigned nr_comps)1185 emit_ubo_read(
1186         compiler_context *ctx,
1187         nir_instr *instr,
1188         unsigned dest,
1189         unsigned offset,
1190         nir_src *indirect_offset,
1191         unsigned indirect_shift,
1192         unsigned index,
1193         unsigned nr_comps)
1194 {
1195         midgard_instruction ins;
1196 
1197         unsigned dest_size = (instr->type == nir_instr_type_intrinsic) ?
1198                 nir_dest_bit_size(nir_instr_as_intrinsic(instr)->dest) : 32;
1199 
1200         unsigned bitsize = dest_size * nr_comps;
1201 
1202         /* Pick the smallest intrinsic to avoid out-of-bounds reads */
1203         if (bitsize <= 8)
1204                 ins = m_ld_ubo_u8(dest, 0);
1205         else if (bitsize <= 16)
1206                 ins = m_ld_ubo_u16(dest, 0);
1207         else if (bitsize <= 32)
1208                 ins = m_ld_ubo_32(dest, 0);
1209         else if (bitsize <= 64)
1210                 ins = m_ld_ubo_64(dest, 0);
1211         else if (bitsize <= 128)
1212                 ins = m_ld_ubo_128(dest, 0);
1213         else
1214                 unreachable("Invalid UBO read size");
1215 
1216         ins.constants.u32[0] = offset;
1217 
1218         if (instr->type == nir_instr_type_intrinsic)
1219                 mir_set_intr_mask(instr, &ins, true);
1220 
1221         if (indirect_offset) {
1222                 ins.src[2] = nir_src_index(ctx, indirect_offset);
1223                 ins.src_types[2] = nir_type_uint32;
1224                 ins.load_store.index_shift = indirect_shift;
1225 
1226                 /* X component for the whole swizzle to prevent register
1227                  * pressure from ballooning from the extra components */
1228                 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[2]); ++i)
1229                         ins.swizzle[2][i] = 0;
1230         } else {
1231                 ins.load_store.index_reg = REGISTER_LDST_ZERO;
1232         }
1233 
1234         if (indirect_offset && indirect_offset->is_ssa && !indirect_shift)
1235                 mir_set_ubo_offset(&ins, indirect_offset, offset);
1236 
1237         midgard_pack_ubo_index_imm(&ins.load_store, index);
1238 
1239         return emit_mir_instruction(ctx, ins);
1240 }
1241 
1242 /* Globals are like UBOs if you squint. And shared memory is like globals if
1243  * you squint even harder */
1244 
1245 static void
emit_global(compiler_context * ctx,nir_instr * instr,bool is_read,unsigned srcdest,nir_src * offset,unsigned seg)1246 emit_global(
1247         compiler_context *ctx,
1248         nir_instr *instr,
1249         bool is_read,
1250         unsigned srcdest,
1251         nir_src *offset,
1252         unsigned seg)
1253 {
1254         midgard_instruction ins;
1255 
1256         nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1257         if (is_read) {
1258                 unsigned bitsize = nir_dest_bit_size(intr->dest) *
1259                         nir_dest_num_components(intr->dest);
1260 
1261                 switch (bitsize) {
1262                 case 8: ins = m_ld_u8(srcdest, 0); break;
1263                 case 16: ins = m_ld_u16(srcdest, 0); break;
1264                 case 32: ins = m_ld_32(srcdest, 0); break;
1265                 case 64: ins = m_ld_64(srcdest, 0); break;
1266                 case 128: ins = m_ld_128(srcdest, 0); break;
1267                 default: unreachable("Invalid global read size");
1268                 }
1269 
1270                 mir_set_intr_mask(instr, &ins, is_read);
1271 
1272                 /* For anything not aligned on 32bit, make sure we write full
1273                  * 32 bits registers. */
1274                 if (bitsize & 31) {
1275                         unsigned comps_per_32b = 32 / nir_dest_bit_size(intr->dest);
1276 
1277                         for (unsigned c = 0; c < 4 * comps_per_32b; c += comps_per_32b) {
1278                                 if (!(ins.mask & BITFIELD_RANGE(c, comps_per_32b)))
1279                                         continue;
1280 
1281                                 unsigned base = ~0;
1282                                 for (unsigned i = 0; i < comps_per_32b; i++) {
1283                                         if (ins.mask & BITFIELD_BIT(c + i)) {
1284                                                 base = ins.swizzle[0][c + i];
1285                                                 break;
1286                                         }
1287                                 }
1288 
1289                                 assert(base != ~0);
1290 
1291                                 for (unsigned i = 0; i < comps_per_32b; i++) {
1292                                         if (!(ins.mask & BITFIELD_BIT(c + i))) {
1293                                                 ins.swizzle[0][c + i] = base + i;
1294                                                 ins.mask |= BITFIELD_BIT(c + i);
1295                                         }
1296                                         assert(ins.swizzle[0][c + i] == base + i);
1297                                 }
1298                         }
1299 
1300                 }
1301         } else {
1302                 unsigned bitsize = nir_src_bit_size(intr->src[0]) *
1303                         nir_src_num_components(intr->src[0]);
1304 
1305                 if (bitsize == 8)
1306                         ins = m_st_u8(srcdest, 0);
1307                 else if (bitsize == 16)
1308                         ins = m_st_u16(srcdest, 0);
1309                 else if (bitsize <= 32)
1310                         ins = m_st_32(srcdest, 0);
1311                 else if (bitsize <= 64)
1312                         ins = m_st_64(srcdest, 0);
1313                 else if (bitsize <= 128)
1314                         ins = m_st_128(srcdest, 0);
1315                 else
1316                         unreachable("Invalid global store size");
1317 
1318                 mir_set_intr_mask(instr, &ins, is_read);
1319         }
1320 
1321         mir_set_offset(ctx, &ins, offset, seg);
1322 
1323         /* Set a valid swizzle for masked out components */
1324         assert(ins.mask);
1325         unsigned first_component = __builtin_ffs(ins.mask) - 1;
1326 
1327         for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i) {
1328                 if (!(ins.mask & (1 << i)))
1329                         ins.swizzle[0][i] = first_component;
1330         }
1331 
1332         emit_mir_instruction(ctx, ins);
1333 }
1334 
1335 /* If is_shared is off, the only other possible value are globals, since
1336  * SSBO's are being lowered to globals through a NIR pass.
1337  * `image_direct_address` should be ~0 when instr is not an image_atomic
1338  * and the destination register of a lea_image op when it is an image_atomic. */
1339 static void
emit_atomic(compiler_context * ctx,nir_intrinsic_instr * instr,bool is_shared,midgard_load_store_op op,unsigned image_direct_address)1340 emit_atomic(
1341         compiler_context *ctx,
1342         nir_intrinsic_instr *instr,
1343         bool is_shared,
1344         midgard_load_store_op op,
1345         unsigned image_direct_address)
1346 {
1347         nir_alu_type type =
1348                 (op == midgard_op_atomic_imin || op == midgard_op_atomic_imax) ?
1349                 nir_type_int : nir_type_uint;
1350 
1351         bool is_image = image_direct_address != ~0;
1352 
1353         unsigned dest = nir_dest_index(&instr->dest);
1354         unsigned val_src = is_image ? 3 : 1;
1355         unsigned val = nir_src_index(ctx, &instr->src[val_src]);
1356         unsigned bitsize = nir_src_bit_size(instr->src[val_src]);
1357         emit_explicit_constant(ctx, val, val);
1358 
1359         midgard_instruction ins = {
1360                 .type = TAG_LOAD_STORE_4,
1361                 .mask = 0xF,
1362                 .dest = dest,
1363                 .src = { ~0, ~0, ~0, val },
1364                 .src_types = { 0, 0, 0, type | bitsize },
1365                 .op = op
1366         };
1367 
1368         nir_src *src_offset = nir_get_io_offset_src(instr);
1369 
1370         if (op == midgard_op_atomic_cmpxchg) {
1371                 unsigned xchg_val_src = is_image ? 4 : 2;
1372                 unsigned xchg_val = nir_src_index(ctx, &instr->src[xchg_val_src]);
1373                 emit_explicit_constant(ctx, xchg_val, xchg_val);
1374 
1375                 ins.src[2] = val;
1376                 ins.src_types[2] = type | bitsize;
1377                 ins.src[3] = xchg_val;
1378 
1379                 if (is_shared) {
1380                         ins.load_store.arg_reg = REGISTER_LDST_LOCAL_STORAGE_PTR;
1381                         ins.load_store.arg_comp = COMPONENT_Z;
1382                         ins.load_store.bitsize_toggle = true;
1383                 } else {
1384                         for(unsigned i = 0; i < 2; ++i)
1385                                 ins.swizzle[1][i] = i;
1386 
1387                         ins.src[1] = is_image ? image_direct_address :
1388                                                 nir_src_index(ctx, src_offset);
1389                         ins.src_types[1] = nir_type_uint64;
1390                 }
1391         } else if (is_image) {
1392                 for(unsigned i = 0; i < 2; ++i)
1393                         ins.swizzle[2][i] = i;
1394 
1395                 ins.src[2] = image_direct_address;
1396                 ins.src_types[2] = nir_type_uint64;
1397 
1398                 ins.load_store.arg_reg = REGISTER_LDST_ZERO;
1399                 ins.load_store.bitsize_toggle = true;
1400                 ins.load_store.index_format = midgard_index_address_u64;
1401         } else
1402                 mir_set_offset(ctx, &ins, src_offset, is_shared ? LDST_SHARED : LDST_GLOBAL);
1403 
1404         mir_set_intr_mask(&instr->instr, &ins, true);
1405 
1406         emit_mir_instruction(ctx, ins);
1407 }
1408 
1409 static void
emit_varying_read(compiler_context * ctx,unsigned dest,unsigned offset,unsigned nr_comp,unsigned component,nir_src * indirect_offset,nir_alu_type type,bool flat)1410 emit_varying_read(
1411         compiler_context *ctx,
1412         unsigned dest, unsigned offset,
1413         unsigned nr_comp, unsigned component,
1414         nir_src *indirect_offset, nir_alu_type type, bool flat)
1415 {
1416         /* XXX: Half-floats? */
1417         /* TODO: swizzle, mask */
1418 
1419         midgard_instruction ins = m_ld_vary_32(dest, PACK_LDST_ATTRIB_OFS(offset));
1420         ins.mask = mask_of(nr_comp);
1421         ins.dest_type = type;
1422 
1423         if (type == nir_type_float16) {
1424                 /* Ensure we are aligned so we can pack it later */
1425                 ins.mask = mask_of(ALIGN_POT(nr_comp, 2));
1426         }
1427 
1428         for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i)
1429                 ins.swizzle[0][i] = MIN2(i + component, COMPONENT_W);
1430 
1431 
1432         midgard_varying_params p = {
1433                 .flat_shading = flat,
1434                 .perspective_correction = 1,
1435                 .interpolate_sample = true,
1436         };
1437         midgard_pack_varying_params(&ins.load_store, p);
1438 
1439         if (indirect_offset) {
1440                 ins.src[2] = nir_src_index(ctx, indirect_offset);
1441                 ins.src_types[2] = nir_type_uint32;
1442         } else
1443                 ins.load_store.index_reg = REGISTER_LDST_ZERO;
1444 
1445         ins.load_store.arg_reg = REGISTER_LDST_ZERO;
1446         ins.load_store.index_format = midgard_index_address_u32;
1447 
1448         /* Use the type appropriate load */
1449         switch (type) {
1450         case nir_type_uint32:
1451         case nir_type_bool32:
1452                 ins.op = midgard_op_ld_vary_32u;
1453                 break;
1454         case nir_type_int32:
1455                 ins.op = midgard_op_ld_vary_32i;
1456                 break;
1457         case nir_type_float32:
1458                 ins.op = midgard_op_ld_vary_32;
1459                 break;
1460         case nir_type_float16:
1461                 ins.op = midgard_op_ld_vary_16;
1462                 break;
1463         default:
1464                 unreachable("Attempted to load unknown type");
1465                 break;
1466         }
1467 
1468         emit_mir_instruction(ctx, ins);
1469 }
1470 
1471 
1472 /* If `is_atomic` is true, we emit a `lea_image` since midgard doesn't not have special
1473  * image_atomic opcodes. The caller can then use that address to emit a normal atomic opcode. */
1474 static midgard_instruction
emit_image_op(compiler_context * ctx,nir_intrinsic_instr * instr,bool is_atomic)1475 emit_image_op(compiler_context *ctx, nir_intrinsic_instr *instr, bool is_atomic)
1476 {
1477         enum glsl_sampler_dim dim = nir_intrinsic_image_dim(instr);
1478         unsigned nr_attr = ctx->stage == MESA_SHADER_VERTEX ?
1479                 util_bitcount64(ctx->nir->info.inputs_read) : 0;
1480         unsigned nr_dim = glsl_get_sampler_dim_coordinate_components(dim);
1481         bool is_array = nir_intrinsic_image_array(instr);
1482         bool is_store = instr->intrinsic == nir_intrinsic_image_store;
1483 
1484         /* TODO: MSAA */
1485         assert(dim != GLSL_SAMPLER_DIM_MS && "MSAA'd images not supported");
1486 
1487         unsigned coord_reg = nir_src_index(ctx, &instr->src[1]);
1488         emit_explicit_constant(ctx, coord_reg, coord_reg);
1489 
1490         nir_src *index = &instr->src[0];
1491         bool is_direct = nir_src_is_const(*index);
1492 
1493         /* For image opcodes, address is used as an index into the attribute descriptor */
1494         unsigned address = nr_attr;
1495         if (is_direct)
1496                 address += nir_src_as_uint(*index);
1497 
1498         midgard_instruction ins;
1499         if (is_store) { /* emit st_image_* */
1500                 unsigned val = nir_src_index(ctx, &instr->src[3]);
1501                 emit_explicit_constant(ctx, val, val);
1502 
1503                 nir_alu_type type = nir_intrinsic_src_type(instr);
1504                 ins = st_image(type, val, PACK_LDST_ATTRIB_OFS(address));
1505                 nir_alu_type base_type = nir_alu_type_get_base_type(type);
1506                 ins.src_types[0] = base_type | nir_src_bit_size(instr->src[3]);
1507         } else if (is_atomic) { /* emit lea_image */
1508                 unsigned dest = make_compiler_temp_reg(ctx);
1509                 ins = m_lea_image(dest, PACK_LDST_ATTRIB_OFS(address));
1510                 ins.mask = mask_of(2); /* 64-bit memory address */
1511         } else { /* emit ld_image_* */
1512                 nir_alu_type type = nir_intrinsic_dest_type(instr);
1513                 ins = ld_image(type, nir_dest_index(&instr->dest), PACK_LDST_ATTRIB_OFS(address));
1514                 ins.mask = mask_of(nir_intrinsic_dest_components(instr));
1515                 ins.dest_type = type;
1516         }
1517 
1518         /* Coord reg */
1519         ins.src[1] = coord_reg;
1520         ins.src_types[1] = nir_type_uint16;
1521         if (nr_dim == 3 || is_array) {
1522                 ins.load_store.bitsize_toggle = true;
1523         }
1524 
1525         /* Image index reg */
1526         if (!is_direct) {
1527                 ins.src[2] = nir_src_index(ctx, index);
1528                 ins.src_types[2] = nir_type_uint32;
1529         } else
1530                 ins.load_store.index_reg = REGISTER_LDST_ZERO;
1531 
1532         emit_mir_instruction(ctx, ins);
1533 
1534         return ins;
1535 }
1536 
1537 static void
emit_attr_read(compiler_context * ctx,unsigned dest,unsigned offset,unsigned nr_comp,nir_alu_type t)1538 emit_attr_read(
1539         compiler_context *ctx,
1540         unsigned dest, unsigned offset,
1541         unsigned nr_comp, nir_alu_type t)
1542 {
1543         midgard_instruction ins = m_ld_attr_32(dest, PACK_LDST_ATTRIB_OFS(offset));
1544         ins.load_store.arg_reg = REGISTER_LDST_ZERO;
1545         ins.load_store.index_reg = REGISTER_LDST_ZERO;
1546         ins.mask = mask_of(nr_comp);
1547 
1548         /* Use the type appropriate load */
1549         switch (t) {
1550         case nir_type_uint:
1551         case nir_type_bool:
1552                 ins.op = midgard_op_ld_attr_32u;
1553                 break;
1554         case nir_type_int:
1555                 ins.op = midgard_op_ld_attr_32i;
1556                 break;
1557         case nir_type_float:
1558                 ins.op = midgard_op_ld_attr_32;
1559                 break;
1560         default:
1561                 unreachable("Attempted to load unknown type");
1562                 break;
1563         }
1564 
1565         emit_mir_instruction(ctx, ins);
1566 }
1567 
1568 static void
emit_sysval_read(compiler_context * ctx,nir_instr * instr,unsigned nr_components,unsigned offset)1569 emit_sysval_read(compiler_context *ctx, nir_instr *instr,
1570                 unsigned nr_components, unsigned offset)
1571 {
1572         nir_dest nir_dest;
1573 
1574         /* Figure out which uniform this is */
1575         unsigned sysval_ubo =
1576                 MAX2(ctx->inputs->sysval_ubo, ctx->nir->info.num_ubos);
1577         int sysval = panfrost_sysval_for_instr(instr, &nir_dest);
1578         unsigned dest = nir_dest_index(&nir_dest);
1579         unsigned uniform =
1580                 pan_lookup_sysval(ctx->sysval_to_id, &ctx->info->sysvals, sysval);
1581 
1582         /* Emit the read itself -- this is never indirect */
1583         midgard_instruction *ins =
1584                 emit_ubo_read(ctx, instr, dest, (uniform * 16) + offset, NULL, 0,
1585                               sysval_ubo, nr_components);
1586 
1587         ins->mask = mask_of(nr_components);
1588 }
1589 
1590 static unsigned
compute_builtin_arg(nir_intrinsic_op op)1591 compute_builtin_arg(nir_intrinsic_op op)
1592 {
1593         switch (op) {
1594         case nir_intrinsic_load_workgroup_id:
1595                 return REGISTER_LDST_GROUP_ID;
1596         case nir_intrinsic_load_local_invocation_id:
1597                 return REGISTER_LDST_LOCAL_THREAD_ID;
1598         case nir_intrinsic_load_global_invocation_id:
1599         case nir_intrinsic_load_global_invocation_id_zero_base:
1600                 return REGISTER_LDST_GLOBAL_THREAD_ID;
1601         default:
1602                 unreachable("Invalid compute paramater loaded");
1603         }
1604 }
1605 
1606 static void
emit_fragment_store(compiler_context * ctx,unsigned src,unsigned src_z,unsigned src_s,enum midgard_rt_id rt,unsigned sample_iter)1607 emit_fragment_store(compiler_context *ctx, unsigned src, unsigned src_z, unsigned src_s,
1608                     enum midgard_rt_id rt, unsigned sample_iter)
1609 {
1610         assert(rt < ARRAY_SIZE(ctx->writeout_branch));
1611         assert(sample_iter < ARRAY_SIZE(ctx->writeout_branch[0]));
1612 
1613         midgard_instruction *br = ctx->writeout_branch[rt][sample_iter];
1614 
1615         assert(!br);
1616 
1617         emit_explicit_constant(ctx, src, src);
1618 
1619         struct midgard_instruction ins =
1620                 v_branch(false, false);
1621 
1622         bool depth_only = (rt == MIDGARD_ZS_RT);
1623 
1624         ins.writeout = depth_only ? 0 : PAN_WRITEOUT_C;
1625 
1626         /* Add dependencies */
1627         ins.src[0] = src;
1628         ins.src_types[0] = nir_type_uint32;
1629 
1630         if (depth_only)
1631                 ins.constants.u32[0] = 0xFF;
1632         else
1633                 ins.constants.u32[0] = ((rt - MIDGARD_COLOR_RT0) << 8) | sample_iter;
1634 
1635         for (int i = 0; i < 4; ++i)
1636                 ins.swizzle[0][i] = i;
1637 
1638         if (~src_z) {
1639                 emit_explicit_constant(ctx, src_z, src_z);
1640                 ins.src[2] = src_z;
1641                 ins.src_types[2] = nir_type_uint32;
1642                 ins.writeout |= PAN_WRITEOUT_Z;
1643         }
1644         if (~src_s) {
1645                 emit_explicit_constant(ctx, src_s, src_s);
1646                 ins.src[3] = src_s;
1647                 ins.src_types[3] = nir_type_uint32;
1648                 ins.writeout |= PAN_WRITEOUT_S;
1649         }
1650 
1651         /* Emit the branch */
1652         br = emit_mir_instruction(ctx, ins);
1653         schedule_barrier(ctx);
1654         ctx->writeout_branch[rt][sample_iter] = br;
1655 
1656         /* Push our current location = current block count - 1 = where we'll
1657          * jump to. Maybe a bit too clever for my own good */
1658 
1659         br->branch.target_block = ctx->block_count - 1;
1660 }
1661 
1662 static void
emit_compute_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1663 emit_compute_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1664 {
1665         unsigned reg = nir_dest_index(&instr->dest);
1666         midgard_instruction ins = m_ldst_mov(reg, 0);
1667         ins.mask = mask_of(3);
1668         ins.swizzle[0][3] = COMPONENT_X; /* xyzx */
1669         ins.load_store.arg_reg = compute_builtin_arg(instr->intrinsic);
1670         emit_mir_instruction(ctx, ins);
1671 }
1672 
1673 static unsigned
vertex_builtin_arg(nir_intrinsic_op op)1674 vertex_builtin_arg(nir_intrinsic_op op)
1675 {
1676         switch (op) {
1677         case nir_intrinsic_load_vertex_id_zero_base:
1678                 return PAN_VERTEX_ID;
1679         case nir_intrinsic_load_instance_id:
1680                 return PAN_INSTANCE_ID;
1681         default:
1682                 unreachable("Invalid vertex builtin");
1683         }
1684 }
1685 
1686 static void
emit_vertex_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1687 emit_vertex_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1688 {
1689         unsigned reg = nir_dest_index(&instr->dest);
1690         emit_attr_read(ctx, reg, vertex_builtin_arg(instr->intrinsic), 1, nir_type_int);
1691 }
1692 
1693 static void
emit_special(compiler_context * ctx,nir_intrinsic_instr * instr,unsigned idx)1694 emit_special(compiler_context *ctx, nir_intrinsic_instr *instr, unsigned idx)
1695 {
1696         unsigned reg = nir_dest_index(&instr->dest);
1697 
1698         midgard_instruction ld = m_ld_tilebuffer_raw(reg, 0);
1699         ld.op = midgard_op_ld_special_32u;
1700         ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(idx);
1701         ld.load_store.index_reg = REGISTER_LDST_ZERO;
1702 
1703         for (int i = 0; i < 4; ++i)
1704                 ld.swizzle[0][i] = COMPONENT_X;
1705 
1706         emit_mir_instruction(ctx, ld);
1707 }
1708 
1709 static void
emit_control_barrier(compiler_context * ctx)1710 emit_control_barrier(compiler_context *ctx)
1711 {
1712         midgard_instruction ins = {
1713                 .type = TAG_TEXTURE_4,
1714                 .dest = ~0,
1715                 .src = { ~0, ~0, ~0, ~0 },
1716                 .op = midgard_tex_op_barrier,
1717         };
1718 
1719         emit_mir_instruction(ctx, ins);
1720 }
1721 
1722 static unsigned
mir_get_branch_cond(nir_src * src,bool * invert)1723 mir_get_branch_cond(nir_src *src, bool *invert)
1724 {
1725         /* Wrap it. No swizzle since it's a scalar */
1726 
1727         nir_alu_src alu = {
1728                 .src = *src
1729         };
1730 
1731         *invert = pan_has_source_mod(&alu, nir_op_inot);
1732         return nir_src_index(NULL, &alu.src);
1733 }
1734 
1735 static uint8_t
output_load_rt_addr(compiler_context * ctx,nir_intrinsic_instr * instr)1736 output_load_rt_addr(compiler_context *ctx, nir_intrinsic_instr *instr)
1737 {
1738         if (ctx->inputs->is_blend)
1739                 return MIDGARD_COLOR_RT0 + ctx->inputs->blend.rt;
1740 
1741         const nir_variable *var;
1742         var = nir_find_variable_with_driver_location(ctx->nir, nir_var_shader_out, nir_intrinsic_base(instr));
1743         assert(var);
1744 
1745         unsigned loc = var->data.location;
1746 
1747         if (loc >= FRAG_RESULT_DATA0)
1748                 return loc - FRAG_RESULT_DATA0;
1749 
1750         if (loc == FRAG_RESULT_DEPTH)
1751                 return 0x1F;
1752         if (loc == FRAG_RESULT_STENCIL)
1753                 return 0x1E;
1754 
1755         unreachable("Invalid RT to load from");
1756 }
1757 
1758 static void
emit_intrinsic(compiler_context * ctx,nir_intrinsic_instr * instr)1759 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1760 {
1761         unsigned offset = 0, reg;
1762 
1763         switch (instr->intrinsic) {
1764         case nir_intrinsic_discard_if:
1765         case nir_intrinsic_discard: {
1766                 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1767                 struct midgard_instruction discard = v_branch(conditional, false);
1768                 discard.branch.target_type = TARGET_DISCARD;
1769 
1770                 if (conditional) {
1771                         discard.src[0] = mir_get_branch_cond(&instr->src[0],
1772                                         &discard.branch.invert_conditional);
1773                         discard.src_types[0] = nir_type_uint32;
1774                 }
1775 
1776                 emit_mir_instruction(ctx, discard);
1777                 schedule_barrier(ctx);
1778 
1779                 break;
1780         }
1781 
1782         case nir_intrinsic_image_load:
1783         case nir_intrinsic_image_store:
1784                 emit_image_op(ctx, instr, false);
1785                 break;
1786 
1787         case nir_intrinsic_image_size: {
1788                 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1789                 emit_sysval_read(ctx, &instr->instr, nr_comp, 0);
1790                 break;
1791         }
1792 
1793         case nir_intrinsic_load_ubo:
1794         case nir_intrinsic_load_global:
1795         case nir_intrinsic_load_global_constant:
1796         case nir_intrinsic_load_shared:
1797         case nir_intrinsic_load_scratch:
1798         case nir_intrinsic_load_input:
1799         case nir_intrinsic_load_kernel_input:
1800         case nir_intrinsic_load_interpolated_input: {
1801                 bool is_ubo = instr->intrinsic == nir_intrinsic_load_ubo;
1802                 bool is_global = instr->intrinsic == nir_intrinsic_load_global ||
1803                         instr->intrinsic == nir_intrinsic_load_global_constant;
1804                 bool is_shared = instr->intrinsic == nir_intrinsic_load_shared;
1805                 bool is_scratch = instr->intrinsic == nir_intrinsic_load_scratch;
1806                 bool is_flat = instr->intrinsic == nir_intrinsic_load_input;
1807                 bool is_kernel = instr->intrinsic == nir_intrinsic_load_kernel_input;
1808                 bool is_interp = instr->intrinsic == nir_intrinsic_load_interpolated_input;
1809 
1810                 /* Get the base type of the intrinsic */
1811                 /* TODO: Infer type? Does it matter? */
1812                 nir_alu_type t =
1813                         (is_interp) ? nir_type_float :
1814                         (is_flat) ? nir_intrinsic_dest_type(instr) :
1815                         nir_type_uint;
1816 
1817                 t = nir_alu_type_get_base_type(t);
1818 
1819                 if (!(is_ubo || is_global || is_scratch)) {
1820                         offset = nir_intrinsic_base(instr);
1821                 }
1822 
1823                 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1824 
1825                 nir_src *src_offset = nir_get_io_offset_src(instr);
1826 
1827                 bool direct = nir_src_is_const(*src_offset);
1828                 nir_src *indirect_offset = direct ? NULL : src_offset;
1829 
1830                 if (direct)
1831                         offset += nir_src_as_uint(*src_offset);
1832 
1833                 /* We may need to apply a fractional offset */
1834                 int component = (is_flat || is_interp) ?
1835                                 nir_intrinsic_component(instr) : 0;
1836                 reg = nir_dest_index(&instr->dest);
1837 
1838                 if (is_kernel) {
1839                         emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0, 0, nr_comp);
1840                 } else if (is_ubo) {
1841                         nir_src index = instr->src[0];
1842 
1843                         /* TODO: Is indirect block number possible? */
1844                         assert(nir_src_is_const(index));
1845 
1846                         uint32_t uindex = nir_src_as_uint(index);
1847                         emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0, uindex, nr_comp);
1848                 } else if (is_global || is_shared || is_scratch) {
1849                         unsigned seg = is_global ? LDST_GLOBAL : (is_shared ? LDST_SHARED : LDST_SCRATCH);
1850                         emit_global(ctx, &instr->instr, true, reg, src_offset, seg);
1851                 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->inputs->is_blend) {
1852                         emit_varying_read(ctx, reg, offset, nr_comp, component, indirect_offset, t | nir_dest_bit_size(instr->dest), is_flat);
1853                 } else if (ctx->inputs->is_blend) {
1854                         /* ctx->blend_input will be precoloured to r0/r2, where
1855                          * the input is preloaded */
1856 
1857                         unsigned *input = offset ? &ctx->blend_src1 : &ctx->blend_input;
1858 
1859                         if (*input == ~0)
1860                                 *input = reg;
1861                         else
1862                                 emit_mir_instruction(ctx, v_mov(*input, reg));
1863                 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1864                         emit_attr_read(ctx, reg, offset, nr_comp, t);
1865                 } else {
1866                         DBG("Unknown load\n");
1867                         assert(0);
1868                 }
1869 
1870                 break;
1871         }
1872 
1873         /* Handled together with load_interpolated_input */
1874         case nir_intrinsic_load_barycentric_pixel:
1875         case nir_intrinsic_load_barycentric_centroid:
1876         case nir_intrinsic_load_barycentric_sample:
1877                 break;
1878 
1879         /* Reads 128-bit value raw off the tilebuffer during blending, tasty */
1880 
1881         case nir_intrinsic_load_raw_output_pan: {
1882                 reg = nir_dest_index(&instr->dest);
1883 
1884                 /* T720 and below use different blend opcodes with slightly
1885                  * different semantics than T760 and up */
1886 
1887                 midgard_instruction ld = m_ld_tilebuffer_raw(reg, 0);
1888 
1889                 unsigned target = output_load_rt_addr(ctx, instr);
1890                 ld.load_store.index_comp = target & 0x3;
1891                 ld.load_store.index_reg = target >> 2;
1892 
1893                 if (nir_src_is_const(instr->src[0])) {
1894                         unsigned sample = nir_src_as_uint(instr->src[0]);
1895                         ld.load_store.arg_comp = sample & 0x3;
1896                         ld.load_store.arg_reg = sample >> 2;
1897                 } else {
1898                         /* Enable sample index via register. */
1899                         ld.load_store.signed_offset |= 1;
1900                         ld.src[1] = nir_src_index(ctx, &instr->src[0]);
1901                         ld.src_types[1] = nir_type_int32;
1902                 }
1903 
1904                 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1905                         ld.op = midgard_op_ld_special_32u;
1906                         ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(16);
1907                         ld.load_store.index_reg = REGISTER_LDST_ZERO;
1908                 }
1909 
1910                 emit_mir_instruction(ctx, ld);
1911                 break;
1912         }
1913 
1914         case nir_intrinsic_load_output: {
1915                 reg = nir_dest_index(&instr->dest);
1916 
1917                 unsigned bits = nir_dest_bit_size(instr->dest);
1918 
1919                 midgard_instruction ld;
1920                 if (bits == 16)
1921                         ld = m_ld_tilebuffer_16f(reg, 0);
1922                 else
1923                         ld = m_ld_tilebuffer_32f(reg, 0);
1924 
1925                 unsigned index = output_load_rt_addr(ctx, instr);
1926                 ld.load_store.index_comp = index & 0x3;
1927                 ld.load_store.index_reg = index >> 2;
1928 
1929                 for (unsigned c = 4; c < 16; ++c)
1930                         ld.swizzle[0][c] = 0;
1931 
1932                 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1933                         if (bits == 16)
1934                                 ld.op = midgard_op_ld_special_16f;
1935                         else
1936                                 ld.op = midgard_op_ld_special_32f;
1937                         ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(1);
1938                         ld.load_store.index_reg = REGISTER_LDST_ZERO;
1939                 }
1940 
1941                 emit_mir_instruction(ctx, ld);
1942                 break;
1943         }
1944 
1945         case nir_intrinsic_store_output:
1946         case nir_intrinsic_store_combined_output_pan:
1947                 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1948 
1949                 reg = nir_src_index(ctx, &instr->src[0]);
1950 
1951                 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1952                         bool combined = instr->intrinsic ==
1953                                 nir_intrinsic_store_combined_output_pan;
1954 
1955                         enum midgard_rt_id rt;
1956 
1957                         unsigned reg_z = ~0, reg_s = ~0, reg_2 = ~0;
1958                         if (combined) {
1959                                 unsigned writeout = nir_intrinsic_component(instr);
1960                                 if (writeout & PAN_WRITEOUT_Z)
1961                                         reg_z = nir_src_index(ctx, &instr->src[2]);
1962                                 if (writeout & PAN_WRITEOUT_S)
1963                                         reg_s = nir_src_index(ctx, &instr->src[3]);
1964                                 if (writeout & PAN_WRITEOUT_2)
1965                                         reg_2 = nir_src_index(ctx, &instr->src[4]);
1966 
1967                                 if (writeout & PAN_WRITEOUT_C)
1968                                         rt = MIDGARD_COLOR_RT0;
1969                                 else
1970                                         rt = MIDGARD_ZS_RT;
1971                         } else {
1972                                 const nir_variable *var =
1973                                         nir_find_variable_with_driver_location(ctx->nir, nir_var_shader_out,
1974                                                  nir_intrinsic_base(instr));
1975 
1976                                 assert(var != NULL);
1977                                 assert(var->data.location >= FRAG_RESULT_DATA0);
1978 
1979                                 rt = MIDGARD_COLOR_RT0 + var->data.location -
1980                                      FRAG_RESULT_DATA0;
1981                         }
1982 
1983                         /* Dual-source blend writeout is done by leaving the
1984                          * value in r2 for the blend shader to use. */
1985                         if (~reg_2) {
1986                                 if (instr->src[4].is_ssa) {
1987                                         emit_explicit_constant(ctx, reg_2, reg_2);
1988 
1989                                         unsigned out = make_compiler_temp(ctx);
1990 
1991                                         midgard_instruction ins = v_mov(reg_2, out);
1992                                         emit_mir_instruction(ctx, ins);
1993 
1994                                         ctx->blend_src1 = out;
1995                                 } else {
1996                                         ctx->blend_src1 = reg_2;
1997                                 }
1998                         }
1999 
2000                         emit_fragment_store(ctx, reg, reg_z, reg_s, rt, 0);
2001                 } else if (ctx->stage == MESA_SHADER_VERTEX) {
2002                         assert(instr->intrinsic == nir_intrinsic_store_output);
2003 
2004                         /* We should have been vectorized, though we don't
2005                          * currently check that st_vary is emitted only once
2006                          * per slot (this is relevant, since there's not a mask
2007                          * parameter available on the store [set to 0 by the
2008                          * blob]). We do respect the component by adjusting the
2009                          * swizzle. If this is a constant source, we'll need to
2010                          * emit that explicitly. */
2011 
2012                         emit_explicit_constant(ctx, reg, reg);
2013 
2014                         offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
2015 
2016                         unsigned dst_component = nir_intrinsic_component(instr);
2017                         unsigned nr_comp = nir_src_num_components(instr->src[0]);
2018 
2019                         midgard_instruction st = m_st_vary_32(reg, PACK_LDST_ATTRIB_OFS(offset));
2020                         st.load_store.arg_reg = REGISTER_LDST_ZERO;
2021                         st.load_store.index_format = midgard_index_address_u32;
2022                         st.load_store.index_reg = REGISTER_LDST_ZERO;
2023 
2024                         switch (nir_alu_type_get_base_type(nir_intrinsic_src_type(instr))) {
2025                         case nir_type_uint:
2026                         case nir_type_bool:
2027                                 st.op = midgard_op_st_vary_32u;
2028                                 break;
2029                         case nir_type_int:
2030                                 st.op = midgard_op_st_vary_32i;
2031                                 break;
2032                         case nir_type_float:
2033                                 st.op = midgard_op_st_vary_32;
2034                                 break;
2035                         default:
2036                                 unreachable("Attempted to store unknown type");
2037                                 break;
2038                         }
2039 
2040                         /* nir_intrinsic_component(store_intr) encodes the
2041                          * destination component start. Source component offset
2042                          * adjustment is taken care of in
2043                          * install_registers_instr(), when offset_swizzle() is
2044                          * called.
2045                          */
2046                         unsigned src_component = COMPONENT_X;
2047 
2048                         assert(nr_comp > 0);
2049                         for (unsigned i = 0; i < ARRAY_SIZE(st.swizzle); ++i) {
2050                                 st.swizzle[0][i] = src_component;
2051                                 if (i >= dst_component && i < dst_component + nr_comp - 1)
2052                                         src_component++;
2053                         }
2054 
2055                         emit_mir_instruction(ctx, st);
2056                 } else {
2057                         DBG("Unknown store\n");
2058                         assert(0);
2059                 }
2060 
2061                 break;
2062 
2063         /* Special case of store_output for lowered blend shaders */
2064         case nir_intrinsic_store_raw_output_pan:
2065                 assert (ctx->stage == MESA_SHADER_FRAGMENT);
2066                 reg = nir_src_index(ctx, &instr->src[0]);
2067                 for (unsigned s = 0; s < ctx->blend_sample_iterations; s++)
2068                         emit_fragment_store(ctx, reg, ~0, ~0,
2069                                             ctx->inputs->blend.rt + MIDGARD_COLOR_RT0,
2070                                             s);
2071                 break;
2072 
2073         case nir_intrinsic_store_global:
2074         case nir_intrinsic_store_shared:
2075         case nir_intrinsic_store_scratch:
2076                 reg = nir_src_index(ctx, &instr->src[0]);
2077                 emit_explicit_constant(ctx, reg, reg);
2078 
2079                 unsigned seg;
2080                 if (instr->intrinsic == nir_intrinsic_store_global)
2081                         seg = LDST_GLOBAL;
2082                 else if (instr->intrinsic == nir_intrinsic_store_shared)
2083                         seg = LDST_SHARED;
2084                 else
2085                         seg = LDST_SCRATCH;
2086 
2087                 emit_global(ctx, &instr->instr, false, reg, &instr->src[1], seg);
2088                 break;
2089 
2090         case nir_intrinsic_load_first_vertex:
2091         case nir_intrinsic_load_ssbo_address:
2092         case nir_intrinsic_load_work_dim:
2093                 emit_sysval_read(ctx, &instr->instr, 1, 0);
2094                 break;
2095 
2096         case nir_intrinsic_load_base_vertex:
2097                 emit_sysval_read(ctx, &instr->instr, 1, 4);
2098                 break;
2099 
2100         case nir_intrinsic_load_base_instance:
2101                 emit_sysval_read(ctx, &instr->instr, 1, 8);
2102                 break;
2103 
2104         case nir_intrinsic_load_sample_positions_pan:
2105                 emit_sysval_read(ctx, &instr->instr, 2, 0);
2106                 break;
2107 
2108         case nir_intrinsic_get_ssbo_size:
2109                 emit_sysval_read(ctx, &instr->instr, 1, 8);
2110                 break;
2111 
2112         case nir_intrinsic_load_viewport_scale:
2113         case nir_intrinsic_load_viewport_offset:
2114         case nir_intrinsic_load_num_workgroups:
2115         case nir_intrinsic_load_sampler_lod_parameters_pan:
2116         case nir_intrinsic_load_workgroup_size:
2117                 emit_sysval_read(ctx, &instr->instr, 3, 0);
2118                 break;
2119 
2120         case nir_intrinsic_load_blend_const_color_rgba:
2121                 emit_sysval_read(ctx, &instr->instr, 4, 0);
2122                 break;
2123 
2124         case nir_intrinsic_load_workgroup_id:
2125         case nir_intrinsic_load_local_invocation_id:
2126         case nir_intrinsic_load_global_invocation_id:
2127         case nir_intrinsic_load_global_invocation_id_zero_base:
2128                 emit_compute_builtin(ctx, instr);
2129                 break;
2130 
2131         case nir_intrinsic_load_vertex_id_zero_base:
2132         case nir_intrinsic_load_instance_id:
2133                 emit_vertex_builtin(ctx, instr);
2134                 break;
2135 
2136         case nir_intrinsic_load_sample_mask_in:
2137                 emit_special(ctx, instr, 96);
2138                 break;
2139 
2140         case nir_intrinsic_load_sample_id:
2141                 emit_special(ctx, instr, 97);
2142                 break;
2143 
2144         /* Midgard doesn't seem to want special handling */
2145         case nir_intrinsic_memory_barrier:
2146         case nir_intrinsic_memory_barrier_buffer:
2147         case nir_intrinsic_memory_barrier_image:
2148         case nir_intrinsic_memory_barrier_shared:
2149         case nir_intrinsic_group_memory_barrier:
2150                 break;
2151 
2152         case nir_intrinsic_control_barrier:
2153                 schedule_barrier(ctx);
2154                 emit_control_barrier(ctx);
2155                 schedule_barrier(ctx);
2156                 break;
2157 
2158         ATOMIC_CASE(ctx, instr, add, add);
2159         ATOMIC_CASE(ctx, instr, and, and);
2160         ATOMIC_CASE(ctx, instr, comp_swap, cmpxchg);
2161         ATOMIC_CASE(ctx, instr, exchange, xchg);
2162         ATOMIC_CASE(ctx, instr, imax, imax);
2163         ATOMIC_CASE(ctx, instr, imin, imin);
2164         ATOMIC_CASE(ctx, instr, or, or);
2165         ATOMIC_CASE(ctx, instr, umax, umax);
2166         ATOMIC_CASE(ctx, instr, umin, umin);
2167         ATOMIC_CASE(ctx, instr, xor, xor);
2168 
2169         IMAGE_ATOMIC_CASE(ctx, instr, add, add);
2170         IMAGE_ATOMIC_CASE(ctx, instr, and, and);
2171         IMAGE_ATOMIC_CASE(ctx, instr, comp_swap, cmpxchg);
2172         IMAGE_ATOMIC_CASE(ctx, instr, exchange, xchg);
2173         IMAGE_ATOMIC_CASE(ctx, instr, imax, imax);
2174         IMAGE_ATOMIC_CASE(ctx, instr, imin, imin);
2175         IMAGE_ATOMIC_CASE(ctx, instr, or, or);
2176         IMAGE_ATOMIC_CASE(ctx, instr, umax, umax);
2177         IMAGE_ATOMIC_CASE(ctx, instr, umin, umin);
2178         IMAGE_ATOMIC_CASE(ctx, instr, xor, xor);
2179 
2180         default:
2181                 fprintf(stderr, "Unhandled intrinsic %s\n", nir_intrinsic_infos[instr->intrinsic].name);
2182                 assert(0);
2183                 break;
2184         }
2185 }
2186 
2187 /* Returns dimension with 0 special casing cubemaps */
2188 static unsigned
midgard_tex_format(enum glsl_sampler_dim dim)2189 midgard_tex_format(enum glsl_sampler_dim dim)
2190 {
2191         switch (dim) {
2192         case GLSL_SAMPLER_DIM_1D:
2193         case GLSL_SAMPLER_DIM_BUF:
2194                 return 1;
2195 
2196         case GLSL_SAMPLER_DIM_2D:
2197         case GLSL_SAMPLER_DIM_MS:
2198         case GLSL_SAMPLER_DIM_EXTERNAL:
2199         case GLSL_SAMPLER_DIM_RECT:
2200                 return 2;
2201 
2202         case GLSL_SAMPLER_DIM_3D:
2203                 return 3;
2204 
2205         case GLSL_SAMPLER_DIM_CUBE:
2206                 return 0;
2207 
2208         default:
2209                 DBG("Unknown sampler dim type\n");
2210                 assert(0);
2211                 return 0;
2212         }
2213 }
2214 
2215 /* Tries to attach an explicit LOD or bias as a constant. Returns whether this
2216  * was successful */
2217 
2218 static bool
pan_attach_constant_bias(compiler_context * ctx,nir_src lod,midgard_texture_word * word)2219 pan_attach_constant_bias(
2220         compiler_context *ctx,
2221         nir_src lod,
2222         midgard_texture_word *word)
2223 {
2224         /* To attach as constant, it has to *be* constant */
2225 
2226         if (!nir_src_is_const(lod))
2227                 return false;
2228 
2229         float f = nir_src_as_float(lod);
2230 
2231         /* Break into fixed-point */
2232         signed lod_int = f;
2233         float lod_frac = f - lod_int;
2234 
2235         /* Carry over negative fractions */
2236         if (lod_frac < 0.0) {
2237                 lod_int--;
2238                 lod_frac += 1.0;
2239         }
2240 
2241         /* Encode */
2242         word->bias = float_to_ubyte(lod_frac);
2243         word->bias_int = lod_int;
2244 
2245         return true;
2246 }
2247 
2248 static enum mali_texture_mode
mdg_texture_mode(nir_tex_instr * instr)2249 mdg_texture_mode(nir_tex_instr *instr)
2250 {
2251         if (instr->op == nir_texop_tg4 && instr->is_shadow)
2252                 return TEXTURE_GATHER_SHADOW;
2253         else if (instr->op == nir_texop_tg4)
2254                 return TEXTURE_GATHER_X + instr->component;
2255         else if (instr->is_shadow)
2256                 return TEXTURE_SHADOW;
2257         else
2258                 return TEXTURE_NORMAL;
2259 }
2260 
2261 static void
set_tex_coord(compiler_context * ctx,nir_tex_instr * instr,midgard_instruction * ins)2262 set_tex_coord(compiler_context *ctx, nir_tex_instr *instr,
2263               midgard_instruction *ins)
2264 {
2265         int coord_idx = nir_tex_instr_src_index(instr, nir_tex_src_coord);
2266 
2267         assert(coord_idx >= 0);
2268 
2269         int comparator_idx = nir_tex_instr_src_index(instr, nir_tex_src_comparator);
2270         int ms_idx = nir_tex_instr_src_index(instr, nir_tex_src_ms_index);
2271         assert(comparator_idx < 0 || ms_idx < 0);
2272         int ms_or_comparator_idx = ms_idx >= 0 ? ms_idx : comparator_idx;
2273 
2274         unsigned coords = nir_src_index(ctx, &instr->src[coord_idx].src);
2275 
2276         emit_explicit_constant(ctx, coords, coords);
2277 
2278         ins->src_types[1] = nir_tex_instr_src_type(instr, coord_idx) |
2279                             nir_src_bit_size(instr->src[coord_idx].src);
2280 
2281         unsigned nr_comps = instr->coord_components;
2282         unsigned written_mask = 0, write_mask = 0;
2283 
2284         /* Initialize all components to coord.x which is expected to always be
2285          * present. Swizzle is updated below based on the texture dimension
2286          * and extra attributes that are packed in the coordinate argument.
2287          */
2288         for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++)
2289                 ins->swizzle[1][c] = COMPONENT_X;
2290 
2291         /* Shadow ref value is part of the coordinates if there's no comparator
2292          * source, in that case it's always placed in the last component.
2293          * Midgard wants the ref value in coord.z.
2294          */
2295         if (instr->is_shadow && comparator_idx < 0) {
2296                 ins->swizzle[1][COMPONENT_Z] = --nr_comps;
2297                 write_mask |= 1 << COMPONENT_Z;
2298         }
2299 
2300         /* The array index is the last component if there's no shadow ref value
2301          * or second last if there's one. We already decremented the number of
2302          * components to account for the shadow ref value above.
2303          * Midgard wants the array index in coord.w.
2304          */
2305         if (instr->is_array) {
2306                 ins->swizzle[1][COMPONENT_W] = --nr_comps;
2307                 write_mask |= 1 << COMPONENT_W;
2308         }
2309 
2310         if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
2311                 /* texelFetch is undefined on samplerCube */
2312                 assert(ins->op != midgard_tex_op_fetch);
2313 
2314                 ins->src[1] = make_compiler_temp_reg(ctx);
2315 
2316                 /* For cubemaps, we use a special ld/st op to select the face
2317                  * and copy the xy into the texture register
2318                  */
2319                 midgard_instruction ld = m_ld_cubemap_coords(ins->src[1], 0);
2320                 ld.src[1] = coords;
2321                 ld.src_types[1] = ins->src_types[1];
2322                 ld.mask = 0x3; /* xy */
2323                 ld.load_store.bitsize_toggle = true;
2324                 ld.swizzle[1][3] = COMPONENT_X;
2325                 emit_mir_instruction(ctx, ld);
2326 
2327                 /* We packed cube coordiates (X,Y,Z) into (X,Y), update the
2328                  * written mask accordingly and decrement the number of
2329                  * components
2330                  */
2331                 nr_comps--;
2332                 written_mask |= 3;
2333         }
2334 
2335         /* Now flag tex coord components that have not been written yet */
2336         write_mask |= mask_of(nr_comps) & ~written_mask;
2337         for (unsigned c = 0; c < nr_comps; c++)
2338                 ins->swizzle[1][c] = c;
2339 
2340         /* Sample index and shadow ref are expected in coord.z */
2341         if (ms_or_comparator_idx >= 0) {
2342                 assert(!((write_mask | written_mask) & (1 << COMPONENT_Z)));
2343 
2344                 unsigned sample_or_ref =
2345                         nir_src_index(ctx, &instr->src[ms_or_comparator_idx].src);
2346 
2347                 emit_explicit_constant(ctx, sample_or_ref, sample_or_ref);
2348 
2349                 if (ins->src[1] == ~0)
2350                         ins->src[1] = make_compiler_temp_reg(ctx);
2351 
2352                 midgard_instruction mov = v_mov(sample_or_ref, ins->src[1]);
2353 
2354                 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++)
2355                         mov.swizzle[1][c] = COMPONENT_X;
2356 
2357                 mov.mask = 1 << COMPONENT_Z;
2358                 written_mask |= 1 << COMPONENT_Z;
2359                 ins->swizzle[1][COMPONENT_Z] = COMPONENT_Z;
2360                 emit_mir_instruction(ctx, mov);
2361         }
2362 
2363         /* Texelfetch coordinates uses all four elements (xyz/index) regardless
2364          * of texture dimensionality, which means it's necessary to zero the
2365          * unused components to keep everything happy.
2366          */
2367         if (ins->op == midgard_tex_op_fetch &&
2368             (written_mask | write_mask) != 0xF) {
2369                 if (ins->src[1] == ~0)
2370                         ins->src[1] = make_compiler_temp_reg(ctx);
2371 
2372                 /* mov index.zw, #0, or generalized */
2373                 midgard_instruction mov =
2374                         v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), ins->src[1]);
2375                 mov.has_constants = true;
2376                 mov.mask = (written_mask | write_mask) ^ 0xF;
2377                 emit_mir_instruction(ctx, mov);
2378                 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++) {
2379                         if (mov.mask & (1 << c))
2380                                 ins->swizzle[1][c] = c;
2381                 }
2382         }
2383 
2384         if (ins->src[1] == ~0) {
2385                 /* No temporary reg created, use the src coords directly */
2386                 ins->src[1] = coords;
2387 	} else if (write_mask) {
2388                 /* Move the remaining coordinates to the temporary reg */
2389                 midgard_instruction mov = v_mov(coords, ins->src[1]);
2390 
2391                 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++) {
2392                         if ((1 << c) & write_mask) {
2393                                 mov.swizzle[1][c] = ins->swizzle[1][c];
2394                                 ins->swizzle[1][c] = c;
2395                         } else {
2396                                 mov.swizzle[1][c] = COMPONENT_X;
2397                         }
2398                 }
2399 
2400                 mov.mask = write_mask;
2401                 emit_mir_instruction(ctx, mov);
2402         }
2403 }
2404 
2405 static void
emit_texop_native(compiler_context * ctx,nir_tex_instr * instr,unsigned midgard_texop)2406 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
2407                   unsigned midgard_texop)
2408 {
2409         nir_dest *dest = &instr->dest;
2410 
2411         int texture_index = instr->texture_index;
2412         int sampler_index = instr->sampler_index;
2413 
2414         nir_alu_type dest_base = nir_alu_type_get_base_type(instr->dest_type);
2415 
2416         /* texture instructions support float outmods */
2417         unsigned outmod = midgard_outmod_none;
2418         if (dest_base == nir_type_float) {
2419                 outmod = mir_determine_float_outmod(ctx, &dest, 0);
2420         }
2421 
2422         midgard_instruction ins = {
2423                 .type = TAG_TEXTURE_4,
2424                 .mask = 0xF,
2425                 .dest = nir_dest_index(dest),
2426                 .src = { ~0, ~0, ~0, ~0 },
2427                 .dest_type = instr->dest_type,
2428                 .swizzle = SWIZZLE_IDENTITY_4,
2429                 .outmod = outmod,
2430                 .op = midgard_texop,
2431                 .texture = {
2432                         .format = midgard_tex_format(instr->sampler_dim),
2433                         .texture_handle = texture_index,
2434                         .sampler_handle = sampler_index,
2435                         .mode = mdg_texture_mode(instr)
2436                 }
2437         };
2438 
2439         if (instr->is_shadow && !instr->is_new_style_shadow && instr->op != nir_texop_tg4)
2440            for (int i = 0; i < 4; ++i)
2441               ins.swizzle[0][i] = COMPONENT_X;
2442 
2443         for (unsigned i = 0; i < instr->num_srcs; ++i) {
2444                 int index = nir_src_index(ctx, &instr->src[i].src);
2445                 unsigned sz = nir_src_bit_size(instr->src[i].src);
2446                 nir_alu_type T = nir_tex_instr_src_type(instr, i) | sz;
2447 
2448                 switch (instr->src[i].src_type) {
2449                 case nir_tex_src_coord:
2450                         set_tex_coord(ctx, instr, &ins);
2451                         break;
2452 
2453                 case nir_tex_src_bias:
2454                 case nir_tex_src_lod: {
2455                         /* Try as a constant if we can */
2456 
2457                         bool is_txf = midgard_texop == midgard_tex_op_fetch;
2458                         if (!is_txf && pan_attach_constant_bias(ctx, instr->src[i].src, &ins.texture))
2459                                 break;
2460 
2461                         ins.texture.lod_register = true;
2462                         ins.src[2] = index;
2463                         ins.src_types[2] = T;
2464 
2465                         for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2466                                 ins.swizzle[2][c] = COMPONENT_X;
2467 
2468                         emit_explicit_constant(ctx, index, index);
2469 
2470                         break;
2471                 };
2472 
2473                 case nir_tex_src_offset: {
2474                         ins.texture.offset_register = true;
2475                         ins.src[3] = index;
2476                         ins.src_types[3] = T;
2477 
2478                         for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2479                                 ins.swizzle[3][c] = (c > COMPONENT_Z) ? 0 : c;
2480 
2481                         emit_explicit_constant(ctx, index, index);
2482                         break;
2483                 };
2484 
2485                 case nir_tex_src_comparator:
2486                 case nir_tex_src_ms_index:
2487                         /* Nothing to do, handled in set_tex_coord() */
2488                         break;
2489 
2490                 default: {
2491                         fprintf(stderr, "Unknown texture source type: %d\n", instr->src[i].src_type);
2492                         assert(0);
2493                 }
2494                 }
2495         }
2496 
2497         emit_mir_instruction(ctx, ins);
2498 }
2499 
2500 static void
emit_tex(compiler_context * ctx,nir_tex_instr * instr)2501 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
2502 {
2503         switch (instr->op) {
2504         case nir_texop_tex:
2505         case nir_texop_txb:
2506                 emit_texop_native(ctx, instr, midgard_tex_op_normal);
2507                 break;
2508         case nir_texop_txl:
2509         case nir_texop_tg4:
2510                 emit_texop_native(ctx, instr, midgard_tex_op_gradient);
2511                 break;
2512         case nir_texop_txf:
2513         case nir_texop_txf_ms:
2514                 emit_texop_native(ctx, instr, midgard_tex_op_fetch);
2515                 break;
2516         case nir_texop_txs:
2517                 emit_sysval_read(ctx, &instr->instr, 4, 0);
2518                 break;
2519         default: {
2520                 fprintf(stderr, "Unhandled texture op: %d\n", instr->op);
2521                 assert(0);
2522         }
2523         }
2524 }
2525 
2526 static void
emit_jump(compiler_context * ctx,nir_jump_instr * instr)2527 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
2528 {
2529         switch (instr->type) {
2530         case nir_jump_break: {
2531                 /* Emit a branch out of the loop */
2532                 struct midgard_instruction br = v_branch(false, false);
2533                 br.branch.target_type = TARGET_BREAK;
2534                 br.branch.target_break = ctx->current_loop_depth;
2535                 emit_mir_instruction(ctx, br);
2536                 break;
2537         }
2538 
2539         default:
2540                 unreachable("Unhandled jump");
2541         }
2542 }
2543 
2544 static void
emit_instr(compiler_context * ctx,struct nir_instr * instr)2545 emit_instr(compiler_context *ctx, struct nir_instr *instr)
2546 {
2547         switch (instr->type) {
2548         case nir_instr_type_load_const:
2549                 emit_load_const(ctx, nir_instr_as_load_const(instr));
2550                 break;
2551 
2552         case nir_instr_type_intrinsic:
2553                 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
2554                 break;
2555 
2556         case nir_instr_type_alu:
2557                 emit_alu(ctx, nir_instr_as_alu(instr));
2558                 break;
2559 
2560         case nir_instr_type_tex:
2561                 emit_tex(ctx, nir_instr_as_tex(instr));
2562                 break;
2563 
2564         case nir_instr_type_jump:
2565                 emit_jump(ctx, nir_instr_as_jump(instr));
2566                 break;
2567 
2568         case nir_instr_type_ssa_undef:
2569                 /* Spurious */
2570                 break;
2571 
2572         default:
2573                 DBG("Unhandled instruction type\n");
2574                 break;
2575         }
2576 }
2577 
2578 
2579 /* ALU instructions can inline or embed constants, which decreases register
2580  * pressure and saves space. */
2581 
2582 #define CONDITIONAL_ATTACH(idx) { \
2583 	void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[idx] + 1); \
2584 \
2585 	if (entry) { \
2586 		attach_constants(ctx, alu, entry, alu->src[idx] + 1); \
2587 		alu->src[idx] = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
2588 	} \
2589 }
2590 
2591 static void
inline_alu_constants(compiler_context * ctx,midgard_block * block)2592 inline_alu_constants(compiler_context *ctx, midgard_block *block)
2593 {
2594         mir_foreach_instr_in_block(block, alu) {
2595                 /* Other instructions cannot inline constants */
2596                 if (alu->type != TAG_ALU_4) continue;
2597                 if (alu->compact_branch) continue;
2598 
2599                 /* If there is already a constant here, we can do nothing */
2600                 if (alu->has_constants) continue;
2601 
2602                 CONDITIONAL_ATTACH(0);
2603 
2604                 if (!alu->has_constants) {
2605                         CONDITIONAL_ATTACH(1)
2606                 } else if (!alu->inline_constant) {
2607                         /* Corner case: _two_ vec4 constants, for instance with a
2608                          * csel. For this case, we can only use a constant
2609                          * register for one, we'll have to emit a move for the
2610                          * other. */
2611 
2612                         void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[1] + 1);
2613                         unsigned scratch = make_compiler_temp(ctx);
2614 
2615                         if (entry) {
2616                                 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), scratch);
2617                                 attach_constants(ctx, &ins, entry, alu->src[1] + 1);
2618 
2619                                 /* Set the source */
2620                                 alu->src[1] = scratch;
2621 
2622                                 /* Inject us -before- the last instruction which set r31 */
2623                                 mir_insert_instruction_before(ctx, mir_prev_op(alu), ins);
2624                         }
2625                 }
2626         }
2627 }
2628 
2629 unsigned
max_bitsize_for_alu(midgard_instruction * ins)2630 max_bitsize_for_alu(midgard_instruction *ins)
2631 {
2632         unsigned max_bitsize = 0;
2633         for (int i = 0; i < MIR_SRC_COUNT; i++) {
2634                 if (ins->src[i] == ~0) continue;
2635                 unsigned src_bitsize = nir_alu_type_get_type_size(ins->src_types[i]);
2636                 max_bitsize = MAX2(src_bitsize, max_bitsize);
2637         }
2638         unsigned dst_bitsize = nir_alu_type_get_type_size(ins->dest_type);
2639         max_bitsize = MAX2(dst_bitsize, max_bitsize);
2640 
2641         /* We don't have fp16 LUTs, so we'll want to emit code like:
2642          *
2643          *      vlut.fsinr hr0, hr0
2644          *
2645          * where both input and output are 16-bit but the operation is carried
2646          * out in 32-bit
2647          */
2648 
2649         switch (ins->op) {
2650         case midgard_alu_op_fsqrt:
2651         case midgard_alu_op_frcp:
2652         case midgard_alu_op_frsqrt:
2653         case midgard_alu_op_fsinpi:
2654         case midgard_alu_op_fcospi:
2655         case midgard_alu_op_fexp2:
2656         case midgard_alu_op_flog2:
2657                 max_bitsize = MAX2(max_bitsize, 32);
2658                 break;
2659 
2660         default:
2661                 break;
2662         }
2663 
2664         /* High implies computing at a higher bitsize, e.g umul_high of 32-bit
2665          * requires computing at 64-bit */
2666         if (midgard_is_integer_out_op(ins->op) && ins->outmod == midgard_outmod_keephi) {
2667                 max_bitsize *= 2;
2668                 assert(max_bitsize <= 64);
2669         }
2670 
2671         return max_bitsize;
2672 }
2673 
2674 midgard_reg_mode
reg_mode_for_bitsize(unsigned bitsize)2675 reg_mode_for_bitsize(unsigned bitsize)
2676 {
2677         switch (bitsize) {
2678                 /* use 16 pipe for 8 since we don't support vec16 yet */
2679         case 8:
2680         case 16:
2681                 return midgard_reg_mode_16;
2682         case 32:
2683                 return midgard_reg_mode_32;
2684         case 64:
2685                 return midgard_reg_mode_64;
2686         default:
2687                 unreachable("invalid bit size");
2688         }
2689 }
2690 
2691 /* Midgard supports two types of constants, embedded constants (128-bit) and
2692  * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2693  * constants can be demoted to inline constants, for space savings and
2694  * sometimes a performance boost */
2695 
2696 static void
embedded_to_inline_constant(compiler_context * ctx,midgard_block * block)2697 embedded_to_inline_constant(compiler_context *ctx, midgard_block *block)
2698 {
2699         mir_foreach_instr_in_block(block, ins) {
2700                 if (!ins->has_constants) continue;
2701                 if (ins->has_inline_constant) continue;
2702 
2703                 unsigned max_bitsize = max_bitsize_for_alu(ins);
2704 
2705                 /* We can inline 32-bit (sometimes) or 16-bit (usually) */
2706                 bool is_16 = max_bitsize == 16;
2707                 bool is_32 = max_bitsize == 32;
2708 
2709                 if (!(is_16 || is_32))
2710                         continue;
2711 
2712                 /* src1 cannot be an inline constant due to encoding
2713                  * restrictions. So, if possible we try to flip the arguments
2714                  * in that case */
2715 
2716                 int op = ins->op;
2717 
2718                 if (ins->src[0] == SSA_FIXED_REGISTER(REGISTER_CONSTANT) &&
2719                                 alu_opcode_props[op].props & OP_COMMUTES) {
2720                         mir_flip(ins);
2721                 }
2722 
2723                 if (ins->src[1] == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2724                         /* Component is from the swizzle. Take a nonzero component */
2725                         assert(ins->mask);
2726                         unsigned first_comp = ffs(ins->mask) - 1;
2727                         unsigned component = ins->swizzle[1][first_comp];
2728 
2729                         /* Scale constant appropriately, if we can legally */
2730                         int16_t scaled_constant = 0;
2731 
2732                         if (is_16) {
2733                                 scaled_constant = ins->constants.u16[component];
2734                         } else if (midgard_is_integer_op(op)) {
2735                                 scaled_constant = ins->constants.u32[component];
2736 
2737                                 /* Constant overflow after resize */
2738                                 if (scaled_constant != ins->constants.u32[component])
2739                                         continue;
2740                         } else {
2741                                 float original = ins->constants.f32[component];
2742                                 scaled_constant = _mesa_float_to_half(original);
2743 
2744                                 /* Check for loss of precision. If this is
2745                                  * mediump, we don't care, but for a highp
2746                                  * shader, we need to pay attention. NIR
2747                                  * doesn't yet tell us which mode we're in!
2748                                  * Practically this prevents most constants
2749                                  * from being inlined, sadly. */
2750 
2751                                 float fp32 = _mesa_half_to_float(scaled_constant);
2752 
2753                                 if (fp32 != original)
2754                                         continue;
2755                         }
2756 
2757                         /* Should've been const folded */
2758                         if (ins->src_abs[1] || ins->src_neg[1])
2759                                 continue;
2760 
2761                         /* Make sure that the constant is not itself a vector
2762                          * by checking if all accessed values are the same. */
2763 
2764                         const midgard_constants *cons = &ins->constants;
2765                         uint32_t value = is_16 ? cons->u16[component] : cons->u32[component];
2766 
2767                         bool is_vector = false;
2768                         unsigned mask = effective_writemask(ins->op, ins->mask);
2769 
2770                         for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c) {
2771                                 /* We only care if this component is actually used */
2772                                 if (!(mask & (1 << c)))
2773                                         continue;
2774 
2775                                 uint32_t test = is_16 ?
2776                                                 cons->u16[ins->swizzle[1][c]] :
2777                                                 cons->u32[ins->swizzle[1][c]];
2778 
2779                                 if (test != value) {
2780                                         is_vector = true;
2781                                         break;
2782                                 }
2783                         }
2784 
2785                         if (is_vector)
2786                                 continue;
2787 
2788                         /* Get rid of the embedded constant */
2789                         ins->has_constants = false;
2790                         ins->src[1] = ~0;
2791                         ins->has_inline_constant = true;
2792                         ins->inline_constant = scaled_constant;
2793                 }
2794         }
2795 }
2796 
2797 /* Dead code elimination for branches at the end of a block - only one branch
2798  * per block is legal semantically */
2799 
2800 static void
midgard_cull_dead_branch(compiler_context * ctx,midgard_block * block)2801 midgard_cull_dead_branch(compiler_context *ctx, midgard_block *block)
2802 {
2803         bool branched = false;
2804 
2805         mir_foreach_instr_in_block_safe(block, ins) {
2806                 if (!midgard_is_branch_unit(ins->unit)) continue;
2807 
2808                 if (branched)
2809                         mir_remove_instruction(ins);
2810 
2811                 branched = true;
2812         }
2813 }
2814 
2815 /* We want to force the invert on AND/OR to the second slot to legalize into
2816  * iandnot/iornot. The relevant patterns are for AND (and OR respectively)
2817  *
2818  *   ~a & #b = ~a & ~(#~b)
2819  *   ~a & b = b & ~a
2820  */
2821 
2822 static void
midgard_legalize_invert(compiler_context * ctx,midgard_block * block)2823 midgard_legalize_invert(compiler_context *ctx, midgard_block *block)
2824 {
2825         mir_foreach_instr_in_block(block, ins) {
2826                 if (ins->type != TAG_ALU_4) continue;
2827 
2828                 if (ins->op != midgard_alu_op_iand &&
2829                     ins->op != midgard_alu_op_ior) continue;
2830 
2831                 if (ins->src_invert[1] || !ins->src_invert[0]) continue;
2832 
2833                 if (ins->has_inline_constant) {
2834                         /* ~(#~a) = ~(~#a) = a, so valid, and forces both
2835                          * inverts on */
2836                         ins->inline_constant = ~ins->inline_constant;
2837                         ins->src_invert[1] = true;
2838                 } else {
2839                         /* Flip to the right invert order. Note
2840                          * has_inline_constant false by assumption on the
2841                          * branch, so flipping makes sense. */
2842                         mir_flip(ins);
2843                 }
2844         }
2845 }
2846 
2847 static unsigned
emit_fragment_epilogue(compiler_context * ctx,unsigned rt,unsigned sample_iter)2848 emit_fragment_epilogue(compiler_context *ctx, unsigned rt, unsigned sample_iter)
2849 {
2850         /* Loop to ourselves */
2851         midgard_instruction *br = ctx->writeout_branch[rt][sample_iter];
2852         struct midgard_instruction ins = v_branch(false, false);
2853         ins.writeout = br->writeout;
2854         ins.branch.target_block = ctx->block_count - 1;
2855         ins.constants.u32[0] = br->constants.u32[0];
2856         memcpy(&ins.src_types, &br->src_types, sizeof(ins.src_types));
2857         emit_mir_instruction(ctx, ins);
2858 
2859         ctx->current_block->epilogue = true;
2860         schedule_barrier(ctx);
2861         return ins.branch.target_block;
2862 }
2863 
2864 static midgard_block *
emit_block_init(compiler_context * ctx)2865 emit_block_init(compiler_context *ctx)
2866 {
2867         midgard_block *this_block = ctx->after_block;
2868         ctx->after_block = NULL;
2869 
2870         if (!this_block)
2871                 this_block = create_empty_block(ctx);
2872 
2873         list_addtail(&this_block->base.link, &ctx->blocks);
2874 
2875         this_block->scheduled = false;
2876         ++ctx->block_count;
2877 
2878         /* Set up current block */
2879         list_inithead(&this_block->base.instructions);
2880         ctx->current_block = this_block;
2881 
2882         return this_block;
2883 }
2884 
2885 static midgard_block *
emit_block(compiler_context * ctx,nir_block * block)2886 emit_block(compiler_context *ctx, nir_block *block)
2887 {
2888         midgard_block *this_block = emit_block_init(ctx);
2889 
2890         nir_foreach_instr(instr, block) {
2891                 emit_instr(ctx, instr);
2892                 ++ctx->instruction_count;
2893         }
2894 
2895         return this_block;
2896 }
2897 
2898 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2899 
2900 static void
emit_if(struct compiler_context * ctx,nir_if * nif)2901 emit_if(struct compiler_context *ctx, nir_if *nif)
2902 {
2903         midgard_block *before_block = ctx->current_block;
2904 
2905         /* Speculatively emit the branch, but we can't fill it in until later */
2906         bool inv = false;
2907         EMIT(branch, true, true);
2908         midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2909         then_branch->src[0] = mir_get_branch_cond(&nif->condition, &inv);
2910         then_branch->src_types[0] = nir_type_uint32;
2911         then_branch->branch.invert_conditional = !inv;
2912 
2913         /* Emit the two subblocks. */
2914         midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2915         midgard_block *end_then_block = ctx->current_block;
2916 
2917         /* Emit a jump from the end of the then block to the end of the else */
2918         EMIT(branch, false, false);
2919         midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2920 
2921         /* Emit second block, and check if it's empty */
2922 
2923         int else_idx = ctx->block_count;
2924         int count_in = ctx->instruction_count;
2925         midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2926         midgard_block *end_else_block = ctx->current_block;
2927         int after_else_idx = ctx->block_count;
2928 
2929         /* Now that we have the subblocks emitted, fix up the branches */
2930 
2931         assert(then_block);
2932         assert(else_block);
2933 
2934         if (ctx->instruction_count == count_in) {
2935                 /* The else block is empty, so don't emit an exit jump */
2936                 mir_remove_instruction(then_exit);
2937                 then_branch->branch.target_block = after_else_idx;
2938         } else {
2939                 then_branch->branch.target_block = else_idx;
2940                 then_exit->branch.target_block = after_else_idx;
2941         }
2942 
2943         /* Wire up the successors */
2944 
2945         ctx->after_block = create_empty_block(ctx);
2946 
2947         pan_block_add_successor(&before_block->base, &then_block->base);
2948         pan_block_add_successor(&before_block->base, &else_block->base);
2949 
2950         pan_block_add_successor(&end_then_block->base, &ctx->after_block->base);
2951         pan_block_add_successor(&end_else_block->base, &ctx->after_block->base);
2952 }
2953 
2954 static void
emit_loop(struct compiler_context * ctx,nir_loop * nloop)2955 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2956 {
2957         /* Remember where we are */
2958         midgard_block *start_block = ctx->current_block;
2959 
2960         /* Allocate a loop number, growing the current inner loop depth */
2961         int loop_idx = ++ctx->current_loop_depth;
2962 
2963         /* Get index from before the body so we can loop back later */
2964         int start_idx = ctx->block_count;
2965 
2966         /* Emit the body itself */
2967         midgard_block *loop_block = emit_cf_list(ctx, &nloop->body);
2968 
2969         /* Branch back to loop back */
2970         struct midgard_instruction br_back = v_branch(false, false);
2971         br_back.branch.target_block = start_idx;
2972         emit_mir_instruction(ctx, br_back);
2973 
2974         /* Mark down that branch in the graph. */
2975         pan_block_add_successor(&start_block->base, &loop_block->base);
2976         pan_block_add_successor(&ctx->current_block->base, &loop_block->base);
2977 
2978         /* Find the index of the block about to follow us (note: we don't add
2979          * one; blocks are 0-indexed so we get a fencepost problem) */
2980         int break_block_idx = ctx->block_count;
2981 
2982         /* Fix up the break statements we emitted to point to the right place,
2983          * now that we can allocate a block number for them */
2984         ctx->after_block = create_empty_block(ctx);
2985 
2986         mir_foreach_block_from(ctx, start_block, _block) {
2987                 mir_foreach_instr_in_block(((midgard_block *) _block), ins) {
2988                         if (ins->type != TAG_ALU_4) continue;
2989                         if (!ins->compact_branch) continue;
2990 
2991                         /* We found a branch -- check the type to see if we need to do anything */
2992                         if (ins->branch.target_type != TARGET_BREAK) continue;
2993 
2994                         /* It's a break! Check if it's our break */
2995                         if (ins->branch.target_break != loop_idx) continue;
2996 
2997                         /* Okay, cool, we're breaking out of this loop.
2998                          * Rewrite from a break to a goto */
2999 
3000                         ins->branch.target_type = TARGET_GOTO;
3001                         ins->branch.target_block = break_block_idx;
3002 
3003                         pan_block_add_successor(_block, &ctx->after_block->base);
3004                 }
3005         }
3006 
3007         /* Now that we've finished emitting the loop, free up the depth again
3008          * so we play nice with recursion amid nested loops */
3009         --ctx->current_loop_depth;
3010 
3011         /* Dump loop stats */
3012         ++ctx->loop_count;
3013 }
3014 
3015 static midgard_block *
emit_cf_list(struct compiler_context * ctx,struct exec_list * list)3016 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
3017 {
3018         midgard_block *start_block = NULL;
3019 
3020         foreach_list_typed(nir_cf_node, node, node, list) {
3021                 switch (node->type) {
3022                 case nir_cf_node_block: {
3023                         midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
3024 
3025                         if (!start_block)
3026                                 start_block = block;
3027 
3028                         break;
3029                 }
3030 
3031                 case nir_cf_node_if:
3032                         emit_if(ctx, nir_cf_node_as_if(node));
3033                         break;
3034 
3035                 case nir_cf_node_loop:
3036                         emit_loop(ctx, nir_cf_node_as_loop(node));
3037                         break;
3038 
3039                 case nir_cf_node_function:
3040                         assert(0);
3041                         break;
3042                 }
3043         }
3044 
3045         return start_block;
3046 }
3047 
3048 /* Due to lookahead, we need to report the first tag executed in the command
3049  * stream and in branch targets. An initial block might be empty, so iterate
3050  * until we find one that 'works' */
3051 
3052 unsigned
midgard_get_first_tag_from_block(compiler_context * ctx,unsigned block_idx)3053 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
3054 {
3055         midgard_block *initial_block = mir_get_block(ctx, block_idx);
3056 
3057         mir_foreach_block_from(ctx, initial_block, _v) {
3058                 midgard_block *v = (midgard_block *) _v;
3059                 if (v->quadword_count) {
3060                         midgard_bundle *initial_bundle =
3061                                 util_dynarray_element(&v->bundles, midgard_bundle, 0);
3062 
3063                         return initial_bundle->tag;
3064                 }
3065         }
3066 
3067         /* Default to a tag 1 which will break from the shader, in case we jump
3068          * to the exit block (i.e. `return` in a compute shader) */
3069 
3070         return 1;
3071 }
3072 
3073 /* For each fragment writeout instruction, generate a writeout loop to
3074  * associate with it */
3075 
3076 static void
mir_add_writeout_loops(compiler_context * ctx)3077 mir_add_writeout_loops(compiler_context *ctx)
3078 {
3079         for (unsigned rt = 0; rt < ARRAY_SIZE(ctx->writeout_branch); ++rt) {
3080                 for (unsigned s = 0; s < MIDGARD_MAX_SAMPLE_ITER; ++s) {
3081                         midgard_instruction *br = ctx->writeout_branch[rt][s];
3082                         if (!br) continue;
3083 
3084                         unsigned popped = br->branch.target_block;
3085                         pan_block_add_successor(&(mir_get_block(ctx, popped - 1)->base),
3086                                                 &ctx->current_block->base);
3087                         br->branch.target_block = emit_fragment_epilogue(ctx, rt, s);
3088                         br->branch.target_type = TARGET_GOTO;
3089 
3090                         /* If we have more RTs, we'll need to restore back after our
3091                          * loop terminates */
3092                         midgard_instruction *next_br = NULL;
3093 
3094                         if ((s + 1) < MIDGARD_MAX_SAMPLE_ITER)
3095                                 next_br = ctx->writeout_branch[rt][s + 1];
3096 
3097                         if (!next_br && (rt + 1) < ARRAY_SIZE(ctx->writeout_branch))
3098 			        next_br = ctx->writeout_branch[rt + 1][0];
3099 
3100                         if (next_br) {
3101                                 midgard_instruction uncond = v_branch(false, false);
3102                                 uncond.branch.target_block = popped;
3103                                 uncond.branch.target_type = TARGET_GOTO;
3104                                 emit_mir_instruction(ctx, uncond);
3105                                 pan_block_add_successor(&ctx->current_block->base,
3106                                                         &(mir_get_block(ctx, popped)->base));
3107                                 schedule_barrier(ctx);
3108                         } else {
3109                                 /* We're last, so we can terminate here */
3110                                 br->last_writeout = true;
3111                         }
3112                 }
3113         }
3114 }
3115 
3116 void
midgard_compile_shader_nir(nir_shader * nir,const struct panfrost_compile_inputs * inputs,struct util_dynarray * binary,struct pan_shader_info * info)3117 midgard_compile_shader_nir(nir_shader *nir,
3118                            const struct panfrost_compile_inputs *inputs,
3119                            struct util_dynarray *binary,
3120                            struct pan_shader_info *info)
3121 {
3122         midgard_debug = debug_get_option_midgard_debug();
3123 
3124         /* TODO: Bound against what? */
3125         compiler_context *ctx = rzalloc(NULL, compiler_context);
3126         ctx->sysval_to_id = panfrost_init_sysvals(&info->sysvals, ctx);
3127 
3128         ctx->inputs = inputs;
3129         ctx->nir = nir;
3130         ctx->info = info;
3131         ctx->stage = nir->info.stage;
3132 
3133         if (inputs->is_blend) {
3134                 unsigned nr_samples = MAX2(inputs->blend.nr_samples, 1);
3135                 const struct util_format_description *desc =
3136                         util_format_description(inputs->rt_formats[inputs->blend.rt]);
3137 
3138                 /* We have to split writeout in 128 bit chunks */
3139                 ctx->blend_sample_iterations =
3140                         DIV_ROUND_UP(desc->block.bits * nr_samples, 128);
3141         }
3142         ctx->blend_input = ~0;
3143         ctx->blend_src1 = ~0;
3144         ctx->quirks = midgard_get_quirks(inputs->gpu_id);
3145 
3146         /* Initialize at a global (not block) level hash tables */
3147 
3148         ctx->ssa_constants = _mesa_hash_table_u64_create(ctx);
3149 
3150         /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
3151          * (so we don't accidentally duplicate the epilogue since mesa/st has
3152          * messed with our I/O quite a bit already) */
3153 
3154         NIR_PASS_V(nir, nir_lower_vars_to_ssa);
3155 
3156         if (ctx->stage == MESA_SHADER_VERTEX) {
3157                 NIR_PASS_V(nir, nir_lower_viewport_transform);
3158                 NIR_PASS_V(nir, nir_lower_point_size, 1.0, 0.0);
3159         }
3160 
3161         NIR_PASS_V(nir, nir_lower_var_copies);
3162         NIR_PASS_V(nir, nir_lower_vars_to_ssa);
3163         NIR_PASS_V(nir, nir_split_var_copies);
3164         NIR_PASS_V(nir, nir_lower_var_copies);
3165         NIR_PASS_V(nir, nir_lower_global_vars_to_local);
3166         NIR_PASS_V(nir, nir_lower_var_copies);
3167         NIR_PASS_V(nir, nir_lower_vars_to_ssa);
3168 
3169         NIR_PASS_V(nir, pan_lower_framebuffer,
3170                    inputs->rt_formats, inputs->raw_fmt_mask,
3171                    inputs->is_blend, ctx->quirks & MIDGARD_BROKEN_BLEND_LOADS);
3172 
3173         NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
3174                         glsl_type_size, 0);
3175         NIR_PASS_V(nir, nir_lower_ssbo);
3176         NIR_PASS_V(nir, pan_nir_lower_zs_store);
3177 
3178         NIR_PASS_V(nir, pan_nir_lower_64bit_intrin);
3179 
3180         NIR_PASS_V(nir, midgard_nir_lower_global_load);
3181 
3182         /* Optimisation passes */
3183 
3184         optimise_nir(nir, ctx->quirks, inputs->is_blend, inputs->is_blit);
3185 
3186         bool skip_internal = nir->info.internal;
3187         skip_internal &= !(midgard_debug & MIDGARD_DBG_INTERNAL);
3188 
3189         if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
3190                 nir_print_shader(nir, stdout);
3191 
3192         info->tls_size = nir->scratch_size;
3193 
3194         nir_foreach_function(func, nir) {
3195                 if (!func->impl)
3196                         continue;
3197 
3198                 list_inithead(&ctx->blocks);
3199                 ctx->block_count = 0;
3200                 ctx->func = func;
3201                 ctx->already_emitted = calloc(BITSET_WORDS(func->impl->ssa_alloc), sizeof(BITSET_WORD));
3202 
3203                 if (nir->info.outputs_read && !inputs->is_blend) {
3204                         emit_block_init(ctx);
3205 
3206                         struct midgard_instruction wait = v_branch(false, false);
3207                         wait.branch.target_type = TARGET_TILEBUF_WAIT;
3208 
3209                         emit_mir_instruction(ctx, wait);
3210 
3211                         ++ctx->instruction_count;
3212                 }
3213 
3214                 emit_cf_list(ctx, &func->impl->body);
3215                 free(ctx->already_emitted);
3216                 break; /* TODO: Multi-function shaders */
3217         }
3218 
3219         /* Per-block lowering before opts */
3220 
3221         mir_foreach_block(ctx, _block) {
3222                 midgard_block *block = (midgard_block *) _block;
3223                 inline_alu_constants(ctx, block);
3224                 embedded_to_inline_constant(ctx, block);
3225         }
3226         /* MIR-level optimizations */
3227 
3228         bool progress = false;
3229 
3230         do {
3231                 progress = false;
3232                 progress |= midgard_opt_dead_code_eliminate(ctx);
3233 
3234                 mir_foreach_block(ctx, _block) {
3235                         midgard_block *block = (midgard_block *) _block;
3236                         progress |= midgard_opt_copy_prop(ctx, block);
3237                         progress |= midgard_opt_combine_projection(ctx, block);
3238                         progress |= midgard_opt_varying_projection(ctx, block);
3239                 }
3240         } while (progress);
3241 
3242         mir_foreach_block(ctx, _block) {
3243                 midgard_block *block = (midgard_block *) _block;
3244                 midgard_lower_derivatives(ctx, block);
3245                 midgard_legalize_invert(ctx, block);
3246                 midgard_cull_dead_branch(ctx, block);
3247         }
3248 
3249         if (ctx->stage == MESA_SHADER_FRAGMENT)
3250                 mir_add_writeout_loops(ctx);
3251 
3252         /* Analyze now that the code is known but before scheduling creates
3253          * pipeline registers which are harder to track */
3254         mir_analyze_helper_requirements(ctx);
3255 
3256         if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
3257                 mir_print_shader(ctx);
3258 
3259         /* Schedule! */
3260         midgard_schedule_program(ctx);
3261         mir_ra(ctx);
3262 
3263         if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
3264                 mir_print_shader(ctx);
3265 
3266         /* Analyze after scheduling since this is order-dependent */
3267         mir_analyze_helper_terminate(ctx);
3268 
3269         /* Emit flat binary from the instruction arrays. Iterate each block in
3270          * sequence. Save instruction boundaries such that lookahead tags can
3271          * be assigned easily */
3272 
3273         /* Cache _all_ bundles in source order for lookahead across failed branches */
3274 
3275         int bundle_count = 0;
3276         mir_foreach_block(ctx, _block) {
3277                 midgard_block *block = (midgard_block *) _block;
3278                 bundle_count += block->bundles.size / sizeof(midgard_bundle);
3279         }
3280         midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
3281         int bundle_idx = 0;
3282         mir_foreach_block(ctx, _block) {
3283                 midgard_block *block = (midgard_block *) _block;
3284                 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3285                         source_order_bundles[bundle_idx++] = bundle;
3286                 }
3287         }
3288 
3289         int current_bundle = 0;
3290 
3291         /* Midgard prefetches instruction types, so during emission we
3292          * need to lookahead. Unless this is the last instruction, in
3293          * which we return 1. */
3294 
3295         mir_foreach_block(ctx, _block) {
3296                 midgard_block *block = (midgard_block *) _block;
3297                 mir_foreach_bundle_in_block(block, bundle) {
3298                         int lookahead = 1;
3299 
3300                         if (!bundle->last_writeout && (current_bundle + 1 < bundle_count))
3301                                 lookahead = source_order_bundles[current_bundle + 1]->tag;
3302 
3303                         emit_binary_bundle(ctx, block, bundle, binary, lookahead);
3304                         ++current_bundle;
3305                 }
3306 
3307                 /* TODO: Free deeper */
3308                 //util_dynarray_fini(&block->instructions);
3309         }
3310 
3311         free(source_order_bundles);
3312 
3313         /* Report the very first tag executed */
3314         info->midgard.first_tag = midgard_get_first_tag_from_block(ctx, 0);
3315 
3316         info->ubo_mask = ctx->ubo_mask & ((1 << ctx->nir->info.num_ubos) - 1);
3317 
3318         if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal) {
3319                 disassemble_midgard(stdout, binary->data,
3320                                     binary->size, inputs->gpu_id,
3321                                     midgard_debug & MIDGARD_DBG_VERBOSE);
3322                 fflush(stdout);
3323         }
3324 
3325         /* A shader ending on a 16MB boundary causes INSTR_INVALID_PC faults,
3326          * workaround by adding some padding to the end of the shader. (The
3327          * kernel makes sure shader BOs can't cross 16MB boundaries.) */
3328         if (binary->size)
3329                 memset(util_dynarray_grow(binary, uint8_t, 16), 0, 16);
3330 
3331         if ((midgard_debug & MIDGARD_DBG_SHADERDB || inputs->shaderdb) &&
3332             !nir->info.internal) {
3333                 unsigned nr_bundles = 0, nr_ins = 0;
3334 
3335                 /* Count instructions and bundles */
3336 
3337                 mir_foreach_block(ctx, _block) {
3338                         midgard_block *block = (midgard_block *) _block;
3339                         nr_bundles += util_dynarray_num_elements(
3340                                               &block->bundles, midgard_bundle);
3341 
3342                         mir_foreach_bundle_in_block(block, bun)
3343                                 nr_ins += bun->instruction_count;
3344                 }
3345 
3346                 /* Calculate thread count. There are certain cutoffs by
3347                  * register count for thread count */
3348 
3349                 unsigned nr_registers = info->work_reg_count;
3350 
3351                 unsigned nr_threads =
3352                         (nr_registers <= 4) ? 4 :
3353                         (nr_registers <= 8) ? 2 :
3354                         1;
3355 
3356                 /* Dump stats */
3357 
3358                 fprintf(stderr, "%s - %s shader: "
3359                         "%u inst, %u bundles, %u quadwords, "
3360                         "%u registers, %u threads, %u loops, "
3361                         "%u:%u spills:fills\n",
3362                         ctx->nir->info.label ?: "",
3363                         ctx->inputs->is_blend ? "PAN_SHADER_BLEND" :
3364                         gl_shader_stage_name(ctx->stage),
3365                         nr_ins, nr_bundles, ctx->quadword_count,
3366                         nr_registers, nr_threads,
3367                         ctx->loop_count,
3368                         ctx->spills, ctx->fills);
3369         }
3370 
3371         _mesa_hash_table_u64_destroy(ctx->ssa_constants);
3372         _mesa_hash_table_u64_destroy(ctx->sysval_to_id);
3373 
3374         ralloc_free(ctx);
3375 }
3376