- renamed init_cons() to firm_init_cons()
[libfirm] / ir / ir / irgopt.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    Optimizations for a whole ir graph, i.e., a procedure.
23  * @author   Christian Schaefer, Goetz Lindenmaier, Sebastian Felis,
24  *           Michael Beck
25  * @version  $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <assert.h>
32
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "irprog_t.h"
36
37 #include "iroptimize.h"
38 #include "ircons_t.h"
39 #include "iropt_t.h"
40 #include "irgopt.h"
41 #include "irgmod.h"
42 #include "irgwalk.h"
43
44 #include "array.h"
45 #include "pset.h"
46 #include "pmap.h"
47 #include "pdeq.h"       /* Fuer code placement */
48 #include "xmalloc.h"
49
50 #include "irouts.h"
51 #include "irloop_t.h"
52 #include "irbackedge_t.h"
53 #include "cgana.h"
54 #include "trouts.h"
55 #include "error.h"
56
57 #include "irflag_t.h"
58 #include "irhooks.h"
59 #include "iredges_t.h"
60 #include "irtools.h"
61
62 /*------------------------------------------------------------------*/
63 /* apply optimizations of iropt to all nodes.                       */
64 /*------------------------------------------------------------------*/
65
66 /**
67  * A wrapper around optimize_inplace_2() to be called from a walker.
68  */
69 static void optimize_in_place_wrapper (ir_node *n, void *env) {
70         ir_node *optimized = optimize_in_place_2(n);
71         (void) env;
72
73         if (optimized != n) {
74                 exchange (n, optimized);
75         }
76 }
77
78 /**
79  * Do local optimizations for a node.
80  *
81  * @param n  the IR-node where to start. Typically the End node
82  *           of a graph
83  *
84  * @note current_ir_graph must be set
85  */
86 static INLINE void do_local_optimize(ir_node *n) {
87         /* Handle graph state */
88         assert(get_irg_phase_state(current_ir_graph) != phase_building);
89
90         if (get_opt_global_cse())
91         set_irg_pinned(current_ir_graph, op_pin_state_floats);
92         set_irg_outs_inconsistent(current_ir_graph);
93         set_irg_doms_inconsistent(current_ir_graph);
94         set_irg_loopinfo_inconsistent(current_ir_graph);
95
96         /* Clean the value_table in irg for the CSE. */
97         del_identities(current_ir_graph->value_table);
98         current_ir_graph->value_table = new_identities();
99
100         /* walk over the graph */
101         irg_walk(n, firm_clear_link, optimize_in_place_wrapper, NULL);
102 }
103
104 /* Applies local optimizations (see iropt.h) to all nodes reachable from node n */
105 void local_optimize_node(ir_node *n) {
106         ir_graph *rem = current_ir_graph;
107         current_ir_graph = get_irn_irg(n);
108
109         do_local_optimize(n);
110
111         current_ir_graph = rem;
112 }
113
114 /**
115  * Block-Walker: uses dominance depth to mark dead blocks.
116  */
117 static void kill_dead_blocks(ir_node *block, void *env) {
118         (void) env;
119
120         if (get_Block_dom_depth(block) < 0) {
121                 /*
122                  * Note that the new dominance code correctly handles
123                  * the End block, i.e. it is always reachable from Start
124                  */
125                 set_Block_dead(block);
126         }
127 }
128
129 /* Applies local optimizations (see iropt.h) to all nodes reachable from node n. */
130 void local_optimize_graph(ir_graph *irg) {
131         ir_graph *rem = current_ir_graph;
132         current_ir_graph = irg;
133
134         if (get_irg_dom_state(irg) == dom_consistent)
135                 irg_block_walk_graph(irg, NULL, kill_dead_blocks, NULL);
136
137         do_local_optimize(get_irg_end(irg));
138
139         current_ir_graph = rem;
140 }
141
142 /**
143  * Enqueue all users of a node to a wait queue.
144  * Handles mode_T nodes.
145  */
146 static void enqueue_users(ir_node *n, pdeq *waitq) {
147         const ir_edge_t *edge;
148
149         foreach_out_edge(n, edge) {
150                 ir_node *succ = get_edge_src_irn(edge);
151
152                 if (get_irn_link(succ) != waitq) {
153                         pdeq_putr(waitq, succ);
154                         set_irn_link(succ, waitq);
155                 }
156                 if (get_irn_mode(succ) == mode_T) {
157                 /* A mode_T node has Proj's. Because most optimizations
158                         run on the Proj's we have to enqueue them also. */
159                         enqueue_users(succ, waitq);
160                 }
161         }
162 }
163
164 /**
165  * Data flow optimization walker.
166  * Optimizes all nodes and enqueue it's users
167  * if done.
168  */
169 static void opt_walker(ir_node *n, void *env) {
170         pdeq *waitq = env;
171         ir_node *optimized;
172
173         optimized = optimize_in_place_2(n);
174         set_irn_link(optimized, NULL);
175
176         if (optimized != n) {
177                 enqueue_users(n, waitq);
178                 exchange(n, optimized);
179         }
180 }
181
182 /* Applies local optimizations to all nodes in the graph until fixpoint. */
183 void optimize_graph_df(ir_graph *irg) {
184         pdeq     *waitq = new_pdeq();
185         ir_graph *rem = current_ir_graph;
186         ir_node  *end;
187         int      i, state;
188
189         current_ir_graph = irg;
190
191         state = edges_assure(irg);
192
193         if (get_opt_global_cse())
194                 set_irg_pinned(current_ir_graph, op_pin_state_floats);
195
196         /* Clean the value_table in irg for the CSE. */
197         del_identities(irg->value_table);
198         irg->value_table = new_identities();
199
200         if (get_irg_dom_state(irg) == dom_consistent)
201                 irg_block_walk_graph(irg, NULL, kill_dead_blocks, NULL);
202
203         /* invalidate info */
204         set_irg_outs_inconsistent(irg);
205         set_irg_doms_inconsistent(irg);
206         set_irg_loopinfo_inconsistent(irg);
207
208         set_using_irn_link(irg);
209
210         /* walk over the graph, but don't touch keep-alives */
211         irg_walk(get_irg_end_block(irg), NULL, opt_walker, waitq);
212
213         end = get_irg_end(irg);
214
215         /* optimize keep-alives by removing superfluous ones */
216         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
217                 ir_node *ka = get_End_keepalive(end, i);
218
219                 if (irn_visited(ka) && !is_irn_keep(ka)) {
220                         /* this node can be regularly visited, no need to keep it */
221                         set_End_keepalive(end, i, get_irg_bad(irg));
222                 }
223         }
224         /* now walk again and visit all not yet visited nodes */
225         set_irg_visited(current_ir_graph, get_irg_visited(irg) - 1);
226         irg_walk(get_irg_end(irg), NULL, opt_walker, waitq);
227
228         /* finish the wait queue */
229         while (! pdeq_empty(waitq)) {
230                 ir_node *n = pdeq_getl(waitq);
231                 if (! is_Bad(n))
232                         opt_walker(n, waitq);
233         }
234
235         del_pdeq(waitq);
236
237         clear_using_irn_link(irg);
238
239         if (! state)
240                 edges_deactivate(irg);
241
242         current_ir_graph = rem;
243 }
244
245
246 /*------------------------------------------------------------------*/
247 /* Routines for dead node elimination / copying garbage collection  */
248 /* of the obstack.                                                  */
249 /*------------------------------------------------------------------*/
250
251 /**
252  * Remember the new node in the old node by using a field all nodes have.
253  */
254 #define set_new_node(oldn, newn)  set_irn_link(oldn, newn)
255
256 /**
257  * Get this new node, before the old node is forgotten.
258  */
259 #define get_new_node(oldn) get_irn_link(oldn)
260
261 /**
262  * Check if a new node was set.
263  */
264 #define has_new_node(n) (get_new_node(n) != NULL)
265
266 /**
267  * We use the block_visited flag to mark that we have computed the
268  * number of useful predecessors for this block.
269  * Further we encode the new arity in this flag in the old blocks.
270  * Remembering the arity is useful, as it saves a lot of pointer
271  * accesses.  This function is called for all Phi and Block nodes
272  * in a Block.
273  */
274 static INLINE int
275 compute_new_arity(ir_node *b) {
276         int i, res, irn_arity;
277         int irg_v, block_v;
278
279         irg_v = get_irg_block_visited(current_ir_graph);
280         block_v = get_Block_block_visited(b);
281         if (block_v >= irg_v) {
282                 /* we computed the number of preds for this block and saved it in the
283                    block_v flag */
284                 return block_v - irg_v;
285         } else {
286                 /* compute the number of good predecessors */
287                 res = irn_arity = get_irn_arity(b);
288                 for (i = 0; i < irn_arity; i++)
289                         if (is_Bad(get_irn_n(b, i))) res--;
290                         /* save it in the flag. */
291                         set_Block_block_visited(b, irg_v + res);
292                         return res;
293         }
294 }
295
296 /**
297  * Copies the node to the new obstack. The Ins of the new node point to
298  * the predecessors on the old obstack.  For block/phi nodes not all
299  * predecessors might be copied.  n->link points to the new node.
300  * For Phi and Block nodes the function allocates in-arrays with an arity
301  * only for useful predecessors.  The arity is determined by counting
302  * the non-bad predecessors of the block.
303  *
304  * @param n    The node to be copied
305  * @param env  if non-NULL, the node number attribute will be copied to the new node
306  *
307  * Note: Also used for loop unrolling.
308  */
309 static void copy_node(ir_node *n, void *env) {
310         ir_node *nn, *block;
311         int new_arity;
312         ir_op *op = get_irn_op(n);
313         (void) env;
314
315         /* The end node looses it's flexible in array.  This doesn't matter,
316            as dead node elimination builds End by hand, inlineing doesn't use
317            the End node. */
318         /* assert(op == op_End ||  ((_ARR_DESCR(n->in))->cookie != ARR_F_MAGIC)); */
319
320         if (op == op_Bad) {
321                 /* node copied already */
322                 return;
323         } else if (op == op_Block) {
324                 block = NULL;
325                 new_arity = compute_new_arity(n);
326                 n->attr.block.graph_arr = NULL;
327         } else {
328                 block = get_nodes_block(n);
329                 if (op == op_Phi) {
330                         new_arity = compute_new_arity(block);
331                 } else {
332                         new_arity = get_irn_arity(n);
333                 }
334         }
335         nn = new_ir_node(get_irn_dbg_info(n),
336                 current_ir_graph,
337                 block,
338                 op,
339                 get_irn_mode(n),
340                 new_arity,
341                 get_irn_in(n) + 1);
342         /* Copy the attributes.  These might point to additional data.  If this
343            was allocated on the old obstack the pointers now are dangling.  This
344            frees e.g. the memory of the graph_arr allocated in new_immBlock. */
345         if (op == op_Block) {
346                 /* we cannot allow blocks WITHOUT macroblock input */
347                 set_Block_MacroBlock(nn, get_Block_MacroBlock(n));
348         }
349         copy_node_attr(n, nn);
350
351 #ifdef DEBUG_libfirm
352         {
353                 int copy_node_nr = env != NULL;
354                 if (copy_node_nr) {
355                         /* for easier debugging, we want to copy the node numbers too */
356                         nn->node_nr = n->node_nr;
357                 }
358         }
359 #endif
360
361         set_new_node(n, nn);
362         hook_dead_node_elim_subst(current_ir_graph, n, nn);
363 }
364
365 /**
366  * Copies new predecessors of old node to new node remembered in link.
367  * Spare the Bad predecessors of Phi and Block nodes.
368  */
369 static void copy_preds(ir_node *n, void *env) {
370         ir_node *nn, *block;
371         int i, j, irn_arity;
372         (void) env;
373
374         nn = get_new_node(n);
375
376         if (is_Block(n)) {
377                 /* copy the macro block header */
378                 ir_node *mbh = get_Block_MacroBlock(n);
379
380                 if (mbh == n) {
381                         /* this block is a macroblock header */
382                         set_Block_MacroBlock(nn, nn);
383                 } else {
384                         /* get the macro block header */
385                         ir_node *nmbh = get_new_node(mbh);
386                         assert(nmbh != NULL);
387                         set_Block_MacroBlock(nn, nmbh);
388                 }
389
390                 /* Don't copy Bad nodes. */
391                 j = 0;
392                 irn_arity = get_irn_arity(n);
393                 for (i = 0; i < irn_arity; i++) {
394                         if (! is_Bad(get_irn_n(n, i))) {
395                                 set_irn_n(nn, j, get_new_node(get_irn_n(n, i)));
396                                 /*if (is_backedge(n, i)) set_backedge(nn, j);*/
397                                 j++;
398                         }
399                 }
400                 /* repair the block visited flag from above misuse. Repair it in both
401                    graphs so that the old one can still be used. */
402                 set_Block_block_visited(nn, 0);
403                 set_Block_block_visited(n, 0);
404                 /* Local optimization could not merge two subsequent blocks if
405                    in array contained Bads.  Now it's possible.
406                    We don't call optimize_in_place as it requires
407                    that the fields in ir_graph are set properly. */
408                 if ((get_opt_control_flow_straightening()) &&
409                         (get_Block_n_cfgpreds(nn) == 1) &&
410                         is_Jmp(get_Block_cfgpred(nn, 0))) {
411                         ir_node *old = get_nodes_block(get_Block_cfgpred(nn, 0));
412                         if (nn == old) {
413                                 /* Jmp jumps into the block it is in -- deal self cycle. */
414                                 assert(is_Bad(get_new_node(get_irg_bad(current_ir_graph))));
415                                 exchange(nn, get_new_node(get_irg_bad(current_ir_graph)));
416                         } else {
417                                 exchange(nn, old);
418                         }
419                 }
420         } else if (is_Phi(n) && get_irn_arity(n) > 0) {
421                 /* Don't copy node if corresponding predecessor in block is Bad.
422                    The Block itself should not be Bad. */
423                 block = get_nodes_block(n);
424                 set_nodes_block(nn, get_new_node(block));
425                 j = 0;
426                 irn_arity = get_irn_arity(n);
427                 for (i = 0; i < irn_arity; i++) {
428                         if (! is_Bad(get_irn_n(block, i))) {
429                                 set_irn_n(nn, j, get_new_node(get_irn_n(n, i)));
430                                 /*if (is_backedge(n, i)) set_backedge(nn, j);*/
431                                 j++;
432                         }
433                 }
434                 /* If the pre walker reached this Phi after the post walker visited the
435                    block block_visited is > 0. */
436                 set_Block_block_visited(get_nodes_block(n), 0);
437                 /* Compacting the Phi's ins might generate Phis with only one
438                    predecessor. */
439                 if (get_irn_arity(nn) == 1)
440                         exchange(nn, get_irn_n(nn, 0));
441         } else {
442                 irn_arity = get_irn_arity(n);
443                 for (i = -1; i < irn_arity; i++)
444                         set_irn_n(nn, i, get_new_node(get_irn_n(n, i)));
445         }
446         /* Now the new node is complete.  We can add it to the hash table for CSE.
447            @@@ inlining aborts if we identify End. Why? */
448         if (!is_End(nn))
449                 add_identities(current_ir_graph->value_table, nn);
450 }
451
452 /**
453  * Copies the graph recursively, compacts the keep-alives of the end node.
454  *
455  * @param irg           the graph to be copied
456  * @param copy_node_nr  If non-zero, the node number will be copied
457  */
458 static void copy_graph(ir_graph *irg, int copy_node_nr) {
459         ir_node *oe, *ne, *ob, *nb, *om, *nm; /* old end, new end, old bad, new bad, old NoMem, new NoMem */
460         ir_node *ka;      /* keep alive */
461         int i, irn_arity;
462         unsigned long vfl;
463
464         /* Some nodes must be copied by hand, sigh */
465         vfl = get_irg_visited(irg);
466         set_irg_visited(irg, vfl + 1);
467
468         oe = get_irg_end(irg);
469         mark_irn_visited(oe);
470         /* copy the end node by hand, allocate dynamic in array! */
471         ne = new_ir_node(get_irn_dbg_info(oe),
472                 irg,
473                 NULL,
474                 op_End,
475                 mode_X,
476                 -1,
477                 NULL);
478         /* Copy the attributes.  Well, there might be some in the future... */
479         copy_node_attr(oe, ne);
480         set_new_node(oe, ne);
481
482         /* copy the Bad node */
483         ob = get_irg_bad(irg);
484         mark_irn_visited(ob);
485         nb = new_ir_node(get_irn_dbg_info(ob),
486                 irg,
487                 NULL,
488                 op_Bad,
489                 mode_T,
490                 0,
491                 NULL);
492         copy_node_attr(ob, nb);
493         set_new_node(ob, nb);
494
495         /* copy the NoMem node */
496         om = get_irg_no_mem(irg);
497         mark_irn_visited(om);
498         nm = new_ir_node(get_irn_dbg_info(om),
499                 irg,
500                 NULL,
501                 op_NoMem,
502                 mode_M,
503                 0,
504                 NULL);
505         copy_node_attr(om, nm);
506         set_new_node(om, nm);
507
508         /* copy the live nodes */
509         set_irg_visited(irg, vfl);
510         irg_walk(get_nodes_block(oe), copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
511
512         /* Note: from yet, the visited flag of the graph is equal to vfl + 1 */
513
514         /* visit the anchors as well */
515         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
516                 ir_node *n = get_irg_anchor(irg, i);
517
518                 if (n && (get_irn_visited(n) <= vfl)) {
519                         set_irg_visited(irg, vfl);
520                         irg_walk(n, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
521                 }
522         }
523
524         /* copy_preds for the end node ... */
525         set_nodes_block(ne, get_new_node(get_nodes_block(oe)));
526
527         /*- ... and now the keep alives. -*/
528         /* First pick the not marked block nodes and walk them.  We must pick these
529            first as else we will oversee blocks reachable from Phis. */
530         irn_arity = get_End_n_keepalives(oe);
531         for (i = 0; i < irn_arity; i++) {
532                 ka = get_End_keepalive(oe, i);
533                 if (is_Block(ka)) {
534                         if (get_irn_visited(ka) <= vfl) {
535                                 /* We must keep the block alive and copy everything reachable */
536                                 set_irg_visited(irg, vfl);
537                                 irg_walk(ka, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
538                         }
539                         add_End_keepalive(ne, get_new_node(ka));
540                 }
541         }
542
543         /* Now pick other nodes.  Here we will keep all! */
544         irn_arity = get_End_n_keepalives(oe);
545         for (i = 0; i < irn_arity; i++) {
546                 ka = get_End_keepalive(oe, i);
547                 if (!is_Block(ka)) {
548                         if (get_irn_visited(ka) <= vfl) {
549                                 /* We didn't copy the node yet.  */
550                                 set_irg_visited(irg, vfl);
551                                 irg_walk(ka, copy_node, copy_preds, INT_TO_PTR(copy_node_nr));
552                         }
553                         add_End_keepalive(ne, get_new_node(ka));
554                 }
555         }
556
557         /* start block sometimes only reached after keep alives */
558         set_nodes_block(nb, get_new_node(get_nodes_block(ob)));
559         set_nodes_block(nm, get_new_node(get_nodes_block(om)));
560 }
561
562 /**
563  * Copies the graph reachable from current_ir_graph->end to the obstack
564  * in current_ir_graph and fixes the environment.
565  * Then fixes the fields in current_ir_graph containing nodes of the
566  * graph.
567  *
568  * @param copy_node_nr  If non-zero, the node number will be copied
569  */
570 static void
571 copy_graph_env(int copy_node_nr) {
572         ir_graph *irg = current_ir_graph;
573         ir_node *old_end, *new_anchor;
574         int i;
575
576         /* remove end_except and end_reg nodes */
577         old_end = get_irg_end(irg);
578         set_irg_end_except (irg, old_end);
579         set_irg_end_reg    (irg, old_end);
580
581         /* Not all nodes remembered in irg might be reachable
582            from the end node.  Assure their link is set to NULL, so that
583            we can test whether new nodes have been computed. */
584         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
585                 ir_node *n = get_irg_anchor(irg, i);
586                 if (n != NULL)
587                         set_new_node(n, NULL);
588         }
589         /* we use the block walk flag for removing Bads from Blocks ins. */
590         inc_irg_block_visited(irg);
591
592         /* copy the graph */
593         copy_graph(irg, copy_node_nr);
594
595         /* fix the anchor */
596         old_end    = get_irg_end(irg);
597         new_anchor = new_Anchor(irg);
598
599         for (i = get_irg_n_anchors(irg) - 1; i >= 0; --i) {
600                 ir_node *n = get_irg_anchor(irg, i);
601                 if (n)
602                         set_irn_n(new_anchor, i, get_new_node(n));
603         }
604         free_End(old_end);
605         irg->anchor = new_anchor;
606
607         /* ensure the new anchor is placed in the endblock */
608         set_nodes_block(new_anchor, get_irg_end_block(irg));
609 }
610
611 /**
612  * Copies all reachable nodes to a new obstack.  Removes bad inputs
613  * from block nodes and the corresponding inputs from Phi nodes.
614  * Merges single exit blocks with single entry blocks and removes
615  * 1-input Phis.
616  * Adds all new nodes to a new hash table for CSE.  Does not
617  * perform CSE, so the hash table might contain common subexpressions.
618  */
619 void dead_node_elimination(ir_graph *irg) {
620         ir_graph *rem;
621 #ifdef INTERPROCEDURAL_VIEW
622         int rem_ipview = get_interprocedural_view();
623 #endif
624         struct obstack *graveyard_obst = NULL;
625         struct obstack *rebirth_obst   = NULL;
626         assert(! edges_activated(irg) && "dead node elimination requires disabled edges");
627
628         /* inform statistics that we started a dead-node elimination run */
629         hook_dead_node_elim(irg, 1);
630
631         /* Remember external state of current_ir_graph. */
632         rem = current_ir_graph;
633         current_ir_graph = irg;
634 #ifdef INTERPROCEDURAL_VIEW
635         set_interprocedural_view(0);
636 #endif
637
638         assert(get_irg_phase_state(irg) != phase_building);
639
640         /* Handle graph state */
641         free_callee_info(irg);
642         free_irg_outs(irg);
643         free_trouts();
644
645         /* @@@ so far we loose loops when copying */
646         free_loop_information(irg);
647
648         set_irg_doms_inconsistent(irg);
649
650         /* A quiet place, where the old obstack can rest in peace,
651            until it will be cremated. */
652         graveyard_obst = irg->obst;
653
654         /* A new obstack, where the reachable nodes will be copied to. */
655         rebirth_obst = xmalloc(sizeof(*rebirth_obst));
656         irg->obst = rebirth_obst;
657         obstack_init(irg->obst);
658         irg->last_node_idx = 0;
659
660         /* We also need a new value table for CSE */
661         del_identities(irg->value_table);
662         irg->value_table = new_identities();
663
664         /* Copy the graph from the old to the new obstack */
665         copy_graph_env(/*copy_node_nr=*/1);
666
667         /* Free memory from old unoptimized obstack */
668         obstack_free(graveyard_obst, 0);  /* First empty the obstack ... */
669         xfree(graveyard_obst);            /* ... then free it.           */
670
671         /* inform statistics that the run is over */
672         hook_dead_node_elim(irg, 0);
673
674         current_ir_graph = rem;
675 #ifdef INTERPROCEDURAL_VIEW
676         set_interprocedural_view(rem_ipview);
677 #endif
678 }
679
680 /**
681  * Relink bad predecessors of a block and store the old in array to the
682  * link field. This function is called by relink_bad_predecessors().
683  * The array of link field starts with the block operand at position 0.
684  * If block has bad predecessors, create a new in array without bad preds.
685  * Otherwise let in array untouched.
686  */
687 static void relink_bad_block_predecessors(ir_node *n, void *env) {
688         ir_node **new_in, *irn;
689         int i, new_irn_n, old_irn_arity, new_irn_arity = 0;
690         (void) env;
691
692         /* if link field of block is NULL, look for bad predecessors otherwise
693            this is already done */
694         if (is_Block(n) && get_irn_link(n) == NULL) {
695                 /* save old predecessors in link field (position 0 is the block operand)*/
696                 set_irn_link(n, get_irn_in(n));
697
698                 /* count predecessors without bad nodes */
699                 old_irn_arity = get_irn_arity(n);
700                 for (i = 0; i < old_irn_arity; i++)
701                         if (!is_Bad(get_irn_n(n, i))) new_irn_arity++;
702
703                         /* arity changing: set new predecessors without bad nodes */
704                         if (new_irn_arity < old_irn_arity) {
705                                 /* Get new predecessor array. We do not resize the array, as we must
706                                    keep the old one to update Phis. */
707                                 new_in = NEW_ARR_D (ir_node *, current_ir_graph->obst, (new_irn_arity+1));
708
709                                 /* set new predecessors in array */
710                                 new_in[0] = NULL;
711                                 new_irn_n = 1;
712                                 for (i = 0; i < old_irn_arity; i++) {
713                                         irn = get_irn_n(n, i);
714                                         if (!is_Bad(irn)) {
715                                                 new_in[new_irn_n] = irn;
716                                                 is_backedge(n, i) ? set_backedge(n, new_irn_n-1) : set_not_backedge(n, new_irn_n-1);
717                                                 ++new_irn_n;
718                                         }
719                                 }
720                                 /* ARR_SETLEN(int, n->attr.block.backedge, new_irn_arity); */
721                                 ARR_SHRINKLEN(n->attr.block.backedge, new_irn_arity);
722                                 n->in = new_in;
723                         } /* ir node has bad predecessors */
724         } /* Block is not relinked */
725 }
726
727 /**
728  * Relinks Bad predecessors from Blocks and Phis called by walker
729  * remove_bad_predecesors(). If n is a Block, call
730  * relink_bad_block_redecessors(). If n is a Phi-node, call also the relinking
731  * function of Phi's Block. If this block has bad predecessors, relink preds
732  * of the Phi-node.
733  */
734 static void relink_bad_predecessors(ir_node *n, void *env) {
735         ir_node *block, **old_in;
736         int i, old_irn_arity, new_irn_arity;
737
738         /* relink bad predecessors of a block */
739         if (is_Block(n))
740                 relink_bad_block_predecessors(n, env);
741
742         /* If Phi node relink its block and its predecessors */
743         if (is_Phi(n)) {
744                 /* Relink predecessors of phi's block */
745                 block = get_nodes_block(n);
746                 if (get_irn_link(block) == NULL)
747                         relink_bad_block_predecessors(block, env);
748
749                 old_in = (ir_node **)get_irn_link(block); /* Of Phi's Block */
750                 old_irn_arity = ARR_LEN(old_in);
751
752                 /* Relink Phi predecessors if count of predecessors changed */
753                 if (old_irn_arity != ARR_LEN(get_irn_in(block))) {
754                         /* set new predecessors in array
755                            n->in[0] remains the same block */
756                         new_irn_arity = 1;
757                         for(i = 1; i < old_irn_arity; i++)
758                                 if (!is_Bad((ir_node *)old_in[i])) {
759                                         n->in[new_irn_arity] = n->in[i];
760                                         is_backedge(n, i) ? set_backedge(n, new_irn_arity) : set_not_backedge(n, new_irn_arity);
761                                         ++new_irn_arity;
762                                 }
763
764                                 ARR_SETLEN(ir_node *, n->in, new_irn_arity);
765                                 ARR_SETLEN(int, n->attr.phi.u.backedge, new_irn_arity);
766                 }
767         } /* n is a Phi node */
768 }
769
770 /*
771  * Removes Bad Bad predecessors from Blocks and the corresponding
772  * inputs to Phi nodes as in dead_node_elimination but without
773  * copying the graph.
774  * On walking up set the link field to NULL, on walking down call
775  * relink_bad_predecessors() (This function stores the old in array
776  * to the link field and sets a new in array if arity of predecessors
777  * changes).
778  */
779 void remove_bad_predecessors(ir_graph *irg) {
780         panic("Fix backedge handling first");
781         irg_walk_graph(irg, firm_clear_link, relink_bad_predecessors, NULL);
782 }
783
784
785 /*
786    __                      _  __ __
787   (_     __    o     _    | \/  |_
788   __)|_| | \_/ | \_/(/_   |_/\__|__
789
790   The following stuff implements a facility that automatically patches
791   registered ir_node pointers to the new node when a dead node elimination occurs.
792 */
793
794 struct _survive_dce_t {
795         struct obstack obst;
796         pmap *places;
797         pmap *new_places;
798         hook_entry_t dead_node_elim;
799         hook_entry_t dead_node_elim_subst;
800 };
801
802 typedef struct _survive_dce_list_t {
803         struct _survive_dce_list_t *next;
804         ir_node **place;
805 } survive_dce_list_t;
806
807 static void dead_node_hook(void *context, ir_graph *irg, int start) {
808         survive_dce_t *sd = context;
809         (void) irg;
810
811         /* Create a new map before the dead node elimination is performed. */
812         if (start) {
813                 sd->new_places = pmap_create_ex(pmap_count(sd->places));
814         } else {
815                 /* Patch back all nodes if dead node elimination is over and something is to be done. */
816                 pmap_destroy(sd->places);
817                 sd->places     = sd->new_places;
818                 sd->new_places = NULL;
819         }
820 }
821
822 /**
823  * Hook called when dead node elimination replaces old by nw.
824  */
825 static void dead_node_subst_hook(void *context, ir_graph *irg, ir_node *old, ir_node *nw) {
826         survive_dce_t *sd = context;
827         survive_dce_list_t *list = pmap_get(sd->places, old);
828         (void) irg;
829
830         /* If the node is to be patched back, write the new address to all registered locations. */
831         if (list) {
832                 survive_dce_list_t *p;
833
834                 for (p = list; p; p = p->next)
835                         *(p->place) = nw;
836
837                 pmap_insert(sd->new_places, nw, list);
838         }
839 }
840
841 /**
842  * Make a new Survive DCE environment.
843  */
844 survive_dce_t *new_survive_dce(void) {
845         survive_dce_t *res = xmalloc(sizeof(res[0]));
846         obstack_init(&res->obst);
847         res->places     = pmap_create();
848         res->new_places = NULL;
849
850         res->dead_node_elim.hook._hook_dead_node_elim = dead_node_hook;
851         res->dead_node_elim.context                   = res;
852         res->dead_node_elim.next                      = NULL;
853
854         res->dead_node_elim_subst.hook._hook_dead_node_elim_subst = dead_node_subst_hook;
855         res->dead_node_elim_subst.context = res;
856         res->dead_node_elim_subst.next    = NULL;
857
858 #ifndef FIRM_ENABLE_HOOKS
859         assert(0 && "need hooks enabled");
860 #endif
861
862         register_hook(hook_dead_node_elim, &res->dead_node_elim);
863         register_hook(hook_dead_node_elim_subst, &res->dead_node_elim_subst);
864         return res;
865 }
866
867 /**
868  * Free a Survive DCE environment.
869  */
870 void free_survive_dce(survive_dce_t *sd) {
871         obstack_free(&sd->obst, NULL);
872         pmap_destroy(sd->places);
873         unregister_hook(hook_dead_node_elim, &sd->dead_node_elim);
874         unregister_hook(hook_dead_node_elim_subst, &sd->dead_node_elim_subst);
875         xfree(sd);
876 }
877
878 /**
879  * Register a node pointer to be patched upon DCE.
880  * When DCE occurs, the node pointer specified by @p place will be
881  * patched to the new address of the node it is pointing to.
882  *
883  * @param sd    The Survive DCE environment.
884  * @param place The address of the node pointer.
885  */
886 void survive_dce_register_irn(survive_dce_t *sd, ir_node **place) {
887         if (*place != NULL) {
888                 ir_node *irn      = *place;
889                 survive_dce_list_t *curr = pmap_get(sd->places, irn);
890                 survive_dce_list_t *nw   = obstack_alloc(&sd->obst, sizeof(nw[0]));
891
892                 nw->next  = curr;
893                 nw->place = place;
894
895                 pmap_insert(sd->places, irn, nw);
896         }
897 }
898
899 /*--------------------------------------------------------------------*/
900 /*  Functionality for inlining                                         */
901 /*--------------------------------------------------------------------*/
902
903 /**
904  * Copy node for inlineing.  Updates attributes that change when
905  * inlineing but not for dead node elimination.
906  *
907  * Copies the node by calling copy_node() and then updates the entity if
908  * it's a local one.  env must be a pointer of the frame type of the
909  * inlined procedure. The new entities must be in the link field of
910  * the entities.
911  */
912 static INLINE void
913 copy_node_inline(ir_node *n, void *env) {
914         ir_node *nn;
915         ir_type *frame_tp = (ir_type *)env;
916
917         copy_node(n, NULL);
918         if (is_Sel(n)) {
919                 nn = get_new_node (n);
920                 assert(is_Sel(nn));
921                 if (get_entity_owner(get_Sel_entity(n)) == frame_tp) {
922                         set_Sel_entity(nn, get_entity_link(get_Sel_entity(n)));
923                 }
924         } else if (is_Block(n)) {
925                 nn = get_new_node (n);
926                 nn->attr.block.irg = current_ir_graph;
927         }
928 }
929
930 /**
931  * Walker: checks if P_value_arg_base is used.
932  */
933 static void find_addr(ir_node *node, void *env) {
934         int *allow_inline = env;
935         if (is_Proj(node) &&
936                         is_Start(get_Proj_pred(node)) &&
937                         get_Proj_proj(node) == pn_Start_P_value_arg_base) {
938                 *allow_inline = 0;
939         }
940 }
941
942 /**
943  * Check if we can inline a given call.
944  * Currently, we cannot inline two cases:
945  * - call with compound arguments
946  * - graphs that take the address of a parameter
947  *
948  * check these conditions here
949  */
950 static int can_inline(ir_node *call, ir_graph *called_graph) {
951         ir_type *call_type = get_Call_type(call);
952         int params, ress, i, res;
953         assert(is_Method_type(call_type));
954
955         params = get_method_n_params(call_type);
956         ress   = get_method_n_ress(call_type);
957
958         /* check parameters for compound arguments */
959         for (i = 0; i < params; ++i) {
960                 ir_type *p_type = get_method_param_type(call_type, i);
961
962                 if (is_compound_type(p_type))
963                         return 0;
964         }
965
966         /* check results for compound arguments */
967         for (i = 0; i < ress; ++i) {
968                 ir_type *r_type = get_method_res_type(call_type, i);
969
970                 if (is_compound_type(r_type))
971                         return 0;
972         }
973
974         res = 1;
975         irg_walk_graph(called_graph, find_addr, NULL, &res);
976
977         return res;
978 }
979
980 enum exc_mode {
981         exc_handler    = 0, /**< There is a handler. */
982         exc_to_end     = 1, /**< Branches to End. */
983         exc_no_handler = 2  /**< Exception handling not represented. */
984 };
985
986 /* Inlines a method at the given call site. */
987 int inline_method(ir_node *call, ir_graph *called_graph) {
988         ir_node *pre_call;
989         ir_node *post_call, *post_bl;
990         ir_node *in[pn_Start_max];
991         ir_node *end, *end_bl;
992         ir_node **res_pred;
993         ir_node **cf_pred;
994         ir_node *ret, *phi;
995         int arity, n_ret, n_exc, n_res, i, n, j, rem_opt, irn_arity;
996         enum exc_mode exc_handling;
997         ir_type *called_frame;
998         irg_inline_property prop = get_irg_inline_property(called_graph);
999         ir_entity *ent;
1000
1001         if (prop == irg_inline_forbidden)
1002                 return 0;
1003
1004         ent = get_irg_entity(called_graph);
1005
1006         /* Do not inline variadic functions. */
1007         if (get_method_variadicity(get_entity_type(ent)) == variadicity_variadic)
1008                 return 0;
1009
1010         assert(get_method_n_params(get_entity_type(ent)) ==
1011                get_method_n_params(get_Call_type(call)));
1012
1013         /*
1014          * We cannot inline a recursive call. The graph must be copied before
1015          * the call the inline_method() using create_irg_copy().
1016          */
1017         if (called_graph == current_ir_graph)
1018                 return 0;
1019
1020         /*
1021          * currently, we cannot inline two cases:
1022          * - call with compound arguments
1023          * - graphs that take the address of a parameter
1024          */
1025         if (! can_inline(call, called_graph))
1026                 return 0;
1027
1028         /* --  Turn off optimizations, this can cause problems when allocating new nodes. -- */
1029         rem_opt = get_opt_optimize();
1030         set_optimize(0);
1031
1032         /* Handle graph state */
1033         assert(get_irg_phase_state(current_ir_graph) != phase_building);
1034         assert(get_irg_pinned(current_ir_graph) == op_pin_state_pinned);
1035         assert(get_irg_pinned(called_graph) == op_pin_state_pinned);
1036         set_irg_outs_inconsistent(current_ir_graph);
1037         set_irg_extblk_inconsistent(current_ir_graph);
1038         set_irg_doms_inconsistent(current_ir_graph);
1039         set_irg_loopinfo_inconsistent(current_ir_graph);
1040         set_irg_callee_info_state(current_ir_graph, irg_callee_info_inconsistent);
1041
1042         /* -- Check preconditions -- */
1043         assert(is_Call(call));
1044
1045         /* here we know we WILL inline, so inform the statistics */
1046         hook_inline(call, called_graph);
1047
1048         /* -- Decide how to handle exception control flow: Is there a handler
1049            for the Call node, or do we branch directly to End on an exception?
1050            exc_handling:
1051            0 There is a handler.
1052            1 Branches to End.
1053            2 Exception handling not represented in Firm. -- */
1054         {
1055                 ir_node *proj, *Mproj = NULL, *Xproj = NULL;
1056                 for (proj = get_irn_link(call); proj; proj = get_irn_link(proj)) {
1057                         long proj_nr = get_Proj_proj(proj);
1058                         if (proj_nr == pn_Call_X_except) Xproj = proj;
1059                         if (proj_nr == pn_Call_M_except) Mproj = proj;
1060                 }
1061                 if      (Mproj) { assert(Xproj); exc_handling = exc_handler; } /*  Mproj           */
1062                 else if (Xproj) {                exc_handling = exc_to_end; } /* !Mproj &&  Xproj   */
1063                 else            {                exc_handling = exc_no_handler; } /* !Mproj && !Xproj   */
1064         }
1065
1066         /* --
1067            the procedure and later replaces the Start node of the called graph.
1068            Post_call is the old Call node and collects the results of the called
1069            graph. Both will end up being a tuple.  -- */
1070         post_bl = get_nodes_block(call);
1071         set_irg_current_block(current_ir_graph, post_bl);
1072         /* XxMxPxPxPxT of Start + parameter of Call */
1073         in[pn_Start_X_initial_exec]   = new_Jmp();
1074         in[pn_Start_M]                = get_Call_mem(call);
1075         in[pn_Start_P_frame_base]     = get_irg_frame(current_ir_graph);
1076         in[pn_Start_P_globals]        = get_irg_globals(current_ir_graph);
1077         in[pn_Start_P_tls]            = get_irg_tls(current_ir_graph);
1078         in[pn_Start_T_args]           = new_Tuple(get_Call_n_params(call), get_Call_param_arr(call));
1079         /* in[pn_Start_P_value_arg_base] = ??? */
1080         assert(pn_Start_P_value_arg_base == pn_Start_max - 1 && "pn_Start_P_value_arg_base not supported, fix");
1081         pre_call = new_Tuple(pn_Start_max - 1, in);
1082         post_call = call;
1083
1084         /* --
1085            The new block gets the ins of the old block, pre_call and all its
1086            predecessors and all Phi nodes. -- */
1087         part_block(pre_call);
1088
1089         /* -- Prepare state for dead node elimination -- */
1090         /* Visited flags in calling irg must be >= flag in called irg.
1091            Else walker and arity computation will not work. */
1092         if (get_irg_visited(current_ir_graph) <= get_irg_visited(called_graph))
1093                 set_irg_visited(current_ir_graph, get_irg_visited(called_graph)+1);
1094         if (get_irg_block_visited(current_ir_graph)< get_irg_block_visited(called_graph))
1095                 set_irg_block_visited(current_ir_graph, get_irg_block_visited(called_graph));
1096         /* Set pre_call as new Start node in link field of the start node of
1097            calling graph and pre_calls block as new block for the start block
1098            of calling graph.
1099            Further mark these nodes so that they are not visited by the
1100            copying. */
1101         set_irn_link(get_irg_start(called_graph), pre_call);
1102         set_irn_visited(get_irg_start(called_graph), get_irg_visited(current_ir_graph));
1103         set_irn_link(get_irg_start_block(called_graph), get_nodes_block(pre_call));
1104         set_irn_visited(get_irg_start_block(called_graph), get_irg_visited(current_ir_graph));
1105         set_irn_link(get_irg_bad(called_graph), get_irg_bad(current_ir_graph));
1106         set_irn_visited(get_irg_bad(called_graph), get_irg_visited(current_ir_graph));
1107
1108         /* Initialize for compaction of in arrays */
1109         inc_irg_block_visited(current_ir_graph);
1110
1111         /* -- Replicate local entities of the called_graph -- */
1112         /* copy the entities. */
1113         called_frame = get_irg_frame_type(called_graph);
1114         for (i = 0, n = get_class_n_members(called_frame); i < n; ++i) {
1115                 ir_entity *new_ent, *old_ent;
1116                 old_ent = get_class_member(called_frame, i);
1117                 new_ent = copy_entity_own(old_ent, get_cur_frame_type());
1118                 set_entity_link(old_ent, new_ent);
1119         }
1120
1121         /* visited is > than that of called graph.  With this trick visited will
1122            remain unchanged so that an outer walker, e.g., searching the call nodes
1123             to inline, calling this inline will not visit the inlined nodes. */
1124         set_irg_visited(current_ir_graph, get_irg_visited(current_ir_graph)-1);
1125
1126         /* -- Performing dead node elimination inlines the graph -- */
1127         /* Copies the nodes to the obstack of current_ir_graph. Updates links to new
1128            entities. */
1129         irg_walk(get_irg_end(called_graph), copy_node_inline, copy_preds,
1130                  get_irg_frame_type(called_graph));
1131
1132         /* Repair called_graph */
1133         set_irg_visited(called_graph, get_irg_visited(current_ir_graph));
1134         set_irg_block_visited(called_graph, get_irg_block_visited(current_ir_graph));
1135         set_Block_block_visited(get_irg_start_block(called_graph), 0);
1136
1137         /* -- Merge the end of the inlined procedure with the call site -- */
1138         /* We will turn the old Call node into a Tuple with the following
1139            predecessors:
1140            -1:  Block of Tuple.
1141            0: Phi of all Memories of Return statements.
1142            1: Jmp from new Block that merges the control flow from all exception
1143            predecessors of the old end block.
1144            2: Tuple of all arguments.
1145            3: Phi of Exception memories.
1146            In case the old Call directly branches to End on an exception we don't
1147            need the block merging all exceptions nor the Phi of the exception
1148            memories.
1149         */
1150
1151         /* -- Precompute some values -- */
1152         end_bl = get_new_node(get_irg_end_block(called_graph));
1153         end = get_new_node(get_irg_end(called_graph));
1154         arity = get_irn_arity(end_bl);    /* arity = n_exc + n_ret  */
1155         n_res = get_method_n_ress(get_Call_type(call));
1156
1157         res_pred = xmalloc(n_res * sizeof(*res_pred));
1158         cf_pred  = xmalloc(arity * sizeof(*res_pred));
1159
1160         set_irg_current_block(current_ir_graph, post_bl); /* just to make sure */
1161
1162         /* -- archive keepalives -- */
1163         irn_arity = get_irn_arity(end);
1164         for (i = 0; i < irn_arity; i++) {
1165                 ir_node *ka = get_End_keepalive(end, i);
1166                 if (! is_Bad(ka))
1167                         add_End_keepalive(get_irg_end(current_ir_graph), ka);
1168         }
1169
1170         /* The new end node will die.  We need not free as the in array is on the obstack:
1171            copy_node() only generated 'D' arrays. */
1172
1173         /* -- Replace Return nodes by Jump nodes. -- */
1174         n_ret = 0;
1175         for (i = 0; i < arity; i++) {
1176                 ir_node *ret;
1177                 ret = get_irn_n(end_bl, i);
1178                 if (is_Return(ret)) {
1179                         cf_pred[n_ret] = new_r_Jmp(current_ir_graph, get_nodes_block(ret));
1180                         n_ret++;
1181                 }
1182         }
1183         set_irn_in(post_bl, n_ret, cf_pred);
1184
1185         /* -- Build a Tuple for all results of the method.
1186            Add Phi node if there was more than one Return.  -- */
1187         turn_into_tuple(post_call, pn_Call_max);
1188         /* First the Memory-Phi */
1189         n_ret = 0;
1190         for (i = 0; i < arity; i++) {
1191                 ret = get_irn_n(end_bl, i);
1192                 if (is_Return(ret)) {
1193                         cf_pred[n_ret] = get_Return_mem(ret);
1194                         n_ret++;
1195                 }
1196         }
1197         phi = new_Phi(n_ret, cf_pred, mode_M);
1198         set_Tuple_pred(call, pn_Call_M_regular, phi);
1199         /* Conserve Phi-list for further inlinings -- but might be optimized */
1200         if (get_nodes_block(phi) == post_bl) {
1201                 set_irn_link(phi, get_irn_link(post_bl));
1202                 set_irn_link(post_bl, phi);
1203         }
1204         /* Now the real results */
1205         if (n_res > 0) {
1206                 for (j = 0; j < n_res; j++) {
1207                         n_ret = 0;
1208                         for (i = 0; i < arity; i++) {
1209                                 ret = get_irn_n(end_bl, i);
1210                                 if (is_Return(ret)) {
1211                                         cf_pred[n_ret] = get_Return_res(ret, j);
1212                                         n_ret++;
1213                                 }
1214                         }
1215                         if (n_ret > 0)
1216                                 phi = new_Phi(n_ret, cf_pred, get_irn_mode(cf_pred[0]));
1217                         else
1218                                 phi = new_Bad();
1219                         res_pred[j] = phi;
1220                         /* Conserve Phi-list for further inlinings -- but might be optimized */
1221                         if (get_nodes_block(phi) == post_bl) {
1222                                 set_Phi_next(phi, get_Block_phis(post_bl));
1223                                 set_Block_phis(post_bl, phi);
1224                         }
1225                 }
1226                 set_Tuple_pred(call, pn_Call_T_result, new_Tuple(n_res, res_pred));
1227         } else {
1228                 set_Tuple_pred(call, pn_Call_T_result, new_Bad());
1229         }
1230         /* handle the regular call */
1231         set_Tuple_pred(call, pn_Call_X_regular, new_Jmp());
1232
1233         /* For now, we cannot inline calls with value_base */
1234         set_Tuple_pred(call, pn_Call_P_value_res_base, new_Bad());
1235
1236         /* Finally the exception control flow.
1237            We have two (three) possible situations:
1238            First if the Call branches to an exception handler: We need to add a Phi node to
1239            collect the memory containing the exception objects.  Further we need
1240            to add another block to get a correct representation of this Phi.  To
1241            this block we add a Jmp that resolves into the X output of the Call
1242            when the Call is turned into a tuple.
1243            Second the Call branches to End, the exception is not handled.  Just
1244            add all inlined exception branches to the End node.
1245            Third: there is no Exception edge at all. Handle as case two. */
1246         if (exc_handling == exc_handler) {
1247                 n_exc = 0;
1248                 for (i = 0; i < arity; i++) {
1249                         ir_node *ret, *irn;
1250                         ret = get_irn_n(end_bl, i);
1251                         irn = skip_Proj(ret);
1252                         if (is_fragile_op(irn) || is_Raise(irn)) {
1253                                 cf_pred[n_exc] = ret;
1254                                 ++n_exc;
1255                         }
1256                 }
1257                 if (n_exc > 0) {
1258                         new_Block(n_exc, cf_pred);      /* watch it: current_block is changed! */
1259                         set_Tuple_pred(call, pn_Call_X_except, new_Jmp());
1260                         /* The Phi for the memories with the exception objects */
1261                         n_exc = 0;
1262                         for (i = 0; i < arity; i++) {
1263                                 ir_node *ret;
1264                                 ret = skip_Proj(get_irn_n(end_bl, i));
1265                                 if (is_Call(ret)) {
1266                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 3);
1267                                         n_exc++;
1268                                 } else if (is_fragile_op(ret)) {
1269                                         /* We rely that all cfops have the memory output at the same position. */
1270                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 0);
1271                                         n_exc++;
1272                                 } else if (is_Raise(ret)) {
1273                                         cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_block(ret), ret, mode_M, 1);
1274                                         n_exc++;
1275                                 }
1276                         }
1277                         set_Tuple_pred(call, pn_Call_M_except, new_Phi(n_exc, cf_pred, mode_M));
1278                 } else {
1279                         set_Tuple_pred(call, pn_Call_X_except, new_Bad());
1280                         set_Tuple_pred(call, pn_Call_M_except, new_Bad());
1281                 }
1282         } else {
1283                 ir_node *main_end_bl;
1284                 int main_end_bl_arity;
1285                 ir_node **end_preds;
1286
1287                 /* assert(exc_handling == 1 || no exceptions. ) */
1288                 n_exc = 0;
1289                 for (i = 0; i < arity; i++) {
1290                         ir_node *ret = get_irn_n(end_bl, i);
1291                         ir_node *irn = skip_Proj(ret);
1292
1293                         if (is_fragile_op(irn) || is_Raise(irn)) {
1294                                 cf_pred[n_exc] = ret;
1295                                 n_exc++;
1296                         }
1297                 }
1298                 main_end_bl = get_irg_end_block(current_ir_graph);
1299                 main_end_bl_arity = get_irn_arity(main_end_bl);
1300                 end_preds =  xmalloc((n_exc + main_end_bl_arity) * sizeof(*end_preds));
1301
1302                 for (i = 0; i < main_end_bl_arity; ++i)
1303                         end_preds[i] = get_irn_n(main_end_bl, i);
1304                 for (i = 0; i < n_exc; ++i)
1305                         end_preds[main_end_bl_arity + i] = cf_pred[i];
1306                 set_irn_in(main_end_bl, n_exc + main_end_bl_arity, end_preds);
1307                 set_Tuple_pred(call, pn_Call_X_except,  new_Bad());
1308                 set_Tuple_pred(call, pn_Call_M_except,  new_Bad());
1309                 free(end_preds);
1310         }
1311         free(res_pred);
1312         free(cf_pred);
1313
1314         /* --  Turn CSE back on. -- */
1315         set_optimize(rem_opt);
1316
1317         return 1;
1318 }
1319
1320 /********************************************************************/
1321 /* Apply inlineing to small methods.                                */
1322 /********************************************************************/
1323
1324 /** Represents a possible inlinable call in a graph. */
1325 typedef struct _call_entry call_entry;
1326 struct _call_entry {
1327         ir_node    *call;   /**< the Call */
1328         ir_graph   *callee; /**< the callee called here */
1329         call_entry *next;   /**< for linking the next one */
1330         unsigned   weight;  /**< the weight of the call */
1331 };
1332
1333 /**
1334  * environment for inlining small irgs
1335  */
1336 typedef struct _inline_env_t {
1337         struct obstack obst;  /**< an obstack where call_entries are allocated on. */
1338         call_entry *head;     /**< the head of the call entry list */
1339         call_entry *tail;     /**< the tail of the call entry list */
1340 } inline_env_t;
1341
1342 /**
1343  * Returns the irg called from a Call node. If the irg is not
1344  * known, NULL is returned.
1345  *
1346  * @param call  the call node
1347  */
1348 static ir_graph *get_call_called_irg(ir_node *call) {
1349         ir_node *addr;
1350
1351         addr = get_Call_ptr(call);
1352         if (is_SymConst_addr_ent(addr)) {
1353                 ir_entity *ent = get_SymConst_entity(addr);
1354                 return get_entity_irg(ent);
1355         }
1356
1357         return NULL;
1358 }
1359
1360 /**
1361  * Walker: Collect all calls to known graphs inside a graph.
1362  */
1363 static void collect_calls(ir_node *call, void *env) {
1364         if (is_Call(call)) {
1365                 ir_graph *called_irg = get_call_called_irg(call);
1366
1367                 if (called_irg != NULL) {
1368                         /* The Call node calls a locally defined method.  Remember to inline. */
1369                         inline_env_t *ienv  = env;
1370                         call_entry   *entry = obstack_alloc(&ienv->obst, sizeof(*entry));
1371                         entry->call   = call;
1372                         entry->callee = called_irg;
1373                         entry->next   = NULL;
1374                         entry->weight = 0;
1375
1376                         if (ienv->tail == NULL)
1377                                 ienv->head = entry;
1378                         else
1379                                 ienv->tail->next = entry;
1380                         ienv->tail = entry;
1381                 }
1382         }
1383 }
1384
1385 /**
1386  * Inlines all small methods at call sites where the called address comes
1387  * from a Const node that references the entity representing the called
1388  * method.
1389  * The size argument is a rough measure for the code size of the method:
1390  * Methods where the obstack containing the firm graph is smaller than
1391  * size are inlined.
1392  */
1393 void inline_small_irgs(ir_graph *irg, int size) {
1394   ir_graph *rem = current_ir_graph;
1395         inline_env_t env;
1396         call_entry *entry;
1397         DEBUG_ONLY(firm_dbg_module_t *dbg;)
1398
1399         FIRM_DBG_REGISTER(dbg, "firm.opt.inline");
1400
1401         current_ir_graph = irg;
1402         /* Handle graph state */
1403         assert(get_irg_phase_state(irg) != phase_building);
1404         free_callee_info(irg);
1405
1406         /* Find Call nodes to inline.
1407            (We can not inline during a walk of the graph, as inlineing the same
1408            method several times changes the visited flag of the walked graph:
1409            after the first inlineing visited of the callee equals visited of
1410            the caller.  With the next inlineing both are increased.) */
1411         obstack_init(&env.obst);
1412         env.head = env.tail = NULL;
1413         irg_walk_graph(irg, NULL, collect_calls, &env);
1414
1415         if (env.head != NULL) {
1416                 /* There are calls to inline */
1417                 collect_phiprojs(irg);
1418                 for (entry = env.head; entry != NULL; entry = entry->next) {
1419                         ir_graph *callee = entry->callee;
1420                         if (((_obstack_memory_used(callee->obst) - (int)obstack_room(callee->obst)) < size) ||
1421                             (get_irg_inline_property(callee) >= irg_inline_forced)) {
1422                                 inline_method(entry->call, callee);
1423                         }
1424                 }
1425         }
1426         obstack_free(&env.obst, NULL);
1427         current_ir_graph = rem;
1428 }
1429
1430 /**
1431  * Environment for inlining irgs.
1432  */
1433 typedef struct {
1434   int n_nodes;             /**< Number of nodes in graph except Id, Tuple, Proj, Start, End. */
1435         int n_nodes_orig;        /**< for statistics */
1436         call_entry *call_head;   /**< The head of the list of all call nodes in this graph. */
1437         call_entry *call_tail;   /**< The tail of the list of all call nodes in this graph .*/
1438         int n_call_nodes;        /**< Number of Call nodes in the graph. */
1439         int n_call_nodes_orig;   /**< for statistics */
1440         int n_callers;           /**< Number of known graphs that call this graphs. */
1441         int n_callers_orig;      /**< for statistics */
1442         int got_inline;          /**< Set, if at leat one call inside this graph was inlined. */
1443 } inline_irg_env;
1444
1445 /**
1446  * Allocate a new environment for inlining.
1447  */
1448 static inline_irg_env *alloc_inline_irg_env(struct obstack *obst) {
1449         inline_irg_env *env    = obstack_alloc(obst, sizeof(*env));
1450         env->n_nodes           = -2; /* do not count count Start, End */
1451         env->n_nodes_orig      = -2; /* do not count Start, End */
1452         env->call_head         = NULL;
1453         env->call_tail         = NULL;
1454         env->n_call_nodes      = 0;
1455         env->n_call_nodes_orig = 0;
1456         env->n_callers         = 0;
1457         env->n_callers_orig    = 0;
1458         env->got_inline        = 0;
1459         return env;
1460 }
1461
1462 typedef struct walker_env {
1463         struct obstack *obst; /**< the obstack for allocations. */
1464         inline_irg_env *x;    /**< the inline environment */
1465         char ignore_runtime;  /**< the ignore runtime flag */
1466         char ignore_callers;  /**< if set, do change callers data */
1467 } wenv_t;
1468
1469 /**
1470  * post-walker: collect all calls in the inline-environment
1471  * of a graph and sum some statistics.
1472  */
1473 static void collect_calls2(ir_node *call, void *ctx) {
1474         wenv_t         *env = ctx;
1475         inline_irg_env *x = env->x;
1476         ir_opcode      code = get_irn_opcode(call);
1477         ir_graph       *callee;
1478         call_entry     *entry;
1479
1480         /* count meaningful nodes in irg */
1481         if (code != iro_Proj && code != iro_Tuple && code != iro_Sync) {
1482                 ++x->n_nodes;
1483                 ++x->n_nodes_orig;
1484         }
1485
1486         if (code != iro_Call) return;
1487
1488         /* check, if it's a runtime call */
1489         if (env->ignore_runtime) {
1490                 ir_node *symc = get_Call_ptr(call);
1491
1492                 if (is_SymConst_addr_ent(symc)) {
1493                         ir_entity *ent = get_SymConst_entity(symc);
1494
1495                         if (get_entity_additional_properties(ent) & mtp_property_runtime)
1496                                 return;
1497                 }
1498         }
1499
1500         /* collect all call nodes */
1501         ++x->n_call_nodes;
1502         ++x->n_call_nodes_orig;
1503
1504         callee = get_call_called_irg(call);
1505         if (callee != NULL) {
1506                 if (! env->ignore_callers) {
1507                         inline_irg_env *callee_env = get_irg_link(callee);
1508                         /* count all static callers */
1509                         ++callee_env->n_callers;
1510                         ++callee_env->n_callers_orig;
1511                 }
1512
1513                 /* link it in the list of possible inlinable entries */
1514                 entry = obstack_alloc(env->obst, sizeof(*entry));
1515                 entry->call   = call;
1516                 entry->callee = callee;
1517                 entry->next   = NULL;
1518                 if (x->call_tail == NULL)
1519                         x->call_head = entry;
1520                 else
1521                         x->call_tail->next = entry;
1522                 x->call_tail = entry;
1523         }
1524 }
1525
1526 /**
1527  * Returns TRUE if the number of callers is 0 in the irg's environment,
1528  * hence this irg is a leave.
1529  */
1530 INLINE static int is_leave(ir_graph *irg) {
1531         inline_irg_env *env = get_irg_link(irg);
1532         return env->n_call_nodes == 0;
1533 }
1534
1535 /**
1536  * Returns TRUE if the number of nodes in the callee is
1537  * smaller then size in the irg's environment.
1538  */
1539 INLINE static int is_smaller(ir_graph *callee, int size) {
1540         inline_irg_env *env = get_irg_link(callee);
1541         return env->n_nodes < size;
1542 }
1543
1544 /**
1545  * Append the nodes of the list src to the nodes of the list in environment dst.
1546  */
1547 static void append_call_list(struct obstack *obst, inline_irg_env *dst, call_entry *src) {
1548         call_entry *entry, *nentry;
1549
1550         /* Note that the src list points to Call nodes in the inlined graph, but
1551            we need Call nodes in our graph. Luckily the inliner leaves this information
1552            in the link field. */
1553         for (entry = src; entry != NULL; entry = entry->next) {
1554                 nentry = obstack_alloc(obst, sizeof(*nentry));
1555                 nentry->call   = get_irn_link(entry->call);
1556                 nentry->callee = entry->callee;
1557                 nentry->next   = NULL;
1558                 dst->call_tail->next = nentry;
1559                 dst->call_tail       = nentry;
1560         }
1561 }
1562
1563 /*
1564  * Inlines small leave methods at call sites where the called address comes
1565  * from a Const node that references the entity representing the called
1566  * method.
1567  * The size argument is a rough measure for the code size of the method:
1568  * Methods where the obstack containing the firm graph is smaller than
1569  * size are inlined.
1570  */
1571 void inline_leave_functions(int maxsize, int leavesize, int size, int ignore_runtime) {
1572         inline_irg_env   *env;
1573         ir_graph         *irg;
1574         int              i, n_irgs;
1575         ir_graph         *rem;
1576         int              did_inline;
1577         wenv_t           wenv;
1578         call_entry       *entry, *tail;
1579         const call_entry *centry;
1580         struct obstack   obst;
1581         pmap             *copied_graphs;
1582         pmap_entry       *pm_entry;
1583         DEBUG_ONLY(firm_dbg_module_t *dbg;)
1584
1585         FIRM_DBG_REGISTER(dbg, "firm.opt.inline");
1586         rem = current_ir_graph;
1587         obstack_init(&obst);
1588
1589         /* a map for the copied graphs, used to inline recursive calls */
1590         copied_graphs = pmap_create();
1591
1592         /* extend all irgs by a temporary data structure for inlining. */
1593         n_irgs = get_irp_n_irgs();
1594         for (i = 0; i < n_irgs; ++i)
1595                 set_irg_link(get_irp_irg(i), alloc_inline_irg_env(&obst));
1596
1597         /* Precompute information in temporary data structure. */
1598         wenv.obst           = &obst;
1599         wenv.ignore_runtime = ignore_runtime;
1600         wenv.ignore_callers = 0;
1601         for (i = 0; i < n_irgs; ++i) {
1602                 ir_graph *irg = get_irp_irg(i);
1603
1604                 assert(get_irg_phase_state(irg) != phase_building);
1605                 free_callee_info(irg);
1606
1607                 wenv.x = get_irg_link(irg);
1608                 irg_walk_graph(irg, NULL, collect_calls2, &wenv);
1609         }
1610
1611         /* -- and now inline. -- */
1612
1613         /* Inline leaves recursively -- we might construct new leaves. */
1614         do {
1615                 did_inline = 0;
1616
1617                 for (i = 0; i < n_irgs; ++i) {
1618                         ir_node *call;
1619                         int phiproj_computed = 0;
1620
1621                         current_ir_graph = get_irp_irg(i);
1622                         env = (inline_irg_env *)get_irg_link(current_ir_graph);
1623
1624                         tail = NULL;
1625                         for (entry = env->call_head; entry != NULL; entry = entry->next) {
1626                                 ir_graph *callee;
1627
1628                                 if (env->n_nodes > maxsize) break;
1629
1630                                 call   = entry->call;
1631                                 callee = entry->callee;
1632
1633                                 if (is_leave(callee) && (
1634                                     is_smaller(callee, leavesize) || (get_irg_inline_property(callee) >= irg_inline_forced))) {
1635                                         if (!phiproj_computed) {
1636                                                 phiproj_computed = 1;
1637                                                 collect_phiprojs(current_ir_graph);
1638                                         }
1639                                         did_inline = inline_method(call, callee);
1640
1641                                         if (did_inline) {
1642                                                 inline_irg_env *callee_env = (inline_irg_env *)get_irg_link(callee);
1643
1644                                                 /* was inlined, must be recomputed */
1645                                                 phiproj_computed = 0;
1646
1647                                                 /* Do some statistics */
1648                                                 env->got_inline = 1;
1649                                                 --env->n_call_nodes;
1650                                                 env->n_nodes += callee_env->n_nodes;
1651                                                 --callee_env->n_callers;
1652
1653                                                 /* remove this call from the list */
1654                                                 if (tail != NULL)
1655                                                         tail->next = entry->next;
1656                                                 else
1657                                                         env->call_head = entry->next;
1658                                                 continue;
1659                                         }
1660                                 }
1661                                 tail = entry;
1662                         }
1663                         env->call_tail = tail;
1664                 }
1665         } while (did_inline);
1666
1667         /* inline other small functions. */
1668         for (i = 0; i < n_irgs; ++i) {
1669                 ir_node *call;
1670                 int phiproj_computed = 0;
1671
1672                 current_ir_graph = get_irp_irg(i);
1673                 env = (inline_irg_env *)get_irg_link(current_ir_graph);
1674
1675                 /* note that the list of possible calls is updated during the process */
1676                 tail = NULL;
1677                 for (entry = env->call_head; entry != NULL; entry = entry->next) {
1678                         ir_graph   *callee;
1679                         pmap_entry *e;
1680
1681                         call   = entry->call;
1682                         callee = entry->callee;
1683
1684                         e = pmap_find(copied_graphs, callee);
1685                         if (e != NULL) {
1686                                 /*
1687                                  * Remap callee if we have a copy.
1688                                  * FIXME: Should we do this only for recursive Calls ?
1689                                  */
1690                                 callee = e->value;
1691                         }
1692
1693                         if (((is_smaller(callee, size) && (env->n_nodes < maxsize)) ||    /* small function */
1694                                 (get_irg_inline_property(callee) >= irg_inline_forced))) {
1695                                 if (current_ir_graph == callee) {
1696                                         /*
1697                                          * Recursive call: we cannot directly inline because we cannot walk
1698                                          * the graph and change it. So we have to make a copy of the graph
1699                                          * first.
1700                                          */
1701
1702                                         inline_irg_env *callee_env;
1703                                         ir_graph       *copy;
1704
1705                                         /*
1706                                          * No copy yet, create one.
1707                                          * Note that recursive methods are never leaves, so it is sufficient
1708                                          * to test this condition here.
1709                                          */
1710                                         copy = create_irg_copy(callee);
1711
1712                                         /* create_irg_copy() destroys the Proj links, recompute them */
1713                                         phiproj_computed = 0;
1714
1715                                         /* allocate new environment */
1716                                         callee_env = alloc_inline_irg_env(&obst);
1717                                         set_irg_link(copy, callee_env);
1718
1719                                         wenv.x              = callee_env;
1720                                         wenv.ignore_callers = 1;
1721                                         irg_walk_graph(copy, NULL, collect_calls2, &wenv);
1722
1723                                         /*
1724                                          * Enter the entity of the original graph. This is needed
1725                                          * for inline_method(). However, note that ent->irg still points
1726                                          * to callee, NOT to copy.
1727                                          */
1728                                         set_irg_entity(copy, get_irg_entity(callee));
1729
1730                                         pmap_insert(copied_graphs, callee, copy);
1731                                         callee = copy;
1732
1733                                         /* we have only one caller: the original graph */
1734                                         callee_env->n_callers      = 1;
1735                                         callee_env->n_callers_orig = 1;
1736                                 }
1737                                 if (! phiproj_computed) {
1738                                         phiproj_computed = 1;
1739                                         collect_phiprojs(current_ir_graph);
1740                                 }
1741                                 did_inline = inline_method(call, callee);
1742                                 if (did_inline) {
1743                                         inline_irg_env *callee_env = (inline_irg_env *)get_irg_link(callee);
1744
1745                                         /* was inlined, must be recomputed */
1746                                         phiproj_computed = 0;
1747
1748                                         /* callee was inline. Append it's call list. */
1749                                         env->got_inline = 1;
1750                                         --env->n_call_nodes;
1751                                         append_call_list(&obst, env, callee_env->call_head);
1752                                         env->n_call_nodes += callee_env->n_call_nodes;
1753                                         env->n_nodes += callee_env->n_nodes;
1754                                         --callee_env->n_callers;
1755
1756                                         /* after we have inlined callee, all called methods inside callee
1757                                            are now called once more */
1758                                         for (centry = callee_env->call_head; centry != NULL; centry = centry->next) {
1759                                                 inline_irg_env *penv = get_irg_link(centry->callee);
1760                                                 ++penv->n_callers;
1761                                         }
1762
1763                                         /* remove this call from the list */
1764                                         if (tail != NULL)
1765                                                 tail->next = entry->next;
1766                                         else
1767                                                 env->call_head = entry->next;
1768                                         continue;
1769                                 }
1770                         }
1771                         tail = entry;
1772                 }
1773                 env->call_tail = tail;
1774         }
1775
1776         for (i = 0; i < n_irgs; ++i) {
1777                 irg = get_irp_irg(i);
1778                 env = (inline_irg_env *)get_irg_link(irg);
1779
1780                 if (env->got_inline) {
1781                         /* this irg got calls inlined */
1782                         set_irg_outs_inconsistent(irg);
1783                         set_irg_doms_inconsistent(irg);
1784
1785                         optimize_graph_df(irg);
1786                         optimize_cf(irg);
1787                 }
1788                 if (env->got_inline || (env->n_callers_orig != env->n_callers)) {
1789                         DB((dbg, SET_LEVEL_1, "Nodes:%3d ->%3d, calls:%3d ->%3d, callers:%3d ->%3d, -- %s\n",
1790                         env->n_nodes_orig, env->n_nodes, env->n_call_nodes_orig, env->n_call_nodes,
1791                         env->n_callers_orig, env->n_callers,
1792                         get_entity_name(get_irg_entity(irg))));
1793                 }
1794         }
1795
1796         /* kill the copied graphs: we don't need them anymore */
1797         foreach_pmap(copied_graphs, pm_entry) {
1798                 ir_graph *copy = pm_entry->value;
1799
1800                 /* reset the entity, otherwise it will be deleted in the next step ... */
1801                 set_irg_entity(copy, NULL);
1802                 free_ir_graph(copy);
1803         }
1804         pmap_destroy(copied_graphs);
1805
1806         obstack_free(&obst, NULL);
1807         current_ir_graph = rem;
1808 }
1809
1810 /*******************************************************************/
1811 /*  Code Placement.  Pins all floating nodes to a block where they */
1812 /*  will be executed only if needed.                               */
1813 /*******************************************************************/
1814
1815 /**
1816  * Returns non-zero, is a block is not reachable from Start.
1817  *
1818  * @param block  the block to test
1819  */
1820 static int
1821 is_Block_unreachable(ir_node *block) {
1822         return is_Block_dead(block) || get_Block_dom_depth(block) < 0;
1823 }
1824
1825 /**
1826  * Find the earliest correct block for node n.  --- Place n into the
1827  * same Block as its dominance-deepest Input.
1828  *
1829  * We have to avoid calls to get_nodes_block() here
1830  * because the graph is floating.
1831  *
1832  * move_out_of_loops() expects that place_floats_early() have placed
1833  * all "living" nodes into a living block. That's why we must
1834  * move nodes in dead block with "live" successors into a valid
1835  * block.
1836  * We move them just into the same block as it's successor (or
1837  * in case of a Phi into the effective use block). For Phi successors,
1838  * this may still be a dead block, but then there is no real use, as
1839  * the control flow will be dead later.
1840  *
1841  * @param n         the node to be placed
1842  * @param worklist  a worklist, predecessors of non-floating nodes are placed here
1843  */
1844 static void
1845 place_floats_early(ir_node *n, waitq *worklist) {
1846         int i, irn_arity;
1847
1848         /* we must not run into an infinite loop */
1849         assert(irn_not_visited(n));
1850         mark_irn_visited(n);
1851
1852         /* Place floating nodes. */
1853         if (get_irn_pinned(n) == op_pin_state_floats) {
1854                 ir_node *curr_block = get_nodes_block(n);
1855                 int in_dead_block   = is_Block_unreachable(curr_block);
1856                 int depth           = 0;
1857                 ir_node *b          = NULL;   /* The block to place this node in */
1858
1859                 assert(is_no_Block(n));
1860
1861                 if (is_irn_start_block_placed(n)) {
1862                         /* These nodes will not be placed by the loop below. */
1863                         b = get_irg_start_block(current_ir_graph);
1864                         depth = 1;
1865                 }
1866
1867                 /* find the block for this node. */
1868                 irn_arity = get_irn_arity(n);
1869                 for (i = 0; i < irn_arity; i++) {
1870                         ir_node *pred = get_irn_n(n, i);
1871                         ir_node *pred_block;
1872
1873                         if ((irn_not_visited(pred))
1874                             && (get_irn_pinned(pred) == op_pin_state_floats)) {
1875
1876                                 /*
1877                                  * If the current node is NOT in a dead block, but one of its
1878                                  * predecessors is, we must move the predecessor to a live block.
1879                                  * Such thing can happen, if global CSE chose a node from a dead block.
1880                                  * We move it simply to our block.
1881                                  * Note that neither Phi nor End nodes are floating, so we don't
1882                                  * need to handle them here.
1883                                  */
1884                                 if (! in_dead_block) {
1885                                         if (get_irn_pinned(pred) == op_pin_state_floats &&
1886                                                 is_Block_unreachable(get_nodes_block(pred)))
1887                                                 set_nodes_block(pred, curr_block);
1888                                 }
1889                                 place_floats_early(pred, worklist);
1890                         }
1891
1892                         /*
1893                          * A node in the Bad block must stay in the bad block,
1894                          * so don't compute a new block for it.
1895                          */
1896                         if (in_dead_block)
1897                                 continue;
1898
1899                         /* Because all loops contain at least one op_pin_state_pinned node, now all
1900                            our inputs are either op_pin_state_pinned or place_early() has already
1901                            been finished on them.  We do not have any unfinished inputs!  */
1902                         pred_block = get_nodes_block(pred);
1903                         if ((!is_Block_dead(pred_block)) &&
1904                                 (get_Block_dom_depth(pred_block) > depth)) {
1905                                 b = pred_block;
1906                                 depth = get_Block_dom_depth(pred_block);
1907                         }
1908                         /* Avoid that the node is placed in the Start block */
1909                         if (depth == 1 &&
1910                                         get_Block_dom_depth(get_nodes_block(n)) > 1 &&
1911                                         get_irg_phase_state(current_ir_graph) != phase_backend) {
1912                                 b = get_Block_cfg_out(get_irg_start_block(current_ir_graph), 0);
1913                                 assert(b != get_irg_start_block(current_ir_graph));
1914                                 depth = 2;
1915                         }
1916                 }
1917                 if (b)
1918                         set_nodes_block(n, b);
1919         }
1920
1921         /*
1922          * Add predecessors of non floating nodes and non-floating predecessors
1923          * of floating nodes to worklist and fix their blocks if the are in dead block.
1924          */
1925         irn_arity = get_irn_arity(n);
1926
1927         if (is_End(n)) {
1928                 /*
1929                  * Simplest case: End node. Predecessors are keep-alives,
1930                  * no need to move out of dead block.
1931                  */
1932                 for (i = -1; i < irn_arity; ++i) {
1933                         ir_node *pred = get_irn_n(n, i);
1934                         if (irn_not_visited(pred))
1935                                 waitq_put(worklist, pred);
1936                 }
1937         } else if (is_Block(n)) {
1938                 /*
1939                  * Blocks: Predecessors are control flow, no need to move
1940                  * them out of dead block.
1941                  */
1942                 for (i = irn_arity - 1; i >= 0; --i) {
1943                         ir_node *pred = get_irn_n(n, i);
1944                         if (irn_not_visited(pred))
1945                                 waitq_put(worklist, pred);
1946                 }
1947         } else if (is_Phi(n)) {
1948                 ir_node *pred;
1949                 ir_node *curr_block = get_nodes_block(n);
1950                 int in_dead_block   = is_Block_unreachable(curr_block);
1951
1952                 /*
1953                  * Phi nodes: move nodes from dead blocks into the effective use
1954                  * of the Phi-input if the Phi is not in a bad block.
1955                  */
1956                 pred = get_nodes_block(n);
1957                 if (irn_not_visited(pred))
1958                         waitq_put(worklist, pred);
1959
1960                 for (i = irn_arity - 1; i >= 0; --i) {
1961                         ir_node *pred = get_irn_n(n, i);
1962
1963                         if (irn_not_visited(pred)) {
1964                                 if (! in_dead_block &&
1965                                         get_irn_pinned(pred) == op_pin_state_floats &&
1966                                         is_Block_unreachable(get_nodes_block(pred))) {
1967                                         set_nodes_block(pred, get_Block_cfgpred_block(curr_block, i));
1968                                 }
1969                                 waitq_put(worklist, pred);
1970                         }
1971                 }
1972         } else {
1973                 ir_node *pred;
1974                 ir_node *curr_block = get_nodes_block(n);
1975                 int in_dead_block   = is_Block_unreachable(curr_block);
1976
1977                 /*
1978                  * All other nodes: move nodes from dead blocks into the same block.
1979                  */
1980                 pred = get_nodes_block(n);
1981                 if (irn_not_visited(pred))
1982                         waitq_put(worklist, pred);
1983
1984                 for (i = irn_arity - 1; i >= 0; --i) {
1985                         ir_node *pred = get_irn_n(n, i);
1986
1987                         if (irn_not_visited(pred)) {
1988                                 if (! in_dead_block &&
1989                                         get_irn_pinned(pred) == op_pin_state_floats &&
1990                                         is_Block_unreachable(get_nodes_block(pred))) {
1991                                         set_nodes_block(pred, curr_block);
1992                                 }
1993                                 waitq_put(worklist, pred);
1994                         }
1995                 }
1996         }
1997 }
1998
1999 /**
2000  * Floating nodes form subgraphs that begin at nodes as Const, Load,
2001  * Start, Call and that end at op_pin_state_pinned nodes as Store, Call.  Place_early
2002  * places all floating nodes reachable from its argument through floating
2003  * nodes and adds all beginnings at op_pin_state_pinned nodes to the worklist.
2004  *
2005  * @param worklist   a worklist, used for the algorithm, empty on in/output
2006  */
2007 static void place_early(waitq *worklist) {
2008         assert(worklist);
2009         inc_irg_visited(current_ir_graph);
2010
2011         /* this inits the worklist */
2012         place_floats_early(get_irg_end(current_ir_graph), worklist);
2013
2014         /* Work the content of the worklist. */
2015         while (!waitq_empty(worklist)) {
2016                 ir_node *n = waitq_get(worklist);
2017                 if (irn_not_visited(n))
2018                         place_floats_early(n, worklist);
2019         }
2020
2021         set_irg_outs_inconsistent(current_ir_graph);
2022         set_irg_pinned(current_ir_graph, op_pin_state_pinned);
2023 }
2024
2025 /**
2026  * Compute the deepest common ancestor of block and dca.
2027  */
2028 static ir_node *calc_dca(ir_node *dca, ir_node *block) {
2029         assert(block);
2030
2031         /* we do not want to place nodes in dead blocks */
2032         if (is_Block_dead(block))
2033                 return dca;
2034
2035         /* We found a first legal placement. */
2036         if (!dca) return block;
2037
2038         /* Find a placement that is dominates both, dca and block. */
2039         while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
2040                 block = get_Block_idom(block);
2041
2042         while (get_Block_dom_depth(dca) > get_Block_dom_depth(block)) {
2043                 dca = get_Block_idom(dca);
2044         }
2045
2046         while (block != dca) {
2047                 block = get_Block_idom(block); dca = get_Block_idom(dca);
2048         }
2049
2050         return dca;
2051 }
2052
2053 /** Deepest common dominance ancestor of DCA and CONSUMER of PRODUCER.
2054  * I.e., DCA is the block where we might place PRODUCER.
2055  * A data flow edge points from producer to consumer.
2056  */
2057 static ir_node *consumer_dom_dca(ir_node *dca, ir_node *consumer, ir_node *producer)
2058 {
2059         /* Compute the last block into which we can place a node so that it is
2060            before consumer. */
2061         if (is_Phi(consumer)) {
2062                 /* our consumer is a Phi-node, the effective use is in all those
2063                    blocks through which the Phi-node reaches producer */
2064                 ir_node *phi_block = get_nodes_block(consumer);
2065                 int      arity     = get_irn_arity(consumer);
2066                 int      i;
2067
2068                 for (i = 0;  i < arity; i++) {
2069                         if (get_Phi_pred(consumer, i) == producer) {
2070                                 ir_node *new_block = get_Block_cfgpred_block(phi_block, i);
2071
2072                                 if (!is_Block_unreachable(new_block))
2073                                         dca = calc_dca(dca, new_block);
2074                         }
2075                 }
2076         } else {
2077                 dca = calc_dca(dca, get_nodes_block(consumer));
2078         }
2079
2080         return dca;
2081 }
2082
2083 /* FIXME: the name clashes here with the function from ana/field_temperature.c
2084  * please rename. */
2085 static INLINE int get_irn_loop_depth(ir_node *n) {
2086         return get_loop_depth(get_irn_loop(n));
2087 }
2088
2089 /**
2090  * Move n to a block with less loop depth than it's current block. The
2091  * new block must be dominated by early.
2092  *
2093  * @param n      the node that should be moved
2094  * @param early  the earliest block we can n move to
2095  */
2096 static void move_out_of_loops(ir_node *n, ir_node *early) {
2097         ir_node *best, *dca;
2098         assert(n && early);
2099
2100
2101         /* Find the region deepest in the dominator tree dominating
2102            dca with the least loop nesting depth, but still dominated
2103            by our early placement. */
2104         dca = get_nodes_block(n);
2105
2106         best = dca;
2107         while (dca != early) {
2108                 dca = get_Block_idom(dca);
2109                 if (!dca || is_Bad(dca)) break; /* may be Bad if not reachable from Start */
2110                 if (get_irn_loop_depth(dca) < get_irn_loop_depth(best)) {
2111                         best = dca;
2112                 }
2113         }
2114         if (best != get_nodes_block(n)) {
2115                 /* debug output
2116                 printf("Moving out of loop: "); DDMN(n);
2117                 printf(" Outermost block: "); DDMN(early);
2118                 printf(" Best block: "); DDMN(best);
2119                 printf(" Innermost block: "); DDMN(get_nodes_block(n));
2120                 */
2121                 set_nodes_block(n, best);
2122         }
2123 }
2124
2125 /* deepest common ancestor in the dominator tree of all nodes'
2126    blocks depending on us; our final placement has to dominate DCA. */
2127 static ir_node *get_deepest_common_ancestor(ir_node *node, ir_node *dca)
2128 {
2129         int i;
2130
2131         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
2132                 ir_node *succ = get_irn_out(node, i);
2133
2134                 if (is_End(succ)) {
2135                         /*
2136                          * This consumer is the End node, a keep alive edge.
2137                          * This is not a real consumer, so we ignore it
2138                          */
2139                         continue;
2140                 }
2141
2142                 if (is_Proj(succ)) {
2143                         dca = get_deepest_common_ancestor(succ, dca);
2144                 } else {
2145                         /* ignore if succ is in dead code */
2146                         ir_node *succ_blk = get_nodes_block(succ);
2147                         if (is_Block_unreachable(succ_blk))
2148                                 continue;
2149                         dca = consumer_dom_dca(dca, succ, node);
2150                 }
2151         }
2152
2153         return dca;
2154 }
2155
2156 static void set_projs_block(ir_node *node, ir_node *block)
2157 {
2158         int i;
2159
2160         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
2161                 ir_node *succ = get_irn_out(node, i);
2162
2163                 assert(is_Proj(succ));
2164
2165                 if(get_irn_mode(succ) == mode_T) {
2166                         set_projs_block(succ, block);
2167                 }
2168                 set_nodes_block(succ, block);
2169         }
2170 }
2171
2172 /**
2173  * Find the latest legal block for N and place N into the
2174  * `optimal' Block between the latest and earliest legal block.
2175  * The `optimal' block is the dominance-deepest block of those
2176  * with the least loop-nesting-depth.  This places N out of as many
2177  * loops as possible and then makes it as control dependent as
2178  * possible.
2179  *
2180  * @param n         the node to be placed
2181  * @param worklist  a worklist, all successors of non-floating nodes are
2182  *                  placed here
2183  */
2184 static void place_floats_late(ir_node *n, pdeq *worklist) {
2185   int i;
2186         ir_node *early_blk;
2187
2188         assert(irn_not_visited(n)); /* no multiple placement */
2189
2190         mark_irn_visited(n);
2191
2192         /* no need to place block nodes, control nodes are already placed. */
2193         if (!is_Block(n) &&
2194             (!is_cfop(n)) &&
2195             (get_irn_mode(n) != mode_X)) {
2196                 /* Remember the early_blk placement of this block to move it
2197                    out of loop no further than the early_blk placement. */
2198                 early_blk = get_nodes_block(n);
2199
2200                 /*
2201                  * BEWARE: Here we also get code, that is live, but
2202                  * was in a dead block.  If the node is life, but because
2203                  * of CSE in a dead block, we still might need it.
2204                  */
2205
2206                 /* Assure that our users are all placed, except the Phi-nodes.
2207                 --- Each data flow cycle contains at least one Phi-node.  We
2208                     have to break the `user has to be placed before the
2209                     producer' dependence cycle and the Phi-nodes are the
2210                     place to do so, because we need to base our placement on the
2211                     final region of our users, which is OK with Phi-nodes, as they
2212                     are op_pin_state_pinned, and they never have to be placed after a
2213                     producer of one of their inputs in the same block anyway. */
2214                 for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
2215                         ir_node *succ = get_irn_out(n, i);
2216                         if (irn_not_visited(succ) && !is_Phi(succ))
2217                                 place_floats_late(succ, worklist);
2218                 }
2219
2220                 if (! is_Block_dead(early_blk)) {
2221                         /* do only move things that where not dead */
2222                         ir_op *op = get_irn_op(n);
2223
2224                         /* We have to determine the final block of this node... except for
2225                            constants and Projs */
2226                         if ((get_irn_pinned(n) == op_pin_state_floats) &&
2227                             (op != op_Const)    &&
2228                             (op != op_SymConst) &&
2229                             (op != op_Proj))
2230                         {
2231                                 /* deepest common ancestor in the dominator tree of all nodes'
2232                                    blocks depending on us; our final placement has to dominate
2233                                    DCA. */
2234                                 ir_node *dca = get_deepest_common_ancestor(n, NULL);
2235                                 if (dca != NULL) {
2236                                         set_nodes_block(n, dca);
2237                                         move_out_of_loops(n, early_blk);
2238                                         if(get_irn_mode(n) == mode_T) {
2239                                                 set_projs_block(n, get_nodes_block(n));
2240                                         }
2241                                 }
2242                         }
2243                 }
2244         }
2245
2246         /* Add successors of all non-floating nodes on list. (Those of floating
2247            nodes are placed already and therefore are marked.)  */
2248         for (i = 0; i < get_irn_n_outs(n); i++) {
2249                 ir_node *succ = get_irn_out(n, i);
2250                 if (irn_not_visited(get_irn_out(n, i))) {
2251                         pdeq_putr(worklist, succ);
2252                 }
2253         }
2254 }
2255
2256 /**
2257  * Place floating nodes on the given worklist as late as possible using
2258  * the dominance tree.
2259  *
2260  * @param worklist   the worklist containing the nodes to place
2261  */
2262 static void place_late(waitq *worklist) {
2263         assert(worklist);
2264         inc_irg_visited(current_ir_graph);
2265
2266         /* This fills the worklist initially. */
2267         place_floats_late(get_irg_start_block(current_ir_graph), worklist);
2268
2269         /* And now empty the worklist again... */
2270         while (!waitq_empty(worklist)) {
2271                 ir_node *n = waitq_get(worklist);
2272                 if (irn_not_visited(n))
2273                         place_floats_late(n, worklist);
2274         }
2275 }
2276
2277 /* Code Placement. */
2278 void place_code(ir_graph *irg) {
2279         waitq *worklist;
2280         ir_graph *rem = current_ir_graph;
2281
2282         current_ir_graph = irg;
2283
2284         /* Handle graph state */
2285         assert(get_irg_phase_state(irg) != phase_building);
2286         assure_doms(irg);
2287
2288         if (1 || get_irg_loopinfo_state(irg) != loopinfo_consistent) {
2289                 free_loop_information(irg);
2290                 construct_cf_backedges(irg);
2291         }
2292
2293         /* Place all floating nodes as early as possible. This guarantees
2294          a legal code placement. */
2295         worklist = new_waitq();
2296         place_early(worklist);
2297
2298         /* place_early() invalidates the outs, place_late needs them. */
2299         compute_irg_outs(irg);
2300
2301         /* Now move the nodes down in the dominator tree. This reduces the
2302            unnecessary executions of the node. */
2303         place_late(worklist);
2304
2305         set_irg_outs_inconsistent(current_ir_graph);
2306         set_irg_loopinfo_inconsistent(current_ir_graph);
2307         del_waitq(worklist);
2308         current_ir_graph = rem;
2309 }
2310
2311 typedef struct cf_env {
2312         char ignore_exc_edges; /**< set if exception edges should be ignored. */
2313         char changed;          /**< flag indicates that the cf graphs has changed. */
2314 } cf_env;
2315
2316 /**
2317  * Called by walker of remove_critical_cf_edges().
2318  *
2319  * Place an empty block to an edge between a blocks of multiple
2320  * predecessors and a block of multiple successors.
2321  *
2322  * @param n   IR node
2323  * @param env Environment of walker.
2324  */
2325 static void walk_critical_cf_edges(ir_node *n, void *env) {
2326         int arity, i;
2327         ir_node *pre, *block, *jmp;
2328         cf_env *cenv = env;
2329         ir_graph *irg = get_irn_irg(n);
2330
2331         /* Block has multiple predecessors */
2332         arity = get_irn_arity(n);
2333         if (arity > 1) {
2334                 if (n == get_irg_end_block(irg))
2335                         return;  /*  No use to add a block here.      */
2336
2337                 for (i = 0; i < arity; ++i) {
2338                         const ir_op *cfop;
2339
2340                         pre = get_irn_n(n, i);
2341                         /* don't count Bad's */
2342                         if (is_Bad(pre))
2343                                 continue;
2344
2345                         cfop = get_irn_op(skip_Proj(pre));
2346                         if (is_op_fragile(cfop)) {
2347                                 if (cenv->ignore_exc_edges && get_Proj_proj(pre) == pn_Generic_X_except)
2348                                         continue;
2349                                 goto insert;
2350                         }
2351                         /* we don't want place nodes in the start block, so handle it like forking */
2352                         if (is_op_forking(cfop) || cfop == op_Start) {
2353                                 /* Predecessor has multiple successors. Insert new control flow edge edges. */
2354 insert:
2355                                 /* set predecessor of new block */
2356                                 block = new_r_Block(irg, 1, &pre);
2357                                 /* insert new jmp node to new block */
2358                                 jmp = new_r_Jmp(irg, block);
2359                                 /* set successor of new block */
2360                                 set_irn_n(n, i, jmp);
2361                                 cenv->changed = 1;
2362                         } /* predecessor has multiple successors */
2363                 } /* for all predecessors */
2364         } /* n is a multi-entry block */
2365 }
2366
2367 void remove_critical_cf_edges(ir_graph *irg) {
2368         cf_env env;
2369
2370         env.ignore_exc_edges = 1;
2371         env.changed          = 0;
2372
2373         irg_block_walk_graph(irg, NULL, walk_critical_cf_edges, &env);
2374         if (env.changed) {
2375                 /* control flow changed */
2376                 set_irg_outs_inconsistent(irg);
2377                 set_irg_extblk_inconsistent(irg);
2378                 set_irg_doms_inconsistent(irg);
2379                 set_irg_loopinfo_inconsistent(irg);
2380         }
2381 }