add code to detect pure function
[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-2004 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 of Proj 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 (get_irn_op(node) == op_Call) {
45     call = node;
46
47     set_irn_link(call, NULL);
48     ptr = get_Call_ptr(call);
49     if (get_irn_op(ptr) == op_SymConst && get_SymConst_kind(ptr) == symconst_addr_ent) {
50       ent = get_SymConst_entity(ptr);
51
52       mode = get_entity_additional_properties(ent);
53       if (mode & (mtp_property_const|mtp_property_pure) == 0)
54         return;
55       ++ctx->n_calls_removed_SymConst;
56     }
57     else if (is_Sel(ptr) &&
58              get_irg_callee_info_state(current_ir_graph) == irg_callee_info_consistent) {
59       /* If all possible callees are const functions, we can remove the memory edge. */
60       int i, n_callees = get_Call_n_callees(call);
61       if (n_callees == 0)
62         /* This is kind of strange:  dying code or a Call that will raise an exception
63                  when executed as there is no implementation to call.  So better not
64                  optimize. */
65         return;
66
67       /* note that const function are a subset of pure ones */
68       mode = mtp_property_const | mtp_property_pure;
69       for (i = 0; i < n_callees; ++i) {
70         ent = get_Call_callee(call, i);
71         if (ent == unknown_entity) {
72           /* we don't know which entity is called here */
73           return;
74         }
75         mode &= get_entity_additional_properties(ent);
76         if (mode == 0)
77           return;
78       }
79       ++ctx->n_calls_removed_Sel;
80     }
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     }
89     else {
90       set_irn_link(call, ctx->const_call_list);
91       ctx->const_call_list = call;
92     }
93   }
94   else if (get_irn_op(node) == op_Proj) {
95     /*
96      * Collect all memory and exception Proj's from
97      * calls.
98      */
99     call = get_Proj_pred(node);
100     if (get_irn_op(call) != op_Call)
101       return;
102
103     switch (get_Proj_proj(node)) {
104     case pn_Call_M_regular:
105     case pn_Call_X_except:
106     case pn_Call_M_except:
107       set_irn_link(node, ctx->proj_list);
108       ctx->proj_list = node;
109       break;
110     default:
111       break;
112     }
113   }
114 }  /* rem_mem_from_const_fkt_calls */
115
116 /**
117  * Fix the list of collected Calls.
118  *
119  * @param irg        the graph that contained calls to pure functions
120  * @param call_list  the list of all call sites of pure functions
121  * @param proj_list  the list of all memory/exception Projs of this call sites
122  */
123 static void fix_const_call_list(ir_graph *irg, ir_node *call_list, ir_node *proj_list) {
124   ir_node *call, *next, *mem, *proj;
125   int exc_changed = 0;
126
127   /* fix all calls by removing it's memory input */
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 analyses 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   /* finally 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     if (! mem)
161       continue;
162
163     switch (get_Proj_proj(proj)) {
164     case pn_Call_M_regular: {
165       exchange(proj, mem);
166     } break;
167     case pn_Call_X_except:
168     case pn_Call_M_except:
169       exc_changed = 1;
170       exchange(proj, get_irg_bad(irg));
171       break;
172     default:
173       ;
174     }
175   }
176
177   /* changes were done ... */
178   set_irg_outs_inconsistent(irg);
179   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
180
181   if (exc_changed) {
182     /* ... including exception edges */
183     set_irg_doms_inconsistent(irg);
184   }
185 }  /* fix_call_list */
186
187
188 /**
189  * Check if a graph represents a const function.
190  *
191  * @param irg  the graph
192  */
193 static int is_const_function(ir_graph *irg)
194 {
195   ir_node *end, *endbl;
196   int j, change;
197
198   if (get_irg_additional_properties(irg) & mtp_property_const) {
199     /* already marked as a const function */
200     return 0;
201   }
202
203   end   = get_irg_end(irg);
204   endbl = get_nodes_block(end);
205   change = 0;
206
207   /* visit every Return */
208   for (j = get_Block_n_cfgpreds(endbl) - 1; j >= 0; --j) {
209     ir_node *node = get_Block_cfgpred(endbl, j);
210     ir_op   *op   = get_irn_op(node);
211     ir_node *mem;
212
213     /* Bad nodes usually do NOT produce anything, so it's ok */
214     if (op == op_Bad)
215       continue;
216
217     if (op == op_Return) {
218       mem = get_Return_mem(node);
219
220       /* Bad nodes usually do NOT produce anything, so it's ok */
221       if (is_Bad(mem))
222         continue;
223
224       change = mem != get_irg_initial_mem(irg);
225       if (change)
226         break;
227     }
228     else {
229       /* exception found */
230       change = 1;
231       break;
232     }
233   }
234
235   if (! change) {
236     /* check, if a keep-alive exists */
237     for (j = get_End_n_keepalives(end) - 1; j >= 0; --j) {
238       ir_node *mem = get_End_keepalive(end, j);
239
240       if (mode_M != get_irn_mode(mem))
241         continue;
242
243       change = mem != get_irg_initial_mem(irg);
244       if (change)
245         break;
246     }
247   }
248
249   if (! change) {
250     /* no memory changes found, it's a const function */
251     set_irg_additional_property(irg, mtp_property_const);
252     return 1;
253   }
254   return 0;
255 }  /* is_const_function */
256
257 /* a marker */
258 static char _mark;
259 #define MARK &_mark
260
261 #define UNMARK_IRG(irg)     set_irg_link((irg), NULL)
262 #define MARK_IRG(irg)       set_irg_link((irg), MARK)
263 #define IS_IRG_MARKED(irg)  (get_irg_link(irg) == MARK)
264
265 /* forward */
266 static int is_pure_function(ir_graph *irg);
267
268 #define UMAX(a,b) (a) > (b) ? (a) : (b)
269
270 /**
271  * Follow the memory chain starting at node and determine
272  * the mtp_property.
273  *
274  * @return mtp_property_const if only calls of const functions are detected
275  *         mtp_property_pure if only Loads and const/pure
276  *         calls detected
277  *         bad_property else
278  */
279 static unsigned _follow_mem(ir_node *node) {
280   unsigned m, mode = mtp_property_const;
281   ir_node  *ptr;
282   int i;
283
284   for (;;) {
285     if (irn_visited(node))
286       return mode;
287
288     mark_irn_visited(node);
289
290     switch (get_irn_opcode(node)) {
291     case iro_Proj:
292       node = get_Proj_pred(node);
293       break;
294
295     case iro_NoMem:
296       /* finish here */
297       return mode;
298
299     case iro_Phi:
300     case iro_Sync:
301       for (i = get_irn_arity(node) - 1; i >= 0; --i) {
302         mode &= _follow_mem(get_irn_n(node, i));
303       }
304       break;
305
306     case iro_Load:
307       /* Beware volatile Loads are NOT allowed in pure functions */
308       if (get_Load_volatility(node) == volatility_is_volatile)
309         return 0;
310       mode = mtp_property_pure;
311       node = get_Load_mem(node);
312       break;
313
314     case iro_Call:
315       /* a call is only tolerable if its either constant or pure */
316       ptr = get_Call_ptr(node);
317       if (get_irn_op(ptr) == op_SymConst &&
318           get_SymConst_kind(ptr) == symconst_addr_ent) {
319         entity   *ent = get_SymConst_entity(ptr);
320         ir_graph *irg = get_entity_irg(ent);
321
322         if (irg == current_ir_graph) {
323           /* A recursive call. The did not mode depend on this call */
324         }
325         else if (irg == NULL) {
326           m = get_entity_additional_properties(ent) & (mtp_property_const|mtp_property_pure);
327           if (! m)
328             return 0;
329           mode = UMAX(mode, m);
330         }
331         else if (irg != NULL) {
332           /* we have a graph. Check if it is already analyzed */
333           if (IS_IRG_MARKED(irg))
334             (void)is_pure_function(irg);
335
336           m = get_irg_additional_properties(irg) & (mtp_property_const|mtp_property_pure);
337           if (! m)
338             return 0;
339           mode = UMAX(mode, m);
340         }
341       }
342       else
343         return 0;
344       node = get_Call_mem(node);
345       break;
346
347     default:
348       return 0;
349     }
350   }
351 }  /* follow_mem */
352
353 /**
354  * Follow the memory chain starting at node and determine
355  * the mtp_property.
356  *
357  * @return mtp_property_const if only calls of const functions are detected
358  *         mtp_property_pure if only Loads and const/pure
359  *         calls detected
360  *         0 else
361  */
362 static unsigned follow_mem(ir_graph *irg, ir_node *node, unsigned mode) {
363   unsigned m;
364
365   inc_irg_visited(irg);
366   /* mark the initial mem: recursion stops here */
367   mark_irn_visited(get_irg_initial_mem(irg));
368   m = _follow_mem(node);
369   if (! m)
370     return 0;
371   return UMAX(mode, m);
372 }  /* follow_mwm */
373
374 /*
375  * Check if a graph represents a pure function.
376  *
377  * @param irg  the graph
378  */
379 static int is_pure_function(ir_graph *irg) {
380   ir_node *end, *endbl;
381   int j;
382   unsigned mode = get_irg_additional_properties(irg);
383   ir_graph *rem = current_ir_graph;
384
385   if (mode & mtp_property_const) {
386     /* already marked as a const function */
387     return mtp_property_const;
388   }
389   if (mode & mtp_property_pure) {
390     /* already marked as a pure function */
391     return mtp_property_const;
392   }
393
394   if (! IS_IRG_MARKED(irg))
395     return 0;
396   UNMARK_IRG(irg);
397
398   end   = get_irg_end(irg);
399   endbl = get_nodes_block(end);
400   mode  = mtp_property_const;
401
402   current_ir_graph = irg;
403
404   /* visit every Return */
405   for (j = get_Block_n_cfgpreds(endbl) - 1; j >= 0; --j) {
406     ir_node *node = get_Block_cfgpred(endbl, j);
407     ir_op   *op   = get_irn_op(node);
408     ir_node *mem;
409
410     /* Bad nodes usually do NOT produce anything, so it's ok */
411     if (op == op_Bad)
412       continue;
413
414     if (op == op_Return) {
415       mem = get_Return_mem(node);
416
417       /* Bad nodes usually do NOT produce anything, so it's ok */
418       if (is_Bad(mem))
419         continue;
420
421       if (mem != get_irg_initial_mem(irg))
422         mode = follow_mem(irg, mem, mode);
423     }
424     else {
425       /* exception found. */
426       mode = follow_mem(irg, mem, mode);
427       break;
428     }
429     if (mode == 0)
430       break;
431   }
432
433   if (mode != 0) {
434     /* check, if a keep-alive exists */
435     for (j = get_End_n_keepalives(end) - 1; j >= 0; --j) {
436       ir_node *mem = get_End_keepalive(end, j);
437
438       if (mode_M != get_irn_mode(mem))
439         continue;
440
441       mode = follow_mem(irg, mem, mode);
442       if (mode == 0)
443         break;
444     }
445   }
446
447   if (mode)
448     set_irg_additional_property(irg, mode);
449   current_ir_graph = rem;
450   return mode;
451 }  /* is_pure_function */
452
453 /**
454  * Handle calls to const functions.
455  */
456 static void handle_const_Calls(env_t *ctx)
457 {
458   int i;
459
460   ctx->n_calls_removed_SymConst = 0;
461   ctx->n_calls_removed_Sel      = 0;
462
463   /* all calls of const functions can be transformed */
464   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
465     ir_graph *irg  = get_irp_irg(i);
466
467     ctx->const_call_list = NULL;
468     ctx->pure_call_list  = NULL;
469     ctx->proj_list = NULL;
470     irg_walk_graph(irg, NULL, collect_calls, ctx);
471
472     if (ctx->const_call_list)
473       fix_const_call_list(irg, ctx->const_call_list, ctx->proj_list);
474   }
475 }  /* handle_const_Calls */
476
477 /*
478  * optimize function calls by handling const functions
479  */
480 void optimize_funccalls(int force_run)
481 {
482   int i, n;
483   unsigned num_const = 0;
484   unsigned num_pure  = 0;
485
486   if (! get_opt_function_call())
487     return;
488
489   /* prepare: mark all graphs as not analyzed */
490   n = get_irp_n_irgs();
491   for (i = n - 1; i >= 0; --i)
492     MARK_IRG(get_irp_irg(i));
493
494   /* first step: detect, which functions are const, i.e. do NOT touch any memory */
495   for (i = n - 1; i >= 0; --i) {
496     ir_graph *irg = get_irp_irg(i);
497     unsigned mode = is_pure_function(irg);
498
499     if (mode & mtp_property_const)
500       ++num_const;
501     else if (mode & mtp_property_pure)
502       ++num_pure;
503   }
504
505   if (force_run || num_const > 0) {
506     env_t ctx;
507
508     handle_const_Calls(&ctx);
509     if (get_firm_verbosity()) {
510       printf("Detected %d graphs without side effects.\n", num_const);
511       printf("Optimizes %d(SymConst) + %d(Sel) calls to const/pure functions.\n",
512                ctx.n_calls_removed_SymConst, ctx.n_calls_removed_Sel);
513     }
514   }
515   else {
516     if (get_firm_verbosity()) {
517       printf("No graphs without side effects detected\n");
518     }
519   }
520 }  /* optimize_funccalls */