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