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