Splitted in two phases pressure/liveness and assignment
[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_t.h"
18 #include "bera_t.h"
19 #include "phiclass_t.h"
20 #include "bephicoal_t.h"
21
22 #define DEBUG_LVL SET_LEVEL_3
23 #define MAX_COLORS 16
24
25 #define INITIAL_SLOTS_PINNED_GLOBAL 256
26 #define INITIAL_SLOTS_FREE_NODES    128
27 #define INITIAL_SLOTS_CHANGED_NODES 32
28
29 /* some things for readable code */
30 #define CHANGE_SAVE NULL
31 #define CHANGE_IMPOSSIBLE (ir_node *)1
32 #define CHANGE_NYI (ir_node *)2
33 #define is_conflicting_node(n) (((int)n) > 2)
34
35 /**
36  * Models conflicts between nodes. These may be life range conflicts or
37  * pinning conflicts which may occur while changing colors
38  */
39 typedef struct _conflict_t {
40         ir_node *n1, *n2;
41 } conflict_t;
42
43 /**
44  * If an irn is changed, the changes first get stored in a node_stat_t,
45  * to allow undo of changes in case of conflicts.
46  */
47 typedef struct _node_stat_t {
48         ir_node *irn;
49         int color;
50         int undo_color;
51         char status;            /**< Bit 0: pinned, Bit 1: removed */
52 } node_stat_t;
53
54 #define _set_pinned(nodestat)    nodestat->status |= 1
55 #define _set_removed(nodestat)   nodestat->status |= 2
56 #define _clear_pinned(nodestat)  nodestat->status &= 255 ^ 1
57 #define _clear_removed(nodestat) nodestat->status &= 255 ^ 2
58 #define _is_pinned(nodestat)     (nodestat->status & 1)
59 #define _is_removed(nodestat)    (nodestat->status & 2)
60
61 /**
62  * Central data structure. Contains infos needed during coalescing of the
63  * corresponding phi class.
64  */
65 typedef struct _phi_unit_t {
66         unsigned char phi_count;                        /**< the number of phi nodes in this unit */
67         /* 1 phi */
68         unsigned char node_count;                       /**< size of the nodes-array */
69         unsigned char conflict_count;           /**< size of the conflicts-array */
70         unsigned char conflict_count_org;       /**< initial size of the conflicts-array */
71         ir_node **nodes;                                        /**< [0] is the phi node. [1..node_count-1] the arguments of the phi not interfering with it */
72         conflict_t *conflicts;                          /**< pairs of conflicting ir_nodes. */
73         set *changed_nodes;                                     /**< contains node_stat_t's. */
74 } phi_unit_t;
75
76 static firm_dbg_module_t *dbgphi = NULL;
77
78 /**
79  * Contains ir_nodes of phi-classes whose colors may change unlimited times.
80  * These nodes are not optimizable, so there is no need to pin their color.
81  */
82 static pset *free_nodes = NULL;
83
84 /**
85  * Contains already optimized ir_nodes of phi-classes fully processed.
86  * So one can perform a check not to switch them twice or more.
87  */
88 static pset *pinned_global = NULL;
89
90 int set_cmp_node_stat_t(const void *x, const void *y, size_t size) {
91         return ((node_stat_t *)x)->irn != ((node_stat_t *)y)->irn;
92 }
93
94 /**
95  * Finds a node status entry of a node if existent.
96  */
97 static INLINE node_stat_t *pu_find_node(phi_unit_t *pu, ir_node *irn) {
98         node_stat_t find;
99         find.irn = irn;
100         return set_find(pu->changed_nodes, &find, sizeof(find), HASH_PTR(irn));
101 }
102
103 /**
104  * Finds a node status entry of a node if existent. Otherwise it will return
105  * an initialized new entry for this node.
106  */
107 static INLINE node_stat_t *pu_find_or_insert_node(phi_unit_t *pu, ir_node *irn) {
108         node_stat_t find;
109         find.irn = irn;
110         find.color = NO_COLOR;
111         find.undo_color = NO_COLOR;
112         find.status = 0;
113         return set_insert(pu->changed_nodes, &find, sizeof(find), HASH_PTR(irn));
114 }
115
116 /**
117  * @return The virtual color of a node, if set before, else just the real color.
118  */
119 static INLINE int pu_get_new_color(phi_unit_t *pu, ir_node *irn) {
120         node_stat_t *found = pu_find_node(pu, irn);
121         if (found)
122                 return found->color;
123         else
124                 return get_irn_color(irn);
125 }
126
127 /**
128  * Sets the virtual color of a node.
129  */
130 static INLINE void pu_set_new_color(phi_unit_t *pu, ir_node *irn, int color) {
131         node_stat_t *found = pu_find_or_insert_node(pu, irn);
132         /* TODO Think about
133          * This is only correct if no color is set >=2 times while changing
134          * a single phi-unit-member */
135         found->undo_color = found->color;
136         found->color = color;
137 }
138
139 /**
140  * Checks if a node is removed from consideration respectively building
141  * a maximum independent set.
142  */
143 static INLINE int pu_is_node_removed(phi_unit_t *pu, ir_node *irn) {
144         node_stat_t *found = pu_find_node(pu, irn);
145         if (found)
146                 return _is_removed(found);
147         else
148                 return 0;
149 }
150
151 /**
152  * Removes a node from the base set, out of which a maximum independet
153  * set gets build from.
154  */
155 static INLINE void pu_remove_node(phi_unit_t *pu, ir_node *irn) {
156         node_stat_t *found = pu_find_or_insert_node(pu, irn);
157         _set_removed(found);
158 }
159
160 /**
161  * Checks if a node is local pinned; i.e. it belongs to the same phi unit and
162  * has been optimized before the current processed one.
163  */
164 static INLINE int pu_is_node_pinned(phi_unit_t *pu, ir_node *irn) {
165         node_stat_t *found = pu_find_node(pu, irn);
166         if (found)
167                 return _is_pinned(found);
168         else
169                 return 0;
170 }
171
172 /**
173  * Local-pins a node, so optimizations of further nodes of the same phi unit
174  * can handle situations in which a color change would undo prior optimizations.
175  */
176 static INLINE void pu_pin_node(phi_unit_t *pu, ir_node *irn) {
177         node_stat_t *found = pu_find_or_insert_node(pu, irn);
178         _set_pinned(found);
179 }
180
181 /**
182  * If a local pinned conflict occurs, a new edge in the conflict graph is added.
183  * The next maximum independent set build, will regard it.
184  */
185 static INLINE void pu_add_conflict(phi_unit_t *pu, ir_node *n1, ir_node *n2) {
186         int count = pu->conflict_count;
187
188         assert(count != 255 && "Too much conflicts. Can hold max 255 entries");
189         if ((count & 15) == 0)
190                 pu->conflicts = realloc(pu->conflicts, (count + 16)*sizeof(*pu->conflicts));
191
192         if ((int)n1 < (int)n2) {
193                 pu->conflicts[count].n1 = n1;
194                 pu->conflicts[count].n2 = n2;
195         } else {
196                 pu->conflicts[count].n1 = n2;
197                 pu->conflicts[count].n2 = n1;
198         }
199
200         pu->conflict_count++;
201 }
202
203 /**
204  * Checks if two nodes are in a conflict.
205  */
206 static INLINE int pu_are_conflicting(phi_unit_t *pu, ir_node *n1, ir_node *n2) {
207         const ir_node *o1, *o2;
208         int i;
209
210         if ((int)n1 < (int)n2) {
211                 o1 = n1;
212                 o2 = n2;
213         } else {
214                 o1 = n2;
215                 o2 = n1;
216         }
217
218         for (i = 0; i < pu->conflict_count; ++i)
219                 if (pu->conflicts[i].n1 == o1 && pu->conflicts[i].n2 == o2)
220                         return 1;
221         return 0;
222 }
223
224 /**
225  * Determines a maximum independent set with respect to the conflict edges
226  * in pu->conflicts and the nodes beeing all non-removed nodes of pu->nodes.
227  * TODO: make this 'un-greedy'
228  * TODO: be aware that phi nodes should find their way in the set.
229  *       for 1 phi in greedy version this is no prob, cause is comes first at [0].
230  */
231 int pu_get_max_ind_set(phi_unit_t *pu, struct obstack *res) {
232         int i, o, size = 0;
233         ir_node **mis;
234
235         DBG((dbgphi, 1, "\t\t    Max indep set\n"));
236         for (i = 0; i < pu->node_count; ++i) {
237                 int intf_det = 0;
238                 if (pu_is_node_removed(pu, pu->nodes[i]))
239                         continue;
240                 mis = (ir_node**) obstack_base(res);
241                 for (o = 0; o < size; ++o)
242                         if (phi_ops_interfere(pu->nodes[i], mis[o])) {
243                                 intf_det = 1;
244                                 break;
245                         }
246
247                 if (!intf_det) {
248                         DBG((dbgphi, 1, "\t\t\tAdding to mis %n\n", pu->nodes[i]));
249                         obstack_ptr_grow(res, pu->nodes[i]);
250                         size++;
251                 }
252         }
253         return size;
254 }
255
256 /**
257  * Performs virtual re-coloring of node @p n to color @p col. Virtual colors of
258  * other nodes are changed too, as required to preserve correctness. Function is
259  * aware of local and global pinning. Recursive.
260  * @param  irn The node to set the color for
261  * @param  col The color to set.
262  * @param  trigger The irn that caused the wish to change the color of the irn
263  * @param  changed_nodes An obstack on which all ir_nodes get growed on, which are changed
264  * @return CHANGE_SAVE iff setting the color is possible, with all transiteve effects.
265  *         CHANGE_IMPOSSIBLE iff conflicts with reg-constraintsis occured.
266  *         CHANGE_NYI iff an unhandled situation occurs.
267  *         Else the first conflicting ir_node encountered is returned.
268  *
269  * ASSUMPTION: Assumes that a life range of a single value can't be spilt into
270  *                         several smaller intervals where other values can live in between.
271  */
272 static ir_node *_pu_color_irn(phi_unit_t *pu, ir_node *irn, int col, const ir_node *trigger, struct obstack *changed_nodes) {
273         ir_node *res;
274         struct obstack confl_ob;
275         ir_node **confl, *cn;
276         int i, irn_col;
277
278         obstack_init(&confl_ob);
279         irn_col = pu_get_new_color(pu, irn);
280
281         if (irn_col == col)
282                 goto ret_save;
283         if (pset_find_ptr(pinned_global, irn) || pu_is_node_pinned(pu, irn)) {
284                 DBG((dbgphi, LEVEL_2, "\t\t\t%n \t~~> %n := %d: Pinned\n", trigger, irn, col));
285                 res = irn;
286                 goto ret_confl;
287         }
288
289         /* get all nodes which would conflict with this change */
290         {
291                 struct obstack q;
292                 int in, out;
293                 ir_node *irn_bl;
294
295                 irn_bl = get_nodes_block(irn);
296
297                 /* first check for a conflicting node which is 'living in' the irns block */
298                 {
299                         ir_node *n;
300                         pset *live_ins = get_live_in(irn_bl);
301                         for (n = pset_first(live_ins); n; n = pset_next(live_ins))
302                                 if (is_allocatable_irn(n) && n != trigger && pu_get_new_color(pu, n) == col && phi_ops_interfere(irn, n)) {
303                                         DBG((dbgphi, LEVEL_3, "\t\t\t\t\t ******************** %n %n\n", irn, n));
304                                         obstack_ptr_grow(&confl_ob, n);
305                                         pset_break(live_ins);
306                                         break;
307                                 }
308                 }
309
310                 /* setup the queue of blocks */
311                 obstack_init(&q);
312                 obstack_ptr_grow(&q, irn_bl);
313                 in = 1;
314                 out = 0;
315
316                 /* process the queue */
317                 while (out < in) {
318                         ir_node *curr_bl, *sub_bl;
319                         int i, max;
320
321                         curr_bl = ((ir_node **)obstack_base(&q))[out++];
322
323                         /* Add to the result all nodes in the block which live in target color
324                          * and interfere with the irn */
325                         for (i = 0, max = get_irn_n_outs(curr_bl); i < max; ++i) {
326                                 ir_node *n = get_irn_out(curr_bl, i);
327                                 if (is_allocatable_irn(n) && n != trigger && pu_get_new_color(pu, n) == col && phi_ops_interfere(irn, n))
328                                         obstack_ptr_grow(&confl_ob, n);
329                         }
330
331                         /* If irn lives out check i-dominated blocks where the irn lives in */
332                         /* Fill the queue */
333                         if (is_live_out(curr_bl, irn)) {
334                                 dominates_for_each(curr_bl, sub_bl)
335                                         if (is_live_in(sub_bl, irn)) {
336                                                 obstack_ptr_grow(&q, sub_bl);
337                                                 in++;
338                                         }
339                         }
340                 }
341                 obstack_free(&q, NULL);
342                 obstack_ptr_grow(&confl_ob, NULL);
343                 confl = (ir_node **) obstack_finish(&confl_ob);
344         }
345
346         /* process all nodes which would conflict with this change */
347         for (i = 0, cn = confl[0]; cn; cn = confl[++i]) {
348                 ir_node *sub_res;
349
350                 /* try to color the conflicting node cn with the color of the irn itself */
351                 DBG((dbgphi, LEVEL_3, "\t\t\t%n \t~~> %n := %d: Subcheck\n", trigger, irn, col));
352                 sub_res = _pu_color_irn(pu, cn, irn_col, irn, changed_nodes);
353                 if (sub_res != CHANGE_SAVE) {
354                         res = sub_res;
355                         goto ret_confl;
356                 }
357         }
358         /* if we arrive here all sub changes can be applied, so it's save to change this irn */
359
360 ret_save:
361         DBG((dbgphi, LEVEL_2, "\t\t\t%n \t~~> %n := %d: Save\n", trigger, irn, col));
362         obstack_free(&confl_ob, NULL);
363         pu_set_new_color(pu, irn, col);
364         obstack_ptr_grow(changed_nodes, irn);
365         return CHANGE_SAVE;
366
367 ret_confl:
368         DBG((dbgphi, LEVEL_2, "\t\t\t%n \t~~> %n := %d: Conflict\n", trigger, irn, col));
369         obstack_free(&confl_ob, NULL);
370         return res;
371 }
372
373 #define pu_color_irn(pu,irn,col,ob) _pu_color_irn(pu, irn, col, irn, ob)
374
375 /**
376  * Tries to set as much members of a phi unit as possible to color @p col.
377  * All changes taken together are guaranteed to be conflict free.
378  */
379 static int pu_try_color(phi_unit_t *pu, int col, int b_size) {
380         struct obstack ob_mis, ob_undo;
381         int i, redo, mis_size;
382         ir_node **mis;
383
384         /* first init pessimistically. Just return if we can't get a better result */
385         mis_size = 0;
386
387         obstack_init(&ob_mis);
388         obstack_init(&ob_undo);
389         redo = 1;
390         while (redo) {
391                 redo = 0;
392                 /* get a max independent set regarding current conflicts */
393                 mis_size = pu_get_max_ind_set(pu, &ob_mis);
394                 mis = obstack_finish(&ob_mis);
395
396                 /* shortcut: if mis size is worse than best, then mis won't be better. */
397                 if (mis_size < b_size)
398                         goto ret;
399
400                 /* check if its possible to set the color for all members of the maximum set*/
401                 for (i = 0; i < mis_size; ++i) {
402                         ir_node *test_node, *confl_node;
403
404                         test_node = mis[i];
405                         DBG((dbgphi, 1, "\t\t    Testing %n\n", test_node));
406                         confl_node = pu_color_irn(pu, test_node, col, &ob_undo);
407
408                         if (confl_node == CHANGE_SAVE) {
409                                 if (!pset_find_ptr(free_nodes, test_node))
410                                         pu_pin_node(pu, test_node);
411                                 obstack_free(&ob_undo, obstack_finish(&ob_undo));
412                                 continue;
413                         } else {
414                                 int i;
415                                 ir_node *undo_node, **undo_nodes;
416
417                                 obstack_ptr_grow(&ob_undo, NULL);
418                                 undo_nodes = obstack_finish(&ob_undo);
419                                 for (i = 0, undo_node = undo_nodes[0]; undo_node; undo_node = undo_nodes[++i]) {
420                                         node_stat_t *ns = pu_find_node(pu, undo_node);
421                                         ns->color = ns->undo_color;
422                                 }
423                                 obstack_free(&ob_undo, undo_nodes);
424
425                                 if (is_conflicting_node(confl_node)) {
426                                         if (pu_is_node_pinned(pu, confl_node))
427                                                 pu_add_conflict(pu, confl_node, test_node);
428                                         if (pset_find_ptr(pinned_global, confl_node))
429                                                 pu_remove_node(pu, test_node);
430                                 }
431                         }
432
433                         /* shortcut: color not possible for phi node (phi comes first) ==> exit */
434                         if (i == 0)
435                                 goto ret;
436                 }
437                 obstack_free(&ob_mis, mis);
438         }
439
440 ret:
441         obstack_free(&ob_undo, NULL);
442         obstack_free(&ob_mis, NULL);
443         return mis_size;
444 }
445
446 /**
447  * Tries to re-allocate colors of nodes in this phi unit, to achieve a lower
448  * number of copy instructions placed during phi destruction. Optimized version.
449  * Works only for phi-classes/phi-units with exactly 1 phi node, which is the
450  * case for approximately 80% of all phi units.
451  */
452 static void pu_coalesce_1_phi(phi_unit_t *pu) {
453         int size, col, b_size, b_color;
454         set *b_changes;
455
456         /* init best search result */
457         b_changes = NULL;
458         b_size = 0;
459         b_color = NO_COLOR;
460
461         /* find optimum of all colors */
462         for (col = MAX_COLORS-1; col >= 0; --col) {
463                 DBG((dbgphi, 1, "\tTrying color %d\n", col));
464                 size = pu_try_color(pu, col, b_size);
465
466                 /* did we find a better max ind. set? */
467                 if (size > b_size) {
468                         DBG((dbgphi, 1, "\t!! Better size: %d\n", size));
469                         if (b_changes)
470                                 del_set(b_changes);
471                         b_changes = pu->changed_nodes;
472                         b_size = size;
473                         b_color = col;
474                 } else {
475                         del_set(pu->changed_nodes);
476                 }
477
478                 /* reset the phi unit to original state for next color */
479                 pu->changed_nodes = new_set(set_cmp_node_stat_t, INITIAL_SLOTS_CHANGED_NODES);
480                 pu->conflict_count = pu->conflict_count_org;
481
482                 /* shortcut: if all members can be colored we are (very) content */
483                 if (b_size == pu->node_count)
484                         break;
485         }
486
487         /* now apply the found optimum */
488         if (b_changes) {
489                 node_stat_t *ns;
490                 DBG((dbgphi, 1, "\tBest color: %d  Copies: %d/%d\n", b_color, pu->node_count-b_size, pu->node_count));
491                 for (ns = set_first(b_changes); ns; ns = set_next(b_changes))
492                         set_irn_color(ns->irn, ns->color);
493                 free(b_changes);
494         } else {
495                 DBG((dbgphi, 1, "\tBest color: none\n"));
496         }
497 }
498
499 /**
500  * Tries to re-allocate colors of nodes in this phi unit, to achieve a lower
501  * number of copy instructions placed during phi destruction.
502  * General purpose version.
503  */
504 static void pu_coalesce_n_phi(phi_unit_t *pu) {
505         DBG((dbgphi, 1, "\n"));
506         /* TODO */
507 }
508
509 /**
510  * Prepares a phi class for further processing as a phi unit.
511  * @param pc The phi class to prepare.
512  * @return A so called phi unit containing some prepared informations
513  *         needed by the following coalescing phase.
514  */
515 static phi_unit_t *new_pu(pset *pc) {
516         phi_unit_t *pu;
517         ir_node *n, *phi = NULL;
518
519         /* get the phi count of this class */
520         pu = calloc(1, sizeof(*pu));
521         for (n = pset_first(pc); n; n = pset_next(pc))
522                 if (is_Phi(n)) {
523                         phi = n;
524                         pu->phi_count++;
525                 }
526
527         if (pu->phi_count == 1) {
528                 ir_node **tmp;
529                 int i, o;
530                 struct obstack ob;
531
532                 obstack_init(&ob);
533
534                 /* build member set not containing phi interferers */
535                 DBG((dbgphi, 1, "Phi-1 class:\n"));
536                 pu->node_count = 1; /*for the phi*/
537                 for (n = pset_first(pc); n; n = pset_next(pc)) {
538                         if (is_Phi(n))
539                                 continue;
540                         if (!phi_ops_interfere(phi, n)) {
541                                 DBG((dbgphi, 1, "\tAdding to members: %n\n", n));
542                                 obstack_ptr_grow(&ob, n);
543                                 pu->node_count++;
544                         } else {
545                                 DBG((dbgphi, 1, "\tPhi interferer: %n\n", n));
546                                 pset_insert_ptr(free_nodes, n);
547                         }
548                 }
549                 tmp = obstack_finish(&ob);
550                 pu->nodes = malloc(pu->node_count * sizeof(*pu->nodes));
551                 pu->nodes[0] = phi;
552                 memcpy(&pu->nodes[1], tmp, (pu->node_count-1) * sizeof(*tmp));
553
554                 /* init conlict graph to life range interference */
555                 for (i = 0; i < pu->node_count; ++i)
556                         for (o = i+1; o < pu->node_count; ++o)
557                                 if (phi_ops_interfere(pu->nodes[i], pu->nodes[o]))
558                                         pu_add_conflict(pu, pu->nodes[i], pu->nodes[o]);
559                 pu->conflict_count_org = pu->conflict_count;
560
561                 pu->changed_nodes = new_set(set_cmp_node_stat_t, INITIAL_SLOTS_CHANGED_NODES);
562
563                 obstack_free(&ob, NULL);
564         } else {
565                 DBG((dbgphi, 1, "Phi-n class:\n"));
566                 /* TODO */
567         }
568
569         DBG((dbgphi, 1, "\n"));
570         return pu;
571 }
572
573
574 /**
575  * Deletes a phi unit
576  */
577 static void free_pu(phi_unit_t *pu) {
578         if (pu->phi_count == 1) {
579                 free(pu->nodes);
580                 free(pu->changed_nodes);
581                 if (pu->conflicts)
582                         free(pu->conflicts);
583         } else {
584                 /* TODO */
585         }
586         free(pu);
587 }
588
589
590 void be_phi_coalesce(pset *all_phi_classes) {
591         pset *pc;
592
593         pinned_global = pset_new_ptr(INITIAL_SLOTS_PINNED_GLOBAL);
594         free_nodes = pset_new_ptr(INITIAL_SLOTS_FREE_NODES);
595
596         for (pc = pset_first(all_phi_classes); pc; pc = pset_next(all_phi_classes)) {
597                 phi_unit_t *pu = new_pu(pc);
598                 if (pu->phi_count == 1)
599                         pu_coalesce_1_phi(pu);
600                 else
601                         pu_coalesce_n_phi(pu);
602                 free_pu(pu);
603         }
604
605         del_pset(free_nodes);
606         del_pset(pinned_global);
607 }
608
609
610 void be_phi_coal_init(void) {
611         dbgphi = firm_dbg_register("ir.be.phicoal");
612         firm_dbg_set_mask(dbgphi, DEBUG_LVL);
613 }