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