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