8863bfe715ab688805318a3c4cbdf1bfb418b892
[libfirm] / ir / ir / iredges.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   Always available outs.
23  * @author  Sebastian Hack, Michael Beck, Andreas Schoesser
24  * @date    14.1.2005
25  * @version $Id$
26  * @brief
27  *   This are out-edges (also called def-use edges) that are dynamically
28  *   updated as the graph changes.
29  */
30 #include "config.h"
31
32 #include "irnode_t.h"
33 #include "iropt_t.h"
34 #include "iredgekinds.h"
35 #include "iredges_t.h"
36 #include "irgwalk.h"
37 #include "irdump_t.h"
38 #include "irprintf.h"
39 #include "debug.h"
40 #include "set.h"
41 #include "bitset.h"
42 #include "error.h"
43 #include "irpass_t.h"
44
45 #include "iredgeset.h"
46 #include "hashptr.h"
47
48 #define DO_REHASH
49 #define SCALAR_RETURN
50 #define HashSet                   ir_edgeset_t
51 #define HashSetIterator           ir_edgeset_iterator_t
52 #define ValueType                 ir_edge_t*
53 #define NullValue                 NULL
54 #define DeletedValue              ((ir_edge_t*)-1)
55 #define Hash(this,key)            (HASH_PTR(key->src) ^ (key->pos * 40013))
56 #define KeysEqual(this,key1,key2) ((key1->src) == (key2->src) && (key1->pos == key2->pos))
57 #define SetRangeEmpty(ptr,size)   memset(ptr, 0, (size) * sizeof((ptr)[0]))
58
59 #define hashset_init            ir_edgeset_init
60 #define hashset_init_size       ir_edgeset_init_size
61 #define hashset_destroy         ir_edgeset_destroy
62 #define hashset_insert          ir_edgeset_insert
63 #define hashset_remove          ir_edgeset_remove
64 #define hashset_find            ir_edgeset_find
65 #define hashset_size            ir_edgeset_size
66 #define hashset_iterator_init   ir_edgeset_iterator_init
67 #define hashset_iterator_next   ir_edgeset_iterator_next
68 #define hashset_remove_iterator ir_edgeset_remove_iterator
69
70 #include "hashset.c"
71
72 /**
73  * A function that allows for setting an edge.
74  * This abstraction is necessary since different edge kind have
75  * different methods of setting edges.
76  */
77 typedef void (set_edge_func_t)(ir_node *src, int pos, ir_node *tgt);
78
79 /**
80  * A function that returns the "arity" of a given edge kind
81  * for a node.
82  */
83 typedef int (get_edge_src_arity_func_t)(const ir_node *src);
84
85 /**
86  * A function that returns the pos'th edge of a given edge kind for a node.
87  */
88 typedef ir_node *(get_edge_src_n_func_t)(const ir_node *src, int pos);
89
90 /**
91  * Additional data for an edge kind.
92  */
93 typedef struct {
94         const char                *name;       /**< name of this edge kind */
95         set_edge_func_t           *set_edge;   /**< the set_edge function */
96         int                       first_idx;   /**< index of the first possible edge */
97         get_edge_src_arity_func_t *get_arity;  /**< the get_arity function */
98         get_edge_src_n_func_t     *get_n;      /**< the get_n function */
99 } ir_edge_kind_info_t;
100
101 /**
102  * Get the predecessor block.
103  */
104 static ir_node *get_block_n(const ir_node *block, int pos) {
105         if (is_Block(block))
106                 return get_Block_cfgpred_block(block, pos);
107         /* might be a Bad */
108         return NULL;
109 }
110
111 static const ir_edge_kind_info_t edge_kind_info[EDGE_KIND_LAST] = {
112         { "normal"     , set_irn_n,   -1, get_irn_arity,  get_irn_n   },
113         { "block succs", NULL,         0, get_irn_arity,  get_block_n },
114         { "dependency",  set_irn_dep,  0, get_irn_deps,   get_irn_dep }
115 };
116
117 #define foreach_tgt(irn, i, n, kind) for(i = edge_kind_info[kind].first_idx, n = edge_kind_info[kind].get_arity(irn); i < n; ++i)
118 #define get_n(irn, pos, kind)        (edge_kind_info[kind].get_n(irn, pos))
119 #define get_kind_str(kind)           (edge_kind_info[kind].name)
120
121 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
122
123 /**
124  * This flag is set to 1, if the edges get initialized for an irg.
125  * Then register additional data is forbidden.
126  */
127 static int edges_used = 0;
128
129 /**
130  * Summed size of all users private data
131  */
132
133 static int edges_private_size = 0;
134 #define EDGE_SIZE (sizeof(ir_edge_t) + edges_private_size)
135
136 /**
137  * If set to 1, the list heads are checked every time an edge is changed.
138  */
139 static int edges_dbg = 0;
140
141 #ifdef DEBUG_libfirm
142 /* a static variable holding the last number assigned to a new edge */
143 static long last_edge_num = -1;
144 #endif
145
146 /**
147  * Returns an ID for the given edge.
148  */
149 static inline long edge_get_id(const ir_edge_t *e) {
150 #ifdef DEBUG_libfirm
151         return e->edge_nr;
152 #else /* DEBUG_libfirm */
153         return (long)e;
154 #endif /* DEBUG_libfirm */
155 }
156
157 /**
158  * Announce to reserve extra space for each edge to be allocated.
159  *
160  * @param n: Size of the space to reserve
161  *
162  * @return Offset at which the private data will begin
163  *
164  * Several users can reserve extra space for private usage.
165  * Each user has to remember his given offset and the size of his private data.
166  * To be called before FIRM is initialized.
167  */
168 int edges_register_private_data(size_t n) {
169         int res = edges_private_size;
170
171         assert(!edges_used && "you cannot register private edge data, if edges have been initialized");
172
173         edges_private_size += n;
174         return res;
175 }
176
177 /*
178  * Reset the user's private data at offset 'offset'
179  * The user has to remember his offset and the size of his data!
180  * Caution: Using wrong values here can destroy other users private data!
181  */
182 void edges_reset_private_data(ir_graph *irg, int offset, unsigned size) {
183         irg_edge_info_t       *info = _get_irg_edge_info(irg, EDGE_KIND_NORMAL);
184         ir_edge_t             *edge;
185         ir_edgeset_iterator_t  iter;
186
187         foreach_ir_edgeset(&info->edges, edge, iter) {
188                 memset(edge + sizeof(*edge) + offset, 0, size);
189         }
190 }
191
192 #define TIMES37(x) (((x) << 5) + ((x) << 2) + (x))
193
194 #define get_irn_out_list_head(irn) (&get_irn_out_info(irn)->outs)
195
196 #define edge_hash(edge) (TIMES37((edge)->pos) + HASH_PTR((edge)->src))
197
198 /**
199  * Initialize the out information for a graph.
200  * @note Dead node elimination can call this on an already initialized graph.
201  */
202 void edges_init_graph_kind(ir_graph *irg, ir_edge_kind_t kind) {
203         if (edges_activated_kind(irg, kind)) {
204                 irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
205                 size_t amount = irg->estimated_node_count * 2;
206
207                 edges_used = 1;
208                 if(info->allocated) {
209                         amount = ir_edgeset_size(&info->edges);
210                         ir_edgeset_destroy(&info->edges);
211                         obstack_free(&info->edges_obst, NULL);
212                 }
213                 obstack_init(&info->edges_obst);
214                 INIT_LIST_HEAD(&info->free_edges);
215                 ir_edgeset_init_size(&info->edges, amount);
216                 info->allocated = 1;
217         }
218 }
219
220 /**
221  * Get the edge object of an outgoing edge at a node.
222  * @param  irg  The graph, the node is in.
223  * @param  src  The node at which the edge originates.
224  * @param  pos  The position of the edge.
225  * @param  kind The kind of the edge.
226  * @return      The corresponding edge object or NULL,
227  *              if no such edge exists.
228  */
229 const ir_edge_t *get_irn_edge_kind(ir_graph *irg, const ir_node *src, int pos, ir_edge_kind_t kind)
230 {
231         if (edges_activated_kind(irg, kind)) {
232                 irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
233                 ir_edge_t       key;
234
235                 key.src = (ir_node *)src;
236                 key.pos = pos;
237
238                 return ir_edgeset_find(&info->edges, &key);
239         }
240
241         return NULL;
242 }
243
244 /**
245  * Get the edge object of an outgoing edge at a node.
246  * Looks for an edge for all kinds.
247  */
248 const ir_edge_t *get_irn_edge(ir_graph *irg, const ir_node *src, int pos) {
249         const ir_edge_t *edge;
250         if((edge = get_irn_edge_kind(irg, src, pos, EDGE_KIND_NORMAL)) == NULL)
251                 edge = get_irn_edge_kind(irg, src, pos, EDGE_KIND_BLOCK);
252         return(edge);
253 }
254
255 /**
256  * Change the out count
257  *
258  * @param tgt  the edge target
259  * @param kind the kind of the edge
260  */
261 static inline void edge_change_cnt(ir_node *tgt, ir_edge_kind_t kind, int ofs) {
262         irn_edge_info_t *info = _get_irn_edge_info(tgt, kind);
263         info->out_count += ofs;
264
265 #if 0
266         assert(info->out_count >= 0);
267         if (info->out_count == 0 && kind == EDGE_KIND_NORMAL) {
268                 /* tgt lost it's last user */
269                 int i;
270
271                 for (i = get_irn_arity(tgt) - 1; i >= -1; --i) {
272                         ir_node *prev = get_irn_n(tgt, i);
273
274                         edges_notify_edge(tgt, i, NULL, prev, current_ir_graph);
275                 }
276                 for (i = get_irn_deps(tgt) - 1; i >= 0; --i) {
277                         ir_node *prev = get_irn_dep(tgt, i);
278
279                         edges_notify_edge_kind(tgt, i, NULL, prev, EDGE_KIND_DEP, current_ir_graph);
280
281                 }
282         }
283 #endif
284 }
285
286 /**
287  * Verify the edge list of a node, ie. ensure it's a loop:
288  * head -> e_1 -> ... -> e_n -> head
289  */
290 static inline void vrfy_list_head(ir_node *irn, ir_edge_kind_t kind) {
291         int                    err       = 0;
292         int                    num       = 0;
293         pset                   *lh_set   = pset_new_ptr(16);
294         const struct list_head *head     = _get_irn_outs_head(irn, kind);
295         const struct list_head *pos;
296
297         list_for_each(pos, head) {
298                 if (pset_find_ptr(lh_set, pos)) {
299                         const ir_edge_t *edge = list_entry(pos, ir_edge_t, list);
300
301                         ir_fprintf(stderr, "EDGE Verifier: edge list broken (self loop not to head) for %+F:\n", irn);
302                         fprintf(stderr, "- at list entry %d\n", num);
303                         if (edge->invalid)
304                                 fprintf(stderr, "- edge(%ld) is invalid\n", edge_get_id(edge));
305                         if (edge->src)
306                                 ir_fprintf(stderr, "- edge(%ld) %+F(%d)\n", edge_get_id(edge), edge->src, edge->pos);
307                         err = 1;
308                         break;
309                 }
310                 num++;
311                 pset_insert_ptr(lh_set, pos);
312         }
313
314         del_pset(lh_set);
315
316         assert(err == 0);
317 }
318
319 /* The edge from (src, pos) -> old_tgt is redirected to tgt */
320 void edges_notify_edge_kind(ir_node *src, int pos, ir_node *tgt,
321                             ir_node *old_tgt, ir_edge_kind_t kind,
322                             ir_graph *irg)
323 {
324         const char      *msg = "";
325         irg_edge_info_t *info;
326         ir_edgeset_t    *edges;
327         ir_edge_t        templ;
328         ir_edge_t       *edge;
329
330         assert(edges_activated_kind(irg, kind));
331
332         /*
333          * Only do something, if the old and new target differ.
334          */
335         if (tgt == old_tgt)
336                 return;
337
338         info  = _get_irg_edge_info(irg, kind);
339         edges = &info->edges;
340
341         /* Initialize the edge template to search in the set. */
342         templ.src = src;
343         templ.pos = pos;
344
345         /*
346          * If the target is NULL, the edge shall be deleted.
347          */
348         if (tgt == NULL) {
349                 /* search the edge in the set. */
350                 edge = ir_edgeset_find(edges, &templ);
351
352                 /* mark the edge invalid if it was found */
353                 if (edge) {
354                         msg = "deleting";
355                         list_del(&edge->list);
356                         ir_edgeset_remove(edges, edge);
357                         list_add(&edge->list, &info->free_edges);
358                         edge->invalid = 1;
359                         edge->pos = -2;
360                         edge->src = NULL;
361 #ifdef DEBUG_libfirm
362                         edge->edge_nr = -1;
363 #endif /* DEBUG_libfirm */
364                         edge_change_cnt(old_tgt, kind, -1);
365                 } else {
366                         /* If the edge was not found issue a warning on the debug stream */
367                         msg = "edge to delete not found!\n";
368                 }
369         } else {
370                 /*
371                  * The target is not NULL and the old target differs
372                  * from the new target, the edge shall be moved (if the
373                  * old target was != NULL) or added (if the old target was
374                  * NULL).
375                  */
376                 struct list_head *head = _get_irn_outs_head(tgt, kind);
377
378                 assert(head->next && head->prev &&
379                                 "target list head must have been initialized");
380
381                 /* If the old target is not null, the edge is moved. */
382                 if (old_tgt) {
383                         edge = ir_edgeset_find(edges, &templ);
384                         assert(edge && "edge to redirect not found!");
385                         assert(! edge->invalid && "Invalid edge encountered");
386
387                         msg = "redirecting";
388
389                         list_move(&edge->list, head);
390                         edge_change_cnt(old_tgt, kind, -1);
391                 } else {
392                         /* The old target was NULL, thus, the edge is newly created. */
393                         ir_edge_t *new_edge;
394                         ir_edge_t *edge;
395
396                         if (list_empty(&info->free_edges)) {
397                                 edge = obstack_alloc(&info->edges_obst, EDGE_SIZE);
398                         } else {
399                                 edge = list_entry(info->free_edges.next, ir_edge_t, list);
400                                 list_del(&edge->list);
401                         }
402
403                         edge->src       = src;
404                         edge->pos       = pos;
405                         edge->invalid   = 0;
406                         edge->present   = 0;
407                         edge->kind      = kind;
408                         edge->list.next = NULL;
409                         edge->list.prev = NULL;
410                         memset(edge + 1, 0, edges_private_size);
411                         DEBUG_ONLY(edge->src_nr = get_irn_node_nr(src));
412
413                         new_edge = ir_edgeset_insert(edges, edge);
414                         if (new_edge != edge) {
415                                 panic("new edge exists already");
416                         }
417
418                         msg = "adding";
419                         list_add(&edge->list, head);
420                         DEBUG_ONLY(edge->edge_nr = ++last_edge_num);
421                 }
422
423                 edge_change_cnt(tgt, kind, +1);
424         } /* else */
425
426 #ifndef DEBUG_libfirm
427         /* verify list heads */
428         if (edges_dbg) {
429                 if (tgt)
430                         vrfy_list_head(tgt, kind);
431                 if (old_tgt)
432                         vrfy_list_head(old_tgt, kind);
433         }
434 #endif
435
436         DBG((dbg, LEVEL_5, "announce out edge: %+F %d-> %+F(%+F): %s\n", src, pos, tgt, old_tgt, msg));
437 }
438
439 void edges_notify_edge(ir_node *src, int pos, ir_node *tgt, ir_node *old_tgt, ir_graph *irg)
440 {
441         if (edges_activated_kind(irg, EDGE_KIND_NORMAL)) {
442                 edges_notify_edge_kind(src, pos, tgt, old_tgt, EDGE_KIND_NORMAL, irg);
443         }
444
445         if (edges_activated_kind(irg, EDGE_KIND_BLOCK) && is_Block(src)) {
446                 if (pos == -1) {
447                         /* a MacroBlock edge: ignore it here */
448                 } else {
449                         ir_node *bl_old = old_tgt ? get_nodes_block(skip_Proj(old_tgt)) : NULL;
450                         ir_node *bl_tgt = NULL;
451
452                         if (tgt)
453                                 bl_tgt = is_Bad(tgt) ? tgt : get_nodes_block(skip_Proj(tgt));
454
455                         edges_notify_edge_kind(src, pos, bl_tgt, bl_old, EDGE_KIND_BLOCK, irg);
456                 }
457         }
458 }
459
460 /**
461  * Delete all in edges of a given kind from the node old.
462  *
463  * @param old   the node
464  * @param kind  the kind of edges to remove
465  * @param irg   the irg of the old node
466  */
467 static void edges_node_deleted_kind(ir_node *old, ir_edge_kind_t kind, ir_graph *irg)
468 {
469         int i, n;
470
471         if (!edges_activated_kind(irg, kind))
472                 return;
473
474         DBG((dbg, LEVEL_5, "node deleted (kind: %s): %+F\n", get_kind_str(kind), old));
475
476         foreach_tgt(old, i, n, kind) {
477                 ir_node *old_tgt = get_n(old, i, kind);
478                 edges_notify_edge_kind(old, i, NULL, old_tgt, kind, irg);
479         }
480 }
481
482 /**
483  * A node might be revivaled by CSE. Assure its edges.
484  *
485  * @param irn   the node
486  * @param kind  the kind of edges to remove
487  * @param irg   the irg of the old node
488  */
489 static void edges_node_revival_kind(ir_node *irn, ir_edge_kind_t kind, ir_graph *irg)
490 {
491         irn_edge_info_t *info;
492         int             i, n;
493
494         if (!edges_activated_kind(irg, kind))
495                 return;
496
497         info = _get_irn_edge_info(irn, kind);
498         if (info->edges_built)
499                 return;
500
501         DBG((dbg, LEVEL_5, "node revivaled (kind: %s): %+F\n", get_kind_str(kind), irn));
502
503         foreach_tgt(irn, i, n, kind) {
504                 ir_node *tgt = get_n(irn, i, kind);
505                 edges_notify_edge_kind(irn, i, tgt, NULL, kind, irg);
506         }
507         info->edges_built = 1;
508 }
509
510 struct build_walker {
511         ir_graph       *irg;
512         ir_edge_kind_t kind;
513         bitset_t       *reachable;
514         unsigned       problem_found;
515 };
516
517 /**
518  * Post-Walker: notify all edges
519  */
520 static void build_edges_walker(ir_node *irn, void *data) {
521         struct build_walker   *w = data;
522         int                   i, n;
523         ir_edge_kind_t        kind = w->kind;
524         ir_graph              *irg = w->irg;
525         get_edge_src_n_func_t *get_n;
526
527         get_n = edge_kind_info[kind].get_n;
528         foreach_tgt(irn, i, n, kind) {
529                 ir_node *pred = get_n(irn, i, kind);
530                 edges_notify_edge_kind(irn, i, pred, NULL, kind, irg);
531         }
532         _get_irn_edge_info(irn, kind)->edges_built = 1;
533 }
534
535 /**
536  * Pre-Walker: initializes the list-heads and set the out-count
537  * of all nodes to 0.
538  */
539 static void init_lh_walker(ir_node *irn, void *data) {
540         struct build_walker *w   = data;
541         ir_edge_kind_t      kind = w->kind;
542         list_head           *head = _get_irn_outs_head(irn, kind);
543         INIT_LIST_HEAD(head);
544         _get_irn_edge_info(irn, kind)->edges_built = 0;
545         _get_irn_edge_info(irn, kind)->out_count   = 0;
546 }
547
548 /**
549  * Pre-Walker: initializes the list-heads and set the out-count
550  * of all nodes to 0.
551  *
552  * Additionally touches DEP nodes, as they might be DEAD.
553  * THIS IS UGLY, but I don't find a better way until we
554  *
555  * a) ensure that dead nodes are not used as input
556  * b) it might be sufficient to add those stupid NO_REG nodes
557  * to the anchor
558  */
559 static void init_lh_walker_dep(ir_node *irn, void *data) {
560         struct build_walker *w   = data;
561         ir_edge_kind_t      kind = w->kind;
562         list_head           *head = _get_irn_outs_head(irn, kind);
563         int                 i;
564
565         INIT_LIST_HEAD(head);
566         _get_irn_edge_info(irn, kind)->edges_built = 0;
567         _get_irn_edge_info(irn, kind)->out_count   = 0;
568
569         for (i = get_irn_deps(irn) - 1; i >= 0; --i) {
570                 ir_node *dep = get_irn_dep(irn, i);
571
572                 head = _get_irn_outs_head(dep, kind);
573
574                 INIT_LIST_HEAD(head);
575                 _get_irn_edge_info(dep, kind)->edges_built = 0;
576                 _get_irn_edge_info(dep, kind)->out_count   = 0;
577         }
578 }
579
580 typedef struct visitor_info_t {
581         irg_walk_func *visit;
582         void *data;
583 } visitor_info_t;
584
585 /**
586  * Visitor: initializes the list-heads and set the out-count
587  * of all nodes to 0 of nodes that are not seen so far.
588  */
589 static void visitor(ir_node *irn, void *data) {
590         visitor_info_t *info = data;
591
592         if (!irn_visited_else_mark(irn)) {
593                 info->visit(irn, info->data);
594         }
595 }
596
597 /*
598  * Build the initial edge set.
599  * Beware, this is not a simple task because it suffers from two
600  * difficulties:
601  * - the anchor set allows access to Nodes that may not be reachable from
602  *   the End node
603  * - the identities add nodes to the "root set" that are not yet reachable
604  *   from End. However, after some transformations, the CSE may revival these
605  *   nodes
606  *
607  * These problems can be fixed using different strategies:
608  * - Add an age flag to every node. Whenever the edge of a node is older
609  *   then the current edge, invalidate the edges of this node.
610  *   While this would help for revivaled nodes, it increases memory and runtime.
611  * - Delete the identities set.
612  *   Solves the revival problem, but may increase the memory consumption, as
613  *   nodes cannot be revivaled at all.
614  * - Manually iterate over the identities root set. This did not consume more memory
615  *   but increase the computation time because the |identities| >= |V|
616  *
617  * Currently, we use the last option.
618  */
619 void edges_activate_kind(ir_graph *irg, ir_edge_kind_t kind)
620 {
621         struct build_walker w;
622         irg_edge_info_t     *info = _get_irg_edge_info(irg, kind);
623         visitor_info_t      visit;
624
625         w.irg  = irg;
626         w.kind = kind;
627
628         visit.data = &w;
629
630         assert(!info->activated);
631
632         info->activated = 1;
633         edges_init_graph_kind(irg, kind);
634         if (kind == EDGE_KIND_DEP) {
635                 irg_walk_anchors(irg, init_lh_walker_dep, NULL, &w);
636                 /* Argh: Dep nodes might be dead, so we MUST visit identities first */
637                 visit.visit = init_lh_walker_dep;
638                 visit_all_identities(irg, visitor, &visit);
639                 irg_walk_anchors(irg, NULL, build_edges_walker, &w);
640         } else {
641                 irg_walk_anchors(irg, init_lh_walker, build_edges_walker, &w);
642                 visit.visit = init_lh_walker;
643                 visit_all_identities(irg, visitor, &visit);
644         }
645 }
646
647 void edges_deactivate_kind(ir_graph *irg, ir_edge_kind_t kind)
648 {
649         irg_edge_info_t *info = _get_irg_edge_info(irg, kind);
650
651         info->activated = 0;
652         if (info->allocated) {
653                 obstack_free(&info->edges_obst, NULL);
654                 ir_edgeset_destroy(&info->edges);
655                 info->allocated = 0;
656         }
657 }
658
659 int (edges_activated_kind)(const ir_graph *irg, ir_edge_kind_t kind)
660 {
661         return _edges_activated_kind(irg, kind);
662 }
663
664
665 /**
666  * Reroute all use-edges from a node to another.
667  * @param from The node whose use-edges shall be withdrawn.
668  * @param to   The node to which all the use-edges of @p from shall be
669  *             sent to.
670  * @param irg  The graph.
671  */
672 void edges_reroute_kind(ir_node *from, ir_node *to, ir_edge_kind_t kind, ir_graph *irg)
673 {
674         set_edge_func_t *set_edge = edge_kind_info[kind].set_edge;
675
676         if(set_edge && edges_activated_kind(irg, kind)) {
677                 struct list_head *head = _get_irn_outs_head(from, kind);
678
679                 DBG((dbg, LEVEL_5, "reroute from %+F to %+F\n", from, to));
680
681                 while (head != head->next) {
682                         ir_edge_t *edge = list_entry(head->next, ir_edge_t, list);
683                         assert(edge->pos >= -1);
684                         set_edge(edge->src, edge->pos, to);
685                 }
686         }
687 }
688
689 static void verify_set_presence(ir_node *irn, void *data)
690 {
691         struct build_walker *w     = data;
692         ir_edgeset_t        *edges = &_get_irg_edge_info(w->irg, w->kind)->edges;
693         int i, n;
694
695         foreach_tgt(irn, i, n, w->kind) {
696                 ir_edge_t templ, *e;
697
698                 templ.src = irn;
699                 templ.pos = i;
700
701                 e = ir_edgeset_find(edges, &templ);
702                 if(e != NULL) {
703                         e->present = 1;
704                 } else {
705                         w->problem_found = 1;
706 #if 0
707                         ir_fprintf(stderr, "Edge Verifier: edge %+F,%d -> %+F (kind: \"%s\") is missing\n",
708                                 irn, i, get_n(irn, i, w->kind), get_kind_str(w->kind));
709 #endif
710                 }
711         }
712 }
713
714 static void verify_list_presence(ir_node *irn, void *data)
715 {
716         struct build_walker *w = data;
717         const ir_edge_t     *e;
718
719         bitset_set(w->reachable, get_irn_idx(irn));
720
721         /* check list heads */
722         vrfy_list_head(irn, w->kind);
723
724         foreach_out_edge_kind(irn, e, w->kind) {
725                 ir_node *tgt;
726
727                 if (w->kind == EDGE_KIND_NORMAL && get_irn_arity(e->src) <= e->pos) {
728                         w->problem_found = 1;
729 #if 0
730                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F -> %+F recorded at src position %d, but src has arity %d\n",
731                                 edge_get_id(e), e->src, irn, e->pos, get_irn_arity(e->src));
732 #endif
733                         continue;
734                 }
735
736                 tgt = get_n(e->src, e->pos, w->kind);
737
738                 if (irn != tgt) {
739                         w->problem_found = 1;
740 #if 0
741                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F,%d (kind \"%s\") is no out edge of %+F but of %+F\n",
742                                 edge_get_id(e), e->src, e->pos, get_kind_str(w->kind), irn, tgt);
743 #endif
744                 }
745         }
746 }
747
748 int edges_verify_kind(ir_graph *irg, ir_edge_kind_t kind)
749 {
750         struct build_walker w;
751         ir_edgeset_t        *edges = &_get_irg_edge_info(irg, kind)->edges;
752         ir_edge_t           *e;
753         ir_edgeset_iterator_t  iter;
754
755         w.irg           = irg;
756         w.kind          = kind;
757         w.reachable     = bitset_alloca(get_irg_last_idx(irg));
758         w.problem_found = 0;
759
760         /* Clear the present bit in all edges available. */
761         foreach_ir_edgeset(edges, e, iter) {
762                 e->present = 0;
763         }
764
765         irg_walk_graph(irg, verify_set_presence, verify_list_presence, &w);
766
767         /*
768          * Dump all edges which are not invalid and not present.
769          * These edges are superfluous and their presence in the
770          * edge set is wrong.
771          */
772         foreach_ir_edgeset(edges, e, iter) {
773                 if (! e->invalid && ! e->present && bitset_is_set(w.reachable, get_irn_idx(e->src))) {
774                         w.problem_found = 1;
775                         ir_fprintf(stderr, "Edge Verifier: edge(%ld) %+F,%d is superfluous\n", edge_get_id(e), e->src, e->pos);
776                 }
777         }
778
779         return w.problem_found;
780 }
781
782 #define IGNORE_NODE(irn) (is_Bad((irn)) || is_Block((irn)))
783
784 /**
785  * Clear link field of all nodes.
786  */
787 static void clear_links(ir_node *irn, void *env) {
788         struct build_walker *w  = env;
789         bitset_t            *bs;
790
791         if (IGNORE_NODE(irn)) {
792                 set_irn_link(irn, NULL);
793                 return;
794         }
795
796         bs = bitset_malloc(get_irg_last_idx(w->irg));
797         set_irn_link(irn, bs);
798 }
799
800 /**
801  * Increases count (stored in link field) for all operands of a node.
802  */
803 static void count_user(ir_node *irn, void *env) {
804         int i;
805         int first;
806         (void) env;
807
808         first = -1;
809         for (i = get_irn_arity(irn) - 1; i >= first; --i) {
810                 ir_node  *op = get_irn_n(irn, i);
811                 bitset_t *bs = get_irn_link(op);
812
813                 if (bs)
814                         bitset_set(bs, get_irn_idx(irn));
815         }
816 }
817
818 /**
819  * Verifies if collected count, number of edges in list and stored edge count are in sync.
820  */
821 static void verify_edge_counter(ir_node *irn, void *env) {
822         struct build_walker    *w = env;
823         bitset_t               *bs;
824         int                    list_cnt;
825         int                    ref_cnt;
826         int                    edge_cnt;
827         unsigned long          idx;
828         const struct list_head *head;
829         const struct list_head *pos;
830
831         if (IGNORE_NODE(irn))
832                 return;
833
834         bs       = get_irn_link(irn);
835         list_cnt = 0;
836         ref_cnt  = 0;
837         edge_cnt = _get_irn_edge_info(irn, EDGE_KIND_NORMAL)->out_count;
838         head     = _get_irn_outs_head(irn, EDGE_KIND_NORMAL);
839
840         /* We can iterate safely here, list heads have already been verified. */
841         list_for_each(pos, head) {
842                 ++list_cnt;
843         }
844
845         /* check all nodes that reference us and count edges that point number
846          * of ins that actually point to us */
847         ref_cnt = 0;
848         bitset_foreach(bs, idx) {
849                 int i, arity;
850                 ir_node *src = get_idx_irn(w->irg, idx);
851
852                 arity = get_irn_arity(src);
853                 for (i = 0; i < arity; ++i) {
854                         ir_node *in = get_irn_n(src, i);
855                         if (in == irn)
856                                 ++ref_cnt;
857                 }
858         }
859
860         if (edge_cnt != list_cnt) {
861                 w->problem_found = 1;
862                 ir_fprintf(stderr, "Edge Verifier: edge count is %d, but %d edge(s) are recorded in list at %+F\n",
863                         edge_cnt, list_cnt, irn);
864         }
865
866         if (ref_cnt != list_cnt) {
867                 w->problem_found = 1;
868                 ir_fprintf(stderr, "Edge Verifier: %+F reachable by %d node(s), but the list contains %d edge(s)\n",
869                         irn, ref_cnt, list_cnt);
870
871                 /* Matze: buggy if a node has multiple ins pointing at irn */
872 #if 0
873                 list_for_each(pos, head) {
874                         ir_edge_t *edge = list_entry(pos, ir_edge_t, list);
875                         bitset_flip(bs, get_irn_idx(edge->src));
876                 }
877
878                 if (ref_cnt < list_cnt)
879                         fprintf(stderr,"               following nodes are recorded in list, but not as user:\n");
880                 else
881                         fprintf(stderr,"               following nodes are user, but not recorded in list:\n");
882
883                 fprintf(stderr,"              ");
884                 bitset_foreach(bs, idx) {
885                         ir_node *src = get_idx_irn(w->irg, idx);
886                         ir_fprintf(stderr, " %+F", src);
887                 }
888                 fprintf(stderr, "\n");
889 #endif
890         }
891
892         bitset_free(bs);
893 }
894
895 /**
896  * Verifies the out edges of an irg.
897  */
898 int edges_verify(ir_graph *irg) {
899         struct build_walker w;
900         int    problem_found = 0;
901
902         /* verify normal edges only */
903         problem_found  = edges_verify_kind(irg, EDGE_KIND_NORMAL);
904
905         w.irg           = irg;
906         w.kind          = EDGE_KIND_NORMAL;
907         w.problem_found = 0;
908
909         /* verify counter */
910         irg_walk_anchors(irg, clear_links, count_user, &w);
911         irg_walk_anchors(irg, NULL, verify_edge_counter, &w);
912
913         return problem_found ? 1 : w.problem_found;
914 }
915
916 struct pass_t {
917         ir_graph_pass_t pass;
918         unsigned        assert_on_problem;
919 };
920
921 /**
922  * Wrapper to edges_verify to be run as an ir_graph pass.
923  */
924 static int edges_verify_wrapper(ir_graph *irg, void *context) {
925         struct pass_t *pass = context;
926         int problems_found = edges_verify(irg);
927         /* do NOT rerun the pass if verify is ok :-) */
928         assert(problems_found && pass->assert_on_problem);
929         return 0;
930 }
931
932 /* Creates an ir_graph pass for edges_verify(). */
933 ir_graph_pass_t *irg_verify_edges_pass(const char *name, unsigned assert_on_problem) {
934         struct pass_t *pass = XMALLOCZ(struct pass_t);
935
936         def_graph_pass_constructor(
937                 &pass->pass, name ? name : "edges_verify", edges_verify_wrapper);
938
939         /* neither dump nor verify */
940         pass->pass.dump_irg   = (DUMP_ON_IRG_FUNC)ir_prog_no_dump;
941         pass->pass.verify_irg = (RUN_ON_IRG_FUNC)ir_prog_no_verify;
942
943         pass->assert_on_problem = assert_on_problem;
944         return &pass->pass;
945 }
946
947 void init_edges(void) {
948         FIRM_DBG_REGISTER(dbg, DBG_EDGES);
949         /* firm_dbg_set_mask(dbg, -1); */
950 }
951
952 void edges_init_dbg(int do_dbg) {
953         edges_dbg = do_dbg;
954 }
955
956 void edges_activate(ir_graph *irg) {
957         edges_activate_kind(irg, EDGE_KIND_NORMAL);
958         edges_activate_kind(irg, EDGE_KIND_BLOCK);
959         if (get_irg_phase_state(irg) == phase_backend)
960                 edges_activate_kind(irg, EDGE_KIND_DEP);
961 }
962
963 void edges_deactivate(ir_graph *irg) {
964         if (get_irg_phase_state(irg) == phase_backend)
965                 edges_deactivate_kind(irg, EDGE_KIND_DEP);
966         edges_deactivate_kind(irg, EDGE_KIND_BLOCK);
967         edges_deactivate_kind(irg, EDGE_KIND_NORMAL);
968 }
969
970 int edges_assure(ir_graph *irg)
971 {
972         int activated = 0;
973
974         if (edges_activated_kind(irg, EDGE_KIND_BLOCK)) {
975                 activated = 1;
976         } else {
977                 edges_activate_kind(irg, EDGE_KIND_BLOCK);
978         }
979         if (edges_activated_kind(irg, EDGE_KIND_NORMAL)) {
980                 activated = 1;
981         } else {
982                 edges_activate_kind(irg, EDGE_KIND_NORMAL);
983         }
984
985         return activated;
986 }
987
988 int edges_assure_kind(ir_graph *irg, ir_edge_kind_t kind) {
989         int activated = edges_activated_kind(irg, kind);
990
991         if (!activated)
992                 edges_activate_kind(irg, kind);
993
994         return activated;
995 }
996
997 void edges_node_deleted(ir_node *irn, ir_graph *irg) {
998         edges_node_deleted_kind(irn, EDGE_KIND_NORMAL, irg);
999         edges_node_deleted_kind(irn, EDGE_KIND_BLOCK, irg);
1000 }
1001
1002 void edges_node_revival(ir_node *irn, ir_graph *irg) {
1003         edges_node_revival_kind(irn, EDGE_KIND_NORMAL, irg);
1004         edges_node_revival_kind(irn, EDGE_KIND_BLOCK, irg);
1005 }
1006
1007 const ir_edge_t *(get_irn_out_edge_first_kind)(const ir_node *irn, ir_edge_kind_t kind) {
1008         return _get_irn_out_edge_first_kind(irn, kind);
1009 }
1010
1011 const ir_edge_t *(get_irn_out_edge_next)(const ir_node *irn, const ir_edge_t *last) {
1012         return _get_irn_out_edge_next(irn, last);
1013 }
1014
1015 ir_node *(get_edge_src_irn)(const ir_edge_t *edge) {
1016         return _get_edge_src_irn(edge);
1017 }
1018
1019 int (get_edge_src_pos)(const ir_edge_t *edge) {
1020         return _get_edge_src_pos(edge);
1021 }
1022
1023 int (get_irn_n_edges_kind)(const ir_node *irn, ir_edge_kind_t kind) {
1024         return _get_irn_n_edges_kind(irn, kind);
1025 }
1026
1027 void dump_all_out_edges(ir_node *irn) {
1028         int i;
1029         for (i = 0; i < EDGE_KIND_LAST; ++i) {
1030                 const ir_edge_t *edge;
1031
1032                 printf("kind \"%s\"\n", get_kind_str(i));
1033                 foreach_out_edge_kind(irn, edge, i) {
1034                         ir_printf("\t%+F(%d)\n", edge->src, edge->pos);
1035                 }
1036         }
1037 }
1038
1039 static void irg_block_edges_walk2(ir_node *bl,
1040                                 irg_walk_func *pre, irg_walk_func *post,
1041                                 void *env) {
1042         const ir_edge_t *edge, *next;
1043
1044         if (!Block_block_visited(bl)) {
1045                 mark_Block_block_visited(bl);
1046
1047                 if (pre)
1048                         pre(bl, env);
1049
1050                 foreach_out_edge_kind_safe(bl, edge, next, EDGE_KIND_BLOCK) {
1051                         /* find the corresponding successor block. */
1052                         ir_node *pred = get_edge_src_irn(edge);
1053                         irg_block_edges_walk2(pred, pre, post, env);
1054                 }
1055
1056                 if (post)
1057                         post(bl, env);
1058         }
1059 }
1060
1061 void irg_block_edges_walk(ir_node *node,
1062                           irg_walk_func *pre, irg_walk_func *post,
1063                           void *env) {
1064
1065         assert(edges_activated(current_ir_graph));
1066         assert(is_Block(node));
1067
1068         ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_VISITED);
1069
1070         inc_irg_block_visited(current_ir_graph);
1071         irg_block_edges_walk2(node, pre, post, env);
1072
1073         ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_VISITED);
1074 }