Wrong var
[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
7  * Created:
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1998-2003 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13
14 #ifdef HAVE_CONFIG_H
15 # include <config.h>
16 #endif
17
18 # include <assert.h>
19 # include <stdbool.h>
20
21 # include "irprog.h"
22 # include "irgopt.h"
23 # include "irnode_t.h"
24 # include "irgraph_t.h"
25 # include "iropt_t.h"
26 # include "irgwalk.h"
27 # include "ircons.h"
28 # include "irgmod.h"
29 # include "array.h"
30 # include "pset.h"
31 # include "eset.h"
32 # include "pdeq.h"       /* Fuer code placement */
33 # include "irouts.h"
34 # include "irloop.h"
35 # include "irbackedge_t.h"
36 # include "irflag_t.h"
37
38 /* Defined in iropt.c */
39 pset *new_identities (void);
40 void  del_identities (pset *value_table);
41 void  add_identities   (pset *value_table, ir_node *node);
42
43 /********************************************************************/
44 /* apply optimizations of iropt to all nodes.                       */
45 /********************************************************************/
46
47 static void init_link (ir_node *n, void *env) {
48   set_irn_link(n, NULL);
49 }
50
51 #if 0   /* Old version. Avoids Ids.
52            This is not necessary:  we do a postwalk, and get_irn_n
53            removes ids anyways.  So it's much cheaper to call the
54            optimization less often and use the exchange() algorithm. */
55 static void
56 optimize_in_place_wrapper (ir_node *n, void *env) {
57   int i, irn_arity;
58   ir_node *optimized, *old;
59
60   irn_arity = get_irn_arity(n);
61   for (i = 0; i < irn_arity; i++) {
62     /* get_irn_n skips Id nodes, so comparison old != optimized does not
63        show all optimizations. Therefore always set new predecessor. */
64     old = get_irn_n(n, i);
65     optimized = optimize_in_place_2(old);
66     set_irn_n(n, i, optimized);
67   }
68
69   if (get_irn_op(n) == op_Block) {
70     optimized = optimize_in_place_2(n);
71     if (optimized != n) exchange (n, optimized);
72   }
73 }
74 #else
75 static void
76 optimize_in_place_wrapper (ir_node *n, void *env) {
77   ir_node *optimized = optimize_in_place_2(n);
78   if (optimized != n) exchange (n, optimized);
79 }
80 #endif
81
82
83
84 void
85 local_optimize_graph (ir_graph *irg) {
86   ir_graph *rem = current_ir_graph;
87   current_ir_graph = irg;
88
89   /* Handle graph state */
90   assert(get_irg_phase_state(irg) != phase_building);
91   if (get_opt_global_cse())
92     set_irg_pinned(current_ir_graph, floats);
93   if (get_irg_outs_state(current_ir_graph) == outs_consistent)
94     set_irg_outs_inconsistent(current_ir_graph);
95   if (get_irg_dom_state(current_ir_graph) == dom_consistent)
96     set_irg_dom_inconsistent(current_ir_graph);
97
98   /* Clean the value_table in irg for the cse. */
99   del_identities(irg->value_table);
100   irg->value_table = new_identities();
101
102   /* walk over the graph */
103   irg_walk(irg->end, init_link, optimize_in_place_wrapper, NULL);
104
105   current_ir_graph = rem;
106 }
107
108 /********************************************************************/
109 /* Routines for dead node elimination / copying garbage collection  */
110 /* of the obstack.                                                  */
111 /********************************************************************/
112
113 /* Remeber the new node in the old node by using a field all nodes have. */
114 static INLINE void
115 set_new_node (ir_node *old, ir_node *new)
116 {
117   old->link = new;
118 }
119
120 /* Get this new node, before the old node is forgotton.*/
121 static INLINE ir_node *
122 get_new_node (ir_node * n)
123 {
124   return n->link;
125 }
126
127 /* We use the block_visited flag to mark that we have computed the
128    number of useful predecessors for this block.
129    Further we encode the new arity in this flag in the old blocks.
130    Remembering the arity is useful, as it saves a lot of pointer
131    accesses.  This function is called for all Phi and Block nodes
132    in a Block. */
133 static INLINE int
134 compute_new_arity(ir_node *b) {
135   int i, res, irn_arity;
136   int irg_v, block_v;
137
138   irg_v = get_irg_block_visited(current_ir_graph);
139   block_v = get_Block_block_visited(b);
140   if (block_v >= irg_v) {
141     /* we computed the number of preds for this block and saved it in the
142        block_v flag */
143     return block_v - irg_v;
144   } else {
145     /* compute the number of good predecessors */
146     res = irn_arity = get_irn_arity(b);
147     for (i = 0; i < irn_arity; i++)
148       if (get_irn_opcode(get_irn_n(b, i)) == iro_Bad) res--;
149     /* save it in the flag. */
150     set_Block_block_visited(b, irg_v + res);
151     return res;
152   }
153 }
154
155 static INLINE void new_backedge_info(ir_node *n) {
156   switch(get_irn_opcode(n)) {
157   case iro_Block:
158     n->attr.block.cg_backedge = NULL;
159     n->attr.block.backedge = new_backedge_arr(current_ir_graph->obst, get_irn_arity(n));
160     break;
161   case iro_Phi:
162     n->attr.phi_backedge = new_backedge_arr(current_ir_graph->obst, get_irn_arity(n));
163     break;
164   case iro_Filter:
165     n->attr.filter.backedge = new_backedge_arr(current_ir_graph->obst, get_irn_arity(n));
166     break;
167   default: ;
168   }
169 }
170
171 /* Copies the node to the new obstack. The Ins of the new node point to
172    the predecessors on the old obstack.  For block/phi nodes not all
173    predecessors might be copied.  n->link points to the new node.
174    For Phi and Block nodes the function allocates in-arrays with an arity
175    only for useful predecessors.  The arity is determined by counting
176    the non-bad predecessors of the block. */
177 static void
178 copy_node (ir_node *n, void *env) {
179   ir_node *nn, *block;
180   int new_arity;
181
182   /* The end node looses it's flexible in array.  This doesn't matter,
183      as dead node elimination builds End by hand, inlineing doesn't use
184      the End node. */
185   //assert(n->op == op_End ||  ((_ARR_DESCR(n->in))->cookie != ARR_F_MAGIC));
186
187   if (get_irn_opcode(n) == iro_Block) {
188     block = NULL;
189     new_arity = compute_new_arity(n);
190     n->attr.block.graph_arr = NULL;
191   } else {
192     block = get_nodes_Block(n);
193     if (get_irn_opcode(n) == iro_Phi) {
194       new_arity = compute_new_arity(block);
195     } else {
196       new_arity = get_irn_arity(n);
197     }
198   }
199   nn = new_ir_node(get_irn_dbg_info(n),
200                    current_ir_graph,
201                    block,
202                    get_irn_op(n),
203                    get_irn_mode(n),
204                    new_arity,
205                    get_irn_in(n));
206   /* Copy the attributes.  These might point to additional data.  If this
207      was allocated on the old obstack the pointers now are dangling.  This
208      frees e.g. the memory of the graph_arr allocated in new_immBlock. */
209   copy_attrs(n, nn);
210   new_backedge_info(nn);
211   set_new_node(n, nn);
212
213   /*  printf("\n old node: "); DDMSG2(n);
214       printf(" new node: "); DDMSG2(nn); */
215
216 }
217
218 /* Copies new predecessors of old node to new node remembered in link.
219    Spare the Bad predecessors of Phi and Block nodes. */
220 static void
221 copy_preds (ir_node *n, void *env) {
222   ir_node *nn, *block;
223   int i, j, irn_arity;
224
225   nn = get_new_node(n);
226
227   /* printf("\n old node: "); DDMSG2(n);
228      printf(" new node: "); DDMSG2(nn);
229      printf(" arities: old: %d, new: %d\n", get_irn_arity(n), get_irn_arity(nn)); */
230
231   if (get_irn_opcode(n) == iro_Block) {
232     /* Don't copy Bad nodes. */
233     j = 0;
234     irn_arity = get_irn_arity(n);
235     for (i = 0; i < irn_arity; i++)
236       if (get_irn_opcode(get_irn_n(n, i)) != iro_Bad) {
237         set_irn_n (nn, j, get_new_node(get_irn_n(n, i)));
238         /*if (is_backedge(n, i)) set_backedge(nn, j);*/
239         j++;
240       }
241     /* repair the block visited flag from above misuse. Repair it in both
242        graphs so that the old one can still be used. */
243     set_Block_block_visited(nn, 0);
244     set_Block_block_visited(n, 0);
245     /* Local optimization could not merge two subsequent blocks if
246        in array contained Bads.  Now it's possible.
247        We don't call optimize_in_place as it requires
248        that the fields in ir_graph are set properly. */
249     if ((get_opt_control_flow_straightening()) &&
250         (get_Block_n_cfgpreds(nn) == 1) &&
251         (get_irn_op(get_Block_cfgpred(nn, 0)) == op_Jmp))
252       exchange(nn, get_nodes_Block(get_Block_cfgpred(nn, 0)));
253   } else if (get_irn_opcode(n) == iro_Phi) {
254     /* Don't copy node if corresponding predecessor in block is Bad.
255        The Block itself should not be Bad. */
256     block = get_nodes_Block(n);
257     set_irn_n (nn, -1, get_new_node(block));
258     j = 0;
259     irn_arity = get_irn_arity(n);
260     for (i = 0; i < irn_arity; i++)
261       if (get_irn_opcode(get_irn_n(block, i)) != iro_Bad) {
262         set_irn_n (nn, j, get_new_node(get_irn_n(n, i)));
263         /*if (is_backedge(n, i)) set_backedge(nn, j);*/
264         j++;
265       }
266     /* If the pre walker reached this Phi after the post walker visited the
267        block block_visited is > 0. */
268     set_Block_block_visited(get_nodes_Block(n), 0);
269     /* Compacting the Phi's ins might generate Phis with only one
270        predecessor. */
271     if (get_irn_arity(n) == 1)
272       exchange(n, get_irn_n(n, 0));
273   } else {
274     irn_arity = get_irn_arity(n);
275     for (i = -1; i < irn_arity; i++)
276       set_irn_n (nn, i, get_new_node(get_irn_n(n, i)));
277   }
278   /* Now the new node is complete.  We can add it to the hash table for cse.
279      @@@ inlinening aborts if we identify End. Why? */
280   if(get_irn_op(nn) != op_End)
281     add_identities (current_ir_graph->value_table, nn);
282 }
283
284 /* Copies the graph recursively, compacts the keepalive of the end node. */
285 static void
286 copy_graph (void) {
287   ir_node *oe, *ne; /* old end, new end */
288   ir_node *ka;      /* keep alive */
289   int i, irn_arity;
290
291   oe = get_irg_end(current_ir_graph);
292   /* copy the end node by hand, allocate dynamic in array! */
293   ne = new_ir_node(get_irn_dbg_info(oe),
294                    current_ir_graph,
295                    NULL,
296                    op_End,
297                    mode_X,
298                    -1,
299                    NULL);
300   /* Copy the attributes.  Well, there might be some in the future... */
301   copy_attrs(oe, ne);
302   set_new_node(oe, ne);
303
304   /* copy the live nodes */
305   irg_walk(get_nodes_Block(oe), copy_node, copy_preds, NULL);
306   /* copy_preds for the end node ... */
307   set_nodes_Block(ne, get_new_node(get_nodes_Block(oe)));
308
309   /** ... and now the keep alives. **/
310   /* First pick the not marked block nodes and walk them.  We must pick these
311      first as else we will oversee blocks reachable from Phis. */
312   irn_arity = get_irn_arity(oe);
313   for (i = 0; i < irn_arity; i++) {
314     ka = get_irn_n(oe, i);
315     if ((get_irn_op(ka) == op_Block) &&
316         (get_irn_visited(ka) < get_irg_visited(current_ir_graph))) {
317       /* We must keep the block alive and copy everything reachable */
318       set_irg_visited(current_ir_graph, get_irg_visited(current_ir_graph)-1);
319       irg_walk(ka, copy_node, copy_preds, NULL);
320       add_End_keepalive(ne, get_new_node(ka));
321     }
322   }
323
324   /* Now pick the Phis.  Here we will keep all! */
325   irn_arity = get_irn_arity(oe);
326   for (i = 0; i < irn_arity; i++) {
327     ka = get_irn_n(oe, i);
328     if ((get_irn_op(ka) == op_Phi)) {
329       if (get_irn_visited(ka) < get_irg_visited(current_ir_graph)) {
330         /* We didn't copy the Phi yet.  */
331         set_irg_visited(current_ir_graph, get_irg_visited(current_ir_graph)-1);
332         irg_walk(ka, copy_node, copy_preds, NULL);
333       }
334       add_End_keepalive(ne, get_new_node(ka));
335     }
336   }
337 }
338
339 /* Copies the graph reachable from current_ir_graph->end to the obstack
340    in current_ir_graph and fixes the environment.
341    Then fixes the fields in current_ir_graph containing nodes of the
342    graph.  */
343 static void
344 copy_graph_env (void) {
345   ir_node *old_end;
346   /* Not all nodes remembered in current_ir_graph might be reachable
347      from the end node.  Assure their link is set to NULL, so that
348      we can test whether new nodes have been computed. */
349   set_irn_link(get_irg_frame  (current_ir_graph), NULL);
350   set_irn_link(get_irg_globals(current_ir_graph), NULL);
351   set_irn_link(get_irg_args   (current_ir_graph), NULL);
352
353   /* we use the block walk flag for removing Bads from Blocks ins. */
354   inc_irg_block_visited(current_ir_graph);
355
356   /* copy the graph */
357   copy_graph();
358
359   /* fix the fields in current_ir_graph */
360   old_end = get_irg_end(current_ir_graph);
361   set_irg_end (current_ir_graph, get_new_node(old_end));
362   free_End(old_end);
363   set_irg_end_block  (current_ir_graph, get_new_node(get_irg_end_block(current_ir_graph)));
364   if (get_irn_link(get_irg_frame(current_ir_graph)) == NULL) {
365     copy_node (get_irg_frame(current_ir_graph), NULL);
366     copy_preds(get_irg_frame(current_ir_graph), NULL);
367   }
368   if (get_irn_link(get_irg_globals(current_ir_graph)) == NULL) {
369     copy_node (get_irg_globals(current_ir_graph), NULL);
370     copy_preds(get_irg_globals(current_ir_graph), NULL);
371   }
372   if (get_irn_link(get_irg_args(current_ir_graph)) == NULL) {
373     copy_node (get_irg_args(current_ir_graph), NULL);
374     copy_preds(get_irg_args(current_ir_graph), NULL);
375   }
376   set_irg_start  (current_ir_graph, get_new_node(get_irg_start(current_ir_graph)));
377
378   set_irg_start_block(current_ir_graph,
379                       get_new_node(get_irg_start_block(current_ir_graph)));
380   set_irg_frame  (current_ir_graph, get_new_node(get_irg_frame(current_ir_graph)));
381   set_irg_globals(current_ir_graph, get_new_node(get_irg_globals(current_ir_graph)));
382   set_irg_args   (current_ir_graph, get_new_node(get_irg_args(current_ir_graph)));
383   if (get_irn_link(get_irg_bad(current_ir_graph)) == NULL) {
384     copy_node(get_irg_bad(current_ir_graph), NULL);
385     copy_preds(get_irg_bad(current_ir_graph), NULL);
386   }
387   set_irg_bad(current_ir_graph, get_new_node(get_irg_bad(current_ir_graph)));
388   /* GL removed: we need unknown with mode for analyses.
389   if (get_irn_link(get_irg_unknown(current_ir_graph)) == NULL) {
390     copy_node(get_irg_unknown(current_ir_graph), NULL);
391     copy_preds(get_irg_unknown(current_ir_graph), NULL);
392   }
393   set_irg_unknown(current_ir_graph, get_new_node(get_irg_unknown(current_ir_graph)));
394   */
395 }
396
397 /* Copies all reachable nodes to a new obstack.  Removes bad inputs
398    from block nodes and the corresponding inputs from Phi nodes.
399    Merges single exit blocks with single entry blocks and removes
400    1-input Phis.
401    Adds all new nodes to a new hash table for cse.  Does not
402    perform cse, so the hash table might contain common subexpressions. */
403 /* Amroq call this emigrate() */
404 void
405 dead_node_elimination(ir_graph *irg) {
406   ir_graph *rem;
407   struct obstack *graveyard_obst = NULL;
408   struct obstack *rebirth_obst   = NULL;
409
410   /* Remember external state of current_ir_graph. */
411   rem = current_ir_graph;
412   current_ir_graph = irg;
413
414   /* Handle graph state */
415   assert(get_irg_phase_state(current_ir_graph) != phase_building);
416   assert(get_irg_callee_info_state(current_ir_graph) == irg_callee_info_none);
417   free_outs(current_ir_graph);
418
419   /* @@@ so far we loose loops when copying */
420   set_irg_loop(current_ir_graph, NULL);
421
422   if (get_opt_optimize() && get_opt_dead_node_elimination()) {
423
424     /* A quiet place, where the old obstack can rest in peace,
425        until it will be cremated. */
426     graveyard_obst = irg->obst;
427
428     /* A new obstack, where the reachable nodes will be copied to. */
429     rebirth_obst = (struct obstack *) xmalloc (sizeof (struct obstack));
430     current_ir_graph->obst = rebirth_obst;
431     obstack_init (current_ir_graph->obst);
432
433     /* We also need a new hash table for cse */
434     del_identities (irg->value_table);
435     irg->value_table = new_identities ();
436
437     /* Copy the graph from the old to the new obstack */
438     copy_graph_env();
439
440     /* Free memory from old unoptimized obstack */
441     obstack_free(graveyard_obst, 0);  /* First empty the obstack ... */
442     xfree (graveyard_obst);           /* ... then free it.           */
443   }
444
445   current_ir_graph = rem;
446 }
447
448 /* Relink bad predeseccors of a block and store the old in array to the
449    link field. This function is called by relink_bad_predecessors().
450    The array of link field starts with the block operand at position 0.
451    If block has bad predecessors, create a new in array without bad preds.
452    Otherwise let in array untouched. */
453 static void relink_bad_block_predecessors(ir_node *n, void *env) {
454   ir_node **new_in, *irn;
455   int i, new_irn_n, old_irn_arity, new_irn_arity = 0;
456
457   /* if link field of block is NULL, look for bad predecessors otherwise
458      this is allready done */
459   if (get_irn_op(n) == op_Block &&
460       get_irn_link(n) == NULL) {
461
462     /* save old predecessors in link field (position 0 is the block operand)*/
463     set_irn_link(n, (void *)get_irn_in(n));
464
465     /* count predecessors without bad nodes */
466     old_irn_arity = get_irn_arity(n);
467     for (i = 0; i < old_irn_arity; i++)
468       if (!is_Bad(get_irn_n(n, i))) new_irn_arity++;
469
470     /* arity changing: set new predecessors without bad nodes */
471     if (new_irn_arity < old_irn_arity) {
472       /* get new predecessor array without Block predecessor */
473       new_in = NEW_ARR_D (ir_node *, current_ir_graph->obst, (new_irn_arity+1));
474
475       /* set new predeseccors in array */
476       new_in[0] = NULL;
477       new_irn_n = 1;
478       for (i = 1; i < old_irn_arity; i++) {
479         irn = get_irn_n(n, i);
480         if (!is_Bad(irn)) new_in[new_irn_n++] = irn;
481       }
482       n->in = new_in;
483     } /* ir node has bad predecessors */
484
485   } /* Block is not relinked */
486 }
487
488 /* Relinks Bad predecesors from Bocks and Phis called by walker
489    remove_bad_predecesors(). If n is a Block, call
490    relink_bad_block_redecessors(). If n is a Phinode, call also the relinking
491    function of Phi's Block. If this block has bad predecessors, relink preds
492    of the Phinode. */
493 static void relink_bad_predecessors(ir_node *n, void *env) {
494   ir_node *block, **old_in;
495   int i, old_irn_arity, new_irn_arity;
496
497   /* relink bad predeseccors of a block */
498   if (get_irn_op(n) == op_Block)
499     relink_bad_block_predecessors(n, env);
500
501   /* If Phi node relink its block and its predecessors */
502   if (get_irn_op(n) == op_Phi) {
503
504     /* Relink predeseccors of phi's block */
505     block = get_nodes_Block(n);
506     if (get_irn_link(block) == NULL)
507       relink_bad_block_predecessors(block, env);
508
509     old_in = (ir_node **)get_irn_link(block); /* Of Phi's Block */
510     old_irn_arity = ARR_LEN(old_in);
511
512     /* Relink Phi predeseccors if count of predeseccors changed */
513     if (old_irn_arity != ARR_LEN(get_irn_in(block))) {
514       /* set new predeseccors in array
515          n->in[0] remains the same block */
516       new_irn_arity = 1;
517       for(i = 1; i < old_irn_arity; i++)
518         if (!is_Bad((ir_node *)old_in[i])) n->in[new_irn_arity++] = n->in[i];
519
520       ARR_SETLEN(ir_node *, n->in, new_irn_arity);
521     }
522
523   } /* n is a Phi node */
524 }
525
526 /* Removes Bad Bad predecesors from Blocks and the corresponding
527    inputs to Phi nodes as in dead_node_elimination but without
528    copying the graph.
529    On walking up set the link field to NULL, on walking down call
530    relink_bad_predecessors() (This function stores the old in array
531    to the link field and sets a new in array if arity of predecessors
532    changes) */
533 void remove_bad_predecessors(ir_graph *irg) {
534   irg_walk_graph(irg, init_link, relink_bad_predecessors, NULL);
535 }
536
537
538 /**********************************************************************/
539 /*  Funcionality for inlining                                         */
540 /**********************************************************************/
541
542 /* Copy node for inlineing.  Updates attributes that change when
543  * inlineing but not for dead node elimination.
544  *
545  * Copies the node by calling copy_node and then updates the entity if
546  * it's a local one.  env must be a pointer of the frame type of the
547  * inlined procedure. The new entities must be in the link field of
548  * the entities. */
549 static INLINE void
550 copy_node_inline (ir_node *n, void *env) {
551   ir_node *new;
552   type *frame_tp = (type *)env;
553
554   copy_node(n, NULL);
555   if (get_irn_op(n) == op_Sel) {
556     new = get_new_node (n);
557     assert(get_irn_op(new) == op_Sel);
558     if (get_entity_owner(get_Sel_entity(n)) == frame_tp) {
559       set_Sel_entity(new, get_entity_link(get_Sel_entity(n)));
560     }
561   } else if (get_irn_op(n) == op_Block) {
562     new = get_new_node (n);
563     new->attr.block.irg = current_ir_graph;
564   }
565 }
566
567
568 void inline_method(ir_node *call, ir_graph *called_graph) {
569   ir_node *pre_call;
570   ir_node *post_call, *post_bl;
571   ir_node *in[5];
572   ir_node *end, *end_bl;
573   ir_node **res_pred;
574   ir_node **cf_pred;
575   ir_node *ret, *phi;
576   int arity, n_ret, n_exc, n_res, i, j, rem_opt, irn_arity;
577   int exc_handling; ir_node *proj;
578   type *called_frame;
579
580   if (!get_opt_optimize() || !get_opt_inline() ||
581       (get_irg_inline_property(called_graph) == irg_inline_forbidden)) return;
582
583   /* --  Turn off optimizations, this can cause problems when allocating new nodes. -- */
584   rem_opt = get_opt_optimize();
585   set_optimize(0);
586
587   /* Handle graph state */
588   assert(get_irg_phase_state(current_ir_graph) != phase_building);
589   assert(get_irg_pinned(current_ir_graph) == pinned);
590   assert(get_irg_pinned(called_graph) == pinned);
591   if (get_irg_outs_state(current_ir_graph) == outs_consistent)
592     set_irg_outs_inconsistent(current_ir_graph);
593
594   /* -- Check preconditions -- */
595   assert(get_irn_op(call) == op_Call);
596   /* @@@ does not work for InterfaceIII.java after cgana
597      assert(get_Call_type(call) == get_entity_type(get_irg_ent(called_graph)));
598      assert(smaller_type(get_entity_type(get_irg_ent(called_graph)),
599      get_Call_type(call)));
600   */
601   assert(get_type_tpop(get_Call_type(call)) == type_method);
602   if (called_graph == current_ir_graph) {
603     set_optimize(rem_opt);
604     return;
605   }
606
607   /* -- Decide how to handle exception control flow: Is there a handler
608      for the Call node, or do we branch directly to End on an exception?
609      exc_handling: 0 There is a handler.
610                    1 Branches to End.
611                    2 Exception handling not represented in Firm. -- */
612   exc_handling = 2;
613   for (proj = (ir_node *)get_irn_link(call); proj; proj = (ir_node *)get_irn_link(proj)) {
614     assert(get_irn_op(proj) == op_Proj);
615     if (get_Proj_proj(proj) == pn_Call_M_except) { exc_handling = 0; break;}
616     if (get_Proj_proj(proj) == pn_Call_X_except) { exc_handling = 1; }
617   }
618
619   {
620     ir_node *proj, *Mproj = NULL, *Xproj = NULL;
621     for (proj = (ir_node *)get_irn_link(call); proj; proj = (ir_node *)get_irn_link(proj)) {
622       assert(get_irn_op(proj) == op_Proj);
623       if (get_Proj_proj(proj) == pn_Call_X_except) Xproj = proj;
624       if (get_Proj_proj(proj) == pn_Call_M_except) Mproj = proj;
625     }
626     if      (Mproj) { assert(Xproj); exc_handling = 0; }
627     else if (Xproj) {                exc_handling = 1; }
628     else            {                exc_handling = 2; }
629   }
630
631
632   /* --
633       the procedure and later replaces the Start node of the called graph.
634       Post_call is the old Call node and collects the results of the called
635       graph. Both will end up being a tuple.  -- */
636   post_bl = get_nodes_Block(call);
637   set_irg_current_block(current_ir_graph, post_bl);
638   /* XxMxPxP of Start + parameter of Call */
639   in[0] = new_Jmp();
640   in[1] = get_Call_mem(call);
641   in[2] = get_irg_frame(current_ir_graph);
642   in[3] = get_irg_globals(current_ir_graph);
643   in[4] = new_Tuple (get_Call_n_params(call), get_Call_param_arr(call));
644   pre_call = new_Tuple(5, in);
645   post_call = call;
646
647   /* --
648       The new block gets the ins of the old block, pre_call and all its
649       predecessors and all Phi nodes. -- */
650   part_block(pre_call);
651
652   /* -- Prepare state for dead node elimination -- */
653   /* Visited flags in calling irg must be >= flag in called irg.
654      Else walker and arity computation will not work. */
655   if (get_irg_visited(current_ir_graph) <= get_irg_visited(called_graph))
656     set_irg_visited(current_ir_graph, get_irg_visited(called_graph)+1);
657   if (get_irg_block_visited(current_ir_graph)< get_irg_block_visited(called_graph))
658     set_irg_block_visited(current_ir_graph, get_irg_block_visited(called_graph));
659   /* Set pre_call as new Start node in link field of the start node of
660      calling graph and pre_calls block as new block for the start block
661      of calling graph.
662      Further mark these nodes so that they are not visited by the
663      copying. */
664   set_irn_link(get_irg_start(called_graph), pre_call);
665   set_irn_visited(get_irg_start(called_graph),
666                   get_irg_visited(current_ir_graph));
667   set_irn_link(get_irg_start_block(called_graph),
668                get_nodes_Block(pre_call));
669   set_irn_visited(get_irg_start_block(called_graph),
670                   get_irg_visited(current_ir_graph));
671
672   /* Initialize for compaction of in arrays */
673   inc_irg_block_visited(current_ir_graph);
674
675   /* -- Replicate local entities of the called_graph -- */
676   /* copy the entities. */
677   called_frame = get_irg_frame_type(called_graph);
678   for (i = 0; i < get_class_n_members(called_frame); i++) {
679     entity *new_ent, *old_ent;
680     old_ent = get_class_member(called_frame, i);
681     new_ent = copy_entity_own(old_ent, get_cur_frame_type());
682     set_entity_link(old_ent, new_ent);
683   }
684
685   /* visited is > than that of called graph.  With this trick visited will
686      remain unchanged so that an outer walker, e.g., searching the call nodes
687      to inline, calling this inline will not visit the inlined nodes. */
688   set_irg_visited(current_ir_graph, get_irg_visited(current_ir_graph)-1);
689
690   /* -- Performing dead node elimination inlines the graph -- */
691   /* Copies the nodes to the obstack of current_ir_graph. Updates links to new
692      entities. */
693   /* @@@ endless loops are not copied!! -- they should be, I think... */
694   irg_walk(get_irg_end(called_graph), copy_node_inline, copy_preds,
695            get_irg_frame_type(called_graph));
696
697   /* Repair called_graph */
698   set_irg_visited(called_graph, get_irg_visited(current_ir_graph));
699   set_irg_block_visited(called_graph, get_irg_block_visited(current_ir_graph));
700   set_Block_block_visited(get_irg_start_block(called_graph), 0);
701
702   /* -- Merge the end of the inlined procedure with the call site -- */
703   /* We will turn the old Call node into a Tuple with the following
704      predecessors:
705        -1:  Block of Tuple.
706        0: Phi of all Memories of Return statements.
707        1: Jmp from new Block that merges the control flow from all exception
708           predecessors of the old end block.
709        2: Tuple of all arguments.
710        3: Phi of Exception memories.
711      In case the old Call directly branches to End on an exception we don't
712      need the block merging all exceptions nor the Phi of the exception
713      memories.
714   */
715
716   /* -- Precompute some values -- */
717   end_bl = get_new_node(get_irg_end_block(called_graph));
718   end = get_new_node(get_irg_end(called_graph));
719   arity = get_irn_arity(end_bl);    /* arity = n_exc + n_ret  */
720   n_res = get_method_n_ress(get_Call_type(call));
721
722   res_pred = (ir_node **) malloc (n_res * sizeof (ir_node *));
723   cf_pred =  (ir_node **) malloc (arity * sizeof (ir_node *));
724
725   set_irg_current_block(current_ir_graph, post_bl); /* just to make sure */
726
727   /* -- archive keepalives -- */
728   irn_arity = get_irn_arity(end);
729   for (i = 0; i < irn_arity; i++)
730     add_End_keepalive(get_irg_end(current_ir_graph), get_irn_n(end, i));
731
732   /* The new end node will die.  We need not free as the in array is on the obstack:
733      copy_node only generated 'D' arrays. */
734
735   /* -- Replace Return nodes by Jump nodes. -- */
736   n_ret = 0;
737   for (i = 0; i < arity; i++) {
738     ir_node *ret;
739     ret = get_irn_n(end_bl, i);
740     if (get_irn_op(ret) == op_Return) {
741       cf_pred[n_ret] = new_r_Jmp(current_ir_graph, get_nodes_Block(ret));
742       n_ret++;
743     }
744   }
745   set_irn_in(post_bl, n_ret, cf_pred);
746
747   /* -- Build a Tuple for all results of the method.
748      Add Phi node if there was more than one Return.  -- */
749   turn_into_tuple(post_call, 4);
750   /* First the Memory-Phi */
751   n_ret = 0;
752   for (i = 0; i < arity; i++) {
753     ret = get_irn_n(end_bl, i);
754     if (get_irn_op(ret) == op_Return) {
755       cf_pred[n_ret] = get_Return_mem(ret);
756       n_ret++;
757     }
758   }
759   phi = new_Phi(n_ret, cf_pred, mode_M);
760   set_Tuple_pred(call, 0, phi);
761   /* Conserve Phi-list for further inlinings -- but might be optimized */
762   if (get_nodes_Block(phi) == post_bl) {
763     set_irn_link(phi, get_irn_link(post_bl));
764     set_irn_link(post_bl, phi);
765   }
766   /* Now the real results */
767   if (n_res > 0) {
768     for (j = 0; j < n_res; j++) {
769       n_ret = 0;
770       for (i = 0; i < arity; i++) {
771         ret = get_irn_n(end_bl, i);
772         if (get_irn_op(ret) == op_Return) {
773           cf_pred[n_ret] = get_Return_res(ret, j);
774           n_ret++;
775         }
776       }
777       phi = new_Phi(n_ret, cf_pred, get_irn_mode(cf_pred[0]));
778       res_pred[j] = phi;
779       /* Conserve Phi-list for further inlinings -- but might be optimized */
780       if (get_nodes_Block(phi) == post_bl) {
781         set_irn_link(phi, get_irn_link(post_bl));
782         set_irn_link(post_bl, phi);
783       }
784     }
785     set_Tuple_pred(call, 2, new_Tuple(n_res, res_pred));
786   } else {
787     set_Tuple_pred(call, 2, new_Bad());
788   }
789   /* Finally the exception control flow.
790      We have two (three) possible situations:
791      First if the Call branches to an exception handler: We need to add a Phi node to
792      collect the memory containing the exception objects.  Further we need
793      to add another block to get a correct representation of this Phi.  To
794      this block we add a Jmp that resolves into the X output of the Call
795      when the Call is turned into a tuple.
796      Second the Call branches to End, the exception is not handled.  Just
797      add all inlined exception branches to the End node.
798      Third: there is no Exception edge at all. Handle as case two. */
799   if (exc_handler == 0) {
800     n_exc = 0;
801     for (i = 0; i < arity; i++) {
802       ir_node *ret;
803       ret = get_irn_n(end_bl, i);
804       if (is_fragile_op(skip_Proj(ret)) || (get_irn_op(skip_Proj(ret)) == op_Raise)) {
805         cf_pred[n_exc] = ret;
806         n_exc++;
807       }
808     }
809     if (n_exc > 0) {
810       new_Block(n_exc, cf_pred);      /* watch it: current_block is changed! */
811       set_Tuple_pred(call, 1, new_Jmp());
812       /* The Phi for the memories with the exception objects */
813       n_exc = 0;
814       for (i = 0; i < arity; i++) {
815         ir_node *ret;
816         ret = skip_Proj(get_irn_n(end_bl, i));
817         if (get_irn_op(ret) == op_Call) {
818           cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_Block(ret), ret, mode_M, 3);
819           n_exc++;
820         } else if (is_fragile_op(ret)) {
821         /* We rely that all cfops have the memory output at the same position. */
822           cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_Block(ret), ret, mode_M, 0);
823           n_exc++;
824         } else if (get_irn_op(ret) == op_Raise) {
825           cf_pred[n_exc] = new_r_Proj(current_ir_graph, get_nodes_Block(ret), ret, mode_M, 1);
826           n_exc++;
827         }
828       }
829       set_Tuple_pred(call, 3, new_Phi(n_exc, cf_pred, mode_M));
830     } else {
831       set_Tuple_pred(call, 1, new_Bad());
832       set_Tuple_pred(call, 3, new_Bad());
833     }
834   } else {
835     ir_node *main_end_bl;
836     int main_end_bl_arity;
837     ir_node **end_preds;
838
839     /* assert(exc_handler == 1 || no exceptions. ) */
840     n_exc = 0;
841     for (i = 0; i < arity; i++) {
842       ir_node *ret = get_irn_n(end_bl, i);
843
844       if (is_fragile_op(skip_Proj(ret)) || (get_irn_op(skip_Proj(ret)) == op_Raise)) {
845         cf_pred[n_exc] = ret;
846         n_exc++;
847       }
848     }
849     main_end_bl = get_irg_end_block(current_ir_graph);
850     main_end_bl_arity = get_irn_arity(main_end_bl);
851     end_preds =  (ir_node **) malloc ((n_exc + main_end_bl_arity) * sizeof (ir_node *));
852
853     for (i = 0; i < main_end_bl_arity; ++i)
854       end_preds[i] = get_irn_n(main_end_bl, i);
855     for (i = 0; i < n_exc; ++i)
856       end_preds[main_end_bl_arity + i] = cf_pred[i];
857     set_irn_in(main_end_bl, n_exc + main_end_bl_arity, end_preds);
858     set_Tuple_pred(call, 1, new_Bad());
859     set_Tuple_pred(call, 3, new_Bad());
860     free(end_preds);
861   }
862   free(res_pred);
863   free(cf_pred);
864
865 #if 0  /* old. now better, correcter, faster implementation. */
866   if (n_exc > 0) {
867     /* -- If the exception control flow from the inlined Call directly
868        branched to the end block we now have the following control
869        flow predecessor pattern: ProjX -> Tuple -> Jmp.  We must
870        remove the Jmp along with it's empty block and add Jmp's
871        predecessors as predecessors of this end block.  No problem if
872        there is no exception, because then branches Bad to End which
873        is fine. --
874        @@@ can't we know this beforehand: by getting the Proj(1) from
875        the Call link list and checking whether it goes to Proj. */
876     /* find the problematic predecessor of the end block. */
877     end_bl = get_irg_end_block(current_ir_graph);
878     for (i = 0; i < get_Block_n_cfgpreds(end_bl); i++) {
879       cf_op = get_Block_cfgpred(end_bl, i);
880       if (get_irn_op(cf_op) == op_Proj) {
881         cf_op = get_Proj_pred(cf_op);
882         if ((get_irn_op(cf_op) == op_Tuple) && (cf_op == call)) {
883           // There are unoptimized tuples from inlineing before when no exc
884           assert(get_Proj_proj(get_Block_cfgpred(end_bl, i)) == pn_Call_X_except);
885           cf_op = get_Tuple_pred(cf_op, pn_Call_X_except);
886           assert(get_irn_op(cf_op) == op_Jmp);
887           break;
888         }
889       }
890     }
891     /* repair */
892     if (i < get_Block_n_cfgpreds(end_bl)) {
893       bl = get_nodes_Block(cf_op);
894       arity = get_Block_n_cfgpreds(end_bl) + get_Block_n_cfgpreds(bl) - 1;
895       cf_pred = (ir_node **) malloc (arity * sizeof (ir_node *));
896       for (j = 0; j < i; j++)
897         cf_pred[j] = get_Block_cfgpred(end_bl, j);
898       for (j = j; j < i + get_Block_n_cfgpreds(bl); j++)
899         cf_pred[j] = get_Block_cfgpred(bl, j-i);
900       for (j = j; j < arity; j++)
901         cf_pred[j] = get_Block_cfgpred(end_bl, j-get_Block_n_cfgpreds(bl) +1);
902       set_irn_in(end_bl, arity, cf_pred);
903       free(cf_pred);
904       // Remove the exception pred from post-call Tuple.
905       set_Tuple_pred(call, pn_Call_X_except, new_Bad());
906     }
907   }
908 #endif
909
910   /* --  Turn cse back on. -- */
911   set_optimize(rem_opt);
912 }
913
914 /********************************************************************/
915 /* Apply inlineing to small methods.                                */
916 /********************************************************************/
917
918 static int pos;
919
920 /* It makes no sense to inline too many calls in one procedure. Anyways,
921    I didn't get a version with NEW_ARR_F to run. */
922 #define MAX_INLINE 1024
923
924 /* given an Call node, returns the irg called.  NULL if not
925  * known. */
926 static ir_graph *get_call_called_irg(ir_node *call) {
927   ir_node *addr;
928   tarval *tv;
929   ir_graph *called_irg = NULL;
930
931   assert(get_irn_op(call) == op_Call);
932
933   addr = get_Call_ptr(call);
934   if (get_irn_op(addr) == op_Const) {
935     /* Check whether the constant is the pointer to a compiled entity. */
936     tv = get_Const_tarval(addr);
937     if (tarval_to_entity(tv))
938       called_irg = get_entity_irg(tarval_to_entity(tv));
939   }
940   return called_irg;
941 }
942
943 static void collect_calls(ir_node *call, void *env) {
944
945   ir_node **calls = (ir_node **)env;
946   ir_node *addr;
947   tarval *tv;
948   ir_graph *called_irg;
949
950   if (get_irn_op(call) != op_Call) return;
951
952   addr = get_Call_ptr(call);
953   if (get_irn_op(addr) == op_Const) {
954     /* Check whether the constant is the pointer to a compiled entity. */
955     tv = get_Const_tarval(addr);
956     if (tarval_to_entity(tv)) {
957       called_irg = get_entity_irg(tarval_to_entity(tv));
958       if (called_irg && pos < MAX_INLINE) {
959         /* The Call node calls a locally defined method.  Remember to inline. */
960         calls[pos] = call;
961         pos++;
962       }
963     }
964   }
965 }
966
967 /* Inlines all small methods at call sites where the called address comes
968    from a Const node that references the entity representing the called
969    method.
970    The size argument is a rough measure for the code size of the method:
971    Methods where the obstack containing the firm graph is smaller than
972    size are inlined. */
973 void inline_small_irgs(ir_graph *irg, int size) {
974   int i;
975   ir_node *calls[MAX_INLINE];
976   ir_graph *rem = current_ir_graph;
977
978   if (!(get_opt_optimize() && get_opt_inline())) return;
979
980   current_ir_graph = irg;
981   /* Handle graph state */
982   assert(get_irg_phase_state(current_ir_graph) != phase_building);
983   assert(get_irg_callee_info_state(current_ir_graph) == irg_callee_info_none);
984
985   /* Find Call nodes to inline.
986      (We can not inline during a walk of the graph, as inlineing the same
987      method several times changes the visited flag of the walked graph:
988      after the first inlineing visited of the callee equals visited of
989      the caller.  With the next inlineing both are increased.) */
990   pos = 0;
991   irg_walk(get_irg_end(irg), NULL, collect_calls, (void *) calls);
992
993   if ((pos > 0) && (pos < MAX_INLINE)) {
994     /* There are calls to inline */
995     collect_phiprojs(irg);
996     for (i = 0; i < pos; i++) {
997       tarval *tv;
998       ir_graph *callee;
999       tv = get_Const_tarval(get_Call_ptr(calls[i]));
1000       callee = get_entity_irg(tarval_to_entity(tv));
1001       if (((_obstack_memory_used(callee->obst) - obstack_room(callee->obst)) < size) ||
1002           (get_irg_inline_property(callee) == irg_inline_forced)) {
1003         inline_method(calls[i], callee);
1004       }
1005     }
1006   }
1007
1008   current_ir_graph = rem;
1009 }
1010
1011 /**
1012  * Environment for inlining irgs.
1013  */
1014 typedef struct {
1015   int n_nodes;       /**< Nodes in graph except Id, Tuple, Proj, Start, End */
1016   int n_nodes_orig;  /**< for statistics */
1017   eset *call_nodes;  /**< All call nodes in this graph */
1018   int n_call_nodes;
1019   int n_call_nodes_orig; /**< for statistics */
1020   int n_callers;   /**< Number of known graphs that call this graphs. */
1021   int n_callers_orig; /**< for statistics */
1022 } inline_irg_env;
1023
1024 static inline_irg_env *new_inline_irg_env(void) {
1025   inline_irg_env *env = malloc(sizeof(inline_irg_env));
1026   env->n_nodes = -2; /* uncount Start, End */
1027   env->n_nodes_orig = -2; /* uncount Start, End */
1028   env->call_nodes = eset_create();
1029   env->n_call_nodes = 0;
1030   env->n_call_nodes_orig = 0;
1031   env->n_callers = 0;
1032   env->n_callers_orig = 0;
1033   return env;
1034 }
1035
1036 static void free_inline_irg_env(inline_irg_env *env) {
1037   eset_destroy(env->call_nodes);
1038   free(env);
1039 }
1040
1041 static void collect_calls2(ir_node *call, void *env) {
1042   inline_irg_env *x = (inline_irg_env *)env;
1043   ir_op *op = get_irn_op(call);
1044   ir_graph *callee;
1045
1046   /* count nodes in irg */
1047   if (op != op_Proj && op != op_Tuple && op != op_Sync) {
1048     x->n_nodes++;
1049     x->n_nodes_orig++;
1050   }
1051
1052   if (op != op_Call) return;
1053
1054   /* collect all call nodes */
1055   eset_insert(x->call_nodes, (void *)call);
1056   x->n_call_nodes++;
1057   x->n_call_nodes_orig++;
1058
1059   /* count all static callers */
1060   callee = get_call_called_irg(call);
1061   if (callee) {
1062     ((inline_irg_env *)get_irg_link(callee))->n_callers++;
1063     ((inline_irg_env *)get_irg_link(callee))->n_callers_orig++;
1064   }
1065 }
1066
1067 INLINE static int is_leave(ir_graph *irg) {
1068   return (((inline_irg_env *)get_irg_link(irg))->n_call_nodes == 0);
1069 }
1070
1071 INLINE static int is_smaller(ir_graph *callee, int size) {
1072   return (((inline_irg_env *)get_irg_link(callee))->n_nodes < size);
1073 }
1074
1075
1076 /* Inlines small leave methods at call sites where the called address comes
1077    from a Const node that references the entity representing the called
1078    method.
1079    The size argument is a rough measure for the code size of the method:
1080    Methods where the obstack containing the firm graph is smaller than
1081    size are inlined. */
1082 void inline_leave_functions(int maxsize, int leavesize, int size) {
1083   inline_irg_env *env;
1084   int i, n_irgs = get_irp_n_irgs();
1085   ir_graph *rem = current_ir_graph;
1086   int did_inline = 1;
1087
1088   if (!(get_opt_optimize() && get_opt_inline())) return;
1089
1090   /* extend all irgs by a temporary data structure for inlineing. */
1091   for (i = 0; i < n_irgs; ++i)
1092     set_irg_link(get_irp_irg(i), new_inline_irg_env());
1093
1094   /* Precompute information in temporary data structure. */
1095   for (i = 0; i < n_irgs; ++i) {
1096     current_ir_graph = get_irp_irg(i);
1097     assert(get_irg_phase_state(current_ir_graph) != phase_building);
1098     assert(get_irg_callee_info_state(current_ir_graph) == irg_callee_info_none);
1099
1100     irg_walk(get_irg_end(current_ir_graph), NULL, collect_calls2,
1101              get_irg_link(current_ir_graph));
1102     env = (inline_irg_env *)get_irg_link(current_ir_graph);
1103   }
1104
1105   /* and now inline.
1106      Inline leaves recursively -- we might construct new leaves. */
1107   //int itercnt = 1;
1108   while (did_inline) {
1109     //printf("iteration %d\n", itercnt++);
1110     did_inline = 0;
1111     for (i = 0; i < n_irgs; ++i) {
1112       ir_node *call;
1113       eset *walkset;
1114       int phiproj_computed = 0;
1115
1116       current_ir_graph = get_irp_irg(i);
1117       env = (inline_irg_env *)get_irg_link(current_ir_graph);
1118
1119       /* we can not walk and change a set, nor remove from it.
1120       So recompute.*/
1121       walkset = env->call_nodes;
1122       env->call_nodes = eset_create();
1123       for (call = eset_first(walkset); call; call = eset_next(walkset)) {
1124         inline_irg_env *callee_env;
1125         ir_graph *callee = get_call_called_irg(call);
1126
1127         if (env->n_nodes > maxsize) break;
1128         if (callee &&
1129             ((is_leave(callee) && is_smaller(callee, leavesize)) ||
1130              (get_irg_inline_property(callee) == irg_inline_forced))) {
1131           if (!phiproj_computed) {
1132             phiproj_computed = 1;
1133             collect_phiprojs(current_ir_graph);
1134           }
1135           callee_env = (inline_irg_env *)get_irg_link(callee);
1136 //        printf(" %s: Inlineing %s.\n", get_entity_name(get_irg_entity(current_ir_graph)),
1137 //            get_entity_name(get_irg_entity(callee)));
1138           inline_method(call, callee);
1139           did_inline = 1;
1140           env->n_call_nodes--;
1141           eset_insert_all(env->call_nodes, callee_env->call_nodes);
1142           env->n_call_nodes += callee_env->n_call_nodes;
1143           env->n_nodes += callee_env->n_nodes;
1144           callee_env->n_callers--;
1145         } else {
1146           eset_insert(env->call_nodes, call);
1147         }
1148       }
1149       eset_destroy(walkset);
1150     }
1151   }
1152
1153   //printf("Non leaves\n");
1154   /* inline other small functions. */
1155   for (i = 0; i < n_irgs; ++i) {
1156     ir_node *call;
1157     eset *walkset;
1158     int phiproj_computed = 0;
1159
1160     current_ir_graph = get_irp_irg(i);
1161     env = (inline_irg_env *)get_irg_link(current_ir_graph);
1162
1163     /* we can not walk and change a set, nor remove from it.
1164        So recompute.*/
1165     walkset = env->call_nodes;
1166     env->call_nodes = eset_create();
1167     for (call = eset_first(walkset); call; call = eset_next(walkset)) {
1168       inline_irg_env *callee_env;
1169       ir_graph *callee = get_call_called_irg(call);
1170
1171       if (env->n_nodes > maxsize) break;
1172       if (callee && is_smaller(callee, size)) {
1173         if (!phiproj_computed) {
1174                 phiproj_computed = 1;
1175                 collect_phiprojs(current_ir_graph);
1176         }
1177         callee_env = (inline_irg_env *)get_irg_link(callee);
1178 //      printf(" %s: Inlineing %s.\n", get_entity_name(get_irg_entity(current_ir_graph)),
1179 //      get_entity_name(get_irg_entity(callee)));
1180         inline_method(call, callee);
1181         did_inline = 1;
1182         env->n_call_nodes--;
1183         eset_insert_all(env->call_nodes, callee_env->call_nodes);
1184         env->n_call_nodes += callee_env->n_call_nodes;
1185         env->n_nodes += callee_env->n_nodes;
1186         callee_env->n_callers--;
1187       } else {
1188         eset_insert(env->call_nodes, call);
1189       }
1190     }
1191     eset_destroy(walkset);
1192   }
1193
1194   for (i = 0; i < n_irgs; ++i) {
1195     current_ir_graph = get_irp_irg(i);
1196 #if 0
1197     env = (inline_irg_env *)get_irg_link(current_ir_graph);
1198     if ((env->n_call_nodes_orig != env->n_call_nodes) ||
1199         (env->n_callers_orig != env->n_callers))
1200       printf("Nodes:%3d ->%3d, calls:%3d ->%3d, callers:%3d ->%3d, -- %s\n",
1201              env->n_nodes_orig, env->n_nodes, env->n_call_nodes_orig, env->n_call_nodes,
1202              env->n_callers_orig, env->n_callers,
1203              get_entity_name(get_irg_entity(current_ir_graph)));
1204 #endif
1205     free_inline_irg_env((inline_irg_env *)get_irg_link(current_ir_graph));
1206   }
1207
1208   current_ir_graph = rem;
1209 }
1210
1211 /********************************************************************/
1212 /*  Code Placement.  Pins all floating nodes to a block where they */
1213 /*  will be executed only if needed.                                */
1214 /********************************************************************/
1215
1216 /* Find the earliest correct block for N.  --- Place N into the
1217    same Block as its dominance-deepest Input.  */
1218 static void
1219 place_floats_early(ir_node *n, pdeq *worklist)
1220 {
1221   int i, start, irn_arity;
1222
1223   /* we must not run into an infinite loop */
1224   assert (irn_not_visited(n));
1225   mark_irn_visited(n);
1226
1227   /* Place floating nodes. */
1228   if (get_op_pinned(get_irn_op(n)) == floats) {
1229     int depth = 0;
1230     ir_node *b = new_Bad();   /* The block to place this node in */
1231
1232     assert(get_irn_op(n) != op_Block);
1233
1234     if ((get_irn_op(n) == op_Const) ||
1235         (get_irn_op(n) == op_SymConst) ||
1236         (is_Bad(n)) ||
1237         (get_irn_op(n) == op_Unknown)) {
1238       /* These nodes will not be placed by the loop below. */
1239       b = get_irg_start_block(current_ir_graph);
1240       depth = 1;
1241     }
1242
1243     /* find the block for this node. */
1244     irn_arity = get_irn_arity(n);
1245     for (i = 0; i < irn_arity; i++) {
1246       ir_node *dep = get_irn_n(n, i);
1247       ir_node *dep_block;
1248       if ((irn_not_visited(dep)) &&
1249           (get_op_pinned(get_irn_op(dep)) == floats)) {
1250         place_floats_early(dep, worklist);
1251       }
1252       /* Because all loops contain at least one pinned node, now all
1253          our inputs are either pinned or place_early has already
1254          been finished on them.  We do not have any unfinished inputs!  */
1255       dep_block = get_nodes_Block(dep);
1256       if ((!is_Bad(dep_block)) &&
1257           (get_Block_dom_depth(dep_block) > depth)) {
1258         b = dep_block;
1259         depth = get_Block_dom_depth(dep_block);
1260       }
1261       /* Avoid that the node is placed in the Start block */
1262       if ((depth == 1) && (get_Block_dom_depth(get_nodes_Block(n)) > 1)) {
1263         b = get_Block_cfg_out(get_irg_start_block(current_ir_graph), 0);
1264         assert(b != get_irg_start_block(current_ir_graph));
1265         depth = 2;
1266       }
1267     }
1268     set_nodes_Block(n, b);
1269   }
1270
1271   /* Add predecessors of non floating nodes on worklist. */
1272   start = (get_irn_op(n) == op_Block) ? 0 : -1;
1273   irn_arity = get_irn_arity(n);
1274   for (i = start; i < irn_arity; i++) {
1275     ir_node *pred = get_irn_n(n, i);
1276     if (irn_not_visited(pred)) {
1277       pdeq_putr (worklist, pred);
1278     }
1279   }
1280 }
1281
1282 /* Floating nodes form subgraphs that begin at nodes as Const, Load,
1283    Start, Call and end at pinned nodes as Store, Call.  Place_early
1284    places all floating nodes reachable from its argument through floating
1285    nodes and adds all beginnings at pinned nodes to the worklist. */
1286 static INLINE void place_early(pdeq* worklist) {
1287   assert(worklist);
1288   inc_irg_visited(current_ir_graph);
1289
1290   /* this inits the worklist */
1291   place_floats_early(get_irg_end(current_ir_graph), worklist);
1292
1293   /* Work the content of the worklist. */
1294   while (!pdeq_empty (worklist)) {
1295     ir_node *n = pdeq_getl (worklist);
1296     if (irn_not_visited(n)) place_floats_early(n, worklist);
1297   }
1298
1299   set_irg_outs_inconsistent(current_ir_graph);
1300   current_ir_graph->pinned = pinned;
1301 }
1302
1303
1304 /* deepest common dominance ancestor of DCA and CONSUMER of PRODUCER */
1305 static ir_node *
1306 consumer_dom_dca (ir_node *dca, ir_node *consumer, ir_node *producer)
1307 {
1308   ir_node *block = NULL;
1309
1310   /* Compute the latest block into which we can place a node so that it is
1311      before consumer. */
1312   if (get_irn_op(consumer) == op_Phi) {
1313     /* our consumer is a Phi-node, the effective use is in all those
1314        blocks through which the Phi-node reaches producer */
1315     int i, irn_arity;
1316     ir_node *phi_block = get_nodes_Block(consumer);
1317     irn_arity = get_irn_arity(consumer);
1318     for (i = 0;  i < irn_arity; i++) {
1319       if (get_irn_n(consumer, i) == producer) {
1320         block = get_nodes_Block(get_Block_cfgpred(phi_block, i));
1321       }
1322     }
1323   } else {
1324     assert(is_no_Block(consumer));
1325     block = get_nodes_Block(consumer);
1326   }
1327
1328   /* Compute the deepest common ancestor of block and dca. */
1329   assert(block);
1330   if (!dca) return block;
1331   while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
1332     block = get_Block_idom(block);
1333   while (get_Block_dom_depth(dca) > get_Block_dom_depth(block))
1334     dca = get_Block_idom(dca);
1335   while (block != dca)
1336     { block = get_Block_idom(block); dca = get_Block_idom(dca); }
1337
1338   return dca;
1339 }
1340
1341 static INLINE int get_irn_loop_depth(ir_node *n) {
1342   return get_loop_depth(get_irn_loop(n));
1343 }
1344
1345 /* Move n to a block with less loop depth than it's current block. The
1346    new block must be dominated by early. */
1347 static void
1348 move_out_of_loops (ir_node *n, ir_node *early)
1349 {
1350   ir_node *best, *dca;
1351   assert(n && early);
1352
1353
1354   /* Find the region deepest in the dominator tree dominating
1355      dca with the least loop nesting depth, but still dominated
1356      by our early placement. */
1357   dca = get_nodes_Block(n);
1358   best = dca;
1359   while (dca != early) {
1360     dca = get_Block_idom(dca);
1361     if (!dca) break; /* should we put assert(dca)? */
1362     if (get_irn_loop_depth(dca) < get_irn_loop_depth(best)) {
1363       best = dca;
1364     }
1365   }
1366   if (best != get_nodes_Block(n)) {
1367     /* debug output
1368     printf("Moving out of loop: "); DDMN(n);
1369     printf(" Outermost block: "); DDMN(early);
1370     printf(" Best block: "); DDMN(best);
1371     printf(" Innermost block: "); DDMN(get_nodes_Block(n));
1372     */
1373     set_nodes_Block(n, best);
1374   }
1375 }
1376
1377 /* Find the latest legal block for N and place N into the
1378    `optimal' Block between the latest and earliest legal block.
1379    The `optimal' block is the dominance-deepest block of those
1380    with the least loop-nesting-depth.  This places N out of as many
1381    loops as possible and then makes it as control dependant as
1382    possible. */
1383 static void
1384 place_floats_late(ir_node *n, pdeq *worklist)
1385 {
1386   int i;
1387   ir_node *early;
1388
1389   assert (irn_not_visited(n)); /* no multiple placement */
1390
1391   /* no need to place block nodes, control nodes are already placed. */
1392   if ((get_irn_op(n) != op_Block) &&
1393       (!is_cfop(n)) &&
1394       (get_irn_mode(n) != mode_X)) {
1395     /* Remember the early placement of this block to move it
1396        out of loop no further than the early placement. */
1397     early = get_nodes_Block(n);
1398     /* Assure that our users are all placed, except the Phi-nodes.
1399        --- Each data flow cycle contains at least one Phi-node.  We
1400        have to break the `user has to be placed before the
1401        producer' dependence cycle and the Phi-nodes are the
1402        place to do so, because we need to base our placement on the
1403        final region of our users, which is OK with Phi-nodes, as they
1404        are pinned, and they never have to be placed after a
1405        producer of one of their inputs in the same block anyway. */
1406     for (i = 0; i < get_irn_n_outs(n); i++) {
1407       ir_node *succ = get_irn_out(n, i);
1408       if (irn_not_visited(succ) && (get_irn_op(succ) != op_Phi))
1409         place_floats_late(succ, worklist);
1410     }
1411
1412     /* We have to determine the final block of this node... except for
1413        constants. */
1414     if ((get_op_pinned(get_irn_op(n)) == floats) &&
1415         (get_irn_op(n) != op_Const) &&
1416         (get_irn_op(n) != op_SymConst)) {
1417       ir_node *dca = NULL;      /* deepest common ancestor in the
1418                                    dominator tree of all nodes'
1419                                    blocks depending on us; our final
1420                                    placement has to dominate DCA. */
1421       for (i = 0; i < get_irn_n_outs(n); i++) {
1422         dca = consumer_dom_dca (dca, get_irn_out(n, i), n);
1423       }
1424       set_nodes_Block(n, dca);
1425
1426       move_out_of_loops (n, early);
1427     }
1428   }
1429
1430   mark_irn_visited(n);
1431
1432   /* Add predecessors of all non-floating nodes on list. (Those of floating
1433      nodes are placeded already and therefore are marked.)  */
1434   for (i = 0; i < get_irn_n_outs(n); i++) {
1435     if (irn_not_visited(get_irn_out(n, i))) {
1436       pdeq_putr (worklist, get_irn_out(n, i));
1437     }
1438   }
1439 }
1440
1441 static INLINE void place_late(pdeq* worklist) {
1442   assert(worklist);
1443   inc_irg_visited(current_ir_graph);
1444
1445   /* This fills the worklist initially. */
1446   place_floats_late(get_irg_start_block(current_ir_graph), worklist);
1447   /* And now empty the worklist again... */
1448   while (!pdeq_empty (worklist)) {
1449     ir_node *n = pdeq_getl (worklist);
1450     if (irn_not_visited(n)) place_floats_late(n, worklist);
1451   }
1452 }
1453
1454 void place_code(ir_graph *irg) {
1455   pdeq* worklist;
1456   ir_graph *rem = current_ir_graph;
1457
1458   current_ir_graph = irg;
1459
1460   if (!(get_opt_optimize() && get_opt_global_cse())) return;
1461
1462   /* Handle graph state */
1463   assert(get_irg_phase_state(irg) != phase_building);
1464   if (get_irg_dom_state(irg) != dom_consistent)
1465     compute_doms(irg);
1466
1467   construct_backedges(irg);
1468
1469   /* Place all floating nodes as early as possible. This guarantees
1470      a legal code placement. */
1471   worklist = new_pdeq();
1472   place_early(worklist);
1473
1474   /* place_early invalidates the outs, place_late needs them. */
1475   compute_outs(irg);
1476   /* Now move the nodes down in the dominator tree. This reduces the
1477      unnecessary executions of the node. */
1478   place_late(worklist);
1479
1480   set_irg_outs_inconsistent(current_ir_graph);
1481   del_pdeq(worklist);
1482   current_ir_graph = rem;
1483 }
1484
1485
1486
1487 /********************************************************************/
1488 /* Control flow optimization.                                       */
1489 /* Removes Bad control flow predecessors and empty blocks.  A block */
1490 /* is empty if it contains only a Jmp node.                         */
1491 /* Blocks can only be removed if they are not needed for the        */
1492 /* semantics of Phi nodes.                                          */
1493 /********************************************************************/
1494
1495 /* Removes Tuples from Block control flow predecessors.
1496    Optimizes blocks with equivalent_node().
1497    Replaces n by Bad if n is unreachable control flow. */
1498 static void merge_blocks(ir_node *n, void *env) {
1499   int i;
1500   set_irn_link(n, NULL);
1501
1502   if (get_irn_op(n) == op_Block) {
1503     /* Remove Tuples */
1504     for (i = 0; i < get_Block_n_cfgpreds(n); i++)
1505       /* GL @@@ : is this possible? if (get_opt_normalize()) -- added, all tests go through.
1506          A different order of optimizations might cause problems. */
1507       if (get_opt_normalize())
1508         set_Block_cfgpred(n, i, skip_Tuple(get_Block_cfgpred(n, i)));
1509   } else if (get_opt_optimize() && (get_irn_mode(n) == mode_X)) {
1510     /* We will soon visit a block.  Optimize it before visiting! */
1511     ir_node *b = get_nodes_Block(n);
1512     ir_node *new_node = equivalent_node(b);
1513     while (irn_not_visited(b) && (!is_Bad(new_node)) && (new_node != b)) {
1514       /* We would have to run gigo if new is bad, so we
1515          promote it directly below. */
1516       assert(((b == new_node) ||
1517               get_opt_control_flow_straightening() ||
1518               get_opt_control_flow_weak_simplification()) &&
1519              ("strange flag setting"));
1520       exchange (b, new_node);
1521       b = new_node;
1522       new_node = equivalent_node(b);
1523     }
1524     /* GL @@@ get_opt_normalize hinzugefuegt, 5.5.2003 */
1525     if (is_Bad(new_node) && get_opt_normalize()) exchange(n, new_Bad());
1526   }
1527 }
1528
1529 /* Collects all Phi nodes in link list of Block.
1530    Marks all blocks "block_visited" if they contain a node other
1531    than Jmp. */
1532 static void collect_nodes(ir_node *n, void *env) {
1533   if (is_no_Block(n)) {
1534     ir_node *b = get_nodes_Block(n);
1535
1536     if ((get_irn_op(n) == op_Phi)) {
1537       /* Collect Phi nodes to compact ins along with block's ins. */
1538       set_irn_link(n, get_irn_link(b));
1539       set_irn_link(b, n);
1540     } else if (get_irn_op(n) != op_Jmp) {  /* Check for non empty block. */
1541       mark_Block_block_visited(b);
1542     }
1543   }
1544 }
1545
1546 /* Returns true if pred is pred of block */
1547 static int is_pred_of(ir_node *pred, ir_node *b) {
1548   int i;
1549   for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
1550     ir_node *b_pred = get_nodes_Block(get_Block_cfgpred(b, i));
1551     if (b_pred == pred) return 1;
1552   }
1553   return 0;
1554 }
1555
1556 static int test_whether_dispensable(ir_node *b, int pos) {
1557   int i, j, n_preds = 1;
1558   int dispensable = 1;
1559   ir_node *cfop = get_Block_cfgpred(b, pos);
1560   ir_node *pred = get_nodes_Block(cfop);
1561
1562   if (get_Block_block_visited(pred) + 1
1563       < get_irg_block_visited(current_ir_graph)) {
1564     if (!get_opt_optimize() || !get_opt_control_flow_strong_simplification()) {
1565       /* Mark block so that is will not be removed. */
1566       set_Block_block_visited(pred, get_irg_block_visited(current_ir_graph)-1);
1567       return 1;
1568     }
1569     /* Seems to be empty. */
1570     if (!get_irn_link(b)) {
1571       /* There are no Phi nodes ==> dispensable. */
1572       n_preds = get_Block_n_cfgpreds(pred);
1573     } else {
1574       /* b's pred blocks and pred's pred blocks must be pairwise disjunct.
1575          Work preds < pos as if they were already removed. */
1576       for (i = 0; i < pos; i++) {
1577         ir_node *b_pred = get_nodes_Block(get_Block_cfgpred(b, i));
1578         if (get_Block_block_visited(b_pred) + 1
1579             < get_irg_block_visited(current_ir_graph)) {
1580           for (j = 0; j < get_Block_n_cfgpreds(b_pred); j++) {
1581             ir_node *b_pred_pred = get_nodes_Block(get_Block_cfgpred(b_pred, j));
1582             if (is_pred_of(b_pred_pred, pred)) dispensable = 0;
1583           }
1584         } else {
1585           if (is_pred_of(b_pred, pred)) dispensable = 0;
1586         }
1587       }
1588       for (i = pos +1; i < get_Block_n_cfgpreds(b); i++) {
1589         ir_node *b_pred = get_nodes_Block(get_Block_cfgpred(b, i));
1590         if (is_pred_of(b_pred, pred)) dispensable = 0;
1591       }
1592       if (!dispensable) {
1593         set_Block_block_visited(pred, get_irg_block_visited(current_ir_graph)-1);
1594         n_preds = 1;
1595       } else {
1596         n_preds = get_Block_n_cfgpreds(pred);
1597       }
1598     }
1599   }
1600
1601   return n_preds;
1602 }
1603
1604 static void optimize_blocks(ir_node *b, void *env) {
1605   int i, j, k, max_preds, n_preds;
1606   ir_node *pred, *phi;
1607   ir_node **in;
1608
1609   /* Count the number of predecessor if this block is merged with pred blocks
1610      that are empty. */
1611   max_preds = 0;
1612   for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
1613     max_preds += test_whether_dispensable(b, i);
1614   }
1615   in = (ir_node **) malloc(max_preds * sizeof(ir_node *));
1616
1617 /**
1618   printf(" working on "); DDMN(b);
1619   for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
1620     pred = get_nodes_Block(get_Block_cfgpred(b, i));
1621     if (is_Bad(get_Block_cfgpred(b, i))) {
1622       printf("  removing Bad %i\n ", i);
1623     } else if (get_Block_block_visited(pred) +1
1624                < get_irg_block_visited(current_ir_graph)) {
1625       printf("  removing pred %i ", i); DDMN(pred);
1626     } else { printf("  Nothing to do for "); DDMN(pred); }
1627   }
1628   * end Debug output **/
1629
1630   /** Fix the Phi nodes **/
1631   phi = get_irn_link(b);
1632   while (phi) {
1633     assert(get_irn_op(phi) == op_Phi);
1634     /* Find the new predecessors for the Phi */
1635     n_preds = 0;
1636     for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
1637       pred = get_nodes_Block(get_Block_cfgpred(b, i));
1638       if (is_Bad(get_Block_cfgpred(b, i))) {
1639         /* Do nothing */
1640       } else if (get_Block_block_visited(pred) +1
1641                  < get_irg_block_visited(current_ir_graph)) {
1642         /* It's an empty block and not yet visited. */
1643         ir_node *phi_pred = get_Phi_pred(phi, i);
1644         for (j = 0; j < get_Block_n_cfgpreds(pred); j++) {
1645           if (get_nodes_Block(phi_pred) == pred) {
1646             assert(get_irn_op(phi_pred) == op_Phi);  /* Block is empty!! */
1647             in[n_preds] = get_Phi_pred(phi_pred, j);
1648           } else {
1649             in[n_preds] = phi_pred;
1650           }
1651           n_preds++;
1652         }
1653         /* The Phi_pred node is replaced now if it is a Phi.
1654            In Schleifen kann offenbar der entfernte Phi Knoten legal verwendet werden.
1655            Daher muss der Phiknoten durch den neuen ersetzt werden.
1656            Weiter muss der alte Phiknoten entfernt werden (durch ersetzen oder
1657            durch einen Bad) damit er aus den keep_alive verschwinden kann.
1658            Man sollte also, falls keine Schleife vorliegt, exchange mit new_Bad
1659            aufrufen.  */
1660         if (get_nodes_Block(phi_pred) == pred) {
1661           /* remove the Phi as it might be kept alive. Further there
1662              might be other users. */
1663           exchange(phi_pred, phi);  /* geht, ist aber doch semantisch falsch! Warum?? */
1664         }
1665       } else {
1666         in[n_preds] = get_Phi_pred(phi, i);
1667         n_preds ++;
1668       }
1669     }
1670     /* Fix the node */
1671     set_irn_in(phi, n_preds, in);
1672
1673     phi = get_irn_link(phi);
1674   }
1675
1676 /**
1677       This happens only if merge between loop backedge and single loop entry. **/
1678   for (k = 0; k < get_Block_n_cfgpreds(b); k++) {
1679     pred = get_nodes_Block(get_Block_cfgpred(b, k));
1680     if (get_Block_block_visited(pred) +1
1681         < get_irg_block_visited(current_ir_graph)) {
1682       phi = get_irn_link(pred);
1683       while (phi) {
1684         if (get_irn_op(phi) == op_Phi) {
1685           set_nodes_Block(phi, b);
1686
1687           n_preds = 0;
1688           for (i = 0; i < k; i++) {
1689             pred = get_nodes_Block(get_Block_cfgpred(b, i));
1690             if (is_Bad(get_Block_cfgpred(b, i))) {
1691               /* Do nothing */
1692             } else if (get_Block_block_visited(pred) +1
1693                        < get_irg_block_visited(current_ir_graph)) {
1694               /* It's an empty block and not yet visited. */
1695               for (j = 0; j < get_Block_n_cfgpreds(pred); j++) {
1696                 /* @@@ Hier brauche ich Schleifeninformation!!! Kontrollflusskante
1697                    muss Rueckwaertskante sein! (An allen vier in[n_preds] = phi
1698                    Anweisungen.) Trotzdem tuts bisher!! */
1699                 in[n_preds] = phi;
1700                 n_preds++;
1701               }
1702             } else {
1703               in[n_preds] = phi;
1704               n_preds++;
1705             }
1706           }
1707           for (i = 0; i < get_Phi_n_preds(phi); i++) {
1708             in[n_preds] = get_Phi_pred(phi, i);
1709             n_preds++;
1710           }
1711           for (i = k+1; i < get_Block_n_cfgpreds(b); i++) {
1712             pred = get_nodes_Block(get_Block_cfgpred(b, i));
1713             if (is_Bad(get_Block_cfgpred(b, i))) {
1714               /* Do nothing */
1715             } else if (get_Block_block_visited(pred) +1
1716                        < get_irg_block_visited(current_ir_graph)) {
1717               /* It's an empty block and not yet visited. */
1718               for (j = 0; j < get_Block_n_cfgpreds(pred); j++) {
1719                 in[n_preds] = phi;
1720                 n_preds++;
1721               }
1722             } else {
1723               in[n_preds] = phi;
1724               n_preds++;
1725             }
1726           }
1727           set_irn_in(phi, n_preds, in);
1728         }
1729         phi = get_irn_link(phi);
1730       }
1731     }
1732   }
1733
1734   /** Fix the block **/
1735   n_preds = 0;
1736   for (i = 0; i < get_Block_n_cfgpreds(b); i++) {
1737     pred = get_nodes_Block(get_Block_cfgpred(b, i));
1738     if (is_Bad(get_Block_cfgpred(b, i))) {
1739       /* Do nothing */
1740     } else if (get_Block_block_visited(pred) +1
1741                < get_irg_block_visited(current_ir_graph)) {
1742       /* It's an empty block and not yet visited. */
1743       assert(get_Block_n_cfgpreds(b) > 1);
1744                         /* Else it should be optimized by equivalent_node. */
1745       for (j = 0; j < get_Block_n_cfgpreds(pred); j++) {
1746         in[n_preds] = get_Block_cfgpred(pred, j);
1747         n_preds++;
1748       }
1749       /* Remove block as it might be kept alive. */
1750       exchange(pred, b/*new_Bad()*/);
1751     } else {
1752       in[n_preds] = get_Block_cfgpred(b, i);
1753       n_preds ++;
1754     }
1755   }
1756   set_irn_in(b, n_preds, in);
1757   free(in);
1758 }
1759
1760 void optimize_cf(ir_graph *irg) {
1761   int i;
1762   ir_node **in;
1763   ir_node *end = get_irg_end(irg);
1764   ir_graph *rem = current_ir_graph;
1765   current_ir_graph = irg;
1766
1767   /* Handle graph state */
1768   assert(get_irg_phase_state(irg) != phase_building);
1769   if (get_irg_outs_state(current_ir_graph) == outs_consistent)
1770     set_irg_outs_inconsistent(current_ir_graph);
1771   if (get_irg_dom_state(current_ir_graph) == dom_consistent)
1772     set_irg_dom_inconsistent(current_ir_graph);
1773
1774   /* Use block visited flag to mark non-empty blocks. */
1775   inc_irg_block_visited(irg);
1776   irg_walk(end, merge_blocks, collect_nodes, NULL);
1777
1778   /* Optimize the standard code. */
1779   irg_block_walk(get_irg_end_block(irg), optimize_blocks, NULL, NULL);
1780
1781   /* Walk all keep alives, optimize them if block, add to new in-array
1782      for end if useful. */
1783   in = NEW_ARR_F (ir_node *, 1);
1784   in[0] = get_nodes_Block(end);
1785   inc_irg_visited(current_ir_graph);
1786   for(i = 0; i < get_End_n_keepalives(end); i++) {
1787     ir_node *ka = get_End_keepalive(end, i);
1788     if (irn_not_visited(ka)) {
1789       if ((get_irn_op(ka) == op_Block) && Block_not_block_visited(ka)) {
1790         set_irg_block_visited(current_ir_graph,  /* Don't walk all the way to Start. */
1791                               get_irg_block_visited(current_ir_graph)-1);
1792         irg_block_walk(ka, optimize_blocks, NULL, NULL);
1793         mark_irn_visited(ka);
1794         ARR_APP1 (ir_node *, in, ka);
1795       } else if (get_irn_op(ka) == op_Phi) {
1796         mark_irn_visited(ka);
1797         ARR_APP1 (ir_node *, in, ka);
1798       }
1799     }
1800   }
1801   /* DEL_ARR_F(end->in);   GL @@@ tut nicht ! */
1802   end->in = in;
1803
1804   current_ir_graph = rem;
1805 }
1806
1807
1808 /**
1809  * Called by walker of remove_critical_cf_edges.
1810  *
1811  * Place an empty block to an edge between a blocks of multiple
1812  * predecessors and a block of multiple successors.
1813  *
1814  * @param n IR node
1815  * @param env Environment of walker. This field is unused and has
1816  *            the value NULL.
1817  */
1818 static void walk_critical_cf_edges(ir_node *n, void *env) {
1819   int arity, i;
1820   ir_node *pre, *block, **in, *jmp;
1821
1822   /* Block has multiple predecessors */
1823   if ((op_Block == get_irn_op(n)) &&
1824       (get_irn_arity(n) > 1)) {
1825     arity = get_irn_arity(n);
1826
1827     if (n == get_irg_end_block(current_ir_graph))
1828       return;  // No use to add a block here.
1829
1830     for (i=0; i<arity; i++) {
1831       pre = get_irn_n(n, i);
1832       /* Predecessor has multiple successors. Insert new flow edge */
1833       if ((NULL != pre) &&
1834           (op_Proj == get_irn_op(pre)) &&
1835           op_Raise != get_irn_op(skip_Proj(pre))) {
1836
1837         /* set predecessor array for new block */
1838         in = NEW_ARR_D (ir_node *, current_ir_graph->obst, 1);
1839         /* set predecessor of new block */
1840         in[0] = pre;
1841         block = new_Block(1, in);
1842         /* insert new jmp node to new block */
1843         switch_block(block);
1844         jmp = new_Jmp();
1845         switch_block(n);
1846         /* set successor of new block */
1847         set_irn_n(n, i, jmp);
1848
1849       } /* predecessor has multiple successors */
1850     } /* for all predecessors */
1851   } /* n is a block */
1852 }
1853
1854 void remove_critical_cf_edges(ir_graph *irg) {
1855   if (get_opt_critical_edges())
1856     irg_walk_graph(irg, NULL, walk_critical_cf_edges, NULL);
1857 }