Added prototype for phi_ops_interfere
[libfirm] / ir / be / bephicoal.c
1 /**
2  * @author Daniel Grund
3  * @date 04.01.2005
4  */
5
6 #include <stdlib.h>
7
8 #include "obst.h"
9 #include "set.h"
10 #include "pset.h"
11 #include "bitset.h"
12 #include "debug.h"
13 #include "irouts.h"
14 #include "irdom.h"
15
16 #include "bechordal.h"
17 #include "belive.h"
18 #include "bera_t.h"
19 #include "bephicongr_t.h"
20 #include "bephicoal_t.h"
21
22 #define DEBUG_LVL SET_LEVEL_3
23 #define MAX_COLORS 16
24
25 /* some things for readable code */
26 #define CHANGE_SAVE NULL
27 #define CHANGE_IMPOSSIBLE (ir_node *)1
28 #define CHANGE_NYI (ir_node *)2
29 typedef enum _perform_t { dryrun = 0, perform = 1 } perform_t;
30 /* TODO: ask/check if additional ir_node-space is initialized with 0000 */
31 //#define belongs_to_a_phi_class(n) (get_irn_phi_info(n)->phi)
32 //#define is_color_free(bl,col) (!bitset_is_set(get_ra_block_info(bl)->used_colors, col))
33
34 typedef struct _phi_unit_t {
35         unsigned char count;
36         unsigned char phi_count;
37
38         /* 1 phi */
39         ir_node **members;                      /**< [0] is the phi node. [1..count-1] the arguments of the phi not interfering with it */
40         int *colors;                            /**< [i] is the color to set for members[i]. [i] == NO_COLOR means dont change anything for members[i]*/
41         /* TODO: perhaps unneccessary */
42         char *is_live_in;                       /**< [i]==1 means members[i] is live-in in (all of) its cf-pred-blocks of the phi node */
43 } phi_unit_t;
44
45
46 static firm_dbg_module_t *dbgphi = NULL;
47 int XXX_copies=0, XXX_count=0;
48
49
50 /**
51  * Contains ir_nodes of phi-classes whose colors may change unlimited times.
52  * These nodes are not optimizable, so there is no need to pin their color.
53  */
54 static pset *free_nodes = NULL;
55
56 /**
57  * Contains already optimized ir_nodes of phi-classes fully processed.
58  * So one can perform a check not to switch them twice or more.
59  */
60 static pset *pinned_global = NULL;
61
62 /**
63  * Contains optimized ir_nodes of the phi-classes
64  * currently optimized. So one can perform a check not to switch them
65  * twice or more.
66  */
67 static pset *pinned_local = NULL;
68
69 /**
70  * Contains the hypothetic colors of currently processed phi unit
71  */
72 static set *hyp_cols = NULL;
73
74 typedef struct _hyp_col_t {
75         ir_node *irn;
76         int color;
77 } hyp_col_t;
78
79 int set_cmp_hyp_col_t(const void *x, const void *y, size_t size) {
80         return ((hyp_col_t *)x)->irn != ((hyp_col_t *)y)->irn;
81 }
82
83
84 /**
85  * @return The hypothetic color of the irn if available.
86  *         Otherwise the current color of it.
87  */
88 static INLINE int get_hyp_color(ir_node *irn) {
89         hyp_col_t hc;
90         hyp_col_t *found;
91         hc.irn = irn;
92         found = set_find(hyp_cols, &hc, sizeof(hc), HASH_PTR(irn));
93         if (found)
94                 return found->color;
95         else
96                 return get_irn_color(irn);
97 }
98
99 /**
100  * Sets the hypothetic color of an irn
101  */
102 static INLINE void set_hyp_color(ir_node *irn, int color) {
103         hyp_col_t hc;
104         hyp_col_t *found;
105         hc.irn = irn;
106         found = set_find(hyp_cols, &hc, sizeof(hc), HASH_PTR(irn));
107         if (found)
108                 found->color = color;
109         else {
110                 hc.color = color;
111                 set_insert(hyp_cols, &hc, sizeof(hc), HASH_PTR(irn));
112         }
113 }
114
115
116
117 /**
118  * Variable neede in _color_irn.
119  * Not on stack, because never changed during recursion.
120  */
121 static perform_t _color_irn_perform;
122
123 /**
124  * Get all nodes which conflict with the color-setting of a node, because they
125  * have the same color and are living together at some point in time.
126  * @param irn The ir_node to find conflicting nodes for
127  * @param color The color the conflicting nodes must have
128  * @param bl  The root-block of the dom-sub-tree to start the search from.
129  * @param exc An exceptional node which is never added to the result set of conflicting nodes
130  * @param res An obstack to grow the resulting nodes on.
131  */
132 static void get_conflicting_nodes(const ir_node *irn, int color, ir_node *bl, const ir_node *exc, struct obstack *res) {
133         struct obstack q;
134         int in, out;
135
136         /* setup the queue */
137         obstack_init(&q);
138         obstack_ptr_grow(&q, bl);
139         in = 1;
140         out = 0;
141
142         /* process the queue */
143         while (out < in) {
144                 ir_node *curr_bl, *sub_bl;
145                 int i, max;
146
147                 curr_bl = ((ir_node **)obstack_base(&q))[out++];
148
149                 /* Add to the result all nodes in the block which live in target color
150                  * and interfere with the irn */
151                 for (i = 0, max = get_irn_n_outs(curr_bl); i < max; ++i) {
152                         ir_node *n = get_irn_out(curr_bl, i);
153                         int n_col;
154                         if (!is_allocatable_irn(n))
155                                 continue;
156                         if (_color_irn_perform == perform)
157                                 n_col = get_irn_color(n);
158                         else
159                                 n_col = get_hyp_color(n);
160
161                         if (n != exc && get_hyp_color(n) == color && phi_ops_interfere(irn, n))
162                                 obstack_ptr_grow(res, n);
163                 }
164
165                 /* If irn lives out check i-dominated blocks where the irn lives in */
166                 /* Fill the queue */
167                 if (is_live_out(curr_bl, irn)) {
168                         dominates_for_each(curr_bl, sub_bl)
169                                 if (is_live_in(sub_bl, irn)) {
170                                         obstack_ptr_grow(&q, sub_bl);
171                                         in++;
172                                 }
173                 }
174         }
175
176         obstack_free(&q, NULL);
177 }
178
179
180 /**
181  * Tries to set the color of @p n to @p col. Performs recoloring of other nodes
182  * as required to preserve correctness. Recursive.
183  * @param  irn The node to set the color for
184  * @param  col The color to set.
185  * @param  trigger The irn that caused the wish to change the color of the irn
186  * @return CHANGE_SAVE iff setting the color is possible.
187  *         CHANGE_IMPOSSIBLE iff conflicts with reg-constraintsis occured.
188  *         Else the conflicting ir_node is returned.
189  *
190  * ASSUMPTION: Assumes that a life range of a single value can't be spilt into
191  *                         several smaller intervals where other values can live in between.
192  */
193 static ir_node *_color_irn(ir_node *irn, int col, const ir_node *trigger) {
194         ir_node *res;
195         struct obstack confl_ob;
196         ir_node **confl, *cn;
197         ir_node *irn_bl;
198         int i, irn_col;
199         if (_color_irn_perform == perform)
200                 irn_col = get_irn_color(irn);
201         else
202                 irn_col = get_hyp_color(irn);
203
204         obstack_init(&confl_ob);
205
206         if (irn_col == col)
207                 goto ret_save;
208
209         if (pset_find_ptr(pinned_global, irn)) {
210                 DBG((dbgphi, LEVEL_3, "\t\t\t%n \t~~> %n := %d: Pinned other\n", trigger, irn, col));
211                 res = irn;
212                 goto ret_confl;
213         }
214
215         if (pset_find_ptr(pinned_local, irn)) {
216                 DBG((dbgphi, LEVEL_3, "\t\t\t%n \t~~> %n := %d: Pinned current\n", trigger, irn, col));
217                 res = irn;
218                 goto ret_confl;
219         }
220
221         /* process all nodes which would conflict with this change */
222         irn_bl = get_nodes_block(irn);
223         get_conflicting_nodes(irn, col, irn_bl, trigger, &confl_ob);
224         obstack_ptr_grow(&confl_ob, NULL);
225         confl = (ir_node **) obstack_finish(&confl_ob);
226
227         for (i = 0, cn = confl[0]; cn; cn = confl[++i]) {
228                 ir_node *sub_res;
229
230                 /* for now don't let the changes spread in root-direction of the dom-tree */
231                 if (is_live_in(irn_bl, cn)) {
232                         DBG((dbgphi, LEVEL_3, "\t\t\t%n \t~~> %n := %d: NYI %n\n", trigger, irn, col, cn));
233                         res = CHANGE_NYI;
234                         goto ret_confl;
235                 }
236
237                 /* try to color the conflicting node cn with the color of the irn itself */
238                 DBG((dbgphi, LEVEL_3, "\t\t\t%n \t~~> %n := %d: Subcheck\n", trigger, irn, col));
239                 sub_res = _color_irn(cn, irn_col, irn);
240                 if (sub_res != CHANGE_SAVE) {
241                         res = sub_res;
242                         goto ret_confl;
243                 }
244         }
245         /* if we arrive here all sub changes can be applied,
246          * so it is save to change this irn */
247
248 ret_save:
249         DBG((dbgphi, LEVEL_2, "\t\t\t%n \t~~> %n := %d: Save\n", trigger, irn, col));
250         obstack_free(&confl_ob, NULL);
251         if (_color_irn_perform == perform)
252                 set_irn_color(irn, col);
253         else
254                 set_hyp_color(irn, col);
255         return CHANGE_SAVE;
256
257 ret_confl:
258         DBG((dbgphi, LEVEL_2, "\t\t\t%n \t~~> %n := %d: Conflict\n", trigger, irn, col));
259         obstack_free(&confl_ob, NULL);
260         assert(!_color_irn_perform && "When applying changes these must be save, but if you reach here they aren't!");
261         return res;
262 }
263
264
265 static ir_node *color_irn(ir_node *irn, int col, perform_t do_what) {
266         ir_node *res;
267
268         _color_irn_perform = do_what;
269         res = _color_irn(irn, col, irn);
270
271         if (res == CHANGE_SAVE && !pset_find_ptr(free_nodes, irn)) {
272                 if (do_what == perform) {
273                         DBG((dbgphi, LEVEL_2, "\t\t\t\t\t @G %n\n", irn));
274                         pset_insert_ptr(pinned_global, irn);
275                 } else {
276                         DBG((dbgphi, LEVEL_2, "\t\t\t\t\t @L %n\n", irn));
277                         pset_insert_ptr(pinned_local, irn);
278                 }
279         }
280         return res;
281 }
282
283
284 /**
285  * Tries to set as much members of a phi unit as possible to color @p col.
286  * - Each change taken alone is guaranteed to be conflict free.
287  * - _If_ all members are neither live-in nor live-out in their cf-pred-blocks
288  *   _then_ all changes together can be applied conflict free.
289  * - _If_ there is a member, which is live-in or live-out in its cf-pred-block
290  *    of the phi node, it is possible that all changes together will conflict.
291  * TODO: Check above comment with swapping complete colors in mind
292  * TODO: Write sth. about dom-tree influence on this.
293  */
294 static int try_colors(phi_unit_t *pu, int col, int b_size) {
295         struct obstack ob;
296         int i, o, cand_size, mis_size;
297         ir_node **cand, **mis;
298
299         obstack_init(&ob);
300         pinned_local = pset_new_ptr(8);
301         hyp_cols = new_set(set_cmp_hyp_col_t, 8);
302
303         /* first init pessimistically, so we can just return
304          * if we see there wont be a better result */
305         mis_size = 0;
306         for (i = 0; i < pu->count; ++i)
307                 pu->colors[i] = NO_COLOR;
308
309         /* For all members check if color would be possible.
310          * Does not check if color is possible in combination with
311          * other members colors being set */
312         cand_size = 0;
313         for (i = 0; i < pu->count; ++i) {
314                 DBG((dbgphi, 1, "\t\t    Testing %n\n", pu->members[i]));
315                 if (color_irn(pu->members[i], col, dryrun) == CHANGE_SAVE) {
316                         DBG((dbgphi, 1, "\t\t\tAdding to cand\n"));
317                         obstack_ptr_grow(&ob, pu->members[i]);
318                         cand_size++;
319                 } else {
320                         DBG((dbgphi, 1, "\t\t\tImpossible\n"));
321                 }
322                 /* if color is not possible for the phi node then exit (phi comes first)*/
323                 if (cand_size == 0)
324                         goto ret;
325         }
326         cand = obstack_finish(&ob);
327
328         /* shortcut: if cand is worse than best then mis wont be better. */
329         if (cand_size < b_size)
330                 goto ret;
331
332         /* now take the candidates cand and determine a max independent set
333          * with respect to edges representing live range interference */
334         /* TODO: make this 'un-greedy' */
335         DBG((dbgphi, 1, "\t\t    Max indep set\n"));
336         for (i = 0; i < cand_size; ++i) {
337                 int intf_det = 0;
338                 for (o = 0; o < mis_size; ++o) {
339                         mis = (ir_node**) obstack_base(&ob);
340                         if (phi_ops_interfere(cand[i], mis[o])) {
341                                 intf_det = 1;
342                                 break;
343                         }
344                 }
345
346                 if (!intf_det) {
347                         DBG((dbgphi, 1, "\t\t\tAdding to mis %n\n", cand[i]));
348                         obstack_ptr_grow(&ob, cand[i]);
349                         mis_size++;
350                 }
351         }
352         mis = obstack_finish(&ob);
353
354         /* Now set the colors of all nodes in the mis to col.
355          * HINT: Set the color of all nodes, even if one has the same color already */
356         for (i = 0; i < pu->count; ++i)
357                 for (o = 0; o < mis_size; ++o)
358                         if (pu->members[i] == mis[o])
359                                 pu->colors[i] = col;
360
361 ret:
362         del_set(hyp_cols);
363         del_pset(pinned_local);
364         obstack_free(&ob, NULL);
365         return mis_size;
366 }
367
368
369 /**
370  * Sets the colors of members[i] to colors[i].
371  * All changes togehter must be conflict free.
372  */
373 static void set_colors(phi_unit_t *pu) {
374         int i;
375
376         for (i = 0; i < pu->count; ++i)
377                 if (pu->colors[i] != NO_COLOR)
378                         color_irn(pu->members[i], pu->colors[i], perform);
379 }
380
381
382 /**
383  * Tries to re-allocate colors of this phi-class, to achieve a lower number of
384  * copies placed during phi destruction. Optimized version. Works only for
385  * phi-classes/phi-units with exactly 1 phi node, which is the case for approx.
386  * 80% of all phi classes.
387  */
388 static void coalesce_1_phi(phi_unit_t *pu) {
389         int *b_colors, b_size, b_color;
390         int i, size, col;
391
392         b_colors = malloc(pu->count * sizeof(*b_colors));
393
394         /* init best search result */
395         b_size = 0;
396         b_color = NO_COLOR;
397         for (i = 0; i < pu->count; ++i)
398                 b_colors[i] = NO_COLOR;
399
400         /* find optimum of all colors */
401         for (col = MAX_COLORS-1; col >= 0; --col) {
402                 DBG((dbgphi, 1, "\tTrying color %d\n", col));
403                 size = try_colors(pu, col, b_size);
404
405                 /* did we find a better max ind. set? */
406                 if (size > b_size) {
407                         b_size = size;
408                         b_color = col;
409                         memcpy(b_colors, pu->colors, pu->count * sizeof(*b_colors));
410                         DBG((dbgphi, 1, "\t!! Better size: %d\n", b_size));
411                 }
412
413                 /* shortcut: if all members can be colored we are content */
414                 if (b_size == pu->count)
415                         break;
416         }
417         DBG((dbgphi, 1, "\tBest color: %d  Copies: %d/%d\n", b_color, pu->count-b_size, pu->count));
418         XXX_copies += pu->count-b_size;
419         XXX_count += pu->count;
420         if (b_color == NO_COLOR)
421                 goto ret;
422
423         /* now apply the found optimum */
424         memcpy(pu->colors, b_colors, pu->count * sizeof(*b_colors));
425         set_colors(pu);
426
427 ret:
428         free(b_colors);
429 }
430
431
432 /**
433  * Tries to re-allocate colors of this phi-class, to achieve a lower number of
434  * copies placed during phi destruction. General purpose version.
435  */
436 static void coalesce_n_phi(phi_unit_t *pu) {
437         DBG((dbgphi, 1, "\n"));
438         /* TODO */
439 }
440
441
442 /**
443  * Prepares a phi class for further processing as a phi unit.
444  * @param pc The phi class to prepare.
445  * @return A so called phi unit containing some prepared informations
446  *         needed by the following coalescing phase.
447  */
448 static phi_unit_t *new_phi_unit(pset *pc) {
449         phi_unit_t *pu;
450         ir_node *n, *phi = NULL;
451
452         /* get the phi count of this class */
453         pu = malloc(sizeof(*pu));
454         pu->phi_count = 0;
455         for (n = pset_first(pc); n; n = pset_next(pc))
456                 if (is_Phi(n)) {
457                         phi = n;
458                         pu->phi_count++;
459                 }
460
461         if (pu->phi_count == 1) {
462                 ir_node **tmp, *phi_block;
463                 int i, max;
464                 struct obstack ob;
465
466                 obstack_init(&ob);
467
468                 /* build member set not containing phi interferers */
469                 DBG((dbgphi, 1, "Phi-1 class:\n"));
470                 pu->count = 1; /*for the phi*/
471                 for (n = pset_first(pc); n; n = pset_next(pc)) {
472                         if (is_Phi(n))
473                                 continue;
474                         if (!phi_ops_interfere(phi, n)) {
475                                 DBG((dbgphi, 1, "\tAdding to members: %n\n", n));
476                                 obstack_ptr_grow(&ob, n);
477                                 pu->count++;
478                         } else {
479                                 DBG((dbgphi, 1, "\tPhi interferer: %n\n", n));
480                                 pset_insert_ptr(free_nodes, n);
481                         }
482                 }
483                 tmp = obstack_finish(&ob);
484                 pu->members = malloc(pu->count * sizeof(*pu->members));
485                 pu->members[0] = phi;
486                 memcpy(&pu->members[1], tmp, (pu->count-1) * sizeof(*tmp));
487
488                 /* init of colors array */
489                 pu->colors = malloc(pu->count * sizeof(*pu->colors));
490
491                 /* live-in analysis */
492                 /* HINT: It is possible that a node occurs twice as arg of a phi,
493                  * one time being live-in, and another time not being live-in.
494                  */
495                 pu->is_live_in = calloc(pu->count, sizeof(*pu->is_live_in));
496                 phi_block = get_nodes_block(phi);
497                 for (i = 0, max = get_irn_arity(phi); i < max; ++i) {
498                         int midx, o;
499                 ir_node *arg, *block_ith_pred;
500
501                 arg = get_irn_n(phi, i);
502                         block_ith_pred = get_nodes_block(get_irn_n(phi_block, i));
503
504                         /* find the arg in the members array */
505                         midx = -1;
506                         for (o = 0; o < pu->count; ++o)
507                                 if (pu->members[o] == arg) {
508                                         midx = o;
509                                         break;
510                                 }
511                         if (midx == -1)
512                                 continue;
513
514                         if (is_live_in(block_ith_pred, arg)) {
515                                 pu->is_live_in[midx] |= 1;
516                                 DBG((dbgphi, 1, "\t%n is live-in in %n\n", arg, block_ith_pred));
517                         }
518                 }
519
520                 obstack_free(&ob, NULL);
521         } else {
522                 DBG((dbgphi, 1, "Phi-n class:\n"));
523                 /* TODO */
524         }
525
526         DBG((dbgphi, 1, "\n"));
527         return pu;
528 }
529
530
531 /**
532  * Deletes a phi unit
533  */
534 static void free_phi_unit(phi_unit_t *pu) {
535         if (pu->phi_count == 1) {
536                 free(pu->members);
537                 free(pu->colors);
538                 free(pu->is_live_in);
539         } else {
540                 /* TODO */
541         }
542         free(pu);
543 }
544
545
546 void be_phi_coalesce(pset *all_phi_classes) {
547         pset *pc;
548
549         pinned_global = pset_new_ptr(256);
550         free_nodes = pset_new_ptr(64);
551
552         for (pc = pset_first(all_phi_classes); pc; pc = pset_next(all_phi_classes)) {
553                 phi_unit_t *pu = new_phi_unit(pc);
554                 if (pu->phi_count == 1)
555                         coalesce_1_phi(pu);
556                 else
557                         coalesce_n_phi(pu);
558                 free_phi_unit(pu);
559         }
560
561         DBG((dbgphi, 1, "Copies: %d / %d\n", XXX_copies, XXX_count));
562
563         del_pset(free_nodes);
564         del_pset(pinned_global);
565 }
566
567
568 void be_phi_coal_init(void) {
569         dbgphi = firm_dbg_register("Phi coalescing");
570         firm_dbg_set_mask(dbgphi, DEBUG_LVL);
571 }