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