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