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