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