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