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