94824800fa1d72bd67f058bbe6860dd157124edd
[libfirm] / ir / opt / condeval.c
1 /*
2  * Copyright (C) 1995-2007 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   Partial condition evaluation
23  * @date    10. Sep. 2006
24  * @author  Christoph Mallon, Matthias Braun
25  * @version $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "iroptimize.h"
32
33 #include <assert.h>
34 #include "array.h"
35 #include "debug.h"
36 #include "ircons.h"
37 #include "irgmod.h"
38 #include "irgopt.h"
39 #include "irgwalk.h"
40 #include "irnode.h"
41 #include "irnode_t.h"
42 #include "iredges.h"
43 #include "iredges_t.h"
44 #include "irtools.h"
45 #include "irgraph.h"
46 #include "tv.h"
47
48 DEBUG_ONLY(static firm_dbg_module_t *dbg);
49
50 /**
51  * Add the new predecessor x to node node, which is either a Block or a Phi
52  */
53 static void add_pred(ir_node* node, ir_node* x)
54 {
55         ir_node** ins;
56         int n;
57         int i;
58
59         assert(is_Block(node) || is_Phi(node));
60
61         n = get_irn_arity(node);
62         NEW_ARR_A(ir_node*, ins, n + 1);
63         for (i = 0; i < n; i++)
64                 ins[i] = get_irn_n(node, i);
65         ins[n] = x;
66         set_irn_in(node, n + 1, ins);
67 }
68
69 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode)
70 {
71         int i;
72         int n_cfgpreds;
73         ir_graph *irg;
74         ir_node *phi;
75         ir_node **in;
76
77         // This is needed because we create bads sometimes
78         if(is_Bad(block))
79                 return new_Bad();
80
81         // already processed this block?
82         if(irn_visited(block)) {
83                 ir_node *value = (ir_node*) get_irn_link(block);
84                 return value;
85         }
86
87         // blocks with only 1 pred need no phi
88         n_cfgpreds = get_Block_n_cfgpreds(block);
89         if(n_cfgpreds == 1) {
90                 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
91                 ir_node *value = search_def_and_create_phis(pred_block, mode);
92
93                 set_irn_link(block, value);
94                 mark_irn_visited(block);
95                 return value;
96         }
97
98         // create a new phi
99         NEW_ARR_A(ir_node*, in, n_cfgpreds);
100         for(i = 0; i < n_cfgpreds; ++i)
101                 in[i] = new_Unknown(mode);
102
103         irg = get_irn_irg(block);
104         phi = new_r_Phi(irg, block, n_cfgpreds, in, mode);
105         set_irn_link(block, phi);
106         mark_irn_visited(block);
107
108         // set phi preds
109         for(i = 0; i < n_cfgpreds; ++i) {
110                 ir_node *pred_block = get_Block_cfgpred_block(block, i);
111                 ir_node *pred_val = search_def_and_create_phis(pred_block, mode);
112
113                 set_irn_n(phi, i, pred_val);
114         }
115
116         return phi;
117 }
118
119 /**
120  * Given a set of values this function constructs SSA-form for the users of the
121  * first value (the users are determined through the out-edges of the value).
122  * Uses the irn_visited flags. Works without using the dominance tree.
123  */
124 static void construct_ssa(ir_node * const *blocks, ir_node * const *vals, int n_vals)
125 {
126         int i;
127         ir_graph *irg;
128         ir_mode *mode;
129         const ir_edge_t *edge;
130         const ir_edge_t *next;
131         ir_node *value;
132
133         assert(n_vals > 0);
134
135         irg = get_irn_irg(vals[0]);
136         inc_irg_visited(irg);
137
138         mode = get_irn_mode(vals[0]);
139         for(i = 0; i < n_vals; ++i) {
140                 ir_node *value = vals[i];
141                 ir_node *value_block = blocks[i];
142
143                 assert(get_irn_mode(value) == mode);
144
145                 set_irn_link(value_block, value);
146                 mark_irn_visited(value_block);
147         }
148
149         // Only fix the users of the first, i.e. the original node
150         value = vals[0];
151
152         // this can happen when fixing phi preds, we mustn't fix the users
153         if(get_nodes_block(value) != blocks[0]) return;
154
155         foreach_out_edge_safe(value, edge, next) {
156                 ir_node *user = get_edge_src_irn(edge);
157                 int j = get_edge_src_pos(edge);
158                 ir_node *user_block = get_nodes_block(user);
159                 ir_node *newval;
160
161                 // ignore keeps
162                 if(get_irn_op(user) == op_End)
163                         continue;
164
165                 DB((dbg, LEVEL_3, ">>> Fixing user %+F (pred %d == %+F)\n", user, j, get_irn_n(user, j)));
166
167                 if(is_Phi(user)) {
168                         ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
169                         newval = search_def_and_create_phis(pred_block, mode);
170                 } else {
171                         newval = search_def_and_create_phis(user_block, mode);
172                 }
173
174                 // don't fix newly created phis from the SSA construction
175                 if (newval != user) {
176                         DB((dbg, LEVEL_4, ">>>> Setting input %d of %+F to %+F\n", j, user, newval));
177                         set_irn_n(user, j, newval);
178                 }
179         }
180 }
181
182 static void split_critical_edge(ir_node *block, int pos) {
183         ir_graph *irg = get_irn_irg(block);
184         ir_node *in[1];
185         ir_node *new_block;
186         ir_node *new_jmp;
187
188         in[0] = get_Block_cfgpred(block, pos);
189         new_block = new_r_Block(irg, 1, in);
190         new_jmp = new_r_Jmp(irg, new_block);
191         set_Block_cfgpred(block, pos, new_jmp);
192 }
193
194 typedef struct condeval_env_t {
195         ir_node       *true_block;
196         pn_Cmp         pnc;
197         ir_node       *cnst;
198         tarval        *tv;
199         unsigned long  visited_nr;
200
201         ir_node       *cnst_pred;   /**< the block before the constant */
202         int            cnst_pos;    /**< the pos to the constant block (needed to
203                                           kill that edge later) */
204 } condeval_env_t;
205
206 static void copy_and_fix(const condeval_env_t *env, ir_node *block,
207                          ir_node *copy_block, int j) {
208         const ir_edge_t *edge;
209
210         /* Look at all nodes in the cond_block and copy them into pred */
211         foreach_out_edge(block, edge) {
212                 ir_node *node = get_edge_src_irn(edge);
213                 ir_node *copy;
214                 ir_mode *mode = get_irn_mode(node);
215
216                 /* ignore control flow */
217                 if (mode == mode_X || is_Cond(node))
218                         continue;
219 #if 1
220                 /* we may not copy mode_b nodes, because this could produce phi with
221                  * mode_bs which can't be handled in all backends. Instead we duplicate
222                  * the node and move it to it's users */
223                 if (mode == mode_b) {
224                         const ir_edge_t *edge, *next;
225                         ir_node *pred;
226                         int      pn;
227
228                         assert(is_Proj(node));
229
230                         pred = get_Proj_pred(node);
231                         pn   = get_Proj_proj(node);
232
233                         foreach_out_edge_safe(node, edge, next) {
234                                 ir_node *cmp_copy;
235                                 ir_node *user       = get_edge_src_irn(edge);
236                                 int pos             = get_edge_src_pos(edge);
237                                 ir_node *user_block = get_nodes_block(user);
238
239                                 if(user_block == block)
240                                         continue;
241
242                                 cmp_copy = exact_copy(pred);
243                                 set_nodes_block(cmp_copy, user_block);
244                                 copy = new_r_Proj(current_ir_graph, user_block, cmp_copy, mode_b, pn);
245                                 set_irn_n(user, pos, copy);
246                         }
247                         continue;
248                 }
249 #endif
250
251                 /* we can evaluate Phis right now, all other nodes get copied */
252                 if (is_Phi(node)) {
253                         copy = get_Phi_pred(node, j);
254                 } else {
255                         copy = exact_copy(node);
256                         set_nodes_block(copy, copy_block);
257                 }
258
259                 set_irn_link(node, copy);
260                 set_irn_visited(node, env->visited_nr);
261
262                 /* we might hit values in blocks that have already been processed by a
263                  * recursive find_phi_with_const call */
264                 assert(get_irn_visited(copy) <= env->visited_nr);
265                 if(get_irn_visited(copy) >= env->visited_nr) {
266                         ir_node *prev_copy = get_irn_link(copy);
267                         if(prev_copy != NULL)
268                                 set_irn_link(node, prev_copy);
269                 }
270         }
271
272         /* fix data-flow (and reconstruct SSA if needed) */
273         foreach_out_edge(block, edge) {
274                 ir_node *vals[2];
275                 ir_node *blocks[2];
276                 ir_node *node = get_edge_src_irn(edge);
277                 ir_mode *mode = get_irn_mode(node);
278
279                 if (mode == mode_X || is_Cond(node))
280                         continue;
281                 if (mode == mode_b)
282                         continue;
283
284                 DB((dbg, LEVEL_2, ">> Fixing users of %+F\n", node));
285
286                 blocks[0] = block;
287                 vals[0] = node;
288                 blocks[1] = copy_block;
289                 vals[1] = get_irn_link(node);
290                 construct_ssa(blocks, vals, 2);
291         }
292 }
293
294 static int eval_cmp(pn_Cmp pnc, tarval *tv1, tarval *tv2) {
295         pn_Cmp cmp_result = tarval_cmp(tv1, tv2);
296
297         // does the compare evaluate to true?
298         if(cmp_result == pn_Cmp_False)
299                 return 0;
300         if((cmp_result & pnc) != cmp_result)
301                 return 0;
302
303         return 1;
304 }
305
306 static ir_node *find_const(condeval_env_t *env, ir_node *jump, ir_node *value)
307 {
308         ir_node *block = get_nodes_block(jump);
309
310         if(irn_visited(value))
311                 return NULL;
312         mark_irn_visited(value);
313
314         if(is_Const(value)) {
315                 tarval *tv_const = get_Const_tarval(env->cnst);
316                 tarval *tv       = get_Const_tarval(value);
317
318                 if(!eval_cmp(env->pnc, tv, tv_const)) {
319                         return NULL;
320                 }
321
322                 DB((
323                         dbg, LEVEL_1,
324                         "> Found condition evaluation candidate %+F->%+F\n",
325                         env->true_block, block
326                 ));
327
328                 // adjust true_block to point directly towards our jump
329                 add_pred(env->true_block, jump);
330
331                 split_critical_edge(env->true_block, 0);
332
333                 // we need a bigger visited nr when going back
334                 env->visited_nr++;
335
336                 return block;
337         }
338
339         if(is_Phi(value)) {
340                 int i, arity;
341
342                 // the phi has to be in the same block as the jump
343                 if(get_nodes_block(value) != block) {
344                         return NULL;
345                 }
346
347                 arity = get_irn_arity(value);
348                 for(i = 0; i < arity; ++i) {
349                         ir_node *copy_block;
350                         ir_node *phi_pred = get_Phi_pred(value, i);
351                         ir_node *cfgpred  = get_Block_cfgpred(block, i);
352
353                         copy_block = find_const(env, cfgpred, phi_pred);
354                         if(copy_block == NULL)
355                                 continue;
356
357                         /* copy duplicated nodes in copy_block and fix SSA */
358                         copy_and_fix(env, block, copy_block, i);
359
360                         if(copy_block == get_nodes_block(cfgpred)) {
361                                 env->cnst_pred = block;
362                                 env->cnst_pos  = i;
363                         }
364
365                         // return now as we can't process more possibilities in 1 run
366                         return copy_block;
367                 }
368         }
369
370         return NULL;
371 }
372
373 static ir_node *find_candidate(condeval_env_t *env, ir_node *jump,
374                                ir_node *value)
375 {
376         ir_node *block = get_nodes_block(jump);
377
378         if(irn_visited(value)) {
379                 return NULL;
380         }
381         mark_irn_visited(value);
382
383         if(is_Const(value)) {
384                 tarval *tv       = get_Const_tarval(value);
385
386                 if(tv != env->tv)
387                         return NULL;
388
389                 DB((
390                         dbg, LEVEL_1,
391                         "> Found condition evaluation candidate %+F->%+F\n",
392                         env->true_block, block
393                 ));
394
395                 // adjust true_block to point directly towards our jump
396                 add_pred(env->true_block, jump);
397
398                 split_critical_edge(env->true_block, 0);
399
400                 // we need a bigger visited nr when going back
401                 env->visited_nr++;
402
403                 return block;
404         }
405         if(is_Phi(value)) {
406                 int i, arity;
407
408                 // the phi has to be in the same block as the jump
409                 if(get_nodes_block(value) != block)
410                         return NULL;
411
412                 arity = get_irn_arity(value);
413                 for(i = 0; i < arity; ++i) {
414                         ir_node *copy_block;
415                         ir_node *phi_pred = get_Phi_pred(value, i);
416                         ir_node *cfgpred  = get_Block_cfgpred(block, i);
417
418                         copy_block = find_candidate(env, cfgpred, phi_pred);
419                         if(copy_block == NULL)
420                                 continue;
421
422                         /* copy duplicated nodes in copy_block and fix SSA */
423                         copy_and_fix(env, block, copy_block, i);
424
425                         if(copy_block == get_nodes_block(cfgpred)) {
426                                 env->cnst_pred = block;
427                                 env->cnst_pos  = i;
428                         }
429
430                         // return now as we can't process more possibilities in 1 run
431                         return copy_block;
432                 }
433         }
434         if(is_Proj(value)) {
435                 ir_node *left;
436                 ir_node *right;
437                 int      pnc;
438                 ir_node *cmp = get_Proj_pred(value);
439                 if(!is_Cmp(cmp))
440                         return NULL;
441
442                 left  = get_Cmp_left(cmp);
443                 right = get_Cmp_right(cmp);
444                 pnc   = get_Proj_proj(value);
445
446                 /* we assume that the constant is on the right side, swap left/right
447                  * if needed */
448                 if(is_Const(left)) {
449                         ir_node *t = left;
450                         left       = right;
451                         right      = t;
452
453                         pnc        = get_inversed_pnc(pnc);
454                 }
455
456                 if(!is_Const(right))
457                         return 0;
458
459                 if(get_nodes_block(left) != block) {
460                         return 0;
461                 }
462
463                 /* negate condition when we're looking for the false block */
464                 if(env->tv == get_tarval_b_false()) {
465                         pnc = get_negated_pnc(pnc, get_irn_mode(right));
466                 }
467
468                 // (recursively) look if a pred of a phi is a constant
469                 env->pnc  = pnc;
470                 env->cnst = right;
471
472                 return find_const(env, jump, left);
473         }
474
475         return NULL;
476 }
477
478 /**
479  * Block-walker: searches for the following construct
480  *
481  *  Const or Phi with constants
482  *           |
483  *          Cmp
484  *           |
485  *         Cond
486  *          /
487  *       ProjX
488  *        /
489  *     Block
490  */
491 static void cond_eval(ir_node* block, void* data)
492 {
493         condeval_env_t env;
494         int *changed = data;
495         ir_node *selector;
496         ir_node *projx;
497         ir_node *cond;
498         ir_node *copy_block;
499         const ir_edge_t *edge, *next;
500         ir_node* bad;
501         size_t   cnst_pos;
502
503         if(get_Block_n_cfgpreds(block) != 1)
504                 return;
505
506         projx = get_Block_cfgpred(block, 0);
507         if (!is_Proj(projx))
508                 return;
509         assert(get_irn_mode(projx) == mode_X);
510
511         cond = get_Proj_pred(projx);
512         if (!is_Cond(cond))
513                 return;
514
515         selector = get_Cond_selector(cond);
516         // TODO handle switch Conds
517         if (get_irn_mode(selector) != mode_b)
518                 return;
519
520         if (get_Proj_proj(projx) == pn_Cond_false) {
521                 env.tv = get_tarval_b_false();
522         } else {
523                 env.tv = get_tarval_b_true();
524         }
525
526         // (recursively) look if a pred of a phi is a constant
527         env.true_block = block;
528         inc_irg_visited(current_ir_graph);
529         env.visited_nr = get_irg_visited(current_ir_graph);
530
531         copy_block = find_candidate(&env, projx, selector);
532         if (copy_block == NULL)
533                 return;
534
535         /* we have to remove the edge towards the pred as the pred now
536          * jumps into the true_block. We also have to shorten phis
537          * in our block because of this */
538         bad      = new_Bad();
539         cnst_pos = env.cnst_pos;
540
541         /* shorten phis */
542         foreach_out_edge_safe(env.cnst_pred, edge, next) {
543                 ir_node *node = get_edge_src_irn(edge);
544
545                 if(is_Phi(node))
546                         set_Phi_pred(node, cnst_pos, bad);
547         }
548
549         set_Block_cfgpred(env.cnst_pred, cnst_pos, bad);
550
551         /* the graph is changed now */
552         *changed = 1;
553 }
554
555 void opt_cond_eval(ir_graph* irg)
556 {
557         int changed, rerun;
558
559         FIRM_DBG_REGISTER(dbg, "firm.opt.condeval");
560
561         DB((dbg, LEVEL_1, "===> Performing condition evaluation on %+F\n", irg));
562
563         remove_critical_cf_edges(irg);
564         normalize_proj_nodes(irg);
565
566         edges_assure(irg);
567         set_using_irn_link(irg);
568         set_using_visited(irg);
569
570         changed = 0;
571         do {
572                 rerun = 0;
573                 irg_block_walk_graph(irg, cond_eval, NULL, &rerun);
574                 changed |= rerun;
575         } while (rerun);
576
577         if (changed) {
578                 /* control flow changed, some blocks may become dead */
579                 set_irg_outs_inconsistent(irg);
580                 set_irg_doms_inconsistent(irg);
581                 set_irg_extblk_inconsistent(irg);
582                 set_irg_loopinfo_inconsistent(irg);
583         }
584
585         clear_using_visited(irg);
586         clear_using_irn_link(irg);
587 }