- check for peculiarity_description for inner functions
[libfirm] / ir / ana / cgana.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      Intraprozedural analyses to estimate the call graph.
23  * @author     Hubert Schmid
24  * @date       09.06.2002
25  * @version    $Id$
26  * @summary
27  *  Interprocedural analysis to estimate the calling relation.
28  *
29  *  This analysis computes all entities representing methods that
30  *  can be called at a Call node.  Further it computes a set of
31  *  methods that are 'free', i.e., their adress is handled by
32  *  the program directly, or they are visible external.
33  */
34 #include "config.h"
35
36 # include <string.h>
37
38 #include "cgana.h"
39 #include "rta.h"
40
41 #include "xmalloc.h"
42 #include "irnode_t.h"
43 #include "irmode_t.h"
44 #include "irprog_t.h"
45 #include "irgwalk.h"
46 #include "ircons.h"
47 #include "irgmod.h"
48 #include "iropt.h"
49 #include "irtools.h"
50
51 #include "irflag_t.h"
52 #include "dbginfo_t.h"
53 #include "iropt_dbg.h"
54
55 #include "eset.h"
56 #include "pmap.h"
57 #include "array.h"
58 #include "error.h"
59
60 #include "irdump.h"
61
62 /* unambiguous address used as a mark. */
63 static void *MARK = &MARK;
64
65 static eset *entities = NULL;
66
67 /*--------------------------------------------------------------------------*/
68 /* The analysis                                                             */
69 /*--------------------------------------------------------------------------*/
70
71
72 /*--------------------------------------------------------------------------*/
73 /* Initialize datastructures, remove unwanted constructs, optimize          */
74 /* call target computations.                                                */
75 /*--------------------------------------------------------------------------*/
76
77 /** Returns the entity that contains the implementation of the inherited
78  *  entity if available, else returns the entity passed. */
79 static ir_entity *get_inherited_methods_implementation(ir_entity *inh_meth) {
80         ir_node *value = get_atomic_ent_value(inh_meth);
81         assert(value && "constant entity without value");
82         assert(is_SymConst_addr_ent(value) &&
83                "Complex constant values not supported -- address of method should be straight constant!");
84
85         return get_SymConst_entity(value);
86 }
87
88 /** Collect the entity representing the implementation of this
89  *  method (not the same if inherited) and all entities for overwriting
90  *  implementations in "set".
91  *  If the implementation of the method is not included in the
92  *  compilation unit "open" is set to true.
93  *  A recursive descend in the overwritten relation.
94  *  Cycle-free, therefore must terminate.
95  *
96  * @param method
97  * @param set      A set of entities.
98  * @param size     Number of entities in set.
99  * @param open
100  */
101 static void collect_impls(ir_entity *method, eset *set, int *size, int *open) {
102         int i;
103         ir_entity *impl;
104
105         /* Add the implementation to the set if it contains an irg, else
106            remember that there are more methods called. */
107         impl = method;
108         if (get_entity_peculiarity(method) == peculiarity_inherited)
109                 impl = get_inherited_methods_implementation(method);
110
111         if (get_entity_peculiarity(method) != peculiarity_description) {
112                 eset_insert(set, impl);
113                 ++(*size);
114         }
115
116         /*- recursive descent -*/
117         for (i = get_entity_n_overwrittenby(method) - 1; i >= 0; --i)
118                 collect_impls(get_entity_overwrittenby(method, i), set, size, open);
119 }
120
121 /** Alle Methoden bestimmen, die die übergebene Methode überschreiben
122  *  (und implementieren). In der zurückgegebenen Reihung kommt jede
123  *  Methode nur einmal vor. Der Wert 'NULL' steht für unbekannte
124  *  (externe) Methoden. Die zurückgegebene Reihung muß vom Aufrufer
125  *  wieder freigegeben werden (siehe "DEL_ARR_F"). Gibt es überhaupt
126  *  keine Methoden, die "method" überschreiben, so gibt die Methode
127  *  "NULL" zurück.
128  *
129  *  @param method
130  */
131 static ir_entity ** get_impl_methods(ir_entity * method) {
132         eset * set = eset_create();
133         int size = 0;
134         ir_entity ** arr;
135         int open = 0;
136
137         /* Collect all method entities that can be called here */
138         collect_impls(method, set, &size, &open);
139
140         /* Vorgaenger einfuegen. */
141         if (size == 0 && !open) {
142                 /* keine implementierte überschriebene Methode */
143                 arr = NULL;
144         } else if (open) {
145                 ir_entity * ent;
146                 arr = NEW_ARR_F(ir_entity *, size + 1);
147                 arr[0] = NULL;  /* Represents open method */
148                 for (ent = eset_first(set); size > 0; ent = eset_next(set), --size)
149                         arr[size] = ent;
150         } else {
151                 ir_entity * ent;
152                 arr = NEW_ARR_F(ir_entity *, size);
153                 for (size -= 1, ent = eset_first(set); size >= 0; ent = eset_next(set), --size)
154                         arr[size] = ent;
155         }
156         eset_destroy(set);
157         return arr;
158 }
159
160 /** Analyze address computations.
161  *
162  *  Compute for all Sel nodes the set of methods that can be selected.
163  *  For each entity we store the set of subentities in the link field.
164  *
165  *  Further do some optimizations:
166  *  - Call standard optimizations for Sel nodes: this removes polymorphic
167  *    calls.
168  *  - If the node is a SymConst(name) replace it by SymConst(ent) if possible.
169  *    For this we precomputed a map name->entity.  Nowadays, we no more support
170  *    this and assert.
171  *  - If the node is a Sel:
172  *    If we found only a single method that can be called, replace the Sel
173  *    by a SymConst.  This is more powerful than the analysis in opt_polymorphy,
174  *    as here we walk the type graph.  In opt_polymorphy we only apply a local
175  *    pattern.
176  *
177  *  @param node  The node to analyze
178  *  @param env   A map that maps names of entities to the entities.
179  */
180 static void sel_methods_walker(ir_node *node, void *env) {
181         pmap *ldname_map = env;
182         ir_entity **arr;
183
184         /* Call standard optimizations */
185         if (is_Sel(node)) {
186                 ir_node *new_node = optimize_in_place(node);
187                 if (node != new_node) {
188                         exchange(node, new_node);
189                         node = new_node;
190                 }
191         }
192
193         /* replace SymConst(name)-operations by SymConst(ent) */
194         if (is_SymConst(node)) {
195                 if (get_SymConst_kind(node) == symconst_addr_name) {
196                         pmap_entry *entry = pmap_find(ldname_map, get_SymConst_name(node));
197                         if (entry != NULL) { /* Method is declared in the compiled code */
198                                 assert(!"There should not be a SymConst[addr_name] addressing a method with an implementation"
199                                         "in this compilation unit.  Use a SymConst[addr_ent].");
200                         }
201                 }
202         } else if (is_Sel(node) && is_Method_type(get_entity_type(get_Sel_entity(node)))) {
203                 ir_entity *ent = get_SymConst_entity(get_atomic_ent_value(get_Sel_entity(node)));
204                 assert(get_entity_peculiarity(ent) != peculiarity_inherited);
205
206                 if (!eset_contains(entities, ent)) {
207                         /* Entity not yet handled. Find all (internal or external)
208                          * implemented methods that overwrites this entity.
209                          * This set is stored in the entity link. */
210                         set_entity_link(ent, get_impl_methods(ent));
211                         eset_insert(entities, ent);
212                 }
213
214                 /* -- As an add on we get an optimization that removes polymorphic calls.
215                 This optimization is more powerful than that in transform_node_Sel().  -- */
216                 arr = get_entity_link(ent);
217                 if (arr == NULL) {
218                         /*
219                          * The Sel node never returns a pointer to a usable method.
220                          * We could not call it, but it may be description:
221                          * We call a method in a dead part of the program.
222                          */
223                         assert(get_entity_peculiarity(ent) == peculiarity_description);
224                 }
225                 else if (get_opt_closed_world() && get_opt_dyn_meth_dispatch() &&
226                         (ARR_LEN(arr) == 1 && arr[0] != NULL)) {
227                         ir_node *new_node;
228
229                         /*
230                          * The Sel node returns only one possible method.
231                          * So we could replace the Sel node by a SymConst.
232                          * This method must exists.
233                          */
234                         set_irg_current_block(current_ir_graph, get_nodes_block(node));
235                         assert(get_entity_peculiarity(get_SymConst_entity(get_atomic_ent_value(arr[0]))) ==
236                                 peculiarity_existent);
237                         new_node = copy_const_value(get_irn_dbg_info(node), get_atomic_ent_value(arr[0]));
238                         DBG_OPT_POLY(node, new_node);
239                         exchange(node, new_node);
240                 }
241         }
242 }
243
244 /**
245  * Initialize auxiliary data structures.
246  *
247  * Computes a set of entities that overwrite an entity and contain
248  * an implementation. The set is stored in the entity's link field.
249  *
250  * Further replaces Sel nodes where this set contains exactly one
251  * method by SymConst nodes.
252  * Finally asserts if there is a SymConst(name) if there could be a
253  * SymConst(ent).
254  */
255 static void sel_methods_init(void) {
256         int i;
257         pmap *ldname_map = pmap_create();   /* Map entity names to entities: to replace
258                                                SymConst(name) by SymConst(ent). */
259         assert(entities == NULL);
260         entities = eset_create();
261         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
262                 ir_entity * ent = get_irg_entity(get_irp_irg(i));
263                 /* only external visible methods are allowed to call by a SymConst_ptr_name */
264                 if (get_entity_visibility(ent) != visibility_local) {
265                         pmap_insert(ldname_map, (void *)get_entity_ld_ident(ent), ent);
266                 }
267         }
268
269         all_irg_walk(sel_methods_walker, NULL, ldname_map);
270         pmap_destroy(ldname_map);
271 }
272
273 /*--------------------------------------------------------------------------*/
274 /* Find free methods.
275  *
276  * We expect that each entity has an array with all implementations in its
277  * link field.                                                              */
278 /*--------------------------------------------------------------------------*/
279
280 /**
281  * Returns an array of all methods that could be called at a Sel node.
282  * This array contains every entry only once.
283  *
284  * @param sel  the Sel node
285  */
286 static ir_entity ** get_Sel_arr(ir_node * sel) {
287         static ir_entity ** NULL_ARRAY = NULL;
288         ir_entity * ent;
289         ir_entity ** arr;
290
291         assert(is_Sel(sel));
292         ent = get_Sel_entity(sel);
293         ent = get_inherited_methods_implementation(ent);
294
295         assert(is_Method_type(get_entity_type(ent))); /* what else? */
296         arr = get_entity_link(ent);
297         if (arr) {
298                 return arr;
299         } else {
300                 /* "NULL" zeigt an, dass keine Implementierung existiert. Dies
301                  * kann für polymorphe (abstrakte) Methoden passieren. */
302                 if (!NULL_ARRAY) {
303                         NULL_ARRAY = NEW_ARR_F(ir_entity *, 0);
304                 }
305                 return NULL_ARRAY;
306         }
307 }
308
309 /**
310  * Returns the number of possible called methods at a Sel node.
311  *
312  * @param sel  the Sel node
313  */
314 static int get_Sel_n_methods(ir_node * sel) {
315         return ARR_LEN(get_Sel_arr(sel));
316 }
317
318 /**
319  * Returns the ith possible called method entity at a Sel node.
320  */
321 static ir_entity * get_Sel_method(ir_node * sel, int pos) {
322         ir_entity ** arr = get_Sel_arr(sel);
323         assert(pos >= 0 && pos < ARR_LEN(arr));
324         return arr[pos];
325 }
326
327 /* forward */
328 static void free_mark(ir_node * node, eset * set);
329
330 static void free_mark_proj(ir_node * node, long n, eset * set) {
331         assert(get_irn_mode(node) == mode_T);
332         if (get_irn_link(node) == MARK) {
333                 /* already visited */
334                 return;
335         }
336         set_irn_link(node, MARK);
337         switch (get_irn_opcode(node)) {
338         case iro_Proj: {
339                 /* proj_proj: in einem "sinnvollen" Graphen kommt jetzt ein
340                  * op_Tuple oder ein Knoten, der in "free_ana_walker" behandelt
341                  * wird. */
342                 ir_node * pred = get_Proj_pred(node);
343                 if (get_irn_link(pred) != MARK && is_Tuple(pred)) {
344                         free_mark_proj(get_Tuple_pred(pred, get_Proj_proj(node)), n, set);
345                 } else {
346                         /* nothing: da in "free_ana_walker" behandelt. */
347                 }
348                 break;
349         }
350
351         case iro_Tuple:
352                 free_mark(get_Tuple_pred(node, n), set);
353                 break;
354
355         case iro_Id:
356                 free_mark_proj(get_Id_pred(node), n, set);
357                 break;
358
359         case iro_Start:
360         case iro_Alloc:
361         case iro_Load:
362                 /* nothing: Die Operationen werden in free_ana_walker() selbst
363                  * behandelt. */
364                 break;
365
366         default:
367                 assert(0 && "unexpected opcode or opcode not implemented");
368                 break;
369         }
370         // set_irn_link(node, NULL);
371 }
372
373 /**
374  * Called for predecessors nodes of "interesting" ones.
375  * Interesting ones include all nodes that can somehow make
376  * a method visible.
377  *
378  * If a method (or a set of methods in case of polymorph calls) gets visible,
379  * add it to the set of 'free' methods
380  *
381  * @param node  the current visited node
382  * @param set   the set of all free methods
383  */
384 static void free_mark(ir_node *node, eset * set) {
385         int i;
386
387         if (get_irn_link(node) == MARK)
388                 return; /* already visited */
389
390         set_irn_link(node, MARK);
391
392         switch (get_irn_opcode(node)) {
393         case iro_Sel: {
394                 ir_entity *ent = get_Sel_entity(node);
395                 if (is_method_entity(ent)) {
396                         for (i = get_Sel_n_methods(node) - 1; i >= 0; --i) {
397                                 eset_insert(set, get_Sel_method(node, i));
398                         }
399                 }
400                 break;
401         }
402         case iro_SymConst:
403                 if (get_SymConst_kind(node) == symconst_addr_ent) {
404                         ir_entity *ent = get_SymConst_entity(node);
405                         if (is_method_entity(ent)) {
406                                 eset_insert(set, ent);
407                         }
408                 } else {
409                         assert(get_SymConst_kind(node) == symconst_addr_name);
410                         /* nothing: SymConst points to extern method */
411                 }
412                 break;
413
414         case iro_Phi:
415                 for (i = get_Phi_n_preds(node) - 1; i >= 0; --i) {
416                         free_mark(get_Phi_pred(node, i), set);
417                 }
418                 break;
419         case iro_Proj:
420                 free_mark_proj(get_Proj_pred(node), get_Proj_proj(node), set);
421                 break;
422         default:
423                 /* nothing: */
424                 break;
425         }
426 }
427
428 /**
429  * post-walker. Find method addresses.
430  */
431 static void free_ana_walker(ir_node *node, void *env) {
432         eset *set = env;
433         int i;
434
435         if (get_irn_link(node) == MARK) {
436                 /* already visited */
437                 return;
438         }
439         switch (get_irn_opcode(node)) {
440                 /* special nodes */
441         case iro_Sel:
442         case iro_SymConst:
443         case iro_Const:
444         case iro_Phi:
445         case iro_Id:
446         case iro_Proj:
447         case iro_Tuple:
448                 /* nothing */
449                 break;
450         case iro_Call:
451                 /* we must handle Call nodes specially, because their call address input
452                    do not expose a method address. */
453                 set_irn_link(node, MARK);
454                 for (i = get_Call_n_params(node) - 1; i >= 0; --i) {
455                         ir_node *pred = get_Call_param(node, i);
456                         if (mode_is_reference(get_irn_mode(pred))) {
457                                 free_mark(pred, set);
458                         }
459                 }
460                 break;
461         default:
462                 /* other nodes: Alle anderen Knoten nehmen wir als Verräter an, bis
463                  * jemand das Gegenteil implementiert. */
464                 set_irn_link(node, MARK);
465                 for (i = get_irn_arity(node) - 1; i >= 0; --i) {
466                         ir_node *pred = get_irn_n(node, i);
467                         if (mode_is_reference(get_irn_mode(pred))) {
468                                 free_mark(pred, set);
469                         }
470                 }
471                 break;
472         }
473 }
474
475 /**
476  * Add all method addresses in global new style initializers to the set.
477  *
478  * @note
479  * We do NOT check the type here, just it it's an entity address.
480  * The reason for this is code like:
481  *
482  * void *p = function;
483  *
484  * which is sometimes used to anchor functions.
485  */
486 static void add_method_address_inititializer(ir_initializer_t *initializer,
487                                              eset *set)
488 {
489         ir_node *n;
490         size_t  i;
491
492         switch (initializer->kind) {
493         case IR_INITIALIZER_CONST:
494                 n = initializer->consti.value;
495
496                 /* let's check if it's the address of a function */
497                 if (is_Global(n)) {
498                         ir_entity *ent = get_Global_entity(n);
499
500                         if (is_Method_type(get_entity_type(ent)))
501                                 eset_insert(set, ent);
502                 }
503                 return;
504         case IR_INITIALIZER_TARVAL:
505         case IR_INITIALIZER_NULL:
506                 return;
507         case IR_INITIALIZER_COMPOUND:
508                 for (i = 0; i < initializer->compound.n_initializers; ++i) {
509                         ir_initializer_t *sub_initializer
510                                 = initializer->compound.initializers[i];
511                         add_method_address_inititializer(sub_initializer, set);
512                 }
513                 return;
514         }
515         panic("invalid initializer found");
516 }
517
518 /**
519  * Add all method addresses in global initializers to the set.
520  *
521  * @note
522  * We do NOT check the type here, just it it's an entity address.
523  * The reason for this is code like:
524  *
525  * void *p = function;
526  *
527  * which is sometimes used to anchor functions.
528  */
529 static void add_method_address(ir_entity *ent, eset *set)
530 {
531         ir_node *n;
532         ir_type *tp;
533         int i;
534
535         /* do not check uninitialized values */
536         if (get_entity_variability(ent) == variability_uninitialized)
537                 return;
538
539         if (ent->has_initializer) {
540                 add_method_address_inititializer(get_entity_initializer(ent), set);
541         } else if (is_atomic_entity(ent)) {
542                 tp = get_entity_type(ent);
543
544                 /* ignore methods: these of course reference it's address */
545                 if (is_Method_type(tp))
546                         return;
547
548                 /* let's check if it's the address of a function */
549                 n = get_atomic_ent_value(ent);
550                 if (is_Global(n)) {
551                         ent = get_Global_entity(n);
552
553                         if (is_Method_type(get_entity_type(ent)))
554                                 eset_insert(set, ent);
555                 }
556         } else {
557                 for (i = get_compound_ent_n_values(ent) - 1; i >= 0; --i) {
558                         n = get_compound_ent_value(ent, i);
559
560                         /* let's check if it's the address of a function */
561                         if (is_Global(n)) {
562                                 ir_entity *ent = get_Global_entity(n);
563
564                                 if (is_Method_type(get_entity_type(ent)))
565                                         eset_insert(set, ent);
566                         }
567                 }
568         }
569 }
570
571 /**
572  * returns a list of 'free' methods, i.e., the methods that can be called
573  * from external or via function pointers.
574  *
575  * Die Datenstrukturen für sel-Methoden (sel_methods) muß vor dem
576  * Aufruf von "get_free_methods" aufgebaut sein. Die (internen)
577  * SymConst(name)-Operationen müssen in passende SymConst(ent)-Operationen
578  * umgewandelt worden sein, d.h. SymConst-Operationen verweisen immer
579  * auf eine echt externe Methode.
580  */
581 static ir_entity **get_free_methods(int *length)
582 {
583         eset *free_set = eset_create();
584         int i;
585         ir_entity **arr;
586         ir_entity *ent;
587         ir_graph *irg;
588         ir_type *tp;
589
590         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
591                 irg = get_irp_irg(i);
592                 ent = get_irg_entity(irg);
593                 if (get_entity_visibility(ent) != visibility_local) {
594                         /* insert non-local (external) methods. */
595                         eset_insert(free_set, ent);
596                 } else if (get_entity_stickyness(ent) == stickyness_sticky) {
597                         /* insert "sticky" methods. */
598                         eset_insert(free_set, ent);
599                 }
600
601                 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
602                 /* Find all method entities that gets "visible" through this graphs,
603                  * for instance because their address is stored. */
604                 irg_walk_graph(irg, firm_clear_link, free_ana_walker, free_set);
605                 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
606         }
607
608         /* insert all methods that are used in global variables initializers */
609         tp = get_glob_type();
610         for (i = get_class_n_members(tp) - 1; i >= 0; --i) {
611                 ent = get_class_member(tp, i);
612                 add_method_address(ent, free_set);
613         }
614         tp = get_tls_type();
615         for (i = get_struct_n_members(tp) - 1; i >= 0; --i) {
616                 ent = get_struct_member(tp, i);
617                 add_method_address(ent, free_set);
618         }
619
620         /* the main program is even then "free", if it's not external visible. */
621         irg = get_irp_main_irg();
622         if (irg != NULL)
623                 eset_insert(free_set, get_irg_entity(irg));
624
625         /* Finally, transform the set into an array. */
626         *length = eset_count(free_set);
627         arr = XMALLOCN(ir_entity*, *length);
628         for (i = 0, ent = eset_first(free_set); ent; ent = eset_next(free_set)) {
629                 arr[i++] = ent;
630         }
631         eset_destroy(free_set);
632
633         return arr;
634 }
635
636 /*--------------------------------------------------------------------------*/
637 /* Callee analysis.                                                         */
638 /*--------------------------------------------------------------------------*/
639
640 static void callee_ana_node(ir_node * node, eset * methods);
641
642 static void callee_ana_proj(ir_node *node, long n, eset *methods) {
643         assert(get_irn_mode(node) == mode_T);
644         if (get_irn_link(node) == MARK) {
645                 /* already visited */
646                 return;
647         }
648         set_irn_link(node, MARK);
649
650         switch (get_irn_opcode(node)) {
651         case iro_Proj: {
652                 /* proj_proj: in einem "sinnvollen" Graphen kommt jetzt ein
653                  * op_Tuple oder ein Knoten, der eine "freie Methode"
654                  * zurückgibt. */
655                 ir_node *pred = get_Proj_pred(node);
656                 if (get_irn_link(pred) != MARK) {
657                         if (is_Tuple(pred)) {
658                                 callee_ana_proj(get_Tuple_pred(pred, get_Proj_proj(node)), n, methods);
659                         } else {
660                                 eset_insert(methods, unknown_entity); /* free method -> unknown */
661                         }
662                 }
663                 break;
664         }
665
666         case iro_Tuple:
667                 callee_ana_node(get_Tuple_pred(node, n), methods);
668                 break;
669
670         default:
671                 eset_insert(methods, unknown_entity); /* free method -> unknown */
672                 break;
673         }
674 }
675
676 /**
677  * Analyse a Call address.
678  *
679  * @param node     the node representing the call address
680  * @param methods  after call contains the set of all possibly called entities
681  */
682 static void callee_ana_node(ir_node *node, eset *methods) {
683         int i;
684
685         assert(mode_is_reference(get_irn_mode(node)) || is_Bad(node));
686         /* Beware of recursion */
687         if (get_irn_link(node) == MARK) {
688                 /* already visited */
689                 return;
690         }
691         set_irn_link(node, MARK);
692
693         switch (get_irn_opcode(node)) {
694         case iro_Const:
695                 /* A direct address call. We tread this as an external
696                    call and ignore it completely. */
697                 eset_insert(methods, unknown_entity); /* free method -> unknown */
698                 break;
699         case iro_SymConst:
700                 if (get_SymConst_kind(node) == symconst_addr_ent) {
701                         ir_entity *ent = get_SymConst_entity(node);
702                         assert(ent && is_method_entity(ent));
703                         eset_insert(methods, ent);
704                 } else {
705                         assert(get_SymConst_kind(node) == symconst_addr_name);
706                         /* external method (because fix_symconst()!) */
707                         eset_insert(methods, unknown_entity); /* free method -> unknown */
708                 }
709                 break;
710         case iro_Sel:
711                 /* polymorphic method */
712                 for (i = get_Sel_n_methods(node) - 1; i >= 0; --i) {
713                         ir_entity *ent = get_Sel_method(node, i);
714                         if (ent != NULL) {
715                                 eset_insert(methods, ent);
716                         } else {
717                                 eset_insert(methods, unknown_entity);
718                         }
719                 }
720                 break;
721
722         case iro_Bad:
723                 /* nothing */
724                 break;
725
726         case iro_Phi:
727                 for (i = get_Phi_n_preds(node) - 1; i >= 0; --i) {
728                         callee_ana_node(get_Phi_pred(node, i), methods);
729                 }
730                 break;
731
732         case iro_Mux:
733                 callee_ana_node(get_Mux_false(node), methods);
734                 callee_ana_node(get_Mux_true(node), methods);
735                 break;
736
737         case iro_Id:
738                 callee_ana_node(get_Id_pred(node), methods);
739                 break;
740
741         case iro_Proj:
742                 callee_ana_proj(get_Proj_pred(node), get_Proj_proj(node), methods);
743                 break;
744
745         case iro_Add:
746         case iro_Sub:
747         case iro_Conv:
748                 /* extern */
749                 eset_insert(methods, unknown_entity); /* free method -> unknown */
750                 break;
751
752         default:
753                 assert(0 && "invalid opcode or opcode not implemented");
754                 break;
755         }
756 }
757
758 /**
759  * Walker: Analyses every Call node and calculates an array of possible
760  * callees for that call.
761  */
762 static void callee_walker(ir_node *call, void *env) {
763         (void) env;
764         if (is_Call(call)) {
765                 eset *methods = eset_create();
766                 ir_entity *ent;
767                 ir_entity **arr;
768                 int i;
769
770                 callee_ana_node(get_Call_ptr(call), methods);
771                 arr = NEW_ARR_F(ir_entity *, eset_count(methods));
772                 for (i = 0, ent = eset_first(methods); ent; ent = eset_next(methods)) {
773                         arr[i] = ent;
774                         /* we want the unknown_entity on the zero position for easy tests later */
775                         if (ent == unknown_entity) {
776                                 arr[i] = arr[0];
777                                 arr[0] = unknown_entity;
778                         }
779                         ++i;
780                 }
781                 set_Call_callee_arr(call, ARR_LEN(arr), arr);
782                 DEL_ARR_F(arr);
783                 eset_destroy(methods);
784         }
785 }
786
787 /**
788  * Walker: Removes all tuple.
789  */
790 static void remove_Tuples(ir_node *proj, void *env) {
791         ir_node *nn;
792         (void) env;
793         if (! is_Proj(proj)) return;
794
795         nn = skip_Tuple(proj);
796         if (nn != proj) exchange(proj, nn);
797 }
798
799
800 /**
801  * Determine for every Call the set of possibly called methods and stores it
802  * inside the Call (@see set_Call_callee()).
803  * Uses the sel_methods set with much be already calculated.
804  */
805 static void callee_ana(void) {
806         int i;
807         /* analyse all graphs */
808         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
809                 ir_graph *irg = get_irp_irg(i);
810                 irg_walk_graph(irg, callee_walker, remove_Tuples, NULL);
811                 set_irg_callee_info_state(irg, irg_callee_info_consistent);
812         }
813         set_irp_callee_info_state(irg_callee_info_consistent);
814 }
815
816 /*--------------------------------------------------------------------------*/
817 /* Cleanup after analyses.                                                  */
818 /*--------------------------------------------------------------------------*/
819
820 /** Frees intermediate data structures. */
821 static void sel_methods_dispose(void) {
822         ir_entity * ent;
823         assert(entities);
824         for (ent = eset_first(entities); ent; ent = eset_next(entities)) {
825                 ir_entity ** arr = get_entity_link(ent);
826                 if (arr) {
827                         DEL_ARR_F(arr);
828                 }
829                 set_entity_link(ent, NULL);
830         }
831         eset_destroy(entities);
832         entities = NULL;
833 }
834
835 /*--------------------------------------------------------------------------*/
836 /* Freeing the callee arrays.                                               */
837 /*--------------------------------------------------------------------------*/
838
839 static void destruct_walker(ir_node * node, void * env) {
840         (void) env;
841         if (is_Call(node)) {
842                 remove_Call_callee_arr(node);
843         }
844 }
845
846 /*--------------------------------------------------------------------------*/
847 /* Main drivers.                                                            */
848 /*--------------------------------------------------------------------------*/
849
850 void cgana(int *length, ir_entity ***free_methods) {
851         /* Optimize Sel/SymConst nodes and compute all methods that implement an entity. */
852         sel_methods_init();
853         *free_methods = get_free_methods(length);
854         callee_ana();
855         sel_methods_dispose();
856 }
857
858 void free_callee_info(ir_graph *irg) {
859         irg_walk_graph(irg, destruct_walker, NULL, NULL);
860         set_irg_callee_info_state(irg, irg_callee_info_none);
861 }
862
863 void free_irp_callee_info(void) {
864         int i;
865         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
866                 free_callee_info(get_irp_irg(i));
867         }
868 }
869
870 /* Optimize the address expressions passed to call nodes.
871  *
872  * This optimization performs the following transformations for
873  * all ir graphs:
874  * - All SymConst operations that refer to intern methods are replaced
875  *   by Const operations referring to the corresponding entity.
876  * - Sel nodes, that select entities that are not overwritten are
877  *   replaced by Const nodes referring to the selected entity.
878  * - Sel nodes, for which no method exists at all are replaced by Bad
879  *   nodes.
880  * - Sel nodes with a pointer input that is an Alloc node are replaced
881  *   by Const nodes referring to the entity that implements the method in
882  *   the type given by the Alloc node.
883  */
884 void opt_call_addrs(void) {
885         sel_methods_init();
886         sel_methods_dispose();
887 }