ff71e0dcd3f80c4a6258bb491a1d422ac19fa8eb
[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
344 /* For an instruction that can fit, adjust it to fit and update the constants
345 * array, in destructive mode. Returns whether the fitting was successful. */
346
347 static bool
348 mir_adjust_constants(midgard_instruction *ins,
349 struct midgard_predicate *pred,
350 bool destructive)
351 {
352 /* Blend constants dominate */
353 if (ins->has_blend_constant) {
354 if (pred->constant_count)
355 return false;
356 else if (destructive) {
357 pred->blend_constant = true;
358 pred->constant_count = 16;
359 return true;
360 }
361 }
362
363 /* No constant, nothing to adjust */
364 if (!ins->has_constants)
365 return true;
366
367 /* TODO: Deduplicate; permit multiple constants within a bundle */
368
369 if (destructive && !pred->constant_count) {
370 if (ins->alu.reg_mode == midgard_reg_mode_16) {
371 /* TODO: Fix packing XXX */
372 uint16_t *bundles = (uint16_t *) pred->constants;
373 uint32_t *constants = (uint32_t *) ins->constants;
374
375 /* Copy them wholesale */
376 for (unsigned i = 0; i < 4; ++i)
377 bundles[i] = constants[i];
378 } else {
379 memcpy(pred->constants, ins->constants, 16);
380 }
381
382 pred->constant_count = 16;
383 return true;
384 }
385
386 return !pred->constant_count;
387 }
388
389 static midgard_instruction *
390 mir_choose_instruction(
391 midgard_instruction **instructions,
392 BITSET_WORD *worklist, unsigned count,
393 struct midgard_predicate *predicate)
394 {
395 /* Parse the predicate */
396 unsigned tag = predicate->tag;
397 bool alu = tag == TAG_ALU_4;
398 unsigned unit = predicate->unit;
399 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
400 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
401 bool no_cond = predicate->no_cond;
402
403 /* Iterate to find the best instruction satisfying the predicate */
404 unsigned i;
405 BITSET_WORD tmp;
406
407 signed best_index = -1;
408 bool best_conditional = false;
409
410 /* Enforce a simple metric limiting distance to keep down register
411 * pressure. TOOD: replace with liveness tracking for much better
412 * results */
413
414 unsigned max_active = 0;
415 unsigned max_distance = 6;
416
417 BITSET_FOREACH_SET(i, tmp, worklist, count) {
418 max_active = MAX2(max_active, i);
419 }
420
421 BITSET_FOREACH_SET(i, tmp, worklist, count) {
422 if ((max_active - i) >= max_distance)
423 continue;
424
425 if (tag != ~0 && instructions[i]->type != tag)
426 continue;
427
428 if (predicate->exclude != ~0 && instructions[i]->dest == predicate->exclude)
429 continue;
430
431 if (alu && !branch && !(alu_opcode_props[instructions[i]->alu.op].props & unit))
432 continue;
433
434 if (branch && !instructions[i]->compact_branch)
435 continue;
436
437 if (alu && scalar && !mir_is_scalar(instructions[i]))
438 continue;
439
440 if (alu && !mir_adjust_constants(instructions[i], predicate, false))
441 continue;
442
443 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
444 conditional |= (branch && !instructions[i]->prepacked_branch && instructions[i]->branch.conditional);
445
446 if (conditional && no_cond)
447 continue;
448
449 /* Simulate in-order scheduling */
450 if ((signed) i < best_index)
451 continue;
452
453 best_index = i;
454 best_conditional = conditional;
455 }
456
457
458 /* Did we find anything? */
459
460 if (best_index < 0)
461 return NULL;
462
463 /* If we found something, remove it from the worklist */
464 assert(best_index < count);
465
466 if (predicate->destructive) {
467 BITSET_CLEAR(worklist, best_index);
468
469 if (alu)
470 mir_adjust_constants(instructions[best_index], predicate, true);
471
472 /* Once we schedule a conditional, we can't again */
473 predicate->no_cond |= best_conditional;
474 }
475
476 return instructions[best_index];
477 }
478
479 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
480 * best bundle type (ALU, load/store, texture). Nondestructive. */
481
482 static unsigned
483 mir_choose_bundle(
484 midgard_instruction **instructions,
485 BITSET_WORD *worklist, unsigned count)
486 {
487 /* At the moment, our algorithm is very simple - use the bundle of the
488 * best instruction, regardless of what else could be scheduled
489 * alongside it. This is not optimal but it works okay for in-order */
490
491 struct midgard_predicate predicate = {
492 .tag = ~0,
493 .destructive = false,
494 .exclude = ~0
495 };
496
497 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
498
499 if (chosen)
500 return chosen->type;
501 else
502 return ~0;
503 }
504
505 /* We want to choose an ALU instruction filling a given unit */
506 static void
507 mir_choose_alu(midgard_instruction **slot,
508 midgard_instruction **instructions,
509 BITSET_WORD *worklist, unsigned len,
510 struct midgard_predicate *predicate,
511 unsigned unit)
512 {
513 /* Did we already schedule to this slot? */
514 if ((*slot) != NULL)
515 return;
516
517 /* Try to schedule something, if not */
518 predicate->unit = unit;
519 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
520
521 /* Store unit upon scheduling */
522 if (*slot && !((*slot)->compact_branch))
523 (*slot)->unit = unit;
524 }
525
526 /* When we are scheduling a branch/csel, we need the consumed condition in the
527 * same block as a pipeline register. There are two options to enable this:
528 *
529 * - Move the conditional into the bundle. Preferred, but only works if the
530 * conditional is used only once and is from this block.
531 * - Copy the conditional.
532 *
533 * We search for the conditional. If it's in this block, single-use, and
534 * without embedded constants, we schedule it immediately. Otherwise, we
535 * schedule a move for it.
536 *
537 * mir_comparison_mobile is a helper to find the moveable condition.
538 */
539
540 static unsigned
541 mir_comparison_mobile(
542 compiler_context *ctx,
543 midgard_instruction **instructions,
544 unsigned count,
545 unsigned cond)
546 {
547 if (!mir_single_use(ctx, cond))
548 return ~0;
549
550 unsigned ret = ~0;
551
552 for (unsigned i = 0; i < count; ++i) {
553 if (instructions[i]->dest != cond)
554 continue;
555
556 /* Must fit in an ALU bundle */
557 if (instructions[i]->type != TAG_ALU_4)
558 return ~0;
559
560 /* We'll need to rewrite to .w but that doesn't work for vector
561 * ops that don't replicate (ball/bany), so bail there */
562
563 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
564 return ~0;
565
566 /* TODO: moving conditionals with constants */
567
568 if (instructions[i]->has_constants)
569 return ~0;
570
571 /* Ensure it is written only once */
572
573 if (ret != ~0)
574 return ~0;
575 else
576 ret = i;
577 }
578
579 return ret;
580 }
581
582 /* Using the information about the moveable conditional itself, we either pop
583 * that condition off the worklist for use now, or create a move to
584 * artificially schedule instead as a fallback */
585
586 static midgard_instruction *
587 mir_schedule_comparison(
588 compiler_context *ctx,
589 midgard_instruction **instructions,
590 BITSET_WORD *worklist, unsigned count,
591 unsigned cond, bool vector, unsigned swizzle,
592 midgard_instruction *user)
593 {
594 /* TODO: swizzle when scheduling */
595 unsigned comp_i =
596 (!vector && (swizzle == 0)) ?
597 mir_comparison_mobile(ctx, instructions, count, cond) : ~0;
598
599 /* If we can, schedule the condition immediately */
600 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
601 assert(comp_i < count);
602 BITSET_CLEAR(worklist, comp_i);
603 return instructions[comp_i];
604 }
605
606 /* Otherwise, we insert a move */
607 midgard_vector_alu_src csel = {
608 .swizzle = swizzle
609 };
610
611 midgard_instruction mov = v_mov(cond, csel, cond);
612 mov.mask = vector ? 0xF : 0x1;
613
614 return mir_insert_instruction_before(ctx, user, mov);
615 }
616
617 /* Most generally, we need instructions writing to r31 in the appropriate
618 * components */
619
620 static midgard_instruction *
621 mir_schedule_condition(compiler_context *ctx,
622 struct midgard_predicate *predicate,
623 BITSET_WORD *worklist, unsigned count,
624 midgard_instruction **instructions,
625 midgard_instruction *last)
626 {
627 /* For a branch, the condition is the only argument; for csel, third */
628 bool branch = last->compact_branch;
629 unsigned condition_index = branch ? 0 : 2;
630
631 /* csel_v is vector; otherwise, conditions are scalar */
632 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
633
634 /* Grab the conditional instruction */
635
636 midgard_instruction *cond = mir_schedule_comparison(
637 ctx, instructions, worklist, count, last->src[condition_index],
638 vector, last->cond_swizzle, last);
639
640 /* We have exclusive reign over this (possibly move) conditional
641 * instruction. We can rewrite into a pipeline conditional register */
642
643 predicate->exclude = cond->dest;
644 cond->dest = SSA_FIXED_REGISTER(31);
645
646 if (!vector) {
647 cond->mask = (1 << COMPONENT_W);
648
649 mir_foreach_src(cond, s) {
650 if (cond->src[s] == ~0)
651 continue;
652
653 mir_set_swizzle(cond, s, (mir_get_swizzle(cond, s) << (2*3)) & 0xFF);
654 }
655 }
656
657 /* Schedule the unit: csel is always in the latter pipeline, so a csel
658 * condition must be in the former pipeline stage (vmul/sadd),
659 * depending on scalar/vector of the instruction itself. A branch must
660 * be written from the latter pipeline stage and a branch condition is
661 * always scalar, so it is always in smul (exception: ball/bany, which
662 * will be vadd) */
663
664 if (branch)
665 cond->unit = UNIT_SMUL;
666 else
667 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
668
669 return cond;
670 }
671
672 /* Schedules a single bundle of the given type */
673
674 static midgard_bundle
675 mir_schedule_texture(
676 midgard_instruction **instructions,
677 BITSET_WORD *worklist, unsigned len)
678 {
679 struct midgard_predicate predicate = {
680 .tag = TAG_TEXTURE_4,
681 .destructive = true,
682 .exclude = ~0
683 };
684
685 midgard_instruction *ins =
686 mir_choose_instruction(instructions, worklist, len, &predicate);
687
688 mir_update_worklist(worklist, len, instructions, ins);
689
690 struct midgard_bundle out = {
691 .tag = TAG_TEXTURE_4,
692 .instruction_count = 1,
693 .instructions = { ins }
694 };
695
696 return out;
697 }
698
699 static midgard_bundle
700 mir_schedule_ldst(
701 midgard_instruction **instructions,
702 BITSET_WORD *worklist, unsigned len)
703 {
704 struct midgard_predicate predicate = {
705 .tag = TAG_LOAD_STORE_4,
706 .destructive = true,
707 .exclude = ~0
708 };
709
710 /* Try to pick two load/store ops. Second not gauranteed to exist */
711
712 midgard_instruction *ins =
713 mir_choose_instruction(instructions, worklist, len, &predicate);
714
715 midgard_instruction *pair =
716 mir_choose_instruction(instructions, worklist, len, &predicate);
717
718 struct midgard_bundle out = {
719 .tag = TAG_LOAD_STORE_4,
720 .instruction_count = pair ? 2 : 1,
721 .instructions = { ins, pair }
722 };
723
724 /* We have to update the worklist atomically, since the two
725 * instructions run concurrently (TODO: verify it's not pipelined) */
726
727 mir_update_worklist(worklist, len, instructions, ins);
728 mir_update_worklist(worklist, len, instructions, pair);
729
730 return out;
731 }
732
733 static midgard_bundle
734 mir_schedule_alu(
735 compiler_context *ctx,
736 midgard_instruction **instructions,
737 BITSET_WORD *worklist, unsigned len)
738 {
739 struct midgard_bundle bundle = {};
740
741 unsigned bytes_emitted = sizeof(bundle.control);
742
743 struct midgard_predicate predicate = {
744 .tag = TAG_ALU_4,
745 .destructive = true,
746 .exclude = ~0,
747 .constants = (uint8_t *) bundle.constants
748 };
749
750 midgard_instruction *vmul = NULL;
751 midgard_instruction *vadd = NULL;
752 midgard_instruction *vlut = NULL;
753 midgard_instruction *smul = NULL;
754 midgard_instruction *sadd = NULL;
755 midgard_instruction *branch = NULL;
756
757 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
758 mir_update_worklist(worklist, len, instructions, branch);
759 bool writeout = branch && branch->writeout;
760
761 if (branch && !branch->prepacked_branch && branch->branch.conditional) {
762 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
763
764 if (cond->unit == UNIT_VADD)
765 vadd = cond;
766 else if (cond->unit == UNIT_SMUL)
767 smul = cond;
768 else
769 unreachable("Bad condition");
770 }
771
772 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
773
774 if (!writeout)
775 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
776
777 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
778
779 mir_update_worklist(worklist, len, instructions, vlut);
780 mir_update_worklist(worklist, len, instructions, vadd);
781 mir_update_worklist(worklist, len, instructions, smul);
782
783 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
784 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
785
786 if (vadd_csel || smul_csel) {
787 midgard_instruction *ins = vadd_csel ? vadd : smul;
788 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
789
790 if (cond->unit == UNIT_VMUL)
791 vmul = cond;
792 else if (cond->unit == UNIT_SADD)
793 sadd = cond;
794 else
795 unreachable("Bad condition");
796 }
797
798 /* Stage 2, let's schedule sadd before vmul for writeout */
799 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
800
801 /* Check if writeout reads its own register */
802 bool bad_writeout = false;
803
804 if (branch && branch->writeout) {
805 midgard_instruction *stages[] = { sadd, vadd, smul };
806 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : branch->src[0];
807 unsigned writeout_mask = 0x0;
808
809 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
810 if (!stages[i])
811 continue;
812
813 if (stages[i]->dest != src)
814 continue;
815
816 writeout_mask |= stages[i]->mask;
817 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
818 }
819
820 /* Add a move if necessary */
821 if (bad_writeout || writeout_mask != 0xF) {
822 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : make_compiler_temp(ctx);
823 midgard_instruction mov = v_mov(src, blank_alu_src, temp);
824 vmul = mem_dup(&mov, sizeof(midgard_instruction));
825 vmul->unit = UNIT_VMUL;
826 vmul->mask = 0xF ^ writeout_mask;
827 /* TODO: Don't leak */
828
829 /* Rewrite to use our temp */
830
831 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
832 if (stages[i])
833 mir_rewrite_index_dst_single(stages[i], src, temp);
834 }
835
836 mir_rewrite_index_src_single(branch, src, temp);
837 }
838 }
839
840 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
841
842 mir_update_worklist(worklist, len, instructions, vmul);
843 mir_update_worklist(worklist, len, instructions, sadd);
844
845 bundle.has_blend_constant = predicate.blend_constant;
846 bundle.has_embedded_constants = predicate.constant_count > 0;
847
848 unsigned padding = 0;
849
850 /* Now that we have finished scheduling, build up the bundle */
851 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
852
853 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
854 if (stages[i]) {
855 bundle.control |= stages[i]->unit;
856 bytes_emitted += bytes_for_instruction(stages[i]);
857 bundle.instructions[bundle.instruction_count++] = stages[i];
858 }
859 }
860
861 /* Pad ALU op to nearest word */
862
863 if (bytes_emitted & 15) {
864 padding = 16 - (bytes_emitted & 15);
865 bytes_emitted += padding;
866 }
867
868 /* Constants must always be quadwords */
869 if (bundle.has_embedded_constants)
870 bytes_emitted += 16;
871
872 /* Size ALU instruction for tag */
873 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
874 bundle.padding = padding;
875 bundle.control |= bundle.tag;
876
877 return bundle;
878 }
879
880 /* Schedule a single block by iterating its instruction to create bundles.
881 * While we go, tally about the bundle sizes to compute the block size. */
882
883
884 static void
885 schedule_block(compiler_context *ctx, midgard_block *block)
886 {
887 /* Copy list to dynamic array */
888 unsigned len = 0;
889 midgard_instruction **instructions = flatten_mir(block, &len);
890
891 if (!len)
892 return;
893
894 /* Calculate dependencies and initial worklist */
895 unsigned node_count = ctx->temp_count + 1;
896 mir_create_dependency_graph(instructions, len, node_count);
897
898 /* Allocate the worklist */
899 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
900 BITSET_WORD *worklist = calloc(sz, 1);
901 mir_initialize_worklist(worklist, instructions, len);
902
903 struct util_dynarray bundles;
904 util_dynarray_init(&bundles, NULL);
905
906 block->quadword_count = 0;
907 unsigned blend_offset = 0;
908
909 for (;;) {
910 unsigned tag = mir_choose_bundle(instructions, worklist, len);
911 midgard_bundle bundle;
912
913 if (tag == TAG_TEXTURE_4)
914 bundle = mir_schedule_texture(instructions, worklist, len);
915 else if (tag == TAG_LOAD_STORE_4)
916 bundle = mir_schedule_ldst(instructions, worklist, len);
917 else if (tag == TAG_ALU_4)
918 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
919 else
920 break;
921
922 util_dynarray_append(&bundles, midgard_bundle, bundle);
923
924 if (bundle.has_blend_constant)
925 blend_offset = block->quadword_count;
926
927 block->quadword_count += quadword_size(bundle.tag);
928 }
929
930 /* We emitted bundles backwards; copy into the block in reverse-order */
931
932 util_dynarray_init(&block->bundles, NULL);
933 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
934 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
935 }
936
937 /* Blend constant was backwards as well. blend_offset if set is
938 * strictly positive, as an offset of zero would imply constants before
939 * any instructions which is invalid in Midgard */
940
941 if (blend_offset)
942 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
943
944 block->is_scheduled = true;
945 ctx->quadword_count += block->quadword_count;
946
947 /* Reorder instructions to match bundled. First remove existing
948 * instructions and then recreate the list */
949
950 mir_foreach_instr_in_block_safe(block, ins) {
951 list_del(&ins->link);
952 }
953
954 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
955 list_add(&ins->link, &block->instructions);
956 }
957 }
958
959 /* When we're 'squeezing down' the values in the IR, we maintain a hash
960 * as such */
961
962 static unsigned
963 find_or_allocate_temp(compiler_context *ctx, unsigned hash)
964 {
965 if (hash >= SSA_FIXED_MINIMUM)
966 return hash;
967
968 unsigned temp = (uintptr_t) _mesa_hash_table_u64_search(
969 ctx->hash_to_temp, hash + 1);
970
971 if (temp)
972 return temp - 1;
973
974 /* If no temp is find, allocate one */
975 temp = ctx->temp_count++;
976 ctx->max_hash = MAX2(ctx->max_hash, hash);
977
978 _mesa_hash_table_u64_insert(ctx->hash_to_temp,
979 hash + 1, (void *) ((uintptr_t) temp + 1));
980
981 return temp;
982 }
983
984 /* Reassigns numbering to get rid of gaps in the indices */
985
986 static void
987 mir_squeeze_index(compiler_context *ctx)
988 {
989 /* Reset */
990 ctx->temp_count = 0;
991 /* TODO don't leak old hash_to_temp */
992 ctx->hash_to_temp = _mesa_hash_table_u64_create(NULL);
993
994 mir_foreach_instr_global(ctx, ins) {
995 ins->dest = find_or_allocate_temp(ctx, ins->dest);
996
997 for (unsigned i = 0; i < ARRAY_SIZE(ins->src); ++i)
998 ins->src[i] = find_or_allocate_temp(ctx, ins->src[i]);
999 }
1000 }
1001
1002 static midgard_instruction
1003 v_load_store_scratch(
1004 unsigned srcdest,
1005 unsigned index,
1006 bool is_store,
1007 unsigned mask)
1008 {
1009 /* We index by 32-bit vec4s */
1010 unsigned byte = (index * 4 * 4);
1011
1012 midgard_instruction ins = {
1013 .type = TAG_LOAD_STORE_4,
1014 .mask = mask,
1015 .dest = ~0,
1016 .src = { ~0, ~0, ~0 },
1017 .load_store = {
1018 .op = is_store ? midgard_op_st_int4 : midgard_op_ld_int4,
1019 .swizzle = SWIZZLE_XYZW,
1020
1021 /* For register spilling - to thread local storage */
1022 .arg_1 = 0xEA,
1023 .arg_2 = 0x1E,
1024
1025 /* Splattered across, TODO combine logically */
1026 .varying_parameters = (byte & 0x1FF) << 1,
1027 .address = (byte >> 9)
1028 },
1029
1030 /* If we spill an unspill, RA goes into an infinite loop */
1031 .no_spill = true
1032 };
1033
1034 if (is_store) {
1035 /* r0 = r26, r1 = r27 */
1036 assert(srcdest == SSA_FIXED_REGISTER(26) || srcdest == SSA_FIXED_REGISTER(27));
1037 ins.src[0] = srcdest;
1038 } else {
1039 ins.dest = srcdest;
1040 }
1041
1042 return ins;
1043 }
1044
1045 /* If register allocation fails, find the best spill node and spill it to fix
1046 * whatever the issue was. This spill node could be a work register (spilling
1047 * to thread local storage), but it could also simply be a special register
1048 * that needs to spill to become a work register. */
1049
1050 static void mir_spill_register(
1051 compiler_context *ctx,
1052 struct ra_graph *g,
1053 unsigned *spill_count)
1054 {
1055 unsigned spill_index = ctx->temp_count;
1056
1057 /* Our first step is to calculate spill cost to figure out the best
1058 * spill node. All nodes are equal in spill cost, but we can't spill
1059 * nodes written to from an unspill */
1060
1061 for (unsigned i = 0; i < ctx->temp_count; ++i) {
1062 ra_set_node_spill_cost(g, i, 1.0);
1063 }
1064
1065 /* We can't spill any bundles that contain unspills. This could be
1066 * optimized to allow use of r27 to spill twice per bundle, but if
1067 * you're at the point of optimizing spilling, it's too late. */
1068
1069 mir_foreach_block(ctx, block) {
1070 mir_foreach_bundle_in_block(block, bun) {
1071 bool no_spill = false;
1072
1073 for (unsigned i = 0; i < bun->instruction_count; ++i)
1074 no_spill |= bun->instructions[i]->no_spill;
1075
1076 if (!no_spill)
1077 continue;
1078
1079 for (unsigned i = 0; i < bun->instruction_count; ++i) {
1080 unsigned dest = bun->instructions[i]->dest;
1081 if (dest < ctx->temp_count)
1082 ra_set_node_spill_cost(g, dest, -1.0);
1083 }
1084 }
1085 }
1086
1087 int spill_node = ra_get_best_spill_node(g);
1088
1089 if (spill_node < 0) {
1090 mir_print_shader(ctx);
1091 assert(0);
1092 }
1093
1094 /* We have a spill node, so check the class. Work registers
1095 * legitimately spill to TLS, but special registers just spill to work
1096 * registers */
1097
1098 unsigned class = ra_get_node_class(g, spill_node);
1099 bool is_special = (class >> 2) != REG_CLASS_WORK;
1100 bool is_special_w = (class >> 2) == REG_CLASS_TEXW;
1101
1102 /* Allocate TLS slot (maybe) */
1103 unsigned spill_slot = !is_special ? (*spill_count)++ : 0;
1104
1105 /* For TLS, replace all stores to the spilled node. For
1106 * special reads, just keep as-is; the class will be demoted
1107 * implicitly. For special writes, spill to a work register */
1108
1109 if (!is_special || is_special_w) {
1110 if (is_special_w)
1111 spill_slot = spill_index++;
1112
1113 mir_foreach_block(ctx, block) {
1114 mir_foreach_instr_in_block_safe(block, ins) {
1115 if (ins->dest != spill_node) continue;
1116
1117 midgard_instruction st;
1118
1119 if (is_special_w) {
1120 st = v_mov(spill_node, blank_alu_src, spill_slot);
1121 st.no_spill = true;
1122 } else {
1123 ins->dest = SSA_FIXED_REGISTER(26);
1124 ins->no_spill = true;
1125 st = v_load_store_scratch(ins->dest, spill_slot, true, ins->mask);
1126 }
1127
1128 /* Hint: don't rewrite this node */
1129 st.hint = true;
1130
1131 mir_insert_instruction_after_scheduled(ctx, block, ins, st);
1132
1133 if (!is_special)
1134 ctx->spills++;
1135 }
1136 }
1137 }
1138
1139 /* For special reads, figure out how many components we need */
1140 unsigned read_mask = 0;
1141
1142 mir_foreach_instr_global_safe(ctx, ins) {
1143 read_mask |= mir_mask_of_read_components(ins, spill_node);
1144 }
1145
1146 /* Insert a load from TLS before the first consecutive
1147 * use of the node, rewriting to use spilled indices to
1148 * break up the live range. Or, for special, insert a
1149 * move. Ironically the latter *increases* register
1150 * pressure, but the two uses of the spilling mechanism
1151 * are somewhat orthogonal. (special spilling is to use
1152 * work registers to back special registers; TLS
1153 * spilling is to use memory to back work registers) */
1154
1155 mir_foreach_block(ctx, block) {
1156 bool consecutive_skip = false;
1157 unsigned consecutive_index = 0;
1158
1159 mir_foreach_instr_in_block(block, ins) {
1160 /* We can't rewrite the moves used to spill in the
1161 * first place. These moves are hinted. */
1162 if (ins->hint) continue;
1163
1164 if (!mir_has_arg(ins, spill_node)) {
1165 consecutive_skip = false;
1166 continue;
1167 }
1168
1169 if (consecutive_skip) {
1170 /* Rewrite */
1171 mir_rewrite_index_src_single(ins, spill_node, consecutive_index);
1172 continue;
1173 }
1174
1175 if (!is_special_w) {
1176 consecutive_index = ++spill_index;
1177
1178 midgard_instruction *before = ins;
1179
1180 /* For a csel, go back one more not to break up the bundle */
1181 if (ins->type == TAG_ALU_4 && OP_IS_CSEL(ins->alu.op))
1182 before = mir_prev_op(before);
1183
1184 midgard_instruction st;
1185
1186 if (is_special) {
1187 /* Move */
1188 st = v_mov(spill_node, blank_alu_src, consecutive_index);
1189 st.no_spill = true;
1190 } else {
1191 /* TLS load */
1192 st = v_load_store_scratch(consecutive_index, spill_slot, false, 0xF);
1193 }
1194
1195 /* Mask the load based on the component count
1196 * actually needed to prvent RA loops */
1197
1198 st.mask = read_mask;
1199
1200 mir_insert_instruction_before_scheduled(ctx, block, before, st);
1201 // consecutive_skip = true;
1202 } else {
1203 /* Special writes already have their move spilled in */
1204 consecutive_index = spill_slot;
1205 }
1206
1207
1208 /* Rewrite to use */
1209 mir_rewrite_index_src_single(ins, spill_node, consecutive_index);
1210
1211 if (!is_special)
1212 ctx->fills++;
1213 }
1214 }
1215
1216 /* Reset hints */
1217
1218 mir_foreach_instr_global(ctx, ins) {
1219 ins->hint = false;
1220 }
1221 }
1222
1223 void
1224 schedule_program(compiler_context *ctx)
1225 {
1226 struct ra_graph *g = NULL;
1227 bool spilled = false;
1228 int iter_count = 1000; /* max iterations */
1229
1230 /* Number of 128-bit slots in memory we've spilled into */
1231 unsigned spill_count = 0;
1232
1233 midgard_promote_uniforms(ctx, 16);
1234
1235 /* Must be lowered right before RA */
1236 mir_squeeze_index(ctx);
1237 mir_lower_special_reads(ctx);
1238 mir_squeeze_index(ctx);
1239
1240 /* Lowering can introduce some dead moves */
1241
1242 mir_foreach_block(ctx, block) {
1243 midgard_opt_dead_move_eliminate(ctx, block);
1244 schedule_block(ctx, block);
1245 }
1246
1247 mir_create_pipeline_registers(ctx);
1248
1249 do {
1250 if (spilled)
1251 mir_spill_register(ctx, g, &spill_count);
1252
1253 mir_squeeze_index(ctx);
1254
1255 g = NULL;
1256 g = allocate_registers(ctx, &spilled);
1257 } while(spilled && ((iter_count--) > 0));
1258
1259 if (iter_count <= 0) {
1260 fprintf(stderr, "panfrost: Gave up allocating registers, rendering will be incomplete\n");
1261 assert(0);
1262 }
1263
1264 /* Report spilling information. spill_count is in 128-bit slots (vec4 x
1265 * fp32), but tls_size is in bytes, so multiply by 16 */
1266
1267 ctx->tls_size = spill_count * 16;
1268
1269 install_registers(ctx, g);
1270 }