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