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