Put a space after if/for/switch/while.
[libfirm] / ir / ana / irouts.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    Compute and access out edges (also called def-use edges).
23  * @author   Goetz Lindenmaier, Michael Beck
24  * @date     1.2002
25  * @version  $Id$
26  */
27 #include "config.h"
28
29 #include <string.h>
30
31 #include "xmalloc.h"
32 #include "irouts.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "irprog_t.h"
36 #include "irgwalk.h"
37 #include "irtools.h"
38 #include "irprintf.h"
39 #include "error.h"
40
41 #ifdef DEBUG_libfirm
42 /* Note:  ir_node.out_valid and ir_graph.n_outs are only present when DEBUG_libfirm is defined */
43 /* Accesses to out_valid and n_outs are fenced out to avoid breakage
44    when compiling with neither DEBUG_libfirm or NDEBUG defined */
45 #endif /* defined DEBUG_libfirm */
46
47 /*--------------------------------------------------------------------*/
48 /** Accessing the out datastructures                                 **/
49 /*--------------------------------------------------------------------*/
50
51 #ifdef DEBUG_libfirm
52 /** Clear the outs of a node */
53 static void reset_outs(ir_node *node, void *unused)
54 {
55         (void) unused;
56         node->out       = NULL;
57         node->out_valid = 0;
58 }
59 #endif
60
61 int get_irn_outs_computed(const ir_node *node)
62 {
63         return node->out != NULL;
64 }
65
66 /* returns the number of successors of the node: */
67 int get_irn_n_outs(const ir_node *node)
68 {
69         assert(node && node->kind == k_ir_node);
70 #ifdef DEBUG_libfirm
71         /* assert(node->out_valid); */
72 #endif /* defined DEBUG_libfirm */
73         /* we misuse the first for the size info of the out array */
74         return node->out[0].pos;
75 }
76
77 /* Access successor n */
78 ir_node *get_irn_out(const ir_node *def, int pos)
79 {
80         assert(pos >= 0 && pos < get_irn_n_outs(def));
81 #ifdef DEBUG_libfirm
82         /* assert(def->out_valid); */
83 #endif /* defined DEBUG_libfirm */
84         return def->out[pos+1].use;
85 }
86
87 /* Access successor n */
88 ir_node *get_irn_out_ex(const ir_node *def, int pos, int *in_pos)
89 {
90         assert(pos >= 0 && pos < get_irn_n_outs(def));
91 #ifdef DEBUG_libfirm
92         /* assert(def->out_valid); */
93 #endif /* defined DEBUG_libfirm */
94         *in_pos = def->out[pos+1].pos;
95         return def->out[pos+1].use;
96 }
97
98 void set_irn_out(ir_node *def, int pos, ir_node *use, int in_pos)
99 {
100         assert(def && use);
101         assert(pos >= 0 && pos < get_irn_n_outs(def));
102 #ifdef DEBUG_libfirm
103         def->out_valid = 1;          /* assume that this function is used correctly */
104 #endif /* defined DEBUG_libfirm */
105         def->out[pos+1].use = use;
106         def->out[pos+1].pos = in_pos;
107 }
108
109 /* Return the number of control flow successors, ignore keep-alives. */
110 int get_Block_n_cfg_outs(const ir_node *bl)
111 {
112         int i, n_cfg_outs = 0;
113         assert(bl && is_Block(bl));
114 #ifdef DEBUG_libfirm
115         assert(bl->out_valid);
116 #endif /* defined DEBUG_libfirm */
117         for (i = 1; i <= bl->out[0].pos; ++i) {
118                 ir_node *succ = bl->out[i].use;
119                 if (get_irn_mode(succ) == mode_X && !is_End(succ))
120                         n_cfg_outs += succ->out[0].pos;
121         }
122         return n_cfg_outs;
123 }
124
125 /* Return the number of control flow successors, honor keep-alives. */
126 int get_Block_n_cfg_outs_ka(const ir_node *bl)
127 {
128         int i, n_cfg_outs = 0;
129         assert(bl && is_Block(bl));
130 #ifdef DEBUG_libfirm
131         assert(bl->out_valid);
132 #endif /* defined DEBUG_libfirm */
133         for (i = 1; i <= bl->out[0].pos; ++i) {
134                 ir_node *succ = bl->out[i].use;
135                 if (get_irn_mode(succ) == mode_X) {
136
137                         if (is_End(succ)) {
138                                 /* ignore End if we are in the Endblock */
139                                 if (get_nodes_block(succ) == bl)
140                                         continue;
141                                 else /* count Keep-alive as one */
142                                         n_cfg_outs += 1;
143                         } else
144                                 n_cfg_outs += succ->out[0].pos;
145                 }
146         }
147         return n_cfg_outs;
148 }
149
150 /* Access predecessor n, ignore keep-alives. */
151 ir_node *get_Block_cfg_out(const ir_node *bl, int pos)
152 {
153         int i;
154         assert(bl && is_Block(bl));
155 #ifdef DEBUG_libfirm
156         assert(bl->out_valid);
157 #endif /* defined DEBUG_libfirm */
158         for (i = 1; i <= bl->out[0].pos; ++i) {
159                 ir_node *succ = bl->out[i].use;
160                 if (get_irn_mode(succ) == mode_X && !is_End(succ)) {
161                         int n_outs = succ->out[0].pos;
162                         if (pos < n_outs)
163                                 return succ->out[pos + 1].use;
164                         else
165                                 pos -= n_outs;
166                 }
167         }
168         return NULL;
169 }
170
171 /* Access predecessor n, honor keep-alives. */
172 ir_node *get_Block_cfg_out_ka(const ir_node *bl, int pos)
173 {
174         int i, n_outs;
175         assert(bl && is_Block(bl));
176 #ifdef DEBUG_libfirm
177         assert (bl->out_valid);
178 #endif /* defined DEBUG_libfirm */
179         for (i = 1; i <= bl->out[0].pos; ++i) {
180                 ir_node *succ = bl->out[i].use;
181                 if (get_irn_mode(succ) == mode_X) {
182                         if (is_End(succ)) {
183                                 ir_node *end_bl = get_nodes_block(succ);
184                                 if (end_bl == bl) {
185                                         /* ignore End if we are in the Endblock */
186                                         continue;
187                                 }
188                                 if (pos == 0) {
189                                         /* handle keep-alive here: return the Endblock instead of the End node */
190                                         return end_bl;
191                                 } else
192                                         --pos;
193                         } else {
194                                 n_outs = succ->out[0].pos;
195                                 if (pos < n_outs)
196                                         return succ->out[pos + 1].use;
197                                 else
198                                         pos -= n_outs;
199                         }
200                 }
201         }
202         return NULL;
203 }
204
205 static void irg_out_walk_2(ir_node *node, irg_walk_func *pre,
206             irg_walk_func *post, void *env) {
207         int     i, n;
208         ir_node *succ;
209
210         assert(node);
211         assert(get_irn_visited(node) < get_irg_visited(current_ir_graph));
212
213         set_irn_visited(node, get_irg_visited(current_ir_graph));
214
215         if (pre) pre(node, env);
216
217         for (i = 0, n = get_irn_n_outs(node); i < n; ++i) {
218                 succ = get_irn_out(node, i);
219                 if (get_irn_visited(succ) < get_irg_visited(current_ir_graph))
220                         irg_out_walk_2(succ, pre, post, env);
221         }
222
223         if (post) post(node, env);
224 }
225
226 void irg_out_walk(ir_node *node,
227                   irg_walk_func *pre, irg_walk_func *post,
228                   void *env) {
229         assert(node);
230         if (get_irg_outs_state(current_ir_graph) != outs_none) {
231                 inc_irg_visited (current_ir_graph);
232                 irg_out_walk_2(node, pre, post, env);
233         }
234 }
235
236 static void irg_out_block_walk2(ir_node *bl,
237                                 irg_walk_func *pre, irg_walk_func *post,
238                                 void *env) {
239         int i, n;
240
241         if (!Block_block_visited(bl)) {
242                 mark_Block_block_visited(bl);
243
244                 if (pre)
245                         pre(bl, env);
246
247                 for (i = 0, n =  get_Block_n_cfg_outs(bl); i < n; ++i) {
248                         /* find the corresponding predecessor block. */
249                         ir_node *pred = get_Block_cfg_out(bl, i);
250                         /* recursion */
251                         irg_out_block_walk2(pred, pre, post, env);
252                 }
253
254                 if (post)
255                         post(bl, env);
256         }
257 }
258
259 /* Walks only over Block nodes in the graph.  Has it's own visited
260    flag, so that it can be interleaved with the other walker.         */
261 void irg_out_block_walk(ir_node *node,
262                         irg_walk_func *pre, irg_walk_func *post,
263                         void *env) {
264
265         assert(is_Block(node) || (get_irn_mode(node) == mode_X));
266
267         inc_irg_block_visited(current_ir_graph);
268
269         if (get_irn_mode(node) == mode_X) {
270                 int i, n;
271
272                 for (i = 0, n = get_irn_n_outs(node); i < n; ++i) {
273                         ir_node *succ = get_irn_out(node, i);
274                         irg_out_block_walk2(succ, pre, post, env);
275                 }
276         }
277         else {
278                 irg_out_block_walk2(node, pre, post, env);
279         }
280 }
281
282 /*--------------------------------------------------------------------*/
283 /** Building and Removing the out datastructure                      **/
284 /**                                                                  **/
285 /** The outs of a graph are allocated in a single, large array.      **/
286 /** This allows to allocate and deallocate the memory for the outs   **/
287 /** on demand.  The large array is separated into many small ones    **/
288 /** for each node.  Only a single field to reference the out array   **/
289 /** is stored in each node and a field referencing the large out     **/
290 /** array in irgraph.  The 0 field of each out array contains the    **/
291 /** size of this array.  This saves memory in the irnodes themselves.**/
292 /** The construction does two passes over the graph.  The first pass **/
293 /** counts the overall number of outs and the outs of each node.  It **/
294 /** stores the outs of each node in the out reference of the node.   **/
295 /** Then the large array is allocated.  The second iteration chops   **/
296 /** the large array into smaller parts, sets the out edges and       **/
297 /** recounts the out edges.                                          **/
298 /** Removes Tuple nodes!                                             **/
299 /*--------------------------------------------------------------------*/
300
301
302 /** Returns the amount of out edges for not yet visited successors. */
303 static int _count_outs(ir_node *n)
304 {
305         int start, i, res, irn_arity;
306
307         mark_irn_visited(n);
308         n->out = INT_TO_PTR(1);     /* Space for array size. */
309
310         start = is_Block(n) ? 0 : -1;
311         irn_arity = get_irn_arity(n);
312         res = irn_arity - start + 1;  /* --1 or --0; 1 for array size. */
313
314         for (i = start; i < irn_arity; ++i) {
315                 /* Optimize Tuples.  They annoy if walking the cfg. */
316                 ir_node *pred         = get_irn_n(n, i);
317                 ir_node *skipped_pred = skip_Tuple(pred);
318
319                 if (skipped_pred != pred) {
320                         set_irn_n(n, i, skipped_pred);
321                 }
322
323                 /* count Def-Use edges for predecessors */
324                 if (!irn_visited(skipped_pred))
325                         res += _count_outs(skipped_pred);
326
327                 /*count my Def-Use edges */
328                 skipped_pred->out = INT_TO_PTR(PTR_TO_INT(skipped_pred->out) + 1);
329         }
330         return res;
331 }
332
333
334 /** Returns the amount of out edges for not yet visited successors.
335  *  This version handles some special nodes like irg_frame, irg_args etc.
336  */
337 static int count_outs(ir_graph *irg)
338 {
339         ir_node *n;
340         int     i, res;
341
342         inc_irg_visited(irg);
343         res = _count_outs(get_irg_end(irg));
344
345         /* Now handle anchored nodes. We need the out count of those
346            even if they are not visible. */
347         for (i = anchor_last - 1; i >= 0; --i) {
348                 n = get_irg_anchor(irg, i);
349                 if (!irn_visited_else_mark(n)) {
350                         n->out = INT_TO_PTR(1);
351                         ++res;
352                 }
353         }
354         return res;
355 }
356
357 /**
358  * Enter memory for the outs to a node.
359  *
360  * @param use    current node
361  * @param free   current free address in the chunk allocated for the outs
362  *
363  * @return The next free address
364  */
365 static ir_def_use_edge *_set_out_edges(ir_node *use, ir_def_use_edge *free)
366 {
367         int     n_outs, start, i, irn_arity, pos;
368
369         mark_irn_visited(use);
370
371         /* Allocate my array */
372         n_outs = PTR_TO_INT(use->out);
373         use->out = free;
374 #ifdef DEBUG_libfirm
375         use->out_valid = 1;
376 #endif /* defined DEBUG_libfirm */
377         free += n_outs;
378         /* We count the successors again, the space will be sufficient.
379            We use this counter to remember the position for the next back
380            edge. */
381         use->out[0].pos = 0;
382
383         start = is_Block(use) ? 0 : -1;
384         irn_arity = get_irn_arity(use);
385
386         for (i = start; i < irn_arity; ++i) {
387                 ir_node *def = get_irn_n(use, i);
388
389                 /* Recursion */
390                 if (!irn_visited(def))
391                         free = _set_out_edges(def, free);
392
393                 /* Remember this Def-Use edge */
394                 pos = def->out[0].pos + 1;
395                 def->out[pos].use = use;
396                 def->out[pos].pos = i;
397
398                 /* increase the number of Def-Use edges so far */
399                 def->out[0].pos = pos;
400         }
401         return free;
402 }
403
404 /**
405  * Enter memory for the outs to a node. Handles special nodes
406  *
407  * @param irg    the graph
408  * @param free   current free address in the chunk allocated for the outs
409  *
410  * @return The next free address
411  */
412 static ir_def_use_edge *set_out_edges(ir_graph *irg, ir_def_use_edge *free)
413 {
414         ir_node *n;
415         int     i, n_outs;
416
417         inc_irg_visited(irg);
418         free = _set_out_edges(get_irg_end(irg), free);
419
420         /* handle anchored nodes */
421         for (i = anchor_last - 1; i >= 0; --i) {
422                 n = get_irg_anchor(irg, i);
423                 if (!irn_visited_else_mark(n)) {
424                         n_outs = PTR_TO_INT(n->out);
425                         n->out = free;
426 #ifdef DEBUG_libfirm
427                         n->out_valid = 1;
428 #endif /* defined DEBUG_libfirm */
429                         free += n_outs;
430                 }
431         }
432
433         return free;
434 }
435
436 /* compute the outs for a given graph */
437 void compute_irg_outs(ir_graph *irg)
438 {
439         ir_graph        *rem = current_ir_graph;
440         int             n_out_edges = 0;
441         ir_def_use_edge *end = NULL;         /* Only for debugging */
442
443         current_ir_graph = irg;
444
445         /* Update graph state */
446         assert(get_irg_phase_state(current_ir_graph) != phase_building);
447
448         if (current_ir_graph->outs_state != outs_none)
449                 free_irg_outs(current_ir_graph);
450
451         /* This first iteration counts the overall number of out edges and the
452            number of out edges for each node. */
453         n_out_edges = count_outs(irg);
454
455         /* allocate memory for all out edges. */
456         irg->outs = XMALLOCNZ(ir_def_use_edge, n_out_edges);
457 #ifdef DEBUG_libfirm
458         irg->n_outs = n_out_edges;
459 #endif /* defined DEBUG_libfirm */
460
461         /* The second iteration splits the irg->outs array into smaller arrays
462            for each node and writes the back edges into this array. */
463         end = set_out_edges(irg, irg->outs);
464
465         /* Check how much memory we have used */
466         assert (end == (irg->outs + n_out_edges));
467
468         current_ir_graph->outs_state = outs_consistent;
469         current_ir_graph = rem;
470 }
471
472 void assure_irg_outs(ir_graph *irg)
473 {
474         if (get_irg_outs_state(irg) != outs_consistent)
475                 compute_irg_outs(irg);
476 }
477
478 void compute_irp_outs(void)
479 {
480         int i;
481         for (i = get_irp_n_irgs() -1; i >= 0; --i)
482                 compute_irg_outs(get_irp_irg(i));
483 }
484
485 void free_irp_outs(void)
486 {
487         int i;
488         for (i = get_irp_n_irgs() -1; i >= 0; --i)
489                 free_irg_outs(get_irp_irg(i));
490 }
491
492
493 /*------------------------------------------------------------*
494  *  This computes the outedges for in interprocedural graph.  *
495  *  There is one quirk:                                       *
496  *  The number of the outedges for each node is saved in      *
497  *  the first member of the ir_node** array. Maybe we should  *
498  *  change this to make it more portable...                   *
499  *------------------------------------------------------------*/
500
501
502 #ifdef INTERPROCEDURAL_VIEW
503 /**
504  * Inits the number of outedges for each node
505  * before counting.
506  */
507 static void init_count(ir_node * node, void *env)
508 {
509         (void) env;
510         node->out = (ir_node **) 1; /* 1 for the array size */
511 }
512
513
514 /**
515  * Adjusts the out edge count for its predecessors
516  * and adds the current arity to the overall count,
517  * which is saved in "env"
518  */
519 static void node_arity_count(ir_node * node, void * env)
520 {
521         int *anz = (int *) env, arity, n_outs, i, start;
522         ir_node *succ;
523
524         arity = get_irn_arity(node);
525         start = (is_Block(node)) ? 0 : -1;
526
527         n_outs = 1 + arity + (-start);  // ((is_Block(node)) ? 0 : 1);   // Why + 1??
528         *anz += n_outs;
529
530         for (i = start; i < arity; i++) {
531                 succ = get_irn_n(node, i);
532                 succ->out = (ir_node **)INT_TO_PTR(PTR_TO_INT(succ->out) + 1);
533         }
534 }
535
536 /*
537  * Inits all nodes for setting the outedges
538  * Returns the overall count of edges
539  */
540 int count_ip_outs(void)
541 {
542         int res = 0;
543
544         cg_walk(init_count, node_arity_count, &res);
545
546         return(res);
547 }
548
549 static int dummy_count = 0, global_count; /* Only for debugging */
550
551 /**
552  * For each node: Sets the pointer to array
553  * in which the outedges are written later.
554  * The current array start is transported in env
555  */
556 static void set_array_pointer(ir_node *node, void *env)
557 {
558         int n_outs;
559         ir_node ***free = (ir_node ***) env;
560
561         /* Allocate my array */
562         n_outs = PTR_TO_INT(node->out);  /* We wrote the count here in count_ip_outs */
563         dummy_count += n_outs;
564         assert(dummy_count <= global_count && "More outedges than initially counted!");
565         node -> out = *free;
566         *free = &((*free)[n_outs]);
567         /* We count the successors again, the space will be sufficient.
568            We use this counter to remember the position for the next back
569            edge. */
570         node -> out[0] = (ir_node *) 0;
571 }
572
573
574 /**
575  * Adds an outedge from the predecessor to the
576  * current node.
577  */
578 static void set_out_pointer(ir_node * node, void *env)
579 {
580         int i, arity = get_irn_arity(node);
581         ir_node *succ;
582         int start = (!is_Block(node)) ? -1 : 0;
583         (void) env;
584
585         for (i = start; i < arity; ++i) {
586                 succ = get_irn_n(node, i);
587                 succ->out[get_irn_n_outs(succ)+1] = node;
588                 succ->out[0] = INT_TO_PTR(get_irn_n_outs(succ) + 1);
589         }
590 }
591
592
593 /*
594  * Sets the outedges for all nodes.
595  */
596 void set_ip_outs(void)
597 {
598         ir_node **outedge_array = get_irp_ip_outedges();
599         cg_walk(set_array_pointer, set_out_pointer, (void *) &outedge_array);
600 }
601
602
603
604 /*
605  * Counts the outedges, allocates memory to save the
606  * outedges and fills this outedge array in interprocedural
607  * view!
608  */
609 void compute_ip_outs(void)
610 {
611         int n_out_edges;
612         ir_node **out_edges;
613
614         assert(get_irp_ip_view_state() == ip_view_valid &&
615          "Cannot construct outs for invalid ip view.");
616
617         if (irp->outs_state != outs_none) {
618                 free_ip_outs();
619         }
620
621         global_count = n_out_edges = count_ip_outs();
622         out_edges    = XMALLOCNZ(ir_node*, n_out_edges);
623         set_irp_ip_outedges(out_edges);
624         set_ip_outs();
625 }
626
627 void free_ip_outs(void)
628 {
629         ir_node **out_edges = get_irp_ip_outedges();
630         if (out_edges != NULL) {
631                 free(out_edges);
632                 set_irp_ip_outedges(NULL);
633         }
634         irp->outs_state = outs_none;
635 }
636 #endif
637
638
639 void free_irg_outs(ir_graph *irg)
640 {
641         /*   current_ir_graph->outs_state = outs_none; */
642         irg->outs_state = outs_none;
643
644         if (irg->outs) {
645 #ifdef DEBUG_libfirm
646                 memset(irg->outs, 0, irg->n_outs);
647 #endif /* defined DEBUG_libfirm */
648                 free(irg->outs);
649                 irg->outs = NULL;
650 #ifdef DEBUG_libfirm
651                 irg->n_outs = 0;
652 #endif /* defined DEBUG_libfirm */
653         }
654
655 #ifdef DEBUG_libfirm
656         /* when debugging, *always* reset all nodes' outs!  irg->outs might
657            have been lying to us */
658         irg_walk_graph (irg, reset_outs, NULL, NULL);
659 #endif /* defined DEBUG_libfirm */
660 }
661
662 static void check_out_edges(ir_node *irn, void *env)
663 {
664         int i, j, pos;
665         int *pError = env;
666         int error = *pError;
667         int last = is_Block(irn) ? 0 : -1;
668
669         /* check forward: every input must have an out edge */
670         for (i = get_irn_arity(irn) - 1; i >= last; --i) {
671                 ir_node *pred = get_irn_n(irn, i);
672
673                 for (j = get_irn_n_outs(pred) - 1; j >= 0; --j) {
674                         ir_node *user = get_irn_out_ex(pred, j, &pos);
675
676                         if (user == irn && pos == i) {
677                                 break;
678                         }
679                 }
680                 if (j < 0) {
681                         ir_fprintf(stderr, "Missing out edge from %+F input %d to %+F", irn, i, pred);
682                         ++error;
683                 }
684         }
685
686         /* checking backward */
687         for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
688                 ir_node *user = get_irn_out_ex(irn, i, &pos);
689
690                 if (get_irn_n(user, pos) != irn) {
691                         ir_fprintf(stderr, "Spurious out edge from %+F output %d to %+F", irn, i, user);
692                         ++error;
693                 }
694         }
695         *pError = error;
696 }
697
698 /* verify outs edges. */
699 void verify_outs(ir_graph *irg)
700 {
701         int errors = 0;
702         irg_walk_graph(irg, NULL, check_out_edges, &errors);
703         if (errors > 0)
704                 panic("Out edges are corrupt");
705 }