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