695a8cbff21cefda34f885d450ed9582226fcead
[libfirm] / ir / ana / callgraph.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ana/callgraph.c
4  * Purpose:     Representation and computation of the callgraph.
5  * Author:      Goetz Lindenmaier
6  * Modified by:
7  * Created:     21.7.2004
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2004 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13 #include "config.h"
14 #include "callgraph.h"
15
16 #include "irloop_t.h"
17 #include "irprog_t.h"
18 #include "irgraph_t.h"
19 #include "irnode_t.h"
20
21 #include "array.h"
22 #include "pmap.h"
23
24 #include "irgwalk.h"
25
26 /* For callees, we want to remember the Call nodes, too. */
27 struct ana_entry {
28   ir_graph *irg;
29   ir_node  *call_list;
30   int       max_depth;
31 };
32
33 typedef struct ana_entry ana_entry;
34
35 static int master_cg_visited = 0;
36 static INLINE int  cg_irg_visited     (ir_graph *n);
37 static INLINE void mark_cg_irg_visited(ir_graph *n);
38 static INLINE void set_cg_irg_visited (ir_graph *n, int i);
39
40 irp_callgraph_state get_irp_callgraph_state(void) {
41   return irp->callgraph_state;
42 }
43 void                set_irp_callgraph_state(irp_callgraph_state s) {
44   irp->callgraph_state = s;
45 }
46
47 /* The functions that call irg. */
48 int       get_irg_n_callers(ir_graph *irg) {
49   if (irg->callers) return ARR_LEN(irg->callers);
50   return -1;
51 }
52 ir_graph *get_irg_caller(ir_graph *irg, int pos) {
53   assert (pos >= 0 && pos < get_irg_n_callers(irg));
54   if (irg->callers) return irg->callers[pos];
55   return NULL;
56 }
57 int       is_irg_caller_backedge(ir_graph *irg, int pos) {
58   assert (pos >= 0 && pos < get_irg_n_callers(irg));
59   return  irg->caller_isbe[pos];
60 }
61
62 static void       set_irg_caller_backedge(ir_graph *irg, ir_graph *caller) {
63   int i, n_callers = get_irg_n_callers(irg);
64   for (i = 0; i < n_callers; ++i) {
65     if (get_irg_caller(irg, i) == caller) {
66       irg->caller_isbe[i] = 1;
67       break;
68     }
69   }
70 }
71
72 int       has_irg_caller_backedge(ir_graph *irg) {
73   int i, n_callers = get_irg_n_callers(irg);
74   for (i = 0; i < n_callers; ++i)
75     if (is_irg_caller_backedge(irg, i)) return 1;
76   return 0;
77 }
78
79 int get_irg_caller_loop_depth(ir_graph *irg, int pos) {
80   ir_graph *caller = get_irg_caller(irg, pos);
81
82   /* search the other relation for the corresponding edge. */
83   int pos_callee = -1;
84   int i, n_callees = get_irg_n_callees(caller);
85   for (i = 0; i < n_callees; ++i) {
86     if (get_irg_callee(caller, i) == irg) {
87       pos_callee = i;
88       break;
89     }
90   }
91
92   assert(pos_callee >= 0);
93
94   return get_irg_callee_loop_depth(caller, pos_callee);
95 }
96
97
98 /* The functions called by irg. */
99 int       get_irg_n_callees(ir_graph *irg) {
100   if (irg->callees) return ARR_LEN(irg->callees);
101   return -1;
102 }
103 ir_graph *get_irg_callee(ir_graph *irg, int pos) {
104   assert (pos >= 0 && pos < get_irg_n_callees(irg));
105   if (irg->callees) return ((ana_entry *)irg->callees[pos])->irg;
106   return NULL;
107 }
108 int       is_irg_callee_backedge(ir_graph *irg, int pos) {
109   assert (pos >= 0 && pos < get_irg_n_callees(irg));
110   return irg->callee_isbe[pos];
111 }
112 int       has_irg_callee_backedge(ir_graph *irg) {
113   int i, n_callees = get_irg_n_callees(irg);
114   for (i = 0; i < n_callees; ++i)
115     if (is_irg_callee_backedge(irg, i)) return 1;
116   return 0;
117 }
118 void       set_irg_callee_backedge(ir_graph *irg, int pos) {
119   assert (pos >= 0 && pos < get_irg_n_callees(irg));
120   irg->callee_isbe[pos] = 1;
121 }
122
123 int get_irg_callee_loop_depth(ir_graph *irg, int pos) {
124   assert (pos >= 0 && pos < get_irg_n_callees(irg));
125   if (irg->callees) return ((ana_entry *)irg->callees[pos])->max_depth;
126   return -1;
127 }
128
129 /* --------------------- Compute the callgraph ------------------------ */
130
131
132 static void ana_Call(ir_node *n, void *env) {
133   int i, n_callees;
134   ir_graph *irg;
135
136   if (get_irn_op(n) != op_Call) return;
137
138   irg = get_irn_irg(n);
139   n_callees = get_Call_n_callees(n);
140   for (i = 0; i < n_callees; ++i) {
141     entity *callee_e = get_Call_callee(n, i);
142     if (callee_e) {  /* Null for unknown caller */
143       ir_graph *callee = get_entity_irg(callee_e);
144       pset_insert((pset *)callee->callers, irg, (unsigned)irg >> 3);
145
146       ana_entry buf = { callee, NULL, 0};
147       ana_entry *found = pset_find((pset *)irg->callees, &buf, (unsigned)callee >> 3);
148       if (found) {  /* add Call node to list, compute new nesting. */
149       } else { /* New node, add Call node and init nesting. */
150         found = (ana_entry *) obstack_alloc (irg->obst, sizeof (ana_entry));
151         found->irg = callee;
152         found->call_list = NULL;
153         found->max_depth = 0;
154         pset_insert((pset *)irg->callees, found, (unsigned)callee >> 3);
155       }
156       int depth = get_loop_depth(get_irn_loop(get_nodes_block(n)));
157       found->max_depth = (depth > found->max_depth) ? depth : found->max_depth;
158     }
159   }
160 }
161
162 /* compare two ir graphs */
163 static int ana_entry_cmp(const void *elt, const void *key) {
164   ana_entry *e1 = (ana_entry *)elt;
165   ana_entry *e2 = (ana_entry *)key;
166   return e1->irg != e2->irg;
167 }
168
169 /* compare two ir graphs */
170 static int graph_cmp(const void *elt, const void *key) {
171   return elt != key;
172 }
173
174
175 /* Construct and destruct the callgraph. */
176 void compute_callgraph(void) {
177   int i, n_irgs = get_irp_n_irgs();
178
179   assert(interprocedural_view == 0);  /* Else walking will not reach the Call nodes. */
180
181   /* initialize */
182   free_callgraph();
183   for (i = 0; i < n_irgs; ++i) {
184     ir_graph *irg = get_irp_irg(i);
185     assert(get_irg_callee_info_state(irg) == irg_callee_info_consistent);
186     irg->callees = (ir_graph **)new_pset(ana_entry_cmp, 8);
187     irg->callers = (ir_graph **)new_pset(graph_cmp, 8);
188     construct_cf_backedges(irg);
189   }
190
191   /* Compute the call graph */
192   for (i = 0; i < n_irgs; ++i) {
193     ir_graph *irg = get_irp_irg(i);
194     construct_cf_backedges(irg);
195     irg_walk_graph(irg, ana_Call, NULL, NULL);
196   }
197
198   /* Change the sets to arrays. */
199   for (i = 0; i < n_irgs; ++i) {
200     int j, count;
201     ir_graph *c, *irg = get_irp_irg(i);
202
203     pset *callee_set = (pset *)irg->callees;
204     count = pset_count(callee_set);
205     irg->callees = NEW_ARR_F(ir_graph *, count);
206     irg->callee_isbe = calloc(count, sizeof(int));
207     c = pset_first(callee_set);
208     for (j = 0; j < count; ++j) {
209       irg->callees[j] = c;
210       c = pset_next(callee_set);
211     }
212     del_pset(callee_set);
213     assert(c == NULL);
214
215     pset *caller_set = (pset *)irg->callers;
216     count = pset_count(caller_set);
217     irg->callers = NEW_ARR_F(ir_graph *, count);
218     irg->caller_isbe =  calloc(count, sizeof(int));
219     c = pset_first(caller_set);
220     for (j = 0; j < count; ++j) {
221       irg->callers[j] = c;
222       c = pset_next(caller_set);
223     }
224     del_pset(caller_set);
225     assert(c == NULL);
226   }
227   set_irp_callgraph_state(irp_callgraph_consistent);
228 }
229
230 void free_callgraph(void) {
231   int i, n_irgs = get_irp_n_irgs();
232   for (i = 0; i < n_irgs; ++i) {
233     ir_graph *irg = get_irp_irg(i);
234     if (irg->callees) DEL_ARR_F(irg->callees);
235     if (irg->callers) DEL_ARR_F(irg->callers);
236     if (irg->callee_isbe) DEL_ARR_F(irg->callee_isbe);
237     if (irg->caller_isbe) DEL_ARR_F(irg->caller_isbe);
238     irg->callees = NULL;
239     irg->callers = NULL;
240     irg->callee_isbe = NULL;
241     irg->caller_isbe = NULL;
242   }
243   set_irp_callgraph_state(irp_callgraph_none);
244 }
245
246 /* ----------------------------------------------------------------------------------- */
247 /* A walker for the callgraph                                                          */
248 /* ----------------------------------------------------------------------------------- */
249
250
251 static void do_walk(ir_graph *irg, callgraph_walk_func *pre, callgraph_walk_func *post, void *env) {
252   int i, n_callees;
253
254   if (cg_irg_visited(irg)) return;
255   mark_cg_irg_visited(irg);
256
257   pre(irg, env);
258
259   n_callees = get_irg_n_callees(irg);
260   for (i = 0; i < n_callees; i++) {
261     ir_graph *m = get_irg_callee(irg, i);
262     do_walk(m, pre, post, env);
263   }
264
265   post(irg, env);
266 }
267
268 void callgraph_walk(callgraph_walk_func *pre, callgraph_walk_func *post, void *env) {
269   int i, n_irgs = get_irp_n_irgs();
270   master_cg_visited++;
271
272   do_walk(get_irp_main_irg(), pre, post, env);
273   for (i = 0; i < n_irgs; i++) {
274     ir_graph *irg = get_irp_irg(i);
275     if (!cg_irg_visited(irg) && get_irg_n_callers(irg) == 0)
276       do_walk(irg, pre, post, env);
277   }
278   for (i = 0; i < n_irgs; i++) {
279     ir_graph *irg = get_irp_irg(i);
280     if (!cg_irg_visited(irg))
281       do_walk(irg, pre, post, env);
282   }
283 }
284
285 /* ----------------------------------------------------------------------------------- */
286 /* loop construction algorithm                                                         */
287 /* ----------------------------------------------------------------------------------- */
288
289 static ir_graph *outermost_ir_graph;      /* The outermost graph the scc is computed
290                       for */
291 static ir_loop *current_loop;      /* Current cfloop construction is working
292                       on. */
293 static int loop_node_cnt = 0;      /* Counts the number of allocated cfloop nodes.
294                       Each cfloop node gets a unique number.
295                       What for? ev. remove. @@@ */
296 static int current_dfn = 1;        /* Counter to generate depth first numbering
297                       of visited nodes.  */
298
299
300 /**********************************************************************/
301 /* Node attributes                                                   **/
302 /**********************************************************************/
303
304 typedef struct scc_info {
305   bool in_stack;         /* Marks whether node is on the stack. */
306   int dfn;               /* Depth first search number. */
307   int uplink;            /* dfn number of ancestor. */
308   int visited;
309 } scc_info;
310
311 static INLINE scc_info* new_scc_info(void) {
312   scc_info *info = obstack_alloc (outermost_ir_graph->obst, sizeof (scc_info));
313   memset (info, 0, sizeof (scc_info));
314   return info;
315 }
316
317 static INLINE int
318 cg_irg_visited(ir_graph *n) {
319   return (((scc_info *)n->link)->visited >= master_cg_visited);
320 }
321
322 static INLINE void
323 mark_cg_irg_visited(ir_graph *n) {
324   ((scc_info *)n->link)->visited = master_cg_visited;
325 }
326
327 static INLINE void
328 set_cg_irg_visited(ir_graph *n, int i) {
329   ((scc_info *)n->link)->visited = i;
330 }
331
332 static INLINE int
333 get_cg_irg_visited(ir_graph *n) {
334   return ((scc_info *)n->link)->visited;
335 }
336
337 static INLINE void
338 mark_irg_in_stack (ir_graph *n) {
339   assert(get_irg_link(n));
340   ((scc_info *)n->link)->in_stack = true;
341 }
342
343 static INLINE void
344 mark_irg_not_in_stack (ir_graph *n) {
345   assert(get_irg_link(n));
346   ((scc_info *)n->link)->in_stack = false;
347 }
348
349 static INLINE bool
350 irg_is_in_stack (ir_graph *n) {
351   assert(get_irg_link(n));
352   return ((scc_info *)n->link)->in_stack;
353 }
354
355 static INLINE void
356 set_irg_uplink (ir_graph *n, int uplink) {
357   assert(get_irg_link(n));
358   ((scc_info *)n->link)->uplink = uplink;
359 }
360
361 static INLINE int
362 get_irg_uplink (ir_graph *n) {
363   assert(get_irg_link(n));
364   return ((scc_info *)n->link)->uplink;
365 }
366
367 static INLINE void
368 set_irg_dfn (ir_graph *n, int dfn) {
369   assert(get_irg_link(n));
370   ((scc_info *)n->link)->dfn = dfn;
371 }
372
373 static INLINE int
374 get_irg_dfn (ir_graph *n) {
375   assert(get_irg_link(n));
376   return ((scc_info *)n->link)->dfn;
377 }
378
379 /**********************************************************************/
380 /* A stack.                                                          **/
381 /**********************************************************************/
382
383 static ir_graph **stack = NULL;
384 static int tos = 0;                /* top of stack */
385
386 static INLINE void init_stack(void) {
387   if (stack) {
388     ARR_RESIZE (ir_graph *, stack, 1000);
389   } else {
390     stack = NEW_ARR_F (ir_graph *, 1000);
391   }
392   tos = 0;
393 }
394
395
396 static INLINE void
397 push (ir_graph *n)
398 {
399   if (tos == ARR_LEN (stack)) {
400     int nlen = ARR_LEN (stack) * 2;
401     ARR_RESIZE (ir_node *, stack, nlen);
402   }
403   stack [tos++] = n;
404   mark_irg_in_stack(n);
405 }
406
407 static INLINE ir_graph *
408 pop (void)
409 {
410   ir_graph *n = stack[--tos];
411   mark_irg_not_in_stack(n);
412   return n;
413 }
414
415 /* The nodes up to n belong to the current loop.
416    Removes them from the stack and adds them to the current loop. */
417 static INLINE void
418 pop_scc_to_loop (ir_graph *n)
419 {
420   ir_graph *m;
421
422   do {
423     m = pop();
424     loop_node_cnt++;
425     set_irg_dfn(m, loop_node_cnt);
426     add_loop_node(current_loop, (ir_node *)m);
427     m->l = current_loop;
428     //m->callgraph_loop_depth = current_loop->depth;
429   } while(m != n);
430 }
431
432 /* GL ??? my last son is my grandson???  Removes cfloops with no
433    ir_nodes in them.  Such loops have only another loop as son. (Why
434    can't they have two loops as sons? Does it never get that far? ) */
435 static void close_loop (ir_loop *l)
436 {
437   int last = get_loop_n_elements(l) - 1;
438   loop_element lelement = get_loop_element(l, last);
439   ir_loop *last_son = lelement.son;
440
441   if (get_kind(last_son) == k_ir_loop &&
442       get_loop_n_elements(last_son) == 1) {
443     ir_loop *gson;
444
445     lelement = get_loop_element(last_son, 0);
446     gson = lelement.son;
447     if(get_kind(gson) == k_ir_loop) {
448       loop_element new_last_son;
449
450       gson -> outer_loop = l;
451       new_last_son.son = gson;
452       l -> children[last] = new_last_son;
453     }
454   }
455
456   current_loop = l;
457 }
458
459 /* Removes and unmarks all nodes up to n from the stack.
460    The nodes must be visited once more to assign them to a scc. */
461 static INLINE void
462 pop_scc_unmark_visit (ir_graph *n)
463 {
464   ir_graph *m = NULL;
465
466   while (m != n) {
467     m = pop();
468     set_cg_irg_visited(m, 0);
469   }
470 }
471
472 /**********************************************************************/
473 /* The loop datastructure.                                           **/
474 /**********************************************************************/
475
476 /* Allocates a new loop as son of current_loop.  Sets current_loop
477    to the new loop and returns the father. */
478 static ir_loop *new_loop (void) {
479   ir_loop *father, *son;
480
481   father = current_loop;
482
483   son = (ir_loop *) obstack_alloc (outermost_ir_graph->obst, sizeof (ir_loop));
484   memset (son, 0, sizeof (ir_loop));
485   son->kind = k_ir_loop;
486   son->children = NEW_ARR_F (loop_element, 0);
487   son->n_nodes = 0;
488   son->n_sons = 0;
489   if (father) {
490     son->outer_loop = father;
491     add_loop_son(father, son);
492     son->depth = father->depth+1;
493   } else {  /* The root loop */
494     son->outer_loop = son;
495     son->depth = 0;
496   }
497
498 #ifdef DEBUG_libfirm
499   son->loop_nr = get_irp_new_node_nr();
500   son->link = NULL;
501 #endif
502
503   current_loop = son;
504   return father;
505 }
506
507 /**********************************************************************/
508 /* Constructing and destructing the loop/backedge information.       **/
509 /**********************************************************************/
510
511 /* Initialization steps. **********************************************/
512
513 static INLINE void
514 init_scc (void) {
515   int i;
516   current_dfn = 1;
517   loop_node_cnt = 0;
518   init_stack();
519   for (i = 0; i < get_irp_n_irgs(); ++i) {
520     set_irg_link(get_irp_irg(i), new_scc_info());
521     get_irp_irg(i)->callgraph_recursion_depth = 0;
522     get_irp_irg(i)->callgraph_loop_depth = 0;
523     get_irp_irg(i)->callgraph_weighted_loop_depth = 0;
524   }
525 }
526
527 /** Returns true if n is a loop header, i.e., it is a Block node
528  *  and has predecessors within the cfloop and out of the cfloop.
529  *
530  *  @param root: only needed for assertion.
531  */
532 static bool
533 is_head (ir_graph *n, ir_graph *root)
534 {
535   int i, arity;
536   int some_outof_loop = 0, some_in_loop = 0;
537
538   arity = get_irg_n_callees(n);
539   for (i = 0; i < arity; i++) {
540     ir_graph *pred = get_irg_callee(n, i);
541     if (is_irg_callee_backedge(n, i)) continue;
542     if (!irg_is_in_stack(pred)) {
543       some_outof_loop = 1;
544     } else {
545       if (get_irg_uplink(pred) < get_irg_uplink(root))  {
546         DDMG(pred); DDMG(root);
547         assert(get_irg_uplink(pred) >= get_irg_uplink(root));
548       }
549       some_in_loop = 1;
550     }
551   }
552
553   return some_outof_loop && some_in_loop;
554 }
555 /* Returns true if n is possible loop head of an endless loop.
556    I.e., it is a Block, Phi or Filter node and has only predecessors
557    within the loop.
558    @arg root: only needed for assertion. */
559 static bool
560 is_endless_head (ir_graph *n, ir_graph *root)
561 {
562   int i, arity;
563   int some_outof_loop = 0, some_in_loop = 0;
564
565   arity = get_irg_n_callees(n);
566   for (i = 0; i < arity; i++) {
567     ir_graph *pred = get_irg_callee(n, i);
568     assert(pred);
569     if (is_irg_callee_backedge(n, i)) { continue; }
570     if (!irg_is_in_stack(pred)) {
571         some_outof_loop = 1;
572     } else {
573       if(get_irg_uplink(pred) < get_irg_uplink(root)) {
574         DDMG(pred); DDMG(root);
575         assert(get_irg_uplink(pred) >= get_irg_uplink(root));
576       }
577       some_in_loop = 1;
578     }
579   }
580
581   return !some_outof_loop && some_in_loop;
582 }
583
584
585 /* Check whether there is a parallel edge in the ip control flow.
586    Only */
587 static bool
588 is_ip_head (ir_graph *n, ir_graph *pred)
589 {
590   int iv_rem = interprocedural_view;
591   interprocedural_view = 1;
592   ir_node *sblock = get_irg_start_block(n);
593   int i, arity = get_Block_n_cfgpreds(sblock);
594   int is_be = 0;
595
596   //printf(" edge from "); DDMG(n);
597   //printf(" to pred   "); DDMG(pred);
598   //printf(" sblock    "); DDMN(sblock);
599
600   for (i = 0; i < arity; i++) {
601     ir_node *pred_cfop = skip_Proj(get_Block_cfgpred(sblock, i));
602     //printf("  "); DDMN(pred_cfop);
603     if (get_irn_op(pred_cfop) == op_CallBegin) {  /* could be Unknown */
604       ir_graph *ip_pred = get_irn_irg(pred_cfop);
605       //printf("   "); DDMG(ip_pred);
606       if ((ip_pred == pred) && is_backedge(sblock, i)) {
607         //printf("   found\n");
608         is_be = 1;
609       }
610     }
611   }
612
613   interprocedural_view = iv_rem;
614   return is_be;
615 }
616
617 /* Returns index of the predecessor with the smallest dfn number
618    greater-equal than limit. */
619 static int
620 smallest_dfn_pred (ir_graph *n, int limit)
621 {
622   int i, index = -2, min = -1;
623
624   int arity = get_irg_n_callees(n);
625   for (i = 0; i < arity; i++) {
626     ir_graph *pred = get_irg_callee(n, i);
627     if (is_irg_callee_backedge(n, i) || !irg_is_in_stack(pred)) continue;
628     if (get_irg_dfn(pred) >= limit && (min == -1 || get_irg_dfn(pred) < min)) {
629       index = i;
630       min = get_irg_dfn(pred);
631     }
632   }
633
634   return index;
635 }
636
637 /* Returns index of the predecessor with the largest dfn number. */
638 static int
639 largest_dfn_pred (ir_graph *n)
640 {
641   int i, index = -2, max = -1;
642
643   int arity = get_irg_n_callees(n);
644   for (i = 0; i < arity; i++) {
645     ir_graph *pred = get_irg_callee(n, i);
646     if (is_irg_callee_backedge (n, i) || !irg_is_in_stack(pred)) continue;
647     if (get_irg_dfn(pred) > max) {
648       index = i;
649       max = get_irg_dfn(pred);
650     }
651   }
652
653   return index;
654 }
655
656 #if 0
657 static ir_graph *
658 find_tail (ir_graph *n) {
659   ir_graph *m;
660   int i, res_index = -2;
661
662   /*
663     if (!icfg && rm_cyclic_phis && remove_cyclic_phis (n)) return NULL;
664   */
665   m = stack[tos-1];  /* tos = top of stack */
666   if (is_head (m, n)) {
667     res_index = smallest_dfn_pred(m, 0);
668     if ((res_index == -2) &&  /* no smallest dfn pred found. */
669     (n == m))
670       return NULL;
671   } else {
672     if (m == n) return NULL;    // Is this to catch Phi - self loops?
673     for (i = tos-2; i >= 0; --i) {
674       m = stack[i];
675
676       if (is_head (m, n)) {
677         res_index = smallest_dfn_pred (m, get_irg_dfn(m) + 1);
678         if (res_index == -2)  /* no smallest dfn pred found. */
679           res_index = largest_dfn_pred (m);
680
681         if ((m == n) && (res_index == -2)) {
682           i = -1;
683         }
684         break;
685       }
686
687       /* We should not walk past our selves on the stack:  The upcoming nodes
688          are not in this loop. We assume a loop not reachable from Start. */
689       if (m == n) {
690         i = -1;
691         break;
692       }
693
694     }
695
696     if (i < 0) {
697       /* A dead loop not reachable from Start. */
698       for (i = tos-2; i >= 0; --i) {
699         m = stack[i];
700         if (is_endless_head (m, n)) {
701           res_index = smallest_dfn_pred (m, get_irg_dfn(m) + 1);
702           if (res_index == -2)  /* no smallest dfn pred found. */
703             res_index = largest_dfn_pred (m);
704           break;
705         }
706         if (m == n) { break; }  /* It's not an unreachable loop, either. */
707       }
708       //assert(0 && "no head found on stack");
709     }
710
711   }
712   assert (res_index > -2);
713
714   set_irg_callee_backedge (m, res_index);
715   return get_irg_callee(m, res_index);
716 }
717 #else
718 static ir_graph *
719 find_tail (ir_graph *n) {
720   ir_graph *m;
721   int i, res_index = -2;
722
723   ir_graph *in_and_out    = NULL;
724   ir_graph *only_in       = NULL;
725   ir_graph *ip_in_and_out = NULL;
726   ir_graph *ip_only_in    = NULL;
727
728   //printf("find tail for "); DDMG(n);
729
730   for (i = tos-1; i >= 0; --i) {
731     ir_graph *pred = (i < tos -1) ? stack[i+1] : n;
732     m = stack[i];
733
734     if (is_head (m, n)) {
735       //printf(" found 1a! "); DDM;
736       in_and_out = m;
737       if (is_ip_head(pred, m)) {
738         //printf(" found 1b! "); DDM;
739         ip_in_and_out = m;
740       }
741     } else if (!ip_only_in && is_endless_head(m, n)) {
742       only_in = m;
743       //printf(" found 2a! "); DDM;
744       if (is_ip_head(pred, m)) {
745         //printf(" found 2b! "); DDM;
746         ip_only_in = m;
747       }
748     } else if (is_ip_head(pred, m)) {
749       //printf(" found 3! "); DDM;   This happens for self recursions in the second
750       //assert(0);                   scc iteration (the one to flip the loop.)
751     }
752
753     if (ip_in_and_out) break;    /* That's what we really want. */
754
755     if (m == n) break;   /* Don't walk past n on the stack! */
756   }
757
758
759   if (!in_and_out && !only_in)
760     /* There is no loop */
761     return NULL;
762
763
764   /* Is there a head in the callgraph without a head in the
765      ip cf graph? */
766   assert(in_and_out || only_in);
767
768   m = (ip_in_and_out) ? ip_in_and_out : ip_only_in;
769
770   if (!m)
771     m = (in_and_out) ? in_and_out : only_in;
772
773   //printf("*** head is "); DDMG(m);
774
775   res_index = smallest_dfn_pred (m, get_irg_dfn(m) + 1);
776   if (res_index == -2)  /* no smallest dfn pred found. */
777     res_index = largest_dfn_pred (m);
778
779   set_irg_callee_backedge (m, res_index);
780   ir_graph *res = get_irg_callee(m, res_index);
781   //printf("*** tail is "); DDMG(res);
782   return res;
783 }
784 #endif
785
786
787 /*-----------------------------------------------------------*
788  *                   The core algorithm.                     *
789  *-----------------------------------------------------------*/
790
791
792 static void cgscc (ir_graph *n) {
793   int i;
794
795   if (cg_irg_visited(n)) return;
796   mark_cg_irg_visited(n);
797
798   /* Initialize the node */
799   set_irg_dfn(n, current_dfn);      /* Depth first number for this node */
800   set_irg_uplink(n, current_dfn);   /* ... is default uplink. */
801   current_dfn ++;
802   push(n);
803
804   int arity = get_irg_n_callees(n);
805
806   for (i = 0; i < arity; i++) {
807     ir_graph *m;
808     if (is_irg_callee_backedge(n, i)) continue;
809     m = get_irg_callee(n, i);
810
811     /** This marks the backedge, but does it guarantee a correct loop tree? */
812     //if (m == n) { set_irg_callee_backedge(n, i); continue; }
813
814     cgscc (m);
815     if (irg_is_in_stack(m)) {
816       /* Uplink of m is smaller if n->m is a backedge.
817          Propagate the uplink to mark the cfloop. */
818       if (get_irg_uplink(m) < get_irg_uplink(n))
819         set_irg_uplink(n, get_irg_uplink(m));
820     }
821   }
822
823   if (get_irg_dfn(n) == get_irg_uplink(n)) {
824     /* This condition holds for
825        1) the node with the incoming backedge.
826        That is: We found a cfloop!
827        2) Straight line code, because no uplink has been propagated, so the
828        uplink still is the same as the dfn.
829
830        But n might not be a proper cfloop head for the analysis. Proper cfloop
831        heads are Block and Phi nodes. find_tail searches the stack for
832        Block's and Phi's and takes those nodes as cfloop heads for the current
833        cfloop instead and marks the incoming edge as backedge. */
834
835     ir_graph *tail = find_tail(n);
836     if (tail) {
837       /* We have a cfloop, that is no straight line code,
838          because we found a cfloop head!
839          Next actions: Open a new cfloop on the cfloop tree and
840          try to find inner cfloops */
841
842
843       ir_loop *l = new_loop();
844
845       /* Remove the cfloop from the stack ... */
846       pop_scc_unmark_visit (n);
847
848       /* The current backedge has been marked, that is temporarily eliminated,
849          by find tail. Start the scc algorithm
850          anew on the subgraph thats left (the current cfloop without the backedge)
851          in order to find more inner cfloops. */
852
853       cgscc (tail);
854
855       assert (cg_irg_visited(n));
856       close_loop(l);
857     } else {
858       pop_scc_to_loop(n);
859     }
860   }
861 }
862
863
864
865 static void reset_isbe(void) {
866   int i, n_irgs = get_irp_n_irgs();
867
868   for (i = 0; i < n_irgs; ++i) {
869     int j, n_cs;
870     ir_graph *irg = get_irp_irg(i);
871
872     n_cs = get_irg_n_callers(irg);
873     for (j = 0; j < n_cs; ++j) {
874       irg->caller_isbe[j] = 0;
875     }
876     n_cs = get_irg_n_callees(irg);
877     for (j = 0; j < n_cs; ++j) {
878       irg->callee_isbe[j] = 0;
879     }
880   }
881 }
882
883 static int in_same_loop(ir_graph *irg1, ir_graph *irg2) {
884   return irg1->l == irg2->l;
885 }
886
887 /* Returns true if loop depth of low < high and low on
888    a path from high to tree root. */
889 static int in_lower_loop(ir_graph *high, ir_graph *low) {
890   ir_loop *highl = high->l;
891   ir_loop *lowl  = low->l;
892   if (get_loop_depth(lowl) < get_loop_depth(highl)) {
893     while (get_loop_outer_loop(highl) != highl) {
894       highl = get_loop_outer_loop(highl);
895       if (highl == lowl) return 1;
896     }
897   }
898   return 0;
899 }
900
901
902 /* compute nesting depth */
903 static void cnd(ir_loop *loop) {
904   int i, n_elems = get_loop_n_elements(loop);
905
906   int same_sum = 0;
907   int max_lower_edge_max = 0;
908
909
910   /* Compute the value for this loop.  Deeper loops use this value. */
911   for (i = 0; i < n_elems; i++) {
912     loop_element le = get_loop_element(loop, i);
913     if (*le.kind == k_ir_graph) {
914       ir_graph *irg = (ir_graph *)le.node;
915       int j, n_callers = get_irg_n_callers(irg);
916       int same_edge_max = 0;
917       int loop_entry_max = 0;
918
919       for (j = 0; j < n_callers; ++j) {
920         ir_graph *caller = get_irg_caller(irg, j);
921         int caller_loop_depth = get_irg_caller_loop_depth(irg, j);
922
923
924         if (in_same_loop(irg, caller))
925           same_edge_max = (same_edge_max < caller_loop_depth) ? caller_loop_depth
926                                                               : same_edge_max;
927         if (in_lower_loop(irg, caller)) {
928           int loop_entry_this = caller_loop_depth + caller->l->weighted_depth;
929           loop_entry_max = (loop_entry_max < loop_entry_this) ? loop_entry_this
930                                                               : loop_entry_max;
931         }
932       }
933
934       max_lower_edge_max = (max_lower_edge_max < loop_entry_max) ? max_lower_edge_max
935                                                                  : loop_entry_max;
936       same_sum += same_edge_max;
937     }
938
939     /* This loop is as expensive as the most expensive entry edge + the count of the cycle. */
940     loop->weighted_depth =  max_lower_edge_max + same_sum + 1;    /* 1 for the recursion itself */
941   }
942
943   /* Recur. */
944   for (i = 0; i < n_elems; i++) {
945     loop_element le = get_loop_element(loop, i);
946     if (*le.kind == k_ir_loop)
947       cnd(le.son);
948   }
949 }
950
951
952 /* ----------------------------------------------------------------------------------- */
953 /* Another algorithm to compute recursion nesting depth                                */
954 /* Walk the callgraph.  For each crossed edge increase the loop depth by the edge      */
955 /* weight. Assign graphs the maximal depth.                                            */
956 /* ----------------------------------------------------------------------------------- */
957
958 void compute_loop_depth (ir_graph *irg, void *env) {
959   int current_nesting = *(int *) env;
960   int i, n_callees;
961
962   if (cg_irg_visited(irg)) return;
963   mark_cg_irg_visited(irg);
964
965   if (current_nesting == 0 || irg->callgraph_loop_depth < current_nesting) {
966     /* Don't walk the graph, but a tree that is an unfolded graph. */
967     n_callees = get_irg_n_callees(irg);
968     for (i = 0; i < n_callees; i++) {
969       ir_graph *m = get_irg_callee(irg, i);
970       *(int *)env += get_irg_callee_loop_depth(irg, i);
971       compute_loop_depth(m, env);
972       *(int *)env -= get_irg_callee_loop_depth(irg, i);
973     }
974   }
975
976   if (irg->callgraph_loop_depth < current_nesting)
977     irg->callgraph_loop_depth = current_nesting;
978
979   set_cg_irg_visited(irg, master_cg_visited-1);
980 }
981
982
983 /* ----------------------------------------------------------------------------------- */
984 /* Another algorithm to compute recursion nesting depth                                */
985 /* Walk the callgraph.  For each crossed loop increase the nesting depth by one.       */
986 /* Assign graphs the maximal nesting depth.   Don't increas if passing loops more than */
987 /* once.                                                                               */
988 /* ----------------------------------------------------------------------------------- */
989
990
991 /* For callees, we want to remember the Call nodes, too. */
992 struct ana_entry2 {
993   ir_loop **loop_stack;
994   int tos;
995   int recursion_nesting;
996 };
997
998 typedef struct ana_entry2 ana_entry2;
999
1000 static void push2(ana_entry2 *e, ir_loop *g) {
1001   if (ARR_LEN(e->loop_stack) == e->tos) {
1002     ARR_APP1(ir_loop *, e->loop_stack, g);
1003   } else {
1004     e->loop_stack[e->tos] = g;
1005   }
1006   e->tos ++;
1007 }
1008
1009 static ir_loop *pop2(ana_entry2 *e) {
1010   e->tos --;
1011   return e->loop_stack[e->tos+1];
1012 }
1013
1014 static int in_stack(ana_entry2 *e, ir_loop *g) {
1015   int i;
1016   for (i = e->tos-1; i >= 0; --i) {
1017     if (e->loop_stack[i] == g) return 1;
1018   }
1019   return 0;
1020 }
1021
1022 void compute_rec_depth (ir_graph *irg, void *env) {
1023   ana_entry2 *e = (ana_entry2 *)env;
1024   ir_loop *l = irg->l;
1025   int depth;
1026   int i, n_callees;
1027   int pushed = 0;
1028
1029   if (cg_irg_visited(irg)) return;
1030   mark_cg_irg_visited(irg);
1031
1032   if ((l != irp->outermost_cg_loop) && !in_stack(e, l)) {
1033     push2(e, l);
1034     e->recursion_nesting++;
1035     pushed = 1;
1036   }
1037   depth = e->recursion_nesting;
1038
1039   if (depth == 0 || irg->callgraph_recursion_depth < depth) {
1040     /* Don't walk the graph, but a tree that is an unfolded graph. */
1041     n_callees = get_irg_n_callees(irg);
1042     for (i = 0; i < n_callees; i++) {
1043       ir_graph *m = get_irg_callee(irg, i);
1044       compute_rec_depth(m, env);
1045     }
1046   }
1047
1048   if (irg->callgraph_recursion_depth < depth)
1049     irg->callgraph_recursion_depth = depth;
1050
1051   if (pushed) {
1052     pop2(e);
1053     e->recursion_nesting--;
1054   }
1055   set_cg_irg_visited(irg, master_cg_visited-1);
1056 }
1057
1058
1059 /* Compute the backedges that represent recursions. */
1060 void find_callgraph_recursions(void) {
1061   int i, n_irgs = get_irp_n_irgs();
1062
1063   reset_isbe();
1064
1065   /* -- Compute the looptree -- */
1066
1067   /* The outermost graph.  We start here.  Then we start at all
1068      functions in irg list that are never called, then at the remaining
1069      unvisited ones. */
1070   assert(get_irp_main_irg());
1071   outermost_ir_graph = get_irp_main_irg();
1072   init_scc();
1073
1074   current_loop = NULL;
1075   new_loop();  /* sets current_loop */
1076
1077   master_cg_visited++;
1078   cgscc(outermost_ir_graph);
1079   for (i = 0; i < n_irgs; i++) {
1080     ir_graph *irg = get_irp_irg(i);
1081     if (!cg_irg_visited(irg) && get_irg_n_callers(irg) == 0)
1082       cgscc(irg);
1083   }
1084   for (i = 0; i < n_irgs; i++) {
1085     ir_graph *irg = get_irp_irg(i);
1086     if (!cg_irg_visited(irg))
1087       cgscc(irg);
1088   }
1089   irp->outermost_cg_loop = current_loop;
1090
1091   /* -- Reverse the backedge information. -- */
1092   for (i = 0; i < n_irgs; i++) {
1093     ir_graph *irg = get_irp_irg(i);
1094     int j, n_callees = get_irg_n_callees(irg);
1095     for (j = 0; j < n_callees; ++j) {
1096       if (is_irg_callee_backedge(irg, j))
1097         set_irg_caller_backedge(get_irg_callee(irg, j), irg);
1098     }
1099   }
1100
1101   /* -- Schleifentiefe berechnen -- */
1102   int current_nesting = 0;
1103   master_cg_visited += 2;
1104   compute_loop_depth(get_irp_main_irg(), &current_nesting);
1105   for (i = 0; i < n_irgs; i++) {
1106     ir_graph *irg = get_irp_irg(i);
1107     if (!cg_irg_visited(irg) && get_irg_n_callers(irg) == 0)
1108       compute_loop_depth(irg, &current_nesting);
1109   }
1110   for (i = 0; i < n_irgs; i++) {
1111     ir_graph *irg = get_irp_irg(i);
1112     if (get_cg_irg_visited(irg) < master_cg_visited-1)
1113       compute_loop_depth(irg, &current_nesting);
1114   }
1115
1116   /* -- Rekursionstiefe berechnen -- */
1117   ana_entry2 e;
1118   e.loop_stack = NEW_ARR_F(ir_loop *, 0);
1119   e.tos = 0;
1120   e.recursion_nesting = 0;
1121
1122   master_cg_visited += 2;
1123   compute_rec_depth(get_irp_main_irg(), &e);
1124   for (i = 0; i < n_irgs; i++) {
1125     ir_graph *irg = get_irp_irg(i);
1126     if (!cg_irg_visited(irg) && get_irg_n_callers(irg) == 0)
1127       compute_rec_depth(irg, &e);
1128   }
1129   for (i = 0; i < n_irgs; i++) {
1130     ir_graph *irg = get_irp_irg(i);
1131     if (get_cg_irg_visited(irg) < master_cg_visited-1)
1132       compute_rec_depth(irg, &e);
1133   }
1134
1135   DEL_ARR_F(e.loop_stack);
1136
1137   //dump_callgraph("-with_nesting");
1138
1139   //dump_callgraph_loop_tree(current_loop, "-after_cons");
1140   irp->callgraph_state =  irp_callgraph_and_calltree_consistent;
1141 }
1142
1143 /* Maximal loop depth of all paths from an external visible method to
1144     this irg. */
1145 int       get_irg_loop_depth(ir_graph *irg) {
1146   assert(irp->callgraph_state == irp_callgraph_consistent ||
1147          irp->callgraph_state == irp_callgraph_and_calltree_consistent);
1148   return  irg->callgraph_loop_depth;
1149 }
1150
1151 /* Maximal recursion depth of all paths from an external visible method to
1152    this irg. */
1153 int       get_irg_recursion_depth(ir_graph *irg) {
1154   assert(irp->callgraph_state == irp_callgraph_and_calltree_consistent);
1155   return irg->callgraph_recursion_depth;
1156 }