keep timer interface simple - no names and descriptions for timers anymore, you shoul...
[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 #if 0
88 static void check_border_list(struct list_head *head)
89 {
90         border_t *x;
91         list_for_each_entry(border_t, x, head, list) {
92                 assert(x->magic == BORDER_FOURCC);
93         }
94 }
95
96 static void check_heads(be_chordal_env_t *env)
97 {
98         pmap_entry *ent;
99         for (ent = pmap_first(env->border_heads); ent; ent = pmap_next(env->border_heads)) {
100                 /* ir_printf("checking border list of block %+F\n", ent->key); */
101                 check_border_list(ent->value);
102         }
103 }
104 #endif
105
106 static int get_next_free_reg(const be_chordal_alloc_env_t *alloc_env, bitset_t *colors)
107 {
108         bitset_t *tmp = alloc_env->tmp_colors;
109         bitset_copy(tmp, colors);
110         bitset_or(tmp, alloc_env->chordal_env->ignore_colors);
111         return bitset_next_clear(tmp, 0);
112 }
113
114 static bitset_t *get_decisive_partner_regs(bitset_t *bs, const be_operand_t *o1, const be_operand_t *o2)
115 {
116         bitset_t *res = bs;
117
118         if (!o1) {
119                 bitset_copy(bs, o2->regs);
120                 return bs;
121         }
122
123         if (!o2) {
124                 bitset_copy(bs, o1->regs);
125                 return bs;
126         }
127
128         assert(o1->req->cls == o2->req->cls || ! o1->req->cls || ! o2->req->cls);
129
130         if (bitset_contains(o1->regs, o2->regs)) {
131                 bitset_copy(bs, o1->regs);
132         } else if (bitset_contains(o2->regs, o1->regs)) {
133                 bitset_copy(bs, o2->regs);
134         } else {
135                 res = NULL;
136         }
137
138         return res;
139 }
140
141 static void pair_up_operands(const be_chordal_alloc_env_t *alloc_env, be_insn_t *insn)
142 {
143         const be_chordal_env_t *env = alloc_env->chordal_env;
144         bitset_t               *bs  = bitset_alloca(env->cls->n_regs);
145         int                     i;
146         int                     j;
147
148         /*
149          * For each out operand, try to find an in operand which can be assigned the
150          * same register as the out operand.
151         */
152         for (j = 0; j < insn->use_start; ++j) {
153                 int smallest         = -1;
154                 int smallest_n_regs  = 2 * env->cls->n_regs + 1;
155                 be_operand_t *out_op = &insn->ops[j];
156
157                 /* Try to find an in operand which has ... */
158                 for (i = insn->use_start; i < insn->n_ops; ++i) {
159                         int n_total;
160                         const be_operand_t *op = &insn->ops[i];
161
162                         if (op->partner != NULL)
163                                 continue;
164                         if (be_values_interfere(env->birg->lv, op->irn, op->carrier))
165                                 continue;
166
167                         bitset_clear_all(bs);
168                         bitset_copy(bs, op->regs);
169                         bitset_and(bs, out_op->regs);
170                         n_total = bitset_popcnt(op->regs) + bitset_popcnt(out_op->regs);
171
172                         if (!bitset_is_empty(bs) && n_total < smallest_n_regs) {
173                                 smallest = i;
174                                 smallest_n_regs = n_total;
175                         }
176                 }
177
178                 if (smallest >= 0) {
179                         be_operand_t *partner = &insn->ops[smallest];
180                         for (i = insn->use_start; i < insn->n_ops; ++i) {
181                                 if (insn->ops[i].carrier == partner->carrier)
182                                         insn->ops[i].partner = out_op;
183                         }
184
185                         out_op->partner  = partner;
186                         partner->partner = out_op;
187                 }
188         }
189 }
190
191 static ir_node *handle_constraints(be_chordal_alloc_env_t *alloc_env,
192                                    ir_node *irn, int *silent)
193 {
194         int n_regs;
195         bitset_t *bs;
196         ir_node **alloc_nodes;
197         //hungarian_problem_t *bp;
198         int *assignment;
199         pmap *partners;
200         int i, n_alloc;
201         bitset_pos_t col;
202         const ir_edge_t *edge;
203         ir_node *perm = NULL;
204         //int match_res, cost;
205         be_chordal_env_t *env  = alloc_env->chordal_env;
206         void *base             = obstack_base(env->obst);
207         be_insn_t *insn        = chordal_scan_insn(env, irn);
208         ir_node *res           = insn->next_insn;
209         int be_silent          = *silent;
210         bipartite_t *bp;
211
212         if (insn->pre_colored) {
213                 int i;
214                 for (i = 0; i < insn->use_start; ++i)
215                         pset_insert_ptr(alloc_env->pre_colored, insn->ops[i].carrier);
216         }
217
218         /*
219          * If the current node is a barrier toggle the silent flag.
220          * If we are in the start block, we are ought to be silent at the beginning,
221          * so the toggling activates the constraint handling but skips the barrier.
222          * If we are in the end block we handle the in requirements of the barrier
223          * and set the rest to silent.
224          */
225         if (be_is_Barrier(irn))
226                 *silent = !*silent;
227
228         if (be_silent)
229                 goto end;
230
231         /*
232          * Perms inserted before the constraint handling phase are considered to be
233          * correctly precolored. These Perms arise during the ABI handling phase.
234          */
235         if (!insn->has_constraints)
236                 goto end;
237
238         n_regs      = env->cls->n_regs;
239         bs          = bitset_alloca(n_regs);
240         alloc_nodes = ALLOCAN(ir_node*, n_regs);
241         //bp          = hungarian_new(n_regs, n_regs, 2, HUNGARIAN_MATCH_PERFECT);
242         bp          = bipartite_new(n_regs, n_regs);
243         assignment  = ALLOCAN(int, n_regs);
244         partners    = pmap_create();
245
246         /*
247          * prepare the constraint handling of this node.
248          * Perms are constructed and Copies are created for constrained values
249          * interfering with the instruction.
250          */
251         perm = pre_process_constraints(alloc_env->chordal_env, &insn);
252
253         /* find suitable in operands to the out operands of the node. */
254         pair_up_operands(alloc_env, insn);
255
256         /*
257          * look at the in/out operands and add each operand (and its possible partner)
258          * to a bipartite graph (left: nodes with partners, right: admissible colors).
259          */
260         for (i = 0, n_alloc = 0; i < insn->n_ops; ++i) {
261                 be_operand_t *op = &insn->ops[i];
262
263                 /*
264                  * If the operand has no partner or the partner has not been marked
265                  * for allocation, determine the admissible registers and mark it
266                  * for allocation by associating the node and its partner with the
267                  * set of admissible registers via a bipartite graph.
268                  */
269                 if (!op->partner || !pmap_contains(partners, op->partner->carrier)) {
270                         ir_node *partner = op->partner ? op->partner->carrier : NULL;
271                         int i;
272
273                         pmap_insert(partners, op->carrier, partner);
274                         if (partner != NULL)
275                                 pmap_insert(partners, partner, op->carrier);
276
277                         /* don't insert a node twice */
278                         for (i = 0; i < n_alloc; ++i) {
279                                 if (alloc_nodes[i] == op->carrier) {
280                                         break;
281                                 }
282                         }
283                         if (i < n_alloc)
284                                 continue;
285
286                         alloc_nodes[n_alloc] = op->carrier;
287
288                         DBG((dbg, LEVEL_2, "\tassociating %+F and %+F\n", op->carrier,
289                              partner));
290
291                         bitset_clear_all(bs);
292                         get_decisive_partner_regs(bs, op, op->partner);
293
294                         DBG((dbg, LEVEL_2, "\tallowed registers for %+F: %B\n", op->carrier,
295                              bs));
296
297                         bitset_foreach(bs, col) {
298                                 //hungarian_add(bp, n_alloc, col, 1);
299                                 bipartite_add(bp, n_alloc, col);
300                         }
301
302                         n_alloc++;
303                 }
304         }
305
306         /*
307          * Put all nodes which live through the constrained instruction also to the
308          * allocation bipartite graph. They are considered unconstrained.
309          */
310         if (perm != NULL) {
311                 foreach_out_edge(perm, edge) {
312                         int i;
313                         ir_node *proj = get_edge_src_irn(edge);
314
315                         assert(is_Proj(proj));
316
317                         if (!be_values_interfere(env->birg->lv, proj, irn)
318                                         || pmap_contains(partners, proj))
319                                 continue;
320
321                         /* don't insert a node twice */
322                         for (i = 0; i < n_alloc; ++i) {
323                                 if (alloc_nodes[i] == proj) {
324                                         break;
325                                 }
326                         }
327                         if (i < n_alloc)
328                                 continue;
329
330
331                         assert(n_alloc < n_regs);
332
333                         alloc_nodes[n_alloc] = proj;
334                         pmap_insert(partners, proj, NULL);
335
336                         bitset_clear_all(bs);
337                         arch_put_non_ignore_regs(env->cls, bs);
338                         bitset_andnot(bs, env->ignore_colors);
339                         bitset_foreach(bs, col) {
340                                 //hungarian_add(bp, n_alloc, col, 1);
341                                 bipartite_add(bp, n_alloc, col);
342                         }
343
344                         n_alloc++;
345                 }
346         }
347
348         /* Compute a valid register allocation. */
349 #if 0
350         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
351         match_res = hungarian_solve(bp, assignment, &cost, 1);
352         assert(match_res == 0 && "matching failed");
353 #else
354         bipartite_matching(bp, assignment);
355 #endif
356
357         /* Assign colors obtained from the matching. */
358         for (i = 0; i < n_alloc; ++i) {
359                 const arch_register_t *reg;
360                 ir_node *irn;
361
362                 assert(assignment[i] >= 0 && "there must have been a register assigned");
363                 reg = arch_register_for_index(env->cls, assignment[i]);
364                 assert(! (reg->type & arch_register_type_ignore));
365
366                 irn = alloc_nodes[i];
367                 if (irn != NULL) {
368                         arch_set_irn_register(irn, reg);
369                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
370                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
371                 }
372
373                 irn = pmap_get(partners, alloc_nodes[i]);
374                 if (irn != NULL) {
375                         arch_set_irn_register(irn, reg);
376                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
377                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
378                 }
379         }
380
381         /* Allocate the non-constrained Projs of the Perm. */
382         if (perm != NULL) {
383                 bitset_clear_all(bs);
384
385                 /* Put the colors of all Projs in a bitset. */
386                 foreach_out_edge(perm, edge) {
387                         ir_node *proj              = get_edge_src_irn(edge);
388                         const arch_register_t *reg = arch_get_irn_register(proj);
389
390                         if (reg != NULL)
391                                 bitset_set(bs, reg->index);
392                 }
393
394                 /* Assign the not yet assigned Projs of the Perm a suitable color. */
395                 foreach_out_edge(perm, edge) {
396                         ir_node *proj              = get_edge_src_irn(edge);
397                         const arch_register_t *reg = arch_get_irn_register(proj);
398
399                         DBG((dbg, LEVEL_2, "\tchecking reg of %+F: %s\n", proj, reg ? reg->name : "<none>"));
400
401                         if (reg == NULL) {
402                                 col = get_next_free_reg(alloc_env, bs);
403                                 reg = arch_register_for_index(env->cls, col);
404                                 bitset_set(bs, reg->index);
405                                 arch_set_irn_register(proj, reg);
406                                 pset_insert_ptr(alloc_env->pre_colored, proj);
407                                 DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", proj, reg->name));
408                         }
409                 }
410         }
411
412         bipartite_free(bp);
413         //hungarian_free(bp);
414         pmap_destroy(partners);
415
416 end:
417         obstack_free(env->obst, base);
418         return res;
419 }
420
421 /**
422  * Handle constraint nodes in each basic block.
423  * handle_constraints() inserts Perm nodes which perm
424  * over all values live at the constrained node right in front
425  * of the constrained node. These Perms signal a constrained node.
426  * For further comments, refer to handle_constraints().
427  */
428 static void constraints(ir_node *bl, void *data)
429 {
430         /*
431          * Start silent in the start block.
432          * The silence remains until the first barrier is seen.
433          * Each other block is begun loud.
434          */
435         int                     silent = bl == get_irg_start_block(get_irn_irg(bl));
436         be_chordal_alloc_env_t *env    = data;
437         ir_node                *irn;
438
439         /*
440          * If the block is the start block search the barrier and
441          * start handling constraints from there.
442          */
443         for (irn = sched_first(bl); !sched_is_end(irn);) {
444                 irn = handle_constraints(env, irn, &silent);
445         }
446 }
447
448 static void assign(ir_node *block, void *env_ptr)
449 {
450         be_chordal_alloc_env_t *alloc_env = env_ptr;
451         be_chordal_env_t *env       = alloc_env->chordal_env;
452         bitset_t *live              = alloc_env->live;
453         bitset_t *colors            = alloc_env->colors;
454         bitset_t *in_colors         = alloc_env->in_colors;
455         struct list_head *head      = get_block_border_head(env, block);
456         be_lv_t *lv                 = env->birg->lv;
457
458         const ir_node *irn;
459         border_t *b;
460         int idx;
461
462         bitset_clear_all(colors);
463         bitset_clear_all(live);
464         bitset_clear_all(in_colors);
465
466         DBG((dbg, LEVEL_4, "Assigning colors for block %+F\n", block));
467         DBG((dbg, LEVEL_4, "\tusedef chain for block\n"));
468         list_for_each_entry(border_t, b, head, list) {
469                 DBG((dbg, LEVEL_4, "\t%s %+F/%d\n", b->is_def ? "def" : "use",
470                                         b->irn, get_irn_idx(b->irn)));
471         }
472
473         /*
474          * Add initial defs for all values live in.
475          * Since their colors have already been assigned (The dominators were
476          * allocated before), we have to mark their colors as used also.
477          */
478         be_lv_foreach(lv, block, be_lv_state_in, idx) {
479                 irn = be_lv_get_irn(lv, block, idx);
480                 if (has_reg_class(env, irn)) {
481                         const arch_register_t *reg = arch_get_irn_register(irn);
482                         int col;
483
484                         assert(reg && "Node must have been assigned a register");
485                         col = arch_register_get_index(reg);
486
487                         DBG((dbg, LEVEL_4, "%+F has reg %s\n", irn, reg->name));
488
489                         /* Mark the color of the live in value as used. */
490                         bitset_set(colors, col);
491                         bitset_set(in_colors, col);
492
493                         /* Mark the value live in. */
494                         bitset_set(live, get_irn_idx(irn));
495                 }
496         }
497
498         /*
499          * Mind that the sequence of defs from back to front defines a perfect
500          * elimination order. So, coloring the definitions from first to last
501          * will work.
502          */
503         list_for_each_entry_reverse(border_t, b, head, list) {
504                 ir_node *irn = b->irn;
505                 int nr       = get_irn_idx(irn);
506                 int ignore   = arch_irn_is_ignore(irn);
507
508                 /*
509                  * Assign a color, if it is a local def. Global defs already have a
510                  * color.
511                  */
512                 if (b->is_def && !be_is_live_in(lv, block, irn)) {
513                         const arch_register_t *reg;
514                         int col = NO_COLOR;
515
516                         if (ignore || pset_find_ptr(alloc_env->pre_colored, irn)) {
517                                 reg = arch_get_irn_register(irn);
518                                 col = reg->index;
519                                 assert(!bitset_is_set(colors, col) && "pre-colored register must be free");
520                         } else {
521                                 col = get_next_free_reg(alloc_env, colors);
522                                 reg = arch_register_for_index(env->cls, col);
523                                 assert(arch_get_irn_register(irn) == NULL && "This node must not have been assigned a register yet");
524                                 assert(!arch_register_type_is(reg, ignore) && "Must not assign ignore register");
525                         }
526
527                         bitset_set(colors, col);
528                         arch_set_irn_register(irn, reg);
529
530                         DBG((dbg, LEVEL_1, "\tassigning register %s(%d) to %+F\n", arch_register_get_name(reg), col, irn));
531
532                         assert(!bitset_is_set(live, nr) && "Value's definition must not have been encountered");
533                         bitset_set(live, nr);
534                 } else if (!b->is_def) {
535                         /* Clear the color upon a use. */
536                         const arch_register_t *reg = arch_get_irn_register(irn);
537                         int col;
538
539                         assert(reg && "Register must have been assigned");
540
541                         col = arch_register_get_index(reg);
542 #ifndef NDEBUG
543                         if (!arch_register_type_is(reg, ignore)) {
544                                 assert(bitset_is_set(live, nr) && "Cannot have a non live use");
545                         }
546 #endif
547
548                         bitset_clear(colors, col);
549                         bitset_clear(live, nr);
550                 }
551         }
552 }
553
554 void be_ra_chordal_color(be_chordal_env_t *chordal_env)
555 {
556         be_chordal_alloc_env_t env;
557         char buf[256];
558         be_lv_t *lv;
559         be_irg_t *birg = chordal_env->birg;
560         const arch_register_class_t *cls = chordal_env->cls;
561
562         int colors_n          = arch_register_class_n_regs(cls);
563         ir_graph *irg         = chordal_env->irg;
564
565         lv = be_assure_liveness(birg);
566         be_liveness_assure_sets(lv);
567         be_liveness_assure_chk(lv);
568
569         assure_doms(irg);
570
571         env.chordal_env   = chordal_env;
572         env.colors_n      = colors_n;
573         env.colors        = bitset_alloca(colors_n);
574         env.tmp_colors    = bitset_alloca(colors_n);
575         env.in_colors     = bitset_alloca(colors_n);
576         env.pre_colored   = pset_new_ptr_default();
577
578         be_timer_push(T_CONSTR);
579
580         /* Handle register targeting constraints */
581         dom_tree_walk_irg(irg, constraints, NULL, &env);
582
583         if (chordal_env->opts->dump_flags & BE_CH_DUMP_CONSTR) {
584                 snprintf(buf, sizeof(buf), "-%s-constr", chordal_env->cls->name);
585                 be_dump(chordal_env->irg, buf, dump_ir_block_graph_sched);
586         }
587
588         be_timer_pop(T_CONSTR);
589
590         env.live = bitset_malloc(get_irg_last_idx(chordal_env->irg));
591
592         /* First, determine the pressure */
593         dom_tree_walk_irg(irg, create_borders, NULL, env.chordal_env);
594
595         /* Assign the colors */
596         dom_tree_walk_irg(irg, assign, NULL, &env);
597
598         if (chordal_env->opts->dump_flags & BE_CH_DUMP_TREE_INTV) {
599                 plotter_t *plotter;
600                 ir_snprintf(buf, sizeof(buf), "ifg_%s_%F.eps", chordal_env->cls->name, irg);
601                 plotter = new_plotter_ps(buf);
602                 draw_interval_tree(&draw_chordal_def_opts, chordal_env, plotter);
603                 plotter_free(plotter);
604         }
605
606         bitset_free(env.live);
607         del_pset(env.pre_colored);
608 }
609
610 void be_init_chordal(void)
611 {
612         static be_ra_chordal_coloring_t coloring = {
613                 be_ra_chordal_color
614         };
615         FIRM_DBG_REGISTER(dbg, "firm.be.chordal");
616
617         be_register_chordal_coloring("default", &coloring);
618 }
619
620 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_chordal);