Remove duplicate implementation of foreach_set().
[libfirm] / ir / ana / irlivechk.c
1 /*
2  * Copyright (C) 1995-2007 Inria Rhone-Alpes.  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    livechk.c
22  * @date    21.04.2007
23  * @author  Sebastian Hack
24  * @brief
25  *
26  * Liveness checks as developed by Benoit Boissinot, Fabrice Rastello and myself.
27  *
28  * The speciality here is, that nothing has to be recomputed if new nodes are created
29  * or old ones deleted.
30  *
31  * This algo has one core routine check_live_end_internal() which performs the liveness check.
32  * It only relies on the precomputation done in the constructor, which in turn needs:
33  * - out edges
34  * - the dominance tree
35  * - data obtained from a depth-first-search
36  *
37  * The precomputation remains valid as long as the CFG is not altered.
38  */
39 #include <config.h>
40
41 #include <stdio.h>
42
43 #include "irgraph_t.h"
44 #include "irnode_t.h"
45 #include "irnodemap.h"
46 #include "iredges_t.h"
47
48 #include "irprintf.h"
49 #include "irdom.h"
50 #include "irdump.h"
51
52 #include "dfs_t.h"
53 #include "bitset.h"
54 #include "util.h"
55
56 #include "irlivechk.h"
57
58 #include "statev.h"
59
60 typedef struct bl_info_t {
61         const ir_node *block;      /**< The block. */
62
63         int be_tgt_calc : 1;
64         int id : 31;               /**< a tight number for the block.
65                                                                  we're just reusing the pre num from
66                                                                  the DFS. */
67         bitset_t *red_reachable;   /**< Holds all id's if blocks reachable
68                                                                  in the CFG modulo back edges. */
69
70         bitset_t *be_tgt_reach;    /**< target blocks of back edges whose
71                                                                  sources are reachable from this block
72                                                                  in the reduced graph. */
73 } bl_info_t;
74
75 struct lv_chk_t {
76         ir_nodemap     block_infos;
77         struct obstack obst;
78         dfs_t         *dfs;
79         int            n_blocks;
80         bitset_t      *back_edge_src;
81         bitset_t      *back_edge_tgt;
82         bl_info_t    **map;
83         DEBUG_ONLY(firm_dbg_module_t *dbg;)
84 };
85
86 static bl_info_t *get_block_info(lv_chk_t *lv, const ir_node *block)
87 {
88         bl_info_t *info = ir_nodemap_get(bl_info_t, &lv->block_infos, block);
89         if (info == NULL) {
90                 info                = OALLOC(&lv->obst, bl_info_t);
91                 info->id            = get_Block_dom_tree_pre_num(block);
92                 info->block         = block;
93                 info->red_reachable = bitset_obstack_alloc(&lv->obst, lv->n_blocks);
94                 info->be_tgt_reach  = bitset_obstack_alloc(&lv->obst, lv->n_blocks);
95                 info->be_tgt_calc   = 0;
96                 ir_nodemap_insert(&lv->block_infos, block, info);
97         }
98         return info;
99 }
100
101 /**
102  * Filter function to select all nodes for which liveness is computed.
103  * @param irn A node.
104  * @return    1 if the node shall be considered in liveness, 0 if not.
105  */
106 static inline int is_liveness_node(const ir_node *irn)
107 {
108         switch (get_irn_opcode(irn)) {
109         case iro_Block:
110         case iro_Bad:
111         case iro_End:
112         case iro_Anchor:
113                 return 0;
114         default:
115                 break;
116         }
117
118         return 1;
119 }
120
121 /**
122  * Compute the transitive closure on the reduced graph.
123  * The reduced graph is the original graph without back edges.
124  * Since that is a DAG, a reverse post order of the graph gives a toposort
125  * which is ideally suited to compute the transitive closure.
126  * Note also, that the DFS tree of the reduced graph is the same than the one
127  * of the original graph. This saves us computing a new reverse post order.
128  * We also can re-use the DFS tree of the original graph.
129  */
130 static void red_trans_closure(lv_chk_t *lv)
131 {
132         int i, n;
133
134         for (i = 0, n = dfs_get_n_nodes(lv->dfs); i < n; ++i) {
135                 const ir_node *bl = (const ir_node*) dfs_get_post_num_node(lv->dfs, i);
136                 bl_info_t *bi = get_block_info(lv, bl);
137
138                 const ir_edge_t *edge;
139
140                 bitset_set(bi->red_reachable, bi->id);
141                 foreach_block_succ (bl, edge) {
142                         ir_node *succ = get_edge_src_irn(edge);
143                         bl_info_t *si = get_block_info(lv, succ);
144                         dfs_edge_kind_t kind = dfs_get_edge_kind(lv->dfs, bl, succ);
145
146                         /*
147                          * if the successor is no back edge, include all reachable
148                          * blocks from there into the reachable set of the current node
149                          */
150                         if (kind != DFS_EDGE_BACK) {
151                                 assert(dfs_get_post_num(lv->dfs, bl) > dfs_get_post_num(lv->dfs, succ));
152                                 bitset_or(bi->red_reachable, si->red_reachable);
153                         }
154
155                         /* mark the block as a back edge src and succ as back edge tgt. */
156                         else {
157                                 bitset_set(lv->back_edge_src, bi->id);
158                                 bitset_set(lv->back_edge_tgt, si->id);
159                         }
160                 }
161
162         }
163
164 }
165
166 static void compute_back_edge_chain(lv_chk_t *lv, const ir_node *bl)
167 {
168         bitset_t *tmp = bitset_alloca(lv->n_blocks);
169         bl_info_t *bi = get_block_info(lv, bl);
170
171         size_t elm;
172
173         DBG((lv->dbg, LEVEL_2, "computing T_%d\n", bi->id));
174
175         /* put all back edge sources reachable (reduced) from here in tmp */
176         bitset_copy(tmp, bi->red_reachable);
177         bitset_set(tmp, bi->id);
178         bitset_and(tmp, lv->back_edge_src);
179         bi->be_tgt_calc = 1;
180
181         DBG((lv->dbg, LEVEL_2, "\treachable be src: %B\n", tmp));
182
183         /* iterate over them ... */
184         bitset_foreach(tmp, elm) {
185                 bl_info_t *si = lv->map[elm];
186                 const ir_edge_t *edge;
187
188                 /* and find back edge targets which are not reduced reachable from bl */
189                 foreach_block_succ (si->block, edge) {
190                         ir_node *tgt         = get_edge_src_irn(edge);
191                         bl_info_t *ti        = get_block_info(lv, tgt);
192                         dfs_edge_kind_t kind = dfs_get_edge_kind(lv->dfs, si->block, tgt);
193
194                         if (kind == DFS_EDGE_BACK && !bitset_is_set(bi->red_reachable, ti->id)) {
195                                 if (!ti->be_tgt_calc)
196                                         compute_back_edge_chain(lv, tgt);
197                                 bitset_set(bi->be_tgt_reach, ti->id);
198                                 bitset_or(bi->be_tgt_reach, ti->be_tgt_reach);
199                         }
200                 }
201                 bitset_clear(bi->be_tgt_reach, bi->id);
202         }
203 }
204
205
206 static inline void compute_back_edge_chains(lv_chk_t *lv)
207 {
208         size_t elm;
209         int i, n;
210
211         DBG((lv->dbg, LEVEL_2, "back edge sources: %B\n", lv->back_edge_src));
212         bitset_foreach(lv->back_edge_src, elm) {
213                 compute_back_edge_chain(lv, lv->map[elm]->block);
214         }
215
216         for (i = 0, n = dfs_get_n_nodes(lv->dfs); i < n; ++i) {
217                 const ir_node *bl = (const ir_node*) dfs_get_post_num_node(lv->dfs, i);
218                 bl_info_t *bi     = get_block_info(lv, bl);
219
220                 const ir_edge_t *edge;
221
222                 if (!bitset_is_set(lv->back_edge_tgt, bi->id)) {
223                         foreach_block_succ (bl, edge) {
224                                 ir_node *succ = get_edge_src_irn(edge);
225                                 bl_info_t *si = get_block_info(lv, succ);
226                                 dfs_edge_kind_t kind = dfs_get_edge_kind(lv->dfs, bl, succ);
227
228                                 if (kind != DFS_EDGE_BACK) {
229                                         assert(dfs_get_post_num(lv->dfs, bl) > dfs_get_post_num(lv->dfs, succ));
230                                         bitset_or(bi->be_tgt_reach, si->be_tgt_reach);
231                                 }
232                         }
233                 }
234         }
235
236         for (i = 0, n = dfs_get_n_nodes(lv->dfs); i < n; ++i) {
237                 const ir_node *bl = (const ir_node*) dfs_get_post_num_node(lv->dfs, i);
238                 bl_info_t *bi     = get_block_info(lv, bl);
239                 bitset_set(bi->be_tgt_reach, bi->id);
240         }
241 }
242
243 lv_chk_t *lv_chk_new(ir_graph *irg)
244 {
245         lv_chk_t *res = XMALLOC(lv_chk_t);
246         int i;
247
248         assure_doms(irg);
249
250         stat_ev_tim_push();
251         ir_nodemap_init(&res->block_infos, irg);
252         obstack_init(&res->obst);
253
254         FIRM_DBG_REGISTER(res->dbg, "ir.ana.lvchk");
255
256         res->dfs           = dfs_new(&absgraph_irg_cfg_succ, irg);
257         res->n_blocks      = dfs_get_n_nodes(res->dfs);
258         res->back_edge_src = bitset_obstack_alloc(&res->obst, res->n_blocks);
259         res->back_edge_tgt = bitset_obstack_alloc(&res->obst, res->n_blocks);
260         res->map           = OALLOCNZ(&res->obst, bl_info_t*, res->n_blocks);
261
262         /* fill the map which maps pre_num to block infos */
263         for (i = res->n_blocks - 1; i >= 0; --i) {
264                 ir_node *irn  = (ir_node *) dfs_get_pre_num_node(res->dfs, i);
265                 bl_info_t *bi = get_block_info(res, irn);
266                 assert(bi->id < res->n_blocks);
267                 assert(res->map[bi->id] == NULL);
268                 res->map[bi->id] = bi;
269         }
270
271         /* first of all, compute the transitive closure of the CFG *without* back edges */
272         red_trans_closure(res);
273
274         /* compute back edge chains */
275         compute_back_edge_chains(res);
276
277 #ifndef NDEBUG
278         DBG((res->dbg, LEVEL_1, "liveness chk in %+F\n", irg));
279         for (i = res->n_blocks - 1; i >= 0; --i) {
280                 const ir_node *irn = (const ir_node*) dfs_get_pre_num_node(res->dfs, i);
281                 bl_info_t *bi      = get_block_info(res, irn);
282                 DBG((res->dbg, LEVEL_1, "lv_chk for %d -> %+F\n", i, irn));
283                 DBG((res->dbg, LEVEL_1, "\tred reach: %B\n", bi->red_reachable));
284                 DBG((res->dbg, LEVEL_1, "\ttgt reach: %B\n", bi->be_tgt_reach));
285         }
286 #endif
287
288         DBG((res->dbg, LEVEL_1, "back edge src: %B\n", res->back_edge_src));
289         DBG((res->dbg, LEVEL_1, "back edge tgt: %B\n", res->back_edge_tgt));
290
291         stat_ev_tim_pop("lv_chk_cons_time");
292         return res;
293 }
294
295 void lv_chk_free(lv_chk_t *lv)
296 {
297         dfs_free(lv->dfs);
298         obstack_free(&lv->obst, NULL);
299         ir_nodemap_destroy(&lv->block_infos);
300         xfree(lv);
301 }
302
303 unsigned lv_chk_bl_xxx(lv_chk_t *lv, const ir_node *bl, const ir_node *var)
304 {
305         int res  = 0;
306         ir_node *def_bl;
307         stat_ev_cnt_decl(uses);
308         stat_ev_cnt_decl(iter);
309
310         assert(is_Block(bl) && "can only check for liveness in a block");
311
312         /* If the variable ist no liveness related var, bail out. */
313         if (!is_liveness_node(var))
314                 return 0;
315
316         stat_ev_ctx_push_fmt("lv_chk", "%u", get_irn_idx(var));
317         stat_ev_tim_push();
318
319         /* If there is no dominance relation, go out, too */
320         def_bl = get_nodes_block(var);
321         if (!block_dominates(def_bl, bl)) {
322                 stat_ev("lv_chk_no_dom");
323                 goto end;
324         }
325
326         /*
327          * If the block in question is the same as the definition block,
328          * the algorithm is simple. Just check for uses not inside this block.
329          */
330         if (def_bl == bl) {
331                 const ir_edge_t *edge;
332
333                 stat_ev("lv_chk_def_block");
334                 DBG((lv->dbg, LEVEL_2, "lv check same block %+F in %+F\n", var, bl));
335                 foreach_out_edge (var, edge) {
336                         ir_node *use    = get_edge_src_irn(edge);
337                         ir_node *use_bl;
338
339                         if (!is_liveness_node(use))
340                                 continue;
341
342                         stat_ev_cnt_inc(uses);
343                         use_bl = get_nodes_block(use);
344                         if (is_Phi(use)) {
345                                 int pos = get_edge_src_pos(edge);
346                                 use_bl  = get_Block_cfgpred_block(use_bl, pos);
347
348                                 if (use_bl == bl) {
349                                         DBG((lv->dbg, LEVEL_2, "\tphi %+F in succ %+F,%d -> live end\n", use, use_bl, pos));
350                                         res |= lv_chk_state_end;
351                                 }
352                         }
353
354                         if (use_bl != def_bl) {
355                                 res = lv_chk_state_end | lv_chk_state_out;
356                                 goto end;
357                         }
358                 }
359
360                 goto end;
361         }
362
363         /*
364          * this is the more complicated case.
365          * We try to gather as much information as possible during looking
366          * at the uses.
367          *
368          * Note that we know for sure that bl != def_bl. That is sometimes
369          * silently exploited below.
370          */
371         else {
372                 bl_info_t *def = get_block_info(lv, def_bl);
373                 bl_info_t *bli = get_block_info(lv, bl);
374                 bitset_t *uses = bitset_alloca(lv->n_blocks);
375                 bitset_t *Tq;
376
377                 size_t i;
378                 unsigned min_dom, max_dom;
379                 const ir_edge_t *edge;
380
381                 /* if the block has no DFS info, it cannot be reached.
382                  * This can happen in functions with endless loops.
383                  * we then go out, since nothing is live there.
384                  *
385                  * TODO: Is that right?
386                  */
387                 if (!bli)
388                         goto end;
389
390                 (void) def;
391                 DBG((lv->dbg, LEVEL_2, "lv check %+F (def in %+F #%d) in different block %+F #%d\n",
392                                         var, def_bl, def->id, bl, bli->id));
393
394                 foreach_out_edge (var, edge) {
395                         ir_node *user = get_edge_src_irn(edge);
396                         int mask      = lv_chk_state_in;
397
398                         ir_node *use_bl;
399                         bl_info_t *bi;
400
401                         /* if the user is no liveness node, the use does not count */
402                         if (!is_liveness_node(user))
403                                 continue;
404
405                         stat_ev_cnt_inc(uses);
406
407                         /* if the user is a phi, the use is in the predecessor
408                          * furthermore, prepare a mask so that in the case where
409                          * bl (the block in question) coincides with a use, it
410                          * can be marked live_end there. */
411                         use_bl = get_nodes_block(user);
412                         if (is_Phi(user)) {
413                                 int pos = get_edge_src_pos(edge);
414                                 use_bl  = get_Block_cfgpred_block(use_bl, pos);
415                                 mask   |= lv_chk_state_end;
416                         }
417
418
419                         /* if the use block coincides with the query block, we
420                          * already gather a little liveness information.
421                          * The variable is surely live there, since bl != def_bl
422                          * (that case is treated above). */
423                         if (use_bl == bl)
424                                 res |= mask;
425
426                         bi = get_block_info(lv, use_bl);
427
428                         if (bi)
429                                 bitset_set(uses, bi->id);
430                 }
431
432                 /* get the dominance range which really matters. all uses outside
433                  * the definition's dominance range are not to consider. note,
434                  * that the definition itself is also not considered. The case
435                  * where bl == def_bl is considered above. */
436                 min_dom = get_Block_dom_tree_pre_num(def_bl) + 1;
437                 max_dom = get_Block_dom_max_subtree_pre_num(def_bl);
438
439                 DBG((lv->dbg, LEVEL_2, "\tuses: %B\n", uses));
440
441                 /* prepare a set with all reachable back edge targets.
442                  * this will determine our "looking points" from where
443                  * we will search/find the calculated uses. */
444                 Tq = bli->be_tgt_reach;
445
446                 /* now, visit all viewing points in the temporary bitset lying
447                  * in the dominance range of the variable. Note that for reducible
448                  * flow-graphs the first iteration is sufficient and the loop
449                  * will be left. */
450                 DBG((lv->dbg, LEVEL_2, "\tbe tgt reach: %B, dom span: [%d, %d]\n", Tq, min_dom, max_dom));
451                 i = bitset_next_set(Tq, min_dom);
452                 while (i <= max_dom) {
453                         bl_info_t *ti = lv->map[i];
454                         int use_in_current_block = bitset_is_set(uses, ti->id);
455
456                         stat_ev_cnt_inc(iter);
457
458                         /*
459                          * This is somewhat tricky. Since this routine handles both, live in
460                          * and end/out we have to handle all the border cases correctly.
461                          * Each node is in its own red_reachable set (see calculation
462                          * function above). That means, that in the case where bl == t, the
463                          * intersection check of uses and reachability below will always
464                          * find an intersection, namely t.
465                          *
466                          * However, if a block contains a use and the variable is dead
467                          * afterwards, it is not live end/out at that block. Besides
468                          * back-edge target. If a var is live-in at a back-edge target it
469                          * is also live out/end there since the variable is live in the
470                          * underlying loop. So in the case where t == bl and that is not
471                          * a back-edge target, we have to remove that use from consideration
472                          * to determine if the var is live out/end there.
473                          *
474                          * Note that the live in information has been calculated by the
475                          * uses iteration above.
476                          */
477                         if (ti == bli && !bitset_is_set(lv->back_edge_tgt, ti->id)) {
478                                 DBG((lv->dbg, LEVEL_2, "\tlooking not from a back edge target and q == t. removing use: %d\n", ti->id));
479                                 bitset_clear(uses, ti->id);
480                         }
481
482                         /* If we can reach a use, the variable is live there and we say goodbye */
483                         DBG((lv->dbg, LEVEL_2, "\tlooking from %d: seeing %B\n", ti->id, ti->red_reachable));
484                         if (bitset_intersect(ti->red_reachable, uses)) {
485                                 res |= lv_chk_state_in | lv_chk_state_out | lv_chk_state_end;
486                                 goto end;
487                         }
488
489                         /*
490                          * if we deleted a use do to the commentary above, we have to
491                          * re-add it since it might be visible from further view points
492                          * (we only need that in the non-reducible case).
493                          */
494                         if (use_in_current_block)
495                                 bitset_set(uses, ti->id);
496
497                         i = bitset_next_set(Tq, get_Block_dom_max_subtree_pre_num(ti->block) + 1);
498                 }
499
500         }
501
502 end:
503         stat_ev_tim_pop("lv_chk_query_time");
504         stat_ev_cnt_done(uses, "lv_chk_uses");
505         stat_ev_cnt_done(iter, "lv_chk_iter");
506         stat_ev_ctx_pop("lv_chk");
507
508         return res;
509 }