guard against multiple users when skipping convs for AM
[libfirm] / ir / opt / return.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   Normalize returns.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include "iroptimize.h"
29 #include "irgraph_t.h"
30 #include "ircons_t.h"
31 #include "irnode_t.h"
32 #include "irgmod.h"
33 #include "irpass.h"
34
35 #define set_bit(n)      (returns[(n) >> 3] |= 1 << ((n) & 7))
36 #define get_bit(n)      (returns[(n) >> 3] & (1 << ((n) & 7)))
37
38 #undef IMAX
39 #define IMAX(a, b)       ((a) > (b) ? (a) : (b))
40
41 /*
42  * Normalize the Returns of a graph by creating a new End block
43  * with One Return(Phi).
44  * This is the preferred input for the if-conversion.
45  *
46  * In pseudocode, it means:
47  *
48  * if (a)
49  *   return b;
50  * else
51  *   return c;
52  *
53  * is transformed into
54  *
55  * if (a)
56  *   res = b;
57  * else
58  *   res = c;
59  * return res;
60  */
61 void normalize_one_return(ir_graph *irg)
62 {
63         ir_node *endbl = get_irg_end_block(irg);
64         int i, j, k, n, last_idx, n_rets, n_ret_vals = -1;
65         unsigned char *returns;
66         ir_node **in, **retvals, **endbl_in;
67         ir_node *block;
68         int       filter_dbgi   = 0;
69         dbg_info *combined_dbgi = NULL;
70
71         /* look, if we have more than one return */
72         n = get_Block_n_cfgpreds(endbl);
73         if (n <= 0) {
74                 /* The end block has no predecessors, we have an endless
75                    loop. In that case, no returns exists. */
76                 return;
77         }
78
79         returns = ALLOCANZ(unsigned char, (n + 7) >> 3);
80
81         for (n_rets = i = 0; i < n; ++i) {
82                 ir_node *node = get_Block_cfgpred(endbl, i);
83
84                 if (is_Return(node)) {
85                         dbg_info *dbgi = get_irn_dbg_info(node);
86
87                         if (dbgi != NULL && dbgi != combined_dbgi) {
88                                 if (filter_dbgi) {
89                                         combined_dbgi = NULL;
90                                 } else {
91                                         combined_dbgi = dbgi;
92                                         filter_dbgi   = 1;
93                                 }
94                         }
95
96                         ++n_rets;
97
98                         set_bit(i);
99
100                         if (n_ret_vals < 0)
101                                 n_ret_vals = get_irn_arity(node);
102                 }
103         }
104
105         /* there should be at least one Return node in Firm */
106         if (n_rets <= 1)
107                 return;
108
109         in       = ALLOCAN(ir_node*,  IMAX(n_rets, n_ret_vals));
110         retvals  = ALLOCAN(ir_node*,  n_rets * n_ret_vals);
111         endbl_in = ALLOCAN(ir_node*,  n);
112
113         last_idx = 0;
114         for (j = i = 0; i < n; ++i) {
115                 ir_node *ret = get_Block_cfgpred(endbl, i);
116
117                 if (get_bit(i)) {
118                         ir_node *block = get_nodes_block(ret);
119
120                         /* create a new Jmp for every Ret and place the in in */
121                         in[j] = new_r_Jmp(block);
122
123                         /* save the return values and shuffle them */
124                         for (k = 0; k < n_ret_vals; ++k)
125                                 retvals[j + k*n_rets] = get_irn_n(ret, k);
126
127                         ++j;
128                 } else
129                         endbl_in[last_idx++] = ret;
130         }
131
132         /* ok, create a new block with all created in's */
133         block = new_r_Block(irg, n_rets, in);
134
135         /* now create the Phi nodes */
136         for (j = i = 0; i < n_ret_vals; ++i, j += n_rets) {
137                 int k;
138                 ir_node *first;
139                 /* the return values are already shuffled */
140
141                 /* Beware: normally the Phi constructor automatically replaces a Phi(a,...a) into a
142                    but NOT, if a is Unknown. Here, we known that this case can be optimize also,
143                    so do it here */
144                 first = retvals[j + 0];
145                 for (k = 1; k < n_rets; ++k) {
146                         if (retvals[j + k] != first) {
147                                 first = NULL;
148                                 break;
149                         }
150                 }
151                 if (first)
152                         in[i] = first;
153                 else
154                         in[i] = new_r_Phi(block, n_rets, &retvals[j], get_irn_mode(retvals[j]));
155         }
156
157         endbl_in[last_idx++] = new_rd_Return(combined_dbgi, block, in[0], n_ret_vals-1, &in[1]);
158
159         set_irn_in(endbl, last_idx, endbl_in);
160
161         /* invalidate analysis information:
162          * a new Block was added, so dominator, outs and loop are inconsistent,
163          * trouts and callee-state should be still valid
164          */
165         set_irg_doms_inconsistent(irg);
166         set_irg_outs_inconsistent(irg);
167         set_irg_extblk_inconsistent(irg);
168         set_irg_loopinfo_inconsistent(irg);
169 }
170
171 /* Create a graph pass. */
172 ir_graph_pass_t *normalize_one_return_pass(const char *name)
173 {
174         return def_graph_pass(name ? name : "one_ret", normalize_one_return);
175 }
176
177 /**
178  * Check, whether a Return can be moved on block upwards.
179  *
180  * In a block with a Return, all live nodes must be linked
181  * with the Return, otherwise they are dead (because the Return leaves
182  * the graph, so no more users of the other nodes can exists.
183  *
184  * We can move a Return, if it's predecessors are Phi nodes or
185  * comes from another block. In the later case, it is always possible
186  * to move the Return one block up, because the predecessor block must
187  * dominate the Return block (SSA) and then it dominates the predecessor
188  * block of the Return block as well.
189  *
190  * All predecessors of the Return block must be Jmp's of course, or we
191  * cannot move it up, so we add blocks if needed.
192  */
193 static int can_move_ret(ir_node *ret)
194 {
195         ir_node *retbl = get_nodes_block(ret);
196         int i, n = get_irn_arity(ret);
197
198         for (i = 0; i < n; ++i) {
199                 ir_node *pred = get_irn_n(ret, i);
200
201                 if (! is_Phi(pred) && retbl == get_nodes_block(pred)) {
202                         /* first condition failed, found a non-Phi predecessor
203                          * then is in the Return block */
204                         return 0;
205                 }
206         }
207
208         /* check, that predecessors are Jmps */
209         n = get_Block_n_cfgpreds(retbl);
210         /* we cannot move above a labeled block, as this might kill the block */
211         if (n <= 1 || has_Block_entity(retbl))
212                 return 0;
213         for (i = 0; i < n; ++i) {
214                 ir_node *pred = get_Block_cfgpred(retbl, i);
215
216                 pred = skip_Tuple(pred);
217                 if (! is_Jmp(pred) && !is_Bad(pred)) {
218                         /* simply place a new block here */
219                         ir_graph *irg  = get_irn_irg(retbl);
220                         ir_node *block = new_r_Block(irg, 1, &pred);
221                         ir_node *jmp   = new_r_Jmp(block);
222                         set_Block_cfgpred(retbl, i, jmp);
223                 }
224         }
225         return 1;
226 }
227
228 /*
229  * Normalize the Returns of a graph by moving
230  * the Returns upwards as much as possible.
231  * This might be preferred for code generation.
232  *
233  * In pseudocode, it means:
234  *
235  * if (a)
236  *   res = b;
237  * else
238  *   res = c;
239  * return res;
240  *
241  * is transformed into
242  *
243  * if (a)
244  *   return b;
245  * else
246  *   return c;
247  */
248 void normalize_n_returns(ir_graph *irg)
249 {
250         int i, j, n, n_rets, n_finals, n_ret_vals;
251         ir_node *list  = NULL;
252         ir_node *final = NULL;
253         ir_node **in;
254         ir_node *endbl = get_irg_end_block(irg);
255         ir_node *end;
256
257         /*
258          * First, link all returns:
259          * These must be predecessors of the endblock.
260          * Place Returns that can be moved on list, all others
261          * on final.
262          */
263         n = get_Block_n_cfgpreds(endbl);
264         for (n_finals = n_rets = i = 0; i < n; ++i) {
265                 ir_node *ret = get_Block_cfgpred(endbl, i);
266
267                 if (is_Return(ret) && can_move_ret(ret)) {
268                         /*
269                          * Ok, all conditions met, we can move this Return, put it
270                          * on our work list.
271                          */
272                         set_irn_link(ret, list);
273                         list = ret;
274                         ++n_rets;
275                 } else {
276                         /* Put all nodes that are not changed on the final list. */
277                         set_irn_link(ret, final);
278                         final = ret;
279                         ++n_finals;
280                 }
281         }
282
283         if (n_rets <= 0)
284                 return;
285
286         /*
287          * Now move the Returns upwards. We move always one block up (and create n
288          * new Returns), than we check if a newly created Return can be moved even further.
289          * If yes, we simply add it to our work list, else to the final list.
290          */
291         end        = get_irg_end(irg);
292         n_ret_vals = get_irn_arity(list);
293         in         = ALLOCAN(ir_node*, n_ret_vals);
294         while (list) {
295                 ir_node  *ret   = list;
296                 ir_node  *block = get_nodes_block(ret);
297                 dbg_info *dbgi  = get_irn_dbg_info(ret);
298                 ir_node  *phiM;
299
300                 list = get_irn_link(ret);
301                 --n_rets;
302
303                 n = get_Block_n_cfgpreds(block);
304                 for (i = 0; i < n; ++i) {
305                         ir_node *jmp = get_Block_cfgpred(block, i);
306                         ir_node *new_bl, *new_ret;
307
308                         if (is_Bad(jmp))
309                                 continue;
310                         assert(is_Jmp(jmp));
311
312                         new_bl = get_nodes_block(jmp);
313
314                         /* create the in-array for the new Return */
315                         for (j = 0; j < n_ret_vals; ++j) {
316                                 ir_node *pred = get_irn_n(ret, j);
317
318                                 in[j] = (is_Phi(pred) && get_nodes_block(pred) == block) ? get_Phi_pred(pred, i) : pred;
319                         }
320
321                         new_ret = new_rd_Return(dbgi, new_bl, in[0], n_ret_vals - 1, &in[1]);
322
323                         if (! is_Bad(new_ret)) {
324                                 /*
325                                  * The newly created node might be bad, if we
326                                  * create it in a block with only Bad predecessors.
327                                  * In that case ignore this block.
328                                  *
329                                  * We could even kill the jmp then ...
330                                  */
331                                 if (can_move_ret(new_ret)) {
332                                         set_irn_link(new_ret, list);
333                                         list = new_ret;
334                                         ++n_rets;
335                                 } else {
336                                         set_irn_link(new_ret, final);
337                                         final = new_ret;
338                                         ++n_finals;
339                                 }
340                         }
341
342                         /* remove the Jmp, we have placed a Return here */
343                         exchange(jmp, new_r_Bad(irg));
344                 }
345
346                 /*
347                  * if the memory of the old Return is a PhiM, remove it
348                  * from the keep-alives, or it will keep the block which
349                  * will crash the dominator algorithm.
350                  */
351                 phiM = get_Return_mem(ret);
352                 if (is_Phi(phiM)) {
353                         n = get_End_n_keepalives(end);
354                         for (i = 0; i < n; ++i) {
355                                 if (get_End_keepalive(end, i) == phiM) {
356                                         set_End_keepalive(end, i, new_r_Bad(irg));
357                                         break;
358                                 }
359                         }
360                 }
361         }
362
363         /*
364          * Last step: Create a new endblock, with all nodes on the final
365          * list as predecessors.
366          */
367         in = ALLOCAN(ir_node*, n_finals);
368
369         for (i = 0; final; ++i, final = get_irn_link(final))
370                 in[i] = final;
371
372         exchange(endbl, new_r_Block(irg, n_finals, in));
373
374         /* the end block is not automatically skipped, so do it here */
375         set_irg_end_block(irg, skip_Id(get_irg_end_block(irg)));
376
377         /* Invalidate analysis information:
378          * Blocks become dead and new Returns were deleted, so dominator, outs and loop are inconsistent,
379          * trouts and callee-state should be still valid
380          */
381         set_irg_doms_inconsistent(irg);
382         set_irg_extblk_inconsistent(irg);  /* may not be needed */
383         set_irg_outs_inconsistent(irg);
384         set_irg_loopinfo_inconsistent(current_ir_graph);
385 }
386
387 /* Create a graph pass. */
388 ir_graph_pass_t *normalize_n_returns_pass(const char *name)
389 {
390         return def_graph_pass(name ? name : "n_rets", normalize_n_returns);
391 }