New optimization flag handling, get_opt functions are always inlined now
[libfirm] / ir / ana / irscc.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ana/irscc.c
4  * Purpose:     Compute the strongly connected regions and build
5  *              backedge/loop datastructures.
6  *              A variation on the Tarjan algorithm. See also [Trapp:99],
7  *              Chapter 5.2.1.2.
8  * Author:      Goetz Lindenmaier
9  * Modified by:
10  * Created:     7.2002
11  * CVS-ID:      $Id$
12  * Copyright:   (c) 2002-2003 Universität Karlsruhe
13  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
14  */
15
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
19
20 #include <string.h>
21
22 #include "irloop_t.h"
23 #include "irnode.h"
24 #include "irgraph_t.h"
25 #include "array.h"
26 #include "pmap.h"
27 #include "irgwalk.h"
28 #include "irprog_t.h"
29 #include "irdump.h"
30
31 ir_graph *outermost_ir_graph;      /* The outermost graph the scc is computed
32                                       for */
33 static ir_loop *current_loop;      /* Current loop construction is working
34                                       on. */
35 static int loop_node_cnt = 0;      /* Counts the number of allocated loop nodes.
36                                       Each loop node gets a unique number.
37                                       What for? ev. remove. @@@ */
38 static int current_dfn = 1;        /* Counter to generate depth first numbering
39                                       of visited nodes.  */
40
41 /**********************************************************************/
42 /* Node attributes                                                   **/
43 /**********************************************************************/
44
45 /* A map to get from irnodes to loop nodes. */
46 static pmap *node_loop_map = NULL;
47
48 /**********************************************************************/
49 /* Node attributes needed for the construction.                      **/
50 /**********************************************************************/
51
52 typedef struct scc_info {
53   bool in_stack;         /* Marks whether node is on the stack. */
54   int dfn;               /* Depth first search number. */
55   int uplink;            /* dfn number of ancestor. */
56   //  ir_loop *loop;         /* Refers to the containing loop. */
57   /*
58       struct section *section;
59       xset def;
60       xset use;
61   */
62 } scc_info;
63
64 static INLINE scc_info* new_scc_info(void) {
65   scc_info *info = obstack_alloc (outermost_ir_graph->obst, sizeof (scc_info));
66   memset (info, 0, sizeof (scc_info));
67   return info;
68 }
69
70 static INLINE void
71 mark_irn_in_stack (ir_node *n) {
72   assert(get_irn_link(n));
73   ((scc_info *)get_irn_link(n))->in_stack = true;
74 }
75
76 static INLINE void
77 mark_irn_not_in_stack (ir_node *n) {
78   assert(get_irn_link(n));
79   ((scc_info *)get_irn_link(n))->in_stack = false;
80 }
81
82 static INLINE bool
83 irn_is_in_stack (ir_node *n) {
84   assert(get_irn_link(n));
85   return ((scc_info *)get_irn_link(n))->in_stack;
86 }
87
88 static INLINE void
89 set_irn_uplink (ir_node *n, int uplink) {
90   assert(get_irn_link(n));
91   ((scc_info *)get_irn_link(n))->uplink = uplink;
92 }
93
94 static INLINE int
95 get_irn_uplink (ir_node *n) {
96   assert(get_irn_link(n));
97   return ((scc_info *)get_irn_link(n))->uplink;
98 }
99
100 static INLINE void
101 set_irn_dfn (ir_node *n, int dfn) {
102   if (! get_irn_link(n)) { DDMN(n); DDME(get_irg_ent(current_ir_graph));}
103   assert(get_irn_link(n));
104   ((scc_info *)get_irn_link(n))->dfn = dfn;
105 }
106
107 static INLINE int
108 get_irn_dfn (ir_node *n) {
109   assert(get_irn_link(n));
110   return ((scc_info *)get_irn_link(n))->dfn;
111 }
112
113 /* Uses temporary information to set the loop */
114 static INLINE void
115 set_irn_loop (ir_node *n, ir_loop* loop) {
116   //assert(get_irn_link(n));
117   //((scc_info *)get_irn_link(n))->loop = loop;
118   assert(node_loop_map && "not initialized!");
119   pmap_insert(node_loop_map, (void *)n, (void *)loop);
120 }
121
122 /* Uses temporary information to get the loop */
123 INLINE ir_loop *
124 get_irn_loop (ir_node *n) {
125   ir_loop *res = NULL;
126   //assert(get_irn_link(n));
127   //return ((scc_info *)get_irn_link(n))->loop;
128   assert(node_loop_map && "not initialized!");
129
130   if (pmap_contains(node_loop_map, (void *)n))
131     res = (ir_loop *) pmap_get(node_loop_map, (void *)n);
132
133   return res;
134 }
135
136 #if 0
137 static ir_loop *find_nodes_loop (ir_node *n, ir_loop *l) {
138   int i;
139   ir_loop *res = NULL;
140
141   /* Test whether n is contained in this loop. */
142   for (i = 0; i < get_loop_n_nodes(l); i++)
143     if (n == get_loop_node(l, i)) return l;
144
145   /* Is this a leave in the loop tree? If so loop not found. */
146   if (get_loop_n_sons(l) == 0) return NULL;
147
148   /* Else descend in the loop tree. */
149   for (i = 0; i < get_loop_n_sons(l); i++) {
150     res = find_nodes_loop(n, get_loop_son(l, i));
151     if (res) break;
152   }
153   return res;
154 }
155
156 /* @@@ temporary implementation, costly!!! */
157 ir_loop * get_irn_loop(ir_node *n) {
158   ir_loop *l = get_irg_loop(current_ir_graph);
159   l = find_nodes_loop(n, l);
160   return l;
161 }
162 #endif
163
164 /**********************************************************************/
165 /* A stack.                                                          **/
166 /**********************************************************************/
167
168 static ir_node **stack = NULL;
169 static int tos = 0;                /* top of stack */
170
171 static INLINE void init_stack(void) {
172   if (stack) {
173     ARR_RESIZE (ir_node *, stack, 1000);
174   } else {
175     stack = NEW_ARR_F (ir_node *, 1000);
176   }
177   tos = 0;
178 }
179
180 #if 0
181 static INLINE void free_stack(void) {
182   DEL_ARR_F(stack);
183   stack = NULL;
184   tos = 0;
185 }
186 #endif
187
188 static INLINE void
189 push (ir_node *n)
190 {
191   /*DDMN(n);*/
192
193   if (tos == ARR_LEN (stack)) {
194     int nlen = ARR_LEN (stack) * 2;
195     ARR_RESIZE (ir_node *, stack, nlen);
196   }
197   stack [tos++] = n;
198   mark_irn_in_stack(n);
199 }
200
201 static INLINE ir_node *
202 pop (void)
203 {
204   ir_node *n = stack[--tos];
205   mark_irn_not_in_stack(n);
206   return n;
207 }
208
209 /* The nodes up to n belong to the current loop.
210    Removes them from the stack and adds them to the current loop. */
211 static INLINE void
212 pop_scc_to_loop (ir_node *n)
213 {
214   ir_node *m;
215   int i = 0;
216
217   /*for (;;) {*/
218   do
219     {
220     m = pop();
221     loop_node_cnt++;
222     set_irn_dfn(m, loop_node_cnt);
223     add_loop_node(current_loop, m);
224     set_irn_loop(m, current_loop);
225     i++;
226     /*    if (m==n) break;*/
227     } while(m != n);
228
229   if(i > 1)
230     printf("Mehr als eine Iteration!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
231 }
232
233 /* GL ??? my last son is my grandson???  Removes loops with no
234    ir_nodes in them.  Such loops have only another loop as son. (Why
235    can't they have two loops as sons? Does it never get that far? ) */
236 void close_loop (ir_loop *l)
237 {
238   int last = get_loop_n_elements(l) - 1;
239   loop_element lelement = get_loop_element(l, last);
240   ir_loop *last_son = lelement.son;
241
242   if (get_kind(last_son) == k_ir_loop &&
243       get_loop_n_elements(last_son) == 1)
244     {
245       ir_loop *gson;
246
247       lelement = get_loop_element(last_son, 0);
248       gson = lelement.son;
249       if(get_kind(gson) == k_ir_loop)
250         {
251           loop_element new_last_son;
252
253           gson -> outer_loop = l;
254           new_last_son.son = gson;
255           l -> children[last] = new_last_son;
256         }
257     }
258
259   current_loop = l;
260 }
261
262 /* Removes and unmarks all nodes up to n from the stack.
263    The nodes must be visited once more to assign them to a scc. */
264 static INLINE void
265 pop_scc_unmark_visit (ir_node *n)
266 {
267   ir_node *m = NULL;
268
269   while (m != n) {
270     m = pop();
271     set_irn_visited(m, 0);
272   }
273 }
274
275 /**********************************************************************/
276 /* The loop datastructure.                                           **/
277 /**********************************************************************/
278
279 /* Allocates a new loop as son of current_loop.  Sets current_loop
280    to the new loop and returns the father. */
281 static ir_loop *new_loop (void) {
282   ir_loop *father, *son;
283
284   father = current_loop;
285
286   son = (ir_loop *) obstack_alloc (outermost_ir_graph->obst, sizeof (ir_loop));
287   memset (son, 0, sizeof (ir_loop));
288   son->kind = k_ir_loop;
289   son->children = NEW_ARR_F (loop_element, 0);
290   son->n_nodes = 0;
291   son->n_sons=0;
292   if (father) {
293     son->outer_loop = father;
294     add_loop_son(father, son);
295     son->depth = father->depth+1;
296   } else {  /* The root loop */
297     son->outer_loop = son;
298     son->depth = 0;
299   }
300
301 #ifdef DEBUG_libfirm
302   son->loop_nr = get_irp_new_node_nr();
303   son->link = NULL;
304 #endif
305
306   current_loop = son;
307   return father;
308 }
309
310 #if 0
311 /* Finishes the datastructures, copies the arrays to the obstack
312    of current_ir_graph.
313    A. Schoesser: Caution: loop -> sons is gone. */
314 static void mature_loop (ir_loop *loop) {
315   ir_loop **new_sons;
316
317   new_sons = NEW_ARR_D (ir_loop *, current_ir_graph->obst, ARR_LEN(loop->sons));
318   memcpy (new_sons, loop->sons, sizeof (ir_loop *) * ARR_LEN(loop->sons));
319   DEL_ARR_F(loop->sons);
320   loop->sons = new_sons;
321 }
322 #endif
323
324 /* Returns outer loop, itself if outermost. */
325 ir_loop *get_loop_outer_loop (ir_loop *loop) {
326   assert(loop && loop->kind == k_ir_loop);
327   return loop->outer_loop;
328 }
329
330 /* Returns nesting depth of this loop */
331 int get_loop_depth (ir_loop *loop) {
332   assert(loop); assert(loop->kind == k_ir_loop);
333   return loop->depth;
334 }
335
336 /* Returns the number of inner loops */
337 int      get_loop_n_sons (ir_loop *loop) {
338   assert(loop && loop->kind == k_ir_loop);
339   return(loop -> n_sons);
340 }
341
342 /* Returns the pos`th loop_node-child              *
343  * TODO: This method isn`t very efficient !        *
344  * Returns NULL if there isnt`t a pos`th loop_node */
345 ir_loop *get_loop_son (ir_loop *loop, int pos) {
346   int child_nr = 0, loop_nr = -1;
347
348   assert(loop && loop->kind == k_ir_loop);
349   while(child_nr < ARR_LEN(loop->children))
350    {
351     if(*(loop -> children[child_nr].kind) == k_ir_loop)
352       loop_nr++;
353     if(loop_nr == pos)
354       return(loop -> children[child_nr].son);
355     child_nr++;
356    }
357   return NULL;
358 }
359
360 /* Use EXCLUSIVELY this function to add sons, otherwise the loop->n_sons
361    is invalid! */
362
363 static INLINE void
364 add_loop_son(ir_loop *loop, ir_loop *son) {
365   loop_element lson;
366   lson.son = son;
367   assert(loop && loop->kind == k_ir_loop);
368   assert(get_kind(son) == k_ir_loop);
369   ARR_APP1 (loop_element, loop->children, lson);
370   loop -> n_sons++;
371 }
372
373 /* Returns the number of nodes in the loop */
374 int      get_loop_n_nodes (ir_loop *loop) {
375   assert(loop); assert(loop->kind == k_ir_loop);
376   return loop -> n_nodes;
377 /*  return ARR_LEN(loop->nodes); */
378 }
379
380 /* Returns the pos`th ir_node-child                *
381  * TODO: This method isn`t very efficient !        *
382  * Returns NULL if there isnt`t a pos`th ir_node   */
383 ir_node *get_loop_node (ir_loop *loop, int pos) {
384   int child_nr, node_nr = -1;
385
386   assert(loop && loop->kind == k_ir_loop);
387   assert(pos < get_loop_n_nodes(loop));
388
389   for (child_nr = 0; child_nr < ARR_LEN(loop->children); child_nr++) {
390     if(*(loop -> children[child_nr].kind) == k_ir_node)
391       node_nr++;
392     if(node_nr == pos)
393       return(loop -> children[child_nr].node);
394   }
395   assert(0 && "no child at pos found");
396   return NULL;
397 }
398
399 /* Use EXCLUSIVELY this function to add nodes, otherwise the loop->n_nodes
400    is invalid! */
401
402 static INLINE void
403 add_loop_node(ir_loop *loop, ir_node *n) {
404   loop_element ln;
405   ln.node = n;
406   assert(loop && loop->kind == k_ir_loop);
407   assert(get_kind(n) == k_ir_node);
408   ARR_APP1 (loop_element, loop->children, ln);
409   loop->n_nodes++;
410 }
411
412 /** Returns the number of elements contained in loop.  */
413 int get_loop_n_elements (ir_loop *loop) {
414   assert(loop && loop->kind == k_ir_loop);
415   return(ARR_LEN(loop->children));
416 }
417
418 /*
419  Returns the pos`th loop element.
420  This may be a loop_node or a ir_node. The caller of this function has
421  to check the *(loop_element.kind) field for "k_ir_node" or "k_ir_loop"
422  and then select the apropriate "loop_element.node" or "loop_element.son".
423 */
424
425 loop_element get_loop_element (ir_loop *loop, int pos) {
426   assert(loop && loop->kind == k_ir_loop && pos < ARR_LEN(loop->children));
427
428   return(loop -> children[pos]);
429 }
430
431 int get_loop_element_pos(ir_loop *loop, void *le) {
432   int i;
433   assert(loop && loop->kind == k_ir_loop);
434
435   for (i = 0; i < get_loop_n_elements(loop); i++)
436     if (get_loop_element(loop, i).node == le) return i;
437   return -1;
438 }
439
440 int get_loop_loop_nr(ir_loop *loop) {
441   assert(loop && loop->kind == k_ir_loop);
442 #ifdef DEBUG_libfirm
443   return loop->loop_nr;
444 #else
445   return (int)loop;
446 #endif
447 }
448
449
450 /** A field to connect additional information to a loop.  Only valid
451     if libfirm_debug is set. */
452 void  set_loop_link (ir_loop *loop, void *link) {
453   assert(loop && loop->kind == k_ir_loop);
454 #ifdef DEBUG_libfirm
455   loop->link = link;
456 #endif
457 }
458 void *get_loop_link (const ir_loop *loop) {
459   assert(loop && loop->kind == k_ir_loop);
460 #ifdef DEBUG_libfirm
461   return loop->link;
462 #else
463   return NULL;
464 #endif
465 }
466
467 /* The outermost loop is remarked in the surrounding graph. */
468 void     set_irg_loop(ir_graph *irg, ir_loop *loop) {
469   assert(irg);
470   irg->loop = loop;
471 }
472 ir_loop *get_irg_loop(ir_graph *irg) {
473   assert(irg);
474   return irg->loop;
475 }
476
477
478 /**********************************************************************/
479 /* Constructing and destructing the loop/backedge information.       **/
480 /**********************************************************************/
481
482 /* Initialization steps. **********************************************/
483
484 static INLINE void
485 init_node (ir_node *n, void *env) {
486   set_irn_link (n, new_scc_info());
487   clear_backedges(n);
488 #if 0
489   /* Also init nodes not visible in intraproc_view. */
490     /* @@@ init_node is called for too many nodes -- this wastes memory!.
491        The mem is not lost as its on the obstack. */
492   if (get_irn_op(n) == op_Filter) {
493     for (i = 0; i < get_Filter_n_cg_preds(n); i++)
494       init_node(get_Filter_cg_pred(n, i), NULL);
495   }
496   if (get_irn_op(n) == op_Block) {
497     for (i = 0; i < get_Block_cg_n_cfgpreds(n); i++) {
498       init_node(get_Block_cg_cfgpred(n, i), NULL);
499     }
500   }
501   /* The following pattern matches only after a call from above pattern. */
502   if ((get_irn_op(n) == op_Proj) /*&& (get_Proj_proj(n) == 0)*/) {
503     /* @@@ init_node is called for every proj -- this wastes memory!.
504        The mem is not lost as its on the obstack. */
505     ir_node *cb = get_Proj_pred(n);
506     if ((get_irn_op(cb) == op_CallBegin) ||
507         (get_irn_op(cb) == op_EndReg) ||
508         (get_irn_op(cb) == op_EndExcept)) {
509       init_node(cb, NULL);
510       init_node(get_nodes_Block(cb), NULL);
511     }
512   }
513 #endif
514 }
515
516 static INLINE void
517 init_scc_common (void) {
518   current_dfn = 1;
519   loop_node_cnt = 0;
520   if (!node_loop_map) node_loop_map = pmap_create();
521   init_stack();
522 }
523
524 static INLINE void
525 init_scc (ir_graph *irg) {
526   init_scc_common();
527   irg_walk_graph (irg, init_node, NULL, NULL);
528   /*
529   irg_walk (irg, link_to_reg_end, NULL, NULL);
530   */
531 }
532
533 static INLINE void
534 init_ip_scc (void) {
535   init_scc_common();
536   cg_walk (init_node, NULL, NULL);
537 }
538
539 /* Condition for breaking the recursion. */
540 static bool is_outermost_Start(ir_node *n) {
541   /* Test whether this is the outermost Start node.  If so
542      recursion must end. */
543   if ((get_irn_op(n) == op_Block)     &&
544       (get_Block_n_cfgpreds(n) == 1)  &&
545       (get_irn_op(skip_Proj(get_Block_cfgpred(n, 0))) == op_Start) &&
546       (get_nodes_Block(skip_Proj(get_Block_cfgpred(n, 0))) == n)) {
547     return true;
548   }
549 #if 0
550   /*  @@@ Bad condition:
551       not possible in interprocedural view as outermost_graph is
552       not necessarily the only with a dead-end start block.
553       Besides current_ir_graph is not set properly. */
554   if ((get_irn_op(n) == op_Block) &&
555       (n == get_irg_start_block(current_ir_graph))) {
556     if ((!interprocedural_view)  ||
557         (current_ir_graph == outermost_ir_graph))
558       return true;
559   }
560 #endif
561   return false;
562 }
563
564 /* Don't walk from nodes to blocks except for Control flow operations. */
565 static INLINE int
566 get_start_index(ir_node *n) {
567   if (is_cfop(n) || is_fragile_op(n) || get_irn_op(n) == op_Start)
568     return -1;
569   else
570     return 0;
571 }
572
573 /* Returns current_ir_graph and set it to the irg of predecessor index
574    of node n. */
575 static INLINE ir_graph *
576 switch_irg (ir_node *n, int index) {
577   ir_graph *old_current = current_ir_graph;
578
579   if (interprocedural_view) {
580     /* Only Filter and Block nodes can have predecessors in other graphs. */
581     if (get_irn_op(n) == op_Filter)
582       n = get_nodes_Block(n);
583     if (get_irn_op(n) == op_Block) {
584       ir_node *cfop = skip_Proj(get_Block_cfgpred(n, index));
585       if (is_ip_cfop(cfop)) {
586         current_ir_graph = get_irn_irg(cfop);
587         set_irg_visited(current_ir_graph, get_max_irg_visited());
588       }
589     }
590   }
591
592   return old_current;
593 }
594
595 #if 0
596 /* Walks up the stack passing n and then finding the node
597    where we walked into the irg n is contained in.
598    Here we switch the irg. */
599 static ir_graph *
600 find_irg_on_stack (ir_node *n) {
601   ir_node *m;
602   ir_graph *old_current = current_ir_graph;
603   int i;
604
605   if (interprocedural_view) {
606     for (i = tos; i >= 0; i--) {
607       if (stack[i] == n) break;
608     }
609     if (i < 0) i = tos;
610
611     assert (i >= 0);
612     for (; i >= 0; i--) {
613       m = stack[i];
614       /*printf(" Visiting %d ", i); DDMN(m);*/
615       if (is_ip_cfop(m)) {
616         current_ir_graph = get_irn_irg(m);
617         break;
618       }
619       if (get_irn_op(m) == op_Filter) {
620         /* Find the corresponding ip_cfop */
621         ir_node *pred = stack[i+1];
622         int j;
623         for (j = 0; j < get_Filter_n_cg_preds(m); j++)
624           if (get_Filter_cg_pred(m, j) == pred) break;
625         if (j >= get_Filter_n_cg_preds(m))
626           /* It is a filter we didn't pass as the predecessors are marked. */
627           continue;
628         assert(get_Filter_cg_pred(m, j) == pred);
629         switch_irg(m, j);
630         break;
631       }
632     }
633   }
634
635   return old_current;
636 }
637 #endif
638
639 #if 0
640 static void test(ir_node *pred, ir_node *root, ir_node *this) {
641   int i;
642   if (get_irn_uplink(pred) >= get_irn_uplink(root)) return;
643
644   printf("this: %d ", get_irn_uplink(this)); DDMN(this);
645   printf("pred: %d ", get_irn_uplink(pred)); DDMN(pred);
646   printf("root: %d ", get_irn_uplink(root)); DDMN(root);
647
648   printf("tos: %d\n", tos);
649
650   for (i = tos; i >= 0; i--) {
651     ir_node *n = stack[i];
652     if (!n) continue;
653     printf(" uplink: %d, pos: %d ", get_irn_uplink(n), i); DDMN(n);
654   }
655 }
656 #endif
657
658 /* Test for legal loop header: Block, Phi, ... */
659 INLINE static bool is_possible_loop_head(ir_node *n) {
660   return ((get_irn_op(n) == op_Block) ||
661           (get_irn_op(n) == op_Phi) ||
662           ((get_irn_op(n) == op_Filter) && interprocedural_view));
663 }
664
665 /* Returns true if n is a loop header, i.e., it is a Block, Phi
666    or Filter node and has predecessors within the loop and out
667    of the loop.
668    @arg root: only needed for assertion. */
669 static bool
670 is_head (ir_node *n, ir_node *root)
671 {
672   int i;
673   int some_outof_loop = 0, some_in_loop = 0;
674
675   /* Test for legal loop header: Block, Phi, ... */
676   if (!is_possible_loop_head(n))
677     return false;
678
679   if (!is_outermost_Start(n)) {
680     for (i = get_start_index(n); i < get_irn_arity(n); i++) {
681       ir_node *pred = get_irn_n(n, i);
682       assert(pred);
683       if (is_backedge(n, i)) continue;
684       if (!irn_is_in_stack(pred)) {
685         some_outof_loop = 1;
686       } else {
687         assert(get_irn_uplink(pred) >= get_irn_uplink(root));
688         some_in_loop = 1;
689       }
690     }
691   }
692   return some_outof_loop && some_in_loop;
693 }
694
695 /* Returns index of the predecessor with the smallest dfn number
696    greater-equal than limit. */
697 static int
698 smallest_dfn_pred (ir_node *n, int limit)
699 {
700   int i, index = -2, min = -1;
701
702   if (!is_outermost_Start(n)) {
703     for (i = get_start_index(n); i < get_irn_arity(n); i++) {
704       ir_node *pred = get_irn_n(n, i);
705       assert(pred);
706       if (is_backedge(n, i) || !irn_is_in_stack(pred)) continue;
707       if (get_irn_dfn(pred) >= limit && (min == -1 || get_irn_dfn(pred) < min)) {
708         index = i;
709         min = get_irn_dfn(pred);
710       }
711     }
712   }
713   return index;
714 }
715
716 /* Returns index of the predecessor with the largest dfn number. */
717 static int
718 largest_dfn_pred (ir_node *n)
719 {
720   int i, index = -2, max = -1;
721
722   if (!is_outermost_Start(n)) {
723     for (i = get_start_index(n); i < get_irn_arity(n); i++) {
724       ir_node *pred = get_irn_n(n, i);
725       if (is_backedge (n, i) || !irn_is_in_stack(pred)) continue;
726       if (get_irn_dfn(pred) > max) {
727         index = i;
728         max = get_irn_dfn(pred);
729       }
730     }
731   }
732   return index;
733 }
734
735 /* Searches the stack for possible loop heads.  Tests these for backedges.
736    If it finds a head with an unmarked backedge it marks this edge and
737    returns the tail of the loop.
738    If it finds no backedge returns NULL.
739    ("disable_backedge" in fiasco) */
740
741 static ir_node *
742 find_tail (ir_node *n) {
743   ir_node *m;
744   int i, res_index = -2;
745
746   /*
747     if (!icfg && rm_cyclic_phis && remove_cyclic_phis (n)) return NULL;
748   */
749
750   m = stack[tos-1];  /* tos = top of stack */
751   if (is_head (m, n)) {
752     res_index = smallest_dfn_pred(m, 0);
753     if ((res_index == -2) &&  /* no smallest dfn pred found. */
754         (n == m))
755       return NULL;
756   } else {
757     if (m == n) return NULL;
758     for (i = tos-2; ; --i) {
759       m = stack[i];
760       if (is_head (m, n)) {
761         res_index = smallest_dfn_pred (m, get_irn_dfn(m) + 1);
762         if (res_index == -2)  /* no smallest dfn pred found. */
763           res_index = largest_dfn_pred (m);
764         break;
765       }
766     }
767   }
768   assert (res_index > -2);
769
770   set_backedge (m, res_index);
771   return is_outermost_Start(n) ? NULL : get_irn_n(m, res_index);
772 }
773
774
775 /* The core algorithm. *****************************************/
776
777 static void scc (ir_node *n) {
778   int i;
779   // GL @@@ remove experimental stuff ir_graph *rem;
780
781   if (irn_visited(n)) return;
782   mark_irn_visited(n);
783
784   /* Initialize the node */
785   set_irn_dfn(n, current_dfn);      /* Depth first number for this node */
786   set_irn_uplink(n, current_dfn);   /* ... is default uplink. */
787   set_irn_loop(n, NULL);
788   current_dfn ++;
789
790   /* What's this good for?
791   n->ana.scc.section = NULL;
792   */
793
794   push(n);
795
796   /* AS: get_start_index might return -1 for Control Flow Nodes, and thus a negative
797      array index would be passed to is_backedge(). But CFG Nodes dont't have a backedge array,
798      so is_backedge does not access array[-1] but correctly returns false! */
799
800   if (!is_outermost_Start(n)) {
801     for (i = get_start_index(n); i < get_irn_arity(n); i++) {
802       ir_node *m;
803       if (is_backedge(n, i)) continue;
804
805       m = get_irn_n(n, i); /*get_irn_ip_pred(n, i);*/
806       assert(m);
807       //if ((!m) || (get_irn_op(m) == op_Unknown)) continue;
808       scc (m);
809       // GL @@@ remove experimental stuff /*return_recur(n, i);*/
810
811       if (irn_is_in_stack(m)) {
812         /* Uplink of m is smaller if n->m is a backedge.
813            Propagate the uplink to mark the loop. */
814         if (get_irn_uplink(m) < get_irn_uplink(n))
815           set_irn_uplink(n, get_irn_uplink(m));
816       }
817     }
818   }
819
820   if (get_irn_dfn(n) == get_irn_uplink(n)) {
821     /* This condition holds for the node with the incoming backedge.
822        AS: That is: For the loop head. */
823     ir_node *tail = find_tail(n);
824     if (tail) {
825       /* We found a new inner loop! */
826
827       /* This is an adaption of the algorithm from fiasco / optscc to
828        * avoid loops without Block or Phi as first node.  This should
829        * severely reduce the number of evaluations of nodes to detect
830        * a fixpoint in the heap analyses.
831        * Further it avoids loops without firm nodes that cause errors
832        * in the heap analyses. */
833 #define NO_LOOPS_WITHOUT_HEAD 1
834 #if NO_LOOPS_WITHOUT_HEAD
835       ir_loop *l;
836       int close;
837       if (get_loop_n_elements(current_loop) > 0) {
838         l = new_loop();
839         close = 1;
840       } else {
841         l = current_loop;
842         close = 0;
843       }
844 #else
845       ir_loop *l = new_loop();
846 #endif
847
848       /* Remove the loop from the stack ... */
849       pop_scc_unmark_visit (n);
850       /* and recompute it in a better order; and so that it goes into
851          the new loop. */
852       // GL @@@ remove experimental stuff rem = find_irg_on_stack(tail);
853
854       scc (tail);
855       // GL @@@ remove experimental stuff current_ir_graph = rem;
856
857       assert (irn_visited(n));
858 #if NO_LOOPS_WITHOUT_HEAD
859       if (close)
860 #endif
861       close_loop(l);
862     } else {
863       /* AS: No inner loop was found. Pop all nodes from the stack
864          to the current loop. */
865       pop_scc_to_loop(n);
866     }
867   }
868 }
869
870 /* Constructs backedge information for irg. In interprocedural view constructs
871    backedges for all methods called by irg, too. */
872 void construct_backedges(ir_graph *irg) {
873   ir_graph *rem = current_ir_graph;
874   ir_loop *head_rem;
875
876   assert(!interprocedural_view &&
877          "not implemented, use construct_ip_backedges");
878
879   current_ir_graph = irg;
880   outermost_ir_graph = irg;
881
882   init_scc(current_ir_graph);
883
884   current_loop = NULL;
885   new_loop();  /* sets current_loop */
886   head_rem = current_loop; /* Just for assertion */
887
888   if (interprocedural_view) {
889     set_irg_visited(current_ir_graph, inc_max_irg_visited());
890     init_ip_walk ();
891   } else {
892     inc_irg_visited(current_ir_graph);
893   }
894
895   scc(get_irg_end(current_ir_graph));
896
897   if (interprocedural_view) finish_ip_walk();
898
899   assert(head_rem == current_loop);
900   set_irg_loop(current_ir_graph, current_loop);
901   assert(get_irg_loop(current_ir_graph)->kind == k_ir_loop);
902   /*
903   irg->loops = current_loop;
904   if (icfg == 1) {
905     int count = 0;
906     int depth = 0;
907     count_loop (the_loop, &count, &depth);
908     }
909   }
910   */
911   current_ir_graph = rem;
912 }
913
914
915 #if 0
916 void construct_ip_backedges (void) {
917   ir_graph *rem = current_ir_graph;
918   int rem_ipv = interprocedural_view;
919   int i, j;
920
921   outermost_ir_graph = get_irp_main_irg();
922
923   init_ip_scc();
924
925   current_loop = NULL;
926   new_loop();  /* sets current_loop */
927   interprocedural_view = 1;
928
929   inc_max_irg_visited();
930   for (i = 0; i < get_irp_n_irgs(); i++)
931     set_irg_visited(get_irp_irg(i), get_max_irg_visited());
932
933   for (i = 0; i < get_irp_n_irgs(); i++) {
934     ir_node *sb;
935     current_ir_graph = get_irp_irg(i);
936     /* Find real entry points */
937     sb = get_irg_start_block(current_ir_graph);
938     if ((get_Block_n_cfgpreds(sb) > 1) ||
939         (get_nodes_Block(get_Block_cfgpred(sb, 0)) != sb)) continue;
940     /* Compute scc for this graph */
941     outermost_ir_graph = current_ir_graph;
942     set_irg_visited(outermost_ir_graph, get_max_irg_visited());
943     scc(get_irg_end(current_ir_graph));
944     for (j = 0; j < get_End_n_keepalives(get_irg_end(outermost_ir_graph)); j++)
945       scc(get_End_keepalive(get_irg_end(outermost_ir_graph), j));
946   }
947
948   set_irg_loop(outermost_ir_graph, current_loop);
949   assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
950
951   current_ir_graph = rem;
952   interprocedural_view = rem_ipv;
953 }
954 #else
955 void construct_ip_backedges (void) {
956   ir_graph *rem = current_ir_graph;
957   int rem_ipv = interprocedural_view;
958   int i;
959
960   outermost_ir_graph = get_irp_main_irg();
961
962   init_ip_scc();
963
964   current_loop = NULL;
965   new_loop();  /* sets current_loop */
966   interprocedural_view = 1;
967
968   inc_max_irg_visited();
969   for (i = 0; i < get_irp_n_irgs(); i++)
970     set_irg_visited(get_irp_irg(i), get_max_irg_visited());
971
972   /** We have to start the walk at the same nodes as cg_walk. **/
973   /* Walk starting at unreachable procedures. Only these
974    * have End blocks visible in interprocedural view. */
975   for (i = 0; i < get_irp_n_irgs(); i++) {
976     ir_node *sb;
977     current_ir_graph = get_irp_irg(i);
978
979     sb = get_irg_start_block(current_ir_graph);
980
981     if ((get_Block_n_cfgpreds(sb) > 1) ||
982         (get_nodes_block(get_Block_cfgpred(sb, 0)) != sb)) continue;
983
984     scc(get_irg_end(current_ir_graph));
985   }
986
987   /* Check whether we walked all procedures: there could be procedures
988      with cyclic calls but no call from the outside. */
989   for (i = 0; i < get_irp_n_irgs(); i++) {
990     ir_node *sb;
991     current_ir_graph = get_irp_irg(i);
992
993     /* Test start block: if inner procedure end and end block are not
994      * visible and therefore not marked. */
995     sb = get_irg_start_block(current_ir_graph);
996     if (get_irn_visited(sb) < get_irg_visited(current_ir_graph)) scc(sb);
997   }
998
999   /* Walk all endless loops in inner procedures.
1000    * We recognize an inner procedure if the End node is not visited. */
1001   for (i = 0; i < get_irp_n_irgs(); i++) {
1002     ir_node *e;
1003     current_ir_graph = get_irp_irg(i);
1004
1005     e = get_irg_end(current_ir_graph);
1006     if (get_irn_visited(e) < get_irg_visited(current_ir_graph)) {
1007       int j;
1008       /* Don't visit the End node. */
1009       for (j = 0; j < get_End_n_keepalives(e); j++) scc(get_End_keepalive(e, j));
1010     }
1011   }
1012
1013   set_irg_loop(outermost_ir_graph, current_loop);
1014   assert(get_irg_loop(outermost_ir_graph)->kind == k_ir_loop);
1015
1016   current_ir_graph = rem;
1017   interprocedural_view = rem_ipv;
1018 }
1019 #endif
1020
1021 static void reset_backedges(ir_node *n) {
1022   if (is_possible_loop_head(n)) {
1023     int rem = interprocedural_view;
1024     interprocedural_view = 1;
1025     clear_backedges(n);
1026     interprocedural_view = 0;
1027     clear_backedges(n);
1028     interprocedural_view = rem;
1029   }
1030 }
1031
1032 static void loop_reset_backedges(ir_loop *l) {
1033   int i;
1034   reset_backedges(get_loop_node(l, 0));
1035   for (i = 0; i < get_loop_n_sons(l); ++i) {
1036     loop_reset_backedges(get_loop_son(l, i));
1037   }
1038 }
1039
1040 /** Removes all loop information.
1041     Resets all backedges */
1042 void free_loop_information(ir_graph *irg) {
1043   if (get_irg_loop(irg))
1044     loop_reset_backedges(get_irg_loop(irg));
1045   set_irg_loop(irg, NULL);
1046   /* We cannot free the loop nodes, they are on the obstack. */
1047 }
1048
1049
1050 void free_all_loop_information (void) {
1051   int i;
1052   int rem = interprocedural_view;
1053   interprocedural_view = 1;  /* To visit all filter nodes */
1054   for (i = 0; i < get_irp_n_irgs(); i++) {
1055     free_loop_information(get_irp_irg(i));
1056   }
1057   pmap_destroy(node_loop_map);
1058   node_loop_map = NULL;
1059   interprocedural_view = rem;
1060 }
1061
1062
1063
1064
1065
1066 /* Debug stuff *************************************************/
1067
1068 static int test_loop_node(ir_loop *l) {
1069   int i, has_node = 0, found_problem = 0;
1070   loop_element le;
1071
1072   assert(l && l->kind == k_ir_loop);
1073
1074   if (get_loop_n_elements(l) == 0) {
1075     printf(" Loop completely empty! "); DDML(l);
1076     found_problem = 1;
1077     dump_loop(l, "-ha");
1078   }
1079
1080   le = get_loop_element(l, 0);
1081   if (*(le.kind) != k_ir_node) {
1082     assert(le.kind && *(le.kind) == k_ir_loop);
1083     printf(" First loop element is not a node! "); DDML(l);
1084     printf("                                   "); DDML(le.son);
1085
1086     found_problem = 1;
1087     dump_loop(l, "-ha");
1088   }
1089
1090   if ((*(le.kind) == k_ir_node) && !is_possible_loop_head(le.node)) {
1091     printf(" Wrong node as head! "); DDML(l);
1092     printf("                     "); DDMN(le.node);
1093     found_problem = 1;
1094     dump_loop(l, "-ha");
1095   }
1096
1097   if ((get_loop_depth(l) != 0) &&
1098       (*(le.kind) == k_ir_node) && !has_backedges(le.node)) {
1099     printf(" Loop head has no backedges! "); DDML(l);
1100     printf("                             "); DDMN(le.node);
1101     found_problem = 1;
1102     dump_loop(l, "-ha");
1103   }
1104
1105   /* Recur */
1106   has_node = 0;
1107   for (i = 0; i < get_loop_n_elements(l); ++i) {
1108     le = get_loop_element(l, i);
1109     if (*(le.kind) == k_ir_node)
1110       has_node++;
1111     else
1112       if (test_loop_node(le.son)) found_problem = 1;
1113   }
1114
1115   if (has_node == 0) {
1116     printf(" Loop has no firm node! "); DDML(l);
1117     found_problem = 1;
1118     dump_loop(l, "-ha");
1119   }
1120
1121   if (get_loop_loop_nr(l) == 11819)
1122     dump_loop(l, "-ha-debug");
1123
1124   return found_problem;
1125 }
1126
1127 /** Prints all loop nodes that
1128  *  - do not have any firm nodes, only loop sons
1129  *  - the header is not a Phi, Block or Filter.
1130  */
1131 void find_strange_loop_nodes(ir_loop *l) {
1132   int found_problem = 0;
1133   printf("\nTesting loop "); DDML(l);
1134   found_problem = test_loop_node(l);
1135   printf("Finished Test\n\n");
1136   if (found_problem) exit(0);
1137
1138 }