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