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