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 <stdlib.h>
75
76#include "blob.h"
77#include "ralloc.h"
78#include "util/bitset.h"
79#include "util/u_dynarray.h"
80#include "u_math.h"
81#include "register_allocate.h"
82#include "register_allocate_internal.h"
83
84/**
85 * Creates a set of registers for the allocator.
86 *
87 * mem_ctx is a ralloc context for the allocator.  The reg set may be freed
88 * using ralloc_free().
89 */
90struct ra_regs *
91ra_alloc_reg_set(void *mem_ctx, unsigned int count, bool need_conflict_lists)
92{
93   unsigned int i;
94   struct ra_regs *regs;
95
96   regs = rzalloc(mem_ctx, struct ra_regs);
97   regs->count = count;
98   regs->regs = rzalloc_array(regs, struct ra_reg, count);
99
100   for (i = 0; i < count; i++) {
101      regs->regs[i].conflicts = rzalloc_array(regs->regs, BITSET_WORD,
102                                              BITSET_WORDS(count));
103      BITSET_SET(regs->regs[i].conflicts, i);
104
105      util_dynarray_init(&regs->regs[i].conflict_list,
106                         need_conflict_lists ? regs->regs : NULL);
107      if (need_conflict_lists)
108         util_dynarray_append(&regs->regs[i].conflict_list, unsigned int, i);
109   }
110
111   return regs;
112}
113
114/**
115 * The register allocator by default prefers to allocate low register numbers,
116 * since it was written for hardware (gen4/5 Intel) that is limited in its
117 * multithreadedness by the number of registers used in a given shader.
118 *
119 * However, for hardware without that restriction, densely packed register
120 * allocation can put serious constraints on instruction scheduling.  This
121 * function tells the allocator to rotate around the registers if possible as
122 * it allocates the nodes.
123 */
124void
125ra_set_allocate_round_robin(struct ra_regs *regs)
126{
127   regs->round_robin = true;
128}
129
130static void
131ra_add_conflict_list(struct ra_regs *regs, unsigned int r1, unsigned int r2)
132{
133   struct ra_reg *reg1 = &regs->regs[r1];
134
135   if (reg1->conflict_list.mem_ctx) {
136      util_dynarray_append(&reg1->conflict_list, unsigned int, r2);
137   }
138   BITSET_SET(reg1->conflicts, r2);
139}
140
141void
142ra_add_reg_conflict(struct ra_regs *regs, unsigned int r1, unsigned int r2)
143{
144   if (!BITSET_TEST(regs->regs[r1].conflicts, r2)) {
145      ra_add_conflict_list(regs, r1, r2);
146      ra_add_conflict_list(regs, r2, r1);
147   }
148}
149
150/**
151 * Adds a conflict between base_reg and reg, and also between reg and
152 * anything that base_reg conflicts with.
153 *
154 * This can simplify code for setting up multiple register classes
155 * which are aggregates of some base hardware registers, compared to
156 * explicitly using ra_add_reg_conflict.
157 */
158void
159ra_add_transitive_reg_conflict(struct ra_regs *regs,
160                               unsigned int base_reg, unsigned int reg)
161{
162   ra_add_reg_conflict(regs, reg, base_reg);
163
164   util_dynarray_foreach(&regs->regs[base_reg].conflict_list, unsigned int,
165                         r2p) {
166      ra_add_reg_conflict(regs, reg, *r2p);
167   }
168}
169
170/**
171 * Set up conflicts between base_reg and it's two half registers reg0 and
172 * reg1, but take care to not add conflicts between reg0 and reg1.
173 *
174 * This is useful for architectures where full size registers are aliased by
175 * two half size registers (eg 32 bit float and 16 bit float registers).
176 */
177void
178ra_add_transitive_reg_pair_conflict(struct ra_regs *regs,
179                                    unsigned int base_reg, unsigned int reg0, unsigned int reg1)
180{
181   ra_add_reg_conflict(regs, reg0, base_reg);
182   ra_add_reg_conflict(regs, reg1, base_reg);
183
184   util_dynarray_foreach(&regs->regs[base_reg].conflict_list, unsigned int, i) {
185      unsigned int conflict = *i;
186      if (conflict != reg1)
187         ra_add_reg_conflict(regs, reg0, conflict);
188      if (conflict != reg0)
189         ra_add_reg_conflict(regs, reg1, conflict);
190   }
191}
192
193/**
194 * Makes every conflict on the given register transitive.  In other words,
195 * every register that conflicts with r will now conflict with every other
196 * register conflicting with r.
197 *
198 * This can simplify code for setting up multiple register classes
199 * which are aggregates of some base hardware registers, compared to
200 * explicitly using ra_add_reg_conflict.
201 */
202void
203ra_make_reg_conflicts_transitive(struct ra_regs *regs, unsigned int r)
204{
205   struct ra_reg *reg = &regs->regs[r];
206   int c;
207
208   BITSET_FOREACH_SET(c, reg->conflicts, regs->count) {
209      struct ra_reg *other = &regs->regs[c];
210      unsigned i;
211      for (i = 0; i < BITSET_WORDS(regs->count); i++)
212         other->conflicts[i] |= reg->conflicts[i];
213   }
214}
215
216struct ra_class *
217ra_alloc_reg_class(struct ra_regs *regs)
218{
219   struct ra_class *class;
220
221   regs->classes = reralloc(regs->regs, regs->classes, struct ra_class *,
222                            regs->class_count + 1);
223
224   class = rzalloc(regs, struct ra_class);
225   class->regset = regs;
226
227   /* Users may rely on the class index being allocated in order starting from 0. */
228   class->index = regs->class_count++;
229   regs->classes[class->index] = class;
230
231   class->regs = rzalloc_array(class, BITSET_WORD, BITSET_WORDS(regs->count));
232
233   return class;
234}
235
236/**
237 * Creates a register class for contiguous register groups of a base register
238 * set.
239 *
240 * A reg set using this type of register class must use only this type of
241 * register class.
242 */
243struct ra_class *
244ra_alloc_contig_reg_class(struct ra_regs *regs, int contig_len)
245{
246   struct ra_class *c = ra_alloc_reg_class(regs);
247
248   assert(contig_len != 0);
249   c->contig_len = contig_len;
250
251   return c;
252}
253
254struct ra_class *
255ra_get_class_from_index(struct ra_regs *regs, unsigned int class)
256{
257   return regs->classes[class];
258}
259
260unsigned int
261ra_class_index(struct ra_class *c)
262{
263   return c->index;
264}
265
266void
267ra_class_add_reg(struct ra_class *class, unsigned int r)
268{
269   assert(r < class->regset->count);
270   assert(r + class->contig_len <= class->regset->count);
271
272   BITSET_SET(class->regs, r);
273   class->p++;
274}
275
276/**
277 * Returns true if the register belongs to the given class.
278 */
279static bool
280reg_belongs_to_class(unsigned int r, struct ra_class *c)
281{
282   return BITSET_TEST(c->regs, r);
283}
284
285/**
286 * Must be called after all conflicts and register classes have been
287 * set up and before the register set is used for allocation.
288 * To avoid costly q value computation, use the q_values paramater
289 * to pass precomputed q values to this function.
290 */
291void
292ra_set_finalize(struct ra_regs *regs, unsigned int **q_values)
293{
294   unsigned int b, c;
295
296   for (b = 0; b < regs->class_count; b++) {
297      regs->classes[b]->q = ralloc_array(regs, unsigned int, regs->class_count);
298   }
299
300   if (q_values) {
301      for (b = 0; b < regs->class_count; b++) {
302         for (c = 0; c < regs->class_count; c++) {
303            regs->classes[b]->q[c] = q_values[b][c];
304         }
305      }
306   } else {
307      /* Compute, for each class B and C, how many regs of B an
308       * allocation to C could conflict with.
309       */
310      for (b = 0; b < regs->class_count; b++) {
311         for (c = 0; c < regs->class_count; c++) {
312            struct ra_class *class_b = regs->classes[b];
313            struct ra_class *class_c = regs->classes[c];
314
315            if (class_b->contig_len && class_c->contig_len) {
316               if (class_b->contig_len == 1 && class_c->contig_len == 1) {
317                  /* If both classes are single registers, then they only
318                   * conflict if there are any regs shared between them.  This
319                   * is a cheap test for a common case.
320                   */
321                  class_b->q[c] = 0;
322                  for (int i = 0; i < BITSET_WORDS(regs->count); i++) {
323                     if (class_b->regs[i] & class_c->regs[i]) {
324                        class_b->q[c] = 1;
325                        break;
326                     }
327                  }
328               } else {
329                  int max_possible_conflicts = class_b->contig_len + class_c->contig_len - 1;
330
331                  unsigned int max_conflicts = 0;
332                  unsigned int rc;
333                  BITSET_FOREACH_SET(rc, regs->classes[c]->regs, regs->count) {
334                     int start = MAX2(0, (int)rc - class_b->contig_len + 1);
335                     int end = MIN2(regs->count, rc + class_c->contig_len);
336                     unsigned int conflicts = 0;
337                     for (int i = start; i < end; i++) {
338                        if (BITSET_TEST(class_b->regs, i))
339                           conflicts++;
340                     }
341                     max_conflicts = MAX2(max_conflicts, conflicts);
342                     /* Unless a class has some restriction like the register
343                      * bases are all aligned, then we should quickly find this
344                      * limit and exit the loop.
345                      */
346                     if (max_conflicts == max_possible_conflicts)
347                        break;
348                  }
349                  class_b->q[c] = max_conflicts;
350               }
351            } else {
352               /* If you're doing contiguous classes, you have to be all in
353                * because I don't want to deal with it.
354                */
355               assert(!class_b->contig_len && !class_c->contig_len);
356
357               unsigned int rc;
358               int max_conflicts = 0;
359
360               BITSET_FOREACH_SET(rc, regs->classes[c]->regs, regs->count) {
361                  int conflicts = 0;
362
363                  util_dynarray_foreach(&regs->regs[rc].conflict_list,
364                                       unsigned int, rbp) {
365                     unsigned int rb = *rbp;
366                     if (reg_belongs_to_class(rb, regs->classes[b]))
367                        conflicts++;
368                  }
369                  max_conflicts = MAX2(max_conflicts, conflicts);
370               }
371               regs->classes[b]->q[c] = max_conflicts;
372            }
373         }
374      }
375   }
376
377   for (b = 0; b < regs->count; b++) {
378      util_dynarray_fini(&regs->regs[b].conflict_list);
379   }
380
381   bool all_contig = true;
382   for (int c = 0; c < regs->class_count; c++)
383      all_contig &= regs->classes[c]->contig_len != 0;
384   if (all_contig) {
385      /* In this case, we never need the conflicts lists (and it would probably
386       * be a mistake to look at conflicts when doing contiguous classes!), so
387       * free them.  TODO: Avoid the allocation in the first place.
388       */
389      for (int i = 0; i < regs->count; i++) {
390         ralloc_free(regs->regs[i].conflicts);
391         regs->regs[i].conflicts = NULL;
392      }
393   }
394}
395
396void
397ra_set_serialize(const struct ra_regs *regs, struct blob *blob)
398{
399   blob_write_uint32(blob, regs->count);
400   blob_write_uint32(blob, regs->class_count);
401
402   bool is_contig = regs->classes[0]->contig_len != 0;
403   blob_write_uint8(blob, is_contig);
404
405   if (!is_contig) {
406      for (unsigned int r = 0; r < regs->count; r++) {
407         struct ra_reg *reg = &regs->regs[r];
408         blob_write_bytes(blob, reg->conflicts, BITSET_WORDS(regs->count) *
409                                                sizeof(BITSET_WORD));
410         assert(util_dynarray_num_elements(&reg->conflict_list, unsigned int) == 0);
411      }
412   }
413
414   for (unsigned int c = 0; c < regs->class_count; c++) {
415      struct ra_class *class = regs->classes[c];
416      blob_write_bytes(blob, class->regs, BITSET_WORDS(regs->count) *
417                                          sizeof(BITSET_WORD));
418      blob_write_uint32(blob, class->contig_len);
419      blob_write_uint32(blob, class->p);
420      blob_write_bytes(blob, class->q, regs->class_count * sizeof(*class->q));
421   }
422
423   blob_write_uint32(blob, regs->round_robin);
424}
425
426struct ra_regs *
427ra_set_deserialize(void *mem_ctx, struct blob_reader *blob)
428{
429   unsigned int reg_count = blob_read_uint32(blob);
430   unsigned int class_count = blob_read_uint32(blob);
431   bool is_contig = blob_read_uint8(blob);
432
433   struct ra_regs *regs = ra_alloc_reg_set(mem_ctx, reg_count, false);
434   assert(regs->count == reg_count);
435
436   if (is_contig) {
437      for (int i = 0; i < regs->count; i++) {
438         ralloc_free(regs->regs[i].conflicts);
439         regs->regs[i].conflicts = NULL;
440      }
441   } else {
442      for (unsigned int r = 0; r < reg_count; r++) {
443         struct ra_reg *reg = &regs->regs[r];
444         blob_copy_bytes(blob, reg->conflicts, BITSET_WORDS(reg_count) *
445                                             sizeof(BITSET_WORD));
446      }
447   }
448
449   assert(regs->classes == NULL);
450   regs->classes = ralloc_array(regs->regs, struct ra_class *, class_count);
451   regs->class_count = class_count;
452
453   for (unsigned int c = 0; c < class_count; c++) {
454      struct ra_class *class = rzalloc(regs, struct ra_class);
455      regs->classes[c] = class;
456      class->regset = regs;
457      class->index = c;
458
459      class->regs = ralloc_array(class, BITSET_WORD, BITSET_WORDS(reg_count));
460      blob_copy_bytes(blob, class->regs, BITSET_WORDS(reg_count) *
461                                         sizeof(BITSET_WORD));
462
463      class->contig_len = blob_read_uint32(blob);
464      class->p = blob_read_uint32(blob);
465
466      class->q = ralloc_array(regs->classes[c], unsigned int, class_count);
467      blob_copy_bytes(blob, class->q, class_count * sizeof(*class->q));
468   }
469
470   regs->round_robin = blob_read_uint32(blob);
471
472   return regs;
473}
474
475static uint64_t
476ra_get_num_adjacency_bits(uint64_t n)
477{
478   return (n * (n - 1)) / 2;
479}
480
481static uint64_t
482ra_get_adjacency_bit_index(unsigned n1, unsigned n2)
483{
484   assert(n1 != n2);
485   unsigned k1 = MAX2(n1, n2);
486   unsigned k2 = MIN2(n1, n2);
487   return ra_get_num_adjacency_bits(k1) + k2;
488}
489
490static bool
491ra_test_adjacency_bit(struct ra_graph *g, unsigned n1, unsigned n2)
492{
493   uint64_t index = ra_get_adjacency_bit_index(n1, n2);
494   return BITSET_TEST(g->adjacency, index);
495}
496
497static void
498ra_set_adjacency_bit(struct ra_graph *g, unsigned n1, unsigned n2)
499{
500   unsigned index = ra_get_adjacency_bit_index(n1, n2);
501   BITSET_SET(g->adjacency, index);
502}
503
504static void
505ra_clear_adjacency_bit(struct ra_graph *g, unsigned n1, unsigned n2)
506{
507   unsigned index = ra_get_adjacency_bit_index(n1, n2);
508   BITSET_CLEAR(g->adjacency, index);
509}
510
511static void
512ra_add_node_adjacency(struct ra_graph *g, unsigned int n1, unsigned int n2)
513{
514   assert(n1 != n2);
515
516   int n1_class = g->nodes[n1].class;
517   int n2_class = g->nodes[n2].class;
518   g->nodes[n1].q_total += g->regs->classes[n1_class]->q[n2_class];
519
520   util_dynarray_append(&g->nodes[n1].adjacency_list, unsigned int, n2);
521}
522
523static void
524ra_node_remove_adjacency(struct ra_graph *g, unsigned int n1, unsigned int n2)
525{
526   assert(n1 != n2);
527   ra_clear_adjacency_bit(g, n1, n2);
528
529   int n1_class = g->nodes[n1].class;
530   int n2_class = g->nodes[n2].class;
531   g->nodes[n1].q_total -= g->regs->classes[n1_class]->q[n2_class];
532
533   util_dynarray_delete_unordered(&g->nodes[n1].adjacency_list, unsigned int,
534                                  n2);
535}
536
537static void
538ra_realloc_interference_graph(struct ra_graph *g, unsigned int alloc)
539{
540   if (alloc <= g->alloc)
541      return;
542
543   /* If we always have a whole number of BITSET_WORDs, it makes it much
544    * easier to memset the top of the growing bitsets.
545    */
546   assert(g->alloc % BITSET_WORDBITS == 0);
547   alloc = align64(alloc, BITSET_WORDBITS);
548   g->nodes = rerzalloc(g, g->nodes, struct ra_node, g->alloc, alloc);
549   g->adjacency = rerzalloc(g, g->adjacency, BITSET_WORD,
550                            BITSET_WORDS(ra_get_num_adjacency_bits(g->alloc)),
551                            BITSET_WORDS(ra_get_num_adjacency_bits(alloc)));
552
553   /* Initialize new nodes. */
554   for (unsigned i = g->alloc; i < alloc; i++) {
555      struct ra_node* node = g->nodes + i;
556      util_dynarray_init(&node->adjacency_list, g);
557      node->q_total = 0;
558      node->forced_reg = NO_REG;
559      node->reg = NO_REG;
560   }
561
562   /* These are scratch values and don't need to be zeroed.  We'll clear them
563    * as part of ra_select() setup.
564    */
565   unsigned bitset_count = BITSET_WORDS(alloc);
566   g->tmp.stack = reralloc(g, g->tmp.stack, unsigned int, alloc);
567   g->tmp.in_stack = reralloc(g, g->tmp.in_stack, BITSET_WORD, bitset_count);
568
569   g->tmp.reg_assigned = reralloc(g, g->tmp.reg_assigned, BITSET_WORD,
570                                  bitset_count);
571   g->tmp.pq_test = reralloc(g, g->tmp.pq_test, BITSET_WORD, bitset_count);
572   g->tmp.min_q_total = reralloc(g, g->tmp.min_q_total, unsigned int,
573                                 bitset_count);
574   g->tmp.min_q_node = reralloc(g, g->tmp.min_q_node, unsigned int,
575                                bitset_count);
576
577   g->alloc = alloc;
578}
579
580struct ra_graph *
581ra_alloc_interference_graph(struct ra_regs *regs, unsigned int count)
582{
583   struct ra_graph *g;
584
585   g = rzalloc(NULL, struct ra_graph);
586   g->regs = regs;
587   g->count = count;
588   ra_realloc_interference_graph(g, count);
589
590   return g;
591}
592
593void
594ra_resize_interference_graph(struct ra_graph *g, unsigned int count)
595{
596   g->count = count;
597   if (count > g->alloc)
598      ra_realloc_interference_graph(g, g->alloc * 2);
599}
600
601void ra_set_select_reg_callback(struct ra_graph *g,
602                                ra_select_reg_callback callback,
603                                void *data)
604{
605   g->select_reg_callback = callback;
606   g->select_reg_callback_data = data;
607}
608
609void
610ra_set_node_class(struct ra_graph *g,
611                  unsigned int n, struct ra_class *class)
612{
613   g->nodes[n].class = class->index;
614}
615
616struct ra_class *
617ra_get_node_class(struct ra_graph *g,
618                  unsigned int n)
619{
620   return g->regs->classes[g->nodes[n].class];
621}
622
623unsigned int
624ra_add_node(struct ra_graph *g, struct ra_class *class)
625{
626   unsigned int n = g->count;
627   ra_resize_interference_graph(g, g->count + 1);
628
629   ra_set_node_class(g, n, class);
630
631   return n;
632}
633
634void
635ra_add_node_interference(struct ra_graph *g,
636                         unsigned int n1, unsigned int n2)
637{
638   assert(n1 < g->count && n2 < g->count);
639   if (n1 != n2 && !ra_test_adjacency_bit(g, n1, n2)) {
640      ra_set_adjacency_bit(g, n1, n2);
641      ra_add_node_adjacency(g, n1, n2);
642      ra_add_node_adjacency(g, n2, n1);
643   }
644}
645
646void
647ra_reset_node_interference(struct ra_graph *g, unsigned int n)
648{
649   util_dynarray_foreach(&g->nodes[n].adjacency_list, unsigned int, n2p) {
650      ra_node_remove_adjacency(g, *n2p, n);
651   }
652
653   util_dynarray_clear(&g->nodes[n].adjacency_list);
654}
655
656static void
657update_pq_info(struct ra_graph *g, unsigned int n)
658{
659   int i = n / BITSET_WORDBITS;
660   int n_class = g->nodes[n].class;
661   if (g->nodes[n].tmp.q_total < g->regs->classes[n_class]->p) {
662      BITSET_SET(g->tmp.pq_test, n);
663   } else if (g->tmp.min_q_total[i] != UINT_MAX) {
664      /* Only update min_q_total and min_q_node if min_q_total != UINT_MAX so
665       * that we don't update while we have stale data and accidentally mark
666       * it as non-stale.  Also, in order to remain consistent with the old
667       * naive implementation of the algorithm, we do a lexicographical sort
668       * to ensure that we always choose the node with the highest node index.
669       */
670      if (g->nodes[n].tmp.q_total < g->tmp.min_q_total[i] ||
671          (g->nodes[n].tmp.q_total == g->tmp.min_q_total[i] &&
672           n > g->tmp.min_q_node[i])) {
673         g->tmp.min_q_total[i] = g->nodes[n].tmp.q_total;
674         g->tmp.min_q_node[i] = n;
675      }
676   }
677}
678
679static void
680add_node_to_stack(struct ra_graph *g, unsigned int n)
681{
682   int n_class = g->nodes[n].class;
683
684   assert(!BITSET_TEST(g->tmp.in_stack, n));
685
686   util_dynarray_foreach(&g->nodes[n].adjacency_list, unsigned int, n2p) {
687      unsigned int n2 = *n2p;
688      unsigned int n2_class = g->nodes[n2].class;
689
690      if (!BITSET_TEST(g->tmp.in_stack, n2) &&
691          !BITSET_TEST(g->tmp.reg_assigned, n2)) {
692         assert(g->nodes[n2].tmp.q_total >= g->regs->classes[n2_class]->q[n_class]);
693         g->nodes[n2].tmp.q_total -= g->regs->classes[n2_class]->q[n_class];
694         update_pq_info(g, n2);
695      }
696   }
697
698   g->tmp.stack[g->tmp.stack_count] = n;
699   g->tmp.stack_count++;
700   BITSET_SET(g->tmp.in_stack, n);
701
702   /* Flag the min_q_total for n's block as dirty so it gets recalculated */
703   g->tmp.min_q_total[n / BITSET_WORDBITS] = UINT_MAX;
704}
705
706/**
707 * Simplifies the interference graph by pushing all
708 * trivially-colorable nodes into a stack of nodes to be colored,
709 * removing them from the graph, and rinsing and repeating.
710 *
711 * If we encounter a case where we can't push any nodes on the stack, then
712 * we optimistically choose a node and push it on the stack. We heuristically
713 * push the node with the lowest total q value, since it has the fewest
714 * neighbors and therefore is most likely to be allocated.
715 */
716static void
717ra_simplify(struct ra_graph *g)
718{
719   bool progress = true;
720   unsigned int stack_optimistic_start = UINT_MAX;
721
722   /* Figure out the high bit and bit mask for the first iteration of a loop
723    * over BITSET_WORDs.
724    */
725   const unsigned int top_word_high_bit = (g->count - 1) % BITSET_WORDBITS;
726
727   /* Do a quick pre-pass to set things up */
728   g->tmp.stack_count = 0;
729   for (int i = BITSET_WORDS(g->count) - 1, high_bit = top_word_high_bit;
730        i >= 0; i--, high_bit = BITSET_WORDBITS - 1) {
731      g->tmp.in_stack[i] = 0;
732      g->tmp.reg_assigned[i] = 0;
733      g->tmp.pq_test[i] = 0;
734      g->tmp.min_q_total[i] = UINT_MAX;
735      g->tmp.min_q_node[i] = UINT_MAX;
736      for (int j = high_bit; j >= 0; j--) {
737         unsigned int n = i * BITSET_WORDBITS + j;
738         g->nodes[n].reg = g->nodes[n].forced_reg;
739         g->nodes[n].tmp.q_total = g->nodes[n].q_total;
740         if (g->nodes[n].reg != NO_REG)
741            g->tmp.reg_assigned[i] |= BITSET_BIT(j);
742         update_pq_info(g, n);
743      }
744   }
745
746   while (progress) {
747      unsigned int min_q_total = UINT_MAX;
748      unsigned int min_q_node = UINT_MAX;
749
750      progress = false;
751
752      for (int i = BITSET_WORDS(g->count) - 1, high_bit = top_word_high_bit;
753           i >= 0; i--, high_bit = BITSET_WORDBITS - 1) {
754         BITSET_WORD mask = ~(BITSET_WORD)0 >> (31 - high_bit);
755
756         BITSET_WORD skip = g->tmp.in_stack[i] | g->tmp.reg_assigned[i];
757         if (skip == mask)
758            continue;
759
760         BITSET_WORD pq = g->tmp.pq_test[i] & ~skip;
761         if (pq) {
762            /* In this case, we have stuff we can immediately take off the
763             * stack.  This also means that we're guaranteed to make progress
764             * and we don't need to bother updating lowest_q_total because we
765             * know we're going to loop again before attempting to do anything
766             * optimistic.
767             */
768            for (int j = high_bit; j >= 0; j--) {
769               if (pq & BITSET_BIT(j)) {
770                  unsigned int n = i * BITSET_WORDBITS + j;
771                  assert(n < g->count);
772                  add_node_to_stack(g, n);
773                  /* add_node_to_stack() may update pq_test for this word so
774                   * we need to update our local copy.
775                   */
776                  pq = g->tmp.pq_test[i] & ~skip;
777                  progress = true;
778               }
779            }
780         } else if (!progress) {
781            if (g->tmp.min_q_total[i] == UINT_MAX) {
782               /* The min_q_total and min_q_node are dirty because we added
783                * one of these nodes to the stack.  It needs to be
784                * recalculated.
785                */
786               for (int j = high_bit; j >= 0; j--) {
787                  if (skip & BITSET_BIT(j))
788                     continue;
789
790                  unsigned int n = i * BITSET_WORDBITS + j;
791                  assert(n < g->count);
792                  if (g->nodes[n].tmp.q_total < g->tmp.min_q_total[i]) {
793                     g->tmp.min_q_total[i] = g->nodes[n].tmp.q_total;
794                     g->tmp.min_q_node[i] = n;
795                  }
796               }
797            }
798            if (g->tmp.min_q_total[i] < min_q_total) {
799               min_q_node = g->tmp.min_q_node[i];
800               min_q_total = g->tmp.min_q_total[i];
801            }
802         }
803      }
804
805      if (!progress && min_q_total != UINT_MAX) {
806         if (stack_optimistic_start == UINT_MAX)
807            stack_optimistic_start = g->tmp.stack_count;
808
809         add_node_to_stack(g, min_q_node);
810         progress = true;
811      }
812   }
813
814   g->tmp.stack_optimistic_start = stack_optimistic_start;
815}
816
817bool
818ra_class_allocations_conflict(struct ra_class *c1, unsigned int r1,
819                              struct ra_class *c2, unsigned int r2)
820{
821   if (c1->contig_len) {
822      assert(c2->contig_len);
823
824      int r1_end = r1 + c1->contig_len;
825      int r2_end = r2 + c2->contig_len;
826      return !(r2 >= r1_end || r1 >= r2_end);
827   } else {
828      return BITSET_TEST(c1->regset->regs[r1].conflicts, r2);
829   }
830}
831
832static struct ra_node *
833ra_find_conflicting_neighbor(struct ra_graph *g, unsigned int n, unsigned int r)
834{
835   util_dynarray_foreach(&g->nodes[n].adjacency_list, unsigned int, n2p) {
836      unsigned int n2 = *n2p;
837
838      /* If our adjacent node is in the stack, it's not allocated yet. */
839      if (!BITSET_TEST(g->tmp.in_stack, n2) &&
840          ra_class_allocations_conflict(g->regs->classes[g->nodes[n].class], r,
841                                        g->regs->classes[g->nodes[n2].class], g->nodes[n2].reg)) {
842         return &g->nodes[n2];
843      }
844   }
845
846   return NULL;
847}
848
849/* Computes a bitfield of what regs are available for a given register
850 * selection.
851 *
852 * This lets drivers implement a more complicated policy than our simple first
853 * or round robin policies (which don't require knowing the whole bitset)
854 */
855static bool
856ra_compute_available_regs(struct ra_graph *g, unsigned int n, BITSET_WORD *regs)
857{
858   struct ra_class *c = g->regs->classes[g->nodes[n].class];
859
860   /* Populate with the set of regs that are in the node's class. */
861   memcpy(regs, c->regs, BITSET_WORDS(g->regs->count) * sizeof(BITSET_WORD));
862
863   /* Remove any regs that conflict with nodes that we're adjacent to and have
864    * already colored.
865    */
866   util_dynarray_foreach(&g->nodes[n].adjacency_list, unsigned int, n2p) {
867      struct ra_node *n2 = &g->nodes[*n2p];
868      struct ra_class *n2c = g->regs->classes[n2->class];
869
870      if (!BITSET_TEST(g->tmp.in_stack, *n2p)) {
871         if (c->contig_len) {
872            int start = MAX2(0, (int)n2->reg - c->contig_len + 1);
873            int end = MIN2(g->regs->count, n2->reg + n2c->contig_len);
874            for (unsigned i = start; i < end; i++)
875               BITSET_CLEAR(regs, i);
876         } else {
877            for (int j = 0; j < BITSET_WORDS(g->regs->count); j++)
878               regs[j] &= ~g->regs->regs[n2->reg].conflicts[j];
879         }
880      }
881   }
882
883   for (int i = 0; i < BITSET_WORDS(g->regs->count); i++) {
884      if (regs[i])
885         return true;
886   }
887
888   return false;
889}
890
891/**
892 * Pops nodes from the stack back into the graph, coloring them with
893 * registers as they go.
894 *
895 * If all nodes were trivially colorable, then this must succeed.  If
896 * not (optimistic coloring), then it may return false;
897 */
898static bool
899ra_select(struct ra_graph *g)
900{
901   int start_search_reg = 0;
902   BITSET_WORD *select_regs = NULL;
903
904   if (g->select_reg_callback)
905      select_regs = malloc(BITSET_WORDS(g->regs->count) * sizeof(BITSET_WORD));
906
907   while (g->tmp.stack_count != 0) {
908      unsigned int ri;
909      unsigned int r = -1;
910      int n = g->tmp.stack[g->tmp.stack_count - 1];
911      struct ra_class *c = g->regs->classes[g->nodes[n].class];
912
913      /* set this to false even if we return here so that
914       * ra_get_best_spill_node() considers this node later.
915       */
916      BITSET_CLEAR(g->tmp.in_stack, n);
917
918      if (g->select_reg_callback) {
919         if (!ra_compute_available_regs(g, n, select_regs)) {
920            free(select_regs);
921            return false;
922         }
923
924         r = g->select_reg_callback(n, select_regs, g->select_reg_callback_data);
925         assert(r < g->regs->count);
926      } else {
927         /* Find the lowest-numbered reg which is not used by a member
928          * of the graph adjacent to us.
929          */
930         for (ri = 0; ri < g->regs->count; ri++) {
931            r = (start_search_reg + ri) % g->regs->count;
932            if (!reg_belongs_to_class(r, c))
933               continue;
934
935            struct ra_node *conflicting = ra_find_conflicting_neighbor(g, n, r);
936            if (!conflicting) {
937               /* Found a reg! */
938               break;
939            }
940            if (g->regs->classes[conflicting->class]->contig_len) {
941               /* Skip to point at the last base reg of the conflicting reg
942                * allocation -- the loop will increment us to check the next reg
943                * after the conflicting allocaiton.
944                */
945               unsigned conflicting_end = (conflicting->reg +
946                                           g->regs->classes[conflicting->class]->contig_len - 1);
947               assert(conflicting_end >= r);
948               ri += conflicting_end - r;
949            }
950         }
951
952         if (ri >= g->regs->count)
953            return false;
954      }
955
956      g->nodes[n].reg = r;
957      g->tmp.stack_count--;
958
959      /* Rotate the starting point except for any nodes above the lowest
960       * optimistically colorable node.  The likelihood that we will succeed
961       * at allocating optimistically colorable nodes is highly dependent on
962       * the way that the previous nodes popped off the stack are laid out.
963       * The round-robin strategy increases the fragmentation of the register
964       * file and decreases the number of nearby nodes assigned to the same
965       * color, what increases the likelihood of spilling with respect to the
966       * dense packing strategy.
967       */
968      if (g->regs->round_robin &&
969          g->tmp.stack_count - 1 <= g->tmp.stack_optimistic_start)
970         start_search_reg = r + 1;
971   }
972
973   free(select_regs);
974
975   return true;
976}
977
978bool
979ra_allocate(struct ra_graph *g)
980{
981   ra_simplify(g);
982   return ra_select(g);
983}
984
985unsigned int
986ra_get_node_reg(struct ra_graph *g, unsigned int n)
987{
988   if (g->nodes[n].forced_reg != NO_REG)
989      return g->nodes[n].forced_reg;
990   else
991      return g->nodes[n].reg;
992}
993
994/**
995 * Forces a node to a specific register.  This can be used to avoid
996 * creating a register class containing one node when handling data
997 * that must live in a fixed location and is known to not conflict
998 * with other forced register assignment (as is common with shader
999 * input data).  These nodes do not end up in the stack during
1000 * ra_simplify(), and thus at ra_select() time it is as if they were
1001 * the first popped off the stack and assigned their fixed locations.
1002 * Nodes that use this function do not need to be assigned a register
1003 * class.
1004 *
1005 * Must be called before ra_simplify().
1006 */
1007void
1008ra_set_node_reg(struct ra_graph *g, unsigned int n, unsigned int reg)
1009{
1010   g->nodes[n].forced_reg = reg;
1011}
1012
1013static float
1014ra_get_spill_benefit(struct ra_graph *g, unsigned int n)
1015{
1016   float benefit = 0;
1017   int n_class = g->nodes[n].class;
1018
1019   /* Define the benefit of eliminating an interference between n, n2
1020    * through spilling as q(C, B) / p(C).  This is similar to the
1021    * "count number of edges" approach of traditional graph coloring,
1022    * but takes classes into account.
1023    */
1024   util_dynarray_foreach(&g->nodes[n].adjacency_list, unsigned int, n2p) {
1025      unsigned int n2 = *n2p;
1026      unsigned int n2_class = g->nodes[n2].class;
1027      benefit += ((float)g->regs->classes[n_class]->q[n2_class] /
1028                  g->regs->classes[n_class]->p);
1029   }
1030
1031   return benefit;
1032}
1033
1034/**
1035 * Returns a node number to be spilled according to the cost/benefit using
1036 * the pq test, or -1 if there are no spillable nodes.
1037 */
1038int
1039ra_get_best_spill_node(struct ra_graph *g)
1040{
1041   unsigned int best_node = -1;
1042   float best_benefit = 0.0;
1043   unsigned int n;
1044
1045   /* Consider any nodes that we colored successfully or the node we failed to
1046    * color for spilling. When we failed to color a node in ra_select(), we
1047    * only considered these nodes, so spilling any other ones would not result
1048    * in us making progress.
1049    */
1050   for (n = 0; n < g->count; n++) {
1051      float cost = g->nodes[n].spill_cost;
1052      float benefit;
1053
1054      if (cost <= 0.0f)
1055         continue;
1056
1057      if (BITSET_TEST(g->tmp.in_stack, n))
1058         continue;
1059
1060      benefit = ra_get_spill_benefit(g, n);
1061
1062      if (benefit / cost > best_benefit) {
1063         best_benefit = benefit / cost;
1064         best_node = n;
1065      }
1066   }
1067
1068   return best_node;
1069}
1070
1071/**
1072 * Only nodes with a spill cost set (cost != 0.0) will be considered
1073 * for register spilling.
1074 */
1075void
1076ra_set_node_spill_cost(struct ra_graph *g, unsigned int n, float cost)
1077{
1078   g->nodes[n].spill_cost = cost;
1079}
1080