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