6fac69033ed0ba4bad248484b64af40a0061db99
[mesa.git] / src / mesa / program / register_allocate.c
1 /*
2 * Copyright © 2010 Intel Corporation
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
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 *
26 */
27
28 /** @file register_allocate.c
29 *
30 * Graph-coloring register allocator.
31 *
32 * The basic idea of graph coloring is to make a node in a graph for
33 * every thing that needs a register (color) number assigned, and make
34 * edges in the graph between nodes that interfere (can't be allocated
35 * to the same register at the same time).
36 *
37 * During the "simplify" process, any any node with fewer edges than
38 * there are registers means that that edge can get assigned a
39 * register regardless of what its neighbors choose, so that node is
40 * pushed on a stack and removed (with its edges) from the graph.
41 * That likely causes other nodes to become trivially colorable as well.
42 *
43 * Then during the "select" process, nodes are popped off of that
44 * stack, their edges restored, and assigned a color different from
45 * their neighbors. Because they were pushed on the stack only when
46 * they were trivially colorable, any color chosen won't interfere
47 * with the registers to be popped later.
48 *
49 * The downside to most graph coloring is that real hardware often has
50 * limitations, like registers that need to be allocated to a node in
51 * pairs, or aligned on some boundary. This implementation follows
52 * the paper "Retargetable Graph-Coloring Register Allocation for
53 * Irregular Architectures" by Johan Runeson and Sven-Olof Nyström.
54 *
55 * In this system, there are register classes each containing various
56 * registers, and registers may interfere with other registers. For
57 * example, one might have a class of base registers, and a class of
58 * aligned register pairs that would each interfere with their pair of
59 * the base registers. Each node has a register class it needs to be
60 * assigned to. Define p(B) to be the size of register class B, and
61 * q(B,C) to be the number of registers in B that the worst choice
62 * register in C could conflict with. Then, this system replaces the
63 * basic graph coloring test of "fewer edges from this node than there
64 * are registers" with "For this node of class B, the sum of q(B,C)
65 * for each neighbor node of class C is less than pB".
66 *
67 * A nice feature of the pq test is that q(B,C) can be computed once
68 * up front and stored in a 2-dimensional array, so that the cost of
69 * coloring a node is constant with the number of registers. We do
70 * this during ra_set_finalize().
71 */
72
73 #include <stdbool.h>
74 #include <ralloc.h>
75
76 #include "main/imports.h"
77 #include "main/macros.h"
78 #include "main/mtypes.h"
79 #include "main/bitset.h"
80 #include "register_allocate.h"
81
82 #define NO_REG ~0
83
84 struct ra_reg {
85 BITSET_WORD *conflicts;
86 unsigned int *conflict_list;
87 unsigned int conflict_list_size;
88 unsigned int num_conflicts;
89 };
90
91 struct ra_regs {
92 struct ra_reg *regs;
93 unsigned int count;
94
95 struct ra_class **classes;
96 unsigned int class_count;
97
98 bool round_robin;
99 };
100
101 struct ra_class {
102 /**
103 * Bitset indicating which registers belong to this class.
104 *
105 * (If bit N is set, then register N belongs to this class.)
106 */
107 BITSET_WORD *regs;
108
109 /**
110 * p(B) in Runeson/Nyström paper.
111 *
112 * This is "how many regs are in the set."
113 */
114 unsigned int p;
115
116 /**
117 * q(B,C) (indexed by C, B is this register class) in
118 * Runeson/Nyström paper. This is "how many registers of B could
119 * the worst choice register from C conflict with".
120 */
121 unsigned int *q;
122 };
123
124 struct ra_node {
125 /** @{
126 *
127 * List of which nodes this node interferes with. This should be
128 * symmetric with the other node.
129 */
130 BITSET_WORD *adjacency;
131 unsigned int *adjacency_list;
132 unsigned int adjacency_list_size;
133 unsigned int adjacency_count;
134 /** @} */
135
136 unsigned int class;
137
138 /* Register, if assigned, or NO_REG. */
139 unsigned int reg;
140
141 /**
142 * Set when the node is in the trivially colorable stack. When
143 * set, the adjacency to this node is ignored, to implement the
144 * "remove the edge from the graph" in simplification without
145 * having to actually modify the adjacency_list.
146 */
147 bool in_stack;
148
149 /* For an implementation that needs register spilling, this is the
150 * approximate cost of spilling this node.
151 */
152 float spill_cost;
153 };
154
155 struct ra_graph {
156 struct ra_regs *regs;
157 /**
158 * the variables that need register allocation.
159 */
160 struct ra_node *nodes;
161 unsigned int count; /**< count of nodes. */
162
163 unsigned int *stack;
164 unsigned int stack_count;
165
166 /**
167 * Tracks the start of the set of optimistically-colored registers in the
168 * stack.
169 *
170 * Along with any registers not in the stack (if one called ra_simplify()
171 * and didn't do optimistic coloring), these need to be considered for
172 * spilling.
173 */
174 unsigned int stack_optimistic_start;
175 };
176
177 /**
178 * Creates a set of registers for the allocator.
179 *
180 * mem_ctx is a ralloc context for the allocator. The reg set may be freed
181 * using ralloc_free().
182 */
183 struct ra_regs *
184 ra_alloc_reg_set(void *mem_ctx, unsigned int count)
185 {
186 unsigned int i;
187 struct ra_regs *regs;
188
189 regs = rzalloc(mem_ctx, struct ra_regs);
190 regs->count = count;
191 regs->regs = rzalloc_array(regs, struct ra_reg, count);
192
193 for (i = 0; i < count; i++) {
194 regs->regs[i].conflicts = rzalloc_array(regs->regs, BITSET_WORD,
195 BITSET_WORDS(count));
196 BITSET_SET(regs->regs[i].conflicts, i);
197
198 regs->regs[i].conflict_list = ralloc_array(regs->regs, unsigned int, 4);
199 regs->regs[i].conflict_list_size = 4;
200 regs->regs[i].conflict_list[0] = i;
201 regs->regs[i].num_conflicts = 1;
202 }
203
204 return regs;
205 }
206
207 /**
208 * The register allocator by default prefers to allocate low register numbers,
209 * since it was written for hardware (gen4/5 Intel) that is limited in its
210 * multithreadedness by the number of registers used in a given shader.
211 *
212 * However, for hardware without that restriction, densely packed register
213 * allocation can put serious constraints on instruction scheduling. This
214 * function tells the allocator to rotate around the registers if possible as
215 * it allocates the nodes.
216 */
217 void
218 ra_set_allocate_round_robin(struct ra_regs *regs)
219 {
220 regs->round_robin = true;
221 }
222
223 static void
224 ra_add_conflict_list(struct ra_regs *regs, unsigned int r1, unsigned int r2)
225 {
226 struct ra_reg *reg1 = &regs->regs[r1];
227
228 if (reg1->conflict_list_size == reg1->num_conflicts) {
229 reg1->conflict_list_size *= 2;
230 reg1->conflict_list = reralloc(regs->regs, reg1->conflict_list,
231 unsigned int, reg1->conflict_list_size);
232 }
233 reg1->conflict_list[reg1->num_conflicts++] = r2;
234 BITSET_SET(reg1->conflicts, r2);
235 }
236
237 void
238 ra_add_reg_conflict(struct ra_regs *regs, unsigned int r1, unsigned int r2)
239 {
240 if (!BITSET_TEST(regs->regs[r1].conflicts, r2)) {
241 ra_add_conflict_list(regs, r1, r2);
242 ra_add_conflict_list(regs, r2, r1);
243 }
244 }
245
246 /**
247 * Adds a conflict between base_reg and reg, and also between reg and
248 * anything that base_reg conflicts with.
249 *
250 * This can simplify code for setting up multiple register classes
251 * which are aggregates of some base hardware registers, compared to
252 * explicitly using ra_add_reg_conflict.
253 */
254 void
255 ra_add_transitive_reg_conflict(struct ra_regs *regs,
256 unsigned int base_reg, unsigned int reg)
257 {
258 int i;
259
260 ra_add_reg_conflict(regs, reg, base_reg);
261
262 for (i = 0; i < regs->regs[base_reg].num_conflicts; i++) {
263 ra_add_reg_conflict(regs, reg, regs->regs[base_reg].conflict_list[i]);
264 }
265 }
266
267 unsigned int
268 ra_alloc_reg_class(struct ra_regs *regs)
269 {
270 struct ra_class *class;
271
272 regs->classes = reralloc(regs->regs, regs->classes, struct ra_class *,
273 regs->class_count + 1);
274
275 class = rzalloc(regs, struct ra_class);
276 regs->classes[regs->class_count] = class;
277
278 class->regs = rzalloc_array(class, BITSET_WORD, BITSET_WORDS(regs->count));
279
280 return regs->class_count++;
281 }
282
283 void
284 ra_class_add_reg(struct ra_regs *regs, unsigned int c, unsigned int r)
285 {
286 struct ra_class *class = regs->classes[c];
287
288 BITSET_SET(class->regs, r);
289 class->p++;
290 }
291
292 /**
293 * Returns true if the register belongs to the given class.
294 */
295 static bool
296 reg_belongs_to_class(unsigned int r, struct ra_class *c)
297 {
298 return BITSET_TEST(c->regs, r);
299 }
300
301 /**
302 * Must be called after all conflicts and register classes have been
303 * set up and before the register set is used for allocation.
304 * To avoid costly q value computation, use the q_values paramater
305 * to pass precomputed q values to this function.
306 */
307 void
308 ra_set_finalize(struct ra_regs *regs, unsigned int **q_values)
309 {
310 unsigned int b, c;
311
312 for (b = 0; b < regs->class_count; b++) {
313 regs->classes[b]->q = ralloc_array(regs, unsigned int, regs->class_count);
314 }
315
316 if (q_values) {
317 for (b = 0; b < regs->class_count; b++) {
318 for (c = 0; c < regs->class_count; c++) {
319 regs->classes[b]->q[c] = q_values[b][c];
320 }
321 }
322 return;
323 }
324
325 /* Compute, for each class B and C, how many regs of B an
326 * allocation to C could conflict with.
327 */
328 for (b = 0; b < regs->class_count; b++) {
329 for (c = 0; c < regs->class_count; c++) {
330 unsigned int rc;
331 int max_conflicts = 0;
332
333 for (rc = 0; rc < regs->count; rc++) {
334 int conflicts = 0;
335 int i;
336
337 if (!reg_belongs_to_class(rc, regs->classes[c]))
338 continue;
339
340 for (i = 0; i < regs->regs[rc].num_conflicts; i++) {
341 unsigned int rb = regs->regs[rc].conflict_list[i];
342 if (BITSET_TEST(regs->classes[b]->regs, rb))
343 conflicts++;
344 }
345 max_conflicts = MAX2(max_conflicts, conflicts);
346 }
347 regs->classes[b]->q[c] = max_conflicts;
348 }
349 }
350 }
351
352 static void
353 ra_add_node_adjacency(struct ra_graph *g, unsigned int n1, unsigned int n2)
354 {
355 BITSET_SET(g->nodes[n1].adjacency, n2);
356
357 if (g->nodes[n1].adjacency_count >=
358 g->nodes[n1].adjacency_list_size) {
359 g->nodes[n1].adjacency_list_size *= 2;
360 g->nodes[n1].adjacency_list = reralloc(g, g->nodes[n1].adjacency_list,
361 unsigned int,
362 g->nodes[n1].adjacency_list_size);
363 }
364
365 g->nodes[n1].adjacency_list[g->nodes[n1].adjacency_count] = n2;
366 g->nodes[n1].adjacency_count++;
367 }
368
369 struct ra_graph *
370 ra_alloc_interference_graph(struct ra_regs *regs, unsigned int count)
371 {
372 struct ra_graph *g;
373 unsigned int i;
374
375 g = rzalloc(regs, struct ra_graph);
376 g->regs = regs;
377 g->nodes = rzalloc_array(g, struct ra_node, count);
378 g->count = count;
379
380 g->stack = rzalloc_array(g, unsigned int, count);
381
382 for (i = 0; i < count; i++) {
383 int bitset_count = BITSET_WORDS(count);
384 g->nodes[i].adjacency = rzalloc_array(g, BITSET_WORD, bitset_count);
385
386 g->nodes[i].adjacency_list_size = 4;
387 g->nodes[i].adjacency_list =
388 ralloc_array(g, unsigned int, g->nodes[i].adjacency_list_size);
389 g->nodes[i].adjacency_count = 0;
390
391 ra_add_node_adjacency(g, i, i);
392 g->nodes[i].reg = NO_REG;
393 }
394
395 return g;
396 }
397
398 void
399 ra_set_node_class(struct ra_graph *g,
400 unsigned int n, unsigned int class)
401 {
402 g->nodes[n].class = class;
403 }
404
405 void
406 ra_add_node_interference(struct ra_graph *g,
407 unsigned int n1, unsigned int n2)
408 {
409 if (!BITSET_TEST(g->nodes[n1].adjacency, n2)) {
410 ra_add_node_adjacency(g, n1, n2);
411 ra_add_node_adjacency(g, n2, n1);
412 }
413 }
414
415 static bool
416 pq_test(struct ra_graph *g, unsigned int n)
417 {
418 unsigned int j;
419 unsigned int q = 0;
420 int n_class = g->nodes[n].class;
421
422 for (j = 0; j < g->nodes[n].adjacency_count; j++) {
423 unsigned int n2 = g->nodes[n].adjacency_list[j];
424 unsigned int n2_class = g->nodes[n2].class;
425
426 if (n != n2 && !g->nodes[n2].in_stack) {
427 q += g->regs->classes[n_class]->q[n2_class];
428 }
429 }
430
431 return q < g->regs->classes[n_class]->p;
432 }
433
434 /**
435 * Simplifies the interference graph by pushing all
436 * trivially-colorable nodes into a stack of nodes to be colored,
437 * removing them from the graph, and rinsing and repeating.
438 *
439 * Returns true if all nodes were removed from the graph. false
440 * means that either spilling will be required, or optimistic coloring
441 * should be applied.
442 */
443 bool
444 ra_simplify(struct ra_graph *g)
445 {
446 bool progress = true;
447 int i;
448
449 while (progress) {
450 progress = false;
451
452 for (i = g->count - 1; i >= 0; i--) {
453 if (g->nodes[i].in_stack || g->nodes[i].reg != NO_REG)
454 continue;
455
456 if (pq_test(g, i)) {
457 g->stack[g->stack_count] = i;
458 g->stack_count++;
459 g->nodes[i].in_stack = true;
460 progress = true;
461 }
462 }
463 }
464
465 for (i = 0; i < g->count; i++) {
466 if (!g->nodes[i].in_stack && g->nodes[i].reg == -1)
467 return false;
468 }
469
470 return true;
471 }
472
473 /**
474 * Pops nodes from the stack back into the graph, coloring them with
475 * registers as they go.
476 *
477 * If all nodes were trivially colorable, then this must succeed. If
478 * not (optimistic coloring), then it may return false;
479 */
480 bool
481 ra_select(struct ra_graph *g)
482 {
483 int i;
484 int start_search_reg = 0;
485
486 while (g->stack_count != 0) {
487 unsigned int ri;
488 unsigned int r = -1;
489 int n = g->stack[g->stack_count - 1];
490 struct ra_class *c = g->regs->classes[g->nodes[n].class];
491
492 /* Find the lowest-numbered reg which is not used by a member
493 * of the graph adjacent to us.
494 */
495 for (ri = 0; ri < g->regs->count; ri++) {
496 r = (start_search_reg + ri) % g->regs->count;
497 if (!reg_belongs_to_class(r, c))
498 continue;
499
500 /* Check if any of our neighbors conflict with this register choice. */
501 for (i = 0; i < g->nodes[n].adjacency_count; i++) {
502 unsigned int n2 = g->nodes[n].adjacency_list[i];
503
504 if (!g->nodes[n2].in_stack &&
505 BITSET_TEST(g->regs->regs[r].conflicts, g->nodes[n2].reg)) {
506 break;
507 }
508 }
509 if (i == g->nodes[n].adjacency_count)
510 break;
511 }
512 if (ri == g->regs->count)
513 return false;
514
515 g->nodes[n].reg = r;
516 g->nodes[n].in_stack = false;
517 g->stack_count--;
518
519 if (g->regs->round_robin)
520 start_search_reg = r + 1;
521 }
522
523 return true;
524 }
525
526 /**
527 * Optimistic register coloring: Just push the remaining nodes
528 * on the stack. They'll be colored first in ra_select(), and
529 * if they succeed then the locally-colorable nodes are still
530 * locally-colorable and the rest of the register allocation
531 * will succeed.
532 */
533 void
534 ra_optimistic_color(struct ra_graph *g)
535 {
536 unsigned int i;
537
538 g->stack_optimistic_start = g->stack_count;
539 for (i = 0; i < g->count; i++) {
540 if (g->nodes[i].in_stack || g->nodes[i].reg != NO_REG)
541 continue;
542
543 g->stack[g->stack_count] = i;
544 g->stack_count++;
545 g->nodes[i].in_stack = true;
546 }
547 }
548
549 bool
550 ra_allocate_no_spills(struct ra_graph *g)
551 {
552 if (!ra_simplify(g)) {
553 ra_optimistic_color(g);
554 }
555 return ra_select(g);
556 }
557
558 unsigned int
559 ra_get_node_reg(struct ra_graph *g, unsigned int n)
560 {
561 return g->nodes[n].reg;
562 }
563
564 /**
565 * Forces a node to a specific register. This can be used to avoid
566 * creating a register class containing one node when handling data
567 * that must live in a fixed location and is known to not conflict
568 * with other forced register assignment (as is common with shader
569 * input data). These nodes do not end up in the stack during
570 * ra_simplify(), and thus at ra_select() time it is as if they were
571 * the first popped off the stack and assigned their fixed locations.
572 * Nodes that use this function do not need to be assigned a register
573 * class.
574 *
575 * Must be called before ra_simplify().
576 */
577 void
578 ra_set_node_reg(struct ra_graph *g, unsigned int n, unsigned int reg)
579 {
580 g->nodes[n].reg = reg;
581 g->nodes[n].in_stack = false;
582 }
583
584 static float
585 ra_get_spill_benefit(struct ra_graph *g, unsigned int n)
586 {
587 int j;
588 float benefit = 0;
589 int n_class = g->nodes[n].class;
590
591 /* Define the benefit of eliminating an interference between n, n2
592 * through spilling as q(C, B) / p(C). This is similar to the
593 * "count number of edges" approach of traditional graph coloring,
594 * but takes classes into account.
595 */
596 for (j = 0; j < g->nodes[n].adjacency_count; j++) {
597 unsigned int n2 = g->nodes[n].adjacency_list[j];
598 if (n != n2) {
599 unsigned int n2_class = g->nodes[n2].class;
600 benefit += ((float)g->regs->classes[n_class]->q[n2_class] /
601 g->regs->classes[n_class]->p);
602 }
603 }
604
605 return benefit;
606 }
607
608 /**
609 * Returns a node number to be spilled according to the cost/benefit using
610 * the pq test, or -1 if there are no spillable nodes.
611 */
612 int
613 ra_get_best_spill_node(struct ra_graph *g)
614 {
615 unsigned int best_node = -1;
616 float best_benefit = 0.0;
617 unsigned int n, i;
618
619 /* For any registers not in the stack to be colored, consider them for
620 * spilling. This will mostly collect nodes that were being optimistally
621 * colored as part of ra_allocate_no_spills() if we didn't successfully
622 * optimistically color.
623 *
624 * It also includes nodes not trivially colorable by ra_simplify() if it
625 * was used directly instead of as part of ra_allocate_no_spills().
626 */
627 for (n = 0; n < g->count; n++) {
628 float cost = g->nodes[n].spill_cost;
629 float benefit;
630
631 if (cost <= 0.0)
632 continue;
633
634 if (g->nodes[n].in_stack)
635 continue;
636
637 benefit = ra_get_spill_benefit(g, n);
638
639 if (benefit / cost > best_benefit) {
640 best_benefit = benefit / cost;
641 best_node = n;
642 }
643 }
644
645 /* Also consider spilling any nodes that were set up to be optimistically
646 * colored that we couldn't manage to color in ra_select().
647 */
648 for (i = g->stack_optimistic_start; i < g->stack_count; i++) {
649 float cost, benefit;
650
651 n = g->stack[i];
652 cost = g->nodes[n].spill_cost;
653
654 if (cost <= 0.0)
655 continue;
656
657 benefit = ra_get_spill_benefit(g, n);
658
659 if (benefit / cost > best_benefit) {
660 best_benefit = benefit / cost;
661 best_node = n;
662 }
663 }
664
665 return best_node;
666 }
667
668 /**
669 * Only nodes with a spill cost set (cost != 0.0) will be considered
670 * for register spilling.
671 */
672 void
673 ra_set_node_spill_cost(struct ra_graph *g, unsigned int n, float cost)
674 {
675 g->nodes[n].spill_cost = cost;
676 }