Some more cleanup: Put the return type and other specifiers on the same line as the...
[libfirm] / ir / opt / opt_blocks.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   Combining congruent blocks
23  * @author  Michael Beck
24  * @version $Id$
25  *
26  * This phase find congruent blocks.
27  * Two block are congruent, if they contains only equal calculations.
28  */
29 #include "config.h"
30 #include "ircons.h"
31 #include "iroptimize.h"
32 #include "irgmod.h"
33 #include "irgraph_t.h"
34 #include "irnode_t.h"
35 #include "iropt_t.h"
36 #include "array_t.h"
37 #include "trouts.h"
38 #include "irgwalk.h"
39 #include "set.h"
40 #include "irpass.h"
41 #include "debug.h"
42
43 /* define this for general block shaping: congruent blocks
44    are found not only before the end block but anywhere in the graph */
45 #define GENERAL_SHAPE
46
47 typedef struct partition_t     partition_t;
48 typedef struct block_t         block_t;
49 typedef struct node_t          node_t;
50 typedef struct pair_t          pair_t;
51 typedef struct phi_t           phi_t;
52 typedef struct opcode_key_t    opcode_key_t;
53 typedef struct listmap_entry_t listmap_entry_t;
54 typedef struct environment_t   environment_t;
55 typedef struct pred_t          pred_t;
56
57 /** An opcode map key. */
58 struct opcode_key_t {
59         ir_opcode   code;   /**< The Firm opcode. */
60         ir_mode     *mode;  /**< The mode of all nodes in the partition. */
61         int         arity;  /**< The arity of this opcode (needed for Phi etc. */
62         union {
63                 long            proj;   /**< For Proj nodes, its proj number */
64                 ir_entity       *ent;   /**< For Sel nodes, its entity */
65                 tarval          *tv;    /**< For Const nodes, its tarval */
66                 symconst_symbol sym;    /**< For SymConst nodes, its symbol .*/
67                 void            *addr;  /**< Alias all addresses. */
68                 int             intVal; /**< For Conv/Div nodes: strict/remainderless. */
69         } u;
70 };
71
72 /** A partition contains all congruent blocks. */
73 struct partition_t {
74         list_head part_list;     /**< Double linked list of partitions. */
75         list_head blocks;        /**< List of blocks in this partition. */
76         unsigned  n_blocks;      /**< Number of block in this partition. */
77         ir_node   *meet_block;   /**< The control flow meet block of this partition. */
78 #ifdef DEBUG_libfirm
79         unsigned  nr;            /**< For debugging: number of this partition. */
80 #endif
81 };
82
83 /** A block. */
84 struct block_t {
85         list_head  block_list;   /**< Double linked list of block inside a partition. */
86         list_head  nodes;        /**< Wait-queue of nodes that must be checked for congruence. */
87         block_t    *next;        /**< Next block of a split list. */
88         ir_node    *block;       /**< Pointer to the associated IR-node block. */
89         ir_node    **roots;      /**< An array of all root nodes. */
90         node_t     *cf_root;     /**< The control flow root node of this block. */
91         pair_t     *input_pairs; /**< The list of inputs to this block. */
92         phi_t      *phis;        /**< The list of Phis in this block. */
93         block_t    *all_next;    /**< Links all created blocks. */
94         int        meet_input;   /**< Input number of this block in the meet-block. */
95 };
96
97 /** A node. */
98 struct node_t {
99         list_head  node_list;    /**< Double linked list of block inside a partition. */
100         ir_node    *node;        /**< Pointer to the associated IR-node or NULL for block inputs. */
101         char       is_input;     /**< Set if this node is an input from other block. */
102 };
103
104 /** The environment. */
105 struct environment_t {
106         list_head       partitions;     /**< list of partitions. */
107         list_head       ready;          /**< list of ready partitions. */
108         set             *opcode2id_map; /**< The opcodeMode->id map. */
109         ir_node         **live_outs;    /**< Live out only nodes. */
110         block_t         *all_blocks;    /**< List of all created blocks. */
111         struct obstack  obst;           /** obstack for temporary data */
112 };
113
114 /** A (node, input index) pair. */
115 struct pair_t {
116         pair_t  *next;    /**< Points to the next pair entry. */
117         ir_node *irn;     /**< The IR-node. */
118         int     index;    /**< An input index. */
119         ir_node **ins;    /**< A new in array once allocated. */
120 };
121
122 /** A Phi, inputs pair. */
123 struct phi_t {
124         phi_t   *next;    /**< Points to the next Phi pair entry. */
125         ir_node *phi;     /**< The Phi node. */
126         ir_node **ins;    /**< A new in array once allocated. */
127 };
128
129 /** Describes a predecessor input. */
130 struct pred_t {
131         ir_node *pred;  /**< The predecessor. */
132         int     index;  /**< Its input index. */
133 };
134
135 /**
136  * An entry in the list_map.
137  */
138 struct listmap_entry_t {
139         void            *id;    /**< The id. */
140         block_t         *list;  /**< The associated list for this id. */
141         listmap_entry_t *next;  /**< Link to the next entry in the map. */
142 };
143
144 /** We must map id's to lists. */
145 typedef struct listmap_t {
146         set             *map;    /**< Map id's to listmap_entry_t's */
147         listmap_entry_t *values; /**< List of all values in the map. */
148 } listmap_t;
149
150 #define get_Block_entry(block)  ((block_t *)get_irn_link(block))
151
152 /** The debug module handle. */
153 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
154
155 /** Next partition number. */
156 DEBUG_ONLY(static unsigned part_nr = 0);
157
158 #ifdef DEBUG_libfirm
159 /**
160  * Dump partition to output.
161  */
162 static void dump_partition(const char *msg, const partition_t *part)
163 {
164         const block_t *block;
165         int           first = 1;
166
167         DB((dbg, LEVEL_2, " %s part%u (%u blocks) {\n  ", msg, part->nr, part->n_blocks));
168         list_for_each_entry(block_t, block, &part->blocks, block_list) {
169                 DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", block->block));
170                 first = 0;
171         }
172         DB((dbg, LEVEL_2, "\n }\n"));
173 }  /* dump_partition */
174
175 /**
176  * Dumps a list.
177  */
178 static void dump_list(const char *msg, const block_t *block)
179 {
180         const block_t *p;
181         int           first = 1;
182
183         DB((dbg, LEVEL_3, "  %s = {\n   ", msg));
184         for (p = block; p != NULL; p = p->next) {
185                 DB((dbg, LEVEL_3, "%s%+F", first ? "" : ", ", p->block));
186                 first = 0;
187         }
188         DB((dbg, LEVEL_3, "\n  }\n"));
189 }  /* do_dump_list */
190 #else
191 #define dump_partition(msg, part)
192 #define dump_list(msg, block)
193 #endif
194
195 /**
196  * Compare two pointer values of a listmap.
197  */
198 static int listmap_cmp_ptr(const void *elt, const void *key, size_t size)
199 {
200         const listmap_entry_t *e1 = elt;
201         const listmap_entry_t *e2 = key;
202
203         (void) size;
204         return e1->id != e2->id;
205 }  /* listmap_cmp_ptr */
206
207 /**
208  * Initializes a listmap.
209  *
210  * @param map  the listmap
211  */
212 static void listmap_init(listmap_t *map)
213 {
214         map->map    = new_set(listmap_cmp_ptr, 16);
215         map->values = NULL;
216 }  /* listmap_init */
217
218 /**
219  * Terminates a listmap.
220  *
221  * @param map  the listmap
222  */
223 static void listmap_term(listmap_t *map)
224 {
225         del_set(map->map);
226 }  /* listmap_term */
227
228 /**
229  * Return the associated listmap entry for a given id.
230  *
231  * @param map  the listmap
232  * @param id   the id to search for
233  *
234  * @return the associated listmap entry for the given id
235  */
236 static listmap_entry_t *listmap_find(listmap_t *map, void *id)
237 {
238         listmap_entry_t key, *entry;
239
240         key.id   = id;
241         key.list = NULL;
242         key.next = NULL;
243         entry = set_insert(map->map, &key, sizeof(key), HASH_PTR(id));
244
245         if (entry->list == NULL) {
246                 /* a new entry, put into the list */
247                 entry->next = map->values;
248                 map->values = entry;
249         }
250         return entry;
251 }  /* listmap_find */
252
253 /**
254  * Calculate the hash value for an opcode map entry.
255  *
256  * @param entry  an opcode map entry
257  *
258  * @return a hash value for the given opcode map entry
259  */
260 static unsigned opcode_hash(const opcode_key_t *entry)
261 {
262         /* assume long >= int */
263         return (entry->mode - (ir_mode *)0) * 9 + entry->code + entry->u.proj * 3 + HASH_PTR(entry->u.addr) + entry->arity;
264 }  /* opcode_hash */
265
266 /**
267  * Compare two entries in the opcode map.
268  */
269 static int cmp_opcode(const void *elt, const void *key, size_t size)
270 {
271         const opcode_key_t *o1 = elt;
272         const opcode_key_t *o2 = key;
273
274         (void) size;
275         return o1->code != o2->code || o1->mode != o2->mode ||
276                o1->arity != o2->arity ||
277                o1->u.proj != o2->u.proj || o1->u.addr != o2->u.addr;
278 }  /* cmp_opcode */
279
280 /**
281  * Creates a new empty partition and put in on the
282  * partitions list.
283  *
284  * @param meet_block  the control flow meet block of this partition
285  * @param env         the environment
286  */
287 static partition_t *create_partition(ir_node *meet_block, environment_t *env)
288 {
289         partition_t *part = OALLOC(&env->obst, partition_t);
290
291         INIT_LIST_HEAD(&part->blocks);
292         part->meet_block = meet_block;
293         part->n_blocks   = 0;
294         DEBUG_ONLY(part->nr = part_nr++);
295         list_add_tail(&part->part_list, &env->partitions);
296         return part;
297 }  /* create_partition */
298
299 /**
300  * Allocate a new block in the given partition.
301  *
302  * @param block      the IR-node
303  * @param meet_input Input number of this block in the meet-block
304  * @param partition  the partition to add to
305  * @param env        the environment
306  */
307 static block_t *create_block(ir_node *block, int meet_input, partition_t *partition, environment_t *env)
308 {
309         block_t *bl = OALLOC(&env->obst, block_t);
310
311         set_irn_link(block, bl);
312
313         INIT_LIST_HEAD(&bl->nodes);
314         bl->next        = NULL;
315         bl->block       = block;
316         bl->roots       = NEW_ARR_F(ir_node *, 0);
317         bl->cf_root     = NULL;
318         bl->input_pairs = NULL;
319         bl->phis        = NULL;
320         bl->meet_input  = meet_input;
321
322         /* put it into the list of partition blocks */
323         list_add_tail(&bl->block_list, &partition->blocks);
324         ++partition->n_blocks;
325
326         /* put in into the list of all blocks */
327         bl->all_next    = env->all_blocks;
328         env->all_blocks = bl;
329
330         return bl;
331 }  /* create_block */
332
333 /**
334  * Allocate a new node and add it to a blocks wait queue.
335  *
336  * @param irn    the IR-node
337  * @param block  the block to add to
338  * @param env    the environment
339  */
340 static node_t *create_node(ir_node *irn, block_t *block, environment_t *env)
341 {
342         node_t *node = OALLOC(&env->obst, node_t);
343
344         node->node     = irn;
345         node->is_input = 0;
346
347         list_add_tail(&node->node_list, &block->nodes);
348
349         return node;
350 }  /* create_node */
351
352 /**
353  * Add an input pair to a block.
354  *
355  * @param block  the block
356  * @param irn    the IR-node that has an block input
357  * @param idx    the index of the block input in node's predecessors
358  * @param env    the environment
359  */
360 static void add_pair(block_t *block, ir_node *irn, int idx, environment_t *env)
361 {
362         pair_t *pair = OALLOC(&env->obst, pair_t);
363
364         pair->next  = block->input_pairs;
365         pair->irn   = irn;
366         pair->index = idx;
367         pair->ins   = NULL;
368
369         block->input_pairs = pair;
370 }  /* add_pair */
371
372 /**
373  * Add a Phi to a block.
374  *
375  * @param block  the block
376  * @param phi    the Phi node
377  * @param env    the environment
378  */
379 static void add_phi(block_t *block, ir_node *phi, environment_t *env)
380 {
381         phi_t *node = OALLOC(&env->obst, phi_t);
382
383         node->next = block->phis;
384         node->phi  = phi;
385         node->ins  = NULL;
386
387         block->phis = node;
388 }  /** add_phi */
389
390 /**
391  * Creates an opcode from a node.
392  */
393 static opcode_key_t *opcode(const node_t *node, environment_t *env)
394 {
395         opcode_key_t key, *entry;
396         ir_node      *irn = node->node;
397
398         if (node->is_input) {
399                 /* Node: as Block nodes are never propagated, it is safe to
400                    use its code for "input" node */
401                 key.code   = iro_Block;
402                 key.arity  = 0;
403         } else {
404                 key.code   = get_irn_opcode(irn);
405                 key.arity  = get_irn_arity(irn);
406         }
407         key.mode   = get_irn_mode(node->node);
408         key.u.proj = 0;
409         key.u.addr = NULL;
410
411         switch (key.code) {
412         case iro_Proj:
413                 key.u.proj = get_Proj_proj(irn);
414                 break;
415         case iro_Sel:
416                 key.u.ent = get_Sel_entity(irn);
417                 break;
418         case iro_SymConst:
419                 key.u.sym = get_SymConst_symbol(irn);
420                 break;
421         case iro_Const:
422                 key.u.tv  = get_Const_tarval(irn);
423                 break;
424         case iro_Conv:
425                 key.u.intVal = get_Conv_strict(irn);
426                 break;
427         case iro_Load:
428                 key.mode = get_Load_mode(irn);
429                 break;
430         case iro_Div:
431                 key.u.intVal = get_Div_no_remainder(irn);
432                 break;
433         case iro_Builtin:
434                 key.u.intVal = get_Builtin_kind(irn);
435                 break;
436         default:
437                 break;
438         }
439
440         entry = set_insert(env->opcode2id_map, &key, sizeof(key), opcode_hash(&key));
441         return entry;
442 }  /* opcode */
443
444 /**
445  * Split a partition by a local list.
446  *
447  * @param Z    partition to split
448  * @param g    a (non-empty) block list
449  * @param env  the environment
450  *
451  * @return  a new partition containing the nodes of g
452  */
453 static partition_t *split(partition_t *Z, block_t *g, environment_t *env)
454 {
455         partition_t *Z_prime;
456         block_t     *block;
457         unsigned    n = 0;
458
459         dump_partition("Splitting ", Z);
460         dump_list("by list ", g);
461
462         assert(g != NULL);
463
464         /* Remove g from Z. */
465         for (block = g; block != NULL; block = block->next) {
466                 list_del(&block->block_list);
467                 ++n;
468         }
469         assert(n < Z->n_blocks);
470         Z->n_blocks -= n;
471
472         /* Move g to a new partition, Z'. */
473         Z_prime = create_partition(Z->meet_block, env);
474         for (block = g; block != NULL; block = block->next) {
475                 list_add_tail(&block->block_list, &Z_prime->blocks);
476         }
477         Z_prime->n_blocks = n;
478
479         dump_partition("Now ", Z);
480         dump_partition("Created new ", Z_prime);
481         return Z_prime;
482 }  /* split */
483
484 /**
485  * Return non-zero if pred should be tread as a input node.
486  */
487 static int is_input_node(ir_node *pred, ir_node *irn, int index)
488 {
489         /* for now, do NOT turn direct calls into indirect one */
490         if (index != 1)
491                 return 1;
492         if (! is_SymConst_addr_ent(pred))
493                 return 1;
494         if (! is_Call(irn))
495                 return 1;
496         return 0;
497 }  /* is_input_node */
498
499 /**
500  * Propagate nodes on all wait queues of the given partition.
501  *
502  * @param part  the partition
503  * @param env   the environment
504  */
505 static void propagate_blocks(partition_t *part, environment_t *env)
506 {
507         block_t         *ready_blocks = NULL;
508         unsigned        n_ready       = 0;
509         block_t         *bl, *next;
510         listmap_t       map;
511         listmap_entry_t *iter;
512
513         DB((dbg, LEVEL_2, " Propagate blocks on part%u\n", part->nr));
514
515         /* Let map be an empty mapping from the range of Opcodes to (local) list of blocks. */
516         listmap_init(&map);
517         list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
518                 opcode_key_t    *id;
519                 listmap_entry_t *entry;
520                 node_t          *node;
521
522                 if (list_empty(&bl->nodes)) {
523                         bl->next     = ready_blocks;
524                         ready_blocks = bl;
525                         ++n_ready;
526                         DB((dbg, LEVEL_2, " Block %+F completely processed\n", bl->block));
527                         continue;
528                 }
529
530                 /* get the first node from the wait queue */
531                 node = list_entry(bl->nodes.next, node_t, node_list);
532                 list_del(&node->node_list);
533
534                 /* put all not-visited predecessors to the wait queue */
535                 if (! node->is_input) {
536                         ir_node *irn = node->node;
537                         int     i;
538
539                         DB((dbg, LEVEL_3, "  propagate %+F\n", irn));
540                         ir_normalize_node(node->node);
541                         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
542                                 ir_node *pred  = get_irn_n(irn, i);
543                                 ir_node *block = get_nodes_block(skip_Proj(pred));
544                                 node_t *p_node;
545
546                                 if (block != bl->block) {
547                                         p_node = create_node(pred, bl, env);
548                                         if (is_input_node(pred, irn, i)) {
549                                                 /* is a block live input */
550                                                 p_node->is_input = 1;
551                                                 if (! is_Phi(irn))
552                                                         add_pair(bl, irn, i, env);
553                                         } else if (is_Phi(pred)) {
554                                                 /* update the Phi list */
555                                                 add_phi(bl, pred, env);
556                                         }
557                                 } else if (! irn_visited_else_mark(pred)) {
558                                         /* not yet visited, ok */
559                                         p_node = create_node(pred, bl, env);
560
561                                         if (is_Phi(pred)) {
562                                                 /* update the Phi list */
563                                                 add_phi(bl, pred, env);
564                                         }
565                                 }
566                         }
567                 } else {
568                         DB((dbg, LEVEL_3, "  propagate Input %+F\n", node->node));
569                 }
570
571                 /* Add bl to map[opcode(n)]. */
572                 id          = opcode(node, env);
573                 entry       = listmap_find(&map, id);
574                 bl->next    = entry->list;
575                 entry->list = bl;
576         }
577
578         /* split out ready blocks */
579         if (n_ready > 0) {
580                 partition_t *Z;
581
582                 if (n_ready < part->n_blocks)
583                         Z = split(part, ready_blocks, env);
584                 else
585                         Z = part;
586                 list_del(&Z->part_list);
587
588                 if (Z->n_blocks > 1) {
589                         DB((dbg, LEVEL_2, " Partition %u is ready\n", Z->nr));
590                         list_add(&Z->part_list, &env->ready);
591                 } else {
592                         DB((dbg, LEVEL_2, " Partition %u contains only one block, killed\n", Z->nr));
593                 }
594         }
595
596         /* for all sets S except one in the range of map do */
597         for (iter = map.values; iter != NULL; iter = iter->next) {
598                 block_t *S;
599
600                 if (iter->next == NULL) {
601                         /* this is the last entry, ignore */
602                         break;
603                 }
604                 S = iter->list;
605
606                 /* Add SPLIT( X, S ) to P. */
607                 split(part, S, env);
608         }
609         listmap_term(&map);
610 }  /* propagate_blocks */
611
612 /**
613  * Propagate nodes on all wait queues.
614  *
615  * @param env    the environment
616  */
617 static void propagate(environment_t *env)
618 {
619         partition_t *part, *next;
620
621         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
622                 if (part->n_blocks < 2) {
623                         /* zero or one block left, kill this partition */
624                         list_del(&part->part_list);
625                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
626                 } else
627                         propagate_blocks(part, env);
628         }
629 }  /* propagate */
630
631 /**
632  * Map a block to the phi[block->input] live-trough.
633  */
634 static void *live_throughs(const block_t *bl, const ir_node *phi)
635 {
636         ir_node *input = get_Phi_pred(phi, bl->meet_input);
637
638         /* If this input is inside our block, this
639            is a live-out and not a live trough.
640            Live-outs are tested inside propagate, so map all of
641            them to the "general" value NULL */
642         if (get_nodes_block(input) == bl->block)
643                 return NULL;
644         return input;
645 }  /* live_throughs */
646
647 /**
648  * Split partition by live-outs and live-troughs.
649  *
650  * @param part  the partition
651  * @param env   the environment
652  */
653 void propagate_blocks_live_troughs(partition_t *part, environment_t *env)
654 {
655         const ir_node   *meet_block = part->meet_block;
656         block_t         *bl, *next;
657         listmap_t       map;
658         listmap_entry_t *iter;
659         const ir_node   *phi;
660
661         DB((dbg, LEVEL_2, " Propagate live-troughs on part%u\n", part->nr));
662
663         for (phi = get_Block_phis(meet_block); phi != NULL; phi = get_Phi_next(phi)) {
664                 /* propagate on all Phis of the meet-block */
665
666                 if (part->n_blocks < 2) {
667                         /* zero or one block left, kill this partition */
668                         list_del(&part->part_list);
669                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
670                         return;
671                 }
672
673                 /* Let map be an empty mapping from the range of live-troughs to (local) list of blocks. */
674                 listmap_init(&map);
675                 list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
676                         opcode_key_t    *id;
677                         listmap_entry_t *entry;
678
679                         /* Add bl to map[live_trough(bl)]. */
680                         id          = live_throughs(bl, phi);
681                         entry       = listmap_find(&map, id);
682                         bl->next    = entry->list;
683                         entry->list = bl;
684                 }
685
686                 /* for all sets S except one in the range of map do */
687                 for (iter = map.values; iter != NULL; iter = iter->next) {
688                         block_t *S;
689
690                         if (iter->next == NULL) {
691                                 /* this is the last entry, ignore */
692                                 break;
693                         }
694                         S = iter->list;
695
696                         /* Add SPLIT( X, S ) to P. */
697                         split(part, S, env);
698                 }
699                 listmap_term(&map);
700         }
701 }  /* propagate_blocks_live_troughs */
702
703 /**
704  * Propagate live-troughs on all partitions on the partition list.
705  *
706  * @param env    the environment
707  */
708 void propagate_live_troughs(environment_t *env)
709 {
710         partition_t *part, *next;
711
712         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
713                 propagate_blocks_live_troughs(part, env);
714         }
715 }  /* propagate_live_troughs */
716
717 /**
718  * Apply analysis results by replacing all blocks of a partition
719  * by one representative.
720  *
721  * Route all inputs from all block of the partition to the one
722  * representative.
723  * Enhance all existing Phis by combining them.
724  * Create new Phis for all previous input nodes.
725  *
726  * @param part  the partition to process
727  */
728 static void apply(ir_graph *irg, partition_t *part)
729 {
730         block_t *repr = list_entry(part->blocks.next, block_t, block_list);
731         block_t *bl;
732         ir_node *block, *end, *meet_block, *p, *next;
733         ir_node **ins, **phi_ins;
734         phi_t   *repr_phi, *phi;
735         pair_t  *repr_pair, *pair;
736         int     i, j, k, n, block_nr, n_phis;
737
738         list_del(&repr->block_list);
739
740         /* prepare new in arrays for the block ... */
741         block = repr->block;
742         n     = get_Block_n_cfgpreds(block);
743         ins   = NEW_ARR_F(ir_node *, n);
744
745         for (i = 0; i < n; ++i) {
746                 ins[i] = get_Block_cfgpred(block, i);
747         }
748
749         /* ... for all existing Phis ... */
750         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
751                 repr_phi->ins = NEW_ARR_F(ir_node *, n);
752
753                 for (i = 0; i < n; ++i)
754                         repr_phi->ins[i] = get_Phi_pred(repr_phi->phi, i);
755         }
756
757         /* ... and all newly created Phis */
758         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
759                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
760
761                 repr_pair->ins = NEW_ARR_F(ir_node *, n);
762                 for (i = 0; i < n; ++i)
763                         repr_pair->ins[i] = input;
764         }
765
766         DB((dbg, LEVEL_1, "Replacing "));
767
768         /* collect new in arrays */
769         end = get_irg_end(irg);
770         block_nr = 0;
771         list_for_each_entry(block_t, bl, &part->blocks, block_list) {
772                 block = bl->block;
773                 ++block_nr;
774
775                 DB((dbg, LEVEL_1, "%+F, ", block));
776
777                 /* first step: kill any keep-alive from this block */
778                 for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
779                         ir_node *ka = get_End_keepalive(end, i);
780
781                         if (is_Block(ka)) {
782                                 if (ka == block)
783                                         remove_End_keepalive(end, ka);
784                         } else {
785                                 if (get_nodes_block(ka) == block)
786                                         remove_End_keepalive(end, ka);
787                         }
788                 }
789
790                 /* second step: update control flow */
791                 n = get_Block_n_cfgpreds(block);
792                 for (i = 0; i < n; ++i) {
793                         ir_node *pred = get_Block_cfgpred(block, i);
794                         ARR_APP1(ir_node *, ins, pred);
795                 }
796
797                 /* third step: update Phis */
798                 for (repr_phi = repr->phis, phi = bl->phis;
799                      repr_phi != NULL;
800                      repr_phi = repr_phi->next, phi = phi->next) {
801                         for (i = 0; i < n; ++i) {
802                                 ir_node *pred = get_Phi_pred(phi->phi, i);
803                                 ARR_APP1(ir_node *, repr_phi->ins, pred);
804                         }
805                 }
806
807                 /* fourth step: update inputs for new Phis */
808                 for (repr_pair = repr->input_pairs, pair = bl->input_pairs;
809                      repr_pair != NULL;
810                      repr_pair = repr_pair->next, pair = pair->next) {
811                         ir_node *input = get_irn_n(pair->irn, pair->index);
812
813                         for (i = 0; i < n; ++i)
814                                 ARR_APP1(ir_node *, repr_pair->ins, input);
815                 }
816         }
817
818         DB((dbg, LEVEL_1, "by %+F\n", repr->block));
819
820         /* rewire block input ... */
821         n = ARR_LEN(ins);
822
823         /*
824          * Some problem here. For:
825          * if (x) y = 1; else y = 2;
826          *
827          * the following code is constructed:
828          *
829          * b0: if (x) goto b1; else goto b1;
830          * b1: y = Phi(1,2)
831          *
832          * However, both predecessors of b1 are b0, making the Phi
833          * "wrong".
834          *
835          * We solve this by fixing critical edges.
836          */
837         for (i = 0; i < n; ++i) {
838                 ir_node     *pred = ins[i];
839                 const ir_op *cfop;
840
841                 if (is_Bad(pred))
842                         continue;
843
844                 cfop = get_irn_op(skip_Proj(pred));
845                 if (is_op_fragile(cfop)) {
846                         /* ignore exception flow */
847                         continue;
848                 }
849                 if (is_op_forking(cfop)) {
850                         /* a critical edge */
851                         ir_node *block = new_r_Block(irg, 1, &ins[i]);
852                         ir_node *jmp   = new_r_Jmp(block);
853                         ins[i] = jmp;
854                 }
855         }
856
857         block = repr->block;
858         set_irn_in(block, n, ins);
859         DEL_ARR_F(ins);
860
861         /* ... existing Phis ... */
862         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
863                 set_irn_in(repr_phi->phi, n, repr_phi->ins);
864                 DEL_ARR_F(repr_phi->ins);
865         }
866
867         /* ... and all inputs by creating new Phis ... */
868         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
869                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
870                 ir_mode *mode  = get_irn_mode(input);
871                 ir_node *phi   = new_r_Phi(block, n, repr_pair->ins, mode);
872
873                 set_irn_n(repr_pair->irn, repr_pair->index, phi);
874                 DEL_ARR_F(repr_pair->ins);
875
876                 /* might be optimized away */
877                 if (is_Phi(phi))
878                         add_Block_phi(block, phi);
879         }
880
881         /* ... finally rewire the meet block and fix its Phi-nodes */
882         meet_block = part->meet_block;
883         n         = get_Block_n_cfgpreds(meet_block);
884
885         ins = NEW_ARR_F(ir_node *, n);
886
887         n_phis = 0;
888         for (p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p)) {
889                 ++n_phis;
890         }
891
892         phi_ins = NEW_ARR_F(ir_node *, n_phis * n);
893
894         for (i = j = 0; i < n; ++i) {
895                 ir_node *pred = get_Block_cfgpred(meet_block, i);
896
897                 list_for_each_entry(block_t, bl, &part->blocks, block_list) {
898                         if (bl->cf_root->node == pred)
899                                 goto continue_outer;
900                 }
901                 ins[j] = pred;
902
903                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p), ++k) {
904                         phi_ins[k * n + j] = get_Phi_pred(p, i);
905                 }
906                 ++j;
907
908 continue_outer:
909                 ;
910         }
911
912         /* fix phis */
913         if (j == 1) {
914                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
915                         next = get_Phi_next(p);
916
917                         exchange(p, phi_ins[k * n]);
918                 }
919                 /* all Phis killed */
920                 set_Block_phis(meet_block, NULL);
921         } else {
922                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
923                         next = get_Phi_next(p);
924
925                         set_irn_in(p, j, &phi_ins[k * n]);
926                 }
927         }
928         DEL_ARR_F(phi_ins);
929
930         /* fix inputs of the meet block */
931         set_irn_in(meet_block, j, ins);
932         DEL_ARR_F(ins);
933 }  /* apply */
934
935 /**
936  * Create a partition for a the end block.
937  *
938  * @param end_block  the end block
939  * @param env        the environment
940  */
941 static void partition_for_end_block(ir_node *end_block, environment_t *env)
942 {
943         partition_t *part = create_partition(end_block, env);
944         ir_node     *end;
945         int         i;
946
947         /* collect normal blocks */
948         for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
949                 ir_node *pred = get_Block_cfgpred(end_block, i);
950                 ir_node *block;
951                 block_t *bl;
952                 node_t  *node;
953
954                 mark_irn_visited(pred);
955
956                 block = get_nodes_block(pred);
957                 bl    = create_block(block, i, part, env);
958                 node  = create_node(pred, bl, env);
959
960                 bl->cf_root = node;
961         }
962
963         /* collect all no-return blocks */
964         end = get_irg_end(current_ir_graph);
965         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
966                 ir_node *ka    = get_End_keepalive(end, i);
967                 ir_node *block;
968                 block_t *bl;
969                 node_t  *node;
970
971                 if (! is_Call(ka))
972                         continue;
973                 mark_irn_visited(ka);
974
975                 /* found one */
976                 block = get_nodes_block(ka);
977                 bl    = create_block(block, -1, part, env);
978                 node  = create_node(ka, bl, env);
979
980                 bl->cf_root = node;
981         }
982
983         dump_partition("Created", part);
984 }  /* partition_for_end_block */
985
986 #ifdef GENERAL_SHAPE
987 /**
988  * Create a partition for a given meet block.
989  *
990  * @param block    the meet block
991  * @param preds    array of candidate predecessors
992  * @param n_preds  number of elements in preds
993  * @param env      the environment
994  */
995 static void partition_for_block(ir_node *block, pred_t preds[], int n_preds, environment_t *env)
996 {
997         partition_t *part = create_partition(block, env);
998         int         i;
999
1000         for (i = n_preds - 1; i >= 0; --i) {
1001                 ir_node *pred = preds[i].pred;
1002                 ir_node *block;
1003                 block_t *bl;
1004                 node_t  *node;
1005
1006                 mark_irn_visited(pred);
1007
1008                 block = get_nodes_block(pred);
1009                 bl    = create_block(block, preds[i].index, part, env);
1010                 node  = create_node(pred, bl, env);
1011
1012                 bl->cf_root = node;
1013         }
1014
1015         dump_partition("Created", part);
1016 }  /* partition_for_block */
1017
1018 /**
1019  * Walker: clear the links of all block phi lists and normal
1020  * links.
1021  */
1022 static void clear_phi_links(ir_node *irn, void *env)
1023 {
1024         (void) env;
1025         if (is_Block(irn)) {
1026                 set_Block_phis(irn, NULL);
1027                 set_irn_link(irn, NULL);
1028         }
1029 }  /* clear_phi_links */
1030
1031 /**
1032  * Walker, detect live-out nodes.
1033  */
1034 static void find_liveouts(ir_node *irn, void *ctx)
1035 {
1036         environment_t *env        = ctx;
1037         ir_node       **live_outs = env->live_outs;
1038         ir_node       *this_block;
1039         int           i;
1040
1041         if (is_Block(irn))
1042                 return;
1043
1044         /* ignore Keep-alives */
1045         if (is_End(irn))
1046                 return;
1047
1048         this_block = get_nodes_block(irn);
1049
1050         if (is_Phi(irn)) {
1051                 /* update the Phi list */
1052                 add_Block_phi(this_block, irn);
1053         }
1054
1055         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1056                 ir_node *pred_block;
1057                 ir_node *pred = get_irn_n(irn, i);
1058                 int     idx   = get_irn_idx(pred);
1059
1060                 if (live_outs[idx] != NULL) {
1061                         /* already marked as live-out */
1062                         return;
1063                 }
1064
1065                 pred_block = get_nodes_block(pred);
1066                 /* Phi nodes always refer to live-outs */
1067                 if (is_Phi(irn) || this_block != pred_block) {
1068                         /* pred is a live-out */
1069                         live_outs[idx] = pred_block;
1070                 }
1071         }
1072 }  /* find_liveouts */
1073
1074 /**
1075  * Check if the current block is the meet block of a its predecessors.
1076  */
1077 static void check_for_cf_meet(ir_node *block, void *ctx)
1078 {
1079         environment_t *env = ctx;
1080         int           i, k, n;
1081         pred_t        *preds;
1082
1083         if (block == get_irg_end_block(current_ir_graph)) {
1084                 /* always create a partition for the end block */
1085                 partition_for_end_block(block, env);
1086                 return;
1087         }
1088
1089         n = get_Block_n_cfgpreds(block);
1090         if (n <= 1) {
1091                 /* Must have at least two predecessors */
1092                 return;
1093         }
1094
1095         NEW_ARR_A(pred_t, preds, n);
1096         k = 0;
1097         for (i = n - 1; i >= 0; --i) {
1098                 ir_node *pred = get_Block_cfgpred(block, i);
1099                 ir_node *pred_block;
1100
1101                 /* pred must be a direct jump to us */
1102                 if (! is_Jmp(pred) && ! is_Raise(pred) && !is_Bad(pred))
1103                         continue;
1104
1105                 pred_block = get_nodes_block(skip_Proj(pred));
1106
1107                 preds[k].pred  = pred;
1108                 preds[k].index = i;
1109         }
1110
1111         if (k > 1)
1112                 partition_for_block(block, preds, k, env);
1113 }  /* check_for_cf_meet */
1114
1115 /**
1116  * Compare two nodes for root ordering.
1117  */
1118 static int cmp_nodes(const void *a, const void *b)
1119 {
1120         const ir_node *const *pa = a;
1121         const ir_node *const *pb = b;
1122         const ir_node  *irn_a  = *pa;
1123         const ir_node  *irn_b  = *pb;
1124         ir_opcode      code_a  = get_irn_opcode(irn_a);
1125         ir_opcode      code_b  = get_irn_opcode(irn_b);
1126         ir_mode        *mode_a, *mode_b;
1127         unsigned       idx_a, idx_b;
1128
1129         /* try opcode first */
1130         if (code_a != code_b)
1131                 return code_a - code_b;
1132
1133         /* try mode */
1134         mode_a = get_irn_mode(irn_a);
1135         mode_b = get_irn_mode(irn_b);
1136
1137         if (mode_a != mode_b)
1138                 return mode_a < mode_b ? -1 : +1;
1139
1140         /* last resort: index */
1141         idx_a = get_irn_idx(irn_a);
1142         idx_b = get_irn_idx(irn_b);
1143
1144         return (idx_a > idx_b) - (idx_a < idx_b);
1145 }  /* cmp_nodes */
1146
1147 /**
1148  * Add the roots to all blocks.
1149  */
1150 static void add_roots(ir_graph *irg, environment_t *env)
1151 {
1152         unsigned idx, n      = get_irg_last_idx(irg);
1153         ir_node  **live_outs = env->live_outs;
1154         block_t  *bl;
1155
1156         for (idx = 0; idx < n; ++idx) {
1157                 ir_node *block = live_outs[idx];
1158
1159                 if (block != NULL && is_Block(block)) {
1160                         block_t *bl = get_Block_entry(block);
1161
1162                         if (bl != NULL) {
1163                                 ir_node *irn = get_idx_irn(irg, idx);
1164
1165                                 if (!irn_visited_else_mark(irn)) {
1166                                         ARR_APP1(ir_node *, bl->roots, irn);
1167                                 }
1168                         }
1169                 }
1170         }
1171         /*
1172          * Now sort the roots to normalize them as good as possible.
1173      * Else, we will split identical blocks if we start which different roots.
1174          */
1175         for (bl = env->all_blocks; bl != NULL; bl = bl->all_next) {
1176                 int i, n = ARR_LEN(bl->roots);
1177
1178 #if 1
1179                 /* TODO: is this really needed? The roots are already in
1180                    idx-order by construction, which might be good enough. */
1181                 qsort(bl->roots, n, sizeof(bl->roots[0]), cmp_nodes);
1182 #endif
1183
1184                 DB((dbg, LEVEL_2, " Adding Roots for block %+F\n  ", bl->block));
1185                 /* ok, add them sorted */
1186                 for (i = 0; i < n; ++i) {
1187                         DB((dbg, LEVEL_2, "%+F, ", bl->roots[i]));
1188                         create_node(bl->roots[i], bl, env);
1189                 }
1190                 DB((dbg, LEVEL_2, "\n"));
1191                 DEL_ARR_F(bl->roots);
1192                 bl->roots = NULL;
1193         }
1194 }  /* add_roots */
1195 #endif /* GENERAL_SHAPE */
1196
1197 /* Combines congruent end blocks into one. */
1198 int shape_blocks(ir_graph *irg)
1199 {
1200         ir_graph      *rem;
1201         environment_t env;
1202         partition_t   *part;
1203         block_t       *bl;
1204         int           res, n;
1205
1206         rem = current_ir_graph;
1207         current_ir_graph = irg;
1208
1209         /* register a debug mask */
1210         FIRM_DBG_REGISTER(dbg, "firm.opt.blocks");
1211
1212         DEBUG_ONLY(part_nr = 0);
1213         DB((dbg, LEVEL_1, "Shaping blocks for %+F\n", irg));
1214
1215         /* works better, when returns are placed at the end of the blocks */
1216         normalize_n_returns(irg);
1217
1218         obstack_init(&env.obst);
1219         INIT_LIST_HEAD(&env.partitions);
1220         INIT_LIST_HEAD(&env.ready);
1221         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
1222
1223         n             = get_irg_last_idx(irg);
1224         env.live_outs = NEW_ARR_F(ir_node *, n);
1225         memset(env.live_outs, 0, sizeof(*env.live_outs) * n);
1226
1227         env.all_blocks = NULL;
1228
1229         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1230
1231 #ifdef GENERAL_SHAPE
1232         /*
1233          * Detect, which nodes are live-out only: these are the roots of our blocks.
1234          * Build phi lists.
1235          */
1236         irg_walk_graph(irg, clear_phi_links, find_liveouts, &env);
1237 #endif
1238
1239         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
1240
1241         inc_irg_visited(irg);
1242 #ifdef GENERAL_SHAPE
1243         /*
1244          * Detect all control flow meets and create partitions.
1245          */
1246         irg_block_walk_graph(irg, NULL, check_for_cf_meet, &env);
1247
1248         /* add root nodes to the partition blocks */
1249         add_roots(irg, &env);
1250 #else
1251         partition_for_end_block(get_irg_end_block(irg), &env);
1252 #endif
1253
1254         propagate_live_troughs(&env);
1255         while (! list_empty(&env.partitions))
1256                 propagate(&env);
1257
1258         res = !list_empty(&env.ready);
1259         //if (res) dump_ir_block_graph(irg, "-before");
1260
1261
1262         list_for_each_entry(partition_t, part, &env.ready, part_list) {
1263                 dump_partition("Ready Partition", part);
1264                 apply(irg, part);
1265         }
1266         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED | IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1267
1268         if (res) {
1269                 /* control flow changed */
1270                 set_irg_outs_inconsistent(irg);
1271                 set_irg_extblk_inconsistent(irg);
1272                 set_irg_doms_inconsistent(irg);
1273                 set_irg_loopinfo_inconsistent(irg);
1274
1275                 /* Calls might be removed. */
1276                 set_trouts_inconsistent();
1277
1278         //      dump_ir_block_graph(irg, "-after");
1279         }
1280
1281         for (bl = env.all_blocks; bl != NULL; bl = bl->all_next) {
1282                 DEL_ARR_F(bl->roots);
1283         }
1284
1285         DEL_ARR_F(env.live_outs);
1286         del_set(env.opcode2id_map);
1287         obstack_free(&env.obst, NULL);
1288         current_ir_graph = rem;
1289
1290         return res;
1291 }  /* shape_blocks */
1292
1293 ir_graph_pass_t *shape_blocks_pass(const char *name)
1294 {
1295         return def_graph_pass_ret(name ? name : "shape_blocks", shape_blocks);
1296 }  /* shape_blocks_pass */