367804bdd0af08cf648e8aa5add7a9f13239fab2
[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_no_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         ir_region *reg, *c, *n;
401         int i;
402         int add = 1;
403
404         /* check, if the exit block is in the list */
405         for (c = cases; c != NULL; c = c->link) {
406                 if (c == exit) {
407                         add = 0;
408                         break;
409                 }
410         }
411
412         ALLOC_REG(obst, reg, type);
413
414         reg->nr    = head->nr;
415         reg->parts = NEW_ARR_D(ir_reg_or_blk, obst, cases_len + add);
416
417         reg->parts[0].region = head; head->parent = reg;
418         i = 1;
419         for (c = cases; c != NULL; c = n) {
420                 n = c->link;
421                 if (c != exit) {
422                         reg->parts[i++].region = c;
423                         c->parent = reg;
424                 }
425                 c->link = NULL;
426         }
427
428         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
429         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
430         reg->succ[0] = exit;
431
432         DEBUG_ONLY(
433                 DB((dbg, LEVEL_2, " Created %s(%u)\n", reg->type == ir_rk_Switch ? "Switch" : "Case", reg->nr));
434                 for (i = 1; i < ARR_LEN(reg->parts); ++i) {
435                         DB((dbg, LEVEL_2, "  Case(%u)\n", reg->parts[i].region->nr));
436                 }
437                 DB((dbg, LEVEL_2, "  Exit(%u)\n", exit->nr));
438         )
439         return reg;
440 }  /* new_SwitchCase */
441
442 /**
443  * Create a new SelfLoop region.
444  */
445 static ir_region *new_SelfLoop(struct obstack *obst, ir_region *head)
446 {
447         ir_region *reg, *succ;
448         int i, j, len;
449
450         ALLOC_REG(obst, reg, ir_rk_SelfLoop);
451
452         reg->nr      = head->nr;
453         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 1);
454
455         reg->parts[0].region = head; head->parent = reg;
456
457         len = ARR_LEN(head->pred);
458         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
459         for (i = j = 0; i < len; ++i) {
460                 ir_region *pred = get_region_pred(head, i);
461                 if (pred != head)
462                         reg->pred[j++] = pred;
463         }
464         assert(j == len - 1);
465
466         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
467         assert(ARR_LEN(head->succ) == 2);
468
469         succ = get_region_succ(head, 0);
470         if (succ != head)
471                 reg->succ[0] = succ;
472         else
473                 reg->succ[0] = get_region_succ(head, 1);
474
475         DB((dbg, LEVEL_2, " Created SelfLoop(%u)\n", reg->nr));
476
477         return reg;
478 }  /* new_SelfLoop */
479
480 /**
481  * Create a new RepeatLoop region.
482  */
483 static ir_region *new_RepeatLoop(struct obstack *obst, ir_region *head, ir_region *body)
484 {
485         ir_region *reg, *succ;
486
487         ALLOC_REG(obst, reg, ir_rk_RepeatLoop);
488
489         reg->nr      = head->nr;
490         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 2);
491
492         reg->parts[0].region = head; head->parent = reg;
493         reg->parts[1].region = body; body->parent = reg;
494
495         reg->pred = DUP_ARR_D(ir_region *, obst, head->pred);
496         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
497         assert(ARR_LEN(body->succ) == 2);
498
499         succ = get_region_succ(body, 0);
500         if (succ != head)
501                 reg->succ[0] = succ;
502         else
503                 reg->succ[0] = get_region_succ(body, 1);
504
505         DB((dbg, LEVEL_2, " Created RepeatLoop(%u)Body(%u)\n", reg->nr, body->nr));
506
507         return reg;
508 }  /* new_RepeatLoop */
509
510 /**
511  * Create a new WhileLoop region.
512  */
513 static ir_region *new_WhileLoop(struct obstack *obst, ir_region *head)
514 {
515         ir_region *reg, *succ;
516         ir_region *body = head->link;
517         int i, j, len;
518
519         head->link = NULL;
520
521         ALLOC_REG(obst, reg, ir_rk_WhileLoop);
522
523         reg->nr      = head->nr;
524         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, 2);
525
526         reg->parts[0].region = head; head->parent = reg;
527         reg->parts[1].region = body; body->parent = reg;
528
529         len = ARR_LEN(head->pred);
530         reg->pred = NEW_ARR_D(ir_region *, obst, len - 1);
531         for (i = j = 0; i < len; ++i) {
532                 ir_region *pred = get_region_pred(head, i);
533                 if (pred != body)
534                         reg->pred[j++] = pred;
535         }
536         assert(j == len - 1);
537
538         reg->succ = NEW_ARR_D(ir_region *, obst, 1);
539         assert(ARR_LEN(head->succ) == 2);
540
541         succ = get_region_succ(head, 0);
542         if (succ != body)
543                 reg->succ[0] = succ;
544         else
545                 reg->succ[0] = get_region_succ(head, 1);
546
547         DB((dbg, LEVEL_2, " Created WhileLoop(%u)Body(%u)\n", reg->nr, body->nr));
548
549         return reg;
550 }  /* new_WhileLoop */
551
552 /**
553  * Create a new new_NaturalLoop region.
554  */
555 static ir_region *new_NaturalLoop(struct obstack *obst, ir_region *head)
556 {
557         ir_region *reg, *c, *n;
558         int i, j, k, len, n_pred, n_succ;
559
560         /* count number of parts */
561         for (len = 0, c = head; c != NULL; c = c->link)
562                 ++len;
563
564         ALLOC_REG(obst, reg, ir_rk_WhileLoop);
565
566         reg->nr      = head->nr;
567         reg->parts   = NEW_ARR_D(ir_reg_or_blk, obst, len);
568
569         /* enter all parts */
570         for (i = 0, c = head; c != NULL; c = n) {
571                 reg->parts[i++].region = c;
572                 c->parent = reg;
573                 n = c->link;
574                 c->link = NULL;
575         }
576
577         /* count number of preds */
578         n_pred = 0;
579         for (i = get_region_n_preds(head) - 1; i >= 0; --i) {
580                 ir_region *pred = get_region_pred(head, i);
581                 if (pred->parent != reg)
582                         ++n_pred;
583         }
584         reg->pred = NEW_ARR_D(ir_region *, obst, n_pred);
585         for (j = 0, i = get_region_n_preds(head) - 1; i >= 0; --i) {
586                 ir_region *pred = get_region_pred(head, i);
587                 if (pred->parent != reg)
588                         reg->pred[j++] = pred;
589         }
590
591         /* count number of succs */
592         n_succ = 0;
593         for (j = 0; j < len; ++j) {
594                 ir_region *c = reg->parts[j].region;
595                 for (i = get_region_n_succs(c) - 1; i >= 0; --i) {
596                         ir_region *succ = get_region_succ(c, i);
597                         if (succ->parent != reg)
598                                 ++n_succ;
599                 }
600         }
601         reg->succ = NEW_ARR_D(ir_region *, obst, n_succ);
602         k = 0;
603         for (j = 0; j < len; ++j) {
604                 ir_region *c = reg->parts[j].region;
605                 for (i = get_region_n_succs(c) - 1; i >= 0; --i) {
606                         ir_region *succ = get_region_succ(c, i);
607                         if (succ->parent != reg)
608                                 reg->succ[k++] = succ;
609                 }
610         }
611
612         DEBUG_ONLY(
613                 DB((dbg, LEVEL_2, " Created NaturalLoop(%u)Head(%u)\n", reg->nr, head->nr));
614                 for (i = 1; i < len; ++i) {
615                         ir_region *p = reg->parts[i].region;
616                         DB((dbg, LEVEL_2, "  Body(%u)\n", p->nr));
617                 }
618         )
619         return reg;
620 }  /* new_NaturalLoop */
621
622 /**
623  * Return true if region a is an ancestor of region b in DFS search.
624  */
625 static int is_ancestor(const ir_region *a, const ir_region *b)
626 {
627         return (a->prenum <= b->prenum && a->postnum > b->postnum);
628 }
629
630 /**
631  * Return true if region pred is a predecessor of region n.
632  */
633 static int pred_of(const ir_region *pred, const ir_region *n)
634 {
635         int i;
636         for (i = get_region_n_preds(n) - 1; i >= 0; --i) {
637                 if (get_region_pred(n, i) == pred)
638                         return 1;
639         }
640         return 0;
641 }
642
643 /**
644  * Return true if region succ is a successor of region n.
645  */
646 static int succ_of(const ir_region *succ, const ir_region *n)
647 {
648         int i;
649         for (i = get_region_n_succs(n) - 1; i >= 0; --i) {
650                 if (get_region_succ(n, i) == succ)
651                         return 1;
652         }
653         return 0;
654 }
655
656 /**
657  * Reverse a linked list of regions.
658  */
659 static struct ir_region *reverse_list(ir_region *n)
660 {
661         ir_region *prev = NULL, *next;
662
663         for (; n; n = next) {
664                 next = n->link;
665                 n->link = prev;
666                 prev = n;
667         }
668         return prev;
669 }
670
671 /**
672  * Find the cyclic region in the subgraph entered by node.
673  */
674 static ir_region *find_cyclic_region(ir_region *node)
675 {
676         int i;
677         ir_region *last = node;
678         int improper = 0;
679
680         for (i = get_region_n_preds(node) - 1; i >= 0; --i) {
681                 ir_region *pred = get_region_pred(node, i);
682
683                 /* search backedges */
684                 if (!pred->link && pred != last && is_ancestor(node, pred)) {
685                         ir_region *rem = last;
686                         int j;
687
688                         last->link = pred;
689                         last       = pred;
690                         for (j = get_region_n_preds(pred) - 1; j >= 0; --j) {
691                                 ir_region *p = get_region_pred(pred, j);
692
693                                 /* Search regions we didn't visited yet and
694                                    link them into the list. */
695                                 if (!p->link && p != last) {
696                                         if (is_ancestor(node, p)) {
697                                                 last->link = p;
698                                                 last       = p;
699                                         } else {
700                                                 improper = 1;
701                                         }
702                                 }
703                         }
704                         /* reverse the list. */
705                         last = rem->link;
706                         rem->link = reverse_list(rem->link);
707                 }
708         }
709
710         if (node->link && improper) {
711                 /* found an improper region, do minimization */
712
713         }
714         return node;
715 }
716
717 #define LINK(list) ((ir_region *)list->link)
718
719 /**
720  * Detect a cyclic region.
721  */
722 static ir_region *cyclic_region_type(struct obstack *obst, ir_region *node)
723 {
724         ir_region *list;
725
726         /* simple cases first */
727         if (succ_of(node, node)) {
728                 return new_SelfLoop(obst, node);
729         }
730         if (get_region_n_succs(node) == 1) {
731                 ir_region *succ = get_region_succ(node, 0);
732                 if (get_region_n_preds(succ) == 1 && succ_of(node, succ)) {
733                         return new_RepeatLoop(obst, node, succ);
734                 }
735         }
736         list = find_cyclic_region(node);
737
738         if (list->link) {
739                 if (!LINK(list)->link && get_region_n_succs(list->link) == 1) {
740                         /* only one body block with only one successor (the head) */
741                         return new_WhileLoop(obst, list);
742                 }
743                 /* A Loop with one head */
744                 return new_NaturalLoop(obst, list);
745         }
746
747         return NULL;
748 }
749
750 /**
751  * Clear all links on a list. Needed, because we expect cleared links.
752  */
753 static void clear_list(ir_region *list)
754 {
755         ir_region *next;
756
757         for (next = list; next; list = next) {
758                 next = list->link;
759                 list->link = NULL;
760         }
761 }
762
763 #define ADD_LIST(list, n) do { n->link = list; list = n; ++list##_len; } while(0)
764
765 /**
766  * Detect an acyclic region.
767  */
768 static ir_region *acyclic_region_type(struct obstack *obst, ir_region *node)
769 {
770         ir_region *n, *m;
771         int p, s, i, k;
772         ir_region *nset = NULL;
773         int nset_len = 0;
774         ir_region *res;
775
776         /* check for a block containing node */
777         n = node;
778         p = get_region_n_preds(n) == 1;
779         s = 1;
780         while (p & s) {
781                 n = get_region_pred(n, 0);
782                 p = get_region_n_preds(n) == 1;
783                 s = get_region_n_succs(n) == 1;
784         }
785         p = 1;
786         s = get_region_n_succs(n) == 1;
787         while (p & s) {
788                 ADD_LIST(nset, n);
789                 n = get_region_succ(n, 0);
790                 p = get_region_n_preds(n) == 1;
791                 s = get_region_n_succs(n) == 1;
792         }
793         if (p) {
794                 ADD_LIST(nset, n);
795         }
796         if (nset_len > 1) {
797                 /* node --> .. --> .. */
798                 res = new_Sequence(obst, nset, nset_len);
799                 return res;
800         }
801         node = n;
802
803         /* check for IfThenElse */
804         k = get_region_n_succs(node);
805         if (k == 2) {
806                 int n_succs, m_succs, n_preds, m_preds;
807
808                 n = get_region_succ(node, 0);
809                 m = get_region_succ(node, 1);
810
811                 n_succs = get_region_n_succs(n);
812                 m_succs = get_region_n_succs(m);
813                 n_preds = get_region_n_preds(n);
814                 m_preds = get_region_n_preds(m);
815                 if (n_succs == 1 && n_succs == m_succs && n_preds == m_preds &&
816                     get_region_succ(n, 0) == get_region_succ(m, 0)) {
817                         /*
818                          *    /-->n---\
819                          * node      ...
820                          *    \-->m---/
821                          */
822                         return new_IfThenElse(obst, node, n, m);
823                 }
824                 if (n_succs == 1 &&
825                     get_region_succ(n, 0) == m &&
826                     pred_of(node, m)) {
827                         /*
828                          * node -->n-->m
829                          *    \-------/
830                          */
831                         return new_IfThen(obst, node, n);
832                 }
833                 if (m_succs == 1 &&
834                     get_region_succ(m, 0) == m &&
835                     pred_of(node, n)) {
836                         /*
837                          * node -->m-->n
838                          *    \-------/
839                          */
840                         return new_IfThen(obst, node, m);
841                 }
842         }
843         /* check for Switch, case */
844         if (k > 0) {
845                 ir_region *exit = NULL;
846                 nset = NULL; nset_len = 0;
847                 p = 0;
848                 for (i = k - 1; i >= 0; --i) {
849                         n = get_region_succ(node, i);
850                         ADD_LIST(nset, n);
851                         if (get_region_n_succs(n) != 1) {
852                                 /* must be the exit */
853                                 exit = n;
854                                 ++p;
855                                 if (p > 1)
856                                         break;
857                         }
858                 }
859                 if (p <= 1) {
860                         ir_region_kind kind = ir_rk_Case;
861                         ir_region *pos_exit_1 = NULL;
862                         ir_region *pos_exit_2 = NULL;
863
864                         /* find the exit */
865                         for (m = nset; m != NULL; m = m->link) {
866                                 if (get_region_n_succs(m) != 1) {
867                                         /* must be the exit block */
868                                         if (exit == NULL) {
869                                                 exit = m;
870                                         } else if (exit != m) {
871                                                 /* two exits */
872                                                 exit = NULL;
873                                                 break;
874                                         }
875                                 } else {
876                                         ir_region *succ = get_region_succ(m, 0);
877
878                                         if (succ->link == NULL) {
879                                                 if (exit == NULL) {
880                                                         if (succ == pos_exit_1)
881                                                                 exit = succ;
882                                                         else if (succ == pos_exit_2)
883                                                                 exit = succ;
884                                                         else if (pos_exit_1 == NULL)
885                                                                 pos_exit_1 = succ;
886                                                         else if (pos_exit_2 == NULL)
887                                                                 pos_exit_2 = succ;
888                                                         else {
889                                                                 /* more than two possible exits */
890                                                                 break;
891                                                         }
892                                                 } else if (exit != succ) {
893                                                         /* two exits */
894                                                         exit = NULL;
895                                                         break;
896                                                 }
897                                         }
898                                 }
899                         }
900                         if (exit != NULL) {
901                                 /* do the checks */
902                                 for (n = nset; n != NULL; n = n->link) {
903                                         ir_region *succ;
904                                         if (n == exit) {
905                                                 /* good, default fall through */
906                                                 continue;
907                                         }
908                                         succ = get_region_succ(n, 0);
909                                         if (succ == exit) {
910                                                 /* good, switch to exit */
911                                                 continue;
912                                         }
913                                         if (succ->link == NULL) {
914                                                 /* another exit */
915                                                 break;
916                                         } else {
917                                                 /* a fall through */
918                                                 kind = ir_rk_Switch;
919                                         }
920                                 }
921
922                                 if (n == NULL) {
923                                         /* detected */
924                                         return new_SwitchCase(obst, kind, node, exit, nset, nset_len);
925                                 }
926                         }
927                 }
928                 clear_list(nset);
929         }
930         return NULL;
931 }
932
933 /**
934  * replace all pred edges from region pred that points to any of the set set
935  * to ONE edge to reg.
936  */
937 static void replace_pred(ir_region *succ, ir_region *reg)
938 {
939         int i, len = get_region_n_preds(succ);
940         int have_one = 0;
941
942         for (i = 0; i < len; ++i) {
943                 ir_region *pred = get_region_pred(succ, i);
944
945                 if (pred->parent == reg) {
946                         ir_region *r;
947
948                         if (have_one) {
949                                 /* kill it */
950                                 r = get_region_pred(succ, --len);
951                         } else {
952                                 /* replace it */
953                                 have_one = 1;
954                                 r = reg;
955                         }
956                         set_region_pred(succ, i, r);
957                 } else {
958                         /* the current region can be entered by this node */
959                         pred->enter = 1;
960                 }
961         }
962         ARR_SHRINKLEN(succ->pred, len);
963 }
964
965 /**
966  * replace all succ edges from region pred that points to any of the set set
967  * to ONE edge to reg.
968  */
969 static void replace_succ(ir_region *pred, ir_region *reg)
970 {
971         int i, len = get_region_n_succs(pred);
972         int have_one = 0;
973
974         for (i = 0; i < len; ++i) {
975                 ir_region *succ = get_region_succ(pred, i);
976
977                 if (succ->parent == reg) {
978                         ir_region *r;
979
980                         if (have_one) {
981                                 /* kill it */
982                                 r = get_region_succ(pred, --len);
983                         } else {
984                                 /* replace it */
985                                 have_one = 1;
986                                 r = reg;
987                         }
988                         set_region_succ(pred, i, r);
989                 } else {
990                         /* current region can be left by this node */
991                         succ->exit = 1;
992                 }
993         }
994         ARR_SHRINKLEN(pred->succ, len);
995 }
996
997 /**
998  * Reduce the graph by the node reg.
999  */
1000 static void reduce(walk_env *env, ir_region *reg)
1001 {
1002         int i;
1003         ir_region *head = reg->parts[0].region;
1004         unsigned maxorder = head->postnum;
1005         unsigned minorder = head->prenum;
1006
1007         /* second step: replace all preds in successors */
1008         for (i = get_region_n_succs(reg) - 1; i >= 0; --i) {
1009                 ir_region *succ = get_region_succ(reg, i);
1010
1011                 replace_pred(succ, reg);
1012         }
1013
1014         /* third step: replace all succs in predessors */
1015         for (i = get_region_n_preds(reg) - 1; i >= 0; --i) {
1016                 ir_region *pred = get_region_pred(reg, i);
1017
1018                 replace_succ(pred, reg);
1019         }
1020
1021         reg->prenum  = minorder;
1022         reg->postnum = maxorder;
1023         env->post[maxorder] = reg;
1024 }
1025
1026 /**
1027  * Construct the region tree of a graph by doing
1028  * structural analysis.
1029  *
1030  * Uses link fields of nodes.
1031  *
1032  * @param irg  the graph
1033  */
1034 ir_reg_tree *construct_region_tree(ir_graph *irg)
1035 {
1036         walk_env env;
1037         ir_graph *rem = current_ir_graph;
1038         ir_reg_tree *res = XMALLOC(ir_reg_tree);
1039
1040         obstack_init(&res->obst);
1041
1042         current_ir_graph = irg;
1043
1044         FIRM_DBG_REGISTER(dbg, "firm.ana.structure");
1045         firm_dbg_set_mask(dbg, SET_LEVEL_5);
1046
1047         DB((dbg, LEVEL_1, "Structural analysis on %+F starts...\n", irg));
1048
1049         dump_ir_block_graph(irg, "-structure_start");
1050
1051         /* we need dominance info */
1052         assure_doms(irg);
1053         /* and out edges */
1054         assure_irg_outs(irg);
1055
1056         env.start_block = get_irg_start_block(irg);
1057         env.end_block   = get_irg_end_block(irg);
1058
1059         /* create the Block wrapper and count them */
1060         env.l_post = 0;
1061         env.obst   = &res->obst;
1062         irg_block_walk_graph(irg, NULL, wrap_BasicBlocks, &env);
1063         irg_block_walk_graph(irg, NULL, update_BasicBlock_regions, &env);
1064
1065         env.post = NEW_ARR_F(ir_region *, env.l_post);
1066
1067         /* do the DFS walk */
1068         dfs_walk(irg, &env);
1069
1070         DB((dbg, LEVEL_1, "%d regions left\n", env.postmax));
1071         if (env.postmax > 1) {
1072                 unsigned postctr = 0;
1073                 do {
1074                         ir_region *reg, *n = env.post[postctr];
1075                         do {
1076                                 if (n->parent != NULL) {
1077                                         /* already folded */
1078                                         break;
1079                                 }
1080                                 /* locate an acyclic region if present */
1081                                 reg = acyclic_region_type(env.obst, n);
1082                                 if (reg == NULL) {
1083                                         /* locate a cyclic region */
1084                                         reg = cyclic_region_type(env.obst, n);
1085                                 }
1086                                 if (reg != NULL) {
1087                                         /* found a new region */
1088                                         reduce(&env, reg);
1089                                         n = reg;
1090                                 }
1091                         } while (reg != NULL);
1092                         ++postctr;
1093                 } while (postctr < env.postmax);
1094         }
1095         DB((dbg, LEVEL_1, "Structural analysis finished.\n"));
1096
1097         DEL_ARR_F(env.post);
1098         current_ir_graph = rem;
1099
1100         res->top = env.post[0];
1101         res->irg = irg;
1102         return res;
1103 }
1104
1105 /**
1106  * Walk over the region tree.
1107  *
1108  * @param reg   a region node
1109  * @param pre   walker function, executed before the children of a tree node are visited
1110  * @param post  walker function, executed after the children of a tree node are visited
1111  * @param env   environment, passed to pre and post
1112  */
1113 static void region_tree_walk2(ir_region *reg, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1114 {
1115         int i, n;
1116
1117         if (pre)
1118                 pre(reg, env);
1119         if (reg->type != ir_rk_BasicBlock) {
1120                 for (i = 0, n = ARR_LEN(reg->parts); i < n; ++i)
1121                         region_tree_walk2(reg->parts[i].region, pre, post, env);
1122         }
1123         if (post)
1124                 post(reg, env);
1125 }
1126
1127 /**
1128  * Walk over the region tree.
1129  *
1130  * @param tree  the tree
1131  * @param pre   walker function, executed before the children of a tree node are visited
1132  * @param post  walker function, executed after the children of a tree node are visited
1133  * @param env   environment, passed to pre and post
1134  */
1135 void region_tree_walk(ir_reg_tree *tree, irg_reg_walk_func *pre, irg_reg_walk_func *post, void *env)
1136 {
1137         region_tree_walk2(tree->top, pre, post, env);
1138 }