protect against cycles in dead code
[libfirm] / ir / opt / funccall.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/funccall.c
4  * Purpose:     optimization of function calls
5  * Author:      Michael Beck
6  * Created:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 1998-2006 Universität Karlsruhe
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11 #include "irnode_t.h"
12 #include "irgraph_t.h"
13 #include "irgmod.h"
14 #include "irgwalk.h"
15 #include "irvrfy.h"
16 #include "dbginfo_t.h"
17 #include "irflag_t.h"
18 #include "ircons.h"
19 #include "funccall.h"
20 #include "irhooks.h"
21
22 /**
23  * The walker environment for rem_mem_from_const_fkt_calls
24  */
25 typedef struct _env_t {
26   int  n_calls_removed_SymConst;
27   int  n_calls_removed_Sel;
28   ir_node *const_call_list;       /**< The list of all const function calls that will be changed. */
29   ir_node *pure_call_list;        /**< The list of all pure function calls that will be changed. */
30   ir_node *proj_list;             /**< The list of all potential Proj nodes that must be fixed. */
31 } env_t;
32
33 /**
34  * Collect all calls to const and pure functions
35  * to lists. Collect all Proj(Call) nodes into a Proj list.
36  */
37 static void collect_calls(ir_node *node, void *env)
38 {
39   env_t *ctx = env;
40   ir_node *call, *ptr;
41   entity *ent;
42   unsigned mode;
43
44   if (is_Call(node)) {
45     call = node;
46
47     /* set the link to NULL for all non-const/pure calls */
48     set_irn_link(call, NULL);
49     ptr = get_Call_ptr(call);
50     if (get_irn_op(ptr) == op_SymConst && get_SymConst_kind(ptr) == symconst_addr_ent) {
51       ent = get_SymConst_entity(ptr);
52
53       mode = get_entity_additional_properties(ent);
54       if ((mode & (mtp_property_const|mtp_property_pure)) == 0)
55         return;
56       ++ctx->n_calls_removed_SymConst;
57     } else if (get_opt_closed_world() &&
58              is_Sel(ptr) &&
59                  get_irg_callee_info_state(current_ir_graph) == irg_callee_info_consistent) {
60       /* If all possible callees are const functions, we can remove the memory edge. */
61       int i, n_callees = get_Call_n_callees(call);
62       if (n_callees == 0)
63         /* This is kind of strange:  dying code or a Call that will raise an exception
64                when executed as there is no implementation to call.  So better not
65                optimize. */
66         return;
67
68       /* note that const function are a subset of pure ones */
69       mode = mtp_property_const | mtp_property_pure;
70       for (i = 0; i < n_callees; ++i) {
71         ent = get_Call_callee(call, i);
72         if (ent == unknown_entity) {
73           /* we don't know which entity is called here */
74           return;
75         }
76         mode &= get_entity_additional_properties(ent);
77         if (mode == 0)
78           return;
79       }
80       ++ctx->n_calls_removed_Sel;
81     } else
82       return;
83
84     /* ok, if we get here we found a call to a const or a pure function */
85     if (mode & mtp_property_pure) {
86       set_irn_link(call, ctx->pure_call_list);
87       ctx->pure_call_list = call;
88     } else {
89       set_irn_link(call, ctx->const_call_list);
90       ctx->const_call_list = call;
91     }
92   } else if (is_Proj(node)) {
93     /*
94      * Collect all memory and exception Proj's from
95      * calls.
96      */
97     call = get_Proj_pred(node);
98     if (! is_Call(call))
99       return;
100
101     /* collect the Proj's in the Proj list */
102     switch (get_Proj_proj(node)) {
103     case pn_Call_M_regular:
104     case pn_Call_X_except:
105     case pn_Call_M_except:
106       set_irn_link(node, ctx->proj_list);
107       ctx->proj_list = node;
108       break;
109     default:
110       break;
111     }
112   }
113 }  /* collect_calls */
114
115 /**
116  * Fix the list of collected Calls.
117  *
118  * @param irg        the graph that contained calls to pure functions
119  * @param call_list  the list of all call sites of const functions
120  * @param proj_list  the list of all memory/exception Proj's of this call sites
121  */
122 static void fix_const_call_list(ir_graph *irg, ir_node *call_list, ir_node *proj_list) {
123   ir_node *call, *next, *mem, *proj;
124   int exc_changed = 0;
125
126   /* First step: fix all calls by removing it's memory input.
127      It's original memory input is preserved in their link fields. */
128   for (call = call_list; call; call = next) {
129     next = get_irn_link(call);
130     mem  = get_Call_mem(call);
131
132     set_irn_link(call, mem);
133     set_Call_mem(call, get_irg_no_mem(irg));
134
135     /*
136      * Sorrily we cannot simply set the node to 'float'.
137      * There is a reason for that:
138      *
139      * - The call might be inside a loop/if that is NOT entered
140      *   and calls a endless function. Setting the call to float
141      *   would allow to move it out from the loop/if causing this
142      *   function be called even if the loop/if is not entered ...
143      *
144      * This could be fixed using post-dominators for calls and Pin nodes
145      * but need some more analyzes to ensure that a call that potential
146      * never returns is not executed before some code that generates
147      * observable states...
148      */
149
150     /* finally, this call can float
151     set_irn_pinned(call, op_pin_state_floats); */
152     hook_func_call(irg, call);
153   }
154
155   /* Second step: fix all Proj's */
156   for (proj = proj_list; proj; proj = next) {
157     next = get_irn_link(proj);
158     call = get_Proj_pred(proj);
159     mem  = get_irn_link(call);
160
161     /* beware of calls in the pure call list */
162     if (! mem || get_irn_op(mem) == op_Call)
163       continue;
164     assert(get_irn_mode(mem) == mode_M);
165
166     switch (get_Proj_proj(proj)) {
167     case pn_Call_M_regular: {
168       /* in dead code there might be cycles where proj == mem */
169       if (proj != mem)
170         exchange(proj, mem);
171     } break;
172     case pn_Call_X_except:
173     case pn_Call_M_except:
174       exc_changed = 1;
175       exchange(proj, get_irg_bad(irg));
176       break;
177     default:
178       ;
179     }
180   }
181
182   /* changes were done ... */
183   set_irg_outs_inconsistent(irg);
184   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
185
186   if (exc_changed) {
187     /* ... including exception edges */
188     set_irg_doms_inconsistent(irg);
189   }
190 }  /* fix_call_list */
191
192
193 /**
194  * Check if a graph represents a const function.
195  *
196  * @param irg  the graph
197  */
198 static int is_const_function(ir_graph *irg)
199 {
200   ir_node *end, *endbl;
201   int j, change;
202
203   if (get_irg_additional_properties(irg) & mtp_property_const) {
204     /* already marked as a const function */
205     return 0;
206   }
207
208   end   = get_irg_end(irg);
209   endbl = get_nodes_block(end);
210   change = 0;
211
212   /* visit every Return */
213   for (j = get_Block_n_cfgpreds(endbl) - 1; j >= 0; --j) {
214     ir_node *node = get_Block_cfgpred(endbl, j);
215     ir_op   *op   = get_irn_op(node);
216     ir_node *mem;
217
218     /* Bad nodes usually do NOT produce anything, so it's ok */
219     if (op == op_Bad)
220       continue;
221
222     if (op == op_Return) {
223       mem = get_Return_mem(node);
224
225       /* Bad nodes usually do NOT produce anything, so it's ok */
226       if (is_Bad(mem))
227         continue;
228
229       change = mem != get_irg_initial_mem(irg);
230       if (change)
231         break;
232     }
233     else {
234       /* exception found */
235       change = 1;
236       break;
237     }
238   }
239
240   if (! change) {
241     /* check, if a keep-alive exists */
242     for (j = get_End_n_keepalives(end) - 1; j >= 0; --j) {
243       ir_node *mem = get_End_keepalive(end, j);
244
245       if (mode_M != get_irn_mode(mem))
246         continue;
247
248       change = mem != get_irg_initial_mem(irg);
249       if (change)
250         break;
251     }
252   }
253
254   if (! change) {
255     /* no memory changes found, it's a const function */
256     set_irg_additional_property(irg, mtp_property_const);
257     return 1;
258   }
259   return 0;
260 }  /* is_const_function */
261
262 /* a marker */
263 static char _mark;
264 #define MARK &_mark
265
266 #define UNMARK_IRG(irg)     set_irg_link((irg), NULL)
267 #define MARK_IRG(irg)       set_irg_link((irg), MARK)
268 #define IS_IRG_MARKED(irg)  (get_irg_link(irg) == MARK)
269
270 /* forward */
271 static int is_pure_function(ir_graph *irg);
272
273 #define UMAX(a,b) (a) > (b) ? (a) : (b)
274
275 /**
276  * Follow the memory chain starting at node and determine
277  * the mtp_property.
278  *
279  * @return mtp_property_const if only calls of const functions are detected
280  *         mtp_property_pure if only Loads and const/pure
281  *         calls detected
282  *         bad_property else
283  */
284 static unsigned _follow_mem(ir_node *node) {
285   unsigned m, mode = mtp_property_const;
286   ir_node  *ptr;
287   int i;
288
289   for (;;) {
290     if (irn_visited(node))
291       return mode;
292
293     mark_irn_visited(node);
294
295     switch (get_irn_opcode(node)) {
296     case iro_Proj:
297       node = get_Proj_pred(node);
298       break;
299
300     case iro_NoMem:
301       /* finish here */
302       return mode;
303
304     case iro_Phi:
305     case iro_Sync:
306       for (i = get_irn_arity(node) - 1; i >= 0; --i) {
307         mode &= _follow_mem(get_irn_n(node, i));
308       }
309       break;
310
311     case iro_Load:
312       /* Beware volatile Loads are NOT allowed in pure functions */
313       if (get_Load_volatility(node) == volatility_is_volatile)
314         return 0;
315       mode = mtp_property_pure;
316       node = get_Load_mem(node);
317       break;
318
319     case iro_Call:
320       /* a call is only tolerable if its either constant or pure */
321       ptr = get_Call_ptr(node);
322       if (get_irn_op(ptr) == op_SymConst &&
323           get_SymConst_kind(ptr) == symconst_addr_ent) {
324         entity   *ent = get_SymConst_entity(ptr);
325         ir_graph *irg = get_entity_irg(ent);
326
327         if (irg == current_ir_graph) {
328           /* A recursive call. The did not mode depend on this call */
329         }
330         else if (irg == NULL) {
331           m = get_entity_additional_properties(ent) & (mtp_property_const|mtp_property_pure);
332           if (! m)
333             return 0;
334           mode = UMAX(mode, m);
335         }
336         else if (irg != NULL) {
337           /* we have a graph. Check if it is already analyzed */
338           if (IS_IRG_MARKED(irg))
339             (void)is_pure_function(irg);
340
341           m = get_irg_additional_properties(irg) & (mtp_property_const|mtp_property_pure);
342           if (! m)
343             return 0;
344           mode = UMAX(mode, m);
345         }
346       }
347       else
348         return 0;
349       node = get_Call_mem(node);
350       break;
351
352     default:
353       return 0;
354     }
355   }
356 }  /* follow_mem */
357
358 /**
359  * Follow the memory chain starting at node and determine
360  * the mtp_property.
361  *
362  * @return mtp_property_const if only calls of const functions are detected
363  *         mtp_property_pure if only Loads and const/pure
364  *         calls detected
365  *         0 else
366  */
367 static unsigned follow_mem(ir_graph *irg, ir_node *node, unsigned mode) {
368   unsigned m;
369
370   inc_irg_visited(irg);
371   /* mark the initial mem: recursion stops here */
372   mark_irn_visited(get_irg_initial_mem(irg));
373   m = _follow_mem(node);
374   if (! m)
375     return 0;
376   return UMAX(mode, m);
377 }  /* follow_mwm */
378
379 /*
380  * Check if a graph represents a pure function.
381  *
382  * @param irg  the graph
383  */
384 static int is_pure_function(ir_graph *irg) {
385   ir_node *end, *endbl;
386   int j;
387   unsigned mode = get_irg_additional_properties(irg);
388   ir_graph *rem = current_ir_graph;
389
390   if (mode & mtp_property_const) {
391     /* already marked as a const function */
392     return mtp_property_const;
393   }
394   if (mode & mtp_property_pure) {
395     /* already marked as a pure function */
396     return mtp_property_const;
397   }
398
399   if (! IS_IRG_MARKED(irg))
400     return 0;
401   UNMARK_IRG(irg);
402
403   end   = get_irg_end(irg);
404   endbl = get_nodes_block(end);
405   mode  = mtp_property_const;
406
407   current_ir_graph = irg;
408
409   /* visit every Return */
410   for (j = get_Block_n_cfgpreds(endbl) - 1; j >= 0; --j) {
411     ir_node *node = get_Block_cfgpred(endbl, j);
412     ir_op   *op   = get_irn_op(node);
413     ir_node *mem;
414
415     /* Bad nodes usually do NOT produce anything, so it's ok */
416     if (op == op_Bad)
417       continue;
418
419     if (op == op_Return) {
420       mem = get_Return_mem(node);
421
422       /* Bad nodes usually do NOT produce anything, so it's ok */
423       if (is_Bad(mem))
424         continue;
425
426       if (mem != get_irg_initial_mem(irg))
427         mode = follow_mem(irg, mem, mode);
428     }
429     else {
430       /* exception found. */
431       mode = follow_mem(irg, node, mode);
432       break;
433     }
434     if (mode == 0)
435       break;
436   }
437
438   if (mode != 0) {
439     /* check, if a keep-alive exists */
440     for (j = get_End_n_keepalives(end) - 1; j >= 0; --j) {
441       ir_node *mem = get_End_keepalive(end, j);
442
443       if (mode_M != get_irn_mode(mem))
444         continue;
445
446       mode = follow_mem(irg, mem, mode);
447       if (mode == 0)
448         break;
449     }
450   }
451
452   if (mode)
453     set_irg_additional_property(irg, mode);
454   current_ir_graph = rem;
455   return mode;
456 }  /* is_pure_function */
457
458 /**
459  * Handle calls to const functions.
460  */
461 static void handle_const_Calls(env_t *ctx)
462 {
463   int i;
464
465   ctx->n_calls_removed_SymConst = 0;
466   ctx->n_calls_removed_Sel      = 0;
467
468   /* all calls of const functions can be transformed */
469   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
470     ir_graph *irg  = get_irp_irg(i);
471
472     ctx->const_call_list = NULL;
473     ctx->pure_call_list  = NULL;
474     ctx->proj_list = NULL;
475     irg_walk_graph(irg, NULL, collect_calls, ctx);
476
477     if (ctx->const_call_list)
478       fix_const_call_list(irg, ctx->const_call_list, ctx->proj_list);
479   }
480 }  /* handle_const_Calls */
481
482 /*
483  * optimize function calls by handling const functions
484  */
485 void optimize_funccalls(int force_run)
486 {
487   int i, n;
488   unsigned num_const = 0;
489   unsigned num_pure  = 0;
490
491   if (! get_opt_function_call())
492     return;
493
494   /* prepare: mark all graphs as not analyzed */
495   n = get_irp_n_irgs();
496   for (i = n - 1; i >= 0; --i)
497     MARK_IRG(get_irp_irg(i));
498
499   /* first step: detect, which functions are const, i.e. do NOT touch any memory */
500   for (i = n - 1; i >= 0; --i) {
501     ir_graph *irg = get_irp_irg(i);
502     unsigned mode = is_pure_function(irg);
503
504     if (mode & mtp_property_const)
505       ++num_const;
506     else if (mode & mtp_property_pure)
507       ++num_pure;
508   }
509
510   if (force_run || num_const > 0) {
511     env_t ctx;
512
513     handle_const_Calls(&ctx);
514     if (get_firm_verbosity()) {
515       printf("Detected %d graphs without side effects.\n", num_const);
516       printf("Optimizes %d(SymConst) + %d(Sel) calls to const/pure functions.\n",
517                ctx.n_calls_removed_SymConst, ctx.n_calls_removed_Sel);
518     }
519   }
520   else {
521     if (get_firm_verbosity()) {
522       printf("No graphs without side effects detected\n");
523     }
524   }
525 }  /* optimize_funccalls */