remove extended basic block support
[libfirm] / ir / opt / scalar_replace.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Scalar replacement of compounds.
23  * @author  Beyhan Veliev, Michael Beck
24  */
25 #include "config.h"
26
27 #include <string.h>
28 #include <stdbool.h>
29
30 #include "iroptimize.h"
31 #include "scalar_replace.h"
32 #include "opt_init.h"
33 #include "irflag_t.h"
34 #include "irouts.h"
35 #include "set.h"
36 #include "pset.h"
37 #include "array.h"
38 #include "tv.h"
39 #include "ircons_t.h"
40 #include "hashptr.h"
41 #include "irgwalk.h"
42 #include "irgmod.h"
43 #include "irnode_t.h"
44 #include "irpass.h"
45 #include "util.h"
46 #include "xmalloc.h"
47 #include "debug.h"
48 #include "error.h"
49 #include "opt_manage.h"
50
51 static unsigned get_vnum(const ir_node *node)
52 {
53         return (unsigned)PTR_TO_INT(get_irn_link(node));
54 }
55
56 static void set_vnum(ir_node *node, unsigned vnum)
57 {
58         set_irn_link(node, INT_TO_PTR(vnum));
59 }
60
61 /**
62  * A path element entry: it is either an entity
63  * or a tarval, because we evaluate only constant array
64  * accesses like a.b.c[8].d
65  */
66 typedef union {
67         ir_entity *ent;
68         ir_tarval *tv;
69 } path_elem_t;
70
71 /**
72  * An access path, used to assign value numbers
73  * to variables that will be scalar replaced.
74  */
75 typedef struct path_t {
76         unsigned    vnum;      /**< The value number. */
77         size_t      path_len;  /**< The length of the access path. */
78         path_elem_t path[1];   /**< The path. */
79 } path_t;
80
81 /** The size of a path in bytes. */
82 static size_t path_size(path_t *p)
83 {
84         return sizeof(*p) + sizeof(p->path[0]) * (p->path_len-1);
85 }
86
87 typedef struct scalars_t {
88         ir_entity *ent;              /**< A entity for scalar replacement. */
89 } scalars_t;
90
91 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
92
93 /**
94  * Compare two pathes.
95  *
96  * @return 0 if they are identically
97  */
98 static int path_cmp(const void *elt, const void *key, size_t size)
99 {
100         const path_t *p1 = (const path_t*)elt;
101         const path_t *p2 = (const path_t*)key;
102         (void) size;
103
104         /* we can use memcmp here, because identical tarvals should have identical addresses */
105         return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
106 }
107
108 /**
109  * Compare two elements of the scalars_t set.
110  *
111  * @return 0 if they are identically
112  */
113 static int ent_cmp(const void *elt, const void *key, size_t size)
114 {
115         const scalars_t *c1 = (const scalars_t*)elt;
116         const scalars_t *c2 = (const scalars_t*)key;
117         (void) size;
118
119         return c1->ent != c2->ent;
120 }
121
122 /**
123  * Calculate a hash value for a path.
124  */
125 static unsigned path_hash(const path_t *path)
126 {
127         unsigned hash = 0;
128         unsigned i;
129
130         for (i = 0; i < path->path_len; ++i)
131                 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
132
133         return hash >> 4;
134 }
135
136 /**
137  * Returns non-zero, if all indeces of a Sel node are constants.
138  *
139  * @param sel  the Sel node that will be checked
140  */
141 static bool is_const_sel(ir_node *sel)
142 {
143         int i, n = get_Sel_n_indexs(sel);
144
145         for (i = 0; i < n; ++i) {
146                 ir_node *idx = get_Sel_index(sel, i);
147
148                 if (!is_Const(idx))
149                         return false;
150         }
151         return true;
152 }
153
154 /**
155  * Check the mode of a Load/Store with the mode of the entity
156  * that is accessed.
157  * If the mode of the entity and the Load/Store mode do not match, we
158  * have the bad reinterpret case:
159  *
160  * int i;
161  * char b = *(char *)&i;
162  *
163  * We do NOT count this as one value and return address_taken
164  * in that case.
165  * However, we support an often used case. If the mode is two-complement
166  * we allow casts between signed/unsigned.
167  *
168  * @param mode     the mode of the Load/Store
169  * @param ent_mode the mode of the accessed entity
170  */
171 static bool check_load_store_mode(ir_mode *mode, ir_mode *ent_mode)
172 {
173         if (ent_mode != mode) {
174                 if (ent_mode == NULL ||
175                     get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
176                     get_mode_arithmetic(ent_mode) != irma_twos_complement ||
177                     get_mode_arithmetic(mode) != irma_twos_complement)
178                         return false;
179         }
180         return true;
181 }
182
183 /*
184  * Returns non-zero, if the address of an entity
185  * represented by a Sel node (or its successor Sels) is taken.
186  */
187 bool is_address_taken(ir_node *sel)
188 {
189         int       i, input_nr, k;
190         ir_mode   *emode, *mode;
191         ir_node   *value;
192         ir_entity *ent;
193
194         if (! is_const_sel(sel))
195                 return true;
196
197         for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
198                 ir_node *succ = get_irn_out(sel, i);
199
200                 switch (get_irn_opcode(succ)) {
201                 case iro_Load:
202                         /* do not remove volatile variables */
203                         if (get_Load_volatility(succ) == volatility_is_volatile)
204                                 return true;
205                         /* check if this load is not a hidden conversion */
206                         mode = get_Load_mode(succ);
207                         ent = get_Sel_entity(sel);
208                         emode = get_type_mode(get_entity_type(ent));
209                         if (! check_load_store_mode(mode, emode))
210                                 return true;
211                         break;
212
213                 case iro_Store:
214                         /* check that Sel is not the Store's value */
215                         value = get_Store_value(succ);
216                         if (value == sel)
217                                 return true;
218                         /* do not remove volatile variables */
219                         if (get_Store_volatility(succ) == volatility_is_volatile)
220                                 return true;
221                         /* check if this Store is not a hidden conversion */
222                         mode = get_irn_mode(value);
223                         ent = get_Sel_entity(sel);
224                         emode = get_type_mode(get_entity_type(ent));
225                         if (! check_load_store_mode(mode, emode))
226                                 return true;
227                         break;
228
229                 case iro_Sel: {
230                         int       res;
231                         ir_entity *entity = get_Sel_entity(succ);
232                         /* we can't handle unions correctly yet -> address taken */
233                         if (is_Union_type(get_entity_owner(entity)))
234                                 return true;
235
236                         /* Check the Sel successor of Sel */
237                         res = is_address_taken(succ);
238                         if (res)
239                                 return true;
240                         break;
241                 }
242
243                 case iro_Call:
244                         /* The address of an entity is given as a parameter.
245                          * As long as we do not have analyses that can tell what
246                          * is done with parameters, think is taken.
247                          * One special case: If the Call type tells that it's a
248                          * value parameter, the address is NOT taken.
249                          */
250                         return true;
251
252                 case iro_Id: {
253                         int res = is_address_taken(succ);
254                         if (res)
255                                 return true;
256                         break;
257                 }
258
259                 case iro_Tuple:
260                         /* Non-optimized Tuple, happens in inlining */
261                         for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
262                                 ir_node *pred = get_Tuple_pred(succ, input_nr);
263
264                                 if (pred == sel) {
265                                         /* we found one input */
266                                         for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
267                                                 ir_node *proj = get_irn_out(succ, k);
268
269                                                 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
270                                                         int res = is_address_taken(proj);
271                                                         if (res)
272                                                                 return true;
273                                                 }
274                                         }
275                                 }
276                         }
277                         break;
278
279                 default:
280                         /* another op, the address is taken */
281                         return true;
282                 }
283         }
284         return false;
285 }
286
287 /**
288  * Link all leave Sels with the entity.
289  *
290  * @param ent  the entity that will be scalar replaced
291  * @param sel  a Sel node that selects some fields of this entity
292  */
293 static bool link_all_leave_sels(ir_entity *ent, ir_node *sel)
294 {
295         int i;
296         bool is_leave = true;
297
298         for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
299                 ir_node *succ = get_irn_out(sel, i);
300
301                 if (is_Sel(succ)) {
302                         /* the current leave has further Sel's, no leave */
303                         is_leave = false;
304                         link_all_leave_sels(ent, succ);
305                 } else if (is_Id(succ)) {
306                         is_leave &= link_all_leave_sels(ent, succ);
307                 }
308         }
309
310         if (is_leave) {
311                 /* beware of Id's */
312                 sel = skip_Id(sel);
313
314                 /* we know we are at a leave, because this function is only
315                  * called if the address is NOT taken, so sel's successor(s)
316                  * must be Loads or Stores
317                  */
318                 set_irn_link(sel, get_entity_link(ent));
319                 set_entity_link(ent, sel);
320         }
321         return is_leave;
322 }
323
324 /* we need a special address that serves as an address taken marker */
325 static char _x;
326 static void *ADDRESS_TAKEN = &_x;
327
328 /**
329  * Find possible scalar replacements.
330  *
331  * @param irg  an IR graph
332  *
333  * This function finds variables on the (members of the) frame type
334  * that can be scalar replaced, because their address is never taken.
335  * If such a variable is found, its entity link will hold a list of all
336  * Sel nodes, that selects the atomic fields of this entity.
337  * Otherwise, the link will be ADDRESS_TAKEN or NULL.
338  *
339  * @return  non-zero if at least one entity could be replaced
340  *          potentially
341  */
342 static int find_possible_replacements(ir_graph *irg)
343 {
344         ir_node *irg_frame;
345         ir_type *frame_tp;
346         size_t  mem_idx;
347         int     i;
348         long    static_link_arg;
349         int     res = 0;
350
351         /*
352          * First, clear the link field of all interesting entities.
353          */
354         frame_tp = get_irg_frame_type(irg);
355         for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
356                 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
357                 set_entity_link(ent, NULL);
358         }
359
360         /* check for inner functions:
361          * FIXME: need a way to get the argument position for the static link */
362         static_link_arg = 0;
363         for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
364                 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
365                 if (is_method_entity(ent)) {
366                         ir_graph *inner_irg = get_entity_irg(ent);
367                         ir_node  *args;
368                         int      j;
369
370                         assure_irg_outs(inner_irg);
371                         args = get_irg_args(inner_irg);
372                         for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
373                                 ir_node *arg = get_irn_out(args, j);
374
375                                 if (get_Proj_proj(arg) == static_link_arg) {
376                                         int k;
377                                         for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
378                                                 ir_node *succ = get_irn_out(arg, k);
379
380                                                 if (is_Sel(succ)) {
381                                                         ir_entity *ent = get_Sel_entity(succ);
382
383                                                         if (get_entity_owner(ent) == frame_tp) {
384                                                                 /* found an access to the outer frame */
385                                                                 set_entity_link(ent, ADDRESS_TAKEN);
386                                                         }
387                                                 }
388                                         }
389                                 }
390                         }
391                 }
392         }
393
394         /*
395          * Check the ir_graph for Sel nodes. If the entity of Sel
396          * isn't a scalar replacement set the link of this entity
397          * equal ADDRESS_TAKEN.
398          */
399         irg_frame = get_irg_frame(irg);
400         for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
401                 ir_node *succ = get_irn_out(irg_frame, i);
402
403                 if (is_Sel(succ)) {
404                         ir_entity *ent = get_Sel_entity(succ);
405                         ir_type *ent_type;
406
407                         /* we are only interested in entities on the frame, NOT
408                            on the value type */
409                         if (get_entity_owner(ent) != frame_tp)
410                                 continue;
411
412                         if (get_entity_link(ent) == ADDRESS_TAKEN)
413                                 continue;
414
415                         ent_type = get_entity_type(ent);
416
417                         /* we can handle arrays, structs and atomic types yet */
418                         if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
419                                 if (is_address_taken(succ)) {
420                                          /* killing one */
421                                         if (get_entity_link(ent))
422                                                 --res;
423                                         set_entity_link(ent, ADDRESS_TAKEN);
424                                 } else {
425                                         /* possible found one */
426                                         if (get_entity_link(ent) == NULL)
427                                                 ++res;
428                                         link_all_leave_sels(ent, succ);
429                                 }
430                         }
431                 }
432         }
433
434         return res;
435 }
436
437 /**
438  * Return a path from the Sel node "sel" to its root.
439  *
440  * @param sel  the Sel node
441  * @param len  the length of the path so far
442  */
443 static path_t *find_path(ir_node *sel, size_t len)
444 {
445         size_t pos;
446         int i, n;
447         path_t *res;
448         ir_node *pred = get_Sel_ptr(sel);
449
450         /* the current Sel node will add some path elements */
451         n    = get_Sel_n_indexs(sel);
452         len += n + 1;
453
454         if (! is_Sel(pred)) {
455                 /* we found the root */
456                 res = XMALLOCF(path_t, path, len);
457                 res->path_len = len;
458         } else
459                 res = find_path(pred, len);
460
461         assert(len <= res->path_len);
462         pos = res->path_len - len;
463
464         res->path[pos++].ent = get_Sel_entity(sel);
465         for (i = 0; i < n; ++i) {
466                 ir_node *index = get_Sel_index(sel, i);
467
468                 res->path[pos++].tv = get_Const_tarval(index);
469         }
470         return res;
471 }
472
473
474 /**
475  * Allocate value numbers for the leaves
476  * in our found entities.
477  *
478  * @param sels  a set that will contain all Sels that have a value number
479  * @param ent   the entity that will be scalar replaced
480  * @param vnum  the first value number we can assign
481  * @param modes a flexible array, containing all the modes of
482  *              the value numbers.
483  *
484  * @return the next free value number
485  */
486 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
487 {
488         ir_node *sel, *next;
489         path_t *key, *path;
490         set *pathes = new_set(path_cmp, 8);
491
492         DB((dbg, SET_LEVEL_3, "  Visiting Sel nodes of entity %+F\n", ent));
493         /* visit all Sel nodes in the chain of the entity */
494         for (sel = (ir_node*)get_entity_link(ent); sel != NULL; sel = next) {
495                 next = (ir_node*)get_irn_link(sel);
496
497                 /* we must mark this sel for later */
498                 pset_insert_ptr(sels, sel);
499
500                 key  = find_path(sel, 0);
501                 path = (path_t*)set_find(pathes, key, path_size(key), path_hash(key));
502
503                 if (path) {
504                         set_vnum(sel, path->vnum);
505                         DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, path->vnum));
506                 } else {
507                         key->vnum = vnum++;
508
509                         set_insert(pathes, key, path_size(key), path_hash(key));
510
511                         set_vnum(sel, key->vnum);
512                         DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, key->vnum));
513
514                         ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
515
516                         (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
517
518                         assert((*modes)[key->vnum] && "Value is not atomic");
519
520 #ifdef DEBUG_libfirm
521                         /* Debug output */
522                         {
523                                 unsigned i;
524                                 DB((dbg, SET_LEVEL_2, "  %s", get_entity_name(key->path[0].ent)));
525                                 for (i = 1; i < key->path_len; ++i) {
526                                         if (is_entity(key->path[i].ent))
527                                                 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
528                                         else
529                                                 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
530                                 }
531                                 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
532                         }
533 #endif /* DEBUG_libfirm */
534                 }
535                 free(key);
536         }
537
538         del_set(pathes);
539         set_entity_link(ent, NULL);
540         return vnum;
541 }
542
543 /**
544  * environment for memory walker
545  */
546 typedef struct env_t {
547         unsigned nvals;      /**< number of values */
548         ir_mode  **modes;    /**< the modes of the values */
549         pset     *sels;      /**< A set of all Sel nodes that have a value number */
550 } env_t;
551
552 /**
553  * topological post-walker.
554  */
555 static void walker(ir_node *node, void *ctx)
556 {
557         env_t    *env = (env_t*)ctx;
558         ir_graph *irg = get_irn_irg(node);
559         ir_node  *addr, *block, *mem, *val;
560         ir_mode  *mode;
561         unsigned vnum;
562
563         if (is_Load(node)) {
564                 /* a load, check if we can resolve it */
565                 addr = get_Load_ptr(node);
566
567                 DB((dbg, SET_LEVEL_3, "  checking %+F for replacement ", node));
568                 if (! is_Sel(addr)) {
569                         DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
570                         return;
571                 }
572
573                 if (! pset_find_ptr(env->sels, addr)) {
574                         DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
575                         return;
576                 }
577
578                 /* ok, we have a Load that will be replaced */
579                 vnum = get_vnum(addr);
580                 assert(vnum < env->nvals);
581
582                 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
583
584                 block = get_nodes_block(node);
585                 set_cur_block(block);
586
587                 /* check, if we can replace this Load */
588                 val = get_value(vnum, env->modes[vnum]);
589
590                 /* Beware: A Load can contain a hidden conversion in Firm.
591                 This happens for instance in the following code:
592
593                  int i;
594                  unsigned j = *(unsigned *)&i;
595
596                 Handle this here. */
597                 mode = get_Load_mode(node);
598                 if (mode != get_irn_mode(val))
599                         val = new_rd_Conv(get_irn_dbg_info(node), block, val, mode);
600
601                 mem = get_Load_mem(node);
602                 turn_into_tuple(node, pn_Load_max+1);
603                 set_Tuple_pred(node, pn_Load_M,         mem);
604                 set_Tuple_pred(node, pn_Load_res,       val);
605                 set_Tuple_pred(node, pn_Load_X_regular, new_r_Jmp(block));
606                 set_Tuple_pred(node, pn_Load_X_except,  new_r_Bad(irg, mode_X));
607         } else if (is_Store(node)) {
608                 DB((dbg, SET_LEVEL_3, "  checking %+F for replacement ", node));
609
610                 /* a Store always can be replaced */
611                 addr = get_Store_ptr(node);
612
613                 if (! is_Sel(addr)) {
614                         DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
615                         return;
616                 }
617
618                 if (! pset_find_ptr(env->sels, addr)) {
619                         DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
620                         return;
621                 }
622
623                 vnum = get_vnum(addr);
624                 assert(vnum < env->nvals);
625
626                 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
627
628                 block = get_nodes_block(node);
629                 set_cur_block(block);
630
631                 /* Beware: A Store can contain a hidden conversion in Firm. */
632                 val = get_Store_value(node);
633                 if (get_irn_mode(val) != env->modes[vnum])
634                         val = new_rd_Conv(get_irn_dbg_info(node), block, val, env->modes[vnum]);
635
636                 set_value(vnum, val);
637
638                 mem = get_Store_mem(node);
639                 turn_into_tuple(node, pn_Store_max+1);
640                 set_Tuple_pred(node, pn_Store_M,         mem);
641                 set_Tuple_pred(node, pn_Store_X_regular, new_r_Jmp(block));
642                 set_Tuple_pred(node, pn_Store_X_except,  new_r_Bad(irg, mode_X));
643         }
644 }
645
646 /**
647  * Make scalar replacement.
648  *
649  * @param sels    A set containing all Sel nodes that have a value number
650  * @param nvals   The number of scalars.
651  * @param modes   A flexible array, containing all the modes of
652  *                the value numbers.
653  */
654 static void do_scalar_replacements(ir_graph *irg, pset *sels, unsigned nvals,
655                                    ir_mode **modes)
656 {
657         env_t env;
658
659         ssa_cons_start(irg, (int)nvals);
660
661         env.nvals = nvals;
662         env.modes = modes;
663         env.sels  = sels;
664
665         /*
666          * second step: walk over the graph blockwise in topological order
667          * and fill the array as much as possible.
668          */
669         DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", irg));
670         irg_walk_blkwise_graph(irg, NULL, walker, &env);
671
672         ssa_cons_finish(irg);
673 }
674
675 /*
676  * Find possible scalar replacements
677  *
678  * @param irg  The current ir graph.
679  */
680 static ir_graph_state_t do_scalar_replacement(ir_graph *irg)
681 {
682         unsigned  nvals;
683         int       i;
684         scalars_t key, *value;
685         ir_node   *irg_frame;
686         ir_mode   **modes;
687         set       *set_ent;
688         pset      *sels;
689         ir_type   *ent_type, *frame_tp;
690
691         /* we use the link field to store the VNUM */
692         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
693         irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
694
695         /* Find possible scalar replacements */
696         if (find_possible_replacements(irg)) {
697                 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
698
699                 /* Insert in set the scalar replacements. */
700                 irg_frame = get_irg_frame(irg);
701                 nvals     = 0;
702                 modes     = NEW_ARR_F(ir_mode *, 16);
703                 set_ent   = new_set(ent_cmp, 8);
704                 sels      = pset_new_ptr(8);
705                 frame_tp  = get_irg_frame_type(irg);
706
707                 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
708                         ir_node *succ = get_irn_out(irg_frame, i);
709
710                         if (is_Sel(succ)) {
711                                 ir_entity *ent = get_Sel_entity(succ);
712
713                                 /* we are only interested in entities on the frame, NOT
714                                    parameters */
715                                 if (get_entity_owner(ent) != frame_tp
716                                     || is_parameter_entity(ent))
717                                         continue;
718
719                                 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
720                                         continue;
721
722                                 ent_type = get_entity_type(ent);
723
724                                 key.ent       = ent;
725                                 set_insert(set_ent, &key, sizeof(key), hash_ptr(key.ent));
726
727 #ifdef DEBUG_libfirm
728                                 if (is_Array_type(ent_type)) {
729                                         DB((dbg, SET_LEVEL_1, "  found array %s\n", get_entity_name(ent)));
730                                 } else if (is_Struct_type(ent_type)) {
731                                         DB((dbg, SET_LEVEL_1, "  found struct %s\n", get_entity_name(ent)));
732                                 } else if (is_atomic_type(ent_type))
733                                         DB((dbg, SET_LEVEL_1, "  found atomic value %s\n", get_entity_name(ent)));
734                                 else {
735                                         panic("Neither an array nor a struct or atomic value found in scalar replace");
736                                 }
737 #endif /* DEBUG_libfirm */
738
739                                 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
740                         }
741                 }
742
743                 DB((dbg, SET_LEVEL_1, "  %u values will be needed\n", nvals));
744
745                 /* If scalars were found. */
746                 if (nvals > 0) {
747                         do_scalar_replacements(irg, sels, nvals, modes);
748
749                         foreach_set(set_ent, scalars_t*, value) {
750                                 free_entity(value->ent);
751                         }
752
753                         /*
754                          * We changed the graph, but did NOT introduce new blocks
755                          * neither changed control flow, cf-backedges should be still
756                          * consistent.
757                          */
758                 }
759                 del_pset(sels);
760                 del_set(set_ent);
761                 DEL_ARR_F(modes);
762         }
763
764         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
765         irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
766
767         return 0;
768 }
769
770 static optdesc_t opt_scalar_rep = {
771         "scalar-replace",
772         IR_GRAPH_STATE_NO_UNREACHABLE_CODE | IR_GRAPH_STATE_CONSISTENT_OUTS,
773         do_scalar_replacement,
774 };
775
776 int scalar_replacement_opt(ir_graph *irg)
777 {
778         perform_irg_optimization(irg, &opt_scalar_rep);
779         return 1;
780 }
781
782 ir_graph_pass_t *scalar_replacement_opt_pass(const char *name)
783 {
784         return def_graph_pass_ret(name ? name : "scalar_rep",
785                                   scalar_replacement_opt);
786 }
787
788 void firm_init_scalar_replace(void)
789 {
790         FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");
791 }