Let list_for_each_entry(), list_for_each_entry_reverse() and list_for_each_entry_safe...
[libfirm] / ir / opt / opt_blocks.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Combining congruent blocks
23  * @author  Michael Beck
24  *
25  * This phase find congruent blocks.
26  * Two block are congruent, if they contains only equal calculations.
27  */
28 #include "config.h"
29
30 #include "iroptimize.h"
31 #include "ircons.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 #include "util.h"
43
44 /* define this for general block shaping: congruent blocks
45    are found not only before the end block but anywhere in the graph */
46 #define GENERAL_SHAPE
47
48 typedef struct partition_t     partition_t;
49 typedef struct block_t         block_t;
50 typedef struct node_t          node_t;
51 typedef struct pair_t          pair_t;
52 typedef struct phi_t           phi_t;
53 typedef struct opcode_key_t    opcode_key_t;
54 typedef struct listmap_entry_t listmap_entry_t;
55 typedef struct environment_t   environment_t;
56 typedef struct pred_t          pred_t;
57
58 /** An opcode map key. */
59 struct opcode_key_t {
60         unsigned    code;   /**< The Firm opcode. */
61         ir_mode     *mode;  /**< The mode of all nodes in the partition. */
62         int         arity;  /**< The arity of this opcode (needed for Phi etc. */
63         union {
64                 long            proj;   /**< For Proj nodes, its proj number */
65                 ir_entity       *ent;   /**< For Sel nodes, its entity */
66                 ir_tarval       *tv;    /**< For Const nodes, its tarval */
67                 symconst_symbol sym;    /**< For SymConst nodes, its symbol .*/
68                 void            *addr;  /**< Alias all addresses. */
69                 int             intVal; /**< For Conv/Div nodes: strict/remainderless. */
70         } u;
71 };
72
73 /** A partition contains all congruent blocks. */
74 struct partition_t {
75         list_head part_list;     /**< Double linked list of partitions. */
76         list_head blocks;        /**< List of blocks in this partition. */
77         unsigned  n_blocks;      /**< Number of block in this partition. */
78         ir_node   *meet_block;   /**< The control flow meet block of this partition. */
79 #ifdef DEBUG_libfirm
80         unsigned  nr;            /**< For debugging: number of this partition. */
81 #endif
82 };
83
84 /** A block. */
85 struct block_t {
86         list_head  block_list;   /**< Double linked list of block inside a partition. */
87         list_head  nodes;        /**< Wait-queue of nodes that must be checked for congruence. */
88         block_t    *next;        /**< Next block of a split list. */
89         ir_node    *block;       /**< Pointer to the associated IR-node block. */
90         ir_node    **roots;      /**< An array of all root nodes. */
91         node_t     *cf_root;     /**< The control flow root node of this block. */
92         pair_t     *input_pairs; /**< The list of inputs to this block. */
93         phi_t      *phis;        /**< The list of Phis in this block. */
94         block_t    *all_next;    /**< Links all created blocks. */
95         int        meet_input;   /**< Input number of this block in the meet-block. */
96 };
97
98 /** A node. */
99 struct node_t {
100         list_head  node_list;    /**< Double linked list of block inside a partition. */
101         ir_node    *node;        /**< Pointer to the associated IR-node or NULL for block inputs. */
102         char       is_input;     /**< Set if this node is an input from other block. */
103 };
104
105 /** The environment. */
106 struct environment_t {
107         list_head       partitions;     /**< list of partitions. */
108         list_head       ready;          /**< list of ready partitions. */
109         set             *opcode2id_map; /**< The opcodeMode->id map. */
110         ir_node         **live_outs;    /**< Live out only nodes. */
111         block_t         *all_blocks;    /**< List of all created blocks. */
112         struct obstack  obst;           /** obstack for temporary data */
113 };
114
115 /** A (node, input index) pair. */
116 struct pair_t {
117         pair_t  *next;    /**< Points to the next pair entry. */
118         ir_node *irn;     /**< The IR-node. */
119         int     index;    /**< An input index. */
120         ir_node **ins;    /**< A new in array once allocated. */
121 };
122
123 /** A Phi, inputs pair. */
124 struct phi_t {
125         phi_t   *next;    /**< Points to the next Phi pair entry. */
126         ir_node *phi;     /**< The Phi node. */
127         ir_node **ins;    /**< A new in array once allocated. */
128 };
129
130 /** Describes a predecessor input. */
131 struct pred_t {
132         ir_node *pred;  /**< The predecessor. */
133         int     index;  /**< Its input index. */
134 };
135
136 /**
137  * An entry in the list_map.
138  */
139 struct listmap_entry_t {
140         void            *id;    /**< The id. */
141         block_t         *list;  /**< The associated list for this id. */
142         listmap_entry_t *next;  /**< Link to the next entry in the map. */
143 };
144
145 /** We must map id's to lists. */
146 typedef struct listmap_t {
147         set             *map;    /**< Map id's to listmap_entry_t's */
148         listmap_entry_t *values; /**< List of all values in the map. */
149 } listmap_t;
150
151 #define get_Block_entry(block)  ((block_t *)get_irn_link(block))
152
153 /** The debug module handle. */
154 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
155
156 /** Next partition number. */
157 DEBUG_ONLY(static unsigned part_nr = 0;)
158
159 #ifdef DEBUG_libfirm
160 /**
161  * Dump partition to output.
162  */
163 static void dump_partition(const char *msg, const partition_t *part)
164 {
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 = (const listmap_entry_t*)elt;
201         const listmap_entry_t *e2 = (const listmap_entry_t*)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(listmap_entry_t, 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 (unsigned)(PTR_TO_INT(entry->mode) * 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 = (opcode_key_t*)elt;
272         const opcode_key_t *o2 = (opcode_key_t*)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(opcode_key_t, 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         listmap_t       map;
510         listmap_entry_t *iter;
511
512         DB((dbg, LEVEL_2, " Propagate blocks on part%u\n", part->nr));
513
514         /* Let map be an empty mapping from the range of Opcodes to (local) list of blocks. */
515         listmap_init(&map);
516         list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
517                 opcode_key_t    *id;
518                 listmap_entry_t *entry;
519                 node_t          *node;
520
521                 if (list_empty(&bl->nodes)) {
522                         bl->next     = ready_blocks;
523                         ready_blocks = bl;
524                         ++n_ready;
525                         DB((dbg, LEVEL_2, " Block %+F completely processed\n", bl->block));
526                         continue;
527                 }
528
529                 /* get the first node from the wait queue */
530                 node = list_entry(bl->nodes.next, node_t, node_list);
531                 list_del(&node->node_list);
532
533                 /* put all not-visited predecessors to the wait queue */
534                 if (! node->is_input) {
535                         ir_node *irn = node->node;
536                         int     i;
537
538                         DB((dbg, LEVEL_3, "  propagate %+F\n", irn));
539                         ir_normalize_node(node->node);
540                         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
541                                 ir_node *pred  = get_irn_n(irn, i);
542                                 ir_node *block = get_nodes_block(skip_Proj(pred));
543                                 node_t *p_node;
544
545                                 if (block != bl->block) {
546                                         p_node = create_node(pred, bl, env);
547                                         if (is_input_node(pred, irn, i)) {
548                                                 /* is a block live input */
549                                                 p_node->is_input = 1;
550                                                 if (! is_Phi(irn))
551                                                         add_pair(bl, irn, i, env);
552                                         } else if (is_Phi(pred)) {
553                                                 /* update the Phi list */
554                                                 add_phi(bl, pred, env);
555                                         }
556                                 } else if (! irn_visited_else_mark(pred)) {
557                                         /* not yet visited, ok */
558                                         p_node = create_node(pred, bl, env);
559
560                                         if (is_Phi(pred)) {
561                                                 /* update the Phi list */
562                                                 add_phi(bl, pred, env);
563                                         }
564                                 }
565                         }
566                 } else {
567                         DB((dbg, LEVEL_3, "  propagate Input %+F\n", node->node));
568                 }
569
570                 /* Add bl to map[opcode(n)]. */
571                 id          = opcode(node, env);
572                 entry       = listmap_find(&map, id);
573                 bl->next    = entry->list;
574                 entry->list = bl;
575         }
576
577         /* split out ready blocks */
578         if (n_ready > 0) {
579                 partition_t *Z;
580
581                 if (n_ready < part->n_blocks)
582                         Z = split(part, ready_blocks, env);
583                 else
584                         Z = part;
585                 list_del(&Z->part_list);
586
587                 if (Z->n_blocks > 1) {
588                         DB((dbg, LEVEL_2, " Partition %u is ready\n", Z->nr));
589                         list_add(&Z->part_list, &env->ready);
590                 } else {
591                         DB((dbg, LEVEL_2, " Partition %u contains only one block, killed\n", Z->nr));
592                 }
593         }
594
595         /* for all sets S except one in the range of map do */
596         for (iter = map.values; iter != NULL; iter = iter->next) {
597                 block_t *S;
598
599                 if (iter->next == NULL) {
600                         /* this is the last entry, ignore */
601                         break;
602                 }
603                 S = iter->list;
604
605                 /* Add SPLIT( X, S ) to P. */
606                 split(part, S, env);
607         }
608         listmap_term(&map);
609 }  /* propagate_blocks */
610
611 /**
612  * Propagate nodes on all wait queues.
613  *
614  * @param env    the environment
615  */
616 static void propagate(environment_t *env)
617 {
618         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
619                 if (part->n_blocks < 2) {
620                         /* zero or one block left, kill this partition */
621                         list_del(&part->part_list);
622                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
623                 } else
624                         propagate_blocks(part, env);
625         }
626 }  /* propagate */
627
628 /**
629  * Map a block to the phi[block->input] live-trough.
630  */
631 static void *live_throughs(const block_t *bl, const ir_node *phi)
632 {
633         ir_node *input = get_Phi_pred(phi, bl->meet_input);
634
635         /* If this input is inside our block, this
636            is a live-out and not a live trough.
637            Live-outs are tested inside propagate, so map all of
638            them to the "general" value NULL */
639         if (get_nodes_block(input) == bl->block)
640                 return NULL;
641         return input;
642 }  /* live_throughs */
643
644 /**
645  * Split partition by live-outs and live-troughs.
646  *
647  * @param part  the partition
648  * @param env   the environment
649  */
650 static void propagate_blocks_live_troughs(partition_t *part, environment_t *env)
651 {
652         const ir_node   *meet_block = part->meet_block;
653         listmap_t       map;
654         listmap_entry_t *iter;
655         const ir_node   *phi;
656
657         DB((dbg, LEVEL_2, " Propagate live-troughs on part%u\n", part->nr));
658
659         for (phi = get_Block_phis(meet_block); phi != NULL; phi = get_Phi_next(phi)) {
660                 /* propagate on all Phis of the meet-block */
661
662                 if (part->n_blocks < 2) {
663                         /* zero or one block left, kill this partition */
664                         list_del(&part->part_list);
665                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
666                         return;
667                 }
668
669                 /* Let map be an empty mapping from the range of live-troughs to (local) list of blocks. */
670                 listmap_init(&map);
671                 list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
672                         opcode_key_t    *id;
673                         listmap_entry_t *entry;
674
675                         /* Add bl to map[live_trough(bl)]. */
676                         id          = (opcode_key_t*)live_throughs(bl, phi);
677                         entry       = listmap_find(&map, id);
678                         bl->next    = entry->list;
679                         entry->list = bl;
680                 }
681
682                 /* for all sets S except one in the range of map do */
683                 for (iter = map.values; iter != NULL; iter = iter->next) {
684                         block_t *S;
685
686                         if (iter->next == NULL) {
687                                 /* this is the last entry, ignore */
688                                 break;
689                         }
690                         S = iter->list;
691
692                         /* Add SPLIT( X, S ) to P. */
693                         split(part, S, env);
694                 }
695                 listmap_term(&map);
696         }
697 }  /* propagate_blocks_live_troughs */
698
699 /**
700  * Propagate live-troughs on all partitions on the partition list.
701  *
702  * @param env    the environment
703  */
704 static void propagate_live_troughs(environment_t *env)
705 {
706         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
707                 propagate_blocks_live_troughs(part, env);
708         }
709 }  /* propagate_live_troughs */
710
711 /**
712  * Apply analysis results by replacing all blocks of a partition
713  * by one representative.
714  *
715  * Route all inputs from all block of the partition to the one
716  * representative.
717  * Enhance all existing Phis by combining them.
718  * Create new Phis for all previous input nodes.
719  *
720  * @param part  the partition to process
721  */
722 static void apply(ir_graph *irg, partition_t *part)
723 {
724         block_t *repr = list_entry(part->blocks.next, block_t, block_list);
725         ir_node *block, *end, *meet_block, *p, *next;
726         ir_node **ins, **phi_ins;
727         phi_t   *repr_phi, *phi;
728         pair_t  *repr_pair, *pair;
729         int     i, j, k, n, n_phis;
730
731         list_del(&repr->block_list);
732
733         /* prepare new in arrays for the block ... */
734         block = repr->block;
735         n     = get_Block_n_cfgpreds(block);
736         ins   = NEW_ARR_F(ir_node *, n);
737
738         for (i = 0; i < n; ++i) {
739                 ins[i] = get_Block_cfgpred(block, i);
740         }
741
742         /* ... for all existing Phis ... */
743         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
744                 repr_phi->ins = NEW_ARR_F(ir_node *, n);
745
746                 for (i = 0; i < n; ++i)
747                         repr_phi->ins[i] = get_Phi_pred(repr_phi->phi, i);
748         }
749
750         /* ... and all newly created Phis */
751         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
752                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
753
754                 repr_pair->ins = NEW_ARR_F(ir_node *, n);
755                 for (i = 0; i < n; ++i)
756                         repr_pair->ins[i] = input;
757         }
758
759         DB((dbg, LEVEL_1, "Replacing "));
760
761         /* collect new in arrays */
762         end = get_irg_end(irg);
763         list_for_each_entry(block_t, bl, &part->blocks, block_list) {
764                 block = bl->block;
765
766                 DB((dbg, LEVEL_1, "%+F, ", block));
767
768                 /* first step: kill any keep-alive from this block */
769                 for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
770                         ir_node *ka = get_End_keepalive(end, i);
771
772                         if (is_Block(ka)) {
773                                 if (ka == block)
774                                         remove_End_keepalive(end, ka);
775                         } else {
776                                 if (get_nodes_block(ka) == block)
777                                         remove_End_keepalive(end, ka);
778                         }
779                 }
780
781                 /* second step: update control flow */
782                 n = get_Block_n_cfgpreds(block);
783                 for (i = 0; i < n; ++i) {
784                         ir_node *pred = get_Block_cfgpred(block, i);
785                         ARR_APP1(ir_node *, ins, pred);
786                 }
787
788                 /* third step: update Phis */
789                 for (repr_phi = repr->phis, phi = bl->phis;
790                      repr_phi != NULL;
791                      repr_phi = repr_phi->next, phi = phi->next) {
792                         for (i = 0; i < n; ++i) {
793                                 ir_node *pred = get_Phi_pred(phi->phi, i);
794                                 ARR_APP1(ir_node *, repr_phi->ins, pred);
795                         }
796                 }
797
798                 /* fourth step: update inputs for new Phis */
799                 for (repr_pair = repr->input_pairs, pair = bl->input_pairs;
800                      repr_pair != NULL;
801                      repr_pair = repr_pair->next, pair = pair->next) {
802                         ir_node *input = get_irn_n(pair->irn, pair->index);
803
804                         for (i = 0; i < n; ++i)
805                                 ARR_APP1(ir_node *, repr_pair->ins, input);
806                 }
807         }
808
809         DB((dbg, LEVEL_1, "by %+F\n", repr->block));
810
811         /* rewire block input ... */
812         n = ARR_LEN(ins);
813
814         /*
815          * Some problem here. For:
816          * if (x) y = 1; else y = 2;
817          *
818          * the following code is constructed:
819          *
820          * b0: if (x) goto b1; else goto b1;
821          * b1: y = Phi(1,2)
822          *
823          * However, both predecessors of b1 are b0, making the Phi
824          * "wrong".
825          *
826          * We solve this by fixing critical edges.
827          */
828         for (i = 0; i < n; ++i) {
829                 ir_node     *pred = ins[i];
830                 const ir_op *cfop;
831
832                 if (is_Bad(pred))
833                         continue;
834
835                 cfop = get_irn_op(skip_Proj(pred));
836                 if (is_op_fragile(cfop)) {
837                         /* ignore exception flow */
838                         continue;
839                 }
840                 if (is_op_forking(cfop)) {
841                         /* a critical edge */
842                         ir_node *block = new_r_Block(irg, 1, &ins[i]);
843                         ir_node *jmp   = new_r_Jmp(block);
844                         ins[i] = jmp;
845                 }
846         }
847
848         block = repr->block;
849         set_irn_in(block, n, ins);
850         DEL_ARR_F(ins);
851
852         /* ... existing Phis ... */
853         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
854                 set_irn_in(repr_phi->phi, n, repr_phi->ins);
855                 DEL_ARR_F(repr_phi->ins);
856         }
857
858         /* ... and all inputs by creating new Phis ... */
859         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
860                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
861                 ir_mode *mode  = get_irn_mode(input);
862                 ir_node *phi   = new_r_Phi(block, n, repr_pair->ins, mode);
863
864                 set_irn_n(repr_pair->irn, repr_pair->index, phi);
865                 DEL_ARR_F(repr_pair->ins);
866
867                 /* might be optimized away */
868                 if (is_Phi(phi))
869                         add_Block_phi(block, phi);
870         }
871
872         /* ... finally rewire the meet block and fix its Phi-nodes */
873         meet_block = part->meet_block;
874         n         = get_Block_n_cfgpreds(meet_block);
875
876         ins = NEW_ARR_F(ir_node *, n);
877
878         n_phis = 0;
879         for (p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p)) {
880                 ++n_phis;
881         }
882
883         phi_ins = NEW_ARR_F(ir_node *, n_phis * n);
884
885         for (i = j = 0; i < n; ++i) {
886                 ir_node *pred = get_Block_cfgpred(meet_block, i);
887
888                 list_for_each_entry(block_t, bl, &part->blocks, block_list) {
889                         if (bl->cf_root->node == pred)
890                                 goto continue_outer;
891                 }
892                 ins[j] = pred;
893
894                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p), ++k) {
895                         phi_ins[k * n + j] = get_Phi_pred(p, i);
896                 }
897                 ++j;
898
899 continue_outer:
900                 ;
901         }
902
903         /* fix phis */
904         if (j == 1) {
905                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
906                         next = get_Phi_next(p);
907
908                         exchange(p, phi_ins[k * n]);
909                 }
910                 /* all Phis killed */
911                 set_Block_phis(meet_block, NULL);
912         } else {
913                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
914                         next = get_Phi_next(p);
915
916                         set_irn_in(p, j, &phi_ins[k * n]);
917                 }
918         }
919         DEL_ARR_F(phi_ins);
920
921         /* fix inputs of the meet block */
922         set_irn_in(meet_block, j, ins);
923         DEL_ARR_F(ins);
924 }  /* apply */
925
926 /**
927  * Create a partition for a the end block.
928  *
929  * @param end_block  the end block
930  * @param env        the environment
931  */
932 static void partition_for_end_block(ir_node *end_block, environment_t *env)
933 {
934         partition_t *part = create_partition(end_block, env);
935         ir_node     *end;
936         int         i;
937
938         /* collect normal blocks */
939         for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
940                 ir_node *pred = get_Block_cfgpred(end_block, i);
941                 ir_node *block;
942                 block_t *bl;
943                 node_t  *node;
944
945                 mark_irn_visited(pred);
946
947                 block = get_nodes_block(pred);
948                 bl    = create_block(block, i, part, env);
949                 node  = create_node(pred, bl, env);
950
951                 bl->cf_root = node;
952         }
953
954         /* collect all no-return blocks */
955         end = get_irg_end(get_irn_irg(end_block));
956         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
957                 ir_node *ka    = get_End_keepalive(end, i);
958                 ir_node *block;
959                 block_t *bl;
960                 node_t  *node;
961
962                 if (! is_Call(ka))
963                         continue;
964                 mark_irn_visited(ka);
965
966                 /* found one */
967                 block = get_nodes_block(ka);
968                 bl    = create_block(block, -1, part, env);
969                 node  = create_node(ka, bl, env);
970
971                 bl->cf_root = node;
972         }
973
974         dump_partition("Created", part);
975 }  /* partition_for_end_block */
976
977 #ifdef GENERAL_SHAPE
978 /**
979  * Create a partition for a given meet block.
980  *
981  * @param block    the meet block
982  * @param preds    array of candidate predecessors
983  * @param n_preds  number of elements in preds
984  * @param env      the environment
985  */
986 static void partition_for_block(ir_node *block, pred_t preds[], int n_preds, environment_t *env)
987 {
988         partition_t *part = create_partition(block, env);
989         int         i;
990
991         for (i = n_preds - 1; i >= 0; --i) {
992                 ir_node *pred = preds[i].pred;
993                 ir_node *block;
994                 block_t *bl;
995                 node_t  *node;
996
997                 mark_irn_visited(pred);
998
999                 block = get_nodes_block(pred);
1000                 bl    = create_block(block, preds[i].index, part, env);
1001                 node  = create_node(pred, bl, env);
1002
1003                 bl->cf_root = node;
1004         }
1005
1006         dump_partition("Created", part);
1007 }  /* partition_for_block */
1008
1009 /**
1010  * Walker: clear the links of all block phi lists and normal
1011  * links.
1012  */
1013 static void clear_phi_links(ir_node *irn, void *env)
1014 {
1015         (void) env;
1016         if (is_Block(irn)) {
1017                 set_Block_phis(irn, NULL);
1018                 set_irn_link(irn, NULL);
1019         }
1020 }  /* clear_phi_links */
1021
1022 /**
1023  * Walker, detect live-out nodes.
1024  */
1025 static void find_liveouts(ir_node *irn, void *ctx)
1026 {
1027         environment_t *env        = (environment_t*)ctx;
1028         ir_node       **live_outs = env->live_outs;
1029         ir_node       *this_block;
1030         int           i;
1031
1032         if (is_Block(irn))
1033                 return;
1034
1035         /* ignore Keep-alives */
1036         if (is_End(irn))
1037                 return;
1038
1039         this_block = get_nodes_block(irn);
1040
1041         if (is_Phi(irn)) {
1042                 /* update the Phi list */
1043                 add_Block_phi(this_block, irn);
1044         }
1045
1046         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1047                 ir_node *pred_block;
1048                 ir_node *pred = get_irn_n(irn, i);
1049                 int     idx   = get_irn_idx(pred);
1050
1051                 if (live_outs[idx] != NULL) {
1052                         /* already marked as live-out */
1053                         return;
1054                 }
1055
1056                 pred_block = get_nodes_block(pred);
1057                 /* Phi nodes always refer to live-outs */
1058                 if (is_Phi(irn) || this_block != pred_block) {
1059                         /* pred is a live-out */
1060                         live_outs[idx] = pred_block;
1061                 }
1062         }
1063 }  /* find_liveouts */
1064
1065 /**
1066  * Check if the current block is the meet block of its predecessors.
1067  */
1068 static void check_for_cf_meet(ir_node *block, void *ctx)
1069 {
1070         environment_t *env = (environment_t*)ctx;
1071         int           i, k, n;
1072         pred_t        *preds;
1073
1074         if (block == get_irg_end_block(get_irn_irg(block))) {
1075                 /* always create a partition for the end block */
1076                 partition_for_end_block(block, env);
1077                 return;
1078         }
1079
1080         n = get_Block_n_cfgpreds(block);
1081         if (n <= 1) {
1082                 /* Must have at least two predecessors */
1083                 return;
1084         }
1085
1086         NEW_ARR_A(pred_t, preds, n);
1087         k = 0;
1088         for (i = n - 1; i >= 0; --i) {
1089                 ir_node *pred = get_Block_cfgpred(block, i);
1090
1091                 /* pred must be a direct jump to us */
1092                 if (! is_Jmp(pred) && ! is_Raise(pred) && !is_Bad(pred))
1093                         continue;
1094
1095                 preds[k].pred  = pred;
1096                 preds[k].index = i;
1097                 ++k;
1098         }
1099
1100         if (k > 1)
1101                 partition_for_block(block, preds, k, env);
1102 }  /* check_for_cf_meet */
1103
1104 /**
1105  * Compare two nodes for root ordering.
1106  */
1107 static int cmp_nodes(const void *a, const void *b)
1108 {
1109         const ir_node *const *pa = (const ir_node*const*)a;
1110         const ir_node *const *pb = (const ir_node*const*)b;
1111         const ir_node  *irn_a  = *pa;
1112         const ir_node  *irn_b  = *pb;
1113         unsigned       code_a  = get_irn_opcode(irn_a);
1114         unsigned       code_b  = get_irn_opcode(irn_b);
1115         ir_mode        *mode_a, *mode_b;
1116         unsigned       idx_a, idx_b;
1117
1118         /* try opcode first */
1119         if (code_a != code_b)
1120                 return code_a - code_b;
1121
1122         /* try mode */
1123         mode_a = get_irn_mode(irn_a);
1124         mode_b = get_irn_mode(irn_b);
1125
1126         if (mode_a != mode_b)
1127                 return mode_a < mode_b ? -1 : +1;
1128
1129         /* last resort: index */
1130         idx_a = get_irn_idx(irn_a);
1131         idx_b = get_irn_idx(irn_b);
1132
1133         return (idx_a > idx_b) - (idx_a < idx_b);
1134 }  /* cmp_nodes */
1135
1136 /**
1137  * Add the roots to all blocks.
1138  */
1139 static void add_roots(ir_graph *irg, environment_t *env)
1140 {
1141         unsigned idx, n      = get_irg_last_idx(irg);
1142         ir_node  **live_outs = env->live_outs;
1143         block_t  *bl;
1144
1145         for (idx = 0; idx < n; ++idx) {
1146                 ir_node *block = live_outs[idx];
1147
1148                 if (block != NULL && is_Block(block)) {
1149                         block_t *bl = get_Block_entry(block);
1150
1151                         if (bl != NULL) {
1152                                 ir_node *irn = get_idx_irn(irg, idx);
1153
1154                                 if (!irn_visited_else_mark(irn)) {
1155                                         ARR_APP1(ir_node *, bl->roots, irn);
1156                                 }
1157                         }
1158                 }
1159         }
1160         /*
1161          * Now sort the roots to normalize them as good as possible.
1162      * Else, we will split identical blocks if we start which different roots.
1163          */
1164         for (bl = env->all_blocks; bl != NULL; bl = bl->all_next) {
1165                 size_t i, n = ARR_LEN(bl->roots);
1166
1167 #if 1
1168                 /* TODO: is this really needed? The roots are already in
1169                    idx-order by construction, which might be good enough. */
1170                 qsort(bl->roots, n, sizeof(bl->roots[0]), cmp_nodes);
1171 #endif
1172
1173                 DB((dbg, LEVEL_2, " Adding Roots for block %+F\n  ", bl->block));
1174                 /* ok, add them sorted */
1175                 for (i = 0; i < n; ++i) {
1176                         DB((dbg, LEVEL_2, "%+F, ", bl->roots[i]));
1177                         create_node(bl->roots[i], bl, env);
1178                 }
1179                 DB((dbg, LEVEL_2, "\n"));
1180                 DEL_ARR_F(bl->roots);
1181                 bl->roots = NULL;
1182         }
1183 }  /* add_roots */
1184 #endif /* GENERAL_SHAPE */
1185
1186 /* Combines congruent end blocks into one. */
1187 void shape_blocks(ir_graph *irg)
1188 {
1189         environment_t env;
1190         block_t       *bl;
1191         int           res, n;
1192
1193         /* register a debug mask */
1194         FIRM_DBG_REGISTER(dbg, "firm.opt.blocks");
1195
1196         DEBUG_ONLY(part_nr = 0;)
1197         DB((dbg, LEVEL_1, "Shaping blocks for %+F\n", irg));
1198
1199         /* works better, when returns are placed at the end of the blocks */
1200         normalize_n_returns(irg);
1201
1202         obstack_init(&env.obst);
1203         INIT_LIST_HEAD(&env.partitions);
1204         INIT_LIST_HEAD(&env.ready);
1205         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
1206
1207         n             = get_irg_last_idx(irg);
1208         env.live_outs = NEW_ARR_F(ir_node *, n);
1209         memset(env.live_outs, 0, sizeof(*env.live_outs) * n);
1210
1211         env.all_blocks = NULL;
1212
1213         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1214
1215 #ifdef GENERAL_SHAPE
1216         /*
1217          * Detect, which nodes are live-out only: these are the roots of our blocks.
1218          * Build phi lists.
1219          */
1220         irg_walk_graph(irg, clear_phi_links, find_liveouts, &env);
1221 #endif
1222
1223         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
1224
1225         inc_irg_visited(irg);
1226 #ifdef GENERAL_SHAPE
1227         /*
1228          * Detect all control flow meets and create partitions.
1229          */
1230         irg_block_walk_graph(irg, NULL, check_for_cf_meet, &env);
1231
1232         /* add root nodes to the partition blocks */
1233         add_roots(irg, &env);
1234 #else
1235         partition_for_end_block(get_irg_end_block(irg), &env);
1236 #endif
1237
1238         propagate_live_troughs(&env);
1239         while (! list_empty(&env.partitions))
1240                 propagate(&env);
1241
1242         res = !list_empty(&env.ready);
1243         //if (res) dump_ir_block_graph(irg, "-before");
1244
1245
1246         list_for_each_entry(partition_t, part, &env.ready, part_list) {
1247                 dump_partition("Ready Partition", part);
1248                 apply(irg, part);
1249         }
1250         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED | IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1251
1252         if (res) {
1253                 /* control flow changed */
1254                 clear_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE);
1255         }
1256
1257         for (bl = env.all_blocks; bl != NULL; bl = bl->all_next) {
1258                 DEL_ARR_F(bl->roots);
1259         }
1260
1261         DEL_ARR_F(env.live_outs);
1262         del_set(env.opcode2id_map);
1263         obstack_free(&env.obst, NULL);
1264 }  /* shape_blocks */
1265
1266 ir_graph_pass_t *shape_blocks_pass(const char *name)
1267 {
1268         return def_graph_pass(name ? name : "shape_blocks", shape_blocks);
1269 }  /* shape_blocks_pass */