add sorting of out edges, some small fixes
[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  * Note that we use the terminology from Click's work here, which is different
27  * in some cases from Firm terminology.  Especially, Click's type is a
28  * Firm tarval, nevertheless we call it type here for "maximum compatibility".
29  */
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <assert.h>
35
36 #include "iroptimize.h"
37 #include "irflag.h"
38 #include "list.h"
39 #include "array.h"
40 #include "set.h"
41 #include "pmap.h"
42 #include "obstack.h"
43 #include "irgraph_t.h"
44 #include "irnode_t.h"
45 #include "iropt_t.h"
46 #include "irgwalk.h"
47 #include "irop.h"
48 #include "irouts.h"
49 #include "irgmod.h"
50 #include "debug.h"
51
52 #include "tv_t.h"
53
54 #include "irprintf.h"
55 #include "irdump.h"
56
57 /* we need the tarval_R and tarval_U */
58 #define tarval_R  tarval_top
59 #define tarval_U  tarval_bottom
60
61 typedef struct node_t            node_t;
62 typedef struct partition_t       partition_t;
63 typedef struct opcode_key_t      opcode_key_t;
64 typedef struct opcode_entry_t    opcode_entry_t;
65 typedef struct listmap_entry_t   listmap_entry_t;
66
67 /** The type of the compute function. */
68 typedef void (*compute_func)(node_t *node);
69
70 /**
71  * An opcode map key.
72  */
73 struct opcode_key_t {
74         ir_opcode   code;   /**< The Firm opcode. */
75         ir_mode     *mode;  /**< The mode of all nodes in the partition. */
76 };
77
78 /**
79  * An entry in the opcode map.
80  */
81 struct opcode_entry_t {
82         opcode_key_t key;    /**< The key. */
83         partition_t  *part;  /**< The associated partition. */
84 };
85
86 /**
87  * An entry in the list_map.
88  */
89 struct listmap_entry_t {
90         void            *id;    /**< The id. */
91         node_t          *list;  /**< The associated list for this id. */
92         listmap_entry_t *next;  /**< Link to the next entry in the map. */
93 };
94
95 /** We must map id's to lists. */
96 typedef struct listmap_t {
97         set             *map;    /**< Map id's to listmap_entry_t's */
98         listmap_entry_t *values; /**< List of all values in the map. */
99 } listmap_t;
100
101 /**
102  * A lattice element. Because we handle constants and symbolic constants different, we
103  * have to use this union.
104  */
105 typedef union {
106         tarval          *tv;
107         symconst_symbol sym;
108 } lattice_elem_t;
109
110 /**
111  * A node.
112  */
113 struct node_t {
114         ir_node         *node;         /**< The IR-node itself. */
115         list_head       node_list;     /**< Double-linked list of entries. */
116         partition_t     *part;         /**< points to the partition this node belongs to */
117         node_t          *cprop_next;   /**< Next node on partition.cprop list. */
118         node_t          *next;         /**< Next node on local list (partition.touched, fallen). */
119         ir_def_use_edge *next_edge;    /**< Points to the next Def-Use edge to use. */
120         lattice_elem_t  type;          /**< The associated lattice element "type". */
121         int             n_inputs;      /**< Maximum input number of Def-Use edges. */
122         unsigned        on_touched:1;  /**< Set, if this node is on the partition.touched set. */
123         unsigned        on_cprop:1;    /**< Set, if this node is on the partition.cprop list. */
124 };
125
126 /**
127  * A partition containing congruent nodes.
128  */
129 struct partition_t {
130         list_head         entries;       /**< The head of partition node list. */
131         node_t            *cprop;        /**< The partition.cprop list. */
132         partition_t       *wl_next;      /**< Next entry in the work list if any. */
133         partition_t       *touched_next; /**< Points to the next partition in the touched set. */
134         partition_t       *cprop_next;   /**< Points to the next partition in the cprop list. */
135         node_t            *touched;      /**< The partition.touched set of this partition. */
136         unsigned          n_nodes;       /**< Number of entries in this partition. */
137         unsigned          n_touched;     /**< Number of entries in the partition.touched. */
138         int               n_inputs;      /**< Maximum number of inputs of all entries. */
139         unsigned          on_worklist:1; /**< Set, if this partition is in the work list. */
140         unsigned          on_touched:1;  /**< Set, if this partition is on the touched set. */
141         unsigned          on_cprop:1;    /**< Set, if this partition is on the cprop list. */
142 #ifdef DEBUG_libfirm
143         partition_t       *dbg_next;     /**< Link all partitions for debugging */
144         unsigned          nr;            /**< A unique number for (what-)mapping, >0. */
145 #endif
146 };
147
148 typedef struct environment_t {
149         struct obstack  obst;           /**< obstack to allocate data structures. */
150         partition_t     *worklist;      /**< The work list. */
151         partition_t     *cprop;         /**< The constant propagation list. */
152         partition_t     *touched;       /**< the touched set. */
153         partition_t     *TOP;           /**< The TOP partition. */
154 #ifdef DEBUG_libfirm
155         partition_t     *dbg_list;      /**< List of all partitions. */
156 #endif
157         set             *opcode_map;    /**< The initial opcode->partition map. */
158         set             *opcode2id_map; /**< The opcodeMode->id map. */
159         pmap            *type2id_map;   /**< The type->id map. */
160         int             end_idx;        /**< -1 for local and 0 for global congruences. */
161         int             lambda_input;   /**< Captured argument for lambda_partition(). */
162 } environment_t;
163
164 /** Type of the what function. */
165 typedef void *(*what_func)(const node_t *node, environment_t *env);
166
167 #define get_irn_node(irn)         ((node_t *)get_irn_link(irn))
168 #define set_irn_node(irn, node)   set_irn_link(irn, node)
169
170 /** The debug module handle. */
171 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
172
173 /** Next partition number. */
174 DEBUG_ONLY(static unsigned part_nr = 0);
175
176 #ifdef DEBUG_libfirm
177 /**
178  * Dump partition to output.
179  */
180 static void dump_partition(const char *msg, partition_t *part) {
181         node_t *node;
182         int    first = 1;
183
184         DB((dbg, LEVEL_2, "%s part%u (%u) {\n  ", msg, part->nr, part->n_nodes));
185         list_for_each_entry(node_t, node, &part->entries, node_list) {
186                 DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
187                 first = 0;
188         }
189         DB((dbg, LEVEL_2, "\n}\n"));
190 }
191
192 /**
193  * Dump all partitions.
194  */
195 static void dump_all_partitions(environment_t *env) {
196         partition_t *P;
197
198         DB((dbg, LEVEL_2, "All partitions\n===============\n"));
199         for (P = env->dbg_list; P != NULL; P = P->dbg_next)
200                 dump_partition("", P);
201 }
202
203 #else
204 #define dump_partition(msg, part)
205 #define dump_all_partitions(env)
206 #endif
207
208 /**
209  * Compare two pointer values of a listmap.
210  */
211 static int listmap_cmp_ptr(const void *elt, const void *key, size_t size) {
212         const listmap_entry_t *e1 = elt;
213         const listmap_entry_t *e2 = key;
214
215         return e1->id != e2->id;
216 }  /* listmap_cmp_ptr */
217
218 /**
219  * Initializes a listmap.
220  *
221  * @param map  the listmap
222  */
223 static void listmap_init(listmap_t *map) {
224         map->map    = new_set(listmap_cmp_ptr, 16);
225         map->values = NULL;
226 }  /* listmap_init */
227
228 /**
229  * Terminates a listmap.
230  *
231  * @param map  the listmap
232  */
233 static void listmap_term(listmap_t *map) {
234         del_set(map->map);
235 }  /* listmap_term */
236
237 /**
238  * Return the associated listmap entry for a given id.
239  *
240  * @param map  the listmap
241  * @param id   the id to search for
242  *
243  * @return the asociated listmap entry for the given id
244  */
245 static listmap_entry_t *listmap_find(listmap_t *map, void *id) {
246         listmap_entry_t key, *entry;
247
248         key.id   = id;
249         key.list = NULL;
250         key.next = NULL;
251         entry = set_insert(map->map, &key, sizeof(key), HASH_PTR(id));
252
253         if (entry->list == NULL) {
254                 /* a new entry, put into the list */
255                 entry->next = map->values;
256                 map->values = entry;
257         }
258         return entry;
259 }  /* listmap_find */
260
261 /**
262  * Calculate the hash value for an opcode map entry.
263  *
264  * @param entry  an opcode map entry
265  *
266  * @return a hash value for the given opcode map entry
267  */
268 static unsigned opcode_hash(const opcode_key_t *entry) {
269         return (entry->mode - (ir_mode *)0) * 9 + entry->code;
270 }  /* opcode_hash */
271
272 /**
273  * Compare two entries in the opcode map.
274  */
275 static int cmp_opcode(const void *elt, const void *key, size_t size) {
276         const opcode_key_t *o1 = elt;
277         const opcode_key_t *o2 = key;
278
279         return o1->code != o2->code || o1->mode != o2->mode;
280 }  /* cmp_opcode */
281
282 /**
283  * Compare two Def-Use edges for input position.
284  */
285 static int cmp_def_use_edge(const void *a, const void *b) {
286         const ir_def_use_edge *ea = a;
287         const ir_def_use_edge *eb = b;
288
289         /* no overrun, because range is [-1, MAXINT] */
290         return ea->pos - eb->pos;
291 }  /* cmp_def_use_edge */
292
293 /**
294  * We need the Def-Use edges sorted.
295  */
296 static void sort_irn_outs(node_t *node) {
297         ir_node *irn = node->node;
298         int n_outs = get_irn_n_outs(irn);
299
300         if (n_outs > 1) {
301                 qsort(&irn->out[1], n_outs, sizeof(irn->out[0]), cmp_def_use_edge);
302         }
303         node->n_inputs = irn->out[n_outs + 1].pos;
304 }  /* sort_irn_outs */
305
306 /**
307  * Return the type of a node.
308  *
309  * @param irn  an IR-node
310  *
311  * @return the associated type of this node
312  */
313 static INLINE lattice_elem_t get_node_type(const ir_node *irn) {
314         return get_irn_node(irn)->type;
315 }  /* get_node_type */
316
317 /**
318  * Return the tarval of a node.
319  *
320  * @param irn  an IR-node
321  *
322  * @return the associated type of this node
323  */
324 static INLINE tarval *get_node_tarval(const ir_node *irn) {
325         lattice_elem_t type = get_node_type(irn);
326
327         if (is_tarval(type.tv))
328                 return type.tv;
329         return tarval_bottom;
330 }  /* get_node_type */
331
332
333 /**
334  * Create a new empty partition.
335  *
336  * @param env   the environment
337  *
338  * @return a newly allocated partition
339  */
340 static INLINE partition_t *new_partition(environment_t *env) {
341         partition_t *part = obstack_alloc(&env->obst, sizeof(*part));
342
343         INIT_LIST_HEAD(&part->entries);
344         part->cprop        = NULL;
345         part->wl_next      = env->worklist;
346         part->touched_next = NULL;
347         part->cprop_next   = NULL;
348         part->touched      = NULL;
349         part->n_nodes      = 0;
350         part->n_touched    = 0;
351         part->n_inputs     = 0;
352         part->on_worklist  = 0;
353         part->on_touched   = 0;
354         part->on_cprop     = 0;
355 #ifdef DEBUG_libfirm
356         part->dbg_next     = env->dbg_list;
357         env->dbg_list      = part;
358         part->nr           = part_nr++;
359 #endif
360
361         return part;
362 }  /* new_partition */
363
364 /**
365  * Get the partition for a given IR-node.
366  *
367  * @param irn   the IR-node
368  * @param env   the environment
369  *
370  * @return the partition where irn lies
371  */
372 static INLINE partition_t *get_partition_for_irn(const ir_node *irn, environment_t *env) {
373         opcode_entry_t key, *entry;
374         unsigned       hash;
375
376         key.key.code = get_irn_opcode(irn);
377         key.key.mode = get_irn_mode(irn);
378         hash         = opcode_hash(&key.key);
379
380         entry = set_find(env->opcode_map, &key, sizeof(key), hash);
381         if (entry == NULL) {
382                 /* create a new partition and place it on the wait queue */
383                 partition_t *part = new_partition(env);
384
385                 part->on_worklist = 1;
386                 env->worklist     = part;
387
388                 key.part = part;
389                 set_insert(env->opcode_map, &key, sizeof(key), hash);
390                 entry = &key;
391         }
392         return entry->part;
393 }  /* get_partition_for_irn */
394
395 /**
396  * Return the type of a partition (assuming partition is non-empty and
397  * all elements have the same type).
398  *
399  * @param X  a partition
400  *
401  * @return the type of the first element of the partition
402  */
403 static INLINE lattice_elem_t get_partition_type(const partition_t *X) {
404         const node_t *first = list_entry(X->entries.next, node_t, node_list);
405         return first->type;
406 }  /* get_partition_type */
407
408 /**
409  * Creates a partition node for the given IR-node and place it
410  * into the given partition.
411  *
412  * @param irn   an IR-node
413  * @param part  a partition to place the node in
414  * @param env   the environment
415  *
416  * @return the created node
417  */
418 static node_t *create_partition_node(ir_node *irn, partition_t *part, environment_t *env) {
419         /* create a partition node and place it in the partition */
420         node_t *node = obstack_alloc(&env->obst, sizeof(*node));
421
422         INIT_LIST_HEAD(&node->node_list);
423         node->node         = irn;
424         node->part         = part;
425         node->cprop_next   = NULL;
426         node->next         = NULL;
427         node->next_edge    = NULL;
428         node->type.tv      = tarval_bottom; /* == tarval_U */
429         node->n_inputs     = 0;
430         node->on_touched   = 0;
431         node->on_cprop     = 0;
432         set_irn_node(irn, node);
433
434         list_add_tail(&node->node_list, &part->entries);
435         ++part->n_nodes;
436
437         DB((dbg, LEVEL_3, "Placing %+F in partition %u\n", irn, part->nr));
438
439         return node;
440 }  /* create_partition_node */
441
442 /**
443  * Walker, initialize all Nodes' type to U or top and place
444  * all nodes into the TOP partition.
445  */
446 static void create_initial_partitions(ir_node *irn, void *ctx) {
447         environment_t *env  = ctx;
448         partition_t   *part = env->TOP;
449         node_t        *node;
450
451         node = create_partition_node(irn, part, env);
452         sort_irn_outs(node);
453         if (node->n_inputs > part->n_inputs)
454                 part->n_inputs = node->n_inputs;
455 }  /* create_initial_partitions */
456
457 /**
458  * Add a partition to the touched set if not already there.
459  *
460  * @param part  the partition
461  * @param env   the environment
462  */
463 static INLINE void add_to_touched(partition_t *part, environment_t *env) {
464         if (part->on_touched == 0) {
465                 part->touched_next = env->touched;
466                 env->touched       = part;
467                 part->on_touched   = 1;
468         }
469 }  /* add_to_touched */
470
471 /**
472  * Add a node to the entry.partition.touched set if not already there.
473  *
474  * @param y  a node
475  */
476 static INLINE void add_to_partition_touched(node_t *y) {
477         if (y->on_touched == 0) {
478                 partition_t *part = y->part;
479
480                 y->next       = part->touched;
481                 part->touched = y;
482                 y->on_touched = 1;
483                 ++part->n_touched;
484         }
485 }  /* add_to_partition_touched */
486
487 /**
488  * Update the worklist: If Z is on worklist then add Z' to worklist.
489  * Else add the smaller of Z and Z' to worklist.
490  *
491  * @param Z        the Z partition
492  * @param Z_prime  the Z' partition, a previous part of Z
493  * @param env      the environment
494  */
495 static void update_worklist(partition_t *Z, partition_t *Z_prime, environment_t *env) {
496         if (Z->on_worklist || Z_prime->n_nodes < Z->n_nodes) {
497                 Z_prime->on_worklist = 1;
498                 Z_prime->wl_next     = env->worklist;
499                 env->worklist        = Z_prime;
500         } else {
501                 Z->on_worklist = 1;
502                 Z->wl_next     = env->worklist;
503                 env->worklist  = Z;
504         }
505 }  /* update_worklist */
506
507 /**
508  * Split a partition by a local list.
509  *
510  * @param Z    the Z partition to split
511  * @param g    a (non-empty) node list
512  * @param env  the environment
513  *
514  * @return  a new partition containing the nodes of g
515  */
516 static partition_t *split(partition_t *Z, node_t *g, environment_t *env) {
517         partition_t *Z_prime;
518         node_t      *node;
519         unsigned    n = 0;
520         int         n_inputs;
521
522         dump_partition("Splitting ", Z);
523
524         assert(g != NULL);
525
526         /* Remove g from Z. */
527         for (node = g; node != NULL; node = node->next) {
528                 list_del(&node->node_list);
529                 ++n;
530         }
531         assert(n < Z->n_nodes);
532         Z->n_nodes -= n;
533
534         /* Move g to a new partition, Z\92. */
535         Z_prime = new_partition(env);
536         n_inputs = 0;
537         for (node = g; node != NULL; node = node->next) {
538                 list_add(&node->node_list, &Z_prime->entries);
539                 node->part = Z_prime;
540                 if (node->n_inputs > n_inputs)
541                         n_inputs = node->n_inputs;
542         }
543         Z_prime->n_inputs = n_inputs;
544         Z_prime->n_nodes  = n;
545
546         update_worklist(Z, Z_prime, env);
547
548         dump_partition("Now ", Z);
549         dump_partition("Created new ", Z_prime);
550         return Z_prime;
551 }  /* split */
552
553 /**
554  * Returns non-zero if the i'th input of a Phi node is live.
555  *
556  * @param phi  a Phi-node
557  * @param i    an input number
558  *
559  * @return non-zero if the i'th input of the given Phi node is live
560  */
561 static int is_live_input(ir_node *phi, int i) {
562         if (i >= 0) {
563                 ir_node        *block = get_nodes_block(phi);
564                 ir_node        *pred  = get_Block_cfgpred(block, i);
565                 lattice_elem_t type   = get_node_type(pred);
566
567                 return type.tv != tarval_U;
568         }
569         /* else it's the control input, always live */
570         return 1;
571 }  /* is_live_input */
572
573 /**
574  * Return non-zero if a type is a constant.
575  */
576 static int is_constant_type(lattice_elem_t type) {
577         if (type.tv != tarval_bottom && type.tv != tarval_top)
578                 return 1;
579         return 0;
580 }  /* is_constant_type */
581
582 /**
583  * Place a node on the cprop list.
584  *
585  * @param y    the node
586  * @param env  the environment
587  */
588 static void add_node_to_cprop(node_t *y, environment_t *env) {
589         /* Add y to y.partition.cprop. */
590         if (y->on_cprop == 0) {
591                 partition_t *Y = y->part;
592
593                 y->cprop_next  = Y->cprop;
594                 Y->cprop = y;
595                 y->on_cprop    = 1;
596
597                 DB((dbg, LEVEL_3, "Add %+F to part%u.cprop\n", y->node, Y->nr));
598
599                 /* place its partition on the cprop list */
600                 if (Y->on_cprop == 0) {
601                         Y->cprop_next = env->cprop;
602                         env->cprop    = Y;
603                         Y->on_cprop   = 1;
604                 }
605         }
606 }  /* add_node_to_cprop */
607
608 /**
609  * Split the partitions if caused by the first entry on the worklist.
610  *
611  * @param env  the environment
612  */
613 static void cause_splits(environment_t *env) {
614         partition_t *X, *Y, *Z;
615         node_t      *x, *y, *e;
616         int         i, end_idx;
617         ir_opcode   code;
618         ir_node     *pred;
619
620         /* remove the first partition from the worklist */
621         X = env->worklist;
622         env->worklist  = X->wl_next;
623         X->on_worklist = 0;
624
625         dump_partition("Cause_split: ", X);
626         end_idx = env->end_idx;
627         for (i = -1; i <= X->n_inputs; ++i) {
628                 /* empty the touched set: already done, just clear the list */
629                 env->touched = NULL;
630
631                 list_for_each_entry(node_t, x, &X->entries, node_list) {
632                         if (i == -1) {
633                                 x->next_edge = &x->node->out[1];
634                         }
635
636                         /* ignore the "control input" for non-pinned nodes
637                            if we are running in GCSE mode */
638                         if (i < end_idx && get_irn_pinned(x->node) != op_pin_state_pinned)
639                                 continue;
640
641                         pred = get_irn_n(x->node, i);
642                         y = get_irn_node(pred);
643
644                         if (is_constant_type(y->type)) {
645                                 code = get_irn_opcode(pred);
646                                 if (code == iro_Sub || (code == iro_Proj && is_Cmp(get_Proj_pred(pred))))
647                                         add_node_to_cprop(y, env);
648                         }
649
650                         /* Partitions of constants should not be split simply because their Nodes have unequal
651                            functions or incongruent inputs. */
652                         if (y->type.tv == tarval_bottom &&
653                                 (! is_Phi(x->node) || is_live_input(x->node, i))) {
654                                 Y = y->part;
655                                 add_to_touched(Y, env);
656                                 add_to_partition_touched(y);
657                         }
658                 }
659
660                 for (Z = env->touched; Z != NULL; Z = Z->touched_next) {
661                         /* remove it from the touched set */
662                         Z->on_touched = 0;
663
664                         if (Z->n_nodes != Z->n_touched) {
665                                 split(Z, Z->touched, env);
666                         }
667                         /* Empty local Z.touched. */
668                         for (e = Z->touched; e != NULL; e = e->next) {
669                                 e->on_touched = 0;
670                         }
671                         Z->touched   = NULL;
672                         Z->n_touched = 0;
673                 }
674         }
675 }  /* cause_splits */
676
677 /**
678  * Implements split_by_what(): Split a partition by characteristics given
679  * by the what function.
680  *
681  * @param X     the partition to split
682  * @param What  a function returning an Id for every node of the partition X
683  * @param P     an flexible array to store the result partitions or NULL
684  * @param env   the environment
685  *
686  * @return if P != NULL P will be filled with the resulting partitions and returned
687  */
688 static partition_t **split_by_what(partition_t *X, what_func What,
689                                                                   partition_t **P, environment_t *env) {
690         node_t          *x, *S;
691         listmap_t       map;
692         listmap_entry_t *iter;
693         partition_t     *R;
694
695         /* Let map be an empty mapping from the range of What to (local) list of Nodes. */
696         listmap_init(&map);
697         list_for_each_entry(node_t, x, &X->entries, node_list) {
698                 void            *id = What(x, env);
699                 listmap_entry_t *entry;
700
701                 if (id == NULL) {
702                         /* input not allowed, ignore */
703                         continue;
704                 }
705                 /* Add x to map[What(x)]. */
706                 entry = listmap_find(&map, id);
707                 x->next     = entry->list;
708                 entry->list = x;
709         }
710         /* Let P be a set of Partitions. */
711
712         /* for all sets S except one in the range of map do */
713         for (iter = map.values; iter != NULL; iter = iter->next) {
714                 if (iter->next == NULL) {
715                         /* this is the last entry, ignore */
716                         break;
717                 }
718                 S = iter->list;
719
720                 /* Add SPLIT( X, S ) to P. */
721                 R = split(X, S, env);
722                 if (P != NULL) {
723                         ARR_APP1(partition_t *, P, R);
724                 }
725         }
726         /* Add X to P. */
727         if (P != NULL) {
728                 ARR_APP1(partition_t *, P, X);
729         }
730
731         listmap_term(&map);
732         return P;
733 }  /* split_by_what */
734
735 /** lambda n.(n.type) */
736 static void *lambda_type(const node_t *node, environment_t *env) {
737         (void)env;
738         return node->type.tv;
739 }  /* lambda_type */
740
741 /** lambda n.(n.opcode) */
742 static void *lambda_opcode(const node_t *node, environment_t *env) {
743         opcode_key_t key, *entry;
744
745         key.code = get_irn_opcode(node->node);
746         key.mode = get_irn_mode(node->node);
747         entry = set_insert(env->opcode2id_map, &key, sizeof(&key), opcode_hash(&key));
748         return entry;
749 }  /* lambda_opcode */
750
751 /** lambda n.(n[i].partition) */
752 static void *lambda_partition(const node_t *node, environment_t *env) {
753         ir_node *pred;
754         node_t  *p;
755         int     i = env->lambda_input;
756
757         if (i >= get_irn_arity(node->node)) {
758                 /* we are outside the allowed range */
759                 return NULL;
760         }
761
762         /* ignore the "control input" for non-pinned nodes
763            if we are running in GCSE mode */
764         if (i < env->end_idx && get_irn_pinned(node->node) != op_pin_state_pinned)
765                 return NULL;
766
767         pred = get_irn_n(node->node, i);
768         p    = get_irn_node(pred);
769
770         return p->part;
771 }  /* lambda_partition */
772
773 /**
774  * Implements split_by().
775  *
776  * @param X    the partition to split
777  * @param env  the environment
778  */
779 static void split_by(partition_t *X, environment_t *env) {
780         partition_t **P = NEW_ARR_F(partition_t *, 0);
781         int         i, j, k;
782
783         P = split_by_what(X, lambda_type, P, env);
784         for (i = ARR_LEN(P) - 1; i >= 0; --i) {
785                 partition_t *Y = P[i];
786
787                 /* we do not want split the TOP or constant partitions */
788                 if (get_partition_type(Y).tv == tarval_bottom) {
789                         partition_t **Q = NEW_ARR_F(partition_t *, 0);
790
791                         Q = split_by_what(Y, lambda_opcode, Q, env);
792
793                         for (j = ARR_LEN(Q) - 1; j >= 0; --j) {
794                                 partition_t *Z = Q[j];
795
796                                 for (k = Z->n_inputs - 1; k >= -1; --k) {
797                                         env->lambda_input = k;
798                                         split_by_what(Z, lambda_partition, NULL, env);
799                                 }
800                         }
801                         DEL_ARR_F(Q);
802                 }
803         }
804         DEL_ARR_F(P);
805 }  /* split_by */
806
807 /**
808  * (Re-)compute the type for a given node.
809  *
810  * @param node  the node
811  */
812 static void default_compute(node_t *node) {
813         int     i;
814         ir_node *irn = node->node;
815
816         if (get_irn_pinned(irn) == op_pin_state_pinned) {
817                 node_t *block = get_irn_node(get_nodes_block(irn));
818
819                 if (block->type.tv == tarval_U) {
820                         node->type.tv = tarval_top;
821                         return;
822                 }
823         }
824
825         /* if any of the data inputs have type top, the result is type top */
826         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
827                 ir_node *pred = get_irn_n(irn, i);
828                 node_t  *p    = get_irn_node(pred);
829
830                 if (p->type.tv == tarval_top) {
831                         node->type.tv = tarval_top;
832                         return;
833                 }
834         }
835
836         node->type.tv = computed_value(irn);
837 }  /* default_compute */
838
839 /**
840  * (Re-)compute the type for a Block node.
841  *
842  * @param node  the node
843  */
844 static void compute_Block(node_t *node) {
845         int     i;
846         ir_node *block = node->node;
847
848         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
849                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
850
851                 if (pred->type.tv == tarval_R) {
852                         /* A block is reachable, if at least of predecessor is reachable. */
853                         node->type.tv = tarval_R;
854                         return;
855                 }
856         }
857         node->type.tv = tarval_U;
858 }  /* compute_Block */
859
860 /**
861  * (Re-)compute the type for a Jmp node.
862  *
863  * @param node  the node
864  */
865 static void compute_Jmp(node_t *node) {
866         node_t *block = get_irn_node(get_nodes_block(node->node));
867
868         node->type = block->type;
869 }  /* compute_Jmp */
870
871 /**
872  * (Re-)compute the type for the End node.
873  *
874  * @param node  the node
875  */
876 static void compute_End(node_t *node) {
877         /* the End node is NOT dead of course */
878         node->type.tv = tarval_R;
879 }
880
881 /**
882  * (Re-)compute the type for a SymConst node.
883  *
884  * @param node  the node
885  */
886 static void compute_SymConst(node_t *node) {
887         ir_node *irn = node->node;
888         node_t  *block = get_irn_node(get_nodes_block(irn));
889
890         if (block->type.tv == tarval_U) {
891                 node->type.tv = tarval_top;
892                 return;
893         }
894         switch (get_SymConst_kind(irn)) {
895         case symconst_addr_ent:
896         case symconst_addr_name:
897                 node->type.sym = get_SymConst_symbol(irn);
898                 break;
899         default:
900                 node->type.tv = computed_value(irn);
901         }
902 }  /* compute_SymConst */
903
904 /**
905  * (Re-)compute the type for a Phi node.
906  *
907  * @param node  the node
908  */
909 static void compute_Phi(node_t *node) {
910         int            i;
911         ir_node        *phi = node->node;
912         lattice_elem_t type;
913
914         /* if a Phi is in a unreachable block, its type is TOP */
915         node_t *block = get_irn_node(get_nodes_block(phi));
916
917         if (block->type.tv == tarval_U) {
918                 node->type.tv = tarval_top;
919                 return;
920         }
921
922         /* Phi implements the Meet operation */
923         type.tv = tarval_top;
924         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
925                 node_t *pred = get_irn_node(get_Phi_pred(phi, i));
926
927                 if (pred->type.tv == tarval_top) {
928                         /* ignore TOP inputs */
929                         continue;
930                 }
931                 if (pred->type.tv == tarval_bottom) {
932                         node->type.tv = tarval_bottom;
933                         return;
934                 } else if (type.tv == tarval_top) {
935                         /* first constant found */
936                         type = pred->type;
937                 } else if (type.tv != pred->type.tv) {
938                         /* different constants or tarval_bottom */
939                         node->type.tv = tarval_bottom;
940                         return;
941                 }
942                 /* else nothing, constants are the same */
943         }
944         node->type = type;
945 }  /* compute_Phi */
946
947 /**
948  * (Re-)compute the type for an Add. Special case: one nodes is a Zero Const.
949  *
950  * @param node  the node
951  */
952 static void compute_Add(node_t *node) {
953         ir_node        *sub = node->node;
954         node_t         *l   = get_irn_node(get_Add_left(sub));
955         node_t         *r   = get_irn_node(get_Add_right(sub));
956         lattice_elem_t a    = l->type;
957         lattice_elem_t b    = r->type;
958         node_t         *block = get_irn_node(get_nodes_block(sub));
959         ir_mode        *mode;
960
961         if (block->type.tv == tarval_U) {
962                 node->type.tv = tarval_top;
963                 return;
964         }
965
966         if (a.tv == tarval_top || b.tv == tarval_top) {
967                 node->type.tv = tarval_top;
968         } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
969                 node->type.tv = tarval_bottom;
970         } else {
971                 /* x + 0 = 0 + x = x, but beware of floating point +0 + -0, so we
972                    must call tarval_add() first to handle this case! */
973                 if (is_tarval(a.tv)) {
974                         if (is_tarval(b.tv)) {
975                                 node->type.tv = tarval_add(a.tv, b.tv);
976                                 return;
977                         }
978                         mode = get_tarval_mode(a.tv);
979                         if (a.tv == get_mode_null(mode)) {
980                                 node->type = b;
981                                 return;
982                         }
983                 } else if (is_tarval(b.tv)) {
984                         mode = get_tarval_mode(b.tv);
985                         if (b.tv == get_mode_null(mode)) {
986                                 node->type = a;
987                                 return;
988                         }
989                 }
990                 node->type.tv = tarval_bottom;
991         }
992 }  /* compute_Add */
993
994 /**
995  * (Re-)compute the type for a Sub. Special case: both nodes are congruent.
996  *
997  * @param node  the node
998  */
999 static void compute_Sub(node_t *node) {
1000         ir_node        *sub = node->node;
1001         node_t         *l   = get_irn_node(get_Sub_left(sub));
1002         node_t         *r   = get_irn_node(get_Sub_right(sub));
1003         lattice_elem_t a    = l->type;
1004         lattice_elem_t b    = r->type;
1005         node_t         *block = get_irn_node(get_nodes_block(sub));
1006
1007         if (block->type.tv == tarval_U) {
1008                 node->type.tv = tarval_top;
1009                 return;
1010         }
1011
1012         if (a.tv == tarval_top || b.tv == tarval_top) {
1013                 node->type.tv = tarval_top;
1014         } else if (r->part == l->part) {
1015                 ir_mode *mode = get_irn_mode(sub);
1016                 node->type.tv = get_mode_null(mode);
1017         } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
1018                 node->type.tv = tarval_bottom;
1019         } else {
1020                 if (is_tarval(a.tv) && is_tarval(b.tv))
1021                         node->type.tv = tarval_sub(a.tv, b.tv);
1022                 else
1023                         node->type.tv = tarval_bottom;
1024         }
1025 }  /* compute_Sub */
1026
1027 /**
1028  * (Re-)compute the type for a Proj(Cmp).
1029  *
1030  * @param node  the node
1031  * @param cond  the predecessor Cmp node
1032  */
1033 static void compute_Proj_Cmp(node_t *node, ir_node *cmp) {
1034         ir_node        *proj = node->node;
1035         node_t         *l    = get_irn_node(get_Cmp_left(cmp));
1036         node_t         *r    = get_irn_node(get_Cmp_right(cmp));
1037         lattice_elem_t a     = l->type;
1038         lattice_elem_t b     = r->type;
1039         pn_Cmp         pnc   = get_Proj_proj(proj);
1040
1041         /*
1042          * BEWARE: a == a is NOT always True for floating Point values, as
1043          * NaN != NaN is defined, so we must check this here.
1044          */
1045         if (!mode_is_float(get_irn_mode(l->node)) || pnc == pn_Cmp_Lt ||  pnc == pn_Cmp_Gt) {
1046                 if (a.tv == tarval_top || b.tv == tarval_top) {
1047                         node->type.tv = tarval_top;
1048                 } else if (r->part == l->part) {
1049                         node->type.tv = new_tarval_from_long(pnc & pn_Cmp_Eq, mode_b);
1050                 } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
1051                         node->type.tv = tarval_bottom;
1052                 } else {
1053                         default_compute(node);
1054                 }
1055         } else {
1056                 default_compute(node);
1057         }
1058 }  /* compute_Proj_Cmp */
1059
1060 /**
1061  * (Re-)compute the type for a Proj(Cond).
1062  *
1063  * @param node  the node
1064  * @param cond  the predecessor Cond node
1065  */
1066 static void compute_Proj_Cond(node_t *node, ir_node *cond) {
1067         ir_node *proj     = node->node;
1068         long    pnc       = get_Proj_proj(proj);
1069         ir_node *sel      = get_Cond_selector(cond);
1070         node_t  *selector = get_irn_node(sel);
1071
1072         if (get_irn_mode(sel) == mode_b) {
1073                 /* an IF */
1074                 if (pnc == pn_Cond_true) {
1075                         if (selector->type.tv == tarval_b_false) {
1076                                 node->type.tv = tarval_U;
1077                         } else if (selector->type.tv == tarval_b_true) {
1078                                 node->type.tv = tarval_R;
1079                         } else if (selector->type.tv == tarval_bottom) {
1080                                 node->type.tv = tarval_R;
1081                         } else {
1082                                 assert(selector->type.tv == tarval_top);
1083                                 node->type.tv = tarval_U;
1084                         }
1085                 } else {
1086                         assert(pnc == pn_Cond_false);
1087
1088                         if (selector->type.tv == tarval_b_false) {
1089                                 node->type.tv = tarval_R;
1090                         } else if (selector->type.tv == tarval_b_true) {
1091                                 node->type.tv = tarval_U;
1092                         } else if (selector->type.tv == tarval_bottom) {
1093                                 node->type.tv = tarval_R;
1094                         } else {
1095                                 assert(selector->type.tv == tarval_top);
1096                                 node->type.tv = tarval_U;
1097                         }
1098                 }
1099         } else {
1100                 /* an SWITCH */
1101                 if (selector->type.tv == tarval_bottom) {
1102                         node->type.tv = tarval_R;
1103                 } else if (selector->type.tv == tarval_top) {
1104                         node->type.tv = tarval_U;
1105                 } else {
1106                         long value = get_tarval_long(selector->type.tv);
1107                         if (pnc == get_Cond_defaultProj(cond)) {
1108                                 /* default switch, have to check ALL other cases */
1109                                 int i;
1110
1111                                 for (i = get_irn_n_outs(cond) - 1; i >= 0; --i) {
1112                                         ir_node *succ = get_irn_out(cond, i);
1113
1114                                         if (succ == proj)
1115                                                 continue;
1116                                         if (value == get_Proj_proj(succ)) {
1117                                                 /* we found a match, will NOT take the default case */
1118                                                 node->type.tv = tarval_U;
1119                                                 return;
1120                                         }
1121                                 }
1122                                 /* all cases checked, no match, will take default case */
1123                                 node->type.tv = tarval_R;
1124                         } else {
1125                                 /* normal case */
1126                                 node->type.tv = value == pnc ? tarval_R : tarval_U;
1127                         }
1128                 }
1129         }
1130 }  /* compute_Proj_Cond */
1131
1132 /**
1133  * (Re-)compute the type for a Proj-Nodes.
1134  *
1135  * @param node  the node
1136  */
1137 static void compute_Proj(node_t *node) {
1138         ir_node *proj = node->node;
1139         ir_mode *mode = get_irn_mode(proj);
1140         ir_node *pred;
1141
1142         if (mode == mode_M) {
1143                 /* mode M is always bottom */
1144                 node->type.tv = tarval_bottom;
1145                 return;
1146         }
1147         if (mode != mode_X) {
1148                 ir_node *cmp = get_Proj_pred(proj);
1149                 if (is_Cmp(cmp))
1150                         compute_Proj_Cmp(node, cmp);
1151                 else
1152                         default_compute(node);
1153                 return;
1154         }
1155         /* handle mode_X nodes */
1156         pred = get_Proj_pred(proj);
1157
1158         switch (get_irn_opcode(pred)) {
1159         case iro_Start:
1160                 /* the Proj_X from the Start is always reachable */
1161                 node->type.tv = tarval_R;
1162                 break;
1163         case iro_Cond:
1164                 compute_Proj_Cond(node, pred);
1165                 break;
1166         default:
1167                 default_compute(node);
1168         }
1169 }  /* compute_Proj */
1170
1171 /**
1172  * (Re-)compute the type for a given node.
1173  *
1174  * @param node  the node
1175  */
1176 static void compute(node_t *node) {
1177         compute_func func = (compute_func)node->node->op->ops.generic;
1178
1179         if (func != NULL)
1180                 func(node);
1181 }  /* compute */
1182
1183 /**
1184  * Propagate constant evaluation.
1185  *
1186  * @param env  the environment
1187  */
1188 static void propagate(environment_t *env) {
1189         partition_t    *X, *Y;
1190         node_t         *x;
1191         lattice_elem_t old_type;
1192         node_t         *fallen = NULL;
1193         unsigned       n_fallen = 0;
1194         int            i;
1195
1196         while (env->cprop != NULL) {
1197                 /* remove the first partition X from cprop but do not set the bit here */
1198                 X          = env->cprop;
1199                 env->cprop = X->cprop_next;
1200
1201                 dump_partition("Propagate", X);
1202                 do {
1203                         /* remove the first Node x from X.cprop but do NOT set the bit here */
1204                         x        = X->cprop;
1205                         X->cprop = x->cprop_next;
1206
1207                         /* compute a new type for x */
1208                         old_type = x->type;
1209                         DB((dbg, LEVEL_3, "computing type of %+F\n", x->node));
1210                         compute(x);
1211                         if (x->type.tv != old_type.tv) {
1212                                 DB((dbg, LEVEL_2, "node %+F has changed type from %+F to %+F\n", x->node, old_type, x->type));
1213                                 /* Add x to fallen. */
1214                                 x->next = fallen;
1215                                 fallen  = x;
1216                                 ++n_fallen;
1217
1218                                 for (i = get_irn_n_outs(x->node) - 1; i >= 0; --i) {
1219                                         ir_node *succ = get_irn_out(x->node, i);
1220                                         node_t  *y    = get_irn_node(succ);
1221
1222                                         /* Add y to y.partition.cprop. */
1223                                         add_node_to_cprop(y, env);
1224                                 }
1225                         }
1226                         /* now remove x from X.cprop: this ensures that a node is not placed on the list again
1227                            if is its user by itself (happens for Phi nodes and dead code) */
1228                         x->on_cprop = 0;
1229                 } while (X->cprop != NULL);
1230
1231                 /* now remove X from cprop, we have emptied it's local list */
1232                 X->on_cprop = 0;
1233
1234                 if (n_fallen != X->n_nodes) {
1235                         assert(n_fallen > 0);
1236                         Y = split(X, fallen, env);
1237                 } else {
1238                         Y = X;
1239                 }
1240                 split_by(Y, env);
1241         }
1242 }  /* propagate */
1243
1244 /**
1245  * Get the leader for a given node from its congruence class.
1246  *
1247  * @param irn  the node
1248  */
1249 static ir_node *get_leader(ir_node *irn) {
1250         partition_t *part = get_irn_node(irn)->part;
1251
1252         if (part->n_nodes > 1) {
1253                 DB((dbg, LEVEL_2, "Found congruence class for %+F ", irn));
1254                 dump_partition("", part);
1255         }
1256         return irn;
1257 }
1258
1259 /**
1260  * Post-Walker, apply the analysis results;
1261  */
1262 static void apply_result(ir_node *irn, void *ctx) {
1263         environment_t *env = ctx;
1264
1265         if (is_no_Block(irn)) {
1266                 ir_node *leader = get_leader(irn);
1267
1268                 if (leader != irn) {
1269                         exchange(irn, leader);
1270                 }
1271         }
1272 }  /* static void apply_result(ir_node *irn, void *ctx) {
1273  */
1274
1275 #define SET(code) op_##code->ops.generic = (op_func)compute_##code
1276
1277 /**
1278  * sets the generic functions to compute.
1279  */
1280 static void set_compute_functions(void) {
1281         int i;
1282
1283         /* set the default compute function */
1284         for (i = get_irp_n_opcodes() - 1; i >= 0; --i) {
1285                 ir_op *op = get_irp_opcode(i);
1286                 op->ops.generic = (op_func)default_compute;
1287         }
1288
1289         /* set specific functions */
1290         SET(Block);
1291         SET(Jmp);
1292         SET(Phi);
1293         SET(Add);
1294         SET(Sub);
1295         SET(SymConst);
1296         SET(Proj);
1297         SET(End);
1298 }  /* set_compute_functions */
1299
1300 static int dump_partition_hook(FILE *F, ir_node *n, ir_node *local) {
1301         ir_node *irn = local != NULL ? local : n;
1302         node_t *node = get_irn_node(n);
1303
1304         ir_fprintf(F, "info2 : \"partition %u type %+F\"\n", node->part->nr, node->type);
1305         return 1;
1306 }
1307
1308 void combo(ir_graph *irg) {
1309         environment_t env;
1310         ir_node       *initial_X;
1311         node_t        *start;
1312         ir_graph      *rem = current_ir_graph;
1313
1314         current_ir_graph = irg;
1315
1316         /* register a debug mask */
1317         FIRM_DBG_REGISTER(dbg, "firm.opt.combo");
1318         firm_dbg_set_mask(dbg, SET_LEVEL_3);
1319
1320         DB((dbg, LEVEL_1, "Doing COMBO for %+F\n", irg));
1321
1322         obstack_init(&env.obst);
1323         env.worklist       = NULL;
1324         env.cprop          = NULL;
1325         env.touched        = NULL;
1326         env.TOP            = NULL;
1327 #ifdef DEBUG_libfirm
1328         env.dbg_list       = NULL;
1329 #endif
1330         env.opcode_map     = new_set(cmp_opcode, iro_Last * 4);
1331         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
1332         env.type2id_map    = pmap_create();
1333         env.end_idx        = get_opt_global_cse() ? 0 : -1;
1334         env.lambda_input   = 0;
1335
1336         assure_irg_outs(irg);
1337
1338         /* we have our own value_of function */
1339         set_value_of_func(get_node_tarval);
1340
1341         set_compute_functions();
1342
1343         /* create the initial partition and place it on the work list */
1344         env.TOP = new_partition(&env);
1345         env.TOP->wl_next = env.worklist;
1346         env.worklist     = env.TOP;
1347         irg_walk_graph(irg, NULL, create_initial_partitions, &env);
1348
1349         /* Place the START Node's partition on cprop.
1350            Place the START Node on its local worklist. */
1351         initial_X = get_irg_initial_exec(irg);
1352         start     = get_irn_node(initial_X);
1353         add_node_to_cprop(start, &env);
1354
1355         do {
1356                 propagate(&env);
1357                 dump_all_partitions(&env);
1358                 if (env.worklist != NULL)
1359                         cause_splits(&env);
1360         } while (env.cprop != NULL || env.worklist != NULL);
1361
1362         dump_all_partitions(&env);
1363
1364         set_dump_node_vcgattr_hook(dump_partition_hook);
1365         dump_ir_block_graph(irg, "-partition");
1366
1367
1368         /* apply the result */
1369         irg_walk_graph(irg, NULL, apply_result, &env);
1370
1371         pmap_destroy(env.type2id_map);
1372         del_set(env.opcode_map);
1373         del_set(env.opcode2id_map);
1374         obstack_free(&env.obst, NULL);
1375
1376         /* restore value_of() default behavior */
1377         set_value_of_func(NULL);
1378         current_ir_graph = rem;
1379 }  /* combo */