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