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