9ea296b1595c19e12f305655e075b8b62e32a5f4
[libfirm] / ir / opt / combo.c
1 /*
2  * Copyright (C) 1995-2011 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   Cliff Click's Combined Analysis/Optimization
23  * @author  Michael Beck
24  *
25  * This is a slightly enhanced version of Cliff Clicks combo algorithm
26  * - support for commutative nodes is added, Add(a,b) and Add(b,a) ARE congruent
27  * - supports all Firm direct (by a data edge) identities except Mux
28  *   (Mux can be a 2-input or 1-input identity, only 2-input is implemented yet)
29  * - supports Confirm nodes (handle them like Copies but do NOT remove them)
30  * - let Cmp nodes calculate Top like all other data nodes: this would let
31  *   Mux nodes to calculate Unknown instead of taking the true result
32  * - let Cond(Top) always select FALSE/default: This is tricky. Nodes are only reevaluated
33  *   IFF the predecessor changed its type. Because nodes are initialized with Top
34  *   this never happens, let all Proj(Cond) be unreachable.
35  *   We avoid this condition by the same way we work around Phi: whenever a Block
36  *   node is placed on the list, place its Cond nodes (and because they are Tuple
37  *   all its Proj-nodes either on the cprop list)
38  *   Especially, this changes the meaning of Click's example:
39  *
40  *   int main() {
41  *     int x;
42  *
43  *     if (x == 2)
44  *       printf("x == 2\n");
45  *     if (x == 3)
46  *       printf("x == 3\n");
47  *   }
48  *
49  *   Would print:
50  *   x == 2
51  *   x == 3
52  *
53  *   using Click's version while is silent with our.
54  * - support for global congruences is implemented but not tested yet
55  *
56  * Note further that we use the terminology from Click's work here, which is different
57  * in some cases from Firm terminology.  Especially, Click's type is a
58  * Firm tarval/entity, nevertheless we call it type here for "maximum compatibility".
59  */
60 #include "config.h"
61
62 #include <assert.h>
63
64 #include "iroptimize.h"
65 #include "irflag.h"
66 #include "ircons.h"
67 #include "list.h"
68 #include "set.h"
69 #include "pmap.h"
70 #include "obstack.h"
71 #include "irgraph_t.h"
72 #include "irnode_t.h"
73 #include "iropt_t.h"
74 #include "irgwalk.h"
75 #include "irop.h"
76 #include "irouts.h"
77 #include "irgmod.h"
78 #include "iropt_dbg.h"
79 #include "debug.h"
80 #include "array_t.h"
81 #include "error.h"
82 #include "irnodeset.h"
83 #include "irpass.h"
84 #include "tv_t.h"
85 #include "irtools.h"
86
87 #include "irprintf.h"
88 #include "irdump.h"
89
90 /* define this to check that all type translations are monotone */
91 #define VERIFY_MONOTONE
92
93 /* define this to check the consistency of partitions */
94 #define CHECK_PARTITIONS
95
96 typedef struct node_t            node_t;
97 typedef struct partition_t       partition_t;
98 typedef struct opcode_key_t      opcode_key_t;
99 typedef struct listmap_entry_t   listmap_entry_t;
100
101 /** The type of the compute function. */
102 typedef void (*compute_func)(node_t *node);
103
104 /**
105  * An opcode map key.
106  */
107 struct opcode_key_t {
108         ir_node *irn;    /**< An IR node representing this opcode. */
109 };
110
111 /**
112  * An entry in the list_map.
113  */
114 struct listmap_entry_t {
115         void            *id;    /**< The id. */
116         node_t          *list;  /**< The associated list for this id. */
117         listmap_entry_t *next;  /**< Link to the next entry in the map. */
118 };
119
120 /** We must map id's to lists. */
121 typedef struct listmap_t {
122         set             *map;    /**< Map id's to listmap_entry_t's */
123         listmap_entry_t *values; /**< List of all values in the map. */
124 } listmap_t;
125
126 /**
127  * A lattice element. Because we handle constants and symbolic constants different, we
128  * have to use this union.
129  */
130 typedef union {
131         ir_tarval      *tv;
132         symconst_symbol sym;
133 } lattice_elem_t;
134
135 /**
136  * A node.
137  */
138 struct node_t {
139         ir_node         *node;          /**< The IR-node itself. */
140         list_head       node_list;      /**< Double-linked list of leader/follower entries. */
141         list_head       cprop_list;     /**< Double-linked partition.cprop list. */
142         partition_t     *part;          /**< points to the partition this node belongs to */
143         node_t          *next;          /**< Next node on local list (partition.touched, fallen). */
144         node_t          *race_next;     /**< Next node on race list. */
145         lattice_elem_t  type;           /**< The associated lattice element "type". */
146         int             max_user_input; /**< Maximum input number of Def-Use edges. */
147         unsigned        next_edge;      /**< Index of the next Def-Use edge to use. */
148         unsigned        n_followers;    /**< Number of Follower in the outs set. */
149         unsigned        on_touched:1;   /**< Set, if this node is on the partition.touched set. */
150         unsigned        on_cprop:1;     /**< Set, if this node is on the partition.cprop list. */
151         unsigned        on_fallen:1;    /**< Set, if this node is on the fallen list. */
152         unsigned        is_follower:1;  /**< Set, if this node is a follower. */
153         unsigned        flagged:2;      /**< 2 Bits, set if this node was visited by race 1 or 2. */
154 };
155
156 /**
157  * A partition containing congruent nodes.
158  */
159 struct partition_t {
160         list_head         Leader;          /**< The head of partition Leader node list. */
161         list_head         Follower;        /**< The head of partition Follower node list. */
162         list_head         cprop;           /**< The head of partition.cprop list. */
163         list_head         cprop_X;         /**< The head of partition.cprop (Cond nodes and its Projs) list. */
164         partition_t       *wl_next;        /**< Next entry in the work list if any. */
165         partition_t       *touched_next;   /**< Points to the next partition in the touched set. */
166         partition_t       *cprop_next;     /**< Points to the next partition in the cprop list. */
167         partition_t       *split_next;     /**< Points to the next partition in the list that must be split by split_by(). */
168         node_t            *touched;        /**< The partition.touched set of this partition. */
169         unsigned          n_leader;        /**< Number of entries in this partition.Leader. */
170         unsigned          n_touched;       /**< Number of entries in the partition.touched. */
171         int               max_user_inputs; /**< Maximum number of user inputs of all entries. */
172         unsigned          on_worklist:1;   /**< Set, if this partition is in the work list. */
173         unsigned          on_touched:1;    /**< Set, if this partition is on the touched set. */
174         unsigned          on_cprop:1;      /**< Set, if this partition is on the cprop list. */
175         unsigned          type_is_T_or_C:1;/**< Set, if all nodes in this partition have type Top or Constant. */
176 #ifdef DEBUG_libfirm
177         partition_t       *dbg_next;       /**< Link all partitions for debugging */
178         unsigned          nr;              /**< A unique number for (what-)mapping, >0. */
179 #endif
180 };
181
182 typedef struct environment_t {
183         struct obstack  obst;           /**< obstack to allocate data structures. */
184         partition_t     *worklist;      /**< The work list. */
185         partition_t     *cprop;         /**< The constant propagation list. */
186         partition_t     *touched;       /**< the touched set. */
187         partition_t     *initial;       /**< The initial partition. */
188         set             *opcode2id_map; /**< The opcodeMode->id map. */
189         ir_node         **kept_memory;  /**< Array of memory nodes that must be kept. */
190         int             end_idx;        /**< -1 for local and 0 for global congruences. */
191         int             lambda_input;   /**< Captured argument for lambda_partition(). */
192         unsigned        modified:1;     /**< Set, if the graph was modified. */
193         unsigned        unopt_cf:1;     /**< If set, control flow is not optimized due to Unknown. */
194         /* options driving the optimization */
195         unsigned        commutative:1;  /**< Set, if commutation nodes should be handled specially. */
196         unsigned        opt_unknown:1;  /**< Set, if non-strict programs should be optimized. */
197 #ifdef DEBUG_libfirm
198         partition_t     *dbg_list;      /**< List of all partitions. */
199 #endif
200 } environment_t;
201
202 /** Type of the what function. */
203 typedef void *(*what_func)(const node_t *node, environment_t *env);
204
205 #define get_irn_node(irn)         ((node_t *)get_irn_link(irn))
206 #define set_irn_node(irn, node)   set_irn_link(irn, node)
207
208 /* we do NOT use tarval_unreachable here, instead we use Top for this purpose */
209 #undef tarval_unreachable
210 #define tarval_unreachable tarval_top
211
212
213 /** The debug module handle. */
214 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
215
216 /** The what reason. */
217 DEBUG_ONLY(static const char *what_reason;)
218
219 /** Next partition number. */
220 DEBUG_ONLY(static unsigned part_nr = 0;)
221
222 /** The tarval returned by Unknown nodes: set to either tarval_bad OR tarval_top. */
223 static ir_tarval *tarval_UNKNOWN;
224
225 /* forward */
226 static node_t *identity(node_t *node);
227
228 /**
229  * Compare two opcode representatives.
230  */
231 static int cmp_irn_opcode(const ir_node *a, const ir_node *b)
232 {
233         int arity;
234
235         if ((get_irn_op(a) != get_irn_op(b)) ||
236             (get_irn_mode(a) != get_irn_mode(b)))
237                 return 1;
238
239         /* compare if a's in and b's in are of equal length */
240         arity = get_irn_arity(a);
241         if (arity != get_irn_arity(b))
242                 return 1;
243
244         if (is_Block(a)) {
245                 /*
246                  * Some ugliness here: Two Blocks having the same
247                  * IJmp predecessor would be congruent, which of course is wrong.
248                  * We fix it by never letting blocks be congruent
249                  * which cannot be detected by combo either.
250                  */
251                 return 1;
252         }
253
254         /*
255          * here, we already know that the nodes are identical except their
256          * attributes
257          */
258         if (a->op->ops.node_cmp_attr)
259                 return a->op->ops.node_cmp_attr(a, b);
260
261         return 0;
262 }  /* cmp_irn_opcode */
263
264 #ifdef CHECK_PARTITIONS
265 /**
266  * Check a partition.
267  */
268 static void check_partition(const partition_t *T)
269 {
270         unsigned n = 0;
271
272         list_for_each_entry(node_t, node, &T->Leader, node_list) {
273                 assert(node->is_follower == 0);
274                 assert(node->flagged == 0);
275                 assert(node->part == T);
276                 ++n;
277         }
278         assert(n == T->n_leader);
279
280         list_for_each_entry(node_t, node, &T->Follower, node_list) {
281                 assert(node->is_follower == 1);
282                 assert(node->flagged == 0);
283                 assert(node->part == T);
284         }
285 }  /* check_partition */
286
287 /**
288  * check that all leader nodes in the partition have the same opcode.
289  */
290 static void check_opcode(const partition_t *Z)
291 {
292         const ir_node *repr = NULL;
293
294         list_for_each_entry(node_t, node, &Z->Leader, node_list) {
295                 ir_node *irn = node->node;
296
297                 if (repr == NULL) {
298                         repr = irn;
299                 } else {
300                         assert(cmp_irn_opcode(repr, irn) == 0);
301                 }
302         }
303 }  /* check_opcode */
304
305 static void check_all_partitions(environment_t *env)
306 {
307 #ifdef DEBUG_libfirm
308         partition_t *P;
309
310         for (P = env->dbg_list; P != NULL; P = P->dbg_next) {
311                 check_partition(P);
312                 if (! P->type_is_T_or_C)
313                         check_opcode(P);
314                 list_for_each_entry(node_t, node, &P->Follower, node_list) {
315                         node_t *leader = identity(node);
316
317                         assert(leader != node && leader->part == node->part);
318                 }
319         }
320 #else
321         (void) env;
322 #endif
323 }
324
325 /**
326  * Check list.
327  */
328 static void do_check_list(const node_t *list, int ofs, const partition_t *Z)
329 {
330
331 #ifndef NDEBUG
332         const node_t *e;
333 #define NEXT(e)  *((const node_t **)((char *)(e) + (ofs)))
334         for (e = list; e != NULL; e = NEXT(e)) {
335                 assert(e->part == Z);
336         }
337 #undef NEXT
338 #else
339         (void) list;
340         (void) ofs;
341         (void) Z;
342 #endif
343 }  /* ido_check_list */
344
345 /**
346  * Check a local list.
347  */
348 static void check_list(const node_t *list, const partition_t *Z)
349 {
350         do_check_list(list, offsetof(node_t, next), Z);
351 }  /* check_list */
352
353 #else
354 #define check_partition(T)
355 #define check_list(list, Z)
356 #define check_all_partitions(env)
357 #endif /* CHECK_PARTITIONS */
358
359 #ifdef DEBUG_libfirm
360 static inline lattice_elem_t get_partition_type(const partition_t *X);
361
362 /**
363  * Dump partition to output.
364  */
365 static void dump_partition(const char *msg, const partition_t *part)
366 {
367         int            first = 1;
368         lattice_elem_t type = get_partition_type(part);
369
370         DB((dbg, LEVEL_2, "%s part%u%s (%u, %+F) {\n  ",
371                 msg, part->nr, part->type_is_T_or_C ? "*" : "",
372                 part->n_leader, type));
373         list_for_each_entry(node_t, node, &part->Leader, node_list) {
374                 DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
375                 first = 0;
376         }
377         if (! list_empty(&part->Follower)) {
378                 DB((dbg, LEVEL_2, "\n---\n  "));
379                 first = 1;
380                 list_for_each_entry(node_t, node, &part->Follower, node_list) {
381                         DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
382                         first = 0;
383                 }
384         }
385         DB((dbg, LEVEL_2, "\n}\n"));
386 }  /* dump_partition */
387
388 /**
389  * Dumps a list.
390  */
391 static void do_dump_list(const char *msg, const node_t *node, int ofs)
392 {
393         const node_t *p;
394         int          first = 1;
395
396 #define GET_LINK(p, ofs)  *((const node_t **)((char *)(p) + (ofs)))
397
398         DB((dbg, LEVEL_3, "%s = {\n  ", msg));
399         for (p = node; p != NULL; p = GET_LINK(p, ofs)) {
400                 DB((dbg, LEVEL_3, "%s%+F", first ? "" : ", ", p->node));
401                 first = 0;
402         }
403         DB((dbg, LEVEL_3, "\n}\n"));
404
405 #undef GET_LINK
406 }  /* do_dump_list */
407
408 /**
409  * Dumps a race list.
410  */
411 static void dump_race_list(const char *msg, const node_t *list)
412 {
413         do_dump_list(msg, list, offsetof(node_t, race_next));
414 }  /* dump_race_list */
415
416 /**
417  * Dumps a local list.
418  */
419 static void dump_list(const char *msg, const node_t *list)
420 {
421         do_dump_list(msg, list, offsetof(node_t, next));
422 }  /* dump_list */
423
424 /**
425  * Dump all partitions.
426  */
427 static void dump_all_partitions(const environment_t *env)
428 {
429         const partition_t *P;
430
431         DB((dbg, LEVEL_2, "All partitions\n===============\n"));
432         for (P = env->dbg_list; P != NULL; P = P->dbg_next)
433                 dump_partition("", P);
434 }  /* dump_all_partitions */
435
436 /**
437  * Sump a split list.
438  */
439 static void dump_split_list(const partition_t *list)
440 {
441         const partition_t *p;
442         char               split = ' ';
443
444         DB((dbg, LEVEL_2, "Split by %s produced = {\n", what_reason));
445         for (p = list; p != NULL; p = p->split_next) {
446                 DB((dbg, LEVEL_2, "%c part%u", split, p->nr));
447                 split = ',';
448         }
449         DB((dbg, LEVEL_2, "\n}\n"));
450 }  /* dump_split_list */
451
452 /**
453  * Dump partition and type for a node.
454  */
455 static int dump_partition_hook(FILE *F, const ir_node *n, const ir_node *local)
456 {
457         const ir_node *irn = local != NULL ? local : n;
458         node_t *node = get_irn_node(irn);
459
460         ir_fprintf(F, "info2 : \"partition %u type %+F\"\n", node->part->nr, node->type);
461         return 1;
462 }  /* dump_partition_hook */
463
464 #else
465 #define dump_partition(msg, part)
466 #define dump_race_list(msg, list)
467 #define dump_list(msg, list)
468 #define dump_all_partitions(env)
469 #define dump_split_list(list)
470 #endif
471
472 #if defined(VERIFY_MONOTONE) && defined (DEBUG_libfirm)
473 /**
474  * Verify that a type transition is monotone
475  */
476 static void verify_type(const lattice_elem_t old_type, node_t *node)
477 {
478         if (old_type.tv == node->type.tv) {
479                 /* no change */
480                 return;
481         }
482         if (old_type.tv == tarval_top) {
483                 /* from Top down-to is always allowed */
484                 return;
485         }
486         if (node->type.tv == tarval_bottom || node->type.tv == tarval_reachable) {
487                 /* bottom reached */
488                 return;
489         }
490         panic("wrong translation from %+F to %+F on node %+F", old_type, node->type, node->node);
491 }  /* verify_type */
492
493 #else
494 #define verify_type(old_type, node)
495 #endif
496
497 /**
498  * Compare two pointer values of a listmap.
499  */
500 static int listmap_cmp_ptr(const void *elt, const void *key, size_t size)
501 {
502         const listmap_entry_t *e1 = (listmap_entry_t*)elt;
503         const listmap_entry_t *e2 = (listmap_entry_t*)key;
504
505         (void) size;
506         return e1->id != e2->id;
507 }  /* listmap_cmp_ptr */
508
509 /**
510  * Initializes a listmap.
511  *
512  * @param map  the listmap
513  */
514 static void listmap_init(listmap_t *map)
515 {
516         map->map    = new_set(listmap_cmp_ptr, 16);
517         map->values = NULL;
518 }  /* listmap_init */
519
520 /**
521  * Terminates a listmap.
522  *
523  * @param map  the listmap
524  */
525 static void listmap_term(listmap_t *map)
526 {
527         del_set(map->map);
528 }  /* listmap_term */
529
530 /**
531  * Return the associated listmap entry for a given id.
532  *
533  * @param map  the listmap
534  * @param id   the id to search for
535  *
536  * @return the associated listmap entry for the given id
537  */
538 static listmap_entry_t *listmap_find(listmap_t *map, void *id)
539 {
540         listmap_entry_t key, *entry;
541
542         key.id   = id;
543         key.list = NULL;
544         key.next = NULL;
545         entry = set_insert(listmap_entry_t, map->map, &key, sizeof(key), hash_ptr(id));
546
547         if (entry->list == NULL) {
548                 /* a new entry, put into the list */
549                 entry->next = map->values;
550                 map->values = entry;
551         }
552         return entry;
553 }  /* listmap_find */
554
555 /**
556  * Calculate the hash value for an opcode map entry.
557  *
558  * @param entry  an opcode map entry
559  *
560  * @return a hash value for the given opcode map entry
561  */
562 static unsigned opcode_hash(const opcode_key_t *entry)
563 {
564         /* we cannot use the ir ops hash function here, because it hashes the
565          * predecessors. */
566         const ir_node *n = entry->irn;
567         ir_opcode code  = (ir_opcode)get_irn_opcode(n);
568         ir_mode   *mode = get_irn_mode(n);
569         unsigned hash = (unsigned)(PTR_TO_INT(mode) * 9 + code) + get_irn_arity(n);
570
571         if (code == iro_Const)
572                 hash ^= (unsigned)hash_ptr(get_Const_tarval(n));
573         else if (code == iro_Proj)
574                 hash += (unsigned)get_Proj_proj(n);
575         return hash;
576 }  /* opcode_hash */
577
578 /**
579  * Compare two entries in the opcode map.
580  */
581 static int cmp_opcode(const void *elt, const void *key, size_t size)
582 {
583         const opcode_key_t *o1 = (opcode_key_t*)elt;
584         const opcode_key_t *o2 = (opcode_key_t*)key;
585
586         (void) size;
587
588         return cmp_irn_opcode(o1->irn, o2->irn);
589 }  /* cmp_opcode */
590
591 /**
592  * Compare two Def-Use edges for input position.
593  */
594 static int cmp_def_use_edge(const void *a, const void *b)
595 {
596         const ir_def_use_edge *ea = (const ir_def_use_edge*)a;
597         const ir_def_use_edge *eb = (const ir_def_use_edge*)b;
598
599         /* no overrun, because range is [-1, MAXINT] */
600         return ea->pos - eb->pos;
601 }  /* cmp_def_use_edge */
602
603 /**
604  * We need the Def-Use edges sorted.
605  */
606 static void sort_irn_outs(node_t *node)
607 {
608         ir_node *irn = node->node;
609         unsigned n_outs = get_irn_n_outs(irn);
610         qsort(irn->o.out->edges, n_outs, sizeof(irn->o.out->edges[0]),
611                   cmp_def_use_edge);
612         node->max_user_input = n_outs > 0 ? irn->o.out->edges[n_outs-1].pos : -1;
613 }  /* sort_irn_outs */
614
615 /**
616  * Return the type of a node.
617  *
618  * @param irn  an IR-node
619  *
620  * @return the associated type of this node
621  */
622 static inline lattice_elem_t get_node_type(const ir_node *irn)
623 {
624         return get_irn_node(irn)->type;
625 }  /* get_node_type */
626
627 /**
628  * Return the tarval of a node.
629  *
630  * @param irn  an IR-node
631  *
632  * @return the associated type of this node
633  */
634 static inline ir_tarval *get_node_tarval(const ir_node *irn)
635 {
636         lattice_elem_t type = get_node_type(irn);
637
638         if (is_tarval(type.tv))
639                 return type.tv;
640         return tarval_bottom;
641 }  /* get_node_type */
642
643 /**
644  * Add a partition to the worklist.
645  */
646 static inline void add_to_worklist(partition_t *X, environment_t *env)
647 {
648         assert(X->on_worklist == 0);
649         DB((dbg, LEVEL_2, "Adding part%d to worklist\n", X->nr));
650         X->wl_next     = env->worklist;
651         X->on_worklist = 1;
652         env->worklist  = X;
653 }  /* add_to_worklist */
654
655 /**
656  * Create a new empty partition.
657  *
658  * @param env   the environment
659  *
660  * @return a newly allocated partition
661  */
662 static inline partition_t *new_partition(environment_t *env)
663 {
664         partition_t *part = OALLOC(&env->obst, partition_t);
665
666         INIT_LIST_HEAD(&part->Leader);
667         INIT_LIST_HEAD(&part->Follower);
668         INIT_LIST_HEAD(&part->cprop);
669         INIT_LIST_HEAD(&part->cprop_X);
670         part->wl_next         = NULL;
671         part->touched_next    = NULL;
672         part->cprop_next      = NULL;
673         part->split_next      = NULL;
674         part->touched         = NULL;
675         part->n_leader        = 0;
676         part->n_touched       = 0;
677         part->max_user_inputs = 0;
678         part->on_worklist     = 0;
679         part->on_touched      = 0;
680         part->on_cprop        = 0;
681         part->type_is_T_or_C  = 0;
682 #ifdef DEBUG_libfirm
683         part->dbg_next        = env->dbg_list;
684         env->dbg_list         = part;
685         part->nr              = part_nr++;
686 #endif
687
688         return part;
689 }  /* new_partition */
690
691 /**
692  * Get the first node from a partition.
693  */
694 static inline node_t *get_first_node(const partition_t *X)
695 {
696         return list_entry(X->Leader.next, node_t, node_list);
697 }  /* get_first_node */
698
699 /**
700  * Return the type of a partition (assuming partition is non-empty and
701  * all elements have the same type).
702  *
703  * @param X  a partition
704  *
705  * @return the type of the first element of the partition
706  */
707 static inline lattice_elem_t get_partition_type(const partition_t *X)
708 {
709         const node_t *first = get_first_node(X);
710         return first->type;
711 }  /* get_partition_type */
712
713 /**
714  * Creates a partition node for the given IR-node and place it
715  * into the given partition.
716  *
717  * @param irn   an IR-node
718  * @param part  a partition to place the node in
719  * @param env   the environment
720  *
721  * @return the created node
722  */
723 static node_t *create_partition_node(ir_node *irn, partition_t *part, environment_t *env)
724 {
725         /* create a partition node and place it in the partition */
726         node_t *node = OALLOC(&env->obst, node_t);
727
728         INIT_LIST_HEAD(&node->node_list);
729         INIT_LIST_HEAD(&node->cprop_list);
730         node->node           = irn;
731         node->part           = part;
732         node->next           = NULL;
733         node->race_next      = NULL;
734         node->type.tv        = tarval_top;
735         node->max_user_input = 0;
736         node->next_edge      = 0;
737         node->n_followers    = 0;
738         node->on_touched     = 0;
739         node->on_cprop       = 0;
740         node->on_fallen      = 0;
741         node->is_follower    = 0;
742         node->flagged        = 0;
743         set_irn_node(irn, node);
744
745         list_add_tail(&node->node_list, &part->Leader);
746         ++part->n_leader;
747
748         return node;
749 }  /* create_partition_node */
750
751 /**
752  * Pre-Walker, initialize all Nodes' type to U or top and place
753  * all nodes into the TOP partition.
754  */
755 static void create_initial_partitions(ir_node *irn, void *ctx)
756 {
757         environment_t *env  = (environment_t*)ctx;
758         partition_t   *part = env->initial;
759         node_t        *node;
760
761         node = create_partition_node(irn, part, env);
762         sort_irn_outs(node);
763         if (node->max_user_input > part->max_user_inputs)
764                 part->max_user_inputs = node->max_user_input;
765
766         if (is_Block(irn)) {
767                 set_Block_phis(irn, NULL);
768         }
769 }  /* create_initial_partitions */
770
771 /**
772  * Post-Walker, collect  all Block-Phi lists, set Cond.
773  */
774 static void init_block_phis(ir_node *irn, void *ctx)
775 {
776         (void) ctx;
777
778         if (is_Phi(irn)) {
779                 ir_node *block = get_nodes_block(irn);
780                 add_Block_phi(block, irn);
781         }
782 }  /* init_block_phis */
783
784 /**
785  * Add a node to the entry.partition.touched set and
786  * node->partition to the touched set if not already there.
787  *
788  * @param y    a node
789  * @param env  the environment
790  */
791 static inline void add_to_touched(node_t *y, environment_t *env)
792 {
793         if (y->on_touched == 0) {
794                 partition_t *part = y->part;
795
796                 y->next       = part->touched;
797                 part->touched = y;
798                 y->on_touched = 1;
799                 ++part->n_touched;
800
801                 if (part->on_touched == 0) {
802                         part->touched_next = env->touched;
803                         env->touched       = part;
804                         part->on_touched   = 1;
805                 }
806
807                 check_list(part->touched, part);
808         }
809 }  /* add_to_touched */
810
811 /**
812  * Place a node on the cprop list.
813  *
814  * @param y    the node
815  * @param env  the environment
816  */
817 static void add_to_cprop(node_t *y, environment_t *env)
818 {
819         ir_node *irn;
820
821         /* Add y to y.partition.cprop. */
822         if (y->on_cprop == 0) {
823                 partition_t *Y = y->part;
824                 ir_node *irn   = y->node;
825                 ir_node *skipped = skip_Proj(irn);
826
827                 /* place Conds and all its Projs on the cprop_X list */
828                 if (is_Cond(skipped) || is_Switch(skipped))
829                         list_add_tail(&y->cprop_list, &Y->cprop_X);
830                 else
831                         list_add_tail(&y->cprop_list, &Y->cprop);
832                 y->on_cprop   = 1;
833
834                 DB((dbg, LEVEL_3, "Add %+F to part%u.cprop\n", y->node, Y->nr));
835
836                 /* place its partition on the cprop list */
837                 if (Y->on_cprop == 0) {
838                         Y->cprop_next = env->cprop;
839                         env->cprop    = Y;
840                         Y->on_cprop   = 1;
841                 }
842         }
843         irn = y->node;
844         if (get_irn_mode(irn) == mode_T) {
845                 /* mode_T nodes always produce tarval_bottom, so we must explicitly
846                  * add its Projs to get constant evaluation to work */
847                 for (unsigned i = get_irn_n_outs(irn); i-- > 0; ) {
848                         node_t *proj = get_irn_node(get_irn_out(irn, i));
849
850                         add_to_cprop(proj, env);
851                 }
852         } else if (is_Block(irn)) {
853                 /* Due to the way we handle Phi's, we must place all Phis of a block on the list
854                  * if someone placed the block. The Block is only placed if the reachability
855                  * changes, and this must be re-evaluated in compute_Phi(). */
856                 ir_node *phi;
857                 for (phi = get_Block_phis(irn); phi != NULL; phi = get_Phi_next(phi)) {
858                         node_t *p = get_irn_node(phi);
859                         add_to_cprop(p, env);
860                 }
861         }
862 }  /* add_to_cprop */
863
864 /**
865  * Update the worklist: If Z is on worklist then add Z' to worklist.
866  * Else add the smaller of Z and Z' to worklist.
867  *
868  * @param Z        the Z partition
869  * @param Z_prime  the Z' partition, a previous part of Z
870  * @param env      the environment
871  */
872 static void update_worklist(partition_t *Z, partition_t *Z_prime, environment_t *env)
873 {
874         if (Z->on_worklist || Z_prime->n_leader < Z->n_leader) {
875                 add_to_worklist(Z_prime, env);
876         } else {
877                 add_to_worklist(Z, env);
878         }
879 }  /* update_worklist */
880
881 /**
882  * Make all inputs to x no longer be F.def_use edges.
883  *
884  * @param x  the node
885  */
886 static void move_edges_to_leader(node_t *x)
887 {
888         ir_node *irn = x->node;
889         for (int i = get_irn_arity(irn) - 1; i >= 0; --i) {
890                 node_t  *pred = get_irn_node(get_irn_n(irn, i));
891                 ir_node *p    = pred->node;
892                 unsigned n    = get_irn_n_outs(p);
893                 for (unsigned j = 0; j < pred->n_followers; ++j) {
894                         ir_def_use_edge edge = p->o.out->edges[j];
895                         if (edge.pos == i && edge.use == irn) {
896                                 /* found a follower edge to x, move it to the Leader */
897                                 /* remove this edge from the Follower set */
898                                 --pred->n_followers;
899                                 p->o.out->edges[j] = p->o.out->edges[pred->n_followers];
900
901                                 /* sort it into the leader set */
902                                 unsigned k;
903                                 for (k = pred->n_followers+1; k < n; ++k) {
904                                         if (p->o.out->edges[k].pos >= edge.pos)
905                                                 break;
906                                         p->o.out->edges[k-1] = p->o.out->edges[k];
907                                 }
908                                 /* place the new edge here */
909                                 p->o.out->edges[k-1] = edge;
910
911                                 /* edge found and moved */
912                                 break;
913                         }
914                 }
915         }
916 }  /* move_edges_to_leader */
917
918 /**
919  * Split a partition that has NO followers by a local list.
920  *
921  * @param Z    partition to split
922  * @param g    a (non-empty) node list
923  * @param env  the environment
924  *
925  * @return  a new partition containing the nodes of g
926  */
927 static partition_t *split_no_followers(partition_t *Z, node_t *g, environment_t *env)
928 {
929         partition_t *Z_prime;
930         node_t      *node;
931         unsigned    n = 0;
932         int         max_input;
933
934         dump_partition("Splitting ", Z);
935         dump_list("by list ", g);
936
937         assert(g != NULL);
938
939         /* Remove g from Z. */
940         for (node = g; node != NULL; node = node->next) {
941                 assert(node->part == Z);
942                 list_del(&node->node_list);
943                 ++n;
944         }
945         assert(n < Z->n_leader);
946         Z->n_leader -= n;
947
948         /* Move g to a new partition, Z'. */
949         Z_prime = new_partition(env);
950         max_input = 0;
951         for (node = g; node != NULL; node = node->next) {
952                 list_add_tail(&node->node_list, &Z_prime->Leader);
953                 node->part = Z_prime;
954                 if (node->max_user_input > max_input)
955                         max_input = node->max_user_input;
956         }
957         Z_prime->max_user_inputs = max_input;
958         Z_prime->n_leader        = n;
959
960         check_partition(Z);
961         check_partition(Z_prime);
962
963         /* for now, copy the type info tag, it will be adjusted in split_by(). */
964         Z_prime->type_is_T_or_C = Z->type_is_T_or_C;
965
966         dump_partition("Now ", Z);
967         dump_partition("Created new ", Z_prime);
968
969         update_worklist(Z, Z_prime, env);
970
971         return Z_prime;
972 }  /* split_no_followers */
973
974 /**
975  * Make the Follower -> Leader transition for a node.
976  *
977  * @param n  the node
978  */
979 static void follower_to_leader(node_t *n)
980 {
981         assert(n->is_follower == 1);
982
983         DB((dbg, LEVEL_2, "%+F make the follower -> leader transition\n", n->node));
984         n->is_follower = 0;
985         move_edges_to_leader(n);
986         list_del(&n->node_list);
987         list_add_tail(&n->node_list, &n->part->Leader);
988         ++n->part->n_leader;
989 }  /* follower_to_leader */
990
991 /**
992  * The environment for one race step.
993  */
994 typedef struct step_env {
995         node_t   *initial;    /**< The initial node list. */
996         node_t   *unwalked;   /**< The unwalked node list. */
997         node_t   *walked;     /**< The walked node list. */
998         unsigned index;       /**< Next index of Follower use_def edge. */
999         unsigned side;        /**< side number. */
1000 } step_env;
1001
1002 /**
1003  * Return non-zero, if a input is a real follower
1004  *
1005  * @param irn    the node to check
1006  * @param input  number of the input
1007  */
1008 static int is_real_follower(const ir_node *irn, int input)
1009 {
1010         node_t *pred;
1011
1012         switch (get_irn_opcode(irn)) {
1013         case iro_Confirm:
1014                 if (input == 1) {
1015                         /* ignore the Confirm bound input */
1016                         return 0;
1017                 }
1018                 break;
1019         case iro_Mux:
1020                 if (input == 0) {
1021                         /* ignore the Mux sel input */
1022                         return 0;
1023                 }
1024                 break;
1025         case iro_Phi: {
1026                 /* dead inputs are not follower edges */
1027                 ir_node *block = get_nodes_block(irn);
1028                 node_t  *pred  = get_irn_node(get_Block_cfgpred(block, input));
1029
1030                 if (pred->type.tv == tarval_unreachable)
1031                         return 0;
1032                 break;
1033         }
1034         case iro_Sub:
1035         case iro_Shr:
1036         case iro_Shl:
1037         case iro_Shrs:
1038         case iro_Rotl:
1039                 if (input == 1) {
1040                         /* only a Sub x,0 / Shift x,0 might be a follower */
1041                         return 0;
1042                 }
1043                 break;
1044         case iro_Add:
1045         case iro_Or:
1046         case iro_Eor:
1047                 pred = get_irn_node(get_irn_n(irn, input));
1048                 if (is_tarval(pred->type.tv) && tarval_is_null(pred->type.tv))
1049                         return 0;
1050                 break;
1051         case iro_Mul:
1052                 pred = get_irn_node(get_irn_n(irn, input));
1053                 if (is_tarval(pred->type.tv) && tarval_is_one(pred->type.tv))
1054                         return 0;
1055                 break;
1056         case iro_And:
1057                 pred = get_irn_node(get_irn_n(irn, input));
1058                 if (is_tarval(pred->type.tv) && tarval_is_all_one(pred->type.tv))
1059                         return 0;
1060                 break;
1061         default:
1062                 assert(!"opcode not implemented yet");
1063                 break;
1064         }
1065         return 1;
1066 }  /* is_real_follower */
1067
1068 /**
1069  * Do one step in the race.
1070  */
1071 static int step(step_env *env)
1072 {
1073         node_t *n;
1074
1075         if (env->initial != NULL) {
1076                 /* Move node from initial to unwalked */
1077                 n             = env->initial;
1078                 env->initial  = n->race_next;
1079
1080                 n->race_next  = env->unwalked;
1081                 env->unwalked = n;
1082
1083                 return 0;
1084         }
1085
1086         while (env->unwalked != NULL) {
1087                 /* let n be the first node in unwalked */
1088                 n = env->unwalked;
1089                 while (env->index < n->n_followers) {
1090                         const ir_def_use_edge *edge = &n->node->o.out->edges[env->index];
1091
1092                         /* let m be n.F.def_use[index] */
1093                         node_t *m = get_irn_node(edge->use);
1094
1095                         assert(m->is_follower);
1096                         /*
1097                          * Some inputs, like the get_Confirm_bound are NOT
1098                          * real followers, sort them out.
1099                          */
1100                         if (! is_real_follower(m->node, edge->pos)) {
1101                                 ++env->index;
1102                                 continue;
1103                         }
1104                         ++env->index;
1105
1106                         /* only followers from our partition */
1107                         if (m->part != n->part)
1108                                 continue;
1109
1110                         if ((m->flagged & env->side) == 0) {
1111                                 m->flagged |= env->side;
1112
1113                                 if (m->flagged != 3) {
1114                                         /* visited the first time */
1115                                         /* add m to unwalked not as first node (we might still need to
1116                                            check for more follower node */
1117                                         m->race_next = n->race_next;
1118                                         n->race_next = m;
1119                                         return 0;
1120                                 }
1121                                 /* else already visited by the other side and on the other list */
1122                         }
1123                 }
1124                 /* move n to walked */
1125                 env->unwalked = n->race_next;
1126                 n->race_next  = env->walked;
1127                 env->walked   = n;
1128                 env->index    = 0;
1129         }
1130         return 1;
1131 }  /* step */
1132
1133 /**
1134  * Clear the flags from a list and check for
1135  * nodes that where touched from both sides.
1136  *
1137  * @param list  the list
1138  */
1139 static int clear_flags(node_t *list)
1140 {
1141         int    res = 0;
1142         node_t *n;
1143
1144         for (n = list; n != NULL; n = n->race_next) {
1145                 if (n->flagged == 3) {
1146                         /* we reach a follower from both sides, this will split congruent
1147                          * inputs and make it a leader. */
1148                         follower_to_leader(n);
1149                         res = 1;
1150                 }
1151                 n->flagged = 0;
1152         }
1153         return res;
1154 }  /* clear_flags */
1155
1156 /**
1157  * Split a partition by a local list using the race.
1158  *
1159  * @param pX   pointer to the partition to split, might be changed!
1160  * @param gg   a (non-empty) node list
1161  * @param env  the environment
1162  *
1163  * @return  a new partition containing the nodes of gg
1164  */
1165 static partition_t *split(partition_t **pX, node_t *gg, environment_t *env)
1166 {
1167         partition_t *X = *pX;
1168         partition_t *X_prime;
1169         list_head   tmp;
1170         step_env    senv[2];
1171         node_t      *g, *h;
1172         int         max_input, transitions, winner, shf;
1173         unsigned    n;
1174         DEBUG_ONLY(static int run = 0;)
1175
1176         DB((dbg, LEVEL_2, "Run %d ", run++));
1177         if (list_empty(&X->Follower)) {
1178                 /* if the partition has NO follower, we can use the fast
1179                    splitting algorithm. */
1180                 return split_no_followers(X, gg, env);
1181         }
1182         /* else do the race */
1183
1184         dump_partition("Splitting ", X);
1185         dump_list("by list ", gg);
1186
1187         INIT_LIST_HEAD(&tmp);
1188
1189         /* Remove gg from X.Leader and put into g */
1190         g = NULL;
1191         for (node_t *node = gg; node != NULL; node = node->next) {
1192                 assert(node->part == X);
1193                 assert(node->is_follower == 0);
1194
1195                 list_del(&node->node_list);
1196                 list_add_tail(&node->node_list, &tmp);
1197                 node->race_next = g;
1198                 g               = node;
1199         }
1200         /* produce h */
1201         h = NULL;
1202         list_for_each_entry(node_t, node, &X->Leader, node_list) {
1203                 node->race_next = h;
1204                 h               = node;
1205         }
1206         /* restore X.Leader */
1207         list_splice(&tmp, &X->Leader);
1208
1209         senv[0].initial   = g;
1210         senv[0].unwalked  = NULL;
1211         senv[0].walked    = NULL;
1212         senv[0].index     = 0;
1213         senv[0].side      = 1;
1214
1215         senv[1].initial   = h;
1216         senv[1].unwalked  = NULL;
1217         senv[1].walked    = NULL;
1218         senv[1].index     = 0;
1219         senv[1].side      = 2;
1220
1221         /*
1222          * Some informations on the race that are not stated clearly in Click's
1223          * thesis.
1224          * 1) A follower stays on the side that reach him first.
1225          * 2) If the other side reaches a follower, if will be converted to
1226          *    a leader. /This must be done after the race is over, else the
1227          *    edges we are iterating on are renumbered./
1228          * 3) /New leader might end up on both sides./
1229          * 4) /If one side ends up with new Leaders, we must ensure that
1230          *    they can split out by opcode, hence we have to put _every_
1231          *    partition with new Leader nodes on the cprop list, as
1232          *    opcode splitting is done by split_by() at the end of
1233          *    constant propagation./
1234          */
1235         for (;;) {
1236                 if (step(&senv[0])) {
1237                         winner = 0;
1238                         break;
1239                 }
1240                 if (step(&senv[1])) {
1241                         winner = 1;
1242                         break;
1243                 }
1244         }
1245         assert(senv[winner].initial == NULL);
1246         assert(senv[winner].unwalked == NULL);
1247
1248         /* clear flags from walked/unwalked */
1249         shf = winner;
1250         transitions  = clear_flags(senv[0].unwalked) << shf;
1251         transitions |= clear_flags(senv[0].walked)   << shf;
1252         shf ^= 1;
1253         transitions |= clear_flags(senv[1].unwalked) << shf;
1254         transitions |= clear_flags(senv[1].walked)   << shf;
1255
1256         dump_race_list("winner ", senv[winner].walked);
1257
1258         /* Move walked_{winner} to a new partition, X'. */
1259         X_prime   = new_partition(env);
1260         max_input = 0;
1261         n         = 0;
1262         for (node_t *node = senv[winner].walked; node != NULL; node = node->race_next) {
1263                 list_del(&node->node_list);
1264                 node->part = X_prime;
1265                 if (node->is_follower) {
1266                         list_add_tail(&node->node_list, &X_prime->Follower);
1267                 } else {
1268                         list_add_tail(&node->node_list, &X_prime->Leader);
1269                         ++n;
1270                 }
1271                 if (node->max_user_input > max_input)
1272                         max_input = node->max_user_input;
1273         }
1274         X_prime->n_leader        = n;
1275         X_prime->max_user_inputs = max_input;
1276         X->n_leader             -= X_prime->n_leader;
1277
1278         /* for now, copy the type info tag, it will be adjusted in split_by(). */
1279         X_prime->type_is_T_or_C = X->type_is_T_or_C;
1280
1281         /*
1282          * Even if a follower was not checked by both sides, it might have
1283          * loose its congruence, so we need to check this case for all follower.
1284          */
1285         list_for_each_entry_safe(node_t, node, t, &X_prime->Follower, node_list) {
1286                 if (identity(node) == node) {
1287                         follower_to_leader(node);
1288                         transitions |= 1;
1289                 }
1290         }
1291
1292         check_partition(X);
1293         check_partition(X_prime);
1294
1295         dump_partition("Now ", X);
1296         dump_partition("Created new ", X_prime);
1297
1298         /* X' is the smaller part */
1299         add_to_worklist(X_prime, env);
1300
1301         /*
1302          * If there where follower to leader transitions, ensure that the nodes
1303          * can be split out if necessary.
1304          */
1305         if (transitions & 1) {
1306                 /* place winner partition on the cprop list */
1307                 if (X_prime->on_cprop == 0) {
1308                         X_prime->cprop_next = env->cprop;
1309                         env->cprop          = X_prime;
1310                         X_prime->on_cprop   = 1;
1311                 }
1312         }
1313         if (transitions & 2) {
1314                 /* place other partition on the cprop list */
1315                 if (X->on_cprop == 0) {
1316                         X->cprop_next = env->cprop;
1317                         env->cprop    = X;
1318                         X->on_cprop   = 1;
1319                 }
1320         }
1321
1322         /* we have to ensure that the partition containing g is returned */
1323         if (winner != 0) {
1324                 *pX = X_prime;
1325                 return X;
1326         }
1327
1328         return X_prime;
1329 }  /* split */
1330
1331 /**
1332  * Returns non-zero if the i'th input of a Phi node is live.
1333  *
1334  * @param phi  a Phi-node
1335  * @param i    an input number
1336  *
1337  * @return non-zero if the i'th input of the given Phi node is live
1338  */
1339 static int is_live_input(ir_node *phi, int i)
1340 {
1341         if (i >= 0) {
1342                 ir_node        *block = get_nodes_block(phi);
1343                 ir_node        *pred  = get_Block_cfgpred(block, i);
1344                 lattice_elem_t type   = get_node_type(pred);
1345
1346                 return type.tv != tarval_unreachable;
1347         }
1348         /* else it's the control input, always live */
1349         return 1;
1350 }  /* is_live_input */
1351
1352 /**
1353  * Return non-zero if a type is a constant.
1354  */
1355 static int is_constant_type(lattice_elem_t type)
1356 {
1357         if (type.tv != tarval_bottom && type.tv != tarval_top)
1358                 return 1;
1359         return 0;
1360 }  /* is_constant_type */
1361
1362 /**
1363  * Check whether a type is neither Top or a constant.
1364  * Note: U is handled like Top here, R is a constant.
1365  *
1366  * @param type  the type to check
1367  */
1368 static int type_is_neither_top_nor_const(const lattice_elem_t type)
1369 {
1370         if (is_tarval(type.tv)) {
1371                 if (type.tv == tarval_top)
1372                         return 0;
1373                 if (tarval_is_constant(type.tv))
1374                         return 0;
1375         } else {
1376                 /* is a symconst */
1377                 return 0;
1378         }
1379         return 1;
1380 }  /* type_is_neither_top_nor_const */
1381
1382 /**
1383  * Collect nodes to the touched list.
1384  *
1385  * @param list  the list which contains the nodes that must be evaluated
1386  * @param idx   the index of the def_use edge to evaluate
1387  * @param env   the environment
1388  */
1389 static void collect_touched(list_head *list, int idx, environment_t *env)
1390 {
1391         node_t *y;
1392         int     end_idx = env->end_idx;
1393
1394         list_for_each_entry(node_t, x, list, node_list) {
1395                 if (idx == -1) {
1396                         /* leader edges start AFTER follower edges */
1397                         x->next_edge = x->n_followers;
1398                 }
1399                 unsigned num_edges = get_irn_n_outs(x->node);
1400
1401                 /* for all edges in x.L.def_use_{idx} */
1402                 while (x->next_edge < num_edges) {
1403                         const ir_def_use_edge *edge = &x->node->o.out->edges[x->next_edge];
1404                         ir_node               *succ;
1405
1406                         /* check if we have necessary edges */
1407                         if (edge->pos > idx)
1408                                 break;
1409
1410                         ++x->next_edge;
1411
1412                         succ = edge->use;
1413
1414                         /* only non-commutative nodes */
1415                         if (env->commutative &&
1416                             (idx == 0 || idx == 1) && is_op_commutative(get_irn_op(succ)))
1417                                 continue;
1418
1419                         /* ignore the "control input" for non-pinned nodes
1420                         if we are running in GCSE mode */
1421                         if (idx < end_idx && get_irn_pinned(succ) != op_pin_state_pinned)
1422                                 continue;
1423
1424                         y = get_irn_node(succ);
1425                         assert(get_irn_n(succ, idx) == x->node);
1426
1427                         /* ignore block edges touching followers */
1428                         if (idx == -1 && y->is_follower)
1429                                 continue;
1430
1431                         if (is_constant_type(y->type)) {
1432                                 unsigned  code = get_irn_opcode(succ);
1433                                 if (code == iro_Sub || code == iro_Cmp)
1434                                         add_to_cprop(y, env);
1435                         }
1436
1437                         /* Partitions of constants should not be split simply because their Nodes have unequal
1438                            functions or incongruent inputs. */
1439                         if (type_is_neither_top_nor_const(y->type) &&
1440                                 (! is_Phi(y->node) || is_live_input(y->node, idx))) {
1441                                         add_to_touched(y, env);
1442                         }
1443                 }
1444         }
1445 }  /* collect_touched */
1446
1447 /**
1448  * Collect commutative nodes to the touched list.
1449  *
1450  * @param list  the list which contains the nodes that must be evaluated
1451  * @param env   the environment
1452  */
1453 static void collect_commutative_touched(list_head *list, environment_t *env)
1454 {
1455         node_t *y;
1456
1457         list_for_each_entry(node_t, x, list, node_list) {
1458                 unsigned num_edges = get_irn_n_outs(x->node);
1459
1460                 x->next_edge = x->n_followers;
1461
1462                 /* for all edges in x.L.def_use_{idx} */
1463                 while (x->next_edge < num_edges) {
1464                         const ir_def_use_edge *edge = &x->node->o.out->edges[x->next_edge];
1465                         ir_node               *succ;
1466
1467                         /* check if we have necessary edges */
1468                         if (edge->pos > 1)
1469                                 break;
1470
1471                         ++x->next_edge;
1472                         if (edge->pos < 0)
1473                                 continue;
1474
1475                         succ = edge->use;
1476
1477                         /* only commutative nodes */
1478                         if (!is_op_commutative(get_irn_op(succ)))
1479                                 continue;
1480
1481                         y = get_irn_node(succ);
1482                         if (is_constant_type(y->type)) {
1483                                 unsigned code = get_irn_opcode(succ);
1484                                 if (code == iro_Eor)
1485                                         add_to_cprop(y, env);
1486                         }
1487
1488                         /* Partitions of constants should not be split simply because their Nodes have unequal
1489                            functions or incongruent inputs. */
1490                         if (type_is_neither_top_nor_const(y->type)) {
1491                                 add_to_touched(y, env);
1492                         }
1493                 }
1494         }
1495 }  /* collect_commutative_touched */
1496
1497 /**
1498  * Split the partitions if caused by the first entry on the worklist.
1499  *
1500  * @param env  the environment
1501  */
1502 static void cause_splits(environment_t *env)
1503 {
1504         partition_t *X, *Z, *N;
1505         int         idx;
1506
1507         /* remove the first partition from the worklist */
1508         X = env->worklist;
1509         env->worklist  = X->wl_next;
1510         X->on_worklist = 0;
1511
1512         dump_partition("Cause_split: ", X);
1513
1514         if (env->commutative) {
1515                 /* handle commutative nodes first */
1516
1517                 /* empty the touched set: already done, just clear the list */
1518                 env->touched = NULL;
1519
1520                 collect_commutative_touched(&X->Leader, env);
1521                 collect_commutative_touched(&X->Follower, env);
1522
1523                 for (Z = env->touched; Z != NULL; Z = N) {
1524                         node_t   *e, *n;
1525                         node_t   *touched     = Z->touched;
1526                         node_t   *touched_aa  = NULL;
1527                         node_t   *touched_ab  = NULL;
1528                         unsigned n_touched_aa = 0;
1529                         unsigned n_touched_ab = 0;
1530
1531                         assert(Z->touched != NULL);
1532
1533                         /* beware, split might change Z */
1534                         N = Z->touched_next;
1535
1536                         /* remove it from the touched set */
1537                         Z->on_touched = 0;
1538
1539                         /* Empty local Z.touched. */
1540                         for (e = touched; e != NULL; e = n) {
1541                                 node_t *left  = get_irn_node(get_irn_n(e->node, 0));
1542                                 node_t *right = get_irn_node(get_irn_n(e->node, 1));
1543
1544                                 assert(e->is_follower == 0);
1545                                 e->on_touched = 0;
1546                                 n = e->next;
1547
1548                                 /*
1549                                  * Note: op(a, a) is NOT congruent to op(a, b).
1550                                  * So, we must split the touched list.
1551                                  */
1552                                 if (left->part == right->part) {
1553                                         e->next = touched_aa;
1554                                         touched_aa = e;
1555                                         ++n_touched_aa;
1556                                 } else {
1557                                         e->next = touched_ab;
1558                                         touched_ab = e;
1559                                         ++n_touched_ab;
1560                                 }
1561                         }
1562                         assert(n_touched_aa + n_touched_ab == Z->n_touched);
1563                         Z->touched   = NULL;
1564                         Z->n_touched = 0;
1565
1566                         if (0 < n_touched_aa && n_touched_aa < Z->n_leader) {
1567                                 partition_t *Z_prime = Z;
1568                                 DB((dbg, LEVEL_2, "Split part%d by touched_aa\n", Z_prime->nr));
1569                                 split(&Z_prime, touched_aa, env);
1570                         } else
1571                                 assert(n_touched_aa <= Z->n_leader);
1572
1573                         if (0 < n_touched_ab && n_touched_ab < Z->n_leader) {
1574                                 partition_t *Z_prime = Z;
1575                                 DB((dbg, LEVEL_2, "Split part%d by touched_ab\n", Z_prime->nr));
1576                                 split(&Z_prime, touched_ab, env);
1577                         } else
1578                                 assert(n_touched_ab <= Z->n_leader);
1579                 }
1580         }
1581
1582         /* combine temporary leader and follower list */
1583         for (idx = -1; idx <= X->max_user_inputs; ++idx) {
1584                 /* empty the touched set: already done, just clear the list */
1585                 env->touched = NULL;
1586
1587                 collect_touched(&X->Leader, idx, env);
1588                 collect_touched(&X->Follower, idx, env);
1589
1590                 for (Z = env->touched; Z != NULL; Z = N) {
1591                         node_t   *e;
1592                         node_t   *touched  = Z->touched;
1593                         unsigned n_touched = Z->n_touched;
1594
1595                         assert(Z->touched != NULL);
1596
1597                         /* beware, split might change Z */
1598                         N = Z->touched_next;
1599
1600                         /* remove it from the touched set */
1601                         Z->on_touched = 0;
1602
1603                         /* Empty local Z.touched. */
1604                         for (e = touched; e != NULL; e = e->next) {
1605                                 assert(e->is_follower == 0);
1606                                 e->on_touched = 0;
1607                         }
1608                         Z->touched   = NULL;
1609                         Z->n_touched = 0;
1610
1611                         if (0 < n_touched && n_touched < Z->n_leader) {
1612                                 DB((dbg, LEVEL_2, "Split part%d by touched\n", Z->nr));
1613                                 split(&Z, touched, env);
1614                         } else
1615                                 assert(n_touched <= Z->n_leader);
1616                 }
1617         }
1618 }  /* cause_splits */
1619
1620 /**
1621  * Implements split_by_what(): Split a partition by characteristics given
1622  * by the what function.
1623  *
1624  * @param X     the partition to split
1625  * @param What  a function returning an Id for every node of the partition X
1626  * @param P     a list to store the result partitions
1627  * @param env   the environment
1628  *
1629  * @return *P
1630  */
1631 static partition_t *split_by_what(partition_t *X, what_func What,
1632                                   partition_t **P, environment_t *env)
1633 {
1634         node_t          *S;
1635         listmap_t       map;
1636         listmap_entry_t *iter;
1637         partition_t     *R;
1638
1639         /* Let map be an empty mapping from the range of What to (local) list of Nodes. */
1640         listmap_init(&map);
1641         list_for_each_entry(node_t, x, &X->Leader, node_list) {
1642                 void            *id = What(x, env);
1643                 listmap_entry_t *entry;
1644
1645                 if (id == NULL) {
1646                         /* input not allowed, ignore */
1647                         continue;
1648                 }
1649                 /* Add x to map[What(x)]. */
1650                 entry = listmap_find(&map, id);
1651                 x->next     = entry->list;
1652                 entry->list = x;
1653         }
1654         /* Let P be a set of Partitions. */
1655
1656         /* for all sets S except one in the range of map do */
1657         for (iter = map.values; iter != NULL; iter = iter->next) {
1658                 if (iter->next == NULL) {
1659                         /* this is the last entry, ignore */
1660                         break;
1661                 }
1662                 S = iter->list;
1663
1664                 /* Add SPLIT( X, S ) to P. */
1665                 DB((dbg, LEVEL_2, "Split part%d by WHAT = %s\n", X->nr, what_reason));
1666                 R = split(&X, S, env);
1667                 R->split_next = *P;
1668                 *P            = R;
1669         }
1670         /* Add X to P. */
1671         X->split_next = *P;
1672         *P            = X;
1673
1674         listmap_term(&map);
1675         return *P;
1676 }  /* split_by_what */
1677
1678 /** lambda n.(n.type) */
1679 static void *lambda_type(const node_t *node, environment_t *env)
1680 {
1681         (void)env;
1682         return node->type.tv;
1683 }  /* lambda_type */
1684
1685 /** lambda n.(n.opcode) */
1686 static void *lambda_opcode(const node_t *node, environment_t *env)
1687 {
1688         opcode_key_t key, *entry;
1689
1690         key.irn = node->node;
1691
1692         entry = set_insert(opcode_key_t, env->opcode2id_map, &key, sizeof(key), opcode_hash(&key));
1693         return entry;
1694 }  /* lambda_opcode */
1695
1696 /** lambda n.(n[i].partition) */
1697 static void *lambda_partition(const node_t *node, environment_t *env)
1698 {
1699         ir_node *skipped = skip_Proj(node->node);
1700         ir_node *pred;
1701         node_t  *p;
1702         int     i = env->lambda_input;
1703
1704         if (i >= get_irn_arity(node->node)) {
1705                 /*
1706                  * We are outside the allowed range: This can happen even
1707                  * if we have split by opcode first: doing so might move Followers
1708                  * to Leaders and those will have a different opcode!
1709                  * Note that in this case the partition is on the cprop list and will be
1710                  * split again.
1711                  */
1712                 return NULL;
1713         }
1714
1715         /* ignore the "control input" for non-pinned nodes
1716            if we are running in GCSE mode */
1717         if (i < env->end_idx && get_irn_pinned(skipped) != op_pin_state_pinned)
1718                 return NULL;
1719
1720         pred = i == -1 ? get_irn_n(skipped, i) : get_irn_n(node->node, i);
1721         p    = get_irn_node(pred);
1722         return p->part;
1723 }  /* lambda_partition */
1724
1725 /** lambda n.(n[i].partition) for commutative nodes */
1726 static void *lambda_commutative_partition(const node_t *node, environment_t *env)
1727 {
1728         ir_node     *irn     = node->node;
1729         ir_node     *skipped = skip_Proj(irn);
1730         ir_node     *pred, *left, *right;
1731         node_t      *p;
1732         partition_t *pl, *pr;
1733         int         i = env->lambda_input;
1734
1735         if (i >= get_irn_arity(node->node)) {
1736                 /*
1737                  * We are outside the allowed range: This can happen even
1738                  * if we have split by opcode first: doing so might move Followers
1739                  * to Leaders and those will have a different opcode!
1740                  * Note that in this case the partition is on the cprop list and will be
1741                  * split again.
1742                  */
1743                 return NULL;
1744         }
1745
1746         /* ignore the "control input" for non-pinned nodes
1747            if we are running in GCSE mode */
1748         if (i < env->end_idx && get_irn_pinned(skipped) != op_pin_state_pinned)
1749                 return NULL;
1750
1751         if (i == -1) {
1752                 pred = get_irn_n(skipped, i);
1753                 p    = get_irn_node(pred);
1754                 return p->part;
1755         }
1756
1757         if (is_op_commutative(get_irn_op(irn))) {
1758                 /* normalize partition order by returning the "smaller" on input 0,
1759                    the "bigger" on input 1. */
1760                 left  = get_binop_left(irn);
1761                 pl    = get_irn_node(left)->part;
1762                 right = get_binop_right(irn);
1763                 pr    = get_irn_node(right)->part;
1764
1765                 if (i == 0)
1766                         return pl < pr ? pl : pr;
1767                 else
1768                 return pl > pr ? pl : pr;
1769         } else {
1770                 /* a not split out Follower */
1771                 pred = get_irn_n(irn, i);
1772                 p    = get_irn_node(pred);
1773
1774                 return p->part;
1775         }
1776 }  /* lambda_commutative_partition */
1777
1778 /**
1779  * Returns true if a type is a constant (and NOT Top
1780  * or Bottom).
1781  */
1782 static int is_con(const lattice_elem_t type)
1783 {
1784         /* be conservative */
1785         if (is_tarval(type.tv))
1786                 return tarval_is_constant(type.tv);
1787         return is_entity(type.sym.entity_p);
1788 }  /* is_con */
1789
1790 /**
1791  * Implements split_by().
1792  *
1793  * @param X    the partition to split
1794  * @param env  the environment
1795  */
1796 static void split_by(partition_t *X, environment_t *env)
1797 {
1798         partition_t *I, *P = NULL;
1799         int         input;
1800
1801         dump_partition("split_by", X);
1802
1803         if (X->n_leader == 1) {
1804                 /* we have only one leader, no need to split, just check its type */
1805                 node_t *x = get_first_node(X);
1806                 X->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1807                 return;
1808         }
1809
1810         DEBUG_ONLY(what_reason = "lambda n.(n.type)";)
1811         P = split_by_what(X, lambda_type, &P, env);
1812         dump_split_list(P);
1813
1814         /* adjust the type tags, we have split partitions by type */
1815         for (I = P; I != NULL; I = I->split_next) {
1816                 node_t *x = get_first_node(I);
1817                 I->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1818         }
1819
1820         do {
1821                 partition_t *Y = P;
1822
1823                 P = P->split_next;
1824                 if (Y->n_leader > 1) {
1825                         /* we do not want split the TOP or constant partitions */
1826                         if (! Y->type_is_T_or_C) {
1827                                 partition_t *Q = NULL;
1828
1829                                 DEBUG_ONLY(what_reason = "lambda n.(n.opcode)";)
1830                                 Q = split_by_what(Y, lambda_opcode, &Q, env);
1831                                 dump_split_list(Q);
1832
1833                                 do {
1834                                         partition_t *Z = Q;
1835
1836                                         Q = Q->split_next;
1837                                         if (Z->n_leader > 1) {
1838                                                 const node_t *first = get_first_node(Z);
1839                                                 int          arity  = get_irn_arity(first->node);
1840                                                 partition_t  *R, *S;
1841                                                 what_func    what = lambda_partition;
1842                                                 DEBUG_ONLY(char buf[64];)
1843
1844                                                 if (env->commutative && is_op_commutative(get_irn_op(first->node)))
1845                                                         what = lambda_commutative_partition;
1846
1847                                                 /*
1848                                                  * BEWARE: during splitting by input 2 for instance we might
1849                                                  * create new partitions which are different by input 1, so collect
1850                                                  * them and split further.
1851                                                  */
1852                                                 Z->split_next = NULL;
1853                                                 R             = Z;
1854                                                 S             = NULL;
1855                                                 for (input = arity - 1; input >= -1; --input) {
1856                                                         do {
1857                                                                 partition_t *Z_prime = R;
1858
1859                                                                 R = R->split_next;
1860                                                                 if (Z_prime->n_leader > 1) {
1861                                                                         env->lambda_input = input;
1862                                                                         DEBUG_ONLY(snprintf(buf, sizeof(buf), "lambda n.(n[%d].partition)", input);)
1863                                                                         DEBUG_ONLY(what_reason = buf;)
1864                                                                         S = split_by_what(Z_prime, what, &S, env);
1865                                                                         dump_split_list(S);
1866                                                                 } else {
1867                                                                         Z_prime->split_next = S;
1868                                                                         S                   = Z_prime;
1869                                                                 }
1870                                                         } while (R != NULL);
1871                                                         R = S;
1872                                                         S = NULL;
1873                                                 }
1874                                         }
1875                                 } while (Q != NULL);
1876                         }
1877                 }
1878         } while (P != NULL);
1879 }  /* split_by */
1880
1881 /**
1882  * (Re-)compute the type for a given node.
1883  *
1884  * @param node  the node
1885  */
1886 static void default_compute(node_t *node)
1887 {
1888         int     i;
1889         ir_node *irn = node->node;
1890
1891         /* if any of the data inputs have type top, the result is type top */
1892         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1893                 ir_node *pred = get_irn_n(irn, i);
1894                 node_t  *p    = get_irn_node(pred);
1895
1896                 if (p->type.tv == tarval_top) {
1897                         node->type.tv = tarval_top;
1898                         return;
1899                 }
1900         }
1901
1902         if (get_irn_mode(node->node) == mode_X)
1903                 node->type.tv = tarval_reachable;
1904         else
1905                 node->type.tv = computed_value(irn);
1906 }  /* default_compute */
1907
1908 /**
1909  * (Re-)compute the type for a Block node.
1910  *
1911  * @param node  the node
1912  */
1913 static void compute_Block(node_t *node)
1914 {
1915         int     i;
1916         ir_node *block = node->node;
1917
1918         if (block == get_irg_start_block(current_ir_graph) || get_Block_entity(block) != NULL) {
1919                 /* start block and labelled blocks are always reachable */
1920                 node->type.tv = tarval_reachable;
1921                 return;
1922         }
1923
1924         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
1925                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
1926
1927                 if (pred->type.tv == tarval_reachable) {
1928                         /* A block is reachable, if at least of predecessor is reachable. */
1929                         node->type.tv = tarval_reachable;
1930                         return;
1931                 }
1932         }
1933         node->type.tv = tarval_top;
1934 }  /* compute_Block */
1935
1936 /**
1937  * (Re-)compute the type for a Bad node.
1938  *
1939  * @param node  the node
1940  */
1941 static void compute_Bad(node_t *node)
1942 {
1943         /* Bad nodes ALWAYS compute Top */
1944         node->type.tv = tarval_top;
1945 }  /* compute_Bad */
1946
1947 /**
1948  * (Re-)compute the type for an Unknown node.
1949  *
1950  * @param node  the node
1951  */
1952 static void compute_Unknown(node_t *node)
1953 {
1954         /* While Unknown nodes should compute Top this is dangerous:
1955          * a Top input to a Cond would lead to BOTH control flows unreachable.
1956          * While this is correct in the given semantics, it would destroy the Firm
1957          * graph.
1958          *
1959          * It would be safe to compute Top IF it can be assured, that only Cmp
1960          * nodes are inputs to Conds. We check that first.
1961          * This is the way Frontends typically build Firm, but some optimizations
1962          * (jump threading for instance) might replace them by Phib's...
1963          */
1964         node->type.tv = tarval_UNKNOWN;
1965 }  /* compute_Unknown */
1966
1967 /**
1968  * (Re-)compute the type for a Jmp node.
1969  *
1970  * @param node  the node
1971  */
1972 static void compute_Jmp(node_t *node)
1973 {
1974         node_t *block = get_irn_node(get_nodes_block(node->node));
1975
1976         node->type = block->type;
1977 }  /* compute_Jmp */
1978
1979 /**
1980  * (Re-)compute the type for the Return node.
1981  *
1982  * @param node  the node
1983  */
1984 static void compute_Return(node_t *node)
1985 {
1986         /* The Return node is NOT dead if it is in a reachable block.
1987          * This is already checked in compute(). so we can return
1988          * Reachable here. */
1989         node->type.tv = tarval_reachable;
1990 }  /* compute_Return */
1991
1992 /**
1993  * (Re-)compute the type for the End node.
1994  *
1995  * @param node  the node
1996  */
1997 static void compute_End(node_t *node)
1998 {
1999         /* the End node is NOT dead of course */
2000         node->type.tv = tarval_reachable;
2001 }  /* compute_End */
2002
2003 /**
2004  * (Re-)compute the type for a Call.
2005  *
2006  * @param node  the node
2007  */
2008 static void compute_Call(node_t *node)
2009 {
2010         /*
2011          * A Call computes always bottom, even if it has Unknown
2012          * predecessors.
2013          */
2014         node->type.tv = tarval_bottom;
2015 }  /* compute_Call */
2016
2017 /**
2018  * (Re-)compute the type for a SymConst node.
2019  *
2020  * @param node  the node
2021  */
2022 static void compute_SymConst(node_t *node)
2023 {
2024         ir_node *irn = node->node;
2025         node_t  *block = get_irn_node(get_nodes_block(irn));
2026
2027         if (block->type.tv == tarval_unreachable) {
2028                 node->type.tv = tarval_top;
2029                 return;
2030         }
2031         switch (get_SymConst_kind(irn)) {
2032         case symconst_addr_ent:
2033                 node->type.sym = get_SymConst_symbol(irn);
2034                 break;
2035         default:
2036                 node->type.tv = computed_value(irn);
2037         }
2038 }  /* compute_SymConst */
2039
2040 /**
2041  * (Re-)compute the type for a Phi node.
2042  *
2043  * @param node  the node
2044  */
2045 static void compute_Phi(node_t *node)
2046 {
2047         int            i;
2048         ir_node        *phi = node->node;
2049         lattice_elem_t type;
2050
2051         /* if a Phi is in a unreachable block, its type is TOP */
2052         node_t *block = get_irn_node(get_nodes_block(phi));
2053
2054         if (block->type.tv == tarval_unreachable) {
2055                 node->type.tv = tarval_top;
2056                 return;
2057         }
2058
2059         /* Phi implements the Meet operation */
2060         type.tv = tarval_top;
2061         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
2062                 node_t *pred   = get_irn_node(get_Phi_pred(phi, i));
2063                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block->node, i));
2064
2065                 if (pred_X->type.tv == tarval_unreachable || pred->type.tv == tarval_top) {
2066                         /* ignore TOP inputs: We must check here for unreachable blocks,
2067                            because Firm constants live in the Start Block are NEVER Top.
2068                            Else, a Phi (1,2) will produce Bottom, even if the 2 for instance
2069                            comes from a unreachable input. */
2070                         continue;
2071                 }
2072                 if (pred->type.tv == tarval_bottom) {
2073                         node->type.tv = tarval_bottom;
2074                         return;
2075                 } else if (type.tv == tarval_top) {
2076                         /* first constant found */
2077                         type = pred->type;
2078                 } else if (type.tv != pred->type.tv) {
2079                         /* different constants or tarval_bottom */
2080                         node->type.tv = tarval_bottom;
2081                         return;
2082                 }
2083                 /* else nothing, constants are the same */
2084         }
2085         node->type = type;
2086 }  /* compute_Phi */
2087
2088 /**
2089  * (Re-)compute the type for an Add. Special case: one nodes is a Zero Const.
2090  *
2091  * @param node  the node
2092  */
2093 static void compute_Add(node_t *node)
2094 {
2095         ir_node        *sub = node->node;
2096         node_t         *l   = get_irn_node(get_Add_left(sub));
2097         node_t         *r   = get_irn_node(get_Add_right(sub));
2098         lattice_elem_t a    = l->type;
2099         lattice_elem_t b    = r->type;
2100         ir_mode        *mode;
2101
2102         if (a.tv == tarval_top || b.tv == tarval_top) {
2103                 node->type.tv = tarval_top;
2104         } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
2105                 node->type.tv = tarval_bottom;
2106         } else {
2107                 /* x + 0 = 0 + x = x, but beware of floating point +0 + -0, so we
2108                    must call tarval_add() first to handle this case! */
2109                 if (is_tarval(a.tv)) {
2110                         if (is_tarval(b.tv)) {
2111                                 node->type.tv = tarval_add(a.tv, b.tv);
2112                                 return;
2113                         }
2114                         mode = get_tarval_mode(a.tv);
2115                         if (a.tv == get_mode_null(mode)) {
2116                                 node->type = b;
2117                                 return;
2118                         }
2119                 } else if (is_tarval(b.tv)) {
2120                         mode = get_tarval_mode(b.tv);
2121                         if (b.tv == get_mode_null(mode)) {
2122                                 node->type = a;
2123                                 return;
2124                         }
2125                 }
2126                 node->type.tv = tarval_bottom;
2127         }
2128 }  /* compute_Add */
2129
2130 /**
2131  * (Re-)compute the type for a Sub. Special case: both nodes are congruent.
2132  *
2133  * @param node  the node
2134  */
2135 static void compute_Sub(node_t *node)
2136 {
2137         ir_node        *sub = node->node;
2138         node_t         *l   = get_irn_node(get_Sub_left(sub));
2139         node_t         *r   = get_irn_node(get_Sub_right(sub));
2140         lattice_elem_t a    = l->type;
2141         lattice_elem_t b    = r->type;
2142         ir_tarval      *tv;
2143
2144         if (a.tv == tarval_top || b.tv == tarval_top) {
2145                 node->type.tv = tarval_top;
2146         } else if (is_con(a) && is_con(b)) {
2147                 if (is_tarval(a.tv) && is_tarval(b.tv)) {
2148                         node->type.tv = tarval_sub(a.tv, b.tv, get_irn_mode(sub));
2149                 } else if (is_tarval(a.tv) && tarval_is_null(a.tv)) {
2150                         node->type = b;
2151                 } else if (is_tarval(b.tv) && tarval_is_null(b.tv)) {
2152                         node->type = a;
2153                 } else {
2154                         node->type.tv = tarval_bottom;
2155                 }
2156         } else if (r->part == l->part &&
2157                    (!mode_is_float(get_irn_mode(l->node)))) {
2158                 /*
2159                  * BEWARE: a - a is NOT always 0 for floating Point values, as
2160                  * NaN op NaN = NaN, so we must check this here.
2161                  */
2162                 ir_mode *mode = get_irn_mode(sub);
2163                 tv = get_mode_null(mode);
2164
2165                 /* if the node was ONCE evaluated by all constants, but now
2166                    this breaks AND we get from the argument partitions a different
2167                    result, switch to bottom.
2168                    This happens because initially all nodes are in the same partition ... */
2169                 if (node->type.tv != tv)
2170                         tv = tarval_bottom;
2171                 node->type.tv = tv;
2172         } else {
2173                 node->type.tv = tarval_bottom;
2174         }
2175 }  /* compute_Sub */
2176
2177 /**
2178  * (Re-)compute the type for an Eor. Special case: both nodes are congruent.
2179  *
2180  * @param node  the node
2181  */
2182 static void compute_Eor(node_t *node)
2183 {
2184         ir_node        *eor = node->node;
2185         node_t         *l   = get_irn_node(get_Eor_left(eor));
2186         node_t         *r   = get_irn_node(get_Eor_right(eor));
2187         lattice_elem_t a    = l->type;
2188         lattice_elem_t b    = r->type;
2189         ir_tarval      *tv;
2190
2191         if (a.tv == tarval_top || b.tv == tarval_top) {
2192                 node->type.tv = tarval_top;
2193         } else if (is_con(a) && is_con(b)) {
2194                 if (is_tarval(a.tv) && is_tarval(b.tv)) {
2195                         node->type.tv = tarval_eor(a.tv, b.tv);
2196                 } else if (is_tarval(a.tv) && tarval_is_null(a.tv)) {
2197                         node->type = b;
2198                 } else if (is_tarval(b.tv) && tarval_is_null(b.tv)) {
2199                         node->type = a;
2200                 } else {
2201                         node->type.tv = tarval_bottom;
2202                 }
2203         } else if (r->part == l->part) {
2204                 ir_mode *mode = get_irn_mode(eor);
2205                 tv = get_mode_null(mode);
2206
2207                 /* if the node was ONCE evaluated by all constants, but now
2208                    this breaks AND we get from the argument partitions a different
2209                    result, switch to bottom.
2210                    This happens because initially all nodes are in the same partition ... */
2211                 if (node->type.tv != tv)
2212                         tv = tarval_bottom;
2213                 node->type.tv = tv;
2214         } else {
2215                 node->type.tv = tarval_bottom;
2216         }
2217 }  /* compute_Eor */
2218
2219 /**
2220  * (Re-)compute the type for Cmp.
2221  *
2222  * @param node  the node
2223  */
2224 static void compute_Cmp(node_t *node)
2225 {
2226         ir_node        *cmp     = node->node;
2227         node_t         *l       = get_irn_node(get_Cmp_left(cmp));
2228         node_t         *r       = get_irn_node(get_Cmp_right(cmp));
2229         lattice_elem_t a        = l->type;
2230         lattice_elem_t b        = r->type;
2231         ir_relation    relation = get_Cmp_relation(cmp);
2232         ir_tarval      *tv;
2233
2234         if (a.tv == tarval_top || b.tv == tarval_top) {
2235                 node->type.tv = tarval_undefined;
2236         } else if (is_con(a) && is_con(b)) {
2237                 default_compute(node);
2238
2239         /*
2240          * BEWARE: a == a is NOT always True for floating Point values, as
2241          * NaN != NaN is defined, so we must check this here.
2242          * (while for some pnc we could still optimize we have to stay
2243          *  consistent with compute_Cmp, so don't do anything for floats)
2244          */
2245         } else if (r->part == l->part && !mode_is_float(get_irn_mode(l->node))) {
2246                 tv = relation & ir_relation_equal ? tarval_b_true : tarval_b_false;
2247
2248                 /* if the node was ONCE evaluated to a constant, but now
2249                    this breaks AND we get from the argument partitions a different
2250                    result, ensure monotony by fall to bottom.
2251                    This happens because initially all nodes are in the same partition ... */
2252                 if (node->type.tv == tarval_bottom)
2253                         tv = tarval_bottom;
2254                 else if (node->type.tv != tv && is_constant_type(node->type))
2255                         tv = tarval_bottom;
2256                 node->type.tv = tv;
2257         } else {
2258                 node->type.tv = tarval_bottom;
2259         }
2260 }
2261
2262 /**
2263  * (Re-)compute the type for a Proj(Cond).
2264  *
2265  * @param node  the node
2266  * @param cond  the predecessor Cond node
2267  */
2268 static void compute_Proj_Cond(node_t *node, ir_node *cond)
2269 {
2270         ir_node *proj     = node->node;
2271         long    pnc       = get_Proj_proj(proj);
2272         ir_node *sel      = get_Cond_selector(cond);
2273         node_t  *selector = get_irn_node(sel);
2274
2275         /*
2276          * Note: it is crucial for the monotony that the Proj(Cond)
2277          * are evaluates after all predecessors of the Cond selector are
2278          * processed.
2279          * Example
2280          *
2281          * if (x != 0)
2282          *
2283          * Due to the fact that 0 is a const, the Cmp gets immediately
2284          * on the cprop list. It will be evaluated before x is evaluated,
2285          * might leaving x as Top. When later x is evaluated, the Cmp
2286          * might change its value.
2287          * BUT if the Cond is evaluated before this happens, Proj(Cond, FALSE)
2288          * gets R, and later changed to F if Cmp is evaluated to True!
2289          *
2290          * We prevent this by putting Conds in an extra cprop_X queue, which
2291          * gets evaluated after the cprop queue is empty.
2292          *
2293          * Note that this even happens with Click's original algorithm, if
2294          * Cmp(x, 0) is evaluated to True first and later changed to False
2295          * if x was Top first and later changed to a Const ...
2296          * It is unclear how Click solved that problem ...
2297          *
2298          * However, in rare cases even this does not help, if a Top reaches
2299          * a compare  through a Phi, than Proj(Cond) is evaluated changing
2300          * the type of the Phi to something other.
2301          * So, we take the last resort and bind the type to R once
2302          * it is calculated.
2303          *
2304          * (This might be even the way Click works around the whole problem).
2305          *
2306          * Finally, we may miss some optimization possibilities due to this:
2307          *
2308          * x = phi(Top, y)
2309          * if (x == 0)
2310          *
2311          * If Top reaches the if first, than we decide for != here.
2312          * If y later is evaluated to 0, we cannot revert this decision
2313          * and must live with both outputs enabled. If this happens,
2314          * we get an unresolved if (true) in the code ...
2315          *
2316          * In Click's version where this decision is done at the Cmp,
2317          * the Cmp is NOT optimized away than (if y evaluated to 1
2318          * for instance) and we get a if (1 == 0) here ...
2319          *
2320          * Both solutions are suboptimal.
2321          * At least, we could easily detect this problem and run
2322          * cf_opt() (or even combo) again :-(
2323          */
2324         if (node->type.tv == tarval_reachable)
2325                 return;
2326
2327         if (pnc == pn_Cond_true) {
2328                 if (selector->type.tv == tarval_b_false) {
2329                         node->type.tv = tarval_unreachable;
2330                 } else if (selector->type.tv == tarval_b_true) {
2331                         node->type.tv = tarval_reachable;
2332                 } else if (selector->type.tv == tarval_bottom) {
2333                         node->type.tv = tarval_reachable;
2334                 } else {
2335                         assert(selector->type.tv == tarval_top);
2336                         if (tarval_UNKNOWN == tarval_top) {
2337                                 /* any condition based on Top is "!=" */
2338                                 node->type.tv = tarval_unreachable;
2339                         } else {
2340                                 node->type.tv = tarval_unreachable;
2341                         }
2342                 }
2343         } else {
2344                 assert(pnc == pn_Cond_false);
2345
2346                 if (selector->type.tv == tarval_b_false) {
2347                         node->type.tv = tarval_reachable;
2348                 } else if (selector->type.tv == tarval_b_true) {
2349                         node->type.tv = tarval_unreachable;
2350                 } else if (selector->type.tv == tarval_bottom) {
2351                         node->type.tv = tarval_reachable;
2352                 } else {
2353                         assert(selector->type.tv == tarval_top);
2354                         if (tarval_UNKNOWN == tarval_top) {
2355                                 /* any condition based on Top is "!=" */
2356                                 node->type.tv = tarval_reachable;
2357                         } else {
2358                                 node->type.tv = tarval_unreachable;
2359                         }
2360                 }
2361         }
2362 }  /* compute_Proj_Cond */
2363
2364 static void compute_Proj_Switch(node_t *node, ir_node *switchn)
2365 {
2366         ir_node *proj     = node->node;
2367         long     pnc      = get_Proj_proj(proj);
2368         ir_node *sel      = get_Switch_selector(switchn);
2369         node_t  *selector = get_irn_node(sel);
2370
2371         /* see long comment in compute_Proj_Cond */
2372         if (node->type.tv == tarval_reachable)
2373                 return;
2374
2375         if (selector->type.tv == tarval_bottom) {
2376                 node->type.tv = tarval_reachable;
2377         } else if (selector->type.tv == tarval_top) {
2378                 if (tarval_UNKNOWN == tarval_top && pnc == pn_Switch_default) {
2379                         /* a switch based of Top is always "default" */
2380                         node->type.tv = tarval_reachable;
2381                 } else {
2382                         node->type.tv = tarval_unreachable;
2383                 }
2384         } else {
2385                 long                   value = get_tarval_long(selector->type.tv);
2386                 const ir_switch_table *table = get_Switch_table(switchn);
2387                 size_t                 n_entries = ir_switch_table_get_n_entries(table);
2388                 size_t                 e;
2389
2390                 for (e = 0; e < n_entries; ++e) {
2391                         const ir_switch_table_entry *entry
2392                                 = ir_switch_table_get_entry_const(table, e);
2393                         ir_tarval *min = entry->min;
2394                         ir_tarval *max = entry->max;
2395                         if (min == max) {
2396                                 if (selector->type.tv == min) {
2397                                         node->type.tv = entry->pn == pnc
2398                                                 ? tarval_reachable : tarval_unreachable;
2399                                         return;
2400                                 }
2401                         } else {
2402                                 long minval = get_tarval_long(min);
2403                                 long maxval = get_tarval_long(max);
2404                                 if (minval <= value && value <= maxval) {
2405                                         node->type.tv = entry->pn == pnc
2406                                                 ? tarval_reachable : tarval_unreachable;
2407                                         return;
2408                                 }
2409                         }
2410                 }
2411
2412                 /* no entry matched: default */
2413                 node->type.tv
2414                         = pnc == pn_Switch_default ? tarval_reachable : tarval_unreachable;
2415         }
2416 }
2417
2418 /**
2419 * (Re-)compute the type for a Proj-Node.
2420 *
2421 * @param node  the node
2422 */
2423 static void compute_Proj(node_t *node)
2424 {
2425 ir_node *proj = node->node;
2426         ir_mode *mode = get_irn_mode(proj);
2427         node_t  *block = get_irn_node(get_nodes_block(skip_Proj(proj)));
2428         ir_node *pred  = get_Proj_pred(proj);
2429
2430         if (block->type.tv == tarval_unreachable) {
2431                 /* a Proj in a unreachable Block stay Top */
2432                 node->type.tv = tarval_top;
2433                 return;
2434         }
2435         if (get_irn_node(pred)->type.tv == tarval_top && !is_Cond(pred) && !is_Switch(pred)) {
2436                 /* if the predecessor is Top, its Proj follow */
2437                 node->type.tv = tarval_top;
2438                 return;
2439         }
2440
2441         if (mode == mode_M) {
2442                 /* mode M is always bottom */
2443                 node->type.tv = tarval_bottom;
2444                 return;
2445         } else if (mode == mode_X) {
2446                 /* handle mode_X nodes */
2447                 switch (get_irn_opcode(pred)) {
2448                 case iro_Start:
2449                         /* the Proj_X from the Start is always reachable.
2450                            However this is already handled at the top. */
2451                         node->type.tv = tarval_reachable;
2452                         return;
2453                 case iro_Cond:
2454                         compute_Proj_Cond(node, pred);
2455                         return;
2456                 case iro_Switch:
2457                         compute_Proj_Switch(node, pred);
2458                         return;
2459                 default:
2460                         break;
2461                 }
2462         }
2463
2464         default_compute(node);
2465 }  /* compute_Proj */
2466
2467 /**
2468  * (Re-)compute the type for a Confirm.
2469  *
2470  * @param node  the node
2471  */
2472 static void compute_Confirm(node_t *node)
2473 {
2474         ir_node *confirm = node->node;
2475         node_t  *pred = get_irn_node(get_Confirm_value(confirm));
2476
2477         if (get_Confirm_relation(confirm) == ir_relation_equal) {
2478                 node_t *bound = get_irn_node(get_Confirm_bound(confirm));
2479
2480                 if (is_con(bound->type)) {
2481                         /* is equal to a constant */
2482                         node->type = bound->type;
2483                         return;
2484                 }
2485         }
2486         /* a Confirm is a copy OR a Const */
2487         node->type = pred->type;
2488 }  /* compute_Confirm */
2489
2490 /**
2491  * (Re-)compute the type for a given node.
2492  *
2493  * @param node  the node
2494  */
2495 static void compute(node_t *node)
2496 {
2497         ir_node *irn = node->node;
2498         compute_func func;
2499
2500 #ifndef VERIFY_MONOTONE
2501         /*
2502          * Once a node reaches bottom, the type cannot fall further
2503          * in the lattice and we can stop computation.
2504          * Do not take this exit if the monotony verifier is
2505          * enabled to catch errors.
2506          */
2507         if (node->type.tv == tarval_bottom)
2508                 return;
2509 #endif
2510
2511         if (!is_Block(irn)) {
2512                 /* for pinned nodes, check its control input */
2513                 if (get_irn_pinned(skip_Proj(irn)) == op_pin_state_pinned) {
2514                         node_t *block = get_irn_node(get_nodes_block(irn));
2515
2516                         if (block->type.tv == tarval_unreachable) {
2517                                 node->type.tv = tarval_top;
2518                                 return;
2519                         }
2520                 }
2521         }
2522
2523         func = (compute_func)node->node->op->ops.generic;
2524         if (func != NULL)
2525                 func(node);
2526 }  /* compute */
2527
2528 /*
2529  * Identity functions: Note that one might think that identity() is just a
2530  * synonym for equivalent_node(). While this is true, we cannot use it for the algorithm
2531  * here, because it expects that the identity node is one of the inputs, which is NOT
2532  * always true for equivalent_node() which can handle (and does sometimes) DAGs.
2533  * So, we have our own implementation, which copies some parts of equivalent_node()
2534  */
2535
2536 /**
2537  * Calculates the Identity for Phi nodes
2538  */
2539 static node_t *identity_Phi(node_t *node)
2540 {
2541         ir_node *phi    = node->node;
2542         ir_node *block  = get_nodes_block(phi);
2543         node_t  *n_part = NULL;
2544         int     i;
2545
2546         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
2547                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block, i));
2548
2549                 if (pred_X->type.tv == tarval_reachable) {
2550                         node_t *pred = get_irn_node(get_Phi_pred(phi, i));
2551
2552                         if (n_part == NULL)
2553                                 n_part = pred;
2554                         else if (n_part->part != pred->part) {
2555                                 /* incongruent inputs, not a follower */
2556                                 return node;
2557                         }
2558                 }
2559         }
2560         /* if n_part is NULL here, all inputs path are dead, the Phi computes
2561          * tarval_top, is in the TOP partition and should NOT being split! */
2562         assert(n_part != NULL);
2563         return n_part;
2564 }  /* identity_Phi */
2565
2566 /**
2567  * Calculates the Identity for commutative 0 neutral nodes.
2568  */
2569 static node_t *identity_comm_zero_binop(node_t *node)
2570 {
2571         ir_node   *op   = node->node;
2572         node_t    *a    = get_irn_node(get_binop_left(op));
2573         node_t    *b    = get_irn_node(get_binop_right(op));
2574         ir_mode   *mode = get_irn_mode(op);
2575         ir_tarval *zero;
2576
2577         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2578         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2579                 return node;
2580
2581         /* node: no input should be tarval_top, else the binop would be also
2582          * Top and not being split. */
2583         zero = get_mode_null(mode);
2584         if (a->type.tv == zero)
2585                 return b;
2586         if (b->type.tv == zero)
2587                 return a;
2588         return node;
2589 }  /* identity_comm_zero_binop */
2590
2591 /**
2592  * Calculates the Identity for Shift nodes.
2593  */
2594 static node_t *identity_shift(node_t *node)
2595 {
2596         ir_node   *op   = node->node;
2597         node_t    *b    = get_irn_node(get_binop_right(op));
2598         ir_mode   *mode = get_irn_mode(b->node);
2599         ir_tarval *zero;
2600
2601         /* node: no input should be tarval_top, else the binop would be also
2602          * Top and not being split. */
2603         zero = get_mode_null(mode);
2604         if (b->type.tv == zero)
2605                 return get_irn_node(get_binop_left(op));
2606         return node;
2607 }  /* identity_shift */
2608
2609 /**
2610  * Calculates the Identity for Mul nodes.
2611  */
2612 static node_t *identity_Mul(node_t *node)
2613 {
2614         ir_node   *op   = node->node;
2615         node_t    *a    = get_irn_node(get_Mul_left(op));
2616         node_t    *b    = get_irn_node(get_Mul_right(op));
2617         ir_mode   *mode = get_irn_mode(op);
2618         ir_tarval *one;
2619
2620         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2621         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2622                 return node;
2623
2624         /* node: no input should be tarval_top, else the binop would be also
2625          * Top and not being split. */
2626         one = get_mode_one(mode);
2627         if (a->type.tv == one)
2628                 return b;
2629         if (b->type.tv == one)
2630                 return a;
2631         return node;
2632 }  /* identity_Mul */
2633
2634 /**
2635  * Calculates the Identity for Sub nodes.
2636  */
2637 static node_t *identity_Sub(node_t *node)
2638 {
2639         ir_node *sub  = node->node;
2640         node_t  *b    = get_irn_node(get_Sub_right(sub));
2641         ir_mode *mode = get_irn_mode(sub);
2642
2643         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2644         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2645                 return node;
2646
2647         /* node: no input should be tarval_top, else the binop would be also
2648          * Top and not being split. */
2649         if (b->type.tv == get_mode_null(mode))
2650                 return get_irn_node(get_Sub_left(sub));
2651         return node;
2652 }  /* identity_Sub */
2653
2654 /**
2655  * Calculates the Identity for And nodes.
2656  */
2657 static node_t *identity_And(node_t *node)
2658 {
2659         ir_node   *andnode = node->node;
2660         node_t    *a       = get_irn_node(get_And_left(andnode));
2661         node_t    *b       = get_irn_node(get_And_right(andnode));
2662         ir_tarval *neutral = get_mode_all_one(get_irn_mode(andnode));
2663
2664         /* node: no input should be tarval_top, else the And would be also
2665          * Top and not being split. */
2666         if (a->type.tv == neutral)
2667                 return b;
2668         if (b->type.tv == neutral)
2669                 return a;
2670         return node;
2671 }  /* identity_And */
2672
2673 /**
2674  * Calculates the Identity for Confirm nodes.
2675  */
2676 static node_t *identity_Confirm(node_t *node)
2677 {
2678         ir_node *confirm = node->node;
2679
2680         /* a Confirm is always a Copy */
2681         return get_irn_node(get_Confirm_value(confirm));
2682 }  /* identity_Confirm */
2683
2684 /**
2685  * Calculates the Identity for Mux nodes.
2686  */
2687 static node_t *identity_Mux(node_t *node)
2688 {
2689         ir_node *mux = node->node;
2690         node_t  *t   = get_irn_node(get_Mux_true(mux));
2691         node_t  *f   = get_irn_node(get_Mux_false(mux));
2692         /*node_t  *sel; */
2693
2694         if (t->part == f->part)
2695                 return t;
2696
2697         /* for now, the 1-input identity is not supported */
2698 #if 0
2699         sel = get_irn_node(get_Mux_sel(mux));
2700
2701         /* Mux sel input is mode_b, so it is always a tarval */
2702         if (sel->type.tv == tarval_b_true)
2703                 return t;
2704         if (sel->type.tv == tarval_b_false)
2705                 return f;
2706 #endif
2707         return node;
2708 }  /* identity_Mux */
2709
2710 /**
2711  * Calculates the Identity for nodes.
2712  */
2713 static node_t *identity(node_t *node)
2714 {
2715         ir_node *irn = node->node;
2716
2717         switch (get_irn_opcode(irn)) {
2718         case iro_Phi:
2719                 return identity_Phi(node);
2720         case iro_Mul:
2721                 return identity_Mul(node);
2722         case iro_Add:
2723         case iro_Or:
2724         case iro_Eor:
2725                 return identity_comm_zero_binop(node);
2726         case iro_Shr:
2727         case iro_Shl:
2728         case iro_Shrs:
2729         case iro_Rotl:
2730                 return identity_shift(node);
2731         case iro_And:
2732                 return identity_And(node);
2733         case iro_Sub:
2734                 return identity_Sub(node);
2735         case iro_Confirm:
2736                 return identity_Confirm(node);
2737         case iro_Mux:
2738                 return identity_Mux(node);
2739         default:
2740                 return node;
2741         }
2742 }  /* identity */
2743
2744 /**
2745  * Node follower is a (new) follower of leader, segregate Leader
2746  * out edges.
2747  */
2748 static void segregate_def_use_chain_1(const ir_node *follower, node_t *leader)
2749 {
2750         DB((dbg, LEVEL_2, "%+F is a follower of %+F\n", follower, leader->node));
2751         /* The leader edges must remain sorted, but follower edges can
2752            be unsorted. */
2753         ir_node *l = leader->node;
2754         unsigned n = get_irn_n_outs(l);
2755         for (unsigned i = leader->n_followers; i < n; ++i) {
2756                 if (l->o.out->edges[i].use == follower) {
2757                         ir_def_use_edge t = l->o.out->edges[i];
2758
2759                         for (unsigned j = i; j-- > leader->n_followers; )
2760                                 l->o.out->edges[j+1] = l->o.out->edges[j];
2761                         l->o.out->edges[leader->n_followers] = t;
2762                         ++leader->n_followers;
2763                         break;
2764                 }
2765         }
2766 }  /* segregate_def_use_chain_1 */
2767
2768 /**
2769  * Node follower is a (new) follower segregate its Leader
2770  * out edges.
2771  *
2772  * @param follower  the follower IR node
2773  */
2774 static void segregate_def_use_chain(const ir_node *follower)
2775 {
2776         int i;
2777
2778         for (i = get_irn_arity(follower) - 1; i >= 0; --i) {
2779                 node_t *pred = get_irn_node(get_irn_n(follower, i));
2780
2781                 segregate_def_use_chain_1(follower, pred);
2782         }
2783 }  /* segregate_def_use_chain */
2784
2785 /**
2786  * Propagate constant evaluation.
2787  *
2788  * @param env  the environment
2789  */
2790 static void propagate(environment_t *env)
2791 {
2792         partition_t    *X, *Y;
2793         node_t         *x;
2794         lattice_elem_t old_type;
2795         node_t         *fallen;
2796         unsigned       n_fallen, old_type_was_T_or_C;
2797
2798         while (env->cprop != NULL) {
2799                 void *oldopcode = NULL;
2800
2801                 /* remove the first partition X from cprop */
2802                 X           = env->cprop;
2803                 X->on_cprop = 0;
2804                 env->cprop  = X->cprop_next;
2805
2806                 old_type_was_T_or_C = X->type_is_T_or_C;
2807
2808                 DB((dbg, LEVEL_2, "Propagate type on part%d\n", X->nr));
2809                 fallen   = NULL;
2810                 n_fallen = 0;
2811                 for (;;) {
2812                         int cprop_empty   = list_empty(&X->cprop);
2813                         int cprop_X_empty = list_empty(&X->cprop_X);
2814
2815                         if (cprop_empty && cprop_X_empty) {
2816                                 /* both cprop lists are empty */
2817                                 break;
2818                         }
2819
2820                         /* remove the first Node x from X.cprop */
2821                         if (cprop_empty) {
2822                                 /* Get a node from the cprop_X list only if
2823                                  * all data nodes are processed.
2824                                  * This ensures, that all inputs of the Cond
2825                                  * predecessor are processed if its type is still Top.
2826                                  */
2827                                 x = list_entry(X->cprop_X.next, node_t, cprop_list);
2828                         } else {
2829                                 x = list_entry(X->cprop.next, node_t, cprop_list);
2830                         }
2831
2832                         //assert(x->part == X);
2833                         list_del(&x->cprop_list);
2834                         x->on_cprop = 0;
2835
2836                         if (x->is_follower && identity(x) == x) {
2837                                 /* check the opcode first */
2838                                 if (oldopcode == NULL) {
2839                                         oldopcode = lambda_opcode(get_first_node(X), env);
2840                                 }
2841                                 if (oldopcode != lambda_opcode(x, env)) {
2842                                         if (x->on_fallen == 0) {
2843                                                 /* different opcode -> x falls out of this partition */
2844                                                 x->next      = fallen;
2845                                                 x->on_fallen = 1;
2846                                                 fallen       = x;
2847                                                 ++n_fallen;
2848                                                 DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2849                                         }
2850                                 }
2851
2852                                 /* x will make the follower -> leader transition */
2853                                 follower_to_leader(x);
2854
2855                                 /* In case of a follower -> leader transition of a Phi node
2856                                  * we have to ensure that the current partition will be split
2857                                  * by lambda n.(n[i].partition).
2858                                  *
2859                                  * This split may already happened before when some predecessors
2860                                  * of the Phi's Block are unreachable. Thus, we have to put the
2861                                  * current partition in the worklist to repeat the check.
2862                                  */
2863                                 if (is_Phi(x->node) && ! x->part->on_worklist)
2864                                         add_to_worklist(x->part, env);
2865                         }
2866
2867                         /* compute a new type for x */
2868                         old_type = x->type;
2869                         DB((dbg, LEVEL_3, "computing type of %+F\n", x->node));
2870                         compute(x);
2871                         if (x->type.tv != old_type.tv) {
2872                                 DB((dbg, LEVEL_2, "node %+F has changed type from %+F to %+F\n", x->node, old_type, x->type));
2873                                 verify_type(old_type, x);
2874
2875                                 if (x->on_fallen == 0) {
2876                                         /* Add x to fallen. Nodes might fall from T -> const -> _|_, so check that they are
2877                                            not already on the list. */
2878                                         x->next      = fallen;
2879                                         x->on_fallen = 1;
2880                                         fallen       = x;
2881                                         ++n_fallen;
2882                                         DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2883                                 }
2884                                 for (unsigned i = get_irn_n_outs(x->node); i-- > 0; ) {
2885                                         ir_node *succ = get_irn_out(x->node, i);
2886                                         node_t  *y    = get_irn_node(succ);
2887
2888                                         /* Add y to y.partition.cprop. */
2889                                         add_to_cprop(y, env);
2890                                 }
2891                         }
2892                 }
2893
2894                 if (n_fallen > 0 && n_fallen != X->n_leader) {
2895                         DB((dbg, LEVEL_2, "Splitting part%d by fallen\n", X->nr));
2896                         Y = split(&X, fallen, env);
2897                         /*
2898                          * We have split out fallen node. The type of the result
2899                          * partition is NOT set yet.
2900                          */
2901                         Y->type_is_T_or_C = 0;
2902                 } else {
2903                         Y = X;
2904                 }
2905                 /* remove the flags from the fallen list */
2906                 for (x = fallen; x != NULL; x = x->next)
2907                         x->on_fallen = 0;
2908
2909                 if (old_type_was_T_or_C) {
2910                         /* check if some nodes will make the leader -> follower transition */
2911                         list_for_each_entry_safe(node_t, y, tmp, &Y->Leader, node_list) {
2912                                 if (y->type.tv != tarval_top && ! is_con(y->type)) {
2913                                         node_t *eq_node = identity(y);
2914
2915                                         if (eq_node != y && eq_node->part == y->part) {
2916                                                 DB((dbg, LEVEL_2, "Node %+F is a follower of %+F\n", y->node, eq_node->node));
2917                                                 /* move to Follower */
2918                                                 y->is_follower = 1;
2919                                                 list_del(&y->node_list);
2920                                                 list_add_tail(&y->node_list, &Y->Follower);
2921                                                 --Y->n_leader;
2922
2923                                                 segregate_def_use_chain(y->node);
2924                                         }
2925                                 }
2926                         }
2927                 }
2928                 split_by(Y, env);
2929         }
2930 }  /* propagate */
2931
2932 /**
2933  * Get the leader for a given node from its congruence class.
2934  *
2935  * @param irn  the node
2936  */
2937 static ir_node *get_leader(node_t *node)
2938 {
2939         partition_t *part = node->part;
2940
2941         if (part->n_leader > 1 || node->is_follower) {
2942                 if (node->is_follower) {
2943                         DB((dbg, LEVEL_2, "Replacing follower %+F\n", node->node));
2944                 }
2945                 else
2946                         DB((dbg, LEVEL_2, "Found congruence class for %+F\n", node->node));
2947
2948                 return get_first_node(part)->node;
2949         }
2950         return node->node;
2951 }  /* get_leader */
2952
2953 /**
2954  * Returns non-zero if a mode_T node has only one reachable output.
2955  */
2956 static int only_one_reachable_proj(ir_node *n)
2957 {
2958         int k = 0;
2959
2960         for (unsigned i = get_irn_n_outs(n); i-- > 0; ) {
2961                 ir_node *proj = get_irn_out(n, i);
2962                 node_t  *node;
2963
2964                 /* skip non-control flow Proj's */
2965                 if (get_irn_mode(proj) != mode_X)
2966                         continue;
2967
2968                 node = get_irn_node(proj);
2969                 if (node->type.tv == tarval_reachable) {
2970                         if (++k > 1)
2971                                 return 0;
2972                 }
2973         }
2974         return 1;
2975 }  /* only_one_reachable_proj */
2976
2977 /**
2978  * Return non-zero if the control flow predecessor node pred
2979  * is the only reachable control flow exit of its block.
2980  *
2981  * @param pred   the control flow exit
2982  * @param block  the destination block
2983  */
2984 static int can_exchange(ir_node *pred, ir_node *block)
2985 {
2986         if (is_Start(pred) || get_Block_entity(block) != NULL)
2987                 return 0;
2988         else if (is_Jmp(pred))
2989                 return 1;
2990         else if (is_Raise(pred)) {
2991                 /* Raise is a tuple and usually has only one reachable ProjX,
2992                  * but it must not be eliminated like a Jmp */
2993                 return 0;
2994         }
2995         else if (get_irn_mode(pred) == mode_T) {
2996                 /* if the predecessor block has more than one
2997                    reachable outputs we cannot remove the block */
2998                 return only_one_reachable_proj(pred);
2999         }
3000         return 0;
3001 }  /* can_exchange */
3002
3003 /**
3004  * Block Post-Walker, apply the analysis results on control flow by
3005  * shortening Phi's and Block inputs.
3006  */
3007 static void apply_cf(ir_node *block, void *ctx)
3008 {
3009         environment_t *env = (environment_t*)ctx;
3010         node_t        *node = get_irn_node(block);
3011         int           i, j, k, n;
3012         ir_node       **ins, **in_X;
3013         ir_node       *phi, *next;
3014
3015         n = get_Block_n_cfgpreds(block);
3016
3017         if (node->type.tv == tarval_unreachable) {
3018                 env->modified = 1;
3019
3020                 for (i = n - 1; i >= 0; --i) {
3021                         ir_node *pred = get_Block_cfgpred(block, i);
3022
3023                         if (! is_Bad(pred)) {
3024                                 ir_node *pred_block = get_nodes_block(skip_Proj(pred));
3025                                 if (!is_Bad(pred_block)) {
3026                                         node_t *pred_bl = get_irn_node(pred_block);
3027
3028                                         if (pred_bl->flagged == 0) {
3029                                                 pred_bl->flagged = 3;
3030
3031                                                 if (pred_bl->type.tv == tarval_reachable) {
3032                                                         /*
3033                                                          * We will remove an edge from block to its pred.
3034                                                          * This might leave the pred block as an endless loop
3035                                                          */
3036                                                         if (! is_backedge(block, i))
3037                                                                 keep_alive(pred_bl->node);
3038                                                 }
3039                                         }
3040                                 }
3041                         }
3042                 }
3043
3044                 if (block == get_irg_end_block(current_ir_graph)) {
3045                         /* Analysis found out that the end block is unreachable,
3046                          * hence we remove all its control flow predecessors. */
3047                         set_irn_in(block, 0, NULL);
3048                 }
3049                 return;
3050         }
3051
3052         if (n == 1) {
3053                 /* only one predecessor combine */
3054                 ir_node *pred = skip_Proj(get_Block_cfgpred(block, 0));
3055
3056                 if (can_exchange(pred, block)) {
3057                         ir_node *new_block = get_nodes_block(pred);
3058                         DB((dbg, LEVEL_1, "Fuse %+F with %+F\n", block, new_block));
3059                         DBG_OPT_COMBO(block, new_block, FS_OPT_COMBO_CF);
3060                         exchange(block, new_block);
3061                         node->node = new_block;
3062                         env->modified = 1;
3063                 }
3064                 return;
3065         }
3066
3067         NEW_ARR_A(ir_node *, in_X, n);
3068         k = 0;
3069         for (i = 0; i < n; ++i) {
3070                 ir_node *pred = get_Block_cfgpred(block, i);
3071                 node_t  *node = get_irn_node(pred);
3072
3073                 if (node->type.tv == tarval_reachable) {
3074                         in_X[k++] = pred;
3075                 } else {
3076                         DB((dbg, LEVEL_1, "Removing dead input %d from %+F (%+F)\n", i, block, pred));
3077                         if (! is_Bad(pred)) {
3078                                 ir_node *pred_block = get_nodes_block(skip_Proj(pred));
3079                                 if (!is_Bad(pred_block)) {
3080                                         node_t *pred_bl = get_irn_node(pred_block);
3081
3082                                         if (!is_Bad(pred_bl->node) && pred_bl->flagged == 0) {
3083                                                 pred_bl->flagged = 3;
3084
3085                                                 if (pred_bl->type.tv == tarval_reachable) {
3086                                                         /*
3087                                                          * We will remove an edge from block to its pred.
3088                                                          * This might leave the pred block as an endless loop
3089                                                          */
3090                                                         if (! is_backedge(block, i))
3091                                                                 keep_alive(pred_bl->node);
3092                                                 }
3093                                         }
3094                                 }
3095                         }
3096                 }
3097         }
3098         if (k >= n)
3099                 return;
3100
3101         /* fix Phi's */
3102         NEW_ARR_A(ir_node *, ins, n);
3103         for (phi = get_Block_phis(block); phi != NULL; phi = next) {
3104                 node_t *node = get_irn_node(phi);
3105
3106                 next = get_Phi_next(phi);
3107                 if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
3108                         /* this Phi is replaced by a constant */
3109                         ir_tarval *tv = node->type.tv;
3110                         ir_node   *c  = new_r_Const(current_ir_graph, tv);
3111
3112                         set_irn_node(c, node);
3113                         node->node = c;
3114                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", phi, c));
3115                         DBG_OPT_COMBO(phi, c, FS_OPT_COMBO_CONST);
3116                         exchange(phi, c);
3117                         env->modified = 1;
3118                 } else {
3119                         j = 0;
3120                         for (i = 0; i < n; ++i) {
3121                                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
3122
3123                                 if (pred->type.tv == tarval_reachable) {
3124                                         ins[j++] = get_Phi_pred(phi, i);
3125                                 }
3126                         }
3127                         if (j == 1) {
3128                                 /* this Phi is replaced by a single predecessor */
3129                                 ir_node *s = ins[0];
3130                                 node_t *phi_node = get_irn_node(phi);
3131
3132                                 node->node = s;
3133                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F because of cf change\n", phi, s));
3134                                 DBG_OPT_COMBO(phi, s, FS_OPT_COMBO_FOLLOWER);
3135                                 exchange(phi, s);
3136                                 phi_node->node = s;
3137                                 env->modified = 1;
3138                         } else {
3139                                 set_irn_in(phi, j, ins);
3140                                 env->modified = 1;
3141                         }
3142                 }
3143         }
3144
3145         /* fix block */
3146         if (k == 1) {
3147                 /* this Block has only one live predecessor */
3148                 ir_node *pred = skip_Proj(in_X[0]);
3149
3150                 if (can_exchange(pred, block)) {
3151                         ir_node *new_block = get_nodes_block(pred);
3152                         DBG_OPT_COMBO(block, new_block, FS_OPT_COMBO_CF);
3153                         exchange(block, new_block);
3154                         node->node = new_block;
3155                         env->modified = 1;
3156                         return;
3157                 }
3158         }
3159         set_irn_in(block, k, in_X);
3160         env->modified = 1;
3161 }  /* apply_cf */
3162
3163 /**
3164  * Exchange a node by its leader.
3165  * Beware: in rare cases the mode might be wrong here, for instance
3166  * AddP(x, NULL) is a follower of x, but with different mode.
3167  * Fix it here.
3168  */
3169 static void exchange_leader(ir_node *irn, ir_node *leader)
3170 {
3171         ir_mode *mode = get_irn_mode(irn);
3172         if (mode != get_irn_mode(leader)) {
3173                 /* The conv is a no-op, so we are free to place it
3174                  * either in the block of the leader OR in irn's block.
3175                  * Probably placing it into leaders block might reduce
3176                  * the number of Conv due to CSE. */
3177                 ir_node  *block = get_nodes_block(leader);
3178                 dbg_info *dbg   = get_irn_dbg_info(irn);
3179                 ir_node  *nlead = new_rd_Conv(dbg, block, leader, mode);
3180
3181                 if (nlead != leader) {
3182                         /* Note: this newly create irn has no node info because
3183                          * it is created after the analysis. However, this node
3184                          * replaces the node irn and should not be visited again,
3185                          * so set its visited count to the count of irn.
3186                          * Otherwise we might visited this node more than once if
3187                          * irn had more than one user.
3188                          */
3189                         set_irn_node(nlead, NULL);
3190                         set_irn_visited(nlead, get_irn_visited(irn));
3191                         leader = nlead;
3192                 }
3193         }
3194         exchange(irn, leader);
3195 }  /* exchange_leader */
3196
3197 /**
3198  * Check, if all users of a mode_M node are dead. Use
3199  * the Def-Use edges for this purpose, as they still
3200  * reflect the situation.
3201  */
3202 static int all_users_are_dead(const ir_node *irn)
3203 {
3204         unsigned n = get_irn_n_outs(irn);
3205         for (unsigned i = 0; i < n; ++i) {
3206                 const ir_node *succ  = get_irn_out(irn, i);
3207                 const node_t  *block = get_irn_node(get_nodes_block(succ));
3208                 const node_t  *node;
3209
3210                 if (block->type.tv == tarval_unreachable) {
3211                         /* block is unreachable */
3212                         continue;
3213                 }
3214                 node = get_irn_node(succ);
3215                 if (node->type.tv != tarval_top) {
3216                         /* found a reachable user */
3217                         return 0;
3218                 }
3219         }
3220         /* all users are unreachable */
3221         return 1;
3222 }  /* all_user_are_dead */
3223
3224 /**
3225  * Walker: Find reachable mode_M nodes that have only
3226  * unreachable users. These nodes must be kept later.
3227  */
3228 static void find_kept_memory(ir_node *irn, void *ctx)
3229 {
3230         environment_t *env = (environment_t*)ctx;
3231         node_t        *node, *block;
3232
3233         if (get_irn_mode(irn) != mode_M)
3234                 return;
3235
3236         block = get_irn_node(get_nodes_block(irn));
3237         if (block->type.tv == tarval_unreachable)
3238                 return;
3239
3240         node = get_irn_node(irn);
3241         if (node->type.tv == tarval_top)
3242                 return;
3243
3244         /* ok, we found a live memory node. */
3245         if (all_users_are_dead(irn)) {
3246                 DB((dbg, LEVEL_1, "%+F must be kept\n", irn));
3247                 ARR_APP1(ir_node *, env->kept_memory, irn);
3248         }
3249 }  /* find_kept_memory */
3250
3251 /**
3252  * Post-Walker, apply the analysis results;
3253  */
3254 static void apply_result(ir_node *irn, void *ctx)
3255 {
3256         environment_t *env = (environment_t*)ctx;
3257         node_t        *node = get_irn_node(irn);
3258
3259         if (is_Block(irn) || is_End(irn) || is_Bad(irn)) {
3260                 /* blocks already handled, do not touch the End node */
3261         } else {
3262                 node_t *block = get_irn_node(get_nodes_block(irn));
3263
3264                 if (block->type.tv == tarval_unreachable) {
3265                         ir_graph *irg  = get_irn_irg(irn);
3266                         ir_mode  *mode = get_irn_mode(node->node);
3267                         ir_node  *bad  = new_r_Bad(irg, mode);
3268
3269                         /* here, bad might already have a node, but this can be safely ignored
3270                            as long as bad has at least ONE valid node */
3271                         set_irn_node(bad, node);
3272                         node->node = bad;
3273                         DB((dbg, LEVEL_1, "%+F is unreachable\n", irn));
3274                         exchange(irn, bad);
3275                         env->modified = 1;
3276                 } else if (node->type.tv == tarval_top) {
3277                         ir_mode *mode = get_irn_mode(irn);
3278
3279                         if (mode == mode_M) {
3280                                 /* never kill a mode_M node */
3281                                 if (is_Proj(irn)) {
3282                                         ir_node *pred  = get_Proj_pred(irn);
3283                                         node_t  *pnode = get_irn_node(pred);
3284
3285                                         if (pnode->type.tv == tarval_top) {
3286                                                 /* skip the predecessor */
3287                                                 ir_node *mem = get_memop_mem(pred);
3288                                                 node->node = mem;
3289                                                 DB((dbg, LEVEL_1, "%+F computes Top, replaced by %+F\n", irn, mem));
3290                                                 exchange(irn, mem);
3291                                                 env->modified = 1;
3292                                         }
3293                                 }
3294                                 /* leave other nodes, especially PhiM */
3295                         } else if (mode == mode_T) {
3296                                 /* Do not kill mode_T nodes, kill their Projs */
3297                         } else if (! is_Unknown(irn)) {
3298                                 /* don't kick away Unknown's, they might be still needed */
3299                                 ir_node *unk = new_r_Unknown(current_ir_graph, mode);
3300
3301                                 /* control flow should already be handled at apply_cf() */
3302                                 assert(mode != mode_X);
3303
3304                                 /* see comment above */
3305                                 set_irn_node(unk, node);
3306                                 node->node = unk;
3307                                 DB((dbg, LEVEL_1, "%+F computes Top\n", irn));
3308                                 exchange(irn, unk);
3309                                 env->modified = 1;
3310                         }
3311                 }
3312                 else if (get_irn_mode(irn) == mode_X) {
3313                         if (is_Proj(irn)) {
3314                                 /* leave or Jmp */
3315                                 ir_node *cond = get_Proj_pred(irn);
3316
3317                                 if (is_Cond(cond) || is_Switch(cond)) {
3318                                         if (only_one_reachable_proj(cond)) {
3319                                                 ir_node *jmp = new_r_Jmp(block->node);
3320                                                 set_irn_node(jmp, node);
3321                                                 node->node = jmp;
3322                                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, jmp));
3323                                                 DBG_OPT_COMBO(irn, jmp, FS_OPT_COMBO_CF);
3324                                                 exchange(irn, jmp);
3325                                                 env->modified = 1;
3326                                         } else {
3327                                                 if (is_Switch(cond)) {
3328                                                         node_t    *sel = get_irn_node(get_Switch_selector(cond));
3329                                                         ir_tarval *tv  = sel->type.tv;
3330
3331                                                         if (is_tarval(tv) && tarval_is_constant(tv)) {
3332                                                                 /* The selector is a constant, but more
3333                                                                  * than one output is active: An unoptimized
3334                                                                  * case found. */
3335                                                                 env->unopt_cf = 1;
3336                                                         }
3337                                                 }
3338                                         }
3339                                 }
3340                         }
3341                 } else {
3342                         /* normal data node */
3343                         if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
3344                                 ir_tarval *tv = node->type.tv;
3345
3346                                 /*
3347                                  * Beware: never replace mode_T nodes by constants. Currently we must mark
3348                                  * mode_T nodes with constants, but do NOT replace them.
3349                                  */
3350                                 if (! is_Const(irn) && get_irn_mode(irn) != mode_T) {
3351                                         /* can be replaced by a constant */
3352                                         ir_node *c = new_r_Const(current_ir_graph, tv);
3353                                         set_irn_node(c, node);
3354                                         node->node = c;
3355                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, c));
3356                                         DBG_OPT_COMBO(irn, c, FS_OPT_COMBO_CONST);
3357                                         exchange_leader(irn, c);
3358                                         env->modified = 1;
3359                                 }
3360                         } else if (is_entity(node->type.sym.entity_p)) {
3361                                 if (! is_SymConst(irn)) {
3362                                         /* can be replaced by a SymConst */
3363                                         ir_node *symc = new_r_SymConst(current_ir_graph, get_irn_mode(irn), node->type.sym, symconst_addr_ent);
3364                                         set_irn_node(symc, node);
3365                                         node->node = symc;
3366
3367                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, symc));
3368                                         DBG_OPT_COMBO(irn, symc, FS_OPT_COMBO_CONST);
3369                                         exchange_leader(irn, symc);
3370                                         env->modified = 1;
3371                                 }
3372                         } else if (is_Confirm(irn)) {
3373                                 /* Confirms are always follower, but do not kill them here */
3374                         } else {
3375                                 ir_node *leader = get_leader(node);
3376
3377                                 if (leader != irn) {
3378                                         int non_strict_phi = 0;
3379
3380                                         /*
3381                                          * Beware: Do not remove Phi(Unknown, ..., x, ..., Unknown)
3382                                          * as this might create non-strict programs.
3383                                          */
3384                                         if (node->is_follower && is_Phi(irn) && !is_Unknown(leader)) {
3385                                                 int i;
3386
3387                                                 for (i = get_Phi_n_preds(irn) - 1; i >= 0; --i) {
3388                                                         ir_node *pred = get_Phi_pred(irn, i);
3389
3390                                                         if (is_Unknown(pred)) {
3391                                                                 non_strict_phi = 1;
3392                                                                 break;
3393                                                         }
3394                                                 }
3395                                         }
3396                                         if (! non_strict_phi) {
3397                                                 DB((dbg, LEVEL_1, "%+F from part%d is replaced by %+F\n", irn, node->part->nr, leader));
3398                                                 if (node->is_follower)
3399                                                         DBG_OPT_COMBO(irn, leader, FS_OPT_COMBO_FOLLOWER);
3400                                                 else
3401                                                         DBG_OPT_COMBO(irn, leader, FS_OPT_COMBO_CONGRUENT);
3402                                                 exchange_leader(irn, leader);
3403                                                 env->modified = 1;
3404                                         }
3405                                 }
3406                         }
3407                 }
3408         }
3409 }  /* apply_result */
3410
3411 /**
3412  * Fix the keep-alives by deleting unreachable ones.
3413  */
3414 static void apply_end(ir_node *end, environment_t *env)
3415 {
3416         int i, j,  n = get_End_n_keepalives(end);
3417         ir_node **in = NULL;
3418
3419         if (n > 0)
3420                 NEW_ARR_A(ir_node *, in, n);
3421
3422         /* fix the keep alive */
3423         for (i = j = 0; i < n; i++) {
3424                 ir_node *ka = get_End_keepalive(end, i);
3425                 ir_node *block;
3426                 node_t  *node;
3427
3428                 if (is_Bad(ka))
3429                         continue;
3430                 if (!is_Block(ka)) {
3431                         block = get_nodes_block(ka);
3432                         if (is_Bad(block))
3433                                 continue;
3434                 } else {
3435                         block = ka;
3436                 }
3437
3438                 node = get_irn_node(block);
3439                 if (node->type.tv != tarval_unreachable)
3440                         in[j++] = ka;
3441         }
3442         if (j != n) {
3443                 set_End_keepalives(end, j, in);
3444                 env->modified = 1;
3445         }
3446 }  /* apply_end */
3447
3448 #define SET(code) op_##code->ops.generic = (op_func)compute_##code
3449
3450 /**
3451  * sets the generic functions to compute.
3452  */
3453 static void set_compute_functions(void)
3454 {
3455         size_t i, n;
3456
3457         /* set the default compute function */
3458         for (i = 0, n = ir_get_n_opcodes(); i < n; ++i) {
3459                 ir_op *op = ir_get_opcode(i);
3460                 op->ops.generic = (op_func)default_compute;
3461         }
3462
3463         /* set specific functions */
3464         SET(Block);
3465         SET(Unknown);
3466         SET(Bad);
3467         SET(Jmp);
3468         SET(Phi);
3469         SET(Add);
3470         SET(Sub);
3471         SET(Eor);
3472         SET(SymConst);
3473         SET(Cmp);
3474         SET(Proj);
3475         SET(Confirm);
3476         SET(Return);
3477         SET(End);
3478         SET(Call);
3479 }  /* set_compute_functions */
3480
3481 /**
3482  * Add memory keeps.
3483  */
3484 static void add_memory_keeps(ir_node **kept_memory, size_t len)
3485 {
3486         ir_node      *end = get_irg_end(current_ir_graph);
3487         int          i;
3488         size_t       idx;
3489         ir_nodeset_t set;
3490
3491         ir_nodeset_init(&set);
3492
3493         /* check, if those nodes are already kept */
3494         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i)
3495                 ir_nodeset_insert(&set, get_End_keepalive(end, i));
3496
3497         for (idx = 0; idx < len; ++idx) {
3498                 ir_node *ka = kept_memory[idx];
3499
3500                 if (! ir_nodeset_contains(&set, ka)) {
3501                         add_End_keepalive(end, ka);
3502                 }
3503         }
3504         ir_nodeset_destroy(&set);
3505 }  /* add_memory_keeps */
3506
3507 void combo(ir_graph *irg)
3508 {
3509         environment_t env;
3510         ir_node       *initial_bl;
3511         node_t        *start;
3512         ir_graph      *rem = current_ir_graph;
3513         size_t        len;
3514
3515         assure_irg_properties(irg,
3516                 IR_GRAPH_PROPERTY_NO_BADS
3517                 | IR_GRAPH_PROPERTY_CONSISTENT_OUTS
3518                 | IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
3519
3520         current_ir_graph = irg;
3521
3522         /* register a debug mask */
3523         FIRM_DBG_REGISTER(dbg, "firm.opt.combo");
3524
3525         DB((dbg, LEVEL_1, "Doing COMBO for %+F\n", irg));
3526
3527         obstack_init(&env.obst);
3528         env.worklist       = NULL;
3529         env.cprop          = NULL;
3530         env.touched        = NULL;
3531         env.initial        = NULL;
3532 #ifdef DEBUG_libfirm
3533         env.dbg_list       = NULL;
3534 #endif
3535         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
3536         env.kept_memory    = NEW_ARR_F(ir_node *, 0);
3537         env.end_idx        = get_opt_global_cse() ? 0 : -1;
3538         env.lambda_input   = 0;
3539         env.modified       = 0;
3540         env.unopt_cf       = 0;
3541         /* options driving the optimization */
3542         env.commutative    = 1;
3543         env.opt_unknown    = 1;
3544
3545         /* we have our own value_of function */
3546         set_value_of_func(get_node_tarval);
3547
3548         set_compute_functions();
3549         DEBUG_ONLY(part_nr = 0;)
3550
3551         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
3552
3553         if (env.opt_unknown)
3554                 tarval_UNKNOWN = tarval_top;
3555         else
3556                 tarval_UNKNOWN = tarval_bad;
3557
3558         /* create the initial partition and place it on the work list */
3559         env.initial = new_partition(&env);
3560         add_to_worklist(env.initial, &env);
3561         irg_walk_graph(irg, create_initial_partitions, init_block_phis, &env);
3562
3563         /* set the hook: from now, every node has a partition and a type */
3564         DEBUG_ONLY(set_dump_node_vcgattr_hook(dump_partition_hook);)
3565
3566         /* all nodes on the initial partition have type Top */
3567         env.initial->type_is_T_or_C = 1;
3568
3569         /* Place the START Node's partition on cprop.
3570            Place the START Node on its local worklist. */
3571         initial_bl = get_irg_start_block(irg);
3572         start      = get_irn_node(initial_bl);
3573         add_to_cprop(start, &env);
3574
3575         do {
3576                 propagate(&env);
3577                 if (env.worklist != NULL)
3578                         cause_splits(&env);
3579         } while (env.cprop != NULL || env.worklist != NULL);
3580
3581         dump_all_partitions(&env);
3582         check_all_partitions(&env);
3583
3584 #if 0
3585         dump_ir_block_graph(irg, "-partition");
3586 #endif
3587
3588         /* apply the result */
3589
3590         /* check, which nodes must be kept */
3591         irg_walk_graph(irg, NULL, find_kept_memory, &env);
3592
3593         /* kill unreachable control flow */
3594         irg_block_walk_graph(irg, NULL, apply_cf, &env);
3595         /* Kill keep-alives of dead blocks: this speeds up apply_result()
3596          * and fixes assertion because dead cf to dead blocks is NOT removed by
3597          * apply_cf(). */
3598         apply_end(get_irg_end(irg), &env);
3599         irg_walk_graph(irg, NULL, apply_result, &env);
3600
3601         len = ARR_LEN(env.kept_memory);
3602         if (len > 0)
3603                 add_memory_keeps(env.kept_memory, len);
3604
3605         if (env.unopt_cf) {
3606                 DB((dbg, LEVEL_1, "Unoptimized Control Flow left"));
3607         }
3608
3609         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
3610
3611         /* remove the partition hook */
3612         DEBUG_ONLY(set_dump_node_vcgattr_hook(NULL);)
3613
3614         DEL_ARR_F(env.kept_memory);
3615         del_set(env.opcode2id_map);
3616         obstack_free(&env.obst, NULL);
3617
3618         /* restore value_of() default behavior */
3619         set_value_of_func(NULL);
3620         current_ir_graph = rem;
3621
3622         confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_NONE);
3623 }  /* combo */
3624
3625 /* Creates an ir_graph pass for combo. */
3626 ir_graph_pass_t *combo_pass(const char *name)
3627 {
3628         return def_graph_pass(name ? name : "combo", combo);
3629 }  /* combo_pass */