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