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