pan/midgard: Represent ld/st offset unpacked
[mesa.git] / src / panfrost / midgard / midgard_schedule.c
1 /*
2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24 #include "compiler.h"
25 #include "midgard_ops.h"
26 #include "util/u_memory.h"
27
28 /* Scheduling for Midgard is complicated, to say the least. ALU instructions
29 * must be grouped into VLIW bundles according to following model:
30 *
31 * [VMUL] [SADD]
32 * [VADD] [SMUL] [VLUT]
33 *
34 * A given instruction can execute on some subset of the units (or a few can
35 * execute on all). Instructions can be either vector or scalar; only scalar
36 * instructions can execute on SADD/SMUL units. Units on a given line execute
37 * in parallel. Subsequent lines execute separately and can pass results
38 * directly via pipeline registers r24/r25, bypassing the register file.
39 *
40 * A bundle can optionally have 128-bits of embedded constants, shared across
41 * all of the instructions within a bundle.
42 *
43 * Instructions consuming conditionals (branches and conditional selects)
44 * require their condition to be written into the conditional register (r31)
45 * within the same bundle they are consumed.
46 *
47 * Fragment writeout requires its argument to be written in full within the
48 * same bundle as the branch, with no hanging dependencies.
49 *
50 * Load/store instructions are also in bundles of simply two instructions, and
51 * texture instructions have no bundling.
52 *
53 * -------------------------------------------------------------------------
54 *
55 */
56
57 /* We create the dependency graph with per-byte granularity */
58
59 #define BYTE_COUNT 16
60
61 static void
62 add_dependency(struct util_dynarray *table, unsigned index, uint16_t mask, midgard_instruction **instructions, unsigned child)
63 {
64 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
65 if (!(mask & (1 << i)))
66 continue;
67
68 struct util_dynarray *parents = &table[(BYTE_COUNT * index) + i];
69
70 util_dynarray_foreach(parents, unsigned, parent) {
71 BITSET_WORD *dependents = instructions[*parent]->dependents;
72
73 /* Already have the dependency */
74 if (BITSET_TEST(dependents, child))
75 continue;
76
77 BITSET_SET(dependents, child);
78 instructions[child]->nr_dependencies++;
79 }
80 }
81 }
82
83 static void
84 mark_access(struct util_dynarray *table, unsigned index, uint16_t mask, unsigned parent)
85 {
86 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
87 if (!(mask & (1 << i)))
88 continue;
89
90 util_dynarray_append(&table[(BYTE_COUNT * index) + i], unsigned, parent);
91 }
92 }
93
94 static void
95 mir_create_dependency_graph(midgard_instruction **instructions, unsigned count, unsigned node_count)
96 {
97 size_t sz = node_count * BYTE_COUNT;
98
99 struct util_dynarray *last_read = calloc(sizeof(struct util_dynarray), sz);
100 struct util_dynarray *last_write = calloc(sizeof(struct util_dynarray), sz);
101
102 for (unsigned i = 0; i < sz; ++i) {
103 util_dynarray_init(&last_read[i], NULL);
104 util_dynarray_init(&last_write[i], NULL);
105 }
106
107 /* Initialize dependency graph */
108 for (unsigned i = 0; i < count; ++i) {
109 instructions[i]->dependents =
110 calloc(BITSET_WORDS(count), sizeof(BITSET_WORD));
111
112 instructions[i]->nr_dependencies = 0;
113 }
114
115 /* Populate dependency graph */
116 for (signed i = count - 1; i >= 0; --i) {
117 if (instructions[i]->compact_branch)
118 continue;
119
120 unsigned dest = instructions[i]->dest;
121 unsigned mask = mir_bytemask(instructions[i]);
122
123 mir_foreach_src((*instructions), s) {
124 unsigned src = instructions[i]->src[s];
125
126 if (src < node_count) {
127 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
128 add_dependency(last_write, src, readmask, instructions, i);
129 }
130 }
131
132 if (dest < node_count) {
133 add_dependency(last_read, dest, mask, instructions, i);
134 add_dependency(last_write, dest, mask, instructions, i);
135 mark_access(last_write, dest, mask, i);
136 }
137
138 mir_foreach_src((*instructions), s) {
139 unsigned src = instructions[i]->src[s];
140
141 if (src < node_count) {
142 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
143 mark_access(last_read, src, readmask, i);
144 }
145 }
146 }
147
148 /* If there is a branch, all instructions depend on it, as interblock
149 * execution must be purely in-order */
150
151 if (instructions[count - 1]->compact_branch) {
152 BITSET_WORD *dependents = instructions[count - 1]->dependents;
153
154 for (signed i = count - 2; i >= 0; --i) {
155 if (BITSET_TEST(dependents, i))
156 continue;
157
158 BITSET_SET(dependents, i);
159 instructions[i]->nr_dependencies++;
160 }
161 }
162
163 /* Free the intermediate structures */
164 for (unsigned i = 0; i < sz; ++i) {
165 util_dynarray_fini(&last_read[i]);
166 util_dynarray_fini(&last_write[i]);
167 }
168 }
169
170 /* Does the mask cover more than a scalar? */
171
172 static bool
173 is_single_component_mask(unsigned mask)
174 {
175 int components = 0;
176
177 for (int c = 0; c < 8; ++c) {
178 if (mask & (1 << c))
179 components++;
180 }
181
182 return components == 1;
183 }
184
185 /* Helpers for scheudling */
186
187 static bool
188 mir_is_scalar(midgard_instruction *ains)
189 {
190 /* Do we try to use it as a vector op? */
191 if (!is_single_component_mask(ains->mask))
192 return false;
193
194 /* Otherwise, check mode hazards */
195 bool could_scalar = true;
196
197 /* Only 16/32-bit can run on a scalar unit */
198 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_8;
199 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_64;
200 could_scalar &= ains->alu.dest_override == midgard_dest_override_none;
201
202 if (ains->alu.reg_mode == midgard_reg_mode_16) {
203 /* If we're running in 16-bit mode, we
204 * can't have any 8-bit sources on the
205 * scalar unit (since the scalar unit
206 * doesn't understand 8-bit) */
207
208 midgard_vector_alu_src s1 =
209 vector_alu_from_unsigned(ains->alu.src1);
210
211 could_scalar &= !s1.half;
212
213 midgard_vector_alu_src s2 =
214 vector_alu_from_unsigned(ains->alu.src2);
215
216 could_scalar &= !s2.half;
217 }
218
219 return could_scalar;
220 }
221
222 /* How many bytes does this ALU instruction add to the bundle? */
223
224 static unsigned
225 bytes_for_instruction(midgard_instruction *ains)
226 {
227 if (ains->unit & UNITS_ANY_VECTOR)
228 return sizeof(midgard_reg_info) + sizeof(midgard_vector_alu);
229 else if (ains->unit == ALU_ENAB_BRANCH)
230 return sizeof(midgard_branch_extended);
231 else if (ains->compact_branch)
232 return sizeof(ains->br_compact);
233 else
234 return sizeof(midgard_reg_info) + sizeof(midgard_scalar_alu);
235 }
236
237 /* We would like to flatten the linked list of midgard_instructions in a bundle
238 * to an array of pointers on the heap for easy indexing */
239
240 static midgard_instruction **
241 flatten_mir(midgard_block *block, unsigned *len)
242 {
243 *len = list_length(&block->instructions);
244
245 if (!(*len))
246 return NULL;
247
248 midgard_instruction **instructions =
249 calloc(sizeof(midgard_instruction *), *len);
250
251 unsigned i = 0;
252
253 mir_foreach_instr_in_block(block, ins)
254 instructions[i++] = ins;
255
256 return instructions;
257 }
258
259 /* The worklist is the set of instructions that can be scheduled now; that is,
260 * the set of instructions with no remaining dependencies */
261
262 static void
263 mir_initialize_worklist(BITSET_WORD *worklist, midgard_instruction **instructions, unsigned count)
264 {
265 for (unsigned i = 0; i < count; ++i) {
266 if (instructions[i]->nr_dependencies == 0)
267 BITSET_SET(worklist, i);
268 }
269 }
270
271 /* Update the worklist after an instruction terminates. Remove its edges from
272 * the graph and if that causes any node to have no dependencies, add it to the
273 * worklist */
274
275 static void
276 mir_update_worklist(
277 BITSET_WORD *worklist, unsigned count,
278 midgard_instruction **instructions, midgard_instruction *done)
279 {
280 /* Sanity check: if no instruction terminated, there is nothing to do.
281 * If the instruction that terminated had dependencies, that makes no
282 * sense and means we messed up the worklist. Finally, as the purpose
283 * of this routine is to update dependents, we abort early if there are
284 * no dependents defined. */
285
286 if (!done)
287 return;
288
289 assert(done->nr_dependencies == 0);
290
291 if (!done->dependents)
292 return;
293
294 /* We have an instruction with dependents. Iterate each dependent to
295 * remove one dependency (`done`), adding dependents to the worklist
296 * where possible. */
297
298 unsigned i;
299 BITSET_WORD tmp;
300 BITSET_FOREACH_SET(i, tmp, done->dependents, count) {
301 assert(instructions[i]->nr_dependencies);
302
303 if (!(--instructions[i]->nr_dependencies))
304 BITSET_SET(worklist, i);
305 }
306
307 free(done->dependents);
308 }
309
310 /* While scheduling, we need to choose instructions satisfying certain
311 * criteria. As we schedule backwards, we choose the *last* instruction in the
312 * worklist to simulate in-order scheduling. Chosen instructions must satisfy a
313 * given predicate. */
314
315 struct midgard_predicate {
316 /* TAG or ~0 for dont-care */
317 unsigned tag;
318
319 /* True if we want to pop off the chosen instruction */
320 bool destructive;
321
322 /* For ALU, choose only this unit */
323 unsigned unit;
324
325 /* State for bundle constants. constants is the actual constants
326 * for the bundle. constant_count is the number of bytes (up to
327 * 16) currently in use for constants. When picking in destructive
328 * mode, the constants array will be updated, and the instruction
329 * will be adjusted to index into the constants array */
330
331 uint8_t *constants;
332 unsigned constant_count;
333 bool blend_constant;
334
335 /* Exclude this destination (if not ~0) */
336 unsigned exclude;
337
338 /* Don't schedule instructions consuming conditionals (since we already
339 * scheduled one). Excludes conditional branches and csel */
340 bool no_cond;
341
342 /* Require a minimal mask and (if nonzero) given destination. Used for
343 * writeout optimizations */
344
345 unsigned mask;
346 unsigned dest;
347 };
348
349 /* For an instruction that can fit, adjust it to fit and update the constants
350 * array, in destructive mode. Returns whether the fitting was successful. */
351
352 static bool
353 mir_adjust_constants(midgard_instruction *ins,
354 struct midgard_predicate *pred,
355 bool destructive)
356 {
357 /* Blend constants dominate */
358 if (ins->has_blend_constant) {
359 if (pred->constant_count)
360 return false;
361 else if (destructive) {
362 pred->blend_constant = true;
363 pred->constant_count = 16;
364 return true;
365 }
366 }
367
368 /* No constant, nothing to adjust */
369 if (!ins->has_constants)
370 return true;
371
372 if (ins->alu.reg_mode != midgard_reg_mode_32) {
373 /* TODO: 16-bit constant combining */
374 if (pred->constant_count)
375 return false;
376
377 uint16_t *bundles = (uint16_t *) pred->constants;
378 uint32_t *constants = (uint32_t *) ins->constants;
379
380 /* Copy them wholesale */
381 for (unsigned i = 0; i < 4; ++i)
382 bundles[i] = constants[i];
383
384 pred->constant_count = 16;
385 } else {
386 /* Pack 32-bit constants */
387 uint32_t *bundles = (uint32_t *) pred->constants;
388 uint32_t *constants = (uint32_t *) ins->constants;
389 unsigned r_constant = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
390 unsigned mask = mir_from_bytemask(mir_bytemask_of_read_components(ins, r_constant), midgard_reg_mode_32);
391
392 /* First, check if it fits */
393 unsigned count = DIV_ROUND_UP(pred->constant_count, sizeof(uint32_t));
394 unsigned existing_count = count;
395
396 for (unsigned i = 0; i < 4; ++i) {
397 if (!(mask & (1 << i)))
398 continue;
399
400 bool ok = false;
401
402 /* Look for existing constant */
403 for (unsigned j = 0; j < existing_count; ++j) {
404 if (bundles[j] == constants[i]) {
405 ok = true;
406 break;
407 }
408 }
409
410 if (ok)
411 continue;
412
413 /* If the constant is new, check ourselves */
414 for (unsigned j = 0; j < i; ++j) {
415 if (constants[j] == constants[i]) {
416 ok = true;
417 break;
418 }
419 }
420
421 if (ok)
422 continue;
423
424 /* Otherwise, this is a new constant */
425 count++;
426 }
427
428 /* Check if we have space */
429 if (count > 4)
430 return false;
431
432 /* If non-destructive, we're done */
433 if (!destructive)
434 return true;
435
436 /* If destructive, let's copy in the new constants and adjust
437 * swizzles to pack it in. */
438
439 unsigned indices[16] = { 0 };
440
441 /* Reset count */
442 count = existing_count;
443
444 for (unsigned i = 0; i < 4; ++i) {
445 if (!(mask & (1 << i)))
446 continue;
447
448 uint32_t cons = constants[i];
449 bool constant_found = false;
450
451 /* Search for the constant */
452 for (unsigned j = 0; j < count; ++j) {
453 if (bundles[j] != cons)
454 continue;
455
456 /* We found it, reuse */
457 indices[i] = j;
458 constant_found = true;
459 break;
460 }
461
462 if (constant_found)
463 continue;
464
465 /* We didn't find it, so allocate it */
466 unsigned idx = count++;
467
468 /* We have space, copy it in! */
469 bundles[idx] = cons;
470 indices[i] = idx;
471 }
472
473 pred->constant_count = count * sizeof(uint32_t);
474
475 /* Use indices as a swizzle */
476
477 mir_foreach_src(ins, s) {
478 if (ins->src[s] == r_constant)
479 mir_compose_swizzle(ins->swizzle[s], indices, ins->swizzle[s]);
480 }
481 }
482
483 return true;
484 }
485
486 static midgard_instruction *
487 mir_choose_instruction(
488 midgard_instruction **instructions,
489 BITSET_WORD *worklist, unsigned count,
490 struct midgard_predicate *predicate)
491 {
492 /* Parse the predicate */
493 unsigned tag = predicate->tag;
494 bool alu = tag == TAG_ALU_4;
495 unsigned unit = predicate->unit;
496 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
497 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
498 bool no_cond = predicate->no_cond;
499
500 unsigned mask = predicate->mask;
501 unsigned dest = predicate->dest;
502 bool needs_dest = mask & 0xF;
503
504 /* Iterate to find the best instruction satisfying the predicate */
505 unsigned i;
506 BITSET_WORD tmp;
507
508 signed best_index = -1;
509 bool best_conditional = false;
510
511 /* Enforce a simple metric limiting distance to keep down register
512 * pressure. TOOD: replace with liveness tracking for much better
513 * results */
514
515 unsigned max_active = 0;
516 unsigned max_distance = 6;
517
518 BITSET_FOREACH_SET(i, tmp, worklist, count) {
519 max_active = MAX2(max_active, i);
520 }
521
522 BITSET_FOREACH_SET(i, tmp, worklist, count) {
523 if ((max_active - i) >= max_distance)
524 continue;
525
526 if (tag != ~0 && instructions[i]->type != tag)
527 continue;
528
529 if (predicate->exclude != ~0 && instructions[i]->dest == predicate->exclude)
530 continue;
531
532 if (alu && !branch && !(alu_opcode_props[instructions[i]->alu.op].props & unit))
533 continue;
534
535 if (branch && !instructions[i]->compact_branch)
536 continue;
537
538 if (alu && scalar && !mir_is_scalar(instructions[i]))
539 continue;
540
541 if (alu && !mir_adjust_constants(instructions[i], predicate, false))
542 continue;
543
544 if (needs_dest && instructions[i]->dest != dest)
545 continue;
546
547 if (mask && ((~instructions[i]->mask) & mask))
548 continue;
549
550 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
551 conditional |= (branch && !instructions[i]->prepacked_branch && instructions[i]->branch.conditional);
552
553 if (conditional && no_cond)
554 continue;
555
556 /* Simulate in-order scheduling */
557 if ((signed) i < best_index)
558 continue;
559
560 best_index = i;
561 best_conditional = conditional;
562 }
563
564
565 /* Did we find anything? */
566
567 if (best_index < 0)
568 return NULL;
569
570 /* If we found something, remove it from the worklist */
571 assert(best_index < count);
572
573 if (predicate->destructive) {
574 BITSET_CLEAR(worklist, best_index);
575
576 if (alu)
577 mir_adjust_constants(instructions[best_index], predicate, true);
578
579 /* Once we schedule a conditional, we can't again */
580 predicate->no_cond |= best_conditional;
581 }
582
583 return instructions[best_index];
584 }
585
586 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
587 * best bundle type (ALU, load/store, texture). Nondestructive. */
588
589 static unsigned
590 mir_choose_bundle(
591 midgard_instruction **instructions,
592 BITSET_WORD *worklist, unsigned count)
593 {
594 /* At the moment, our algorithm is very simple - use the bundle of the
595 * best instruction, regardless of what else could be scheduled
596 * alongside it. This is not optimal but it works okay for in-order */
597
598 struct midgard_predicate predicate = {
599 .tag = ~0,
600 .destructive = false,
601 .exclude = ~0
602 };
603
604 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
605
606 if (chosen)
607 return chosen->type;
608 else
609 return ~0;
610 }
611
612 /* We want to choose an ALU instruction filling a given unit */
613 static void
614 mir_choose_alu(midgard_instruction **slot,
615 midgard_instruction **instructions,
616 BITSET_WORD *worklist, unsigned len,
617 struct midgard_predicate *predicate,
618 unsigned unit)
619 {
620 /* Did we already schedule to this slot? */
621 if ((*slot) != NULL)
622 return;
623
624 /* Try to schedule something, if not */
625 predicate->unit = unit;
626 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
627
628 /* Store unit upon scheduling */
629 if (*slot && !((*slot)->compact_branch))
630 (*slot)->unit = unit;
631 }
632
633 /* When we are scheduling a branch/csel, we need the consumed condition in the
634 * same block as a pipeline register. There are two options to enable this:
635 *
636 * - Move the conditional into the bundle. Preferred, but only works if the
637 * conditional is used only once and is from this block.
638 * - Copy the conditional.
639 *
640 * We search for the conditional. If it's in this block, single-use, and
641 * without embedded constants, we schedule it immediately. Otherwise, we
642 * schedule a move for it.
643 *
644 * mir_comparison_mobile is a helper to find the moveable condition.
645 */
646
647 static unsigned
648 mir_comparison_mobile(
649 compiler_context *ctx,
650 midgard_instruction **instructions,
651 struct midgard_predicate *predicate,
652 unsigned count,
653 unsigned cond)
654 {
655 if (!mir_single_use(ctx, cond))
656 return ~0;
657
658 unsigned ret = ~0;
659
660 for (unsigned i = 0; i < count; ++i) {
661 if (instructions[i]->dest != cond)
662 continue;
663
664 /* Must fit in an ALU bundle */
665 if (instructions[i]->type != TAG_ALU_4)
666 return ~0;
667
668 /* We'll need to rewrite to .w but that doesn't work for vector
669 * ops that don't replicate (ball/bany), so bail there */
670
671 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
672 return ~0;
673
674 /* Ensure it will fit with constants */
675
676 if (!mir_adjust_constants(instructions[i], predicate, false))
677 return ~0;
678
679 /* Ensure it is written only once */
680
681 if (ret != ~0)
682 return ~0;
683 else
684 ret = i;
685 }
686
687 /* Inject constants now that we are sure we want to */
688 if (ret != ~0)
689 mir_adjust_constants(instructions[ret], predicate, true);
690
691 return ret;
692 }
693
694 /* Using the information about the moveable conditional itself, we either pop
695 * that condition off the worklist for use now, or create a move to
696 * artificially schedule instead as a fallback */
697
698 static midgard_instruction *
699 mir_schedule_comparison(
700 compiler_context *ctx,
701 midgard_instruction **instructions,
702 struct midgard_predicate *predicate,
703 BITSET_WORD *worklist, unsigned count,
704 unsigned cond, bool vector, unsigned *swizzle,
705 midgard_instruction *user)
706 {
707 /* TODO: swizzle when scheduling */
708 unsigned comp_i =
709 (!vector && (swizzle[0] == 0)) ?
710 mir_comparison_mobile(ctx, instructions, predicate, count, cond) : ~0;
711
712 /* If we can, schedule the condition immediately */
713 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
714 assert(comp_i < count);
715 BITSET_CLEAR(worklist, comp_i);
716 return instructions[comp_i];
717 }
718
719 /* Otherwise, we insert a move */
720
721 midgard_instruction mov = v_mov(cond, cond);
722 mov.mask = vector ? 0xF : 0x1;
723 memcpy(mov.swizzle[1], swizzle, sizeof(mov.swizzle[1]));
724
725 return mir_insert_instruction_before(ctx, user, mov);
726 }
727
728 /* Most generally, we need instructions writing to r31 in the appropriate
729 * components */
730
731 static midgard_instruction *
732 mir_schedule_condition(compiler_context *ctx,
733 struct midgard_predicate *predicate,
734 BITSET_WORD *worklist, unsigned count,
735 midgard_instruction **instructions,
736 midgard_instruction *last)
737 {
738 /* For a branch, the condition is the only argument; for csel, third */
739 bool branch = last->compact_branch;
740 unsigned condition_index = branch ? 0 : 2;
741
742 /* csel_v is vector; otherwise, conditions are scalar */
743 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
744
745 /* Grab the conditional instruction */
746
747 midgard_instruction *cond = mir_schedule_comparison(
748 ctx, instructions, predicate, worklist, count, last->src[condition_index],
749 vector, last->swizzle[2], last);
750
751 /* We have exclusive reign over this (possibly move) conditional
752 * instruction. We can rewrite into a pipeline conditional register */
753
754 predicate->exclude = cond->dest;
755 cond->dest = SSA_FIXED_REGISTER(31);
756
757 if (!vector) {
758 cond->mask = (1 << COMPONENT_W);
759
760 mir_foreach_src(cond, s) {
761 if (cond->src[s] == ~0)
762 continue;
763
764 for (unsigned q = 0; q < 4; ++q)
765 cond->swizzle[s][q + COMPONENT_W] = cond->swizzle[s][q];
766 }
767 }
768
769 /* Schedule the unit: csel is always in the latter pipeline, so a csel
770 * condition must be in the former pipeline stage (vmul/sadd),
771 * depending on scalar/vector of the instruction itself. A branch must
772 * be written from the latter pipeline stage and a branch condition is
773 * always scalar, so it is always in smul (exception: ball/bany, which
774 * will be vadd) */
775
776 if (branch)
777 cond->unit = UNIT_SMUL;
778 else
779 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
780
781 return cond;
782 }
783
784 /* Schedules a single bundle of the given type */
785
786 static midgard_bundle
787 mir_schedule_texture(
788 midgard_instruction **instructions,
789 BITSET_WORD *worklist, unsigned len)
790 {
791 struct midgard_predicate predicate = {
792 .tag = TAG_TEXTURE_4,
793 .destructive = true,
794 .exclude = ~0
795 };
796
797 midgard_instruction *ins =
798 mir_choose_instruction(instructions, worklist, len, &predicate);
799
800 mir_update_worklist(worklist, len, instructions, ins);
801
802 struct midgard_bundle out = {
803 .tag = TAG_TEXTURE_4,
804 .instruction_count = 1,
805 .instructions = { ins }
806 };
807
808 return out;
809 }
810
811 static midgard_bundle
812 mir_schedule_ldst(
813 midgard_instruction **instructions,
814 BITSET_WORD *worklist, unsigned len)
815 {
816 struct midgard_predicate predicate = {
817 .tag = TAG_LOAD_STORE_4,
818 .destructive = true,
819 .exclude = ~0
820 };
821
822 /* Try to pick two load/store ops. Second not gauranteed to exist */
823
824 midgard_instruction *ins =
825 mir_choose_instruction(instructions, worklist, len, &predicate);
826
827 midgard_instruction *pair =
828 mir_choose_instruction(instructions, worklist, len, &predicate);
829
830 struct midgard_bundle out = {
831 .tag = TAG_LOAD_STORE_4,
832 .instruction_count = pair ? 2 : 1,
833 .instructions = { ins, pair }
834 };
835
836 /* We have to update the worklist atomically, since the two
837 * instructions run concurrently (TODO: verify it's not pipelined) */
838
839 mir_update_worklist(worklist, len, instructions, ins);
840 mir_update_worklist(worklist, len, instructions, pair);
841
842 return out;
843 }
844
845 static midgard_bundle
846 mir_schedule_alu(
847 compiler_context *ctx,
848 midgard_instruction **instructions,
849 BITSET_WORD *worklist, unsigned len)
850 {
851 struct midgard_bundle bundle = {};
852
853 unsigned bytes_emitted = sizeof(bundle.control);
854
855 struct midgard_predicate predicate = {
856 .tag = TAG_ALU_4,
857 .destructive = true,
858 .exclude = ~0,
859 .constants = (uint8_t *) bundle.constants
860 };
861
862 midgard_instruction *vmul = NULL;
863 midgard_instruction *vadd = NULL;
864 midgard_instruction *vlut = NULL;
865 midgard_instruction *smul = NULL;
866 midgard_instruction *sadd = NULL;
867 midgard_instruction *branch = NULL;
868
869 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
870 mir_update_worklist(worklist, len, instructions, branch);
871 bool writeout = branch && branch->writeout;
872
873 if (branch && !branch->prepacked_branch && branch->branch.conditional) {
874 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
875
876 if (cond->unit == UNIT_VADD)
877 vadd = cond;
878 else if (cond->unit == UNIT_SMUL)
879 smul = cond;
880 else
881 unreachable("Bad condition");
882 }
883
884 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
885
886 if (!writeout)
887 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
888
889 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
890
891 mir_update_worklist(worklist, len, instructions, vlut);
892 mir_update_worklist(worklist, len, instructions, vadd);
893 mir_update_worklist(worklist, len, instructions, smul);
894
895 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
896 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
897
898 if (vadd_csel || smul_csel) {
899 midgard_instruction *ins = vadd_csel ? vadd : smul;
900 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
901
902 if (cond->unit == UNIT_VMUL)
903 vmul = cond;
904 else if (cond->unit == UNIT_SADD)
905 sadd = cond;
906 else
907 unreachable("Bad condition");
908 }
909
910 /* Stage 2, let's schedule sadd before vmul for writeout */
911 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
912
913 /* Check if writeout reads its own register */
914 bool bad_writeout = false;
915
916 if (branch && branch->writeout) {
917 midgard_instruction *stages[] = { sadd, vadd, smul };
918 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : branch->src[0];
919 unsigned writeout_mask = 0x0;
920
921 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
922 if (!stages[i])
923 continue;
924
925 if (stages[i]->dest != src)
926 continue;
927
928 writeout_mask |= stages[i]->mask;
929 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
930 }
931
932 /* It's possible we'll be able to schedule something into vmul
933 * to fill r0. Let's peak into the future, trying to schedule
934 * vmul specially that way. */
935
936 if (!bad_writeout && writeout_mask != 0xF) {
937 predicate.unit = UNIT_VMUL;
938 predicate.dest = src;
939 predicate.mask = writeout_mask ^ 0xF;
940
941 struct midgard_instruction *peaked =
942 mir_choose_instruction(instructions, worklist, len, &predicate);
943
944 if (peaked) {
945 vmul = peaked;
946 vmul->unit = UNIT_VMUL;
947 writeout_mask |= predicate.mask;
948 assert(writeout_mask == 0xF);
949 }
950
951 /* Cleanup */
952 predicate.dest = predicate.mask = 0;
953 }
954
955 /* Finally, add a move if necessary */
956 if (bad_writeout || writeout_mask != 0xF) {
957 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : make_compiler_temp(ctx);
958 midgard_instruction mov = v_mov(src, temp);
959 vmul = mem_dup(&mov, sizeof(midgard_instruction));
960 vmul->unit = UNIT_VMUL;
961 vmul->mask = 0xF ^ writeout_mask;
962 /* TODO: Don't leak */
963
964 /* Rewrite to use our temp */
965
966 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
967 if (stages[i])
968 mir_rewrite_index_dst_single(stages[i], src, temp);
969 }
970
971 mir_rewrite_index_src_single(branch, src, temp);
972 }
973 }
974
975 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
976
977 mir_update_worklist(worklist, len, instructions, vmul);
978 mir_update_worklist(worklist, len, instructions, sadd);
979
980 bundle.has_blend_constant = predicate.blend_constant;
981 bundle.has_embedded_constants = predicate.constant_count > 0;
982
983 unsigned padding = 0;
984
985 /* Now that we have finished scheduling, build up the bundle */
986 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
987
988 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
989 if (stages[i]) {
990 bundle.control |= stages[i]->unit;
991 bytes_emitted += bytes_for_instruction(stages[i]);
992 bundle.instructions[bundle.instruction_count++] = stages[i];
993 }
994 }
995
996 /* Pad ALU op to nearest word */
997
998 if (bytes_emitted & 15) {
999 padding = 16 - (bytes_emitted & 15);
1000 bytes_emitted += padding;
1001 }
1002
1003 /* Constants must always be quadwords */
1004 if (bundle.has_embedded_constants)
1005 bytes_emitted += 16;
1006
1007 /* Size ALU instruction for tag */
1008 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
1009 bundle.padding = padding;
1010 bundle.control |= bundle.tag;
1011
1012 return bundle;
1013 }
1014
1015 /* Schedule a single block by iterating its instruction to create bundles.
1016 * While we go, tally about the bundle sizes to compute the block size. */
1017
1018
1019 static void
1020 schedule_block(compiler_context *ctx, midgard_block *block)
1021 {
1022 /* Copy list to dynamic array */
1023 unsigned len = 0;
1024 midgard_instruction **instructions = flatten_mir(block, &len);
1025
1026 if (!len)
1027 return;
1028
1029 /* Calculate dependencies and initial worklist */
1030 unsigned node_count = ctx->temp_count + 1;
1031 mir_create_dependency_graph(instructions, len, node_count);
1032
1033 /* Allocate the worklist */
1034 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
1035 BITSET_WORD *worklist = calloc(sz, 1);
1036 mir_initialize_worklist(worklist, instructions, len);
1037
1038 struct util_dynarray bundles;
1039 util_dynarray_init(&bundles, NULL);
1040
1041 block->quadword_count = 0;
1042 unsigned blend_offset = 0;
1043
1044 for (;;) {
1045 unsigned tag = mir_choose_bundle(instructions, worklist, len);
1046 midgard_bundle bundle;
1047
1048 if (tag == TAG_TEXTURE_4)
1049 bundle = mir_schedule_texture(instructions, worklist, len);
1050 else if (tag == TAG_LOAD_STORE_4)
1051 bundle = mir_schedule_ldst(instructions, worklist, len);
1052 else if (tag == TAG_ALU_4)
1053 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
1054 else
1055 break;
1056
1057 util_dynarray_append(&bundles, midgard_bundle, bundle);
1058
1059 if (bundle.has_blend_constant)
1060 blend_offset = block->quadword_count;
1061
1062 block->quadword_count += quadword_size(bundle.tag);
1063 }
1064
1065 /* We emitted bundles backwards; copy into the block in reverse-order */
1066
1067 util_dynarray_init(&block->bundles, NULL);
1068 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
1069 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
1070 }
1071
1072 /* Blend constant was backwards as well. blend_offset if set is
1073 * strictly positive, as an offset of zero would imply constants before
1074 * any instructions which is invalid in Midgard. TODO: blend constants
1075 * are broken if you spill since then quadword_count becomes invalid
1076 * XXX */
1077
1078 if (blend_offset)
1079 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
1080
1081 block->is_scheduled = true;
1082 ctx->quadword_count += block->quadword_count;
1083
1084 /* Reorder instructions to match bundled. First remove existing
1085 * instructions and then recreate the list */
1086
1087 mir_foreach_instr_in_block_safe(block, ins) {
1088 list_del(&ins->link);
1089 }
1090
1091 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
1092 list_add(&ins->link, &block->instructions);
1093 }
1094 }
1095
1096 /* When we're 'squeezing down' the values in the IR, we maintain a hash
1097 * as such */
1098
1099 static unsigned
1100 find_or_allocate_temp(compiler_context *ctx, unsigned hash)
1101 {
1102 if (hash >= SSA_FIXED_MINIMUM)
1103 return hash;
1104
1105 unsigned temp = (uintptr_t) _mesa_hash_table_u64_search(
1106 ctx->hash_to_temp, hash + 1);
1107
1108 if (temp)
1109 return temp - 1;
1110
1111 /* If no temp is find, allocate one */
1112 temp = ctx->temp_count++;
1113 ctx->max_hash = MAX2(ctx->max_hash, hash);
1114
1115 _mesa_hash_table_u64_insert(ctx->hash_to_temp,
1116 hash + 1, (void *) ((uintptr_t) temp + 1));
1117
1118 return temp;
1119 }
1120
1121 /* Reassigns numbering to get rid of gaps in the indices and to prioritize
1122 * smaller register classes */
1123
1124 static void
1125 mir_squeeze_index(compiler_context *ctx)
1126 {
1127 /* Reset */
1128 ctx->temp_count = 0;
1129 /* TODO don't leak old hash_to_temp */
1130 ctx->hash_to_temp = _mesa_hash_table_u64_create(NULL);
1131
1132 /* We need to prioritize texture registers on older GPUs so we don't
1133 * fail RA trying to assign to work registers r0/r1 when a work
1134 * register is already there */
1135
1136 mir_foreach_instr_global(ctx, ins) {
1137 if (ins->type == TAG_TEXTURE_4)
1138 ins->dest = find_or_allocate_temp(ctx, ins->dest);
1139 }
1140
1141 mir_foreach_instr_global(ctx, ins) {
1142 if (ins->type != TAG_TEXTURE_4)
1143 ins->dest = find_or_allocate_temp(ctx, ins->dest);
1144
1145 for (unsigned i = 0; i < ARRAY_SIZE(ins->src); ++i)
1146 ins->src[i] = find_or_allocate_temp(ctx, ins->src[i]);
1147 }
1148 }
1149
1150 static midgard_instruction
1151 v_load_store_scratch(
1152 unsigned srcdest,
1153 unsigned index,
1154 bool is_store,
1155 unsigned mask)
1156 {
1157 /* We index by 32-bit vec4s */
1158 unsigned byte = (index * 4 * 4);
1159
1160 midgard_instruction ins = {
1161 .type = TAG_LOAD_STORE_4,
1162 .mask = mask,
1163 .dest = ~0,
1164 .src = { ~0, ~0, ~0 },
1165 .swizzle = SWIZZLE_IDENTITY_4,
1166 .load_store = {
1167 .op = is_store ? midgard_op_st_int4 : midgard_op_ld_int4,
1168
1169 /* For register spilling - to thread local storage */
1170 .arg_1 = 0xEA,
1171 .arg_2 = 0x1E,
1172 },
1173
1174 /* If we spill an unspill, RA goes into an infinite loop */
1175 .no_spill = true
1176 };
1177
1178 ins.constants[0] = byte;
1179
1180 if (is_store) {
1181 /* r0 = r26, r1 = r27 */
1182 assert(srcdest == SSA_FIXED_REGISTER(26) || srcdest == SSA_FIXED_REGISTER(27));
1183 ins.src[0] = srcdest;
1184 } else {
1185 ins.dest = srcdest;
1186 }
1187
1188 return ins;
1189 }
1190
1191 /* If register allocation fails, find the best spill node and spill it to fix
1192 * whatever the issue was. This spill node could be a work register (spilling
1193 * to thread local storage), but it could also simply be a special register
1194 * that needs to spill to become a work register. */
1195
1196 static void mir_spill_register(
1197 compiler_context *ctx,
1198 struct lcra_state *l,
1199 unsigned *spill_count)
1200 {
1201 unsigned spill_index = ctx->temp_count;
1202
1203 /* Our first step is to calculate spill cost to figure out the best
1204 * spill node. All nodes are equal in spill cost, but we can't spill
1205 * nodes written to from an unspill */
1206
1207 unsigned *cost = calloc(ctx->temp_count, sizeof(cost[0]));
1208
1209 mir_foreach_instr_global(ctx, ins) {
1210 if (ins->dest < ctx->temp_count)
1211 cost[ins->dest]++;
1212
1213 mir_foreach_src(ins, s) {
1214 if (ins->src[s] < ctx->temp_count)
1215 cost[ins->src[s]]++;
1216 }
1217 }
1218
1219 for (unsigned i = 0; i < ctx->temp_count; ++i)
1220 lcra_set_node_spill_cost(l, i, cost[i]);
1221
1222 /* We can't spill any bundles that contain unspills. This could be
1223 * optimized to allow use of r27 to spill twice per bundle, but if
1224 * you're at the point of optimizing spilling, it's too late.
1225 *
1226 * We also can't double-spill. */
1227
1228 mir_foreach_block(ctx, block) {
1229 mir_foreach_bundle_in_block(block, bun) {
1230 bool no_spill = false;
1231
1232 for (unsigned i = 0; i < bun->instruction_count; ++i) {
1233 no_spill |= bun->instructions[i]->no_spill;
1234
1235 if (bun->instructions[i]->no_spill) {
1236 mir_foreach_src(bun->instructions[i], s) {
1237 unsigned src = bun->instructions[i]->src[s];
1238
1239 if (src < ctx->temp_count)
1240 lcra_set_node_spill_cost(l, src, -1);
1241 }
1242 }
1243 }
1244
1245 if (!no_spill)
1246 continue;
1247
1248 for (unsigned i = 0; i < bun->instruction_count; ++i) {
1249 unsigned dest = bun->instructions[i]->dest;
1250 if (dest < ctx->temp_count)
1251 lcra_set_node_spill_cost(l, dest, -1);
1252 }
1253 }
1254 }
1255
1256 int spill_node = lcra_get_best_spill_node(l);
1257
1258 if (spill_node < 0) {
1259 mir_print_shader(ctx);
1260 assert(0);
1261 }
1262
1263 /* We have a spill node, so check the class. Work registers
1264 * legitimately spill to TLS, but special registers just spill to work
1265 * registers */
1266
1267 bool is_special = l->class[spill_node] != REG_CLASS_WORK;
1268 bool is_special_w = l->class[spill_node] == REG_CLASS_TEXW;
1269
1270 /* Allocate TLS slot (maybe) */
1271 unsigned spill_slot = !is_special ? (*spill_count)++ : 0;
1272
1273 /* For TLS, replace all stores to the spilled node. For
1274 * special reads, just keep as-is; the class will be demoted
1275 * implicitly. For special writes, spill to a work register */
1276
1277 if (!is_special || is_special_w) {
1278 if (is_special_w)
1279 spill_slot = spill_index++;
1280
1281 mir_foreach_block(ctx, block) {
1282 mir_foreach_instr_in_block_safe(block, ins) {
1283 if (ins->dest != spill_node) continue;
1284
1285 midgard_instruction st;
1286
1287 if (is_special_w) {
1288 st = v_mov(spill_node, spill_slot);
1289 st.no_spill = true;
1290 } else {
1291 ins->dest = SSA_FIXED_REGISTER(26);
1292 ins->no_spill = true;
1293 st = v_load_store_scratch(ins->dest, spill_slot, true, ins->mask);
1294 }
1295
1296 /* Hint: don't rewrite this node */
1297 st.hint = true;
1298
1299 mir_insert_instruction_after_scheduled(ctx, block, ins, st);
1300
1301 if (!is_special)
1302 ctx->spills++;
1303 }
1304 }
1305 }
1306
1307 /* For special reads, figure out how many bytes we need */
1308 unsigned read_bytemask = 0;
1309
1310 mir_foreach_instr_global_safe(ctx, ins) {
1311 read_bytemask |= mir_bytemask_of_read_components(ins, spill_node);
1312 }
1313
1314 /* Insert a load from TLS before the first consecutive
1315 * use of the node, rewriting to use spilled indices to
1316 * break up the live range. Or, for special, insert a
1317 * move. Ironically the latter *increases* register
1318 * pressure, but the two uses of the spilling mechanism
1319 * are somewhat orthogonal. (special spilling is to use
1320 * work registers to back special registers; TLS
1321 * spilling is to use memory to back work registers) */
1322
1323 mir_foreach_block(ctx, block) {
1324 bool consecutive_skip = false;
1325 unsigned consecutive_index = 0;
1326
1327 mir_foreach_instr_in_block(block, ins) {
1328 /* We can't rewrite the moves used to spill in the
1329 * first place. These moves are hinted. */
1330 if (ins->hint) continue;
1331
1332 if (!mir_has_arg(ins, spill_node)) {
1333 consecutive_skip = false;
1334 continue;
1335 }
1336
1337 if (consecutive_skip) {
1338 /* Rewrite */
1339 mir_rewrite_index_src_single(ins, spill_node, consecutive_index);
1340 continue;
1341 }
1342
1343 if (!is_special_w) {
1344 consecutive_index = ++spill_index;
1345
1346 midgard_instruction *before = ins;
1347
1348 /* TODO: Remove me I'm a fossil */
1349 if (ins->type == TAG_ALU_4 && OP_IS_CSEL(ins->alu.op))
1350 before = mir_prev_op(before);
1351
1352 midgard_instruction st;
1353
1354 if (is_special) {
1355 /* Move */
1356 st = v_mov(spill_node, consecutive_index);
1357 st.no_spill = true;
1358 } else {
1359 /* TLS load */
1360 st = v_load_store_scratch(consecutive_index, spill_slot, false, 0xF);
1361 }
1362
1363 /* Mask the load based on the component count
1364 * actually needed to prevent RA loops */
1365
1366 st.mask = mir_from_bytemask(read_bytemask, midgard_reg_mode_32);
1367
1368 mir_insert_instruction_before_scheduled(ctx, block, before, st);
1369 // consecutive_skip = true;
1370 } else {
1371 /* Special writes already have their move spilled in */
1372 consecutive_index = spill_slot;
1373 }
1374
1375
1376 /* Rewrite to use */
1377 mir_rewrite_index_src_single(ins, spill_node, consecutive_index);
1378
1379 if (!is_special)
1380 ctx->fills++;
1381 }
1382 }
1383
1384 /* Reset hints */
1385
1386 mir_foreach_instr_global(ctx, ins) {
1387 ins->hint = false;
1388 }
1389 }
1390
1391 void
1392 schedule_program(compiler_context *ctx)
1393 {
1394 struct lcra_state *l = NULL;
1395 bool spilled = false;
1396 int iter_count = 1000; /* max iterations */
1397
1398 /* Number of 128-bit slots in memory we've spilled into */
1399 unsigned spill_count = 0;
1400
1401 midgard_promote_uniforms(ctx, 16);
1402
1403 /* Must be lowered right before RA */
1404 mir_squeeze_index(ctx);
1405 mir_lower_special_reads(ctx);
1406 mir_squeeze_index(ctx);
1407
1408 /* Lowering can introduce some dead moves */
1409
1410 mir_foreach_block(ctx, block) {
1411 midgard_opt_dead_move_eliminate(ctx, block);
1412 schedule_block(ctx, block);
1413 }
1414
1415 mir_create_pipeline_registers(ctx);
1416
1417 do {
1418 if (spilled)
1419 mir_spill_register(ctx, l, &spill_count);
1420
1421 mir_squeeze_index(ctx);
1422 mir_invalidate_liveness(ctx);
1423
1424 l = NULL;
1425 l = allocate_registers(ctx, &spilled);
1426 } while(spilled && ((iter_count--) > 0));
1427
1428 if (iter_count <= 0) {
1429 fprintf(stderr, "panfrost: Gave up allocating registers, rendering will be incomplete\n");
1430 assert(0);
1431 }
1432
1433 /* Report spilling information. spill_count is in 128-bit slots (vec4 x
1434 * fp32), but tls_size is in bytes, so multiply by 16 */
1435
1436 ctx->tls_size = spill_count * 16;
1437
1438 install_registers(ctx, l);
1439 }