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