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