Remove VISITED in link-field hackery. Cleanups.
[libfirm] / ir / ana / structure.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    Structure Analysis
23  * @author   Michael Beck
24  * @date     5.4.2007
25  * @version  $Id$
26  */
27 #include "config.h"
28
29 #include "firm_common.h"
30 #include "irnode_t.h"
31 #include "structure.h"
32 #include "irdom.h"
33 #include "irouts.h"
34 #include "irtools.h"
35 #include "irgwalk.h"
36 #include "array.h"
37 #include "irdump.h"
38
39 #include "debug.h"
40
41 typedef union ir_reg_or_blk ir_reg_or_blk;
42
43 /* The structure tree. */
44 struct ir_reg_tree {
45         struct obstack obst;   /**< The obstack where the data is allocated. */
46         ir_region *top;        /**< The top region. */
47         ir_graph *irg;         /**< Associated graph. */
48 };
49
50 /* A region. */
51 struct ir_region {
52         firm_kind      kind;      /**< Must be k_ir_region. */
53         ir_region_kind type;      /**< The type of this region. */
54         ir_region      *parent;   /**< points to the parent. */
55         ir_reg_or_blk  *parts;    /**< The list of all region parts. */
56         ir_region      **pred;    /**< The predecessor (control flow) regions of this region. */
57         ir_region      **succ;    /**< The successor (control flow) regions of this region. */
58         unsigned       prenum;    /**< DFS pre-oder number */
59         unsigned       postnum;   /**< DFS post-oder number */
60         void           *link;     /**< A link field. */
61         unsigned long  nr;        /**< for debugging */
62         unsigned       visited:1; /**< The visited flag. */
63         unsigned       exit:1;    /**< If set, the parent region can be left by this node. */
64         unsigned       enter:1;   /**< If set, the parent region can be entered by this node. */
65 };
66
67 /* A helper type for unioning blocks and regions. */
68 union ir_reg_or_blk {
69         firm_kind *kind;    /**< For easier check. */
70         ir_node   *blk;     /**< A node */
71         ir_region *region;  /**< A region. */
72 };
73
74 /* The debug handle. */
75 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
76
77 /**
78  * Returns the link of a region.
79  */
80 void *get_region_link(const ir_region *reg)
81 {
82         return reg->link;
83 }
84
85 /**
86  * Sets the link of a region.
87  */
88 void set_region_link(ir_region *reg, void *data)
89 {
90         reg->link = data;
91 }
92
93 /**
94  * Get the immediate region of a block.
95  */
96 ir_region *get_block_region(const ir_node *block)
97 {
98         assert(is_Block(block));
99         return block->attr.block.region;
100 }
101
102 /**
103  * Sets the immediate region of a block.
104  */
105 void set_block_region(ir_node *block, ir_region *reg)
106 {
107         assert(is_Block(block));
108         block->attr.block.region = reg;
109 }
110
111 /**
112  * Get the immediate region of a node.
113  */
114 ir_region *get_irn_region(ir_node *n)
115 {
116         if (!is_Block(n))
117                 n = get_nodes_block(n);
118         return get_block_region(n);
119 }
120
121 /**
122  * Return non-zero if a given firm thing is a region.
123  */
124 int is_region(const void *thing)
125 {
126         const firm_kind *kind = thing;
127         return *kind == k_ir_region;
128 }
129
130 /**
131  * Return the number of predecessors of a region.
132  */
133 int get_region_n_preds(const ir_region *reg)
134 {
135         return ARR_LEN(reg->pred);
136 }
137
138 /**
139  * Return the predecessor region at position pos.
140  */
141 ir_region *get_region_pred(const ir_region *reg, int pos)
142 {
143         assert(0 <= pos && pos <= get_region_n_preds(reg));
144         return reg->pred[pos];
145 }
146
147 /**
148  * Set the predecessor region at position pos.
149  */
150 void set_region_pred(ir_region *reg, int pos, ir_region *n)
151 {
152         assert(0 <= pos && pos <= get_region_n_preds(reg));
153         reg->pred[pos] = n;
154 }
155
156 /**
157  * Return the number of successors in a region.
158  */
159 int get_region_n_succs(const ir_region *reg)
160 {
161         return ARR_LEN(reg->succ);
162 }
163
164 /**
165  * Return the successor region at position pos.
166  */
167 ir_region *get_region_succ(const ir_region *reg, int pos)
168 {
169         assert(0 <= pos && pos <= get_region_n_succs(reg));
170         return reg->succ[pos];
171 }
172
173 /**
174  * Set the successor region at position pos.
175  */
176 void set_region_succ(ir_region *reg, int pos, ir_region *n)
177 {
178         assert(0 <= pos && pos <= get_region_n_succs(reg));
179         reg->succ[pos] = n;
180 }
181
182 /* ----------------------- construction -------------------------- */
183
184 /** Walker environment. */
185 typedef struct walk_env {
186         struct obstack *obst;  /**< An obstack to allocate from. */
187         ir_region **post;      /**< The list of all currently existent top regions. */
188         unsigned l_post;       /**< The length of the allocated regions array. */
189         unsigned premax;       /**< maximum pre counter */
190         unsigned postmax;      /**< maximum post counter */
191         ir_node *start_block;  /**< The start block of the graph. */
192         ir_node *end_block;    /**< The end block of the graph. */
193 } walk_env;
194
195 /**
196  * Do a DFS search on the initial regions, assign a prenum and a postnum to every
197  * node and store the region nodes into the post array.
198  */
199 static void dfs_walk2(ir_region *reg, walk_env *env)
200 {
201         int i, n;
202
203         if (reg->visited == 0) {
204                 reg->visited = 1;
205
206                 reg->prenum = env->premax++;
207                 for (i = 0, n = get_region_n_succs(reg); i < n; ++i) {
208                         /* recursion */
209                         ir_region *succ = get_region_succ(reg, i);
210                         dfs_walk2(succ, env);
211                 }
212
213                 env->post[env->postmax] = reg;
214                 reg->postnum = env->postmax++;
215         }
216 }
217
218 /**
219  * Do a DFS search on the initial regions, assign a prenum and a postnum to every
220  * node and store the region nodes into the post array.
221  */
222 static void dfs_walk(ir_graph *irg, walk_env *env)
223 {
224         ir_graph *rem = current_ir_graph;
225         ir_region *reg;
226
227         current_ir_graph = irg;
228         reg              = get_irn_link(get_irg_start_block(irg));
229
230         env->premax  = 0;
231         env->postmax = 0;
232         dfs_walk2(reg, env);
233         current_ir_graph = rem;
234 }
235
236 /**
237  * Post-walker: wrap all blocks with a BasicBlock region
238  * and count them
239  */
240 static void wrap_BasicBlocks(ir_node *block, void *ctx)
241 {
242         walk_env *env = ctx;
243         ir_region *reg;
244
245         /* Allocate a Block wrapper */
246         reg          = OALLOC(env->obst, ir_region);
247         reg->kind    = k_ir_region;
248         reg->type    = ir_rk_BasicBlock;
249         reg->parent  = NULL;
250         reg->prenum  = 0;
251         reg->postnum = 0;
252         reg->visited = 0;
253         reg->exit    = 0;
254         reg->enter   = 0;
255         reg->link    = NULL;
256         reg->nr      = get_irn_node_nr(block);
257         reg->parts   = NEW_ARR_D(ir_reg_or_blk, env->obst, 1);
258
259         reg->parts[0].blk = block;
260         set_irn_link(block, reg);
261
262         ++env->l_post;
263 }  /* wrap_BasicBlocks */
264
265 /**
266  * Post-walker: Create the pred and succ edges for Block wrapper.
267  * Kill edges to the Start and End blocks.
268  */
269 static void update_BasicBlock_regions(ir_node *blk, void *ctx)
270 {
271         walk_env *env = ctx;
272         ir_region *reg = get_irn_link(blk);
273         int i, j, len;
274
275         if (blk == env->start_block) {
276                 /* handle Firm's self loop: Start block has no predecessors */
277                 reg->pred = NEW_ARR_D(ir_region *, env->obst, 0);
278         } else {
279                 len = get_Block_n_cfgpreds(blk);
280                 reg->pred = NEW_ARR_D(ir_region *, env->obst, len);
281                 for (i = j = 0; i < len; ++i) {
282                         ir_node *pred = get_Block_cfgpred_block(blk, i);
283                         reg->pred[j++] = get_irn_link(pred);
284                 }
285                 ARR_SHRINKLEN(reg->pred, j);
286         }
287
288         len = get_Block_n_cfg_outs(blk);
289         reg->succ = NEW_ARR_D(ir_region *, env->obst, len);
290         for (i = j = 0; i < len; ++i) {
291                 ir_node *succ = get_Block_cfg_out(blk, i);
292                 reg->succ[j++] = get_irn_link(succ);
293         }
294         ARR_SHRINKLEN(reg->succ, j);
295 }  /* update_BasicBlock_regions */
296
297 /** Allocate a new region on an obstack */
298 #define ALLOC_REG(obst, reg, tp) \
299         do { \
300                 (reg)          = OALLOC((obst), ir_region); \
301                 (reg)->kind    = k_ir_region; \
302                 (reg)->type    = tp; \
303                 (reg)->parent  = NULL; \
304                 (reg)->prenum  = 0; \
305                 (reg)->postnum = 0; \
306                 (reg)->visited = 0; \
307                 (reg)->exit    = 0; \
308                 (reg)->enter   = 0; \
309                 (reg)->link    = NULL; \
310         } while (0)
311
312 /**
313  * Creates a new Sequence region.
314  */
315 static ir_region *new_Sequence(struct obstack *obst, ir_region *nset, int nset_len)
316 {
317         ir_region *reg, *next;
318         int i;
319
320         ALLOC_REG(obst, reg, ir_rk_Sequence);
321
322         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, nset_len);
323
324         /* beware: list is in reverse order, reverse */
325         next = nset;
326         for (i = nset_len - 1; i >= 0; --i) {
327                 nset = next;
328                 reg->parts[i].region = nset;
329                 nset->parent = reg;
330                 next = nset->link;
331                 nset->link = NULL;
332         }
333
334         reg->nr   = reg->parts[0].region->nr;
335         reg->pred = DUP_ARR_D(ir_region *, obst, reg->parts[0].region->pred);
336         reg->succ = DUP_ARR_D(ir_region *, obst, reg->parts[nset_len - 1].region->succ);
337
338         DEBUG_ONLY(
339                 DB((dbg, LEVEL_2, " Created Sequence "));
340                 for (i = 0; i < nset_len; ++i) {
341                         DB((dbg, LEVEL_2, "(%u)", reg->parts[i].region->nr));
342                 }
343                 DB((dbg, LEVEL_2, "\n"));
344         )
345         return reg;
346 }  /* new_Sequence */
347
348 /**
349  * Create a new IfThenElse region.
350  */
351 static ir_region *new_IfThenElse(struct obstack *obst, ir_region *if_b, ir_region *then_b, ir_region *else_b)
352 {
353         ir_region *reg;
354
355         ALLOC_REG(obst, reg, ir_rk_IfThenElse);
356
357         reg->nr    = if_b->nr;
358         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 3);
359
360         reg->parts[0].region = if_b;   if_b->parent   = reg;
361         reg->parts[1].region = then_b; then_b->parent = reg;
362         reg->parts[2].region = else_b; else_b->parent = reg;
363
364         reg->pred = DUP_ARR_D(ir_region *, obst, if_b->pred);
365         reg->succ = DUP_ARR_D(ir_region *, obst, then_b->succ);
366
367         DB((dbg, LEVEL_2, " Created If(%u)Then(%u)Else(%u)\n", reg->nr, then_b->nr, else_b->nr));
368
369         return reg;
370 }  /* new_IfThenElse */
371
372 /**
373  * Create a new IfThen region.
374  */
375 static ir_region *new_IfThen(struct obstack *obst, ir_region *if_b, ir_region *then_b)
376 {
377         ir_region *reg;
378
379         ALLOC_REG(obst, reg, ir_rk_IfThen);
380
381         reg->nr    = if_b->nr;
382         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, 2);
383
384         reg->parts[0].region = if_b;   if_b->parent   = reg;
385         reg->parts[1].region = then_b; then_b->parent = reg;
386
387         reg->pred = DUP_ARR_D(ir_region *, obst, if_b->pred);
388         reg->succ = DUP_ARR_D(ir_region *, obst, then_b->succ);
389
390         DB((dbg, LEVEL_2, " Created If(%u)Then(%u)\n", reg->nr, then_b->nr));
391
392         return reg;
393 }  /* new_IfThenElse */
394
395 /**
396  * Create a new Switch/case region.
397  */
398 static ir_region *new_SwitchCase(struct obstack *obst, ir_region_kind type, ir_region *head, ir_region *exit,
399                                  ir_region *cases, int cases_len)
400 {
401         ir_region *reg, *c, *n;
402         int i;
403         int add = 1;
404
405         /* check, if the exit block is in the list */
406         for (c = cases; c != NULL; c = c->link) {
407                 if (c == exit) {
408                         add = 0;
409                         break;
410                 }
411         }
412
413         ALLOC_REG(obst, reg, type);
414
415         reg->nr    = head->nr;
416         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, cases_len + add);
417
418         reg->parts[0].region = head; head->parent = reg;
419         i = 1;
420         for (c = cases; c != NULL; c = n) {
421                 n = c->link;
422                 if (c != exit) {
423                         reg->parts[i++].region = c;
424                         c->parent = reg;
425                 }
426                 c->link = NULL;
427         }
428
429         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
430         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
431         reg->succ[0] = exit;
432
433         DEBUG_ONLY(
434                 DB((dbg, LEVEL_2, " Created %s(%u)\n", reg->type == ir_rk_Switch ? "Switch" : "Case", reg->nr));
435                 for (i = 1; i < ARR_LEN(reg->parts); ++i) {
436                         DB((dbg, LEVEL_2, "  Case(%u)\n", reg->parts[i].region->nr));
437                 }
438                 DB((dbg, LEVEL_2, "  Exit(%u)\n", exit->nr));
439         )
440         return reg;
441 }  /* new_SwitchCase */
442
443 /**
444  * Create a new SelfLoop region.
445  */
446 static ir_region *new_SelfLoop(struct obstack *obst, ir_region *head)
447 {
448         ir_region *reg, *succ;
449         int i, j, len;
450
451         ALLOC_REG(obst, reg, ir_rk_SelfLoop);
452
453         reg->nr      = head->nr;
454         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 1);
455
456         reg->parts[0].region = head; head->parent = reg;
457
458         len = ARR_LEN(head->pred);
459         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
460         for (i = j = 0; i < len; ++i) {
461                 ir_region *pred = get_region_pred(head, i);
462                 if (pred != head)
463                         reg->pred[j++] = pred;
464         }
465         assert(j == len - 1);
466
467         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
468         assert(ARR_LEN(head->succ) == 2);
469
470         succ = get_region_succ(head, 0);
471         if (succ != head)
472                 reg->succ[0] = succ;
473         else
474                 reg->succ[0] = get_region_succ(head, 1);
475
476         DB((dbg, LEVEL_2, " Created SelfLoop(%u)\n", reg->nr));
477
478         return reg;
479 }  /* new_SelfLoop */
480
481 /**
482  * Create a new RepeatLoop region.
483  */
484 static ir_region *new_RepeatLoop(struct obstack *obst, ir_region *head, ir_region *body)
485 {
486         ir_region *reg, *succ;
487
488         ALLOC_REG(obst, reg, ir_rk_RepeatLoop);
489
490         reg->nr      = head->nr;
491         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 2);
492
493         reg->parts[0].region = head; head->parent = reg;
494         reg->parts[1].region = body; body->parent = reg;
495
496         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
497         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
498         assert(ARR_LEN(body->succ) == 2);
499
500         succ = get_region_succ(body, 0);
501         if (succ != head)
502                 reg->succ[0] = succ;
503         else
504                 reg->succ[0] = get_region_succ(body, 1);
505
506         DB((dbg, LEVEL_2, " Created RepeatLoop(%u)Body(%u)\n", reg->nr, body->nr));
507
508         return reg;
509 }  /* new_RepeatLoop */
510
511 /**
512  * Create a new WhileLoop region.
513  */
514 static ir_region *new_WhileLoop(struct obstack *obst, ir_region *head)
515 {
516         ir_region *reg, *succ;
517         ir_region *body = head->link;
518         int i, j, len;
519
520         head->link = NULL;
521
522         ALLOC_REG(obst, reg, ir_rk_WhileLoop);
523
524         reg->nr      = head->nr;
525         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 2);
526
527         reg->parts[0].region = head; head->parent = reg;
528         reg->parts[1].region = body; body->parent = reg;
529
530         len = ARR_LEN(head->pred);
531         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
532         for (i = j = 0; i < len; ++i) {
533                 ir_region *pred = get_region_pred(head, i);
534                 if (pred != body)
535                         reg->pred[j++] = pred;
536         }
537         assert(j == len - 1);
538
539         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
540         assert(ARR_LEN(head->succ) == 2);
541
542         succ = get_region_succ(head, 0);
543         if (succ != body)
544                 reg->succ[0] = succ;
545         else
546                 reg->succ[0] = get_region_succ(head, 1);
547
548         DB((dbg, LEVEL_2, " Created WhileLoop(%u)Body(%u)\n", reg->nr, body->nr));
549
550         return reg;
551 }  /* new_WhileLoop */
552
553 /**
554  * Create a new new_NaturalLoop region.
555  */
556 static ir_region *new_NaturalLoop(struct obstack *obst, ir_region *head)
557 {
558         ir_region *reg, *c, *n;
559         int i, j, k, len, n_pred, n_succ;
560
561         /* count number of parts */
562         for (len = 0, c = head; c != NULL; c = c->link)
563                 ++len;
564
565         ALLOC_REG(obst, reg, ir_rk_WhileLoop);
566
567         reg->nr      = head->nr;
568         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, len);
569
570         /* enter all parts */
571         for (i = 0, c = head; c != NULL; c = n) {
572                 reg->parts[i++].region = c;
573                 c->parent = reg;
574                 n = c->link;
575                 c->link = NULL;
576         }
577
578         /* count number of preds */
579         n_pred = 0;
580         for (i = get_region_n_preds(head) - 1; i >= 0; --i) {
581                 ir_region *pred = get_region_pred(head, i);
582                 if (pred->parent != reg)
583                         ++n_pred;
584         }
585         reg->pred = NEW_ARR_D(ir_region *, obst, n_pred);
586         for (j = 0, i = get_region_n_preds(head) - 1; i >= 0; --i) {
587                 ir_region *pred = get_region_pred(head, i);
588                 if (pred->parent != reg)
589                         reg->pred[j++] = pred;
590         }
591
592         /* count number of succs */
593         n_succ = 0;
594         for (j = 0; j < len; ++j) {
595                 ir_region *pc = reg->parts[j].region;
596                 for (i = get_region_n_succs(pc) - 1; i >= 0; --i) {
597                         ir_region *succ = get_region_succ(pc, i);
598                         if (succ->parent != reg)
599                                 ++n_succ;
600                 }
601         }
602         reg->succ = NEW_ARR_D(ir_region *, obst, n_succ);
603         k = 0;
604         for (j = 0; j < len; ++j) {
605                 ir_region *pc = reg->parts[j].region;
606                 for (i = get_region_n_succs(pc) - 1; i >= 0; --i) {
607                         ir_region *succ = get_region_succ(pc, i);
608                         if (succ->parent != reg)
609                                 reg->succ[k++] = succ;
610                 }
611         }
612
613         DEBUG_ONLY(
614                 DB((dbg, LEVEL_2, " Created NaturalLoop(%u)Head(%u)\n", reg->nr, head->nr));
615                 for (i = 1; i < len; ++i) {
616                         ir_region *p = reg->parts[i].region;
617                         DB((dbg, LEVEL_2, "  Body(%u)\n", p->nr));
618                 }
619         )
620         return reg;
621 }  /* new_NaturalLoop */
622
623 /**
624  * Return true if region a is an ancestor of region b in DFS search.
625  */
626 static int is_ancestor(const ir_region *a, const ir_region *b)
627 {
628         return (a->prenum <= b->prenum && a->postnum > b->postnum);
629 }
630
631 /**
632  * Return true if region pred is a predecessor of region n.
633  */
634 static int pred_of(const ir_region *pred, const ir_region *n)
635 {
636         int i;
637         for (i = get_region_n_preds(n) - 1; i >= 0; --i) {
638                 if (get_region_pred(n, i) == pred)
639                         return 1;
640         }
641         return 0;
642 }
643
644 /**
645  * Return true if region succ is a successor of region n.
646  */
647 static int succ_of(const ir_region *succ, const ir_region *n)
648 {
649         int i;
650         for (i = get_region_n_succs(n) - 1; i >= 0; --i) {
651                 if (get_region_succ(n, i) == succ)
652                         return 1;
653         }
654         return 0;
655 }
656
657 /**
658  * Reverse a linked list of regions.
659  */
660 static struct ir_region *reverse_list(ir_region *n)
661 {
662         ir_region *prev = NULL, *next;
663
664         for (; n; n = next) {
665                 next = n->link;
666                 n->link = prev;
667                 prev = n;
668         }
669         return prev;
670 }
671
672 /**
673  * Find the cyclic region in the subgraph entered by node.
674  */
675 static ir_region *find_cyclic_region(ir_region *node)
676 {
677         int i;
678         ir_region *last = node;
679         int improper = 0;
680
681         for (i = get_region_n_preds(node) - 1; i >= 0; --i) {
682                 ir_region *pred = get_region_pred(node, i);
683
684                 /* search backedges */
685                 if (!pred->link && pred != last && is_ancestor(node, pred)) {
686                         ir_region *rem = last;
687                         int j;
688
689                         last->link = pred;
690                         last       = pred;
691                         for (j = get_region_n_preds(pred) - 1; j >= 0; --j) {
692                                 ir_region *p = get_region_pred(pred, j);
693
694                                 /* Search regions we didn't visited yet and
695                                    link them into the list. */
696                                 if (!p->link && p != last) {
697                                         if (is_ancestor(node, p)) {
698                                                 last->link = p;
699                                                 last       = p;
700                                         } else {
701                                                 improper = 1;
702                                         }
703                                 }
704                         }
705                         /* reverse the list. */
706                         last = rem->link;
707                         rem->link = reverse_list(rem->link);
708                 }
709         }
710
711         if (node->link && improper) {
712                 /* found an improper region, do minimization */
713
714         }
715         return node;
716 }
717
718 #define LINK(list) ((ir_region *)list->link)
719
720 /**
721  * Detect a cyclic region.
722  */
723 static ir_region *cyclic_region_type(struct obstack *obst, ir_region *node)
724 {
725         ir_region *list;
726
727         /* simple cases first */
728         if (succ_of(node, node)) {
729                 return new_SelfLoop(obst, node);
730         }
731         if (get_region_n_succs(node) == 1) {
732                 ir_region *succ = get_region_succ(node, 0);
733                 if (get_region_n_preds(succ) == 1 && succ_of(node, succ)) {
734                         return new_RepeatLoop(obst, node, succ);
735                 }
736         }
737         list = find_cyclic_region(node);
738
739         if (list->link) {
740                 if (!LINK(list)->link && get_region_n_succs(list->link) == 1) {
741                         /* only one body block with only one successor (the head) */
742                         return new_WhileLoop(obst, list);
743                 }
744                 /* A Loop with one head */
745                 return new_NaturalLoop(obst, list);
746         }
747
748         return NULL;
749 }
750
751 /**
752  * Clear all links on a list. Needed, because we expect cleared links.
753  */
754 static void clear_list(ir_region *list)
755 {
756         ir_region *next;
757
758         for (next = list; next; list = next) {
759                 next = list->link;
760                 list->link = NULL;
761         }
762 }
763
764 #define ADD_LIST(list, n) do { n->link = list; list = n; ++list##_len; } while (0)
765
766 /**
767  * Detect an acyclic region.
768  */
769 static ir_region *acyclic_region_type(struct obstack *obst, ir_region *node)
770 {
771         ir_region *n, *m;
772         int p, s, i, k;
773         ir_region *nset = NULL;
774         int nset_len = 0;
775         ir_region *res;
776
777         /* check for a block containing node */
778         n = node;
779         p = get_region_n_preds(n) == 1;
780         s = 1;
781         while (p & s) {
782                 n = get_region_pred(n, 0);
783                 p = get_region_n_preds(n) == 1;
784                 s = get_region_n_succs(n) == 1;
785         }
786         p = 1;
787         s = get_region_n_succs(n) == 1;
788         while (p & s) {
789                 ADD_LIST(nset, n);
790                 n = get_region_succ(n, 0);
791                 p = get_region_n_preds(n) == 1;
792                 s = get_region_n_succs(n) == 1;
793         }
794         if (p) {
795                 ADD_LIST(nset, n);
796         }
797         if (nset_len > 1) {
798                 /* node --> .. --> .. */
799                 res = new_Sequence(obst, nset, nset_len);
800                 return res;
801         }
802         node = n;
803
804         /* check for IfThenElse */
805         k = get_region_n_succs(node);
806         if (k == 2) {
807                 int n_succs, m_succs, n_preds, m_preds;
808
809                 n = get_region_succ(node, 0);
810                 m = get_region_succ(node, 1);
811
812                 n_succs = get_region_n_succs(n);
813                 m_succs = get_region_n_succs(m);
814                 n_preds = get_region_n_preds(n);
815                 m_preds = get_region_n_preds(m);
816                 if (n_succs == 1 && n_succs == m_succs && n_preds == m_preds &&
817                     get_region_succ(n, 0) == get_region_succ(m, 0)) {
818                         /*
819                          *    /-->n---\
820                          * node      ...
821                          *    \-->m---/
822                          */
823                         return new_IfThenElse(obst, node, n, m);
824                 }
825                 if (n_succs == 1 &&
826                     get_region_succ(n, 0) == m &&
827                     pred_of(node, m)) {
828                         /*
829                          * node -->n-->m
830                          *    \-------/
831                          */
832                         return new_IfThen(obst, node, n);
833                 }
834                 if (m_succs == 1 &&
835                     get_region_succ(m, 0) == m &&
836                     pred_of(node, n)) {
837                         /*
838                          * node -->m-->n
839                          *    \-------/
840                          */
841                         return new_IfThen(obst, node, m);
842                 }
843         }
844         /* check for Switch, case */
845         if (k > 0) {
846                 ir_region *rexit = NULL;
847                 nset = NULL; nset_len = 0;
848                 p = 0;
849                 for (i = k - 1; i >= 0; --i) {
850                         n = get_region_succ(node, i);
851                         ADD_LIST(nset, n);
852                         if (get_region_n_succs(n) != 1) {
853                                 /* must be the exit */
854                                 rexit = n;
855                                 ++p;
856                                 if (p > 1)
857                                         break;
858                         }
859                 }
860                 if (p <= 1) {
861                         ir_region_kind kind = ir_rk_Case;
862                         ir_region *pos_exit_1 = NULL;
863                         ir_region *pos_exit_2 = NULL;
864
865                         /* find the exit */
866                         for (m = nset; m != NULL; m = m->link) {
867                                 if (get_region_n_succs(m) != 1) {
868                                         /* must be the exit block */
869                                         if (rexit == NULL) {
870                                                 rexit = m;
871                                         } else if (rexit != m) {
872                                                 /* two exits */
873                                                 rexit = NULL;
874                                                 break;
875                                         }
876                                 } else {
877                                         ir_region *succ = get_region_succ(m, 0);
878
879                                         if (succ->link == NULL) {
880                                                 if (rexit == NULL) {
881                                                         if (succ == pos_exit_1)
882                                                                 rexit = succ;
883                                                         else if (succ == pos_exit_2)
884                                                                 rexit = succ;
885                                                         else if (pos_exit_1 == NULL)
886                                                                 pos_exit_1 = succ;
887                                                         else if (pos_exit_2 == NULL)
888                                                                 pos_exit_2 = succ;
889                                                         else {
890                                                                 /* more than two possible exits */
891                                                                 break;
892                                                         }
893                                                 } else if (rexit != succ) {
894                                                         /* two exits */
895                                                         rexit = NULL;
896                                                         break;
897                                                 }
898                                         }
899                                 }
900                         }
901                         if (rexit != NULL) {
902                                 /* do the checks */
903                                 for (n = nset; n != NULL; n = n->link) {
904                                         ir_region *succ;
905                                         if (n == rexit) {
906                                                 /* good, default fall through */
907                                                 continue;
908                                         }
909                                         succ = get_region_succ(n, 0);
910                                         if (succ == rexit) {
911                                                 /* good, switch to exit */
912                                                 continue;
913                                         }
914                                         if (succ->link == NULL) {
915                                                 /* another exit */
916                                                 break;
917                                         } else {
918                                                 /* a fall through */
919                                                 kind = ir_rk_Switch;
920                                         }
921                                 }
922
923                                 if (n == NULL) {
924                                         /* detected */
925                                         return new_SwitchCase(obst, kind, node, rexit, nset, nset_len);
926                                 }
927                         }
928                 }
929                 clear_list(nset);
930         }
931         return NULL;
932 }
933
934 /**
935  * replace all pred edges from region pred that points to any of the set set
936  * to ONE edge to reg.
937  */
938 static void replace_pred(ir_region *succ, ir_region *reg)
939 {
940         int i, len = get_region_n_preds(succ);
941         int have_one = 0;
942
943         for (i = 0; i < len; ++i) {
944                 ir_region *pred = get_region_pred(succ, i);
945
946                 if (pred->parent == reg) {
947                         ir_region *r;
948
949                         if (have_one) {
950                                 /* kill it */
951                                 r = get_region_pred(succ, --len);
952                         } else {
953                                 /* replace it */
954                                 have_one = 1;
955                                 r = reg;
956                         }
957                         set_region_pred(succ, i, r);
958                 } else {
959                         /* the current region can be entered by this node */
960                         pred->enter = 1;
961                 }
962         }
963         ARR_SHRINKLEN(succ->pred, len);
964 }
965
966 /**
967  * replace all succ edges from region pred that points to any of the set set
968  * to ONE edge to reg.
969  */
970 static void replace_succ(ir_region *pred, ir_region *reg)
971 {
972         int i, len = get_region_n_succs(pred);
973         int have_one = 0;
974
975         for (i = 0; i < len; ++i) {
976                 ir_region *succ = get_region_succ(pred, i);
977
978                 if (succ->parent == reg) {
979                         ir_region *r;
980
981                         if (have_one) {
982                                 /* kill it */
983                                 r = get_region_succ(pred, --len);
984                         } else {
985                                 /* replace it */
986                                 have_one = 1;
987                                 r = reg;
988                         }
989                         set_region_succ(pred, i, r);
990                 } else {
991                         /* current region can be left by this node */
992                         succ->exit = 1;
993                 }
994         }
995         ARR_SHRINKLEN(pred->succ, len);
996 }
997
998 /**
999  * Reduce the graph by the node reg.
1000  */
1001 static void reduce(walk_env *env, ir_region *reg)
1002 {
1003         int i;
1004         ir_region *head = reg->parts[0].region;
1005         unsigned maxorder = head->postnum;
1006         unsigned minorder = head->prenum;
1007
1008         /* second step: replace all preds in successors */
1009         for (i = get_region_n_succs(reg) - 1; i >= 0; --i) {
1010                 ir_region *succ = get_region_succ(reg, i);
1011
1012                 replace_pred(succ, reg);
1013         }
1014
1015         /* third step: replace all succs in predessors */
1016         for (i = get_region_n_preds(reg) - 1; i >= 0; --i) {
1017                 ir_region *pred = get_region_pred(reg, i);
1018
1019                 replace_succ(pred, reg);
1020         }
1021
1022         reg->prenum  = minorder;
1023         reg->postnum = maxorder;
1024         env->post[maxorder] = reg;
1025 }
1026
1027 /**
1028  * Construct the region tree of a graph by doing
1029  * structural analysis.
1030  *
1031  * Uses link fields of nodes.
1032  *
1033  * @param irg  the graph
1034  */
1035 ir_reg_tree *construct_region_tree(ir_graph *irg)
1036 {
1037         walk_env env;
1038         ir_graph *rem = current_ir_graph;
1039         ir_reg_tree *res = XMALLOC(ir_reg_tree);
1040
1041         obstack_init(&res->obst);
1042
1043         current_ir_graph = irg;
1044
1045         FIRM_DBG_REGISTER(dbg, "firm.ana.structure");
1046         firm_dbg_set_mask(dbg, SET_LEVEL_5);
1047
1048         DB((dbg, LEVEL_1, "Structural analysis on %+F starts...\n", irg));
1049
1050         /* we need dominance info */
1051         assure_doms(irg);
1052         /* and out edges */
1053         assure_irg_outs(irg);
1054
1055         env.start_block = get_irg_start_block(irg);
1056         env.end_block   = get_irg_end_block(irg);
1057
1058         /* create the Block wrapper and count them */
1059         env.l_post = 0;
1060         env.obst   = &res->obst;
1061         irg_block_walk_graph(irg, NULL, wrap_BasicBlocks, &env);
1062         irg_block_walk_graph(irg, NULL, update_BasicBlock_regions, &env);
1063
1064         env.post = NEW_ARR_F(ir_region *, env.l_post);
1065
1066         /* do the DFS walk */
1067         dfs_walk(irg, &env);
1068
1069         DB((dbg, LEVEL_1, "%d regions left\n", env.postmax));
1070         if (env.postmax > 1) {
1071                 unsigned postctr = 0;
1072                 do {
1073                         ir_region *reg, *n = env.post[postctr];
1074                         do {
1075                                 if (n->parent != NULL) {
1076                                         /* already folded */
1077                                         break;
1078                                 }
1079                                 /* locate an acyclic region if present */
1080                                 reg = acyclic_region_type(env.obst, n);
1081                                 if (reg == NULL) {
1082                                         /* locate a cyclic region */
1083                                         reg = cyclic_region_type(env.obst, n);
1084                                 }
1085                                 if (reg != NULL) {
1086                                         /* found a new region */
1087                                         reduce(&env, reg);
1088                                         n = reg;
1089                                 }
1090                         } while (reg != NULL);
1091                         ++postctr;
1092                 } while (postctr < env.postmax);
1093         }
1094         DB((dbg, LEVEL_1, "Structural analysis finished.\n"));
1095
1096         DEL_ARR_F(env.post);
1097         current_ir_graph = rem;
1098
1099         res->top = env.post[0];
1100         res->irg = irg;
1101         return res;
1102 }
1103
1104 /**
1105  * Walk over the region tree.
1106  *
1107  * @param reg   a region node
1108  * @param pre   walker function, executed before the children of a tree node are visited
1109  * @param post  walker function, executed after the children of a tree node are visited
1110  * @param env   environment, passed to pre and post
1111  */
1112 static void region_tree_walk2(ir_region *reg, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1113 {
1114         int i, n;
1115
1116         if (pre)
1117                 pre(reg, env);
1118         if (reg->type != ir_rk_BasicBlock) {
1119                 for (i = 0, n = ARR_LEN(reg->parts); i < n; ++i)
1120                         region_tree_walk2(reg->parts[i].region, pre, post, env);
1121         }
1122         if (post)
1123                 post(reg, env);
1124 }
1125
1126 /**
1127  * Walk over the region tree.
1128  *
1129  * @param tree  the tree
1130  * @param pre   walker function, executed before the children of a tree node are visited
1131  * @param post  walker function, executed after the children of a tree node are visited
1132  * @param env   environment, passed to pre and post
1133  */
1134 void region_tree_walk(ir_reg_tree *tree, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1135 {
1136         region_tree_walk2(tree->top, pre, post, env);
1137 }