pan/mdg: Remove redundant redundancy
[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 "midgard_quirks.h"
27 #include "util/u_memory.h"
28 #include "util/u_math.h"
29
30 /* Scheduling for Midgard is complicated, to say the least. ALU instructions
31 * must be grouped into VLIW bundles according to following model:
32 *
33 * [VMUL] [SADD]
34 * [VADD] [SMUL] [VLUT]
35 *
36 * A given instruction can execute on some subset of the units (or a few can
37 * execute on all). Instructions can be either vector or scalar; only scalar
38 * instructions can execute on SADD/SMUL units. Units on a given line execute
39 * in parallel. Subsequent lines execute separately and can pass results
40 * directly via pipeline registers r24/r25, bypassing the register file.
41 *
42 * A bundle can optionally have 128-bits of embedded constants, shared across
43 * all of the instructions within a bundle.
44 *
45 * Instructions consuming conditionals (branches and conditional selects)
46 * require their condition to be written into the conditional register (r31)
47 * within the same bundle they are consumed.
48 *
49 * Fragment writeout requires its argument to be written in full within the
50 * same bundle as the branch, with no hanging dependencies.
51 *
52 * Load/store instructions are also in bundles of simply two instructions, and
53 * texture instructions have no bundling.
54 *
55 * -------------------------------------------------------------------------
56 *
57 */
58
59 /* We create the dependency graph with per-byte granularity */
60
61 #define BYTE_COUNT 16
62
63 static void
64 add_dependency(struct util_dynarray *table, unsigned index, uint16_t mask, midgard_instruction **instructions, unsigned child)
65 {
66 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
67 if (!(mask & (1 << i)))
68 continue;
69
70 struct util_dynarray *parents = &table[(BYTE_COUNT * index) + i];
71
72 util_dynarray_foreach(parents, unsigned, parent) {
73 BITSET_WORD *dependents = instructions[*parent]->dependents;
74
75 /* Already have the dependency */
76 if (BITSET_TEST(dependents, child))
77 continue;
78
79 BITSET_SET(dependents, child);
80 instructions[child]->nr_dependencies++;
81 }
82 }
83 }
84
85 static void
86 mark_access(struct util_dynarray *table, unsigned index, uint16_t mask, unsigned parent)
87 {
88 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
89 if (!(mask & (1 << i)))
90 continue;
91
92 util_dynarray_append(&table[(BYTE_COUNT * index) + i], unsigned, parent);
93 }
94 }
95
96 static void
97 mir_create_dependency_graph(midgard_instruction **instructions, unsigned count, unsigned node_count)
98 {
99 size_t sz = node_count * BYTE_COUNT;
100
101 struct util_dynarray *last_read = calloc(sizeof(struct util_dynarray), sz);
102 struct util_dynarray *last_write = calloc(sizeof(struct util_dynarray), sz);
103
104 for (unsigned i = 0; i < sz; ++i) {
105 util_dynarray_init(&last_read[i], NULL);
106 util_dynarray_init(&last_write[i], NULL);
107 }
108
109 /* Initialize dependency graph */
110 for (unsigned i = 0; i < count; ++i) {
111 instructions[i]->dependents =
112 calloc(BITSET_WORDS(count), sizeof(BITSET_WORD));
113
114 instructions[i]->nr_dependencies = 0;
115 }
116
117 /* Populate dependency graph */
118 for (signed i = count - 1; i >= 0; --i) {
119 if (instructions[i]->compact_branch)
120 continue;
121
122 unsigned dest = instructions[i]->dest;
123 unsigned mask = mir_bytemask(instructions[i]);
124
125 mir_foreach_src((*instructions), s) {
126 unsigned src = instructions[i]->src[s];
127
128 if (src < node_count) {
129 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
130 add_dependency(last_write, src, readmask, instructions, i);
131 }
132 }
133
134 if (dest < node_count) {
135 add_dependency(last_read, dest, mask, instructions, i);
136 add_dependency(last_write, dest, mask, instructions, i);
137 mark_access(last_write, dest, mask, i);
138 }
139
140 mir_foreach_src((*instructions), s) {
141 unsigned src = instructions[i]->src[s];
142
143 if (src < node_count) {
144 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
145 mark_access(last_read, src, readmask, i);
146 }
147 }
148 }
149
150 /* If there is a branch, all instructions depend on it, as interblock
151 * execution must be purely in-order */
152
153 if (instructions[count - 1]->compact_branch) {
154 BITSET_WORD *dependents = instructions[count - 1]->dependents;
155
156 for (signed i = count - 2; i >= 0; --i) {
157 if (BITSET_TEST(dependents, i))
158 continue;
159
160 BITSET_SET(dependents, i);
161 instructions[i]->nr_dependencies++;
162 }
163 }
164
165 /* Free the intermediate structures */
166 for (unsigned i = 0; i < sz; ++i) {
167 util_dynarray_fini(&last_read[i]);
168 util_dynarray_fini(&last_write[i]);
169 }
170
171 free(last_read);
172 free(last_write);
173 }
174
175 /* Does the mask cover more than a scalar? */
176
177 static bool
178 is_single_component_mask(unsigned mask)
179 {
180 int components = 0;
181
182 for (int c = 0; c < 8; ++c) {
183 if (mask & (1 << c))
184 components++;
185 }
186
187 return components == 1;
188 }
189
190 /* Helpers for scheudling */
191
192 static bool
193 mir_is_scalar(midgard_instruction *ains)
194 {
195 /* Do we try to use it as a vector op? */
196 if (!is_single_component_mask(ains->mask))
197 return false;
198
199 /* Otherwise, check mode hazards */
200 bool could_scalar = true;
201 unsigned sz0 = nir_alu_type_get_type_size(ains->src_types[0]);
202 unsigned sz1 = nir_alu_type_get_type_size(ains->src_types[1]);
203
204 /* Only 16/32-bit can run on a scalar unit */
205 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_8;
206 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_64;
207 could_scalar &= ains->alu.dest_override == midgard_dest_override_none;
208
209 if (ains->src[0] != ~0)
210 could_scalar &= (sz0 == 16) || (sz0 == 32);
211
212 if (ains->src[1] != ~0)
213 could_scalar &= (sz1 == 16) || (sz1 == 32);
214
215 return could_scalar;
216 }
217
218 /* How many bytes does this ALU instruction add to the bundle? */
219
220 static unsigned
221 bytes_for_instruction(midgard_instruction *ains)
222 {
223 if (ains->unit & UNITS_ANY_VECTOR)
224 return sizeof(midgard_reg_info) + sizeof(midgard_vector_alu);
225 else if (ains->unit == ALU_ENAB_BRANCH)
226 return sizeof(midgard_branch_extended);
227 else if (ains->compact_branch)
228 return sizeof(ains->br_compact);
229 else
230 return sizeof(midgard_reg_info) + sizeof(midgard_scalar_alu);
231 }
232
233 /* We would like to flatten the linked list of midgard_instructions in a bundle
234 * to an array of pointers on the heap for easy indexing */
235
236 static midgard_instruction **
237 flatten_mir(midgard_block *block, unsigned *len)
238 {
239 *len = list_length(&block->base.instructions);
240
241 if (!(*len))
242 return NULL;
243
244 midgard_instruction **instructions =
245 calloc(sizeof(midgard_instruction *), *len);
246
247 unsigned i = 0;
248
249 mir_foreach_instr_in_block(block, ins)
250 instructions[i++] = ins;
251
252 return instructions;
253 }
254
255 /* The worklist is the set of instructions that can be scheduled now; that is,
256 * the set of instructions with no remaining dependencies */
257
258 static void
259 mir_initialize_worklist(BITSET_WORD *worklist, midgard_instruction **instructions, unsigned count)
260 {
261 for (unsigned i = 0; i < count; ++i) {
262 if (instructions[i]->nr_dependencies == 0)
263 BITSET_SET(worklist, i);
264 }
265 }
266
267 /* Update the worklist after an instruction terminates. Remove its edges from
268 * the graph and if that causes any node to have no dependencies, add it to the
269 * worklist */
270
271 static void
272 mir_update_worklist(
273 BITSET_WORD *worklist, unsigned count,
274 midgard_instruction **instructions, midgard_instruction *done)
275 {
276 /* Sanity check: if no instruction terminated, there is nothing to do.
277 * If the instruction that terminated had dependencies, that makes no
278 * sense and means we messed up the worklist. Finally, as the purpose
279 * of this routine is to update dependents, we abort early if there are
280 * no dependents defined. */
281
282 if (!done)
283 return;
284
285 assert(done->nr_dependencies == 0);
286
287 if (!done->dependents)
288 return;
289
290 /* We have an instruction with dependents. Iterate each dependent to
291 * remove one dependency (`done`), adding dependents to the worklist
292 * where possible. */
293
294 unsigned i;
295 BITSET_FOREACH_SET(i, done->dependents, count) {
296 assert(instructions[i]->nr_dependencies);
297
298 if (!(--instructions[i]->nr_dependencies))
299 BITSET_SET(worklist, i);
300 }
301
302 free(done->dependents);
303 }
304
305 /* While scheduling, we need to choose instructions satisfying certain
306 * criteria. As we schedule backwards, we choose the *last* instruction in the
307 * worklist to simulate in-order scheduling. Chosen instructions must satisfy a
308 * given predicate. */
309
310 struct midgard_predicate {
311 /* TAG or ~0 for dont-care */
312 unsigned tag;
313
314 /* True if we want to pop off the chosen instruction */
315 bool destructive;
316
317 /* For ALU, choose only this unit */
318 unsigned unit;
319
320 /* State for bundle constants. constants is the actual constants
321 * for the bundle. constant_count is the number of bytes (up to
322 * 16) currently in use for constants. When picking in destructive
323 * mode, the constants array will be updated, and the instruction
324 * will be adjusted to index into the constants array */
325
326 midgard_constants *constants;
327 unsigned constant_mask;
328 bool blend_constant;
329
330 /* Exclude this destination (if not ~0) */
331 unsigned exclude;
332
333 /* Don't schedule instructions consuming conditionals (since we already
334 * scheduled one). Excludes conditional branches and csel */
335 bool no_cond;
336
337 /* Require a minimal mask and (if nonzero) given destination. Used for
338 * writeout optimizations */
339
340 unsigned mask;
341 unsigned dest;
342
343 /* For load/store: how many pipeline registers are in use? The two
344 * scheduled instructions cannot use more than the 256-bits of pipeline
345 * space available or RA will fail (as it would run out of pipeline
346 * registers and fail to spill without breaking the schedule) */
347
348 unsigned pipeline_count;
349 };
350
351 /* For an instruction that can fit, adjust it to fit and update the constants
352 * array, in destructive mode. Returns whether the fitting was successful. */
353
354 static bool
355 mir_adjust_constants(midgard_instruction *ins,
356 struct midgard_predicate *pred,
357 bool destructive)
358 {
359 /* Blend constants dominate */
360 if (ins->has_blend_constant) {
361 if (pred->constant_mask)
362 return false;
363 else if (destructive) {
364 pred->blend_constant = true;
365 pred->constant_mask = 0xffff;
366 return true;
367 }
368 }
369
370 /* No constant, nothing to adjust */
371 if (!ins->has_constants)
372 return true;
373
374 unsigned r_constant = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
375 unsigned bundle_constant_mask = pred->constant_mask;
376 unsigned comp_mapping[2][16] = { };
377 uint8_t bundle_constants[16];
378
379 memcpy(bundle_constants, pred->constants, 16);
380
381 /* Let's try to find a place for each active component of the constant
382 * register.
383 */
384 for (unsigned src = 0; src < 2; ++src) {
385 if (ins->src[src] != SSA_FIXED_REGISTER(REGISTER_CONSTANT))
386 continue;
387
388 unsigned type_size = nir_alu_type_get_type_size(ins->src_types[src]) / 8;
389 unsigned max_comp = 16 / type_size;
390 unsigned comp_mask = mir_from_bytemask(mir_round_bytemask_up(
391 mir_bytemask_of_read_components_index(ins, src),
392 type_size * 8),
393 type_size * 8);
394 unsigned type_mask = (1 << type_size) - 1;
395
396 for (unsigned comp = 0; comp < max_comp; comp++) {
397 if (!(comp_mask & (1 << comp)))
398 continue;
399
400 uint8_t *constantp = ins->constants.u8 + (type_size * comp);
401 unsigned best_reuse_bytes = 0;
402 signed best_place = -1;
403 unsigned i, j;
404
405 for (i = 0; i < 16; i += type_size) {
406 unsigned reuse_bytes = 0;
407
408 for (j = 0; j < type_size; j++) {
409 if (!(bundle_constant_mask & (1 << (i + j))))
410 continue;
411 if (constantp[j] != bundle_constants[i + j])
412 break;
413
414 reuse_bytes++;
415 }
416
417 /* Select the place where existing bytes can be
418 * reused so we leave empty slots to others
419 */
420 if (j == type_size &&
421 (reuse_bytes > best_reuse_bytes || best_place < 0)) {
422 best_reuse_bytes = reuse_bytes;
423 best_place = i;
424 break;
425 }
426 }
427
428 /* This component couldn't fit in the remaining constant slot,
429 * no need check the remaining components, bail out now
430 */
431 if (best_place < 0)
432 return false;
433
434 memcpy(&bundle_constants[i], constantp, type_size);
435 bundle_constant_mask |= type_mask << best_place;
436 comp_mapping[src][comp] = best_place / type_size;
437 }
438 }
439
440 /* If non-destructive, we're done */
441 if (!destructive)
442 return true;
443
444 /* Otherwise update the constant_mask and constant values */
445 pred->constant_mask = bundle_constant_mask;
446 memcpy(pred->constants, bundle_constants, 16);
447
448 /* Use comp_mapping as a swizzle */
449 mir_foreach_src(ins, s) {
450 if (ins->src[s] == r_constant)
451 mir_compose_swizzle(ins->swizzle[s], comp_mapping[s], ins->swizzle[s]);
452 }
453
454 return true;
455 }
456
457 /* Conservative estimate of the pipeline registers required for load/store */
458
459 static unsigned
460 mir_pipeline_count(midgard_instruction *ins)
461 {
462 unsigned bytecount = 0;
463
464 mir_foreach_src(ins, i) {
465 /* Skip empty source */
466 if (ins->src[i] == ~0) continue;
467
468 unsigned bytemask = mir_bytemask_of_read_components_index(ins, i);
469
470 unsigned max = util_logbase2(bytemask) + 1;
471 bytecount += max;
472 }
473
474 return DIV_ROUND_UP(bytecount, 16);
475 }
476
477 static midgard_instruction *
478 mir_choose_instruction(
479 midgard_instruction **instructions,
480 BITSET_WORD *worklist, unsigned count,
481 struct midgard_predicate *predicate)
482 {
483 /* Parse the predicate */
484 unsigned tag = predicate->tag;
485 bool alu = tag == TAG_ALU_4;
486 bool ldst = tag == TAG_LOAD_STORE_4;
487 unsigned unit = predicate->unit;
488 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
489 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
490 bool no_cond = predicate->no_cond;
491
492 unsigned mask = predicate->mask;
493 unsigned dest = predicate->dest;
494 bool needs_dest = mask & 0xF;
495
496 /* Iterate to find the best instruction satisfying the predicate */
497 unsigned i;
498
499 signed best_index = -1;
500 bool best_conditional = false;
501
502 /* Enforce a simple metric limiting distance to keep down register
503 * pressure. TOOD: replace with liveness tracking for much better
504 * results */
505
506 unsigned max_active = 0;
507 unsigned max_distance = 6;
508
509 BITSET_FOREACH_SET(i, worklist, count) {
510 max_active = MAX2(max_active, i);
511 }
512
513 BITSET_FOREACH_SET(i, worklist, count) {
514 if ((max_active - i) >= max_distance)
515 continue;
516
517 if (tag != ~0 && instructions[i]->type != tag)
518 continue;
519
520 if (predicate->exclude != ~0 && instructions[i]->dest == predicate->exclude)
521 continue;
522
523 if (alu && !branch && !(alu_opcode_props[instructions[i]->alu.op].props & unit))
524 continue;
525
526 if (branch && !instructions[i]->compact_branch)
527 continue;
528
529 if (alu && scalar && !mir_is_scalar(instructions[i]))
530 continue;
531
532 if (alu && !mir_adjust_constants(instructions[i], predicate, false))
533 continue;
534
535 if (needs_dest && instructions[i]->dest != dest)
536 continue;
537
538 if (mask && ((~instructions[i]->mask) & mask))
539 continue;
540
541 if (ldst && mir_pipeline_count(instructions[i]) + predicate->pipeline_count > 2)
542 continue;
543
544 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
545 conditional |= (branch && instructions[i]->branch.conditional);
546
547 if (conditional && no_cond)
548 continue;
549
550 /* Simulate in-order scheduling */
551 if ((signed) i < best_index)
552 continue;
553
554 best_index = i;
555 best_conditional = conditional;
556 }
557
558
559 /* Did we find anything? */
560
561 if (best_index < 0)
562 return NULL;
563
564 /* If we found something, remove it from the worklist */
565 assert(best_index < count);
566
567 if (predicate->destructive) {
568 BITSET_CLEAR(worklist, best_index);
569
570 if (alu)
571 mir_adjust_constants(instructions[best_index], predicate, true);
572
573 if (ldst)
574 predicate->pipeline_count += mir_pipeline_count(instructions[best_index]);
575
576 /* Once we schedule a conditional, we can't again */
577 predicate->no_cond |= best_conditional;
578 }
579
580 return instructions[best_index];
581 }
582
583 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
584 * best bundle type (ALU, load/store, texture). Nondestructive. */
585
586 static unsigned
587 mir_choose_bundle(
588 midgard_instruction **instructions,
589 BITSET_WORD *worklist, unsigned count)
590 {
591 /* At the moment, our algorithm is very simple - use the bundle of the
592 * best instruction, regardless of what else could be scheduled
593 * alongside it. This is not optimal but it works okay for in-order */
594
595 struct midgard_predicate predicate = {
596 .tag = ~0,
597 .destructive = false,
598 .exclude = ~0
599 };
600
601 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
602
603 if (chosen)
604 return chosen->type;
605 else
606 return ~0;
607 }
608
609 /* We want to choose an ALU instruction filling a given unit */
610 static void
611 mir_choose_alu(midgard_instruction **slot,
612 midgard_instruction **instructions,
613 BITSET_WORD *worklist, unsigned len,
614 struct midgard_predicate *predicate,
615 unsigned unit)
616 {
617 /* Did we already schedule to this slot? */
618 if ((*slot) != NULL)
619 return;
620
621 /* Try to schedule something, if not */
622 predicate->unit = unit;
623 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
624
625 /* Store unit upon scheduling */
626 if (*slot && !((*slot)->compact_branch))
627 (*slot)->unit = unit;
628 }
629
630 /* When we are scheduling a branch/csel, we need the consumed condition in the
631 * same block as a pipeline register. There are two options to enable this:
632 *
633 * - Move the conditional into the bundle. Preferred, but only works if the
634 * conditional is used only once and is from this block.
635 * - Copy the conditional.
636 *
637 * We search for the conditional. If it's in this block, single-use, and
638 * without embedded constants, we schedule it immediately. Otherwise, we
639 * schedule a move for it.
640 *
641 * mir_comparison_mobile is a helper to find the moveable condition.
642 */
643
644 static unsigned
645 mir_comparison_mobile(
646 compiler_context *ctx,
647 midgard_instruction **instructions,
648 struct midgard_predicate *predicate,
649 unsigned count,
650 unsigned cond)
651 {
652 if (!mir_single_use(ctx, cond))
653 return ~0;
654
655 unsigned ret = ~0;
656
657 for (unsigned i = 0; i < count; ++i) {
658 if (instructions[i]->dest != cond)
659 continue;
660
661 /* Must fit in an ALU bundle */
662 if (instructions[i]->type != TAG_ALU_4)
663 return ~0;
664
665 /* If it would itself require a condition, that's recursive */
666 if (OP_IS_CSEL(instructions[i]->alu.op))
667 return ~0;
668
669 /* We'll need to rewrite to .w but that doesn't work for vector
670 * ops that don't replicate (ball/bany), so bail there */
671
672 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
673 return ~0;
674
675 /* Ensure it will fit with constants */
676
677 if (!mir_adjust_constants(instructions[i], predicate, false))
678 return ~0;
679
680 /* Ensure it is written only once */
681
682 if (ret != ~0)
683 return ~0;
684 else
685 ret = i;
686 }
687
688 /* Inject constants now that we are sure we want to */
689 if (ret != ~0)
690 mir_adjust_constants(instructions[ret], predicate, true);
691
692 return ret;
693 }
694
695 /* Using the information about the moveable conditional itself, we either pop
696 * that condition off the worklist for use now, or create a move to
697 * artificially schedule instead as a fallback */
698
699 static midgard_instruction *
700 mir_schedule_comparison(
701 compiler_context *ctx,
702 midgard_instruction **instructions,
703 struct midgard_predicate *predicate,
704 BITSET_WORD *worklist, unsigned count,
705 unsigned cond, bool vector, unsigned *swizzle,
706 midgard_instruction *user)
707 {
708 /* TODO: swizzle when scheduling */
709 unsigned comp_i =
710 (!vector && (swizzle[0] == 0)) ?
711 mir_comparison_mobile(ctx, instructions, predicate, count, cond) : ~0;
712
713 /* If we can, schedule the condition immediately */
714 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
715 assert(comp_i < count);
716 BITSET_CLEAR(worklist, comp_i);
717 return instructions[comp_i];
718 }
719
720 /* Otherwise, we insert a move */
721
722 midgard_instruction mov = v_mov(cond, cond);
723 mov.mask = vector ? 0xF : 0x1;
724 memcpy(mov.swizzle[1], swizzle, sizeof(mov.swizzle[1]));
725
726 return mir_insert_instruction_before(ctx, user, mov);
727 }
728
729 /* Most generally, we need instructions writing to r31 in the appropriate
730 * components */
731
732 static midgard_instruction *
733 mir_schedule_condition(compiler_context *ctx,
734 struct midgard_predicate *predicate,
735 BITSET_WORD *worklist, unsigned count,
736 midgard_instruction **instructions,
737 midgard_instruction *last)
738 {
739 /* For a branch, the condition is the only argument; for csel, third */
740 bool branch = last->compact_branch;
741 unsigned condition_index = branch ? 0 : 2;
742
743 /* csel_v is vector; otherwise, conditions are scalar */
744 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
745
746 /* Grab the conditional instruction */
747
748 midgard_instruction *cond = mir_schedule_comparison(
749 ctx, instructions, predicate, worklist, count, last->src[condition_index],
750 vector, last->swizzle[2], last);
751
752 /* We have exclusive reign over this (possibly move) conditional
753 * instruction. We can rewrite into a pipeline conditional register */
754
755 predicate->exclude = cond->dest;
756 cond->dest = SSA_FIXED_REGISTER(31);
757
758 if (!vector) {
759 cond->mask = (1 << COMPONENT_W);
760
761 mir_foreach_src(cond, s) {
762 if (cond->src[s] == ~0)
763 continue;
764
765 for (unsigned q = 0; q < 4; ++q)
766 cond->swizzle[s][q + COMPONENT_W] = cond->swizzle[s][q];
767 }
768 }
769
770 /* Schedule the unit: csel is always in the latter pipeline, so a csel
771 * condition must be in the former pipeline stage (vmul/sadd),
772 * depending on scalar/vector of the instruction itself. A branch must
773 * be written from the latter pipeline stage and a branch condition is
774 * always scalar, so it is always in smul (exception: ball/bany, which
775 * will be vadd) */
776
777 if (branch)
778 cond->unit = UNIT_SMUL;
779 else
780 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
781
782 return cond;
783 }
784
785 /* Schedules a single bundle of the given type */
786
787 static midgard_bundle
788 mir_schedule_texture(
789 midgard_instruction **instructions,
790 BITSET_WORD *worklist, unsigned len)
791 {
792 struct midgard_predicate predicate = {
793 .tag = TAG_TEXTURE_4,
794 .destructive = true,
795 .exclude = ~0
796 };
797
798 midgard_instruction *ins =
799 mir_choose_instruction(instructions, worklist, len, &predicate);
800
801 mir_update_worklist(worklist, len, instructions, ins);
802
803 struct midgard_bundle out = {
804 .tag = ins->texture.op == TEXTURE_OP_BARRIER ?
805 TAG_TEXTURE_4_BARRIER : TAG_TEXTURE_4,
806 .instruction_count = 1,
807 .instructions = { ins }
808 };
809
810 return out;
811 }
812
813 static midgard_bundle
814 mir_schedule_ldst(
815 midgard_instruction **instructions,
816 BITSET_WORD *worklist, unsigned len)
817 {
818 struct midgard_predicate predicate = {
819 .tag = TAG_LOAD_STORE_4,
820 .destructive = true,
821 .exclude = ~0
822 };
823
824 /* Try to pick two load/store ops. Second not gauranteed to exist */
825
826 midgard_instruction *ins =
827 mir_choose_instruction(instructions, worklist, len, &predicate);
828
829 midgard_instruction *pair =
830 mir_choose_instruction(instructions, worklist, len, &predicate);
831
832 struct midgard_bundle out = {
833 .tag = TAG_LOAD_STORE_4,
834 .instruction_count = pair ? 2 : 1,
835 .instructions = { ins, pair }
836 };
837
838 /* We have to update the worklist atomically, since the two
839 * instructions run concurrently (TODO: verify it's not pipelined) */
840
841 mir_update_worklist(worklist, len, instructions, ins);
842 mir_update_worklist(worklist, len, instructions, pair);
843
844 return out;
845 }
846
847 static midgard_bundle
848 mir_schedule_alu(
849 compiler_context *ctx,
850 midgard_instruction **instructions,
851 BITSET_WORD *worklist, unsigned len)
852 {
853 struct midgard_bundle bundle = {};
854
855 unsigned bytes_emitted = sizeof(bundle.control);
856
857 struct midgard_predicate predicate = {
858 .tag = TAG_ALU_4,
859 .destructive = true,
860 .exclude = ~0,
861 .constants = &bundle.constants
862 };
863
864 midgard_instruction *vmul = NULL;
865 midgard_instruction *vadd = NULL;
866 midgard_instruction *vlut = NULL;
867 midgard_instruction *smul = NULL;
868 midgard_instruction *sadd = NULL;
869 midgard_instruction *branch = NULL;
870
871 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
872 mir_update_worklist(worklist, len, instructions, branch);
873 bool writeout = branch && branch->writeout;
874 bool zs_writeout = writeout && (branch->writeout_depth | branch->writeout_stencil);
875
876 if (branch && branch->branch.conditional) {
877 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
878
879 if (cond->unit == UNIT_VADD)
880 vadd = cond;
881 else if (cond->unit == UNIT_SMUL)
882 smul = cond;
883 else
884 unreachable("Bad condition");
885 }
886
887 /* If we have a render target reference, schedule a move for it. Since
888 * this will be in sadd, we boost this to prevent scheduling csel into
889 * smul */
890
891 if (writeout && (branch->constants.u32[0] || ctx->is_blend)) {
892 sadd = ralloc(ctx, midgard_instruction);
893 *sadd = v_mov(~0, make_compiler_temp(ctx));
894 sadd->unit = UNIT_SADD;
895 sadd->mask = 0x1;
896 sadd->has_inline_constant = true;
897 sadd->inline_constant = branch->constants.u32[0];
898 branch->src[1] = sadd->dest;
899 branch->src_types[1] = sadd->dest_type;
900
901 /* Mask off any conditionals. Could be optimized to just scalar
902 * conditionals TODO */
903 predicate.no_cond = true;
904 }
905
906 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
907
908 if (!writeout) {
909 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
910 } else {
911 /* Propagate up */
912 bundle.last_writeout = branch->last_writeout;
913 }
914
915 if (writeout && !zs_writeout) {
916 vadd = ralloc(ctx, midgard_instruction);
917 *vadd = v_mov(~0, make_compiler_temp(ctx));
918
919 if (!ctx->is_blend) {
920 vadd->alu.op = midgard_alu_op_iadd;
921 vadd->src[0] = SSA_FIXED_REGISTER(31);
922 vadd->src_types[0] = nir_type_uint32;
923
924 for (unsigned c = 0; c < 16; ++c)
925 vadd->swizzle[0][c] = COMPONENT_X;
926
927 vadd->has_inline_constant = true;
928 vadd->inline_constant = 0;
929 } else {
930 vadd->src[1] = SSA_FIXED_REGISTER(1);
931 vadd->src_types[0] = nir_type_uint32;
932
933 for (unsigned c = 0; c < 16; ++c)
934 vadd->swizzle[1][c] = COMPONENT_W;
935 }
936
937 vadd->unit = UNIT_VADD;
938 vadd->mask = 0x1;
939 branch->src[2] = vadd->dest;
940 branch->src_types[2] = vadd->dest_type;
941 }
942
943 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
944
945 mir_update_worklist(worklist, len, instructions, vlut);
946 mir_update_worklist(worklist, len, instructions, vadd);
947 mir_update_worklist(worklist, len, instructions, smul);
948
949 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
950 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
951
952 if (vadd_csel || smul_csel) {
953 midgard_instruction *ins = vadd_csel ? vadd : smul;
954 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
955
956 if (cond->unit == UNIT_VMUL)
957 vmul = cond;
958 else if (cond->unit == UNIT_SADD)
959 sadd = cond;
960 else
961 unreachable("Bad condition");
962 }
963
964 /* Stage 2, let's schedule sadd before vmul for writeout */
965 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
966
967 /* Check if writeout reads its own register */
968
969 if (writeout) {
970 midgard_instruction *stages[] = { sadd, vadd, smul };
971 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(zs_writeout ? 1 : 0) : branch->src[0];
972 unsigned writeout_mask = 0x0;
973 bool bad_writeout = false;
974
975 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
976 if (!stages[i])
977 continue;
978
979 if (stages[i]->dest != src)
980 continue;
981
982 writeout_mask |= stages[i]->mask;
983 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
984 }
985
986 /* It's possible we'll be able to schedule something into vmul
987 * to fill r0/r1. Let's peak into the future, trying to schedule
988 * vmul specially that way. */
989
990 unsigned full_mask = zs_writeout ?
991 (1 << (branch->writeout_depth + branch->writeout_stencil)) - 1 :
992 0xF;
993
994 if (!bad_writeout && writeout_mask != full_mask) {
995 predicate.unit = UNIT_VMUL;
996 predicate.dest = src;
997 predicate.mask = writeout_mask ^ full_mask;
998
999 struct midgard_instruction *peaked =
1000 mir_choose_instruction(instructions, worklist, len, &predicate);
1001
1002 if (peaked) {
1003 vmul = peaked;
1004 vmul->unit = UNIT_VMUL;
1005 writeout_mask |= predicate.mask;
1006 assert(writeout_mask == full_mask);
1007 }
1008
1009 /* Cleanup */
1010 predicate.dest = predicate.mask = 0;
1011 }
1012
1013 /* Finally, add a move if necessary */
1014 if (bad_writeout || writeout_mask != full_mask) {
1015 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(zs_writeout ? 1 : 0) : make_compiler_temp(ctx);
1016
1017 vmul = ralloc(ctx, midgard_instruction);
1018 *vmul = v_mov(src, temp);
1019 vmul->unit = UNIT_VMUL;
1020 vmul->mask = full_mask ^ writeout_mask;
1021
1022 /* Rewrite to use our temp */
1023
1024 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1025 if (stages[i])
1026 mir_rewrite_index_dst_single(stages[i], src, temp);
1027 }
1028
1029 mir_rewrite_index_src_single(branch, src, temp);
1030 }
1031 }
1032
1033 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
1034
1035 mir_update_worklist(worklist, len, instructions, vmul);
1036 mir_update_worklist(worklist, len, instructions, sadd);
1037
1038 bundle.has_blend_constant = predicate.blend_constant;
1039 bundle.has_embedded_constants = predicate.constant_mask != 0;
1040
1041 unsigned padding = 0;
1042
1043 /* Now that we have finished scheduling, build up the bundle */
1044 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
1045
1046 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1047 if (stages[i]) {
1048 bundle.control |= stages[i]->unit;
1049 bytes_emitted += bytes_for_instruction(stages[i]);
1050 bundle.instructions[bundle.instruction_count++] = stages[i];
1051
1052 /* If we branch, we can't spill to TLS since the store
1053 * instruction will never get executed. We could try to
1054 * break the bundle but this is probably easier for
1055 * now. */
1056
1057 if (branch)
1058 stages[i]->no_spill |= (1 << REG_CLASS_WORK);
1059 }
1060 }
1061
1062 /* Pad ALU op to nearest word */
1063
1064 if (bytes_emitted & 15) {
1065 padding = 16 - (bytes_emitted & 15);
1066 bytes_emitted += padding;
1067 }
1068
1069 /* Constants must always be quadwords */
1070 if (bundle.has_embedded_constants)
1071 bytes_emitted += 16;
1072
1073 /* Size ALU instruction for tag */
1074 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
1075
1076 /* MRT capable GPUs use a special writeout procedure */
1077 if (writeout && !(ctx->quirks & MIDGARD_NO_UPPER_ALU))
1078 bundle.tag += 4;
1079
1080 bundle.padding = padding;
1081 bundle.control |= bundle.tag;
1082
1083 return bundle;
1084 }
1085
1086 /* Schedule a single block by iterating its instruction to create bundles.
1087 * While we go, tally about the bundle sizes to compute the block size. */
1088
1089
1090 static void
1091 schedule_block(compiler_context *ctx, midgard_block *block)
1092 {
1093 /* Copy list to dynamic array */
1094 unsigned len = 0;
1095 midgard_instruction **instructions = flatten_mir(block, &len);
1096
1097 if (!len)
1098 return;
1099
1100 /* Calculate dependencies and initial worklist */
1101 unsigned node_count = ctx->temp_count + 1;
1102 mir_create_dependency_graph(instructions, len, node_count);
1103
1104 /* Allocate the worklist */
1105 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
1106 BITSET_WORD *worklist = calloc(sz, 1);
1107 mir_initialize_worklist(worklist, instructions, len);
1108
1109 struct util_dynarray bundles;
1110 util_dynarray_init(&bundles, NULL);
1111
1112 block->quadword_count = 0;
1113 unsigned blend_offset = 0;
1114
1115 for (;;) {
1116 unsigned tag = mir_choose_bundle(instructions, worklist, len);
1117 midgard_bundle bundle;
1118
1119 if (tag == TAG_TEXTURE_4)
1120 bundle = mir_schedule_texture(instructions, worklist, len);
1121 else if (tag == TAG_LOAD_STORE_4)
1122 bundle = mir_schedule_ldst(instructions, worklist, len);
1123 else if (tag == TAG_ALU_4)
1124 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
1125 else
1126 break;
1127
1128 util_dynarray_append(&bundles, midgard_bundle, bundle);
1129
1130 if (bundle.has_blend_constant)
1131 blend_offset = block->quadword_count;
1132
1133 block->quadword_count += midgard_tag_props[bundle.tag].size;
1134 }
1135
1136 /* We emitted bundles backwards; copy into the block in reverse-order */
1137
1138 util_dynarray_init(&block->bundles, block);
1139 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
1140 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
1141 }
1142 util_dynarray_fini(&bundles);
1143
1144 /* Blend constant was backwards as well. blend_offset if set is
1145 * strictly positive, as an offset of zero would imply constants before
1146 * any instructions which is invalid in Midgard. TODO: blend constants
1147 * are broken if you spill since then quadword_count becomes invalid
1148 * XXX */
1149
1150 if (blend_offset)
1151 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
1152
1153 block->scheduled = true;
1154 ctx->quadword_count += block->quadword_count;
1155
1156 /* Reorder instructions to match bundled. First remove existing
1157 * instructions and then recreate the list */
1158
1159 mir_foreach_instr_in_block_safe(block, ins) {
1160 list_del(&ins->link);
1161 }
1162
1163 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
1164 list_add(&ins->link, &block->base.instructions);
1165 }
1166
1167 free(instructions); /* Allocated by flatten_mir() */
1168 free(worklist);
1169 }
1170
1171 void
1172 midgard_schedule_program(compiler_context *ctx)
1173 {
1174 midgard_promote_uniforms(ctx);
1175
1176 /* Must be lowered right before scheduling */
1177 mir_squeeze_index(ctx);
1178 mir_lower_special_reads(ctx);
1179 mir_squeeze_index(ctx);
1180
1181 /* Lowering can introduce some dead moves */
1182
1183 mir_foreach_block(ctx, _block) {
1184 midgard_block *block = (midgard_block *) _block;
1185 midgard_opt_dead_move_eliminate(ctx, block);
1186 schedule_block(ctx, block);
1187 }
1188
1189 }