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