replace psets with arrays to make the compiler more predictable across runs (and...
[libfirm] / ir / be / bechordal.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Chordal register allocation.
23  * @author      Sebastian Hack
24  * @date        08.12.2004
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <ctype.h>
30
31 #include "obst.h"
32 #include "pset.h"
33 #include "list.h"
34 #include "bitset.h"
35 #include "raw_bitset.h"
36 #include "iterator.h"
37 #include "bipartite.h"
38 #include "hungarian.h"
39
40 #include "irmode_t.h"
41 #include "irgraph_t.h"
42 #include "irprintf_t.h"
43 #include "irgwalk.h"
44 #include "irdump.h"
45 #include "irdom.h"
46 #include "irtools.h"
47 #include "irbitset.h"
48 #include "debug.h"
49 #include "iredges.h"
50
51 #include "beutil.h"
52 #include "besched.h"
53 #include "besched.h"
54 #include "belive_t.h"
55 #include "benode.h"
56 #include "bearch.h"
57 #include "beirgmod.h"
58 #include "beifg.h"
59 #include "beinsn_t.h"
60 #include "bestatevent.h"
61 #include "beirg.h"
62 #include "beintlive_t.h"
63 #include "bera.h"
64 #include "bechordal_t.h"
65 #include "bechordal_draw.h"
66 #include "bemodule.h"
67 #include "bearch.h"
68 #include "bechordal_common.h"
69
70 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
71
72 #define NO_COLOR (-1)
73
74 #define DUMP_INTERVALS
75
76 typedef struct _be_chordal_alloc_env_t {
77         be_chordal_env_t *chordal_env;
78
79         pset *pre_colored;     /**< Set of precolored nodes. */
80         bitset_t *live;            /**< A liveness bitset. */
81         bitset_t *tmp_colors;  /**< An auxiliary bitset which is as long as the number of colors in the class. */
82         bitset_t *colors;          /**< The color mask. */
83         bitset_t *in_colors;   /**< Colors used by live in values. */
84         int colors_n;          /**< The number of colors. */
85 } be_chordal_alloc_env_t;
86
87 static int get_next_free_reg(const be_chordal_alloc_env_t *alloc_env, bitset_t *colors)
88 {
89         bitset_t *tmp = alloc_env->tmp_colors;
90         bitset_copy(tmp, colors);
91         bitset_or(tmp, alloc_env->chordal_env->ignore_colors);
92         return bitset_next_clear(tmp, 0);
93 }
94
95 static bitset_t *get_decisive_partner_regs(bitset_t *bs, const be_operand_t *o1, const be_operand_t *o2)
96 {
97         bitset_t *res = bs;
98
99         if (!o1) {
100                 bitset_copy(bs, o2->regs);
101                 return bs;
102         }
103
104         if (!o2) {
105                 bitset_copy(bs, o1->regs);
106                 return bs;
107         }
108
109         assert(o1->req->cls == o2->req->cls || ! o1->req->cls || ! o2->req->cls);
110
111         if (bitset_contains(o1->regs, o2->regs)) {
112                 bitset_copy(bs, o1->regs);
113         } else if (bitset_contains(o2->regs, o1->regs)) {
114                 bitset_copy(bs, o2->regs);
115         } else {
116                 res = NULL;
117         }
118
119         return res;
120 }
121
122 static void pair_up_operands(const be_chordal_alloc_env_t *alloc_env, be_insn_t *insn)
123 {
124         const be_chordal_env_t *env = alloc_env->chordal_env;
125         bitset_t               *bs  = bitset_alloca(env->cls->n_regs);
126         int                     i;
127         int                     j;
128
129         /*
130          * For each out operand, try to find an in operand which can be assigned the
131          * same register as the out operand.
132         */
133         for (j = 0; j < insn->use_start; ++j) {
134                 int smallest         = -1;
135                 int smallest_n_regs  = 2 * env->cls->n_regs + 1;
136                 be_operand_t *out_op = &insn->ops[j];
137
138                 /* Try to find an in operand which has ... */
139                 for (i = insn->use_start; i < insn->n_ops; ++i) {
140                         int n_total;
141                         const be_operand_t *op = &insn->ops[i];
142                         be_lv_t            *lv;
143
144                         if (op->partner != NULL)
145                                 continue;
146                         lv = be_get_irg_liveness(env->irg);
147                         if (be_values_interfere(lv, op->irn, op->carrier))
148                                 continue;
149
150                         bitset_clear_all(bs);
151                         bitset_copy(bs, op->regs);
152                         bitset_and(bs, out_op->regs);
153                         n_total = bitset_popcount(op->regs) + bitset_popcount(out_op->regs);
154
155                         if (!bitset_is_empty(bs) && n_total < smallest_n_regs) {
156                                 smallest = i;
157                                 smallest_n_regs = n_total;
158                         }
159                 }
160
161                 if (smallest >= 0) {
162                         be_operand_t *partner = &insn->ops[smallest];
163                         for (i = insn->use_start; i < insn->n_ops; ++i) {
164                                 if (insn->ops[i].carrier == partner->carrier)
165                                         insn->ops[i].partner = out_op;
166                         }
167
168                         out_op->partner  = partner;
169                         partner->partner = out_op;
170                 }
171         }
172 }
173
174 static ir_node *handle_constraints(be_chordal_alloc_env_t *alloc_env,
175                                    ir_node *irn, int *silent)
176 {
177         int n_regs;
178         bitset_t *bs;
179         ir_node **alloc_nodes;
180         //hungarian_problem_t *bp;
181         int *assignment;
182         pmap *partners;
183         int i, n_alloc;
184         unsigned col;
185         const ir_edge_t *edge;
186         ir_node *perm = NULL;
187         //int match_res, cost;
188         be_chordal_env_t *env  = alloc_env->chordal_env;
189         void *base             = obstack_base(env->obst);
190         be_insn_t *insn        = chordal_scan_insn(env, irn);
191         ir_node *res           = insn->next_insn;
192         int be_silent          = *silent;
193         bipartite_t *bp;
194
195         if (insn->pre_colored) {
196                 int i;
197                 for (i = 0; i < insn->use_start; ++i)
198                         pset_insert_ptr(alloc_env->pre_colored, insn->ops[i].carrier);
199         }
200
201         /*
202          * If the current node is a barrier toggle the silent flag.
203          * If we are in the start block, we are ought to be silent at the beginning,
204          * so the toggling activates the constraint handling but skips the barrier.
205          * If we are in the end block we handle the in requirements of the barrier
206          * and set the rest to silent.
207          */
208         if (be_is_Barrier(irn))
209                 *silent = !*silent;
210
211         if (be_silent)
212                 goto end;
213
214         /*
215          * Perms inserted before the constraint handling phase are considered to be
216          * correctly precolored. These Perms arise during the ABI handling phase.
217          */
218         if (!insn->has_constraints)
219                 goto end;
220
221         n_regs      = env->cls->n_regs;
222         bs          = bitset_alloca(n_regs);
223         alloc_nodes = ALLOCAN(ir_node*, n_regs);
224         //bp          = hungarian_new(n_regs, n_regs, 2, HUNGARIAN_MATCH_PERFECT);
225         bp          = bipartite_new(n_regs, n_regs);
226         assignment  = ALLOCAN(int, n_regs);
227         partners    = pmap_create();
228
229         /*
230          * prepare the constraint handling of this node.
231          * Perms are constructed and Copies are created for constrained values
232          * interfering with the instruction.
233          */
234         perm = pre_process_constraints(alloc_env->chordal_env, &insn);
235
236         /* find suitable in operands to the out operands of the node. */
237         pair_up_operands(alloc_env, insn);
238
239         /*
240          * look at the in/out operands and add each operand (and its possible partner)
241          * to a bipartite graph (left: nodes with partners, right: admissible colors).
242          */
243         for (i = 0, n_alloc = 0; i < insn->n_ops; ++i) {
244                 be_operand_t *op = &insn->ops[i];
245
246                 /*
247                  * If the operand has no partner or the partner has not been marked
248                  * for allocation, determine the admissible registers and mark it
249                  * for allocation by associating the node and its partner with the
250                  * set of admissible registers via a bipartite graph.
251                  */
252                 if (!op->partner || !pmap_contains(partners, op->partner->carrier)) {
253                         ir_node *partner = op->partner ? op->partner->carrier : NULL;
254                         int i;
255
256                         pmap_insert(partners, op->carrier, partner);
257                         if (partner != NULL)
258                                 pmap_insert(partners, partner, op->carrier);
259
260                         /* don't insert a node twice */
261                         for (i = 0; i < n_alloc; ++i) {
262                                 if (alloc_nodes[i] == op->carrier) {
263                                         break;
264                                 }
265                         }
266                         if (i < n_alloc)
267                                 continue;
268
269                         alloc_nodes[n_alloc] = op->carrier;
270
271                         DBG((dbg, LEVEL_2, "\tassociating %+F and %+F\n", op->carrier,
272                              partner));
273
274                         bitset_clear_all(bs);
275                         get_decisive_partner_regs(bs, op, op->partner);
276
277                         DBG((dbg, LEVEL_2, "\tallowed registers for %+F: %B\n", op->carrier,
278                              bs));
279
280                         bitset_foreach(bs, col) {
281                                 //hungarian_add(bp, n_alloc, col, 1);
282                                 bipartite_add(bp, n_alloc, col);
283                         }
284
285                         n_alloc++;
286                 }
287         }
288
289         /*
290          * Put all nodes which live through the constrained instruction also to the
291          * allocation bipartite graph. They are considered unconstrained.
292          */
293         if (perm != NULL) {
294                 foreach_out_edge(perm, edge) {
295                         int i;
296                         ir_node *proj = get_edge_src_irn(edge);
297                         be_lv_t *lv   = be_get_irg_liveness(env->irg);
298
299                         assert(is_Proj(proj));
300
301                         if (!be_values_interfere(lv, proj, irn)
302                             || pmap_contains(partners, proj))
303                                 continue;
304
305                         /* don't insert a node twice */
306                         for (i = 0; i < n_alloc; ++i) {
307                                 if (alloc_nodes[i] == proj) {
308                                         break;
309                                 }
310                         }
311                         if (i < n_alloc)
312                                 continue;
313
314
315                         assert(n_alloc < n_regs);
316
317                         alloc_nodes[n_alloc] = proj;
318                         pmap_insert(partners, proj, NULL);
319
320                         bitset_clear_all(bs);
321                         arch_put_non_ignore_regs(env->cls, bs);
322                         bitset_andnot(bs, env->ignore_colors);
323                         bitset_foreach(bs, col) {
324                                 //hungarian_add(bp, n_alloc, col, 1);
325                                 bipartite_add(bp, n_alloc, col);
326                         }
327
328                         n_alloc++;
329                 }
330         }
331
332         /* Compute a valid register allocation. */
333 #if 0
334         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
335         match_res = hungarian_solve(bp, assignment, &cost, 1);
336         assert(match_res == 0 && "matching failed");
337 #else
338         /*bipartite_dump_f(stderr, bp);*/
339         bipartite_matching(bp, assignment);
340 #endif
341
342         /* Assign colors obtained from the matching. */
343         for (i = 0; i < n_alloc; ++i) {
344                 const arch_register_t *reg;
345                 ir_node *irn;
346
347                 assert(assignment[i] >= 0 && "there must have been a register assigned (node not register pressure faithful?)");
348                 reg = arch_register_for_index(env->cls, assignment[i]);
349                 assert(! (reg->type & arch_register_type_ignore));
350
351                 irn = alloc_nodes[i];
352                 if (irn != NULL) {
353                         arch_set_irn_register(irn, reg);
354                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
355                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
356                 }
357
358                 irn = pmap_get(partners, alloc_nodes[i]);
359                 if (irn != NULL) {
360                         arch_set_irn_register(irn, reg);
361                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
362                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
363                 }
364         }
365
366         /* Allocate the non-constrained Projs of the Perm. */
367         if (perm != NULL) {
368                 bitset_clear_all(bs);
369
370                 /* Put the colors of all Projs in a bitset. */
371                 foreach_out_edge(perm, edge) {
372                         ir_node *proj              = get_edge_src_irn(edge);
373                         const arch_register_t *reg = arch_get_irn_register(proj);
374
375                         if (reg != NULL)
376                                 bitset_set(bs, reg->index);
377                 }
378
379                 /* Assign the not yet assigned Projs of the Perm a suitable color. */
380                 foreach_out_edge(perm, edge) {
381                         ir_node *proj              = get_edge_src_irn(edge);
382                         const arch_register_t *reg = arch_get_irn_register(proj);
383
384                         DBG((dbg, LEVEL_2, "\tchecking reg of %+F: %s\n", proj, reg ? reg->name : "<none>"));
385
386                         if (reg == NULL) {
387                                 col = get_next_free_reg(alloc_env, bs);
388                                 reg = arch_register_for_index(env->cls, col);
389                                 bitset_set(bs, reg->index);
390                                 arch_set_irn_register(proj, reg);
391                                 pset_insert_ptr(alloc_env->pre_colored, proj);
392                                 DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", proj, reg->name));
393                         }
394                 }
395         }
396
397         bipartite_free(bp);
398         //hungarian_free(bp);
399         pmap_destroy(partners);
400
401 end:
402         obstack_free(env->obst, base);
403         return res;
404 }
405
406 /**
407  * Handle constraint nodes in each basic block.
408  * handle_constraints() inserts Perm nodes which perm
409  * over all values live at the constrained node right in front
410  * of the constrained node. These Perms signal a constrained node.
411  * For further comments, refer to handle_constraints().
412  */
413 static void constraints(ir_node *bl, void *data)
414 {
415         /*
416          * Start silent in the start block.
417          * The silence remains until the first barrier is seen.
418          * Each other block is begun loud.
419          */
420         int                     silent = bl == get_irg_start_block(get_irn_irg(bl));
421         be_chordal_alloc_env_t *env    = data;
422         ir_node                *irn;
423
424         /*
425          * If the block is the start block search the barrier and
426          * start handling constraints from there.
427          */
428         for (irn = sched_first(bl); !sched_is_end(irn);) {
429                 irn = handle_constraints(env, irn, &silent);
430         }
431 }
432
433 static void assign(ir_node *block, void *env_ptr)
434 {
435         be_chordal_alloc_env_t *alloc_env = env_ptr;
436         be_chordal_env_t *env       = alloc_env->chordal_env;
437         bitset_t *live              = alloc_env->live;
438         bitset_t *colors            = alloc_env->colors;
439         bitset_t *in_colors         = alloc_env->in_colors;
440         struct list_head *head      = get_block_border_head(env, block);
441         be_lv_t *lv                 = be_get_irg_liveness(env->irg);
442
443         const ir_node *irn;
444         border_t *b;
445         int idx;
446
447         bitset_clear_all(colors);
448         bitset_clear_all(live);
449         bitset_clear_all(in_colors);
450
451         DBG((dbg, LEVEL_4, "Assigning colors for block %+F\n", block));
452         DBG((dbg, LEVEL_4, "\tusedef chain for block\n"));
453         list_for_each_entry(border_t, b, head, list) {
454                 DBG((dbg, LEVEL_4, "\t%s %+F/%d\n", b->is_def ? "def" : "use",
455                                         b->irn, get_irn_idx(b->irn)));
456         }
457
458         /*
459          * Add initial defs for all values live in.
460          * Since their colors have already been assigned (The dominators were
461          * allocated before), we have to mark their colors as used also.
462          */
463         be_lv_foreach(lv, block, be_lv_state_in, idx) {
464                 irn = be_lv_get_irn(lv, block, idx);
465                 if (has_reg_class(env, irn)) {
466                         const arch_register_t *reg = arch_get_irn_register(irn);
467                         int col;
468
469                         assert(reg && "Node must have been assigned a register");
470                         col = arch_register_get_index(reg);
471
472                         DBG((dbg, LEVEL_4, "%+F has reg %s\n", irn, reg->name));
473
474                         /* Mark the color of the live in value as used. */
475                         bitset_set(colors, col);
476                         bitset_set(in_colors, col);
477
478                         /* Mark the value live in. */
479                         bitset_set(live, get_irn_idx(irn));
480                 }
481         }
482
483         /*
484          * Mind that the sequence of defs from back to front defines a perfect
485          * elimination order. So, coloring the definitions from first to last
486          * will work.
487          */
488         list_for_each_entry_reverse(border_t, b, head, list) {
489                 ir_node *irn = b->irn;
490                 int nr       = get_irn_idx(irn);
491                 int ignore   = arch_irn_is_ignore(irn);
492
493                 /*
494                  * Assign a color, if it is a local def. Global defs already have a
495                  * color.
496                  */
497                 if (b->is_def && !be_is_live_in(lv, block, irn)) {
498                         const arch_register_t *reg;
499                         int col = NO_COLOR;
500
501                         if (ignore || pset_find_ptr(alloc_env->pre_colored, irn)) {
502                                 reg = arch_get_irn_register(irn);
503                                 col = reg->index;
504                                 assert(!bitset_is_set(colors, col) && "pre-colored register must be free");
505                         } else {
506                                 col = get_next_free_reg(alloc_env, colors);
507                                 reg = arch_register_for_index(env->cls, col);
508                                 assert(arch_get_irn_register(irn) == NULL && "This node must not have been assigned a register yet");
509                                 assert(!arch_register_type_is(reg, ignore) && "Must not assign ignore register");
510                         }
511
512                         bitset_set(colors, col);
513                         arch_set_irn_register(irn, reg);
514
515                         DBG((dbg, LEVEL_1, "\tassigning register %s(%d) to %+F\n", arch_register_get_name(reg), col, irn));
516
517                         assert(!bitset_is_set(live, nr) && "Value's definition must not have been encountered");
518                         bitset_set(live, nr);
519                 } else if (!b->is_def) {
520                         /* Clear the color upon a use. */
521                         const arch_register_t *reg = arch_get_irn_register(irn);
522                         int col;
523
524                         assert(reg && "Register must have been assigned");
525
526                         col = arch_register_get_index(reg);
527 #ifndef NDEBUG
528                         if (!arch_register_type_is(reg, ignore)) {
529                                 assert(bitset_is_set(live, nr) && "Cannot have a non live use");
530                         }
531 #endif
532
533                         bitset_clear(colors, col);
534                         bitset_clear(live, nr);
535                 }
536         }
537 }
538
539 void be_ra_chordal_color(be_chordal_env_t *chordal_env)
540 {
541         be_chordal_alloc_env_t env;
542         char buf[256];
543         be_lv_t *lv;
544         const arch_register_class_t *cls = chordal_env->cls;
545
546         int colors_n          = arch_register_class_n_regs(cls);
547         ir_graph *irg         = chordal_env->irg;
548
549         lv = be_assure_liveness(irg);
550         be_liveness_assure_sets(lv);
551         be_liveness_assure_chk(lv);
552
553         assure_doms(irg);
554
555         env.chordal_env   = chordal_env;
556         env.colors_n      = colors_n;
557         env.colors        = bitset_alloca(colors_n);
558         env.tmp_colors    = bitset_alloca(colors_n);
559         env.in_colors     = bitset_alloca(colors_n);
560         env.pre_colored   = pset_new_ptr_default();
561
562         be_timer_push(T_CONSTR);
563
564         /* Handle register targeting constraints */
565         dom_tree_walk_irg(irg, constraints, NULL, &env);
566
567         if (chordal_env->opts->dump_flags & BE_CH_DUMP_CONSTR) {
568                 snprintf(buf, sizeof(buf), "%s-constr", chordal_env->cls->name);
569                 dump_ir_graph(chordal_env->irg, buf);
570         }
571
572         be_timer_pop(T_CONSTR);
573
574         env.live = bitset_malloc(get_irg_last_idx(chordal_env->irg));
575
576         /* First, determine the pressure */
577         dom_tree_walk_irg(irg, create_borders, NULL, env.chordal_env);
578
579         /* Assign the colors */
580         dom_tree_walk_irg(irg, assign, NULL, &env);
581
582         if (chordal_env->opts->dump_flags & BE_CH_DUMP_TREE_INTV) {
583                 plotter_t *plotter;
584                 ir_snprintf(buf, sizeof(buf), "ifg_%s_%F.eps", chordal_env->cls->name, irg);
585                 plotter = new_plotter_ps(buf);
586                 draw_interval_tree(&draw_chordal_def_opts, chordal_env, plotter);
587                 plotter_free(plotter);
588         }
589
590         bitset_free(env.live);
591         del_pset(env.pre_colored);
592 }
593
594 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_chordal);
595 void be_init_chordal(void)
596 {
597         static be_ra_chordal_coloring_t coloring = {
598                 be_ra_chordal_color
599         };
600         FIRM_DBG_REGISTER(dbg, "firm.be.chordal");
601
602         be_register_chordal_coloring("default", &coloring);
603 }