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