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