lower_highlevel didn't invalidate outedges, code_placement must assure doms
[libfirm] / ir / lower / lower_hl.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   Lower some High-level constructs, moved from the firmlower.
23  * @author  Boris Boesler, Goetz Lindenmaier, Michael Beck
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include "lowering.h"
29 #include "irmode_t.h"
30 #include "irnode_t.h"
31 #include "entity_t.h"
32 #include "typerep.h"
33 #include "irprog_t.h"
34 #include "ircons.h"
35 #include "irhooks.h"
36 #include "irgmod.h"
37 #include "irgwalk.h"
38 #include "irtools.h"
39 #include "irpass_t.h"
40
41 /**
42  * Lower a Sel node. Do not touch Sels accessing entities on the frame type.
43  */
44 static void lower_sel(ir_node *sel) {
45         ir_graph *irg = current_ir_graph;
46         ir_entity   *ent;
47         ir_node  *newn, *cnst, *index, *ptr, *bl;
48         tarval   *tv;
49         ir_mode  *basemode, *mode, *mode_Int;
50         ir_type  *basetyp, *owner;
51         dbg_info *dbg;
52
53         assert(is_Sel(sel));
54
55         /* Do not lower frame type/global offset table access: must be lowered by the backend. */
56         ptr = get_Sel_ptr(sel);
57         if (ptr == get_irg_frame(current_ir_graph))
58                 return;
59
60         ent   = get_Sel_entity(sel);
61         owner = get_entity_owner(ent);
62
63         /*
64          * Cannot handle value param entities or frame type entities here.
65          * Must be lowered by the backend.
66          */
67         if (is_value_param_type(owner) || is_frame_type(owner))
68                 return;
69
70         dbg  = get_irn_dbg_info(sel);
71         mode = get_irn_mode(sel);
72
73         mode_Int = get_reference_mode_signed_eq(mode);
74
75         /* TLS access, must be handled by the linker */
76         if (get_tls_type() == owner) {
77                 symconst_symbol sym;
78
79                 sym.entity_p = ent;
80                 bl = get_nodes_block(sel);
81
82                 cnst = new_rd_SymConst(dbg, irg, mode, sym, symconst_addr_ent);
83                 newn = new_rd_Add(dbg, bl, ptr, cnst, mode);
84         } else {
85                 /* not TLS */
86
87                 assert(get_type_state(get_entity_owner(ent)) == layout_fixed);
88                 assert(get_type_state(get_entity_type(ent)) == layout_fixed);
89
90                 bl = get_nodes_block(sel);
91                 if (0 < get_Sel_n_indexs(sel)) {
92                         /* an Array access */
93                         basetyp = get_entity_type(ent);
94                         if (is_Primitive_type(basetyp))
95                                 basemode = get_type_mode(basetyp);
96                         else
97                                 basemode = mode_P_data;
98
99                         assert(basemode && "no mode for lowering Sel");
100                         assert((get_mode_size_bits(basemode) % 8 == 0) && "can not deal with unorthodox modes");
101                         index = get_Sel_index(sel, 0);
102
103                         if (is_Array_type(owner)) {
104                                 ir_type *arr_ty = owner;
105                                 int      dims   = get_array_n_dimensions(arr_ty);
106                                 int     *map    = ALLOCAN(int, dims);
107                                 ir_node *last_size;
108                                 int      i;
109
110                                 assert(dims == get_Sel_n_indexs(sel)
111                                         && "array dimension must match number of indices of Sel node");
112
113                                 for (i = 0; i < dims; i++) {
114                                         int order = get_array_order(arr_ty, i);
115
116                                         assert(order < dims &&
117                                                 "order of a dimension must be smaller than the arrays dim");
118                                         map[order] = i;
119                                 }
120                                 newn = get_Sel_ptr(sel);
121
122                                 /* Size of the array element */
123                                 tv = new_tarval_from_long(get_type_size_bytes(basetyp), mode_Int);
124                                 last_size = new_rd_Const(dbg, irg, tv);
125
126                                 /*
127                                  * We compute the offset part of dimension d_i recursively
128                                  * with the the offset part of dimension d_{i-1}
129                                  *
130                                  *     off_0 = sizeof(array_element_type);
131                                  *     off_i = (u_i - l_i) * off_{i-1}  ; i >= 1
132                                  *
133                                  * whereas u_i is the upper bound of the current dimension
134                                  * and l_i the lower bound of the current dimension.
135                                  */
136                                 for (i = dims - 1; i >= 0; i--) {
137                                         int dim = map[i];
138                                         ir_node *lb, *ub, *elms, *n, *ind;
139
140                                         elms = NULL;
141                                         lb = get_array_lower_bound(arr_ty, dim);
142                                         ub = get_array_upper_bound(arr_ty, dim);
143
144                                         assert(irg == current_ir_graph);
145                                         if (! is_Unknown(lb))
146                                                 lb = new_rd_Conv(dbg, bl, copy_const_value(get_irn_dbg_info(sel), lb), mode_Int);
147                                         else
148                                                 lb = NULL;
149
150                                         if (! is_Unknown(ub))
151                                                 ub = new_rd_Conv(dbg, bl, copy_const_value(get_irn_dbg_info(sel), ub), mode_Int);
152                                         else
153                                                 ub = NULL;
154
155                                         /*
156                                          * If the array has more than one dimension, lower and upper
157                                          * bounds have to be set in the non-last dimension.
158                                          */
159                                         if (i > 0) {
160                                                 assert(lb != NULL && "lower bound has to be set in multi-dim array");
161                                                 assert(ub != NULL && "upper bound has to be set in multi-dim array");
162
163                                                 /* Elements in one Dimension */
164                                                 elms = new_rd_Sub(dbg, bl, ub, lb, mode_Int);
165                                         }
166
167                                         ind = new_rd_Conv(dbg, bl, get_Sel_index(sel, dim), mode_Int);
168
169                                         /*
170                                          * Normalize index, id lower bound is set, also assume
171                                          * lower bound == 0
172                                          */
173                                         if (lb != NULL)
174                                                 ind = new_rd_Sub(dbg, bl, ind, lb, mode_Int);
175
176                                         n = new_rd_Mul(dbg, bl, ind, last_size, mode_Int);
177
178                                         /*
179                                          * see comment above.
180                                          */
181                                         if (i > 0)
182                                                 last_size = new_rd_Mul(dbg, bl, last_size, elms, mode_Int);
183
184                                         newn = new_rd_Add(dbg, bl, newn, n, mode);
185                                 }
186                         } else {
187                                 /* no array type */
188                                 ir_mode *idx_mode = get_irn_mode(index);
189                                 tarval *tv = new_tarval_from_long(get_mode_size_bytes(basemode), idx_mode);
190
191                                 newn = new_rd_Add(dbg, bl, get_Sel_ptr(sel),
192                                         new_rd_Mul(dbg, bl, index,
193                                         new_r_Const(irg, tv),
194                                         idx_mode),
195                                         mode);
196                         }
197                 } else if (is_Method_type(get_entity_type(ent)) &&
198                            is_Class_type(owner) &&
199                            (owner != get_glob_type()) &&
200                            (!is_frame_type(owner)))  {
201                         ir_node *add;
202                         ir_mode *ent_mode = get_type_mode(get_entity_type(ent));
203
204                         /* We need an additional load when accessing methods from a dispatch table. */
205                         tv   = new_tarval_from_long(get_entity_offset(ent), mode_Int);
206                         cnst = new_rd_Const(dbg, irg, tv);
207                         add  = new_rd_Add(dbg, bl, get_Sel_ptr(sel), cnst, mode);
208 #ifdef DO_CACHEOPT  /* cacheopt version */
209                         newn = new_rd_Load(dbg, bl, get_Sel_mem(sel), sel, ent_mode, 0);
210                         cacheopt_map_addrs_register_node(newn);
211                         set_Load_ptr(newn, add);
212 #else /* normal code */
213                         newn = new_rd_Load(dbg, bl, get_Sel_mem(sel), add, ent_mode, 0);
214 #endif
215                         newn = new_r_Proj(bl, newn, ent_mode, pn_Load_res);
216
217                 } else if (get_entity_owner(ent) != get_glob_type()) {
218                         int offset;
219
220                         /* replace Sel by add(obj, const(ent.offset)) */
221                         assert(!(get_entity_allocation(ent) == allocation_static &&
222                                 (get_entity_n_overwrites(ent) == 0 && get_entity_n_overwrittenby(ent) == 0)));
223                         newn   = get_Sel_ptr(sel);
224                         offset = get_entity_offset(ent);
225                         if (offset != 0) {
226                                 ir_mode *mode_UInt = get_reference_mode_unsigned_eq(mode);
227
228                                 tv = new_tarval_from_long(offset, mode_UInt);
229                                 cnst = new_r_Const(irg, tv);
230                                 newn = new_rd_Add(dbg, bl, newn, cnst, mode);
231                         }
232                 } else {
233                         /* global_type */
234                         newn = new_rd_SymConst_addr_ent(NULL, irg, mode, ent, firm_unknown_type);
235                 }
236         }
237         /* run the hooks */
238         hook_lower(sel);
239
240         exchange(sel, newn);
241 }  /* lower_sel */
242
243 /**
244  * Lower a all possible SymConst nodes.
245  */
246 static void lower_symconst(ir_node *symc) {
247         ir_node       *newn;
248         ir_type       *tp;
249         ir_entity     *ent;
250         tarval        *tv;
251         ir_enum_const *ec;
252         ir_mode       *mode;
253
254         switch (get_SymConst_kind(symc)) {
255         case symconst_type_tag:
256                 assert(!"SymConst kind symconst_type_tag not implemented");
257                 break;
258         case symconst_type_size:
259                 /* rewrite the SymConst node by a Const node */
260                 tp   = get_SymConst_type(symc);
261                 assert(get_type_state(tp) == layout_fixed);
262                 mode = get_irn_mode(symc);
263                 newn = new_Const_long(mode, get_type_size_bytes(tp));
264                 assert(newn);
265                 /* run the hooks */
266                 hook_lower(symc);
267                 exchange(symc, newn);
268                 break;
269         case symconst_type_align:
270                 /* rewrite the SymConst node by a Const node */
271                 tp   = get_SymConst_type(symc);
272                 assert(get_type_state(tp) == layout_fixed);
273                 mode = get_irn_mode(symc);
274                 newn = new_Const_long(mode, get_type_alignment_bytes(tp));
275                 assert(newn);
276                 /* run the hooks */
277                 hook_lower(symc);
278                 exchange(symc, newn);
279                 break;
280         case symconst_addr_name:
281                 /* do not rewrite - pass info to back end */
282                 break;
283         case symconst_addr_ent:
284                 /* leave */
285                 break;
286         case symconst_ofs_ent:
287                 /* rewrite the SymConst node by a Const node */
288                 ent  = get_SymConst_entity(symc);
289                 assert(get_type_state(get_entity_type(ent)) == layout_fixed);
290                 mode = get_irn_mode(symc);
291                 newn = new_Const_long(mode, get_entity_offset(ent));
292                 assert(newn);
293                 /* run the hooks */
294                 hook_lower(symc);
295                 exchange(symc, newn);
296                 break;
297         case symconst_enum_const:
298                 /* rewrite the SymConst node by a Const node */
299                 ec   = get_SymConst_enum(symc);
300                 assert(get_type_state(get_enumeration_owner(ec)) == layout_fixed);
301                 tv   = get_enumeration_value(ec);
302                 newn = new_Const(tv);
303                 assert(newn);
304                 /* run the hooks */
305                 hook_lower(symc);
306                 exchange(symc, newn);
307                 break;
308
309         default:
310                 assert(!"unknown SymConst kind");
311                 break;
312         }
313 }  /* lower_symconst */
314
315 /**
316  * Checks, whether a size is an integral size
317  *
318  * @param size  the size on bits
319  */
320 static int is_integral_size(int size) {
321         /* must be a 2^n */
322         if (size & (size-1))
323                 return 0;
324         /* must be at least byte size */
325         return size >= 8;
326 }  /* is_integral_size */
327
328 /**
329  * lower bitfield load access.
330  *
331  * @param proj  the Proj(result) node
332  * @param load  the Load node
333  */
334 static void lower_bitfields_loads(ir_node *proj, ir_node *load) {
335         ir_node *sel = get_Load_ptr(load);
336         ir_node *block, *n_proj, *res, *ptr;
337         ir_entity *ent;
338         ir_type *bf_type;
339         ir_mode *bf_mode, *mode;
340         int offset, bit_offset, bits, bf_bits, old_cse;
341         dbg_info *db;
342
343         if (!is_Sel(sel))
344                 return;
345
346         ent     = get_Sel_entity(sel);
347         bf_type = get_entity_type(ent);
348
349         /* must be a bitfield type */
350         if (!is_Primitive_type(bf_type) || get_primitive_base_type(bf_type) == NULL)
351                 return;
352
353         /* We have a bitfield access, if either a bit offset is given, or
354            the size is not integral. */
355         bf_mode = get_type_mode(bf_type);
356         if (! bf_mode)
357                 return;
358
359         mode       = get_irn_mode(proj);
360         block      = get_nodes_block(proj);
361         bf_bits    = get_mode_size_bits(bf_mode);
362         bit_offset = get_entity_offset_bits_remainder(ent);
363
364         if (bit_offset == 0 && is_integral_size(bf_bits) && bf_mode == get_Load_mode(load))
365                 return;
366
367         bits   = get_mode_size_bits(mode);
368         offset = get_entity_offset(ent);
369
370         /*
371          * ok, here we are: now convert the Proj_mode_bf(Load) into And(Shr(Proj_mode(Load)) for unsigned
372          * and Shr(Shl(Proj_mode(load)) for signed
373          */
374
375         /* abandon bitfield sel */
376         ptr = get_Sel_ptr(sel);
377         db  = get_irn_dbg_info(sel);
378         ptr = new_rd_Add(db, block, ptr, new_Const_long(mode_Is, offset), get_irn_mode(ptr));
379
380         set_Load_ptr(load, ptr);
381         set_Load_mode(load, mode);
382
383
384         /* create new proj, switch off CSE or we may get the old one back */
385         old_cse = get_opt_cse();
386         set_opt_cse(0);
387         res = n_proj = new_r_Proj(block, load, mode, pn_Load_res);
388         set_opt_cse(old_cse);
389
390         if (mode_is_signed(mode)) { /* signed */
391                 int shift_count_up    = bits - (bf_bits + bit_offset);
392                 int shift_count_down  = bits - bf_bits;
393
394                 if (shift_count_up) {
395                         res = new_r_Shl(block, res,     new_Const_long(mode_Iu, shift_count_up), mode);
396                 }
397                 if (shift_count_down) {
398                         res = new_r_Shrs(block, res, new_Const_long(mode_Iu, shift_count_down), mode);
399                 }
400         } else { /* unsigned */
401                 int shift_count_down  = bit_offset;
402                 unsigned mask = ((unsigned)-1) >> (bits - bf_bits);
403
404                 if (shift_count_down) {
405                         res = new_r_Shr(block, res,     new_Const_long(mode_Iu, shift_count_down), mode);
406                 }
407                 if (bits != bf_bits) {
408                         res = new_r_And(block, res, new_Const_long(mode, mask), mode);
409                 }
410         }
411
412         exchange(proj, res);
413 }  /* lower_bitfields_loads */
414
415 /**
416  * lower bitfield store access.
417  *
418  * @todo: It adds a load which may produce an exception!
419  */
420 static void lower_bitfields_stores(ir_node *store) {
421         ir_node   *sel = get_Store_ptr(store);
422         ir_node   *ptr, *value;
423         ir_entity *ent;
424         ir_type *bf_type;
425         ir_mode *bf_mode, *mode;
426         ir_node *mem, *irn, *block;
427         unsigned mask, neg_mask;
428         int bf_bits, bits_mask, offset, bit_offset;
429         dbg_info *db;
430
431         /* check bitfield access */
432         if (!is_Sel(sel))
433                 return;
434
435         ent     = get_Sel_entity(sel);
436         bf_type = get_entity_type(ent);
437
438         /* must be a bitfield type */
439         if (!is_Primitive_type(bf_type) || get_primitive_base_type(bf_type) == NULL)
440                 return;
441
442         /* We have a bitfield access, if either a bit offset is given, or
443            the size is not integral. */
444         bf_mode = get_type_mode(bf_type);
445         if (! bf_mode)
446                 return;
447
448         value      = get_Store_value(store);
449         mode       = get_irn_mode(value);
450         block      = get_nodes_block(store);
451
452         bf_bits    = get_mode_size_bits(bf_mode);
453         bit_offset = get_entity_offset_bits_remainder(ent);
454
455         if (bit_offset == 0 && is_integral_size(bf_bits) && bf_mode == get_irn_mode(value))
456                 return;
457
458         /*
459          * ok, here we are: now convert the Store(Sel(), value) into Or(And(Load(Sel),c), And(Value,c))
460          */
461         mem        = get_Store_mem(store);
462         offset     = get_entity_offset(ent);
463
464         bits_mask = get_mode_size_bits(mode) - bf_bits;
465         mask = ((unsigned)-1) >> bits_mask;
466         mask <<= bit_offset;
467         neg_mask = ~mask;
468
469         /* abandon bitfield sel */
470         ptr = get_Sel_ptr(sel);
471         db  = get_irn_dbg_info(sel);
472         ptr = new_rd_Add(db, block, ptr, new_Const_long(mode_Is, offset), get_irn_mode(ptr));
473
474         if (neg_mask) {
475                 /* there are some bits, normal case */
476                 irn  = new_r_Load( block, mem, ptr, mode, 0);
477                 mem  = new_r_Proj( block, irn, mode_M, pn_Load_M);
478                 irn  = new_r_Proj( block, irn, mode, pn_Load_res);
479
480                 irn = new_r_And(block, irn, new_Const_long(mode, neg_mask), mode);
481
482                 if (bit_offset > 0) {
483                         value = new_r_Shl(block, value, new_Const_long(mode_Iu, bit_offset), mode);
484                 }
485
486                 value = new_r_And(block, value, new_Const_long(mode, mask), mode);
487
488                 value = new_r_Or(block, value, irn, mode);
489         }
490
491         set_Store_mem(store, mem);
492         set_Store_value(store, value);
493         set_Store_ptr(store, ptr);
494 }  /* lower_bitfields_stores */
495
496 /**
497  * Lowers unaligned Loads.
498  */
499 static void lower_unaligned_Load(ir_node *load) {
500   (void) load;
501         /* NYI */
502 }
503
504 /**
505  * Lowers unaligned Stores
506  */
507 static void lower_unaligned_Store(ir_node *store) {
508         (void) store;
509         /* NYI */
510 }
511
512 /**
513  * lowers IR-nodes, called from walker
514  */
515 static void lower_irnode(ir_node *irn, void *env)
516 {
517         (void) env;
518         switch (get_irn_opcode(irn)) {
519         case iro_Sel:
520                 lower_sel(irn);
521                 break;
522         case iro_SymConst:
523                 lower_symconst(irn);
524                 break;
525         case iro_Load:
526                 if (env != NULL && get_Load_align(irn) == align_non_aligned)
527                         lower_unaligned_Load(irn);
528                 break;
529         case iro_Store:
530                 if (env != NULL && get_Store_align(irn) == align_non_aligned)
531                         lower_unaligned_Store(irn);
532                 break;
533         case iro_Cast:
534                 exchange(irn, get_Cast_op(irn));
535                 break;
536         default:
537                 break;
538         }
539 }
540
541 /**
542  * Walker: lowers IR-nodes for bitfield access
543  */
544 static void lower_bf_access(ir_node *irn, void *env)
545 {
546         (void) env;
547         switch (get_irn_opcode(irn)) {
548         case iro_Proj:
549         {
550                 long proj     = get_Proj_proj(irn);
551                 ir_node *pred = get_Proj_pred(irn);
552
553                 if (proj == pn_Load_res && is_Load(pred))
554                         lower_bitfields_loads(irn, pred);
555                 break;
556         }
557         case iro_Store:
558                 lower_bitfields_stores(irn);
559                 break;
560
561         default:
562                 break;
563         }
564 }
565
566 /*
567  * Replaces SymConsts by a real constant if possible.
568  * Replace Sel nodes by address computation.  Also resolves array access.
569  * Handle Bitfields by added And/Or calculations.
570  */
571 void lower_highlevel_graph(ir_graph *irg, int lower_bitfields)
572 {
573         if (lower_bitfields) {
574                 /* First step: lower bitfield access: must be run as long as Sels still
575                  * exists. */
576                 irg_walk_graph(irg, NULL, lower_bf_access, NULL);
577         }
578
579         /* Finally: lower SymConst-Size and Sel nodes, Casts, unaligned Load/Stores. */
580         irg_walk_graph(irg, NULL, lower_irnode, NULL);
581
582         set_irg_outs_inconsistent(irg);
583 }
584
585 struct pass_t {
586         ir_graph_pass_t pass;
587         int            lower_bitfields;
588 };
589
590 /**
591  * Wrapper for running lower_highlevel_graph() as an ir_graph pass.
592  */
593 static int lower_highlevel_graph_wrapper(ir_graph *irg, void *context) {
594         struct pass_t *pass = context;
595
596         lower_highlevel_graph(irg, pass->lower_bitfields);
597         return 0;
598 }  /* lower_highlevel_graph_wrapper */
599
600 ir_graph_pass_t *lower_highlevel_graph_pass(const char *name, int lower_bitfields) {
601         struct pass_t *pass = XMALLOCZ(struct pass_t);
602
603         pass->lower_bitfields = lower_bitfields;
604         return def_graph_pass_constructor(
605                 &pass->pass, name ? name : "lower_hl", lower_highlevel_graph_wrapper);
606 }  /* lower_highlevel_graph_pass */
607
608 /*
609  * does the same as lower_highlevel() for all nodes on the const code irg
610  */
611 void lower_const_code(void) {
612         walk_const_code(NULL, lower_irnode, NULL);
613 }  /* lower_const_code */
614
615 ir_prog_pass_t *lower_const_code_pass(const char *name) {
616         return def_prog_pass(name ? name : "lower_const_code", lower_const_code);
617 }
618
619 /*
620  * Replaces SymConsts by a real constant if possible.
621  * Replace Sel nodes by address computation.  Also resolves array access.
622  * Handle Bitfields by added And/Or calculations.
623  */
624 void lower_highlevel(int lower_bitfields) {
625         int i, n;
626
627         n = get_irp_n_irgs();
628         for (i = 0; i < n; ++i) {
629                 ir_graph *irg = get_irp_irg(i);
630                 lower_highlevel_graph(irg, lower_bitfields);
631         }
632         lower_const_code();
633 }  /* lower_highlevel */