Fixed some size_t related warnings.
[libfirm] / ir / opt / escape_ana.c
1 /*
2  * Copyright (C) 1995-2011 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  * Project:     libFIRM
22  * File name:   ir/opt/escape_ana.c
23  * Purpose:     escape analysis and optimization
24  * Author:      Michael Beck
25  * Modified by:
26  * Created:     03.11.2005
27  * CVS-ID:      $Id$
28  * Copyright:   (c) 1999-2005 Universität Karlsruhe
29  */
30
31 /**
32  * @file escape_ana.c
33  *
34  * A fast and simple Escape analysis.
35  */
36 #include "config.h"
37
38 #include "iroptimize.h"
39
40 #include "irgraph_t.h"
41 #include "irnode_t.h"
42 #include "type_t.h"
43 #include "irgwalk.h"
44 #include "irouts.h"
45 #include "analyze_irg_args.h"
46 #include "irgmod.h"
47 #include "ircons.h"
48 #include "irprintf.h"
49 #include "debug.h"
50 #include "error.h"
51
52 /**
53  * walker environment
54  */
55 typedef struct walk_env {
56   ir_node *found_allocs;            /**< list of all found non-escaped allocs */
57   ir_node *dead_allocs;             /**< list of all found dead alloc */
58   check_alloc_entity_func callback; /**< callback that checks a given entity for allocation */
59   unsigned nr_removed;              /**< number of removed allocs (placed of frame) */
60   unsigned nr_changed;              /**< number of changed allocs (allocated on stack now) */
61   unsigned nr_deads;                /**< number of dead allocs */
62
63   /* these fields are only used in the global escape analysis */
64   ir_graph *irg;                    /**< the irg for this environment */
65   struct walk_env *next;           /**< for linking environments */
66
67 } walk_env_t;
68
69 /** debug handle */
70 DEBUG_ONLY(firm_dbg_module_t *dbgHandle;)
71
72 /**
73  * checks whether a Raise leaves a method
74  */
75 static int is_method_leaving_raise(ir_node *raise)
76 {
77   int i;
78   ir_node *proj = NULL;
79   ir_node *n;
80
81   for (i = get_irn_n_outs(raise) - 1; i >= 0; --i) {
82     ir_node *succ = get_irn_out(raise, i);
83
84     /* there should be only one ProjX node */
85     if (get_Proj_proj(succ) == pn_Raise_X) {
86       proj = succ;
87       break;
88     }
89   }
90
91   if (! proj) {
92     /* Hmm: no ProjX from a Raise? This should be a verification
93      * error. For now we just assert and return.
94      */
95     panic("No ProjX after Raise found");
96   }
97
98   if (get_irn_n_outs(proj) != 1) {
99     /* Hmm: more than one user of ProjX: This is a verification
100      * error.
101      */
102     panic("More than one user of ProjX");
103   }
104
105   n = get_irn_out(proj, 0);
106   assert(is_Block(n) && "Argh: user of ProjX is no block");
107
108   if (n == get_irg_end_block(get_irn_irg(n)))
109     return 1;
110
111   /* ok, we get here so the raise will not leave the function */
112   return 0;
113 }
114
115 /**
116  * returns an Alloc node if the node adr Select
117  * from one
118  */
119 static ir_node *is_depend_alloc(ir_node *adr)
120 {
121   ir_node *alloc;
122
123   if (!is_Sel(adr))
124     return NULL;
125
126   /* should be a simple Sel */
127   if (get_Sel_n_indexs(adr) != 0)
128     return NULL;
129
130   alloc = skip_Proj(get_Sel_ptr(adr));
131   if (!is_Alloc(alloc))
132     return NULL;
133
134   /* hmm, we depend on this Alloc */
135   ir_printf("depend alloc %+F\n", alloc);
136
137   return NULL;
138 }
139
140 /**
141  * determine if a value calculated by n "escape", ie
142  * is stored somewhere we could not track
143  */
144 static int can_escape(ir_node *n)
145 {
146   int i;
147
148   /* should always be pointer mode or we made some mistake */
149   assert(mode_is_reference(get_irn_mode(n)));
150
151   for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
152     ir_node *succ = get_irn_out(n, i);
153
154     switch (get_irn_opcode(succ)) {
155     case iro_Store:
156       if (get_Store_value(succ) == n) {
157         ir_node *adr = get_Store_ptr(succ);
158
159         /*
160          * if this Alloc depends on another one,
161          * we can enqueue it
162          */
163         if (is_depend_alloc(adr))
164           break;
165
166         /*
167          * We are storing n. As long as we do not further
168          * evaluate things, the pointer 'escape' here
169          */
170         return 1;
171       }
172       break;
173
174     case iro_Conv:
175       /*
176        * Should not happen, but if it does we leave the pointer
177        * path and do not track further
178        */
179       return 1;
180
181     case iro_Call: { /* most complicated case */
182       ir_node *ptr = get_Call_ptr(succ);
183       ir_entity *ent;
184
185       if (is_SymConst_addr_ent(ptr)) {
186         size_t j;
187         ent = get_SymConst_entity(ptr);
188
189         /* we know the called entity */
190         for (j = get_Call_n_params(succ); j > 0;) {
191           if (get_Call_param(succ, --j) == n) {
192             /* n is the j'th param of the call */
193             if (get_method_param_access(ent, j) & ptr_access_store)
194               /* n is store in ent */
195               return 1;
196           }
197         }
198       } else if (is_Sel(ptr)) {
199         size_t k;
200
201         /* go through all possible callees */
202         for (k = get_Call_n_callees(succ); k > 0;) {
203           size_t j;
204           ent = get_Call_callee(succ, --k);
205
206           if (ent == unknown_entity) {
207             /* we don't know what will be called, a possible escape */
208             return 1;
209           }
210
211           for (j = get_Call_n_params(succ); j > 0;) {
212             if (get_Call_param(succ, --j) == n) {
213               /* n is the j'th param of the call */
214               if (get_method_param_access(ent, j) & ptr_access_store)
215                 /* n is store in ent */
216                 return 1;
217             }
218           }
219         }
220       } else /* we don't know want will called */
221         return 1;
222
223       break;
224     }
225
226     case iro_Return:
227       /* Bad: the allocate object is returned */
228       return 1;
229
230     case iro_Raise:
231       /* Hmm: if we do NOT leave the method, it's local */
232       if (is_method_leaving_raise(succ))
233         return 1;
234       break;
235
236     case iro_Tuple: {
237       ir_node *proj;
238       int j, k;
239
240       /* Bad: trace the tuple backwards */
241       for (j = get_irn_arity(succ) - 1; j >= 0; --j)
242         if (get_irn_n(succ, j) == n)
243           break;
244
245       assert(j >= 0);
246
247
248       for (k = get_irn_n_outs(succ); k >= 0; --k) {
249         proj = get_irn_out(succ, k);
250
251         if (get_Proj_proj(proj) == j) {
252           /* we found the right Proj */
253           succ = proj;
254           break;
255         }
256       }
257
258       /*
259        * If we haven't found the right Proj, succ is still
260        * the Tuple and the search will end here.
261        */
262       break;
263     }
264
265     default:
266       break;
267
268     }
269
270     if (! mode_is_reference(get_irn_mode(succ)))
271       continue;
272
273     if (can_escape(succ))
274       return 1;
275   }
276   return 0;
277 }
278
279 /**
280  * walker: search for Alloc nodes and follow the usages
281  */
282 static void find_allocations(ir_node *alloc, void *ctx)
283 {
284   walk_env_t *env = (walk_env_t*)ctx;
285   int i;
286   ir_node *adr;
287
288   if (! is_Alloc(alloc))
289     return;
290
291   /* we searching only for heap allocations */
292   if (get_Alloc_where(alloc) != heap_alloc)
293     return;
294
295   adr = NULL;
296   for (i = get_irn_n_outs(alloc) - 1; i >= 0; --i) {
297     ir_node *proj = get_irn_out(alloc, i);
298
299     if (get_Proj_proj(proj) == pn_Alloc_res) {
300       adr = proj;
301       break;
302     }
303   }
304
305   if (! adr) {
306     /*
307      * bad: no-one wants the result, should NOT happen but
308      * if it does we could delete it.
309      */
310     set_irn_link(alloc, env->dead_allocs);
311     env->dead_allocs = alloc;
312
313     return;
314   }
315
316   if (! can_escape(adr)) {
317     set_irn_link(alloc, env->found_allocs);
318     env->found_allocs = alloc;
319   }
320 }
321
322 /**
323  * walker: search for allocation Call nodes and follow the usages
324  */
325 static void find_allocation_calls(ir_node *call, void *ctx)
326 {
327   walk_env_t *env = (walk_env_t*)ctx;
328   int        i;
329   ir_node    *adr;
330   ir_entity  *ent;
331
332   if (! is_Call(call))
333     return;
334   adr = get_Call_ptr(call);
335   if (! is_SymConst_addr_ent(adr))
336     return;
337   ent = get_SymConst_entity(adr);
338   if (! env->callback(ent))
339     return;
340
341   adr = NULL;
342   for (i = get_irn_n_outs(call) - 1; i >= 0; --i) {
343     ir_node *res_proj = get_irn_out(call, i);
344
345     if (get_Proj_proj(res_proj) == pn_Call_T_result) {
346       for (i = get_irn_n_outs(res_proj) - 1; i >= 0; --i) {
347         ir_node *proj = get_irn_out(res_proj, i);
348
349         if (get_Proj_proj(proj) == 0) {
350           /* found first result */
351           adr = proj;
352           break;
353         }
354       }
355       break;
356     }
357   }
358
359   if (! adr) {
360     /*
361      * bad: no-one wants the result, should NOT happen but
362      * if it does we could delete it.
363      */
364     set_irn_link(call, env->dead_allocs);
365     env->dead_allocs = call;
366
367     return;
368   }
369
370   if (! can_escape(adr)) {
371     set_irn_link(call, env->found_allocs);
372     env->found_allocs = call;
373   }
374 }
375
376 /**
377  * Do the necessary graph transformations to transform
378  * Alloc nodes.
379  */
380 static void transform_allocs(ir_graph *irg, walk_env_t *env)
381 {
382   ir_node *alloc, *next, *mem, *sel, *size, *blk;
383   ir_type *ftp, *atp, *tp;
384   ir_entity *ent;
385   char name[128];
386   unsigned nr = 0;
387   dbg_info *dbg;
388
389   /* kill all dead allocs */
390   for (alloc = env->dead_allocs; alloc; alloc = next) {
391     next = (ir_node*)get_irn_link(alloc);
392
393     DBG((dbgHandle, LEVEL_1, "%+F allocation of %+F unused, deleted.\n", irg, alloc));
394
395     mem = get_Alloc_mem(alloc);
396         blk = get_nodes_block(alloc);
397     turn_into_tuple(alloc, pn_Alloc_max);
398     set_Tuple_pred(alloc, pn_Alloc_M, mem);
399     set_Tuple_pred(alloc, pn_Alloc_X_regular, new_r_Jmp(blk));
400     set_Tuple_pred(alloc, pn_Alloc_X_except, new_r_Bad(irg));
401
402     ++env->nr_deads;
403   }
404
405   /* convert all non-escaped heap allocs into frame variables */
406   ftp = get_irg_frame_type(irg);
407   for (alloc = env->found_allocs; alloc; alloc = next) {
408     next = (ir_node*)get_irn_link(alloc);
409     size = get_Alloc_count(alloc);
410     atp  = get_Alloc_type(alloc);
411
412     tp = NULL;
413     if (is_SymConst(size) && get_SymConst_kind(size) == symconst_type_size)  {
414       /* if the size is a type size and the types matched */
415       assert(atp == get_SymConst_type(size));
416       tp = atp;
417     } else if (is_Const(size)) {
418       ir_tarval *tv = get_Const_tarval(size);
419
420       if (tv != tarval_bad && tarval_is_long(tv) &&
421           get_type_state(atp) == layout_fixed &&
422           (unsigned)get_tarval_long(tv) == get_type_size_bytes(atp)) {
423         /* a already lowered type size */
424         tp = atp;
425       }
426     }
427
428     if (tp && tp != firm_unknown_type) {
429       /* we could determine the type, so we could place it on the frame */
430       dbg  = get_irn_dbg_info(alloc);
431       blk  = get_nodes_block(alloc);
432
433       DBG((dbgHandle, LEVEL_DEFAULT, "%+F allocation of %+F type %+F placed on frame\n", irg, alloc, tp));
434
435       snprintf(name, sizeof(name), "%s_NE_%u", get_entity_name(get_irg_entity(irg)), nr++);
436       name[sizeof(name) - 1] = '\0';
437       ent = new_d_entity(ftp, new_id_from_str(name), get_Alloc_type(alloc), dbg);
438
439       sel = new_rd_simpleSel(dbg, get_nodes_block(alloc), get_irg_no_mem(irg), get_irg_frame(irg), ent);
440       mem = get_Alloc_mem(alloc);
441
442       turn_into_tuple(alloc, pn_Alloc_max);
443       set_Tuple_pred(alloc, pn_Alloc_M, mem);
444           set_Tuple_pred(alloc, pn_Alloc_X_regular, new_r_Jmp(blk));
445       set_Tuple_pred(alloc, pn_Alloc_X_except, new_r_Bad(irg));
446       set_Tuple_pred(alloc, pn_Alloc_res, sel);
447
448       ++env->nr_removed;
449     }
450     else {
451       /*
452        * We could not determine the type or it is variable size.
453        * At least, we could place it on the stack
454        */
455       DBG((dbgHandle, LEVEL_DEFAULT, "%+F allocation of %+F type %+F placed on stack\n", irg, alloc));
456       set_Alloc_where(alloc, stack_alloc);
457
458       ++env->nr_changed;
459     }
460   }
461
462   /* if allocs were removed somehow */
463   if (env->nr_removed | env->nr_deads) {
464     set_irg_outs_inconsistent(irg);
465
466     if (env->nr_deads) {
467       /* exception control flow might have been changed */
468       set_irg_doms_inconsistent(irg);
469     }
470   }
471 }
472
473 /**
474  * Do the necessary graph transformations to transform
475  * Call nodes.
476  */
477 static void transform_alloc_calls(ir_graph *irg, walk_env_t *env)
478 {
479   ir_node *call, *next, *mem, *blk;
480   ir_type *ftp;
481
482   /* kill all dead allocs */
483   for (call = env->dead_allocs; call; call = next) {
484     next = (ir_node*)get_irn_link(call);
485
486     DBG((dbgHandle, LEVEL_1, "%+F allocation of %+F unused, deleted.\n", irg, call));
487
488     mem = get_Call_mem(call);
489         blk = get_nodes_block(call);
490     turn_into_tuple(call, pn_Call_max);
491     set_Tuple_pred(call, pn_Call_M,                mem);
492         set_Tuple_pred(call, pn_Call_X_regular,        new_r_Jmp(blk));
493     set_Tuple_pred(call, pn_Call_X_except,         new_r_Bad(irg));
494     set_Tuple_pred(call, pn_Call_T_result,         new_r_Bad(irg));
495
496     ++env->nr_deads;
497   }
498
499   /* convert all non-escaped heap allocs into frame variables */
500   ftp = get_irg_frame_type(irg);
501   for (call = env->found_allocs; call; call = next) {
502     next = (ir_node*)get_irn_link(call);
503   }
504 }
505
506
507 /* Do simple and fast escape analysis for one graph. */
508 void escape_enalysis_irg(ir_graph *irg, check_alloc_entity_func callback)
509 {
510   walk_env_t env;
511
512   if (get_irg_callee_info_state(irg) != irg_callee_info_consistent) {
513     /* no way yet to calculate this for one irg */
514     assert(! "need callee info");
515     return;
516   }
517
518   if (get_irg_outs_state(irg) != outs_consistent)
519     compute_irg_outs(irg);
520
521   env.found_allocs = NULL;
522   env.dead_allocs  = NULL;
523   env.callback     = callback;
524   env.nr_removed   = 0;
525   env.nr_changed   = 0;
526   env.nr_deads     = 0;
527
528   if (callback) {
529     /* search for Calls */
530     irg_walk_graph(irg, NULL, find_allocation_calls, &env);
531     transform_alloc_calls(irg, &env);
532   } else {
533     /* search for Alloc nodes */
534     irg_walk_graph(irg, NULL, find_allocations, &env);
535     transform_allocs(irg, &env);
536   }
537 }
538
539 /* Do simple and fast escape analysis for all graphs. */
540 void escape_analysis(int run_scalar_replace, check_alloc_entity_func callback)
541 {
542   size_t i, n;
543   struct obstack obst;
544   walk_env_t *env, *elist;
545   (void) run_scalar_replace;
546
547   if (get_irp_callee_info_state() != irg_callee_info_consistent) {
548     assert(! "need callee info");
549     return;
550   }
551
552   FIRM_DBG_REGISTER(dbgHandle, "firm.opt.escape_ana");
553
554   /*
555    * We treat memory for speed: we first collect all info in a
556    * list of environments, than do the transformation.
557    * Doing it this way, no analysis info gets invalid while we run
558    * over graphs
559    */
560   obstack_init(&obst);
561   elist = NULL;
562
563   env = OALLOC(&obst, walk_env_t);
564   env->found_allocs = NULL;
565   env->dead_allocs  = NULL;
566   env->callback     = callback;
567
568   for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
569     ir_graph *irg = get_irp_irg(i);
570
571     assure_irg_outs(irg);
572
573     if (callback) {
574       /* search for Calls */
575       irg_walk_graph(irg, NULL, find_allocation_calls, env);
576     } else {
577       /* search for Alloc nodes */
578       irg_walk_graph(irg, NULL, find_allocations, env);
579     }
580
581     if (env->found_allocs || env->dead_allocs) {
582       env->nr_removed   = 0;
583       env->nr_deads     = 0;
584       env->irg          = irg;
585       env->next         = elist;
586
587       elist = env;
588
589       env = OALLOC(&obst, walk_env_t);
590       env->found_allocs = NULL;
591       env->dead_allocs  = NULL;
592       env->callback     = callback;
593     }
594   }
595
596   if (callback) {
597     for (env = elist; env; env = env->next) {
598       transform_alloc_calls(env->irg, env);
599     }
600   } else {
601     for (env = elist; env; env = env->next) {
602       transform_allocs(env->irg, env);
603     }
604   }
605
606   obstack_free(&obst, NULL);
607 }