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