make block numbers accross functions more deterministic
[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_Load:
425                 key.mode = get_Load_mode(irn);
426                 break;
427         case iro_Div:
428                 key.u.intVal = get_Div_no_remainder(irn);
429                 break;
430         case iro_Builtin:
431                 key.u.intVal = get_Builtin_kind(irn);
432                 break;
433         default:
434                 break;
435         }
436
437         entry = set_insert(opcode_key_t, env->opcode2id_map, &key, sizeof(key), opcode_hash(&key));
438         return entry;
439 }  /* opcode */
440
441 /**
442  * Split a partition by a local list.
443  *
444  * @param Z    partition to split
445  * @param g    a (non-empty) block list
446  * @param env  the environment
447  *
448  * @return  a new partition containing the nodes of g
449  */
450 static partition_t *split(partition_t *Z, block_t *g, environment_t *env)
451 {
452         partition_t *Z_prime;
453         block_t     *block;
454         unsigned    n = 0;
455
456         dump_partition("Splitting ", Z);
457         dump_list("by list ", g);
458
459         assert(g != NULL);
460
461         /* Remove g from Z. */
462         for (block = g; block != NULL; block = block->next) {
463                 list_del(&block->block_list);
464                 ++n;
465         }
466         assert(n < Z->n_blocks);
467         Z->n_blocks -= n;
468
469         /* Move g to a new partition, Z'. */
470         Z_prime = create_partition(Z->meet_block, env);
471         for (block = g; block != NULL; block = block->next) {
472                 list_add_tail(&block->block_list, &Z_prime->blocks);
473         }
474         Z_prime->n_blocks = n;
475
476         dump_partition("Now ", Z);
477         dump_partition("Created new ", Z_prime);
478         return Z_prime;
479 }  /* split */
480
481 /**
482  * Return non-zero if pred should be tread as a input node.
483  */
484 static int is_input_node(ir_node *pred, ir_node *irn, int index)
485 {
486         /* for now, do NOT turn direct calls into indirect one */
487         if (index != 1)
488                 return 1;
489         if (! is_SymConst_addr_ent(pred))
490                 return 1;
491         if (! is_Call(irn))
492                 return 1;
493         return 0;
494 }  /* is_input_node */
495
496 /**
497  * Propagate nodes on all wait queues of the given partition.
498  *
499  * @param part  the partition
500  * @param env   the environment
501  */
502 static void propagate_blocks(partition_t *part, environment_t *env)
503 {
504         block_t         *ready_blocks = NULL;
505         unsigned        n_ready       = 0;
506         listmap_t       map;
507         listmap_entry_t *iter;
508
509         DB((dbg, LEVEL_2, " Propagate blocks on part%u\n", part->nr));
510
511         /* Let map be an empty mapping from the range of Opcodes to (local) list of blocks. */
512         listmap_init(&map);
513         list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
514                 opcode_key_t    *id;
515                 listmap_entry_t *entry;
516                 node_t          *node;
517
518                 if (list_empty(&bl->nodes)) {
519                         bl->next     = ready_blocks;
520                         ready_blocks = bl;
521                         ++n_ready;
522                         DB((dbg, LEVEL_2, " Block %+F completely processed\n", bl->block));
523                         continue;
524                 }
525
526                 /* get the first node from the wait queue */
527                 node = list_entry(bl->nodes.next, node_t, node_list);
528                 list_del(&node->node_list);
529
530                 /* put all not-visited predecessors to the wait queue */
531                 if (! node->is_input) {
532                         ir_node *irn = node->node;
533                         int     i;
534
535                         DB((dbg, LEVEL_3, "  propagate %+F\n", irn));
536                         ir_normalize_node(node->node);
537                         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
538                                 ir_node *pred  = get_irn_n(irn, i);
539                                 ir_node *block = get_nodes_block(skip_Proj(pred));
540                                 node_t *p_node;
541
542                                 if (block != bl->block) {
543                                         p_node = create_node(pred, bl, env);
544                                         if (is_input_node(pred, irn, i)) {
545                                                 /* is a block live input */
546                                                 p_node->is_input = 1;
547                                                 if (! is_Phi(irn))
548                                                         add_pair(bl, irn, i, env);
549                                         } else if (is_Phi(pred)) {
550                                                 /* update the Phi list */
551                                                 add_phi(bl, pred, env);
552                                         }
553                                 } else if (! irn_visited_else_mark(pred)) {
554                                         /* not yet visited, ok */
555                                         p_node = create_node(pred, bl, env);
556
557                                         if (is_Phi(pred)) {
558                                                 /* update the Phi list */
559                                                 add_phi(bl, pred, env);
560                                         }
561                                 }
562                         }
563                 } else {
564                         DB((dbg, LEVEL_3, "  propagate Input %+F\n", node->node));
565                 }
566
567                 /* Add bl to map[opcode(n)]. */
568                 id          = opcode(node, env);
569                 entry       = listmap_find(&map, id);
570                 bl->next    = entry->list;
571                 entry->list = bl;
572         }
573
574         /* split out ready blocks */
575         if (n_ready > 0) {
576                 partition_t *Z;
577
578                 if (n_ready < part->n_blocks)
579                         Z = split(part, ready_blocks, env);
580                 else
581                         Z = part;
582                 list_del(&Z->part_list);
583
584                 if (Z->n_blocks > 1) {
585                         DB((dbg, LEVEL_2, " Partition %u is ready\n", Z->nr));
586                         list_add(&Z->part_list, &env->ready);
587                 } else {
588                         DB((dbg, LEVEL_2, " Partition %u contains only one block, killed\n", Z->nr));
589                 }
590         }
591
592         /* for all sets S except one in the range of map do */
593         for (iter = map.values; iter != NULL; iter = iter->next) {
594                 block_t *S;
595
596                 if (iter->next == NULL) {
597                         /* this is the last entry, ignore */
598                         break;
599                 }
600                 S = iter->list;
601
602                 /* Add SPLIT( X, S ) to P. */
603                 split(part, S, env);
604         }
605         listmap_term(&map);
606 }  /* propagate_blocks */
607
608 /**
609  * Propagate nodes on all wait queues.
610  *
611  * @param env    the environment
612  */
613 static void propagate(environment_t *env)
614 {
615         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
616                 if (part->n_blocks < 2) {
617                         /* zero or one block left, kill this partition */
618                         list_del(&part->part_list);
619                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
620                 } else
621                         propagate_blocks(part, env);
622         }
623 }  /* propagate */
624
625 /**
626  * Map a block to the phi[block->input] live-trough.
627  */
628 static void *live_throughs(const block_t *bl, const ir_node *phi)
629 {
630         ir_node *input = get_Phi_pred(phi, bl->meet_input);
631
632         /* If this input is inside our block, this
633            is a live-out and not a live trough.
634            Live-outs are tested inside propagate, so map all of
635            them to the "general" value NULL */
636         if (get_nodes_block(input) == bl->block)
637                 return NULL;
638         return input;
639 }  /* live_throughs */
640
641 /**
642  * Split partition by live-outs and live-troughs.
643  *
644  * @param part  the partition
645  * @param env   the environment
646  */
647 static void propagate_blocks_live_troughs(partition_t *part, environment_t *env)
648 {
649         const ir_node   *meet_block = part->meet_block;
650         listmap_t       map;
651         listmap_entry_t *iter;
652         const ir_node   *phi;
653
654         DB((dbg, LEVEL_2, " Propagate live-troughs on part%u\n", part->nr));
655
656         for (phi = get_Block_phis(meet_block); phi != NULL; phi = get_Phi_next(phi)) {
657                 /* propagate on all Phis of the meet-block */
658
659                 if (part->n_blocks < 2) {
660                         /* zero or one block left, kill this partition */
661                         list_del(&part->part_list);
662                         DB((dbg, LEVEL_2, " Partition %u contains less than 2 blocks, killed\n", part->nr));
663                         return;
664                 }
665
666                 /* Let map be an empty mapping from the range of live-troughs to (local) list of blocks. */
667                 listmap_init(&map);
668                 list_for_each_entry_safe(block_t, bl, next, &part->blocks, block_list) {
669                         opcode_key_t    *id;
670                         listmap_entry_t *entry;
671
672                         /* Add bl to map[live_trough(bl)]. */
673                         id          = (opcode_key_t*)live_throughs(bl, phi);
674                         entry       = listmap_find(&map, id);
675                         bl->next    = entry->list;
676                         entry->list = bl;
677                 }
678
679                 /* for all sets S except one in the range of map do */
680                 for (iter = map.values; iter != NULL; iter = iter->next) {
681                         block_t *S;
682
683                         if (iter->next == NULL) {
684                                 /* this is the last entry, ignore */
685                                 break;
686                         }
687                         S = iter->list;
688
689                         /* Add SPLIT( X, S ) to P. */
690                         split(part, S, env);
691                 }
692                 listmap_term(&map);
693         }
694 }  /* propagate_blocks_live_troughs */
695
696 /**
697  * Propagate live-troughs on all partitions on the partition list.
698  *
699  * @param env    the environment
700  */
701 static void propagate_live_troughs(environment_t *env)
702 {
703         list_for_each_entry_safe(partition_t, part, next, &env->partitions, part_list) {
704                 propagate_blocks_live_troughs(part, env);
705         }
706 }  /* propagate_live_troughs */
707
708 /**
709  * Apply analysis results by replacing all blocks of a partition
710  * by one representative.
711  *
712  * Route all inputs from all block of the partition to the one
713  * representative.
714  * Enhance all existing Phis by combining them.
715  * Create new Phis for all previous input nodes.
716  *
717  * @param part  the partition to process
718  */
719 static void apply(ir_graph *irg, partition_t *part)
720 {
721         block_t *repr = list_entry(part->blocks.next, block_t, block_list);
722         ir_node *block, *end, *meet_block, *p, *next;
723         ir_node **ins, **phi_ins;
724         phi_t   *repr_phi, *phi;
725         pair_t  *repr_pair, *pair;
726         int     i, j, k, n, n_phis;
727
728         list_del(&repr->block_list);
729
730         /* prepare new in arrays for the block ... */
731         block = repr->block;
732         n     = get_Block_n_cfgpreds(block);
733         ins   = NEW_ARR_F(ir_node *, n);
734
735         for (i = 0; i < n; ++i) {
736                 ins[i] = get_Block_cfgpred(block, i);
737         }
738
739         /* ... for all existing Phis ... */
740         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
741                 repr_phi->ins = NEW_ARR_F(ir_node *, n);
742
743                 for (i = 0; i < n; ++i)
744                         repr_phi->ins[i] = get_Phi_pred(repr_phi->phi, i);
745         }
746
747         /* ... and all newly created Phis */
748         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
749                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
750
751                 repr_pair->ins = NEW_ARR_F(ir_node *, n);
752                 for (i = 0; i < n; ++i)
753                         repr_pair->ins[i] = input;
754         }
755
756         DB((dbg, LEVEL_1, "Replacing "));
757
758         /* collect new in arrays */
759         end = get_irg_end(irg);
760         list_for_each_entry(block_t, bl, &part->blocks, block_list) {
761                 block = bl->block;
762
763                 DB((dbg, LEVEL_1, "%+F, ", block));
764
765                 /* first step: kill any keep-alive from this block */
766                 for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
767                         ir_node *ka = get_End_keepalive(end, i);
768
769                         if (is_Block(ka)) {
770                                 if (ka == block)
771                                         remove_End_keepalive(end, ka);
772                         } else {
773                                 if (get_nodes_block(ka) == block)
774                                         remove_End_keepalive(end, ka);
775                         }
776                 }
777
778                 /* second step: update control flow */
779                 n = get_Block_n_cfgpreds(block);
780                 for (i = 0; i < n; ++i) {
781                         ir_node *pred = get_Block_cfgpred(block, i);
782                         ARR_APP1(ir_node *, ins, pred);
783                 }
784
785                 /* third step: update Phis */
786                 for (repr_phi = repr->phis, phi = bl->phis;
787                      repr_phi != NULL;
788                      repr_phi = repr_phi->next, phi = phi->next) {
789                         for (i = 0; i < n; ++i) {
790                                 ir_node *pred = get_Phi_pred(phi->phi, i);
791                                 ARR_APP1(ir_node *, repr_phi->ins, pred);
792                         }
793                 }
794
795                 /* fourth step: update inputs for new Phis */
796                 for (repr_pair = repr->input_pairs, pair = bl->input_pairs;
797                      repr_pair != NULL;
798                      repr_pair = repr_pair->next, pair = pair->next) {
799                         ir_node *input = get_irn_n(pair->irn, pair->index);
800
801                         for (i = 0; i < n; ++i)
802                                 ARR_APP1(ir_node *, repr_pair->ins, input);
803                 }
804         }
805
806         DB((dbg, LEVEL_1, "by %+F\n", repr->block));
807
808         /* rewire block input ... */
809         n = ARR_LEN(ins);
810
811         /*
812          * Some problem here. For:
813          * if (x) y = 1; else y = 2;
814          *
815          * the following code is constructed:
816          *
817          * b0: if (x) goto b1; else goto b1;
818          * b1: y = Phi(1,2)
819          *
820          * However, both predecessors of b1 are b0, making the Phi
821          * "wrong".
822          *
823          * We solve this by fixing critical edges.
824          */
825         for (i = 0; i < n; ++i) {
826                 ir_node     *pred = ins[i];
827                 const ir_op *cfop;
828
829                 if (is_Bad(pred))
830                         continue;
831
832                 cfop = get_irn_op(skip_Proj(pred));
833                 if (is_op_fragile(cfop)) {
834                         /* ignore exception flow */
835                         continue;
836                 }
837                 if (is_op_forking(cfop)) {
838                         /* a critical edge */
839                         ir_node *block = new_r_Block(irg, 1, &ins[i]);
840                         ir_node *jmp   = new_r_Jmp(block);
841                         ins[i] = jmp;
842                 }
843         }
844
845         block = repr->block;
846         set_irn_in(block, n, ins);
847         DEL_ARR_F(ins);
848
849         /* ... existing Phis ... */
850         for (repr_phi = repr->phis; repr_phi != NULL; repr_phi = repr_phi->next) {
851                 set_irn_in(repr_phi->phi, n, repr_phi->ins);
852                 DEL_ARR_F(repr_phi->ins);
853         }
854
855         /* ... and all inputs by creating new Phis ... */
856         for (repr_pair = repr->input_pairs; repr_pair != NULL; repr_pair = repr_pair->next) {
857                 ir_node *input = get_irn_n(repr_pair->irn, repr_pair->index);
858                 ir_mode *mode  = get_irn_mode(input);
859                 ir_node *phi   = new_r_Phi(block, n, repr_pair->ins, mode);
860
861                 set_irn_n(repr_pair->irn, repr_pair->index, phi);
862                 DEL_ARR_F(repr_pair->ins);
863
864                 /* might be optimized away */
865                 if (is_Phi(phi))
866                         add_Block_phi(block, phi);
867         }
868
869         /* ... finally rewire the meet block and fix its Phi-nodes */
870         meet_block = part->meet_block;
871         n         = get_Block_n_cfgpreds(meet_block);
872
873         ins = NEW_ARR_F(ir_node *, n);
874
875         n_phis = 0;
876         for (p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p)) {
877                 ++n_phis;
878         }
879
880         phi_ins = NEW_ARR_F(ir_node *, n_phis * n);
881
882         for (i = j = 0; i < n; ++i) {
883                 ir_node *pred = get_Block_cfgpred(meet_block, i);
884
885                 list_for_each_entry(block_t, bl, &part->blocks, block_list) {
886                         if (bl->cf_root->node == pred)
887                                 goto continue_outer;
888                 }
889                 ins[j] = pred;
890
891                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = get_Phi_next(p), ++k) {
892                         phi_ins[k * n + j] = get_Phi_pred(p, i);
893                 }
894                 ++j;
895
896 continue_outer:
897                 ;
898         }
899
900         /* fix phis */
901         if (j == 1) {
902                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
903                         next = get_Phi_next(p);
904
905                         exchange(p, phi_ins[k * n]);
906                 }
907                 /* all Phis killed */
908                 set_Block_phis(meet_block, NULL);
909         } else {
910                 for (k = 0, p = get_Block_phis(meet_block); p != NULL; p = next, ++k) {
911                         next = get_Phi_next(p);
912
913                         set_irn_in(p, j, &phi_ins[k * n]);
914                 }
915         }
916         DEL_ARR_F(phi_ins);
917
918         /* fix inputs of the meet block */
919         set_irn_in(meet_block, j, ins);
920         DEL_ARR_F(ins);
921 }  /* apply */
922
923 /**
924  * Create a partition for a the end block.
925  *
926  * @param end_block  the end block
927  * @param env        the environment
928  */
929 static void partition_for_end_block(ir_node *end_block, environment_t *env)
930 {
931         partition_t *part = create_partition(end_block, env);
932         ir_node     *end;
933         int         i;
934
935         /* collect normal blocks */
936         for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
937                 ir_node *pred = get_Block_cfgpred(end_block, i);
938                 ir_node *block;
939                 block_t *bl;
940                 node_t  *node;
941
942                 mark_irn_visited(pred);
943
944                 block = get_nodes_block(pred);
945                 bl    = create_block(block, i, part, env);
946                 node  = create_node(pred, bl, env);
947
948                 bl->cf_root = node;
949         }
950
951         /* collect all no-return blocks */
952         end = get_irg_end(get_irn_irg(end_block));
953         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
954                 ir_node *ka    = get_End_keepalive(end, i);
955                 ir_node *block;
956                 block_t *bl;
957                 node_t  *node;
958
959                 if (! is_Call(ka))
960                         continue;
961                 mark_irn_visited(ka);
962
963                 /* found one */
964                 block = get_nodes_block(ka);
965                 bl    = create_block(block, -1, part, env);
966                 node  = create_node(ka, bl, env);
967
968                 bl->cf_root = node;
969         }
970
971         dump_partition("Created", part);
972 }  /* partition_for_end_block */
973
974 #ifdef GENERAL_SHAPE
975 /**
976  * Create a partition for a given meet block.
977  *
978  * @param block    the meet block
979  * @param preds    array of candidate predecessors
980  * @param n_preds  number of elements in preds
981  * @param env      the environment
982  */
983 static void partition_for_block(ir_node *block, pred_t preds[], int n_preds, environment_t *env)
984 {
985         partition_t *part = create_partition(block, env);
986         int         i;
987
988         for (i = n_preds - 1; i >= 0; --i) {
989                 ir_node *pred = preds[i].pred;
990                 ir_node *block;
991                 block_t *bl;
992                 node_t  *node;
993
994                 mark_irn_visited(pred);
995
996                 block = get_nodes_block(pred);
997                 bl    = create_block(block, preds[i].index, part, env);
998                 node  = create_node(pred, bl, env);
999
1000                 bl->cf_root = node;
1001         }
1002
1003         dump_partition("Created", part);
1004 }  /* partition_for_block */
1005
1006 /**
1007  * Walker: clear the links of all block phi lists and normal
1008  * links.
1009  */
1010 static void clear_phi_links(ir_node *irn, void *env)
1011 {
1012         (void) env;
1013         if (is_Block(irn)) {
1014                 set_Block_phis(irn, NULL);
1015                 set_irn_link(irn, NULL);
1016         }
1017 }  /* clear_phi_links */
1018
1019 /**
1020  * Walker, detect live-out nodes.
1021  */
1022 static void find_liveouts(ir_node *irn, void *ctx)
1023 {
1024         environment_t *env        = (environment_t*)ctx;
1025         ir_node       **live_outs = env->live_outs;
1026         ir_node       *this_block;
1027         int           i;
1028
1029         if (is_Block(irn))
1030                 return;
1031
1032         /* ignore Keep-alives */
1033         if (is_End(irn))
1034                 return;
1035
1036         this_block = get_nodes_block(irn);
1037
1038         if (is_Phi(irn)) {
1039                 /* update the Phi list */
1040                 add_Block_phi(this_block, irn);
1041         }
1042
1043         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1044                 ir_node *pred_block;
1045                 ir_node *pred = get_irn_n(irn, i);
1046                 int     idx   = get_irn_idx(pred);
1047
1048                 if (live_outs[idx] != NULL) {
1049                         /* already marked as live-out */
1050                         return;
1051                 }
1052
1053                 pred_block = get_nodes_block(pred);
1054                 /* Phi nodes always refer to live-outs */
1055                 if (is_Phi(irn) || this_block != pred_block) {
1056                         /* pred is a live-out */
1057                         live_outs[idx] = pred_block;
1058                 }
1059         }
1060 }  /* find_liveouts */
1061
1062 /**
1063  * Check if the current block is the meet block of its predecessors.
1064  */
1065 static void check_for_cf_meet(ir_node *block, void *ctx)
1066 {
1067         environment_t *env = (environment_t*)ctx;
1068         int           i, k, n;
1069         pred_t        *preds;
1070
1071         if (block == get_irg_end_block(get_irn_irg(block))) {
1072                 /* always create a partition for the end block */
1073                 partition_for_end_block(block, env);
1074                 return;
1075         }
1076
1077         n = get_Block_n_cfgpreds(block);
1078         if (n <= 1) {
1079                 /* Must have at least two predecessors */
1080                 return;
1081         }
1082
1083         NEW_ARR_A(pred_t, preds, n);
1084         k = 0;
1085         for (i = n - 1; i >= 0; --i) {
1086                 ir_node *pred = get_Block_cfgpred(block, i);
1087
1088                 /* pred must be a direct jump to us */
1089                 if (! is_Jmp(pred) && ! is_Raise(pred) && !is_Bad(pred))
1090                         continue;
1091
1092                 preds[k].pred  = pred;
1093                 preds[k].index = i;
1094                 ++k;
1095         }
1096
1097         if (k > 1)
1098                 partition_for_block(block, preds, k, env);
1099 }  /* check_for_cf_meet */
1100
1101 /**
1102  * Compare two nodes for root ordering.
1103  */
1104 static int cmp_nodes(const void *a, const void *b)
1105 {
1106         const ir_node *const *pa = (const ir_node*const*)a;
1107         const ir_node *const *pb = (const ir_node*const*)b;
1108         const ir_node  *irn_a  = *pa;
1109         const ir_node  *irn_b  = *pb;
1110         unsigned       code_a  = get_irn_opcode(irn_a);
1111         unsigned       code_b  = get_irn_opcode(irn_b);
1112         ir_mode        *mode_a, *mode_b;
1113         unsigned       idx_a, idx_b;
1114
1115         /* try opcode first */
1116         if (code_a != code_b)
1117                 return code_a - code_b;
1118
1119         /* try mode */
1120         mode_a = get_irn_mode(irn_a);
1121         mode_b = get_irn_mode(irn_b);
1122
1123         if (mode_a != mode_b)
1124                 return mode_a < mode_b ? -1 : +1;
1125
1126         /* last resort: index */
1127         idx_a = get_irn_idx(irn_a);
1128         idx_b = get_irn_idx(irn_b);
1129
1130         return (idx_a > idx_b) - (idx_a < idx_b);
1131 }  /* cmp_nodes */
1132
1133 /**
1134  * Add the roots to all blocks.
1135  */
1136 static void add_roots(ir_graph *irg, environment_t *env)
1137 {
1138         unsigned idx, n      = get_irg_last_idx(irg);
1139         ir_node  **live_outs = env->live_outs;
1140         block_t  *bl;
1141
1142         for (idx = 0; idx < n; ++idx) {
1143                 ir_node *block = live_outs[idx];
1144
1145                 if (block != NULL && is_Block(block)) {
1146                         block_t *bl = get_Block_entry(block);
1147
1148                         if (bl != NULL) {
1149                                 ir_node *irn = get_idx_irn(irg, idx);
1150
1151                                 if (!irn_visited_else_mark(irn)) {
1152                                         ARR_APP1(ir_node *, bl->roots, irn);
1153                                 }
1154                         }
1155                 }
1156         }
1157         /*
1158          * Now sort the roots to normalize them as good as possible.
1159      * Else, we will split identical blocks if we start which different roots.
1160          */
1161         for (bl = env->all_blocks; bl != NULL; bl = bl->all_next) {
1162                 size_t i, n = ARR_LEN(bl->roots);
1163
1164 #if 1
1165                 /* TODO: is this really needed? The roots are already in
1166                    idx-order by construction, which might be good enough. */
1167                 qsort(bl->roots, n, sizeof(bl->roots[0]), cmp_nodes);
1168 #endif
1169
1170                 DB((dbg, LEVEL_2, " Adding Roots for block %+F\n  ", bl->block));
1171                 /* ok, add them sorted */
1172                 for (i = 0; i < n; ++i) {
1173                         DB((dbg, LEVEL_2, "%+F, ", bl->roots[i]));
1174                         create_node(bl->roots[i], bl, env);
1175                 }
1176                 DB((dbg, LEVEL_2, "\n"));
1177                 DEL_ARR_F(bl->roots);
1178                 bl->roots = NULL;
1179         }
1180 }  /* add_roots */
1181 #endif /* GENERAL_SHAPE */
1182
1183 /* Combines congruent end blocks into one. */
1184 void shape_blocks(ir_graph *irg)
1185 {
1186         environment_t env;
1187         block_t       *bl;
1188         int           res, n;
1189
1190         /* register a debug mask */
1191         FIRM_DBG_REGISTER(dbg, "firm.opt.blocks");
1192
1193         DEBUG_ONLY(part_nr = 0;)
1194         DB((dbg, LEVEL_1, "Shaping blocks for %+F\n", irg));
1195
1196         /* works better, when returns are placed at the end of the blocks */
1197         normalize_n_returns(irg);
1198
1199         obstack_init(&env.obst);
1200         INIT_LIST_HEAD(&env.partitions);
1201         INIT_LIST_HEAD(&env.ready);
1202         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
1203
1204         n             = get_irg_last_idx(irg);
1205         env.live_outs = NEW_ARR_F(ir_node *, n);
1206         memset(env.live_outs, 0, sizeof(*env.live_outs) * n);
1207
1208         env.all_blocks = NULL;
1209
1210         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1211
1212 #ifdef GENERAL_SHAPE
1213         /*
1214          * Detect, which nodes are live-out only: these are the roots of our blocks.
1215          * Build phi lists.
1216          */
1217         irg_walk_graph(irg, clear_phi_links, find_liveouts, &env);
1218 #endif
1219
1220         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
1221
1222         inc_irg_visited(irg);
1223 #ifdef GENERAL_SHAPE
1224         /*
1225          * Detect all control flow meets and create partitions.
1226          */
1227         irg_block_walk_graph(irg, NULL, check_for_cf_meet, &env);
1228
1229         /* add root nodes to the partition blocks */
1230         add_roots(irg, &env);
1231 #else
1232         partition_for_end_block(get_irg_end_block(irg), &env);
1233 #endif
1234
1235         propagate_live_troughs(&env);
1236         while (! list_empty(&env.partitions))
1237                 propagate(&env);
1238
1239         res = !list_empty(&env.ready);
1240         //if (res) dump_ir_block_graph(irg, "-before");
1241
1242
1243         list_for_each_entry(partition_t, part, &env.ready, part_list) {
1244                 dump_partition("Ready Partition", part);
1245                 apply(irg, part);
1246         }
1247         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED | IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
1248
1249         if (res) {
1250                 /* control flow changed */
1251                 clear_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE);
1252         }
1253
1254         for (bl = env.all_blocks; bl != NULL; bl = bl->all_next) {
1255                 DEL_ARR_F(bl->roots);
1256         }
1257
1258         DEL_ARR_F(env.live_outs);
1259         del_set(env.opcode2id_map);
1260         obstack_free(&env.obst, NULL);
1261 }  /* shape_blocks */
1262
1263 ir_graph_pass_t *shape_blocks_pass(const char *name)
1264 {
1265         return def_graph_pass(name ? name : "shape_blocks", shape_blocks);
1266 }  /* shape_blocks_pass */