Several bug fixes
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 /**
2  * Project:     libFIRM
3  * File name:   ir/be/ia32/ia32_optimize.c
4  * Purpose:     Implements several optimizations for IA32
5  * Author:      Christian Wuerdig
6  * CVS-ID:      $Id$
7  * Copyright:   (c) 2006 Universität Karlsruhe
8  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #include "irnode.h"
16 #include "irprog_t.h"
17 #include "ircons.h"
18 #include "firm_types.h"
19 #include "iredges.h"
20 #include "tv.h"
21 #include "irgmod.h"
22 #include "irgwalk.h"
23 #include "height.h"
24 #include "irbitset.h"
25
26 #include "../be_t.h"
27 #include "../beabi.h"
28 #include "../benode_t.h"
29 #include "../besched_t.h"
30
31 #include "ia32_new_nodes.h"
32 #include "bearch_ia32_t.h"
33 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
34 #include "ia32_transform.h"
35 #include "ia32_dbg_stat.h"
36 #include "ia32_util.h"
37
38 typedef enum {
39         IA32_AM_CAND_NONE  = 0,
40         IA32_AM_CAND_LEFT  = 1,
41         IA32_AM_CAND_RIGHT = 2,
42         IA32_AM_CAND_BOTH  = 3
43 } ia32_am_cand_t;
44
45 #undef is_NoMem
46 #define is_NoMem(irn) (get_irn_op(irn) == op_NoMem)
47
48 typedef int is_op_func_t(const ir_node *n);
49 typedef ir_node *load_func_t(dbg_info *db, ir_graph *irg, ir_node *block, ir_node *base, ir_node *index, ir_node *mem);
50
51 /**
52  * checks if a node represents the NOREG value
53  */
54 static int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
55   be_abi_irg_t *babi = cg->birg->abi;
56         const arch_register_t *fp_noreg = USE_SSE2(cg) ?
57                 &ia32_xmm_regs[REG_XMM_NOREG] : &ia32_vfp_regs[REG_VFP_NOREG];
58
59         return (be_abi_get_callee_save_irn(babi, &ia32_gp_regs[REG_GP_NOREG]) == irn) ||
60                (be_abi_get_callee_save_irn(babi, fp_noreg) == irn);
61 }
62
63
64
65 /*************************************************
66  *   _____                _              _
67  *  / ____|              | |            | |
68  * | |     ___  _ __  ___| |_ __ _ _ __ | |_ ___
69  * | |    / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
70  * | |___| (_) | | | \__ \ || (_| | | | | |_\__ \
71  *  \_____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
72  *
73  *************************************************/
74
75 /**
76  * creates a unique ident by adding a number to a tag
77  *
78  * @param tag   the tag string, must contain a %d if a number
79  *              should be added
80  */
81 static ident *unique_id(const char *tag)
82 {
83         static unsigned id = 0;
84         char str[256];
85
86         snprintf(str, sizeof(str), tag, ++id);
87         return new_id_from_str(str);
88 }
89
90 /**
91  * Transforms a SymConst.
92  *
93  * @param mod     the debug module
94  * @param block   the block the new node should belong to
95  * @param node    the ir SymConst node
96  * @param mode    mode of the SymConst
97  * @return the created ia32 Const node
98  */
99 static ir_node *gen_SymConst(ia32_transform_env_t *env) {
100         dbg_info *dbg   = env->dbg;
101         ir_mode  *mode  = env->mode;
102         ir_graph *irg   = env->irg;
103         ir_node  *block = env->block;
104         ir_node  *cnst;
105
106         if (mode_is_float(mode)) {
107                 FP_USED(env->cg);
108                 if (USE_SSE2(env->cg))
109                         cnst = new_rd_ia32_xConst(dbg, irg, block, get_irg_no_mem(irg), mode);
110                 else
111                         cnst = new_rd_ia32_vfConst(dbg, irg, block, get_irg_no_mem(irg), mode);
112         }
113         else
114                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irg_no_mem(irg), mode);
115
116         set_ia32_Const_attr(cnst, env->irn);
117
118         return cnst;
119 }
120
121 /**
122  * Get a primitive type for a mode.
123  */
124 static ir_type *get_prim_type(pmap *types, ir_mode *mode)
125 {
126         pmap_entry *e = pmap_find(types, mode);
127         ir_type *res;
128
129         if (! e) {
130                 char buf[64];
131                 snprintf(buf, sizeof(buf), "prim_type_%s", get_mode_name(mode));
132                 res = new_type_primitive(new_id_from_str(buf), mode);
133                 pmap_insert(types, mode, res);
134         }
135         else
136                 res = e->value;
137         return res;
138 }
139
140 /**
141  * Get an entity that is initialized with a tarval
142  */
143 static entity *get_entity_for_tv(ia32_code_gen_t *cg, ir_node *cnst)
144 {
145         tarval *tv    = get_Const_tarval(cnst);
146         pmap_entry *e = pmap_find(cg->isa->tv_ent, tv);
147         entity *res;
148         ir_graph *rem;
149
150         if (! e) {
151                 ir_mode *mode = get_irn_mode(cnst);
152                 ir_type *tp = get_Const_type(cnst);
153                 if (tp == firm_unknown_type)
154                         tp = get_prim_type(cg->isa->types, mode);
155
156                 res = new_entity(get_glob_type(), unique_id(".LC%u"), tp);
157
158                 set_entity_ld_ident(res, get_entity_ident(res));
159                 set_entity_visibility(res, visibility_local);
160                 set_entity_variability(res, variability_constant);
161                 set_entity_allocation(res, allocation_static);
162
163                  /* we create a new entity here: It's initialization must resist on the
164                     const code irg */
165                 rem = current_ir_graph;
166                 current_ir_graph = get_const_code_irg();
167                 set_atomic_ent_value(res, new_Const_type(tv, tp));
168                 current_ir_graph = rem;
169
170                 pmap_insert(cg->isa->tv_ent, tv, res);
171         }
172         else
173                 res = e->value;
174         return res;
175 }
176
177 /**
178  * Transforms a Const.
179  *
180  * @param mod     the debug module
181  * @param block   the block the new node should belong to
182  * @param node    the ir Const node
183  * @param mode    mode of the Const
184  * @return the created ia32 Const node
185  */
186 static ir_node *gen_Const(ia32_transform_env_t *env) {
187         ir_node *cnst, *load;
188         symconst_symbol sym;
189         ir_graph *irg   = env->irg;
190         ir_node  *block = env->block;
191         ir_node  *node  = env->irn;
192         dbg_info *dbg   = env->dbg;
193         ir_mode  *mode  = env->mode;
194
195         if (mode_is_float(mode)) {
196                 FP_USED(env->cg);
197                 if (! USE_SSE2(env->cg)) {
198                         cnst_classify_t clss = classify_Const(node);
199
200                         if (clss == CNST_NULL)
201                                 return new_rd_ia32_vfldz(dbg, irg, block, mode);
202                         else if (clss == CNST_ONE)
203                                 return new_rd_ia32_vfld1(dbg, irg, block, mode);
204                 }
205                 sym.entity_p = get_entity_for_tv(env->cg, node);
206
207
208                 cnst      = new_rd_SymConst(dbg, irg, block, sym, symconst_addr_ent);
209                 load      = new_r_Load(irg, block, get_irg_no_mem(irg), cnst, mode);
210                 load      = new_r_Proj(irg, block, load, mode, pn_Load_res);
211                 env->irn  = cnst;
212                 env->mode = mode_P;
213                 cnst      = gen_SymConst(env);
214                 set_Load_ptr(get_Proj_pred(load), cnst);
215                 cnst      = load;
216         }
217         else {
218                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irg_no_mem(irg), get_irn_mode(node));
219                 set_ia32_Const_attr(cnst, node);
220         }
221         return cnst;
222 }
223
224 /**
225  * Transforms (all) Const's into ia32_Const and places them in the
226  * block where they are used (or in the cfg-pred Block in case of Phi's).
227  * Additionally all reference nodes are changed into mode_Is nodes.
228  * NOTE: irn must be a firm constant!
229  */
230 static void ia32_transform_const(ir_node *irn, void *env) {
231         ia32_code_gen_t      *cg   = env;
232         ir_node              *cnst = NULL;
233         ia32_transform_env_t tenv;
234
235         tenv.cg   = cg;
236         tenv.irg  = cg->irg;
237         tenv.mode = get_irn_mode(irn);
238         tenv.dbg  = get_irn_dbg_info(irn);
239         tenv.irn  = irn;
240         DEBUG_ONLY(tenv.mod = cg->mod;)
241
242         /* place const either in the smallest dominator of all its users or the original block */
243         if (cg->opt & IA32_OPT_PLACECNST)
244                 tenv.block = node_users_smallest_common_dominator(irn, 1);
245         else
246                 tenv.block = get_nodes_block(irn);
247
248         switch (get_irn_opcode(irn)) {
249                 case iro_Const:
250                         cnst = gen_Const(&tenv);
251                         break;
252                 case iro_SymConst:
253                         cnst = gen_SymConst(&tenv);
254                         break;
255                 default:
256                         assert(0 && "Wrong usage of ia32_transform_const!");
257         }
258
259         assert(cnst && "Could not create ia32 Const");
260
261         /* set the new ia32 const */
262         exchange(irn, cnst);
263 }
264
265 /**
266  * Transform all firm consts and assure, we visit each const only once.
267  */
268 static void ia32_place_consts_walker(ir_node *irn, void *env) {
269         ia32_code_gen_t *cg = env;
270
271         if(!is_Const(irn) && !is_SymConst(irn))
272                 return;
273
274         ia32_transform_const(irn, cg);
275 }
276
277 /**
278  * Replace reference modes with mode_Iu and preserve store value modes.
279  */
280 static void ia32_set_modes(ir_node *irn, void *env) {
281         if (is_Block(irn))
282                 return;
283
284         /* transform all reference nodes into mode_Iu nodes */
285         if (mode_is_reference(get_irn_mode(irn))) {
286                 set_irn_mode(irn, mode_Iu);
287         }
288 }
289
290 /**
291  * Walks over the graph, transforms all firm consts into ia32 consts
292  * and places them into the "best" block.
293  * @param cg  The ia32 codegenerator object
294  */
295 static void ia32_transform_all_firm_consts(ia32_code_gen_t *cg) {
296         irg_walk_graph(cg->irg, NULL, ia32_place_consts_walker, cg);
297 }
298
299 /* Place all consts and change pointer arithmetics into unsigned integer arithmetics. */
300 void ia32_pre_transform_phase(ia32_code_gen_t *cg) {
301         /*
302                 We need to transform the consts twice:
303                 - the psi condition tree transformer needs existing constants to be ia32 constants
304                 - the psi condition tree transformer inserts new firm constants which need to be transformed
305         */
306         ia32_transform_all_firm_consts(cg);
307         irg_walk_graph(cg->irg, ia32_set_modes, ia32_transform_psi_cond_tree, cg);
308         ia32_transform_all_firm_consts(cg);
309 }
310
311 /********************************************************************************************************
312  *  _____                _           _         ____        _   _           _          _   _
313  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
314  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
315  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
316  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
317  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
318  *                | |                               | |
319  *                |_|                               |_|
320  ********************************************************************************************************/
321
322 /**
323  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
324  */
325
326 static int ia32_cnst_compare(ir_node *n1, ir_node *n2) {
327         return get_ia32_id_cnst(n1) == get_ia32_id_cnst(n2);
328 }
329
330 /**
331  * Checks for potential CJmp/CJmpAM optimization candidates.
332  */
333 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
334         ir_node *cand = NULL;
335         ir_node *prev = sched_prev(irn);
336
337         if (is_Block(prev)) {
338                 if (get_Block_n_cfgpreds(prev) == 1)
339                         prev = get_Block_cfgpred(prev, 0);
340                 else
341                         prev = NULL;
342         }
343
344         /* The predecessor must be a ProjX. */
345         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
346                 prev = get_Proj_pred(prev);
347
348                 if (is_op_func(prev))
349                         cand = prev;
350         }
351
352         return cand;
353 }
354
355 static int is_TestJmp_cand(const ir_node *irn) {
356         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
357 }
358
359 /**
360  * Checks if two consecutive arguments of cand matches
361  * the two arguments of irn (TestJmp).
362  */
363 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
364         ir_node *in1       = get_irn_n(irn, 0);
365         ir_node *in2       = get_irn_n(irn, 1);
366         int      i, n      = get_irn_arity(cand);
367         int      same_args = 0;
368
369         for (i = 0; i < n - 1; i++) {
370                 if (get_irn_n(cand, i)     == in1 &&
371                         get_irn_n(cand, i + 1) == in2)
372                 {
373                         same_args = 1;
374                         break;
375                 }
376         }
377
378         if (same_args)
379                 return ia32_cnst_compare(cand, irn);
380
381         return 0;
382 }
383
384 /**
385  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
386  */
387 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
388         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
389         int      replace = 0;
390
391         /* we found a possible candidate */
392         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
393
394         if (replace) {
395                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
396
397                 if (is_ia32_And(cand))
398                         set_irn_op(irn, op_ia32_CJmpAM);
399                 else
400                         set_irn_op(irn, op_ia32_CJmp);
401
402                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
403         }
404 }
405
406 static int is_CondJmp_cand(const ir_node *irn) {
407         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
408 }
409
410 /**
411  * Checks if the arguments of cand are the same of irn.
412  */
413 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
414         int i, n      = get_irn_arity(cand);
415         int same_args = 1;
416
417         for (i = 0; i < n; i++) {
418                 if (get_irn_n(cand, i) != get_irn_n(irn, i)) {
419                         same_args = 0;
420                         break;
421                 }
422         }
423
424         if (same_args)
425                 return ia32_cnst_compare(cand, irn);
426
427         return 0;
428 }
429
430 /**
431  * Tries to replace a CondJmp by a CJmpAM
432  */
433 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
434         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
435         int      replace = 0;
436
437         /* we found a possible candidate */
438         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
439
440         if (replace) {
441                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
442                 DBG_OPT_CJMP(irn);
443
444                 set_irn_op(irn, op_ia32_CJmpAM);
445
446                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
447         }
448 }
449
450 /**
451  * Creates a Push from Store(IncSP(gp_reg_size))
452  */
453 static void ia32_create_Push(ir_node *irn, ia32_code_gen_t *cg) {
454         ir_node  *sp  = get_irn_n(irn, 0);
455         ir_graph *irg = cg->irg;
456         ir_node *val, *next, *push, *bl, *proj_M, *proj_res, *old_proj_M, *mem;
457         const ir_edge_t *edge;
458         heights_t *h;
459
460         /* do not create push if store has already an offset assigned or base is not a IncSP */
461         if (get_ia32_am_offs(irn) || ! be_is_IncSP(sp))
462                 return;
463
464         /* do not create push if index is not NOREG */
465         if (arch_get_irn_register(cg->arch_env, get_irn_n(irn, 1)) !=
466                 &ia32_gp_regs[REG_GP_NOREG])
467                 return;
468
469         /* do not create push for floating point */
470         val = get_irn_n(irn, 2);
471         if (mode_is_float(get_irn_mode(val)))
472                 return;
473
474         /* do not create push if IncSp doesn't expand stack or expand size is different from register size */
475         if (be_get_IncSP_offset(sp) != get_mode_size_bytes(ia32_reg_classes[CLASS_ia32_gp].mode))
476                 return;
477
478         /* do not create push, if there is a path (inside the block) from the push value to IncSP */
479         h = heights_new(cg->irg);
480         if (get_nodes_block(val) == get_nodes_block(sp) &&
481                 heights_reachable_in_block(h, val, sp))
482         {
483                 heights_free(h);
484                 return;
485         }
486         heights_free(h);
487
488         /* ok, translate into Push */
489         edge       = get_irn_out_edge_first(irn);
490         old_proj_M = get_edge_src_irn(edge);
491         bl         = get_nodes_block(irn);
492
493         next = sched_next(irn);
494         sched_remove(irn);
495         sched_remove(sp);
496
497         /*
498                 build memory input:
499                 if the IncSP points to NoMem -> just use the memory input from store
500                 if IncSP points to somewhere else -> sync memory of IncSP and Store
501         */
502         mem = get_irn_n(irn, 3);
503
504         push = new_rd_ia32_Push(NULL, irg, bl, be_get_IncSP_pred(sp), val, mem);
505         proj_res = new_r_Proj(irg, bl, push, get_irn_mode(sp), pn_ia32_Push_stack);
506         proj_M   = new_r_Proj(irg, bl, push, mode_M, pn_ia32_Push_M);
507         add_irn_deps(push, sp);
508
509         /* copy a possible constant from the store */
510         set_ia32_id_cnst(push, get_ia32_id_cnst(irn));
511         set_ia32_immop_type(push, get_ia32_immop_type(irn));
512
513         /* the push must have SP out register */
514         arch_set_irn_register(cg->arch_env, push, arch_get_irn_register(cg->arch_env, sp));
515
516         exchange(old_proj_M, proj_M);
517         exchange(sp, proj_res);
518         sched_add_before(next, push);
519         sched_add_after(push, proj_res);
520 }
521
522 /**
523  * Creates a Pop from IncSP(Load(sp))
524  */
525 static void ia32_create_Pop(ir_node *irn, ia32_code_gen_t *cg) {
526         ir_node *old_proj_M = be_get_IncSP_mem(irn);
527         ir_node *load = skip_Proj(old_proj_M);
528         ir_node *old_proj_res = NULL;
529         ir_node *bl, *pop, *next, *proj_res, *proj_sp, *proj_M;
530         const ir_edge_t *edge;
531         const arch_register_t *reg, *sp;
532
533         if (! is_ia32_Load(load) || get_ia32_am_offs(load))
534                 return;
535
536         if (arch_get_irn_register(cg->arch_env, get_irn_n(load, 1)) !=
537                 &ia32_gp_regs[REG_GP_NOREG])
538                 return;
539         if (arch_get_irn_register(cg->arch_env, get_irn_n(load, 0)) != cg->isa->arch_isa.sp)
540                 return;
541
542         /* ok, translate into pop */
543         foreach_out_edge(load, edge) {
544                 ir_node *succ = get_edge_src_irn(edge);
545                 if (succ != old_proj_M) {
546                         old_proj_res = succ;
547                         break;
548                 }
549         }
550         if (! old_proj_res) {
551                 assert(0);
552                 return; /* should not happen */
553         }
554
555         bl = get_nodes_block(load);
556
557         /* IncSP is typically scheduled after the load, so remove it first */
558         sched_remove(irn);
559         next = sched_next(old_proj_res);
560         sched_remove(old_proj_res);
561         sched_remove(load);
562
563         reg = arch_get_irn_register(cg->arch_env, load);
564         sp  = arch_get_irn_register(cg->arch_env, irn);
565
566         pop      = new_rd_ia32_Pop(NULL, current_ir_graph, bl, get_irn_n(irn, 0), get_irn_n(load, 2));
567         proj_res = new_r_Proj(current_ir_graph, bl, pop, get_irn_mode(old_proj_res), pn_ia32_Pop_res);
568         proj_sp  = new_r_Proj(current_ir_graph, bl, pop, get_irn_mode(irn), pn_ia32_Pop_stack);
569         proj_M   = new_r_Proj(current_ir_graph, bl, pop, mode_M, pn_ia32_Pop_M);
570
571         exchange(old_proj_M, proj_M);
572         exchange(old_proj_res, proj_res);
573         exchange(irn, proj_sp);
574
575         arch_set_irn_register(cg->arch_env, proj_res, reg);
576         arch_set_irn_register(cg->arch_env, proj_sp, sp);
577
578         sched_add_before(next, proj_sp);
579         sched_add_before(proj_sp, proj_res);
580         sched_add_before(proj_res,pop);
581 }
582
583 /**
584  * Tries to optimize two following IncSP.
585  */
586 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
587         ir_node *prev = be_get_IncSP_pred(irn);
588         int real_uses = get_irn_n_edges(prev);
589
590         if (be_is_IncSP(prev) && real_uses == 1) {
591                 /* first IncSP has only one IncSP user, kill the first one */
592                 int prev_offs = be_get_IncSP_offset(prev);
593                 int curr_offs = be_get_IncSP_offset(irn);
594
595                 be_set_IncSP_offset(prev, prev_offs + curr_offs);
596
597                 /* Omit the optimized IncSP */
598                 be_set_IncSP_pred(irn, be_get_IncSP_pred(prev));
599         }
600 }
601
602 /**
603  * Performs Peephole Optimizations.
604  */
605 void ia32_peephole_optimization(ir_node *irn, void *env) {
606         ia32_code_gen_t *cg = env;
607
608         /* AMD CPUs want explicit compare before conditional jump  */
609         if (! ARCH_AMD(cg->opt_arch)) {
610                 if (is_ia32_TestJmp(irn))
611                         ia32_optimize_TestJmp(irn, cg);
612                 else if (is_ia32_CondJmp(irn))
613                         ia32_optimize_CondJmp(irn, cg);
614         }
615         /* seems to be buggy when using Pushes */
616         else if (be_is_IncSP(irn))
617                 ia32_optimize_IncSP(irn, cg);
618         else if (is_ia32_Store(irn))
619                 ia32_create_Push(irn, cg);
620 }
621
622
623
624 /******************************************************************
625  *              _     _                   __  __           _
626  *     /\      | |   | |                 |  \/  |         | |
627  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
628  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
629  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
630  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
631  *
632  ******************************************************************/
633
634 typedef struct {
635         ia32_code_gen_t *cg;
636         heights_t       *h;
637 } ia32_am_opt_env_t;
638
639 static int node_is_ia32_comm(const ir_node *irn) {
640         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
641 }
642
643 static int ia32_get_irn_n_edges(const ir_node *irn) {
644         const ir_edge_t *edge;
645         int cnt = 0;
646
647         foreach_out_edge(irn, edge) {
648                 cnt++;
649         }
650
651         return cnt;
652 }
653
654 /**
655  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
656  *
657  * @param pred       The node to be checked
658  * @param is_op_func The check-function
659  * @return 1 if conditions are fulfilled, 0 otherwise
660  */
661 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
662         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
663                 return 1;
664         }
665
666         return 0;
667 }
668
669 /**
670  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
671  * and if the predecessor is in block bl.
672  *
673  * @param bl         The block
674  * @param pred       The node to be checked
675  * @param is_op_func The check-function
676  * @return 1 if conditions are fulfilled, 0 otherwise
677  */
678 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
679         int (*is_op_func)(const ir_node *n))
680 {
681         if (is_Proj(pred)) {
682                 pred = get_Proj_pred(pred);
683                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
684                         return 1;
685                 }
686         }
687
688         return 0;
689 }
690
691 /**
692  * Checks if irn is a candidate for address calculation.
693  *
694  * - none of the operand must be a Load  within the same block OR
695  * - all Loads must have more than one user                    OR
696  * - the irn has a frame entity (it's a former FrameAddr)
697  *
698  * @param block   The block the Loads must/mustnot be in
699  * @param irn     The irn to check
700  * return 1 if irn is a candidate, 0 otherwise
701  */
702 static int is_addr_candidate(const ir_node *block, const ir_node *irn) {
703         ir_node *in, *left, *right;
704         int      n, is_cand = 1;
705
706         left  = get_irn_n(irn, 2);
707         right = get_irn_n(irn, 3);
708
709         in = left;
710
711         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
712                 n         = ia32_get_irn_n_edges(in);
713                 is_cand   = (n == 1) ? 0 : is_cand;  /* load with only one user: don't create LEA */
714         }
715
716         in = right;
717
718         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
719                 n         = ia32_get_irn_n_edges(in);
720                 is_cand   = (n == 1) ? 0 : is_cand;  /* load with only one user: don't create LEA */
721         }
722
723         is_cand = get_ia32_frame_ent(irn) ? 1 : is_cand;
724
725         return is_cand;
726 }
727
728 /**
729  * Checks if irn is a candidate for address mode.
730  *
731  * address mode (AM):
732  * - at least one operand has to be a Load within the same block AND
733  * - the load must not have other users than the irn             AND
734  * - the irn must not have a frame entity set
735  *
736  * @param cg          The ia32 code generator
737  * @param h           The height information of the irg
738  * @param block       The block the Loads must/mustnot be in
739  * @param irn         The irn to check
740  * return 0 if irn is no candidate, 1 if left load can be used, 2 if right one, 3 for both
741  */
742 static ia32_am_cand_t is_am_candidate(ia32_code_gen_t *cg, heights_t *h, const ir_node *block, ir_node *irn) {
743         ir_node *in, *load, *other, *left, *right;
744         int      n, is_cand = 0, cand;
745
746         if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn) || is_ia32_vfild(irn) || is_ia32_vfist(irn) ||
747                 is_ia32_GetST0(irn) || is_ia32_SetST0(irn) || is_ia32_xStoreSimple(irn))
748                 return 0;
749
750         left  = get_irn_n(irn, 2);
751         right = get_irn_n(irn, 3);
752
753         in = left;
754
755         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
756                 n         = ia32_get_irn_n_edges(in);
757                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
758
759                 load  = get_Proj_pred(in);
760                 other = right;
761
762                 /* 8bit Loads are not supported, they cannot be used with every register */
763                 if (get_mode_size_bits(get_ia32_ls_mode(load)) < 16)
764                         is_cand = 0;
765
766                 /* If there is a data dependency of other irn from load: cannot use AM */
767                 if (is_cand && get_nodes_block(other) == block) {
768                         other   = skip_Proj(other);
769                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
770                         /* this could happen in loops */
771                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
772                 }
773         }
774
775         cand    = is_cand ? IA32_AM_CAND_LEFT : IA32_AM_CAND_NONE;
776         in      = right;
777         is_cand = 0;
778
779         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
780                 n         = ia32_get_irn_n_edges(in);
781                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
782
783                 load  = get_Proj_pred(in);
784                 other = left;
785
786                 /* 8bit Loads are not supported, they cannot be used with every register */
787                 if (get_mode_size_bits(get_ia32_ls_mode(load)) < 16)
788                         is_cand = 0;
789
790                 /* If there is a data dependency of other irn from load: cannot use load */
791                 if (is_cand && get_nodes_block(other) == block) {
792                         other   = skip_Proj(other);
793                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
794                         /* this could happen in loops */
795                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
796                 }
797         }
798
799         cand = is_cand ? (cand | IA32_AM_CAND_RIGHT) : cand;
800
801         /* check some special cases */
802         if (USE_SSE2(cg) && is_ia32_Conv_I2FP(irn)) {
803                 /* SSE Conv I -> FP cvtsi2s(s|d) can only load 32 bit values */
804                 if (get_mode_size_bits(get_ia32_tgt_mode(irn)) != 32)
805                         cand = IA32_AM_CAND_NONE;
806         }
807         else if (is_ia32_Conv_I2I(irn)) {
808                 /* we cannot load an N bit value and implicitly convert it into an M bit value if N > M */
809                 if (get_mode_size_bits(get_ia32_src_mode(irn)) > get_mode_size_bits(get_ia32_tgt_mode(irn)))
810                         cand = IA32_AM_CAND_NONE;
811         }
812
813         /* if the irn has a frame entity: we do not use address mode */
814         return get_ia32_frame_ent(irn) ? IA32_AM_CAND_NONE : cand;
815 }
816
817 /**
818  * Compares the base and index addr and the load/store entities
819  * and returns 1 if they are equal.
820  */
821 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
822                                                                         const ir_node *addr_b, const ir_node *addr_i)
823 {
824         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
825         entity *lent     = get_ia32_frame_ent(load);
826         entity *sent     = get_ia32_frame_ent(store);
827         ident  *lid      = get_ia32_am_sc(load);
828         ident  *sid      = get_ia32_am_sc(store);
829         char   *loffs    = get_ia32_am_offs(load);
830         char   *soffs    = get_ia32_am_offs(store);
831
832         /* are both entities set and equal? */
833         if (is_equal && (lent || sent))
834                 is_equal = lent && sent && (lent == sent);
835
836         /* are address mode idents set and equal? */
837         if (is_equal && (lid || sid))
838                 is_equal = lid && sid && (lid == sid);
839
840         /* are offsets set and equal */
841         if (is_equal && (loffs || soffs))
842                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
843
844         /* are the load and the store of the same mode? */
845         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
846
847         return is_equal;
848 }
849
850 typedef enum _ia32_take_lea_attr {
851         IA32_LEA_ATTR_NONE  = 0,
852         IA32_LEA_ATTR_BASE  = (1 << 0),
853         IA32_LEA_ATTR_INDEX = (1 << 1),
854         IA32_LEA_ATTR_OFFS  = (1 << 2),
855         IA32_LEA_ATTR_SCALE = (1 << 3),
856         IA32_LEA_ATTR_AMSC  = (1 << 4),
857         IA32_LEA_ATTR_FENT  = (1 << 5)
858 } ia32_take_lea_attr;
859
860 /**
861  * Decides if we have to keep the LEA operand or if we can assimilate it.
862  */
863 static int do_new_lea(ir_node *irn, ir_node *base, ir_node *index, ir_node *lea,
864                 int have_am_sc, ia32_code_gen_t *cg)
865 {
866         entity  *irn_ent  = get_ia32_frame_ent(irn);
867         entity  *lea_ent  = get_ia32_frame_ent(lea);
868         int      ret_val  = 0;
869         int      is_noreg_base  = be_is_NoReg(cg, base);
870         int      is_noreg_index = be_is_NoReg(cg, index);
871         ia32_am_flavour_t am_flav = get_ia32_am_flavour(lea);
872
873         /* If the Add and the LEA both have a different frame entity set: keep */
874         if (irn_ent && lea_ent && (irn_ent != lea_ent))
875                 return IA32_LEA_ATTR_NONE;
876         else if (! irn_ent && lea_ent)
877                 ret_val |= IA32_LEA_ATTR_FENT;
878
879         /* If the Add and the LEA both have already an address mode symconst: keep */
880         if (have_am_sc && get_ia32_am_sc(lea))
881                 return IA32_LEA_ATTR_NONE;
882         else if (get_ia32_am_sc(lea))
883                 ret_val |= IA32_LEA_ATTR_AMSC;
884
885         /* Check the different base-index combinations */
886
887         if (! is_noreg_base && ! is_noreg_index) {
888                 /* Assimilate if base is the lea and the LEA is just a Base + Offset calculation */
889                 if ((base == lea) && ! (am_flav & ia32_I ? 1 : 0)) {
890                         if (am_flav & ia32_O)
891                                 ret_val |= IA32_LEA_ATTR_OFFS;
892
893                         ret_val |= IA32_LEA_ATTR_BASE;
894                 }
895                 else
896                         return IA32_LEA_ATTR_NONE;
897         }
898         else if (! is_noreg_base && is_noreg_index) {
899                 /* Base is set but index not */
900                 if (base == lea) {
901                         /* Base points to LEA: assimilate everything */
902                         if (am_flav & ia32_O)
903                                 ret_val |= IA32_LEA_ATTR_OFFS;
904                         if (am_flav & ia32_S)
905                                 ret_val |= IA32_LEA_ATTR_SCALE;
906                         if (am_flav & ia32_I)
907                                 ret_val |= IA32_LEA_ATTR_INDEX;
908
909                         ret_val |= IA32_LEA_ATTR_BASE;
910                 }
911                 else if (am_flav & ia32_B ? 0 : 1) {
912                         /* Base is not the LEA but the LEA is an index only calculation: assimilate */
913                         if (am_flav & ia32_O)
914                                 ret_val |= IA32_LEA_ATTR_OFFS;
915                         if (am_flav & ia32_S)
916                                 ret_val |= IA32_LEA_ATTR_SCALE;
917
918                         ret_val |= IA32_LEA_ATTR_INDEX;
919                 }
920                 else
921                         return IA32_LEA_ATTR_NONE;
922         }
923         else if (is_noreg_base && ! is_noreg_index) {
924                 /* Index is set but not base */
925                 if (index == lea) {
926                         /* Index points to LEA: assimilate everything */
927                         if (am_flav & ia32_O)
928                                 ret_val |= IA32_LEA_ATTR_OFFS;
929                         if (am_flav & ia32_S)
930                                 ret_val |= IA32_LEA_ATTR_SCALE;
931                         if (am_flav & ia32_B)
932                                 ret_val |= IA32_LEA_ATTR_BASE;
933
934                         ret_val |= IA32_LEA_ATTR_INDEX;
935                 }
936                 else if (am_flav & ia32_I ? 0 : 1) {
937                         /* Index is not the LEA but the LEA is a base only calculation: assimilate */
938                         if (am_flav & ia32_O)
939                                 ret_val |= IA32_LEA_ATTR_OFFS;
940                         if (am_flav & ia32_S)
941                                 ret_val |= IA32_LEA_ATTR_SCALE;
942
943                         ret_val |= IA32_LEA_ATTR_BASE;
944                 }
945                 else
946                         return IA32_LEA_ATTR_NONE;
947         }
948         else {
949                 assert(0 && "There must have been set base or index");
950         }
951
952         return ret_val;
953 }
954
955 /**
956  * Adds res before irn into schedule if irn was scheduled.
957  * @param irn  The schedule point
958  * @param res  The node to be scheduled
959  */
960 static INLINE void try_add_to_sched(ir_node *irn, ir_node *res) {
961         if (sched_is_scheduled(irn))
962                 sched_add_before(irn, res);
963 }
964
965 /**
966  * Removes irn from schedule if it was scheduled. If irn is a mode_T node
967  * all it's Projs are removed as well.
968  * @param irn  The irn to be removed from schedule
969  */
970 static INLINE void try_remove_from_sched(ir_node *irn) {
971         if (sched_is_scheduled(irn)) {
972                 if (get_irn_mode(irn) == mode_T) {
973                         const ir_edge_t *edge;
974                         foreach_out_edge(irn, edge) {
975                                 ir_node *proj = get_edge_src_irn(edge);
976                                 if (sched_is_scheduled(proj))
977                                         sched_remove(proj);
978                         }
979                 }
980                 sched_remove(irn);
981         }
982 }
983
984 /**
985  * Folds Add or Sub to LEA if possible
986  */
987 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
988         ir_graph   *irg        = get_irn_irg(irn);
989         dbg_info   *dbg        = get_irn_dbg_info(irn);
990         ir_node    *block      = get_nodes_block(irn);
991         ir_node    *res        = irn;
992         ir_node    *shift      = NULL;
993         ir_node    *lea_o      = NULL;
994         ir_node    *lea        = NULL;
995         char       *offs       = NULL;
996         const char *offs_cnst  = NULL;
997         char       *offs_lea   = NULL;
998         int         scale      = 0;
999         int         isadd      = 0;
1000         int         dolea      = 0;
1001         int         have_am_sc = 0;
1002         int         am_sc_sign = 0;
1003         ident      *am_sc      = NULL;
1004         entity     *lea_ent    = NULL;
1005         ir_node    *left, *right, *temp;
1006         ir_node    *base, *index;
1007         int consumed_left_shift;
1008         ia32_am_flavour_t am_flav;
1009         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
1010
1011         if (is_ia32_Add(irn))
1012                 isadd = 1;
1013
1014         left  = get_irn_n(irn, 2);
1015         right = get_irn_n(irn, 3);
1016
1017         /* "normalize" arguments in case of add with two operands */
1018         if  (isadd && ! be_is_NoReg(cg, right)) {
1019                 /* put LEA == ia32_am_O as right operand */
1020                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
1021                         set_irn_n(irn, 2, right);
1022                         set_irn_n(irn, 3, left);
1023                         temp  = left;
1024                         left  = right;
1025                         right = temp;
1026                 }
1027
1028                 /* put LEA != ia32_am_O as left operand */
1029                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
1030                         set_irn_n(irn, 2, right);
1031                         set_irn_n(irn, 3, left);
1032                         temp  = left;
1033                         left  = right;
1034                         right = temp;
1035                 }
1036
1037                 /* put SHL as left operand iff left is NOT a LEA */
1038                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
1039                         set_irn_n(irn, 2, right);
1040                         set_irn_n(irn, 3, left);
1041                         temp  = left;
1042                         left  = right;
1043                         right = temp;
1044                 }
1045         }
1046
1047         base    = left;
1048         index   = noreg;
1049         offs    = NULL;
1050         scale   = 0;
1051         am_flav = 0;
1052
1053         /* check for operation with immediate */
1054         if (is_ia32_ImmConst(irn)) {
1055                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
1056
1057                 offs_cnst = get_ia32_cnst(irn);
1058                 dolea     = 1;
1059         }
1060         else if (is_ia32_ImmSymConst(irn)) {
1061                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
1062
1063                 have_am_sc = 1;
1064                 dolea      = 1;
1065                 am_sc      = get_ia32_id_cnst(irn);
1066                 am_sc_sign = is_ia32_am_sc_sign(irn);
1067         }
1068
1069         /* determine the operand which needs to be checked */
1070         temp = be_is_NoReg(cg, right) ? left : right;
1071
1072         /* check if right operand is AMConst (LEA with ia32_am_O)  */
1073         /* but we can only eat it up if there is no other symconst */
1074         /* because the linker won't accept two symconsts           */
1075         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
1076                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
1077
1078                 offs_lea   = get_ia32_am_offs(temp);
1079                 am_sc      = get_ia32_am_sc(temp);
1080                 am_sc_sign = is_ia32_am_sc_sign(temp);
1081                 have_am_sc = 1;
1082                 dolea      = 1;
1083                 lea_o      = temp;
1084
1085                 if (temp == base)
1086                         base = noreg;
1087                 else if (temp == right)
1088                         right = noreg;
1089         }
1090
1091         if (isadd) {
1092                 /* default for add -> make right operand to index */
1093                 index               = right;
1094                 dolea               = 1;
1095                 consumed_left_shift = -1;
1096
1097                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
1098
1099                 /* determine the operand which needs to be checked */
1100                 temp = left;
1101                 if (is_ia32_Lea(left)) {
1102                         temp = right;
1103                         consumed_left_shift = 0;
1104                 }
1105
1106                 /* check for SHL 1,2,3 */
1107                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
1108                         temp  = get_Proj_pred(temp);
1109                         shift = temp;
1110
1111                         if (get_ia32_Immop_tarval(temp)) {
1112                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
1113
1114                                 if (scale <= 3) {
1115                                         index               = get_irn_n(temp, 2);
1116                                         consumed_left_shift = consumed_left_shift < 0 ? 1 : 0;
1117
1118                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
1119                                 }
1120                                 else {
1121                                         scale = 0;
1122                                         shift = NULL;
1123                                 }
1124                         }
1125                 }
1126
1127                 /* fix base */
1128                 if (! be_is_NoReg(cg, index)) {
1129                         /* if we have index, but left == right -> no base */
1130                         if (left == right) {
1131                                 base = noreg;
1132                         }
1133                         else if (consumed_left_shift == 1) {
1134                                 /* -> base is right operand  */
1135                                 base = (right == lea_o) ? noreg : right;
1136                         }
1137                 }
1138         }
1139
1140         /* Try to assimilate a LEA as left operand */
1141         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
1142                 /* check if we can assimilate the LEA */
1143                 int take_attr = do_new_lea(irn, base, index, left, have_am_sc, cg);
1144
1145                 if (take_attr == IA32_LEA_ATTR_NONE) {
1146                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
1147                 }
1148                 else {
1149                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
1150                         lea = left; /* for statistics */
1151
1152                         if (take_attr & IA32_LEA_ATTR_OFFS)
1153                                 offs = get_ia32_am_offs(left);
1154
1155                         if (take_attr & IA32_LEA_ATTR_AMSC) {
1156                                 am_sc      = get_ia32_am_sc(left);
1157                                 have_am_sc = 1;
1158                                 am_sc_sign = is_ia32_am_sc_sign(left);
1159                         }
1160
1161                         if (take_attr & IA32_LEA_ATTR_SCALE)
1162                                 scale = get_ia32_am_scale(left);
1163
1164                         if (take_attr & IA32_LEA_ATTR_BASE)
1165                                 base = get_irn_n(left, 0);
1166
1167                         if (take_attr & IA32_LEA_ATTR_INDEX)
1168                                 index = get_irn_n(left, 1);
1169
1170                         if (take_attr & IA32_LEA_ATTR_FENT)
1171                                 lea_ent = get_ia32_frame_ent(left);
1172                 }
1173         }
1174
1175         /* ok, we can create a new LEA */
1176         if (dolea) {
1177                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
1178
1179                 /* add the old offset of a previous LEA */
1180                 if (offs) {
1181                         add_ia32_am_offs(res, offs);
1182                 }
1183
1184                 /* add the new offset */
1185                 if (isadd) {
1186                         if (offs_cnst) {
1187                                 add_ia32_am_offs(res, offs_cnst);
1188                         }
1189                         if (offs_lea) {
1190                                 add_ia32_am_offs(res, offs_lea);
1191                         }
1192                 }
1193                 else {
1194                         /* either lea_O-cnst, -cnst or -lea_O  */
1195                         if (offs_cnst) {
1196                                 if (offs_lea) {
1197                                         add_ia32_am_offs(res, offs_lea);
1198                                 }
1199
1200                                 sub_ia32_am_offs(res, offs_cnst);
1201                         }
1202                         else {
1203                                 sub_ia32_am_offs(res, offs_lea);
1204                         }
1205                 }
1206
1207                 /* set the address mode symconst */
1208                 if (have_am_sc) {
1209                         set_ia32_am_sc(res, am_sc);
1210                         if (am_sc_sign)
1211                                 set_ia32_am_sc_sign(res);
1212                 }
1213
1214                 /* copy the frame entity (could be set in case of Add */
1215                 /* which was a FrameAddr) */
1216                 if (lea_ent)
1217                         set_ia32_frame_ent(res, lea_ent);
1218                 else
1219                         set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
1220
1221                 if (get_ia32_frame_ent(res))
1222                         set_ia32_use_frame(res);
1223
1224                 /* set scale */
1225                 set_ia32_am_scale(res, scale);
1226
1227                 am_flav = ia32_am_N;
1228                 /* determine new am flavour */
1229                 if (offs || offs_cnst || offs_lea || have_am_sc) {
1230                         am_flav |= ia32_O;
1231                 }
1232                 if (! be_is_NoReg(cg, base)) {
1233                         am_flav |= ia32_B;
1234                 }
1235                 if (! be_is_NoReg(cg, index)) {
1236                         am_flav |= ia32_I;
1237                 }
1238                 if (scale > 0) {
1239                         am_flav |= ia32_S;
1240                 }
1241                 set_ia32_am_flavour(res, am_flav);
1242
1243                 set_ia32_op_type(res, ia32_AddrModeS);
1244
1245                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
1246
1247                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
1248
1249                 /* we will exchange it, report here before the Proj is created */
1250                 if (shift && lea && lea_o) {
1251                         try_remove_from_sched(shift);
1252                         try_remove_from_sched(lea);
1253                         try_remove_from_sched(lea_o);
1254                         DBG_OPT_LEA4(irn, lea_o, lea, shift, res);
1255                 }
1256                 else if (shift && lea) {
1257                         try_remove_from_sched(shift);
1258                         try_remove_from_sched(lea);
1259                         DBG_OPT_LEA3(irn, lea, shift, res);
1260                 }
1261                 else if (shift && lea_o) {
1262                         try_remove_from_sched(shift);
1263                         try_remove_from_sched(lea_o);
1264                         DBG_OPT_LEA3(irn, lea_o, shift, res);
1265                 }
1266                 else if (lea && lea_o) {
1267                         try_remove_from_sched(lea);
1268                         try_remove_from_sched(lea_o);
1269                         DBG_OPT_LEA3(irn, lea_o, lea, res);
1270                 }
1271                 else if (shift) {
1272                         try_remove_from_sched(shift);
1273                         DBG_OPT_LEA2(irn, shift, res);
1274                 }
1275                 else if (lea) {
1276                         try_remove_from_sched(lea);
1277                         DBG_OPT_LEA2(irn, lea, res);
1278                 }
1279                 else if (lea_o) {
1280                         try_remove_from_sched(lea_o);
1281                         DBG_OPT_LEA2(irn, lea_o, res);
1282                 }
1283                 else
1284                         DBG_OPT_LEA1(irn, res);
1285
1286                 /* get the result Proj of the Add/Sub */
1287                 try_add_to_sched(irn, res);
1288                 try_remove_from_sched(irn);
1289                 irn = ia32_get_res_proj(irn);
1290
1291                 assert(irn && "Couldn't find result proj");
1292
1293                 /* exchange the old op with the new LEA */
1294                 exchange(irn, res);
1295         }
1296
1297         return res;
1298 }
1299
1300
1301 /**
1302  * Merges a Load/Store node with a LEA.
1303  * @param irn The Load/Store node
1304  * @param lea The LEA
1305  */
1306 static void merge_loadstore_lea(ir_node *irn, ir_node *lea) {
1307         entity *irn_ent = get_ia32_frame_ent(irn);
1308         entity *lea_ent = get_ia32_frame_ent(lea);
1309
1310         /* If the irn and the LEA both have a different frame entity set: do not merge */
1311         if (irn_ent && lea_ent && (irn_ent != lea_ent))
1312                 return;
1313         else if (! irn_ent && lea_ent) {
1314                 set_ia32_frame_ent(irn, lea_ent);
1315                 set_ia32_use_frame(irn);
1316         }
1317
1318         /* get the AM attributes from the LEA */
1319         add_ia32_am_offs(irn, get_ia32_am_offs(lea));
1320         set_ia32_am_scale(irn, get_ia32_am_scale(lea));
1321         set_ia32_am_flavour(irn, get_ia32_am_flavour(lea));
1322
1323         set_ia32_am_sc(irn, get_ia32_am_sc(lea));
1324         if (is_ia32_am_sc_sign(lea))
1325                 set_ia32_am_sc_sign(irn);
1326
1327         set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1328
1329         /* set base and index */
1330         set_irn_n(irn, 0, get_irn_n(lea, 0));
1331         set_irn_n(irn, 1, get_irn_n(lea, 1));
1332
1333         try_remove_from_sched(lea);
1334
1335         /* clear remat flag */
1336         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1337
1338         if (is_ia32_Ld(irn))
1339                 DBG_OPT_LOAD_LEA(lea, irn);
1340         else
1341                 DBG_OPT_STORE_LEA(lea, irn);
1342
1343 }
1344
1345 /**
1346  * Sets new_right index of irn to right and new_left index to left.
1347  * Also exchange left and right
1348  */
1349 static void exchange_left_right(ir_node *irn, ir_node **left, ir_node **right, int new_left, int new_right) {
1350         ir_node *temp;
1351
1352         set_irn_n(irn, new_right, *right);
1353         set_irn_n(irn, new_left, *left);
1354
1355         temp   = *left;
1356         *left  = *right;
1357         *right = temp;
1358
1359         /* this is only needed for Compares, but currently ALL nodes
1360          * have this attribute :-) */
1361         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1362 }
1363
1364 /**
1365  * Performs address calculation optimization (create LEAs if possible)
1366  */
1367 static void optimize_lea(ir_node *irn, void *env) {
1368         ia32_code_gen_t *cg  = env;
1369         ir_node         *block, *noreg_gp, *left, *right;
1370
1371         if (! is_ia32_irn(irn))
1372                 return;
1373
1374         /* Following cases can occur:                                  */
1375         /* - Sub (l, imm) -> LEA [base - offset]                       */
1376         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
1377         /* - Add (l, imm) -> LEA [base + offset]                       */
1378         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
1379         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
1380         /* - Add (l, r) -> LEA [base + index * scale]                  */
1381         /*              with scale > 1 iff l/r == shl (1,2,3)          */
1382
1383         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
1384                 left     = get_irn_n(irn, 2);
1385                 right    = get_irn_n(irn, 3);
1386                 block    = get_nodes_block(irn);
1387                 noreg_gp = ia32_new_NoReg_gp(cg);
1388
1389             /* Do not try to create a LEA if one of the operands is a Load. */
1390                 /* check is irn is a candidate for address calculation */
1391                 if (is_addr_candidate(block, irn)) {
1392                         ir_node *res;
1393
1394                         DBG((cg->mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
1395                         res = fold_addr(cg, irn, noreg_gp);
1396
1397                         if (res != irn)
1398                                 DB((cg->mod, LEVEL_1, "transformed into %+F\n", res));
1399                         else
1400                                 DB((cg->mod, LEVEL_1, "not transformed\n"));
1401                 }
1402         }
1403         else if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
1404                 /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
1405                 /* - Store -> LEA into Store }       it might be better to keep the LEA             */
1406                 left = get_irn_n(irn, 0);
1407
1408                 if (is_ia32_Lea(left)) {
1409                         const ir_edge_t *edge, *ne;
1410                         ir_node *src;
1411
1412                         /* merge all Loads/Stores connected to this LEA with the LEA */
1413                         foreach_out_edge_safe(left, edge, ne) {
1414                                 src = get_edge_src_irn(edge);
1415
1416                                 if (src && (get_edge_src_pos(edge) == 0) && (is_ia32_Ld(src) || is_ia32_St(src) || is_ia32_Store8Bit(src))) {
1417                                         DBG((cg->mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1418                                         if (! is_ia32_got_lea(src))
1419                                                 merge_loadstore_lea(src, left);
1420                                         set_ia32_got_lea(src);
1421                                 }
1422                         }
1423                 }
1424         }
1425 }
1426
1427
1428 /**
1429  * Checks for address mode patterns and performs the
1430  * necessary transformations.
1431  * This function is called by a walker.
1432  */
1433 static void optimize_am(ir_node *irn, void *env) {
1434         ia32_am_opt_env_t *am_opt_env = env;
1435         ia32_code_gen_t   *cg         = am_opt_env->cg;
1436         heights_t         *h          = am_opt_env->h;
1437         ir_node           *block, *noreg_gp, *noreg_fp;
1438         ir_node           *left, *right;
1439         ir_node           *store, *load, *mem_proj;
1440         ir_node           *succ, *addr_b, *addr_i;
1441         int               check_am_src          = 0;
1442         int               need_exchange_on_fail = 0;
1443         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
1444
1445         if (! is_ia32_irn(irn) || is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn))
1446                 return;
1447
1448         block    = get_nodes_block(irn);
1449         noreg_gp = ia32_new_NoReg_gp(cg);
1450         noreg_fp = ia32_new_NoReg_fp(cg);
1451
1452         DBG((mod, LEVEL_1, "checking for AM\n"));
1453
1454         /* fold following patterns:                                                         */
1455         /* - op -> Load into AMop with am_Source                                            */
1456         /*   conditions:                                                                    */
1457         /*     - op is am_Source capable AND                                                */
1458         /*     - the Load is only used by this op AND                                       */
1459         /*     - the Load is in the same block                                              */
1460         /* - Store -> op -> Load  into AMop with am_Dest                                    */
1461         /*   conditions:                                                                    */
1462         /*     - op is am_Dest capable AND                                                  */
1463         /*     - the Store uses the same address as the Load AND                            */
1464         /*     - the Load is only used by this op AND                                       */
1465         /*     - the Load and Store are in the same block AND                               */
1466         /*     - nobody else uses the result of the op                                      */
1467
1468         if ((get_ia32_am_support(irn) != ia32_am_None) && ! is_ia32_Lea(irn)) {
1469                 ia32_am_cand_t cand      = is_am_candidate(cg, h, block, irn);
1470                 ia32_am_cand_t orig_cand = cand;
1471
1472                 /* cand == 1: load is left;   cand == 2: load is right; */
1473
1474                 if (cand == IA32_AM_CAND_NONE)
1475                         return;
1476
1477                 DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1478
1479                 left  = get_irn_n(irn, 2);
1480                 if (get_irn_arity(irn) == 4) {
1481                         /* it's an "unary" operation */
1482                         right = left;
1483                 }
1484                 else {
1485                         right = get_irn_n(irn, 3);
1486                 }
1487
1488                 /* normalize commutative ops */
1489                 if (node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_RIGHT)) {
1490
1491                         /* Assure that left operand is always a Load if there is one    */
1492                         /* because non-commutative ops can only use Dest AM if the left */
1493                         /* operand is a load, so we only need to check left operand.    */
1494
1495                         exchange_left_right(irn, &left, &right, 3, 2);
1496                         need_exchange_on_fail = 1;
1497
1498                         /* now: load is right */
1499                         cand = IA32_AM_CAND_LEFT;
1500                 }
1501
1502                 /* check for Store -> op -> Load */
1503
1504                 /* Store -> op -> Load optimization is only possible if supported by op */
1505                 /* and if right operand is a Load                                       */
1506                 if ((get_ia32_am_support(irn) & ia32_am_Dest) && (cand & IA32_AM_CAND_LEFT))
1507                 {
1508                         /* An address mode capable op always has a result Proj.                  */
1509                         /* If this Proj is used by more than one other node, we don't need to    */
1510                         /* check further, otherwise we check for Store and remember the address, */
1511                         /* the Store points to. */
1512
1513                         succ = ia32_get_res_proj(irn);
1514                         assert(succ && "Couldn't find result proj");
1515
1516                         addr_b = NULL;
1517                         addr_i = NULL;
1518                         store  = NULL;
1519
1520                         /* now check for users and Store */
1521                         if (ia32_get_irn_n_edges(succ) == 1) {
1522                                 succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1523
1524                                 if (is_ia32_xStore(succ) || is_ia32_Store(succ)) {
1525                                         store  = succ;
1526                                         addr_b = get_irn_n(store, 0);
1527                                         addr_i = get_irn_n(store, 1);
1528                                 }
1529                         }
1530
1531                         if (store) {
1532                                 /* we found a Store as single user: Now check for Load */
1533
1534                                 /* skip the Proj for easier access */
1535                                 load = is_Proj(right) ? (is_ia32_Load(get_Proj_pred(right)) ? get_Proj_pred(right) : NULL) : NULL;
1536
1537                                 /* Extra check for commutative ops with two Loads */
1538                                 /* -> put the interesting Load left               */
1539                                 if (load && node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_BOTH)) {
1540                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1541                                                 /* We exchange left and right, so it's easier to kill     */
1542                                                 /* the correct Load later and to handle unary operations. */
1543                                                 exchange_left_right(irn, &left, &right, 3, 2);
1544                                                 need_exchange_on_fail ^= 1;
1545                                         }
1546                                 }
1547
1548                                 /* skip the Proj for easier access */
1549                                 load = get_Proj_pred(left);
1550
1551                                 /* Compare Load and Store address */
1552                                 if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1553                                         /* Left Load is from same address, so we can */
1554                                         /* disconnect the Load and Store here        */
1555
1556                                         /* set new base, index and attributes */
1557                                         set_irn_n(irn, 0, addr_b);
1558                                         set_irn_n(irn, 1, addr_i);
1559                                         add_ia32_am_offs(irn, get_ia32_am_offs(load));
1560                                         set_ia32_am_scale(irn, get_ia32_am_scale(load));
1561                                         set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1562                                         set_ia32_op_type(irn, ia32_AddrModeD);
1563                                         set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1564                                         set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1565
1566                                         set_ia32_am_sc(irn, get_ia32_am_sc(load));
1567                                         if (is_ia32_am_sc_sign(load))
1568                                                 set_ia32_am_sc_sign(irn);
1569
1570                                         if (is_ia32_use_frame(load))
1571                                                 set_ia32_use_frame(irn);
1572
1573                                         /* connect to Load memory and disconnect Load */
1574                                         if (get_irn_arity(irn) == 5) {
1575                                                 /* binary AMop */
1576                                                 set_irn_n(irn, 4, get_irn_n(load, 2));
1577                                                 set_irn_n(irn, 2, noreg_gp);
1578                                         }
1579                                         else {
1580                                                 /* unary AMop */
1581                                                 set_irn_n(irn, 3, get_irn_n(load, 2));
1582                                                 set_irn_n(irn, 2, noreg_gp);
1583                                         }
1584
1585                                         /* connect the memory Proj of the Store to the op */
1586                                         mem_proj = ia32_get_proj_for_mode(store, mode_M);
1587                                         set_Proj_pred(mem_proj, irn);
1588                                         set_Proj_proj(mem_proj, 1);
1589
1590                                         /* clear remat flag */
1591                                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1592
1593                                         try_remove_from_sched(load);
1594                                         try_remove_from_sched(store);
1595                                         DBG_OPT_AM_D(load, store, irn);
1596
1597                                         DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1598
1599                                         need_exchange_on_fail = 0;
1600                                 }
1601                         } /* if (store) */
1602                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1603                                 /* There was no store, check if we still can optimize for source address mode */
1604                                 check_am_src = 1;
1605                         }
1606                 } /* if (support AM Dest) */
1607                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1608                         /* op doesn't support am AM Dest -> check for AM Source */
1609                         check_am_src = 1;
1610                 }
1611
1612                 /* was exchanged but optimize failed: exchange back */
1613                 if (need_exchange_on_fail) {
1614                         exchange_left_right(irn, &left, &right, 3, 2);
1615                         cand = orig_cand;
1616                 }
1617
1618                 need_exchange_on_fail = 0;
1619
1620                 /* normalize commutative ops */
1621                 if (check_am_src && node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_LEFT)) {
1622
1623                         /* Assure that right operand is always a Load if there is one  */
1624                         /* because non-commutative ops can only use Source AM if the   */
1625                         /* right operand is a Load, so we only need to check the right */
1626                         /* operand afterwards.                                         */
1627
1628                         exchange_left_right(irn, &left, &right, 3, 2);
1629                         need_exchange_on_fail = 1;
1630
1631                         /* now: load is left */
1632                         cand = IA32_AM_CAND_RIGHT;
1633                 }
1634
1635                 /* optimize op -> Load iff Load is only used by this op    */
1636                 /* and right operand is a Load which only used by this irn */
1637                 if (check_am_src                &&
1638                         (cand & IA32_AM_CAND_RIGHT) &&
1639                         (get_irn_arity(irn) == 5)   &&
1640                         (ia32_get_irn_n_edges(right) == 1))
1641                 {
1642                         right = get_Proj_pred(right);
1643
1644                         addr_b = get_irn_n(right, 0);
1645                         addr_i = get_irn_n(right, 1);
1646
1647                         /* set new base, index and attributes */
1648                         set_irn_n(irn, 0, addr_b);
1649                         set_irn_n(irn, 1, addr_i);
1650                         add_ia32_am_offs(irn, get_ia32_am_offs(right));
1651                         set_ia32_am_scale(irn, get_ia32_am_scale(right));
1652                         set_ia32_am_flavour(irn, get_ia32_am_flavour(right));
1653                         set_ia32_op_type(irn, ia32_AddrModeS);
1654                         set_ia32_frame_ent(irn, get_ia32_frame_ent(right));
1655                         set_ia32_ls_mode(irn, get_ia32_ls_mode(right));
1656
1657                         set_ia32_am_sc(irn, get_ia32_am_sc(right));
1658                         if (is_ia32_am_sc_sign(right))
1659                                 set_ia32_am_sc_sign(irn);
1660
1661                         /* clear remat flag */
1662                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1663
1664                         if (is_ia32_use_frame(right))
1665                                 set_ia32_use_frame(irn);
1666
1667                         /* connect to Load memory */
1668                         set_irn_n(irn, 4, get_irn_n(right, 2));
1669
1670                         /* this is only needed for Compares, but currently ALL nodes
1671                          * have this attribute :-) */
1672                         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1673
1674                         /* disconnect from Load */
1675                         set_irn_n(irn, 3, noreg_gp);
1676
1677                         DBG_OPT_AM_S(right, irn);
1678
1679                         /* If Load has a memory Proj, connect it to the op */
1680                         mem_proj = ia32_get_proj_for_mode(right, mode_M);
1681                         if (mem_proj) {
1682                                 set_Proj_pred(mem_proj, irn);
1683                                 set_Proj_proj(mem_proj, 1);
1684                         }
1685
1686                         try_remove_from_sched(right);
1687
1688                         DB((mod, LEVEL_1, "merged with %+F into source AM\n", right));
1689                 }
1690                 else {
1691                         /* was exchanged but optimize failed: exchange back */
1692                         if (need_exchange_on_fail)
1693                                 exchange_left_right(irn, &left, &right, 3, 2);
1694                 }
1695         }
1696 }
1697
1698 /**
1699  * Performs address mode optimization.
1700  */
1701 void ia32_optimize_addressmode(ia32_code_gen_t *cg) {
1702         /* if we are supposed to do AM or LEA optimization: recalculate edges */
1703         if (cg->opt & (IA32_OPT_DOAM | IA32_OPT_LEA)) {
1704                 edges_deactivate(cg->irg);
1705                 edges_activate(cg->irg);
1706         }
1707         else {
1708                 /* no optimizations at all */
1709                 return;
1710         }
1711
1712         /* beware: we cannot optimize LEA and AM in one run because */
1713         /*         LEA optimization adds new nodes to the irg which */
1714         /*         invalidates the phase data                       */
1715
1716         if (cg->opt & IA32_OPT_LEA) {
1717                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_lea, cg);
1718         }
1719
1720         if (cg->dump)
1721                 be_dump(cg->irg, "-lea", dump_ir_block_graph_sched);
1722
1723         if (cg->opt & IA32_OPT_DOAM) {
1724                 /* we need height information for am optimization */
1725                 heights_t *h = heights_new(cg->irg);
1726                 ia32_am_opt_env_t env;
1727
1728                 env.cg = cg;
1729                 env.h  = h;
1730
1731                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_am, &env);
1732
1733                 heights_free(h);
1734         }
1735 }