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