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