Debian Codegraph @

src/panfrost/compiler/bifrost/bi_ra.c

raw
1 /*
2 * Copyright (C) 2020,2025 Collabora Ltd.
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include "util/u_memory.h"
7 #include "bi_debug.h"
8 #include "bi_builder.h"
9 #include "compiler.h"
10 #include "nodearray.h"
11 #include "valhall.h"
12
13 struct lcra_state {
14 unsigned node_count;
15 uint64_t *affinity;
16
17 /* Linear constraints imposed. For each node there there is a
18 * 'nodearray' structure, which changes between a sparse and dense
19 * array depending on the number of elements.
20 *
21 * Each element is itself a bit field denoting whether (c_j - c_i) bias
22 * is present or not, including negative biases.
23 *
24 * We support up to 8 components so the bias is in range
25 * [-7, 7] encoded by a 16-bit field
26 */
27 nodearray *linear;
28
29 /* Before solving, forced registers; after solving, solutions. */
30 unsigned *solutions;
31
32 /** Node which caused register allocation to fail */
33 unsigned spill_node;
34 };
35
36 /* This module is an implementation of "Linearly Constrained
37 * Register Allocation". The paper is available in PDF form
38 * (https://people.collabora.com/~alyssa/LCRA.pdf) as well as Markdown+LaTeX
39 * (https://gitlab.freedesktop.org/alyssa/lcra/blob/master/LCRA.md)
40 */
41
42 static struct lcra_state *
43 lcra_alloc_equations(unsigned node_count)
44 {
45 struct lcra_state *l = calloc(1, sizeof(*l));
46
47 l->node_count = node_count;
48
49 l->linear = calloc(sizeof(l->linear[0]), node_count);
50 l->solutions = calloc(sizeof(l->solutions[0]), node_count);
51 l->affinity = calloc(sizeof(l->affinity[0]), node_count);
52
53 memset(l->solutions, ~0, sizeof(l->solutions[0]) * node_count);
54
55 return l;
56 }
57
58 static void
59 lcra_free(struct lcra_state *l)
60 {
61 for (unsigned i = 0; i < l->node_count; ++i)
62 nodearray_reset(&l->linear[i]);
63
64 free(l->linear);
65 free(l->affinity);
66 free(l->solutions);
67 free(l);
68 }
69
70 static void
71 lcra_add_node_interference(struct lcra_state *l, unsigned i, unsigned cmask_i,
72 unsigned j, unsigned cmask_j)
73 {
74 if (i == j)
75 return;
76
77 nodearray_value constraint_fw = 0;
78 nodearray_value constraint_bw = 0;
79
80 /* The constraint bits are reversed from lcra.c so that register
81 * allocation can be done in parallel for every possible solution,
82 * with lower-order bits representing smaller registers. */
83
84 for (unsigned D = 0; D < 8; ++D) {
85 if (cmask_i & (cmask_j << D)) {
86 constraint_fw |= (1 << (7 + D));
87 constraint_bw |= (1 << (7 - D));
88 }
89
90 if (cmask_i & (cmask_j >> D)) {
91 constraint_bw |= (1 << (7 + D));
92 constraint_fw |= (1 << (7 - D));
93 }
94 }
95
96 /* Use dense arrays after adding 256 elements */
97 nodearray_orr(&l->linear[j], i, constraint_fw, 256, l->node_count);
98 nodearray_orr(&l->linear[i], j, constraint_bw, 256, l->node_count);
99 }
100
101 static bool
102 lcra_test_linear(struct lcra_state *l, unsigned *solutions, unsigned i)
103 {
104 signed constant = solutions[i];
105
106 if (nodearray_is_sparse(&l->linear[i])) {
107 nodearray_sparse_foreach(&l->linear[i], elem) {
108 unsigned j = nodearray_sparse_key(elem);
109 nodearray_value constraint = nodearray_sparse_value(elem);
110
111 if (solutions[j] == ~0)
112 continue;
113
114 signed lhs = constant - solutions[j];
115
116 if (lhs < -7 || lhs > 7)
117 continue;
118
119 if (constraint & (1 << (lhs + 7)))
120 return false;
121 }
122
123 return true;
124 }
125
126 nodearray_value *row = l->linear[i].dense;
127
128 for (unsigned j = 0; j < l->node_count; ++j) {
129 if (solutions[j] == ~0)
130 continue;
131
132 signed lhs = constant - solutions[j];
133
134 if (lhs < -7 || lhs > 7)
135 continue;
136
137 if (row[j] & (1 << (lhs + 7)))
138 return false;
139 }
140
141 return true;
142 }
143
144 static bool
145 lcra_solve(struct lcra_state *l)
146 {
147 for (unsigned step = 0; step < l->node_count; ++step) {
148 if (l->solutions[step] != ~0)
149 continue;
150 if (l->affinity[step] == 0)
151 continue;
152
153 bool succ = false;
154
155 u_foreach_bit64(r, l->affinity[step]) {
156 l->solutions[step] = r;
157
158 if (lcra_test_linear(l, l->solutions, step)) {
159 succ = true;
160 break;
161 }
162 }
163
164 /* Out of registers - prepare to spill */
165 if (!succ) {
166 l->spill_node = step;
167 return false;
168 }
169 }
170
171 return true;
172 }
173
174 /* Register spilling is implemented with a cost-benefit system. Costs are set
175 * by the user. Benefits are calculated from the constraints. */
176
177 static unsigned
178 lcra_count_constraints(struct lcra_state *l, unsigned i)
179 {
180 unsigned count = 0;
181 nodearray *constraints = &l->linear[i];
182
183 if (nodearray_is_sparse(constraints)) {
184 nodearray_sparse_foreach(constraints, elem)
185 count += util_bitcount(nodearray_sparse_value(elem));
186 } else {
187 nodearray_dense_foreach_64(constraints, elem)
188 count += util_bitcount64(*elem);
189 }
190
191 return count;
192 }
193
194 /* Liveness analysis is a backwards-may dataflow analysis pass. Within a block,
195 * we compute live_out from live_in. The intrablock pass is linear-time. It
196 * returns whether progress was made. */
197
198 static void
199 bi_liveness_ins_update_ra(uint8_t *live, bi_instr *ins)
200 {
201 /* live_in[s] = GEN[s] + (live_out[s] - KILL[s]) */
202
203 bi_foreach_dest(ins, d) {
204 live[ins->dest[d].value] &= ~bi_writemask(ins, d);
205 }
206
207 bi_foreach_ssa_src(ins, src) {
208 unsigned count = bi_count_read_registers(ins, src);
209 unsigned rmask = BITFIELD_MASK(count);
210
211 live[ins->src[src].value] |= (rmask << ins->src[src].offset);
212 }
213 }
214
215 static bool
216 liveness_block_update(bi_block *blk, unsigned temp_count)
217 {
218 bool progress = false;
219
220 /* live_out[s] = sum { p in succ[s] } ( live_in[p] ) */
221 bi_foreach_successor(blk, succ) {
222 for (unsigned i = 0; i < temp_count; ++i)
223 blk->live_out[i] |= succ->live_in[i];
224 }
225
226 uint8_t *live = ralloc_array(blk, uint8_t, temp_count);
227 memcpy(live, blk->live_out, temp_count);
228
229 bi_foreach_instr_in_block_rev(blk, ins)
230 bi_liveness_ins_update_ra(live, ins);
231
232 /* To figure out progress, diff live_in */
233
234 for (unsigned i = 0; (i < temp_count) && !progress; ++i)
235 progress |= (blk->live_in[i] != live[i]);
236
237 ralloc_free(blk->live_in);
238 blk->live_in = live;
239
240 return progress;
241 }
242
243 /* Globally, liveness analysis uses a fixed-point algorithm based on a
244 * worklist. We initialize a work list with the exit block. We iterate the work
245 * list to compute live_in from live_out for each block on the work list,
246 * adding the predecessors of the block to the work list if we made progress.
247 */
248
249 static void
250 bi_compute_liveness_ra(bi_context *ctx)
251 {
252 u_worklist worklist;
253 bi_worklist_init(ctx, &worklist);
254
255 bi_foreach_block(ctx, block) {
256 ralloc_free(block->live_in);
257 ralloc_free(block->live_out);
258
259 block->live_in = rzalloc_array(block, uint8_t, ctx->ssa_alloc);
260 block->live_out = rzalloc_array(block, uint8_t, ctx->ssa_alloc);
261
262 bi_worklist_push_tail(&worklist, block);
263 }
264
265 while (!u_worklist_is_empty(&worklist)) {
266 /* Pop off in reverse order since liveness is backwards */
267 bi_block *blk = bi_worklist_pop_tail(&worklist);
268
269 /* Update liveness information. If we made progress, we need to
270 * reprocess the predecessors
271 */
272 if (liveness_block_update(blk, ctx->ssa_alloc)) {
273 bi_foreach_predecessor(blk, pred)
274 bi_worklist_push_head(&worklist, *pred);
275 }
276 }
277
278 u_worklist_fini(&worklist);
279 }
280
281 /* Construct an affinity mask such that the vector with `count` elements does
282 * not intersect any of the registers in the bitset `clobber`. In other words,
283 * an allocated register r needs to satisfy for each i < count: a + i != b.
284 * Equivalently that's a != b - i, so we need a \ne { b - i : i < n }. For the
285 * entire clobber set B, we need a \ne union b \in B { b - i : i < n }, where
286 * that union is the desired clobber set. That may be written equivalently as
287 * the union over i < n of (B - i), where subtraction is defined elementwise
288 * and corresponds to a shift of the entire bitset.
289 *
290 * EVEN_BITS_MASK is an affinity mask for aligned register pairs. Interpreted
291 * as a bit set, it is { x : 0 <= x < 64 if x is even }
292 */
293
294 #define EVEN_BITS_MASK (0x5555555555555555ull)
295
296 static uint64_t
297 bi_make_affinity(uint64_t clobber, unsigned count, bool split_file)
298 {
299 uint64_t clobbered = 0;
300
301 for (unsigned i = 0; i < count; ++i)
302 clobbered |= (clobber >> i);
303
304 /* Don't allocate past the end of the register file */
305 if (count > 1) {
306 unsigned excess = count - 1;
307 uint64_t mask = BITFIELD_MASK(excess);
308 clobbered |= mask << (64 - excess);
309
310 if (split_file)
311 clobbered |= mask << (16 - excess);
312 }
313
314 /* Don't allocate the middle if we split out the middle */
315 if (split_file)
316 clobbered |= BITFIELD64_MASK(32) << 16;
317
318 /* We can use a register iff it's not clobberred */
319 return ~clobbered;
320 }
321
322 static void
323 bi_mark_interference(bi_block *block, struct lcra_state *l, uint8_t *live,
324 uint64_t preload_live, unsigned node_count, bool is_blend,
325 bool split_file, unsigned arch)
326 {
327 bool aligned_sr = arch >= 9;
328 bi_foreach_instr_in_block_rev(block, ins) {
329 /* Mark all registers live after the instruction as
330 * interfering with the destination */
331
332 bi_foreach_dest(ins, d) {
333 unsigned node = ins->dest[d].value;
334
335 /* Don't allocate to anything that's read later as a
336 * preloaded register. The affinity is the intersection
337 * of affinity masks for each write. Since writes have
338 * offsets, but the affinity is for the whole node, we
339 * need to offset the affinity opposite the write
340 * offset, so we shift right. */
341 unsigned count = bi_count_write_registers(ins, d);
342 unsigned offset = ins->dest[d].offset;
343 uint64_t affinity =
344 bi_make_affinity(preload_live, count, split_file) >> offset;
345 /* Valhall needs >= 64-bit staging writes to be pair-aligned */
346 if (aligned_sr && (count >= 2 || offset))
347 affinity &= EVEN_BITS_MASK;
348
349 l->affinity[node] &= affinity;
350
351 for (unsigned i = 0; i < node_count; ++i) {
352 uint8_t r = live[i];
353
354 /* Nodes only interfere if they occupy
355 * /different values/ at the same time
356 * (Boissinot). In particular, sources of
357 * moves do not interfere with their
358 * destinations. This enables a limited form of
359 * coalescing.
360 */
361 if (ins->op == BI_OPCODE_MOV_I32 && bi_is_ssa(ins->src[0]) &&
362 i == ins->src[0].value) {
363
364 r &= ~BITFIELD_BIT(ins->src[0].offset);
365 }
366
367 if (r) {
368 lcra_add_node_interference(l, node, bi_writemask(ins, d), i, r);
369 }
370 }
371
372 unsigned node_first = ins->dest[0].value;
373 if (d == 1) {
374 lcra_add_node_interference(l, node, bi_writemask(ins, 1),
375 node_first, bi_writemask(ins, 0));
376 }
377 }
378
379 /* Valhall needs >= 64-bit reads to be pair-aligned */
380 if (aligned_sr) {
381 bi_foreach_ssa_src(ins, s) {
382 if (bi_count_read_registers(ins, s) >= 2)
383 l->affinity[ins->src[s].value] &= EVEN_BITS_MASK;
384 else if (s < valhall_opcodes[ins->op].nr_srcs &&
385 va_src_info(ins->op, s).size > VA_SIZE_32)
386 l->affinity[ins->src[s].value] &= EVEN_BITS_MASK;
387 }
388 }
389
390 if (!is_blend && ins->op == BI_OPCODE_BLEND) {
391 /* Blend shaders might clobber r0-r15, blend link reg. */
392 uint64_t clobber =
393 BITFIELD64_MASK(16) |
394 BITFIELD64_BIT(bi_preload_reg(BI_PRELOAD_BLEND_LINK, arch));
395
396 for (unsigned i = 0; i < node_count; ++i) {
397 if (live[i])
398 l->affinity[i] &= ~clobber;
399 }
400 }
401
402 /* Update live_in */
403 preload_live = bi_postra_liveness_ins(preload_live, ins);
404 bi_liveness_ins_update_ra(live, ins);
405 }
406
407 block->reg_live_in = preload_live;
408 }
409
410 static void
411 bi_compute_interference(bi_context *ctx, struct lcra_state *l, bool full_regs)
412 {
413 bi_compute_liveness_ra(ctx);
414 bi_postra_liveness(ctx);
415
416 bi_foreach_block_rev(ctx, blk) {
417 uint8_t *live = mem_dup(blk->live_out, ctx->ssa_alloc);
418
419 bi_mark_interference(blk, l, live, blk->reg_live_out, ctx->ssa_alloc,
420 ctx->inputs->is_blend, !full_regs, ctx->arch);
421
422 free(live);
423 }
424 }
425
426 static struct lcra_state *
427 bi_allocate_registers(bi_context *ctx, bool *success, bool full_regs)
428 {
429 struct lcra_state *l = lcra_alloc_equations(ctx->ssa_alloc);
430
431 /* Blend shaders are restricted to R0-R15. Other shaders at full
432 * occupancy also can access R48-R63. At half occupancy they can access
433 * the whole file. */
434
435 uint64_t default_affinity =
436 ctx->inputs->is_blend ? BITFIELD64_MASK(16)
437 : full_regs ? BITFIELD64_MASK(64)
438 : (BITFIELD64_MASK(16) | (BITFIELD64_MASK(16) << 48));
439
440 /* To test spilling, mimic a small register file */
441 if (bifrost_debug & BIFROST_DBG_SPILL && !ctx->inputs->is_blend && (bifrost_debug & BIFROST_DBG_NOSSARA))
442 default_affinity &= BITFIELD64_MASK(48) << 8;
443
444 bi_foreach_instr_global(ctx, ins) {
445 bi_foreach_dest(ins, d)
446 l->affinity[ins->dest[d].value] = default_affinity;
447
448 /* Blend shaders expect the src colour to be in blend_src0_c0
449 * through c3 */
450 if (ins->op == BI_OPCODE_BLEND && !ctx->inputs->is_blend) {
451 assert(bi_is_ssa(ins->src[0]));
452 l->solutions[ins->src[0].value] =
453 bi_preload_reg(BI_PRELOAD_BLEND_SRC0_C0, ctx->arch);
454
455 /* Dual source blend input in blend_src1_c0 through c3 */
456 if (bi_is_ssa(ins->src[4]))
457 l->solutions[ins->src[4].value] =
458 bi_preload_reg(BI_PRELOAD_BLEND_SRC1_C0, ctx->arch);
459
460 /* Writes to blend link */
461 if (!bi_is_null(ins->dest[0]))
462 l->solutions[ins->dest[0].value] =
463 bi_preload_reg(BI_PRELOAD_BLEND_LINK, ctx->arch);
464 }
465
466 /* Coverage mask writes stay in the cumulative coverage reg */
467 if ((ins->op == BI_OPCODE_ATEST || ins->op == BI_OPCODE_ZS_EMIT) &&
468 !bi_is_null(ins->dest[0])) {
469 l->solutions[ins->dest[0].value] =
470 bi_preload_reg(BI_PRELOAD_CUMULATIVE_COVERAGE, ctx->arch);
471 }
472
473 /* Experimentally, it seems coverage masks inputs to ATEST must
474 * be in the cumulative coverage reg. Otherwise coverage mask
475 * writes do not work with early-ZS with pixel-frequency-shading
476 * (this combination of settings is legal if depth/stencil
477 * writes are disabled). Allowing a FAU index also seems to
478 * work on Valhall, at least.
479 */
480 if (ins->op == BI_OPCODE_ATEST) {
481 assert(bi_is_ssa(ins->src[0]) || ins->src[0].type == BI_INDEX_FAU);
482 if (bi_is_ssa(ins->src[0]))
483 l->solutions[ins->src[0].value] =
484 bi_preload_reg(BI_PRELOAD_CUMULATIVE_COVERAGE, ctx->arch);
485 }
486 }
487
488 bi_compute_interference(ctx, l, full_regs);
489
490 /* Coalesce register moves if we're allowed. We need to be careful due
491 * to the restricted affinity induced by the blend shader ABI.
492 */
493 bi_foreach_instr_global(ctx, I) {
494 if (I->op != BI_OPCODE_MOV_I32)
495 continue;
496 if (I->src[0].type != BI_INDEX_REGISTER)
497 continue;
498
499 unsigned reg = I->src[0].value;
500 unsigned node = I->dest[0].value;
501
502 if (l->solutions[node] != ~0)
503 continue;
504
505 uint64_t affinity = l->affinity[node];
506
507 if (ctx->inputs->is_blend) {
508 /* We're allowed to coalesce the moves to these */
509 affinity |=
510 BITFIELD64_BIT(bi_preload_reg(BI_PRELOAD_BLEND_LINK, ctx->arch));
511 affinity |= BITFIELD64_BIT(
512 bi_preload_reg(BI_PRELOAD_CUMULATIVE_COVERAGE, ctx->arch));
513 }
514
515 /* Try to coalesce */
516 if (affinity & BITFIELD64_BIT(reg)) {
517 l->solutions[node] = reg;
518
519 if (!lcra_test_linear(l, l->solutions, node))
520 l->solutions[node] = ~0;
521 }
522 }
523
524 *success = lcra_solve(l);
525
526 return l;
527 }
528
529 static bi_index
530 bi_reg_from_index(bi_context *ctx, struct lcra_state *l, bi_index index)
531 {
532 /* Offsets can only be applied when we register allocated an index, or
533 * alternatively for FAU's encoding */
534
535 ASSERTED bool is_offset = (index.offset > 0) && (index.type != BI_INDEX_FAU);
536
537 /* Did we run RA for this index at all */
538 if (!bi_is_ssa(index)) {
539 assert(!is_offset);
540 return index;
541 }
542
543 /* LCRA didn't bother solving this index (how lazy!) */
544 signed solution = l->solutions[index.value];
545 if (solution < 0) {
546 assert(0 && "no solution for index");
547 return index;
548 }
549
550 /* todo: do we want to compose with the subword swizzle? */
551 bi_index new_index = bi_register(solution + index.offset);
552 new_index.swizzle = index.swizzle;
553 new_index.abs = index.abs;
554 new_index.neg = index.neg;
555 return new_index;
556 }
557
558 /* Dual texture instructions write to two sets of staging registers, modeled as
559 * two destinations in the IR. The first set is communicated with the usual
560 * staging register mechanism. The second set is encoded in the texture
561 * operation descriptor. This is quite unusual, and requires the following late
562 * fixup.
563 */
564 static void
565 bi_fixup_dual_tex_register(bi_instr *I)
566 {
567 assert(I->dest[1].type == BI_INDEX_REGISTER);
568 assert(I->src[3].type == BI_INDEX_CONSTANT);
569
570 struct bifrost_dual_texture_operation desc = {
571 .secondary_register = I->dest[1].value,
572 };
573
574 I->src[3].value |= bi_dual_tex_as_u32(desc);
575 }
576
577 static void
578 bi_install_registers(bi_context *ctx, struct lcra_state *l)
579 {
580 bi_foreach_instr_global(ctx, ins) {
581 bi_foreach_dest(ins, d)
582 ins->dest[d] = bi_reg_from_index(ctx, l, ins->dest[d]);
583
584 bi_foreach_src(ins, s)
585 ins->src[s] = bi_reg_from_index(ctx, l, ins->src[s]);
586
587 if (ins->op == BI_OPCODE_TEXC_DUAL)
588 bi_fixup_dual_tex_register(ins);
589 }
590 }
591
592 static void
593 bi_rewrite_index_src_single(bi_instr *ins, bi_index old, bi_index new)
594 {
595 bi_foreach_src(ins, i) {
596 if (bi_is_equiv(ins->src[i], old)) {
597 ins->src[i].type = new.type;
598 ins->src[i].value = new.value;
599 }
600 }
601 }
602
603 /* If register allocation fails, find the best spill node */
604
605 static signed
606 bi_choose_spill_node(bi_context *ctx, struct lcra_state *l)
607 {
608 /* Pick a node satisfying bi_spill_register's preconditions */
609 BITSET_WORD *no_spill = BITSET_CALLOC(l->node_count);
610
611 bi_foreach_instr_global(ctx, ins) {
612 bi_foreach_dest(ins, d) {
613 /* Don't allow spilling coverage mask writes because the
614 * register preload logic assumes it will stay in the
615 * cumulative coverage reg. This could be optimized.
616 */
617 if (ins->no_spill || ins->op == BI_OPCODE_ATEST ||
618 ins->op == BI_OPCODE_ZS_EMIT ||
619 (ins->op == BI_OPCODE_MOV_I32 &&
620 ins->src[0].type == BI_INDEX_REGISTER &&
621 ins->src[0].value ==
622 bi_preload_reg(BI_PRELOAD_CUMULATIVE_COVERAGE, ctx->arch))) {
623 BITSET_SET(no_spill, ins->dest[d].value);
624 }
625 }
626 }
627
628 unsigned best_benefit = 0;
629 signed best_node = -1;
630
631 if (nodearray_is_sparse(&l->linear[l->spill_node])) {
632 nodearray_sparse_foreach(&l->linear[l->spill_node], elem) {
633 unsigned i = nodearray_sparse_key(elem);
634 unsigned constraint = nodearray_sparse_value(elem);
635
636 /* Only spill nodes that interfere with the node failing
637 * register allocation. It's pointless to spill anything else */
638 if (!constraint)
639 continue;
640
641 if (BITSET_TEST(no_spill, i))
642 continue;
643
644 unsigned benefit = lcra_count_constraints(l, i);
645
646 if (benefit > best_benefit) {
647 best_benefit = benefit;
648 best_node = i;
649 }
650 }
651 } else {
652 nodearray_value *row = l->linear[l->spill_node].dense;
653
654 for (unsigned i = 0; i < l->node_count; ++i) {
655 /* Only spill nodes that interfere with the node failing
656 * register allocation. It's pointless to spill anything else */
657 if (!row[i])
658 continue;
659
660 if (BITSET_TEST(no_spill, i))
661 continue;
662
663 unsigned benefit = lcra_count_constraints(l, i);
664
665 if (benefit > best_benefit) {
666 best_benefit = benefit;
667 best_node = i;
668 }
669 }
670 }
671
672 free(no_spill);
673 return best_node;
674 }
675
676 static unsigned
677 bi_count_read_index(bi_instr *I, bi_index index)
678 {
679 unsigned max = 0;
680
681 bi_foreach_src(I, s) {
682 if (bi_is_equiv(I->src[s], index)) {
683 unsigned count = bi_count_read_registers(I, s);
684 max = MAX2(max, count + I->src[s].offset);
685 }
686 }
687
688 return max;
689 }
690
691 /*
692 * Wrappers to emit loads/stores to thread-local storage in an appropriate way
693 * for the target, so the spill/fill code becomes architecture-independent.
694 */
695
696 static bi_index
697 bi_tls_ptr(bool hi)
698 {
699 return bi_fau(BIR_FAU_TLS_PTR, hi);
700 }
701
702 bi_instr *
703 bi_load_tl(bi_builder *b, unsigned bits, bi_index dst, unsigned offset)
704 {
705 if (b->shader->arch >= 9) {
706 assert(offset < 0x8000); /* valhall has 16 bit signed offset */
707 return bi_load_to(b, bits, dst, bi_tls_ptr(false), bi_tls_ptr(true),
708 BI_SEG_TL, offset);
709 } else {
710 return bi_load_to(b, bits, dst, bi_imm_u32(offset), bi_zero(), BI_SEG_TL,
711 0);
712 }
713 }
714
715 void
716 bi_store_tl(bi_builder *b, unsigned bits, bi_index src, unsigned offset)
717 {
718 if (b->shader->arch >= 9) {
719 assert(offset < 0x8000); /* valhall has 16 bit signed offset */
720 bi_store(b, bits, src, bi_tls_ptr(false), bi_tls_ptr(true), BI_SEG_TL,
721 offset);
722 } else {
723 bi_store(b, bits, src, bi_imm_u32(offset), bi_zero(), BI_SEG_TL, 0);
724 }
725 }
726
727 static void
728 bi_compute_reg_alignment(bi_context *ctx)
729 {
730 unsigned idx;
731 unsigned count;
732 ctx->reg_alignment = rzalloc_array(ctx, uint8_t, ctx->ssa_alloc);
733 bi_foreach_instr_global(ctx, I) {
734 bi_foreach_ssa_dest(I, d) {
735 idx = I->dest[d].value;
736 count = bi_count_write_registers(I, d);
737 if (count == 3) count = 4;
738 assert(idx < ctx->ssa_alloc);
739 ctx->reg_alignment[idx] = MAX2(count*4, ctx->reg_alignment[idx]);
740 }
741 bi_foreach_ssa_src(I, s) {
742 idx = I->src[s].value;
743 count = bi_count_read_index(I, I->src[s]);
744 if (count == 3) count = 4;
745 assert(idx < ctx->ssa_alloc);
746 ctx->reg_alignment[idx] = MAX2(count*4, ctx->reg_alignment[idx]);
747 }
748 }
749 }
750
751 /* Once we've chosen a spill node, spill it and return new (aligned) offset */
752
753 static unsigned
754 bi_spill_register(bi_context *ctx, bi_index index, uint32_t offset,
755 bi_index spill_point)
756 {
757 bi_builder b = {.shader = ctx};
758 unsigned alignment = 4;
759 unsigned channels = 0;
760
761 /* first figure out the alignment we will need, based on the
762 * maximum count we see
763 */
764 if (ctx->arch >= 9) {
765 if (!ctx->reg_alignment)
766 bi_compute_reg_alignment(ctx);
767 assert(index.value < ctx->ssa_alloc);
768 alignment = ctx->reg_alignment[index.value];
769 }
770 offset = ALIGN_POT(offset, alignment);
771
772 /* Spill after every store, fill before every load */
773 bi_foreach_block(ctx, block) {
774 bool fill = true;
775 bool found_spill_point = false;
776 bi_foreach_instr_in_block_safe(block, I) {
777 bi_foreach_dest(I, d) {
778 if (bi_is_equiv(I->dest[d], spill_point)) {
779 found_spill_point = true;
780 fill = true;
781 }
782 if (!bi_is_equiv(I->dest[d], index))
783 continue;
784
785 unsigned count = bi_count_write_registers(I, d);
786 unsigned extra = I->dest[d].offset;
787
788 channels = MAX2(channels, extra + count);
789 I->no_spill = true;
790
791 if (channels == extra + count) {
792 b.cursor = bi_after_instr(I);
793 bi_store_tl(&b, channels * 32, index, offset);
794
795 ctx->spills++;
796 /* Don't disable filling if spill_point is before index. */
797 fill = found_spill_point;
798 }
799 }
800
801 if (bi_has_arg(I, index) && fill) {
802 b.cursor = bi_before_instr(I);
803 bi_index tmp = bi_temp(ctx);
804
805 unsigned bits = bi_count_read_index(I, index) * 32;
806 bi_rewrite_index_src_single(I, index, tmp);
807
808 bi_instr *ld = bi_load_tl(&b, bits, tmp, offset);
809 ld->no_spill = true;
810 ctx->fills++;
811 }
812 }
813 }
814
815 return offset + (channels * 4);
816 }
817
818 /*
819 * For transition, lower collects and splits before RA, rather than after RA.
820 * LCRA knows how to deal with offsets (broken SSA), but not how to coalesce
821 * these vector moves.
822 */
823 static void
824 bi_lower_vector(bi_context *ctx, unsigned first_reg)
825 {
826 bi_index *remap = calloc(ctx->ssa_alloc, sizeof(bi_index));
827
828 bi_foreach_instr_global_safe(ctx, I) {
829 bi_builder b = bi_init_builder(ctx, bi_after_instr(I));
830
831 if (I->op == BI_OPCODE_SPLIT_I32) {
832 bi_index src = I->src[0];
833 assert(src.offset == 0);
834
835 bi_foreach_dest(I, i) {
836 src.offset = i;
837 bi_mov_i32_to(&b, I->dest[i], src);
838
839 if (I->dest[i].value < first_reg)
840 remap[I->dest[i].value] = src;
841 }
842
843 bi_remove_instruction(I);
844 } else if (I->op == BI_OPCODE_COLLECT_I32) {
845 bi_index dest = I->dest[0];
846 assert(dest.offset == 0);
847 assert(((dest.value < first_reg) || I->nr_srcs == 1) &&
848 "nir_lower_phis_to_scalar");
849
850 bi_foreach_src(I, i) {
851 if (bi_is_null(I->src[i]))
852 continue;
853
854 dest.offset = i;
855 bi_mov_i32_to(&b, dest, I->src[i]);
856 }
857
858 bi_remove_instruction(I);
859 }
860 }
861
862 bi_foreach_instr_global(ctx, I) {
863 bi_foreach_ssa_src(I, s) {
864 if (I->src[s].value < first_reg && !bi_is_null(remap[I->src[s].value]))
865 bi_replace_src(I, s, remap[I->src[s].value]);
866 }
867 }
868
869 free(remap);
870
871 /* After generating a pile of moves, clean up */
872 bi_compute_liveness_ra(ctx);
873
874 bi_foreach_block_rev(ctx, block) {
875 uint8_t *live = rzalloc_array(block, uint8_t, ctx->ssa_alloc);
876
877 bi_foreach_successor(block, succ) {
878 for (unsigned i = 0; i < ctx->ssa_alloc; ++i)
879 live[i] |= succ->live_in[i];
880 }
881
882 bi_foreach_instr_in_block_safe_rev(block, ins) {
883 bool all_null = true;
884
885 bi_foreach_dest(ins, d) {
886 if (live[ins->dest[d].value] & bi_writemask(ins, d))
887 all_null = false;
888 }
889
890 if (all_null && !bi_side_effects(ins))
891 bi_remove_instruction(ins);
892 else
893 bi_liveness_ins_update_ra(live, ins);
894 }
895
896 ralloc_free(block->live_in);
897 block->live_in = live;
898 }
899 }
900
901 /*
902 * Check if the instruction requires a "tied" operand. Such instructions MUST
903 * allocate their source and destination to the same register. This is a
904 * constraint on RA, and may require extra moves.
905 *
906 * In particular, this is the case for Bifrost instructions that both read and
907 * write with the staging register mechanism.
908 */
909 static bool
910 bi_is_tied(const bi_instr *I)
911 {
912 return (I->op == BI_OPCODE_TEXC || I->op == BI_OPCODE_TEXC_DUAL ||
913 I->op == BI_OPCODE_ATOM_RETURN_I32 || I->op == BI_OPCODE_AXCHG_I32 ||
914 I->op == BI_OPCODE_ACMPXCHG_I32 || I->op == BI_OPCODE_AXCHG_I64 ||
915 I->op == BI_OPCODE_ACMPXCHG_I64) &&
916 !bi_is_null(I->src[0]);
917 }
918
919 /*
920 * For transition, coalesce tied operands together, as LCRA knows how to handle
921 * non-SSA operands but doesn't know about tied operands.
922 *
923 * This breaks the SSA form of the program, but that doesn't matter for LCRA.
924 */
925 static void
926 bi_coalesce_tied(bi_context *ctx)
927 {
928 if (ctx->reg_alignment) {
929 ralloc_free(ctx->reg_alignment);
930 ctx->reg_alignment = NULL;
931 }
932 bi_foreach_instr_global(ctx, I) {
933 if (!bi_is_tied(I))
934 continue;
935
936 bi_builder b = bi_init_builder(ctx, bi_before_instr(I));
937 unsigned n = bi_count_read_registers(I, 0);
938
939 bi_index dst = I->dest[0], src = I->src[0];
940 assert(dst.offset == 0);
941 for (unsigned i = 0; i < n; ++i) {
942 bi_mov_i32_to(&b, dst, src);
943 dst.offset++;
944 src.offset++;
945 }
946
947 bi_replace_src(I, 0, I->dest[0]);
948 }
949 }
950
951 static unsigned
952 find_or_allocate_temp(unsigned *map, unsigned value, unsigned *alloc)
953 {
954 if (!map[value])
955 map[value] = ++(*alloc);
956
957 assert(map[value]);
958 return map[value] - 1;
959 }
960
961 /* Reassigns numbering to get rid of gaps in the indices and to prioritize
962 * smaller register classes */
963
964 static void
965 squeeze_index(bi_context *ctx)
966 {
967 unsigned *map = rzalloc_array(ctx, unsigned, ctx->ssa_alloc);
968 ctx->ssa_alloc = 0;
969
970 bi_foreach_instr_global(ctx, I) {
971 bi_foreach_dest(I, d)
972 I->dest[d].value =
973 find_or_allocate_temp(map, I->dest[d].value, &ctx->ssa_alloc);
974
975 bi_foreach_ssa_src(I, s)
976 I->src[s].value =
977 find_or_allocate_temp(map, I->src[s].value, &ctx->ssa_alloc);
978 }
979
980 ralloc_free(map);
981 }
982
983 /*
984 * Brainless out-of-SSA pass. The eventual goal is to go out-of-SSA after RA and
985 * coalesce implicitly with biased colouring in a tree scan allocator. For now,
986 * this should be good enough for LCRA.
987 */
988 static unsigned
989 bi_out_of_ssa(bi_context *ctx)
990 {
991 bi_index zero = bi_fau(BIR_FAU_IMMEDIATE | 0, false);
992 unsigned first_reg = ctx->ssa_alloc;
993 bool allow_propagate;
994
995 /* Trivially lower phis */
996 bi_foreach_block(ctx, block) {
997 bi_foreach_instr_in_block_safe(block, I) {
998 if (I->op != BI_OPCODE_PHI)
999 break;
1000
1001 /* Assign a register for the phi */
1002 bi_index reg = bi_temp(ctx);
1003 assert(reg.value >= first_reg);
1004
1005 /* Lower to a move in each predecessor. The destinations
1006 * cannot interfere so these can be sequentialized
1007 * in arbitrary order.
1008 */
1009 bi_foreach_predecessor(block, pred) {
1010 bi_builder b = bi_init_builder(ctx, bi_after_block_logical(*pred));
1011 unsigned i = bi_predecessor_index(block, *pred);
1012
1013 assert(!I->src[i].abs);
1014 assert(!I->src[i].neg);
1015 assert(I->src[i].swizzle == BI_SWIZZLE_H01);
1016
1017 if (I->src[i].memory)
1018 /* spilled register, need to un-spill */
1019 bi_load_tl(&b, 32, reg, I->src[i].value);
1020 else if (ctx->arch >= 9 && I->src[i].type == BI_INDEX_CONSTANT)
1021 /* MOV of immediate needs lowering on Valhall */
1022 bi_iadd_imm_i32_to(&b, reg, zero, I->src[i].value);
1023 else
1024 bi_mov_i32_to(&b, reg, I->src[i]);
1025 }
1026
1027 /* Replace the phi with a move */
1028 allow_propagate = true;
1029 bi_builder b = bi_init_builder(ctx, bi_before_instr(I));
1030 if (I->dest[0].memory) {
1031 /* dest was spilled to memory */
1032 bi_store_tl(&b, 32, reg, I->dest[0].value);
1033 allow_propagate = false;
1034 } else if (ctx->arch >= 9 && reg.type == BI_INDEX_CONSTANT)
1035 /* MOV of immediate needs lowering on Valhall */
1036 bi_iadd_imm_i32_to(&b, I->dest[0], zero, reg.value);
1037 else
1038 bi_mov_i32_to(&b, I->dest[0], reg);
1039 bi_remove_instruction(I);
1040
1041 /* Propagate that move within the block. The destination
1042 * is SSA and the source is not written in this block,
1043 * so this is legal. The move itself will be DCE'd if
1044 * possible in the next pass.
1045 */
1046 bi_foreach_instr_in_block_rev(block, prop) {
1047 if (prop->op == BI_OPCODE_PHI || !allow_propagate)
1048 break;
1049
1050 bi_foreach_src(prop, s) {
1051 if (bi_is_equiv(prop->src[s], I->dest[0])) {
1052 bi_replace_src(prop, s, reg);
1053 }
1054 }
1055 }
1056 }
1057 }
1058
1059 /* Try to locally propagate the moves we created. We need to be extra
1060 * careful because we're not in SSA at this point, as such this
1061 * algorithm is quadratic. This will go away when we go out of SSA after
1062 * RA.
1063 */
1064 BITSET_WORD *used = BITSET_CALLOC(ctx->ssa_alloc);
1065 BITSET_WORD *multiple_uses = BITSET_CALLOC(ctx->ssa_alloc);
1066
1067 bi_foreach_instr_global(ctx, I) {
1068 bi_foreach_ssa_src(I, s) {
1069 if (BITSET_TEST(used, I->src[s].value))
1070 BITSET_SET(multiple_uses, I->src[s].value);
1071 else
1072 BITSET_SET(used, I->src[s].value);
1073 }
1074 }
1075
1076 bi_foreach_block(ctx, block) {
1077 bi_foreach_instr_in_block_safe_rev(block, mov) {
1078 /* Match "reg = ssa" */
1079 if (mov->op != BI_OPCODE_MOV_I32)
1080 continue;
1081 if (mov->dest[0].type != BI_INDEX_NORMAL)
1082 continue;
1083 if (mov->dest[0].value < first_reg)
1084 continue;
1085 if (!bi_is_ssa(mov->src[0]))
1086 continue;
1087 if (mov->src[0].value >= first_reg)
1088 continue;
1089 if (BITSET_TEST(multiple_uses, mov->src[0].value))
1090 continue;
1091
1092 bool found = false;
1093
1094 /* Look locally for the write of the SSA */
1095 bi_foreach_instr_in_block_rev(block, I) {
1096 bool bail = false;
1097
1098 bi_foreach_src(I, s) {
1099 /* Bail: write-after-read */
1100 if (bi_is_equiv(I->src[s], mov->dest[0]))
1101 bail = true;
1102 }
1103
1104 if (bail)
1105 break;
1106
1107 bi_foreach_dest(I, d) {
1108 /* Bail: write-after-write */
1109 if (bi_is_equiv(I->dest[d], mov->dest[0]))
1110 break;
1111
1112 if (!bi_is_equiv(I->dest[d], mov->src[0]))
1113 continue;
1114
1115 /* We found it, replace */
1116 I->dest[d] = bi_replace_index(I->dest[d], mov->dest[0]);
1117 found = true;
1118 break;
1119 }
1120
1121 if (found)
1122 break;
1123 }
1124
1125 if (found)
1126 bi_remove_instruction(mov);
1127 }
1128 }
1129
1130 free(used);
1131 free(multiple_uses);
1132 return first_reg;
1133 }
1134
1135 static bool
1136 op_is_load_store(enum bi_opcode op)
1137 {
1138 switch (op) {
1139 case BI_OPCODE_STORE_I8:
1140 case BI_OPCODE_STORE_I16:
1141 case BI_OPCODE_STORE_I24:
1142 case BI_OPCODE_STORE_I32:
1143 case BI_OPCODE_STORE_I48:
1144 case BI_OPCODE_STORE_I64:
1145 case BI_OPCODE_STORE_I96:
1146 case BI_OPCODE_STORE_I128:
1147 return true;
1148 case BI_OPCODE_LOAD_I8:
1149 case BI_OPCODE_LOAD_I16:
1150 case BI_OPCODE_LOAD_I24:
1151 case BI_OPCODE_LOAD_I32:
1152 case BI_OPCODE_LOAD_I48:
1153 case BI_OPCODE_LOAD_I64:
1154 case BI_OPCODE_LOAD_I96:
1155 case BI_OPCODE_LOAD_I128:
1156 return true;
1157 default:
1158 return false;
1159 }
1160 }
1161
1162 static uint64_t
1163 compute_spill_cost(bi_context *ctx)
1164 {
1165 void *mctx = ralloc_context(NULL);
1166
1167 /* Required for finding blocks belonging to loops. */
1168 bi_calc_dominance(ctx);
1169
1170 /* The cost of a spill/fill is just 10*block_depth for now. */
1171
1172 uint32_t *block_depth = rzalloc_array(mctx, uint32_t, ctx->num_blocks);
1173 BITSET_WORD *loop_block = BITSET_RZALLOC(mctx, ctx->num_blocks);
1174
1175 bi_foreach_block(ctx, block) {
1176 if (!block->loop_header)
1177 continue;
1178
1179 bi_find_loop_blocks(ctx, block, loop_block);
1180
1181 for (uint32_t b = 0; b < ctx->num_blocks; ++b) {
1182 if (BITSET_SET(loop_block, b))
1183 block_depth[b] += 1;
1184 }
1185 }
1186
1187 uint64_t cost = 0;
1188 bi_foreach_block(ctx, block) {
1189 bi_foreach_instr_in_block(block, I) {
1190 if (op_is_load_store(I->op) && I->seg == BI_SEG_TL)
1191 cost += 10 * (block_depth[block->index] + 1);
1192 }
1193 }
1194
1195 ralloc_free(mctx);
1196
1197 return cost;
1198 }
1199
1200 void
1201 bi_register_allocate(bi_context *ctx)
1202 {
1203 struct lcra_state *l = NULL;
1204 bool success = false;
1205
1206 unsigned iter_count = 0;
1207 unsigned max_iters = 2000;
1208 /* Number of bytes of memory we've spilled into */
1209 unsigned spill_count = ctx->info.tls_size;
1210
1211 if (ctx->arch >= 9)
1212 va_lower_split_64bit(ctx);
1213
1214 /* get estimate of register demand (must be done in SSA form)
1215 * and do a preliminary spill; this doesn't have to be perfect,
1216 * since register allocation can spill too, but RA is really slow
1217 * so the closer we get to having enough registers free, the better
1218 */
1219 if (!(bifrost_debug & BIFROST_DBG_NOSSARA)) {
1220 unsigned regs_to_use =
1221 ((bifrost_debug & BIFROST_DBG_SPILL) && !ctx->inputs->is_blend) ? 16 : BI_MAX_REGS;
1222 bool verbose = bifrost_debug & BIFROST_DBG_VERBOSE;
1223
1224 bi_compute_liveness_ssa(ctx);
1225 if (verbose) {
1226 bi_print_shader(ctx, stderr);
1227 }
1228 unsigned register_demand = bi_calc_register_demand(ctx);
1229 if (register_demand > regs_to_use) {
1230 /* spill registers if we can */
1231 if (ctx->inputs->is_blend)
1232 UNREACHABLE("Blend shaders may not spill");
1233
1234 bi_spill_ssa(ctx, regs_to_use);
1235 spill_count += bi_lower_spill(ctx, spill_count);
1236
1237 /* By default, we use packed TLS addressing on Valhall.
1238 * We cannot cross 16 byte boundaries with packed TLS
1239 * addressing. Align to ensure this doesn't happen. This
1240 * could be optimized a bit.
1241 */
1242 if (ctx->arch >= 9)
1243 spill_count = ALIGN_POT(spill_count, 16);
1244 if (verbose) {
1245 fprintf(stderr, "\nspill_registers=%d\n", spill_count);
1246 bi_print_shader(ctx, stderr);
1247 }
1248 }
1249 }
1250
1251 /* Lower tied operands. SSA is broken from here on. */
1252 unsigned first_reg = bi_out_of_ssa(ctx);
1253 bi_lower_vector(ctx, first_reg);
1254 bi_coalesce_tied(ctx);
1255 squeeze_index(ctx);
1256
1257 /* Try with reduced register pressure to improve thread count */
1258 if (ctx->arch >= 7) {
1259 l = bi_allocate_registers(ctx, &success, false);
1260
1261 if (success) {
1262 ctx->info.work_reg_count = 32;
1263 } else {
1264 lcra_free(l);
1265 l = NULL;
1266 }
1267 }
1268
1269 /* Otherwise, use the register file and spill until we succeed */
1270 while (!success && ((iter_count++) < max_iters)) {
1271 l = bi_allocate_registers(ctx, &success, true);
1272
1273 if (success) {
1274 ctx->info.work_reg_count = BI_MAX_REGS;
1275 } else {
1276 signed spill_node = bi_choose_spill_node(ctx, l);
1277
1278 if (spill_node == -1)
1279 UNREACHABLE("Failed to choose spill node\n");
1280
1281 if (ctx->inputs->is_blend)
1282 UNREACHABLE("Blend shaders may not spill");
1283
1284 spill_count =
1285 bi_spill_register(ctx, bi_get_index(spill_node), spill_count,
1286 bi_get_index(l->spill_node));
1287
1288 lcra_free(l);
1289 l = NULL;
1290 /* In case the spill affected an instruction with tied
1291 * operands, we need to fix up.
1292 */
1293 bi_coalesce_tied(ctx);
1294 }
1295 }
1296
1297 ctx->spill_cost = compute_spill_cost(ctx);
1298
1299 assert(success);
1300 assert(l != NULL);
1301
1302 if (ctx->arch >= 9)
1303 spill_count = ALIGN_POT(spill_count, 16);
1304 ctx->info.tls_size = spill_count;
1305 bi_install_registers(ctx, l);
1306
1307 lcra_free(l);
1308 }