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