- Improved addressmode optimisation for conv nodes
[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                 ia32_create_Pushs(irn, cg);
670         }
671 }
672
673 void ia32_peephole_optimization(ir_graph *irg, ia32_code_gen_t *cg) {
674         irg_walk_graph(irg, ia32_peephole_optimize_node, NULL, cg);
675 }
676
677 /******************************************************************
678  *              _     _                   __  __           _
679  *     /\      | |   | |                 |  \/  |         | |
680  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
681  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
682  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
683  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
684  *
685  ******************************************************************/
686
687 typedef struct {
688         ia32_code_gen_t *cg;
689         heights_t       *h;
690 } ia32_am_opt_env_t;
691
692 static int node_is_ia32_comm(const ir_node *irn) {
693         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
694 }
695
696 static int ia32_get_irn_n_edges(const ir_node *irn) {
697         const ir_edge_t *edge;
698         int cnt = 0;
699
700         foreach_out_edge(irn, edge) {
701                 cnt++;
702         }
703
704         return cnt;
705 }
706
707 /**
708  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
709  *
710  * @param pred       The node to be checked
711  * @param is_op_func The check-function
712  * @return 1 if conditions are fulfilled, 0 otherwise
713  */
714 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
715         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
716                 return 1;
717         }
718
719         return 0;
720 }
721
722 /**
723  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
724  * and if the predecessor is in block bl.
725  *
726  * @param bl         The block
727  * @param pred       The node to be checked
728  * @param is_op_func The check-function
729  * @return 1 if conditions are fulfilled, 0 otherwise
730  */
731 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
732         int (*is_op_func)(const ir_node *n))
733 {
734         if (is_Proj(pred)) {
735                 pred = get_Proj_pred(pred);
736                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
737                         return 1;
738                 }
739         }
740
741         return 0;
742 }
743
744 /**
745  * Checks if irn is a candidate for address calculation.
746  *
747  * - none of the operand must be a Load  within the same block OR
748  * - all Loads must have more than one user                    OR
749  * - the irn has a frame entity (it's a former FrameAddr)
750  *
751  * @param block   The block the Loads must/mustnot be in
752  * @param irn     The irn to check
753  * return 1 if irn is a candidate, 0 otherwise
754  */
755 static int is_addr_candidate(const ir_node *block, const ir_node *irn) {
756         ir_node *in, *left, *right;
757         int      n, is_cand = 1;
758
759         left  = get_irn_n(irn, 2);
760         right = get_irn_n(irn, 3);
761
762         in = left;
763
764 #ifndef AGGRESSIVE_AM
765         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
766                 n         = ia32_get_irn_n_edges(in);
767                 is_cand   = (n == 1) ? 0 : is_cand;  /* load with only one user: don't create LEA */
768         }
769
770         in = right;
771
772         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
773                 n         = ia32_get_irn_n_edges(in);
774                 is_cand   = (n == 1) ? 0 : is_cand;  /* load with only one user: don't create LEA */
775         }
776 #else
777         (void) n;
778 #endif
779
780         is_cand = get_ia32_frame_ent(irn) ? 1 : is_cand;
781
782         return is_cand;
783 }
784
785 /**
786  * Checks if irn is a candidate for address mode.
787  *
788  * address mode (AM):
789  * - at least one operand has to be a Load within the same block AND
790  * - the load must not have other users than the irn             AND
791  * - the irn must not have a frame entity set
792  *
793  * @param cg          The ia32 code generator
794  * @param h           The height information of the irg
795  * @param block       The block the Loads must/mustnot be in
796  * @param irn         The irn to check
797  * return 0 if irn is no candidate, 1 if left load can be used, 2 if right one, 3 for both
798  */
799 static ia32_am_cand_t is_am_candidate(ia32_code_gen_t *cg, heights_t *h, const ir_node *block, ir_node *irn) {
800         ir_node *in, *load, *other, *left, *right;
801         int      is_cand = 0, cand;
802
803         if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn) || is_ia32_vfild(irn) || is_ia32_vfist(irn) ||
804                 is_ia32_GetST0(irn) || is_ia32_SetST0(irn) || is_ia32_xStoreSimple(irn))
805                 return 0;
806
807         left  = get_irn_n(irn, 2);
808         right = get_irn_n(irn, 3);
809
810         in = left;
811
812         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
813 #ifndef AGGRESSIVE_AM
814                 int n;
815                 n         = ia32_get_irn_n_edges(in);
816                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
817 #else
818                 is_cand   = 1;
819 #endif
820
821                 load  = get_Proj_pred(in);
822                 other = right;
823
824                 /* 8bit Loads are not supported (for binary ops),
825                  * they cannot be used with every register */
826                 if (get_irn_arity(irn) != 4 && get_mode_size_bits(get_ia32_ls_mode(load)) < 16) {
827                         assert(get_irn_arity(irn) == 5);
828                         is_cand = 0;
829                 }
830
831                 /* If there is a data dependency of other irn from load: cannot use AM */
832                 if (is_cand && get_nodes_block(other) == block) {
833                         other   = skip_Proj(other);
834                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
835                         /* this could happen in loops */
836                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
837                 }
838         }
839
840         cand    = is_cand ? IA32_AM_CAND_LEFT : IA32_AM_CAND_NONE;
841         in      = right;
842         is_cand = 0;
843
844         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
845 #ifndef AGGRESSIVE_AM
846                 int n;
847                 n         = ia32_get_irn_n_edges(in);
848                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
849 #endif
850
851                 load  = get_Proj_pred(in);
852                 other = left;
853
854                 /* 8bit Loads are not supported, they cannot be used with every register */
855                 if (get_mode_size_bits(get_ia32_ls_mode(load)) < 16)
856                         is_cand = 0;
857
858                 /* If there is a data dependency of other irn from load: cannot use load */
859                 if (is_cand && get_nodes_block(other) == block) {
860                         other   = skip_Proj(other);
861                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
862                         /* this could happen in loops */
863                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
864                 }
865         }
866
867         cand = is_cand ? (cand | IA32_AM_CAND_RIGHT) : cand;
868
869         /* check some special cases */
870         if (USE_SSE2(cg) && is_ia32_Conv_I2FP(irn)) {
871                 /* SSE Conv I -> FP cvtsi2s(s|d) can only load 32 bit values */
872                 if (get_mode_size_bits(get_ia32_tgt_mode(irn)) != 32)
873                         cand = IA32_AM_CAND_NONE;
874         }
875         else if (is_ia32_Conv_I2I(irn)) {
876                 /* we cannot load an N bit value and implicitly convert it into an M bit value if N > M */
877                 if (get_mode_size_bits(get_ia32_src_mode(irn)) > get_mode_size_bits(get_ia32_tgt_mode(irn)))
878                         cand = IA32_AM_CAND_NONE;
879         }
880
881         /* if the irn has a frame entity: we do not use address mode */
882         return get_ia32_frame_ent(irn) ? IA32_AM_CAND_NONE : cand;
883 }
884
885 /**
886  * Compares the base and index addr and the load/store entities
887  * and returns 1 if they are equal.
888  */
889 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
890                                                                         const ir_node *addr_b, const ir_node *addr_i)
891 {
892         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
893         entity *lent     = get_ia32_frame_ent(load);
894         entity *sent     = get_ia32_frame_ent(store);
895         ident  *lid      = get_ia32_am_sc(load);
896         ident  *sid      = get_ia32_am_sc(store);
897         char   *loffs    = get_ia32_am_offs(load);
898         char   *soffs    = get_ia32_am_offs(store);
899
900         /* are both entities set and equal? */
901         if (is_equal && (lent || sent))
902                 is_equal = lent && sent && (lent == sent);
903
904         /* are address mode idents set and equal? */
905         if (is_equal && (lid || sid))
906                 is_equal = lid && sid && (lid == sid);
907
908         /* are offsets set and equal */
909         if (is_equal && (loffs || soffs))
910                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
911
912         /* are the load and the store of the same mode? */
913         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
914
915         return is_equal;
916 }
917
918 typedef enum _ia32_take_lea_attr {
919         IA32_LEA_ATTR_NONE  = 0,
920         IA32_LEA_ATTR_BASE  = (1 << 0),
921         IA32_LEA_ATTR_INDEX = (1 << 1),
922         IA32_LEA_ATTR_OFFS  = (1 << 2),
923         IA32_LEA_ATTR_SCALE = (1 << 3),
924         IA32_LEA_ATTR_AMSC  = (1 << 4),
925         IA32_LEA_ATTR_FENT  = (1 << 5)
926 } ia32_take_lea_attr;
927
928 /**
929  * Decides if we have to keep the LEA operand or if we can assimilate it.
930  */
931 static int do_new_lea(ir_node *irn, ir_node *base, ir_node *index, ir_node *lea,
932                 int have_am_sc, ia32_code_gen_t *cg)
933 {
934         entity  *irn_ent  = get_ia32_frame_ent(irn);
935         entity  *lea_ent  = get_ia32_frame_ent(lea);
936         int      ret_val  = 0;
937         int      is_noreg_base  = be_is_NoReg(cg, base);
938         int      is_noreg_index = be_is_NoReg(cg, index);
939         ia32_am_flavour_t am_flav = get_ia32_am_flavour(lea);
940
941         /* If the Add and the LEA both have a different frame entity set: keep */
942         if (irn_ent && lea_ent && (irn_ent != lea_ent))
943                 return IA32_LEA_ATTR_NONE;
944         else if (! irn_ent && lea_ent)
945                 ret_val |= IA32_LEA_ATTR_FENT;
946
947         /* If the Add and the LEA both have already an address mode symconst: keep */
948         if (have_am_sc && get_ia32_am_sc(lea))
949                 return IA32_LEA_ATTR_NONE;
950         else if (get_ia32_am_sc(lea))
951                 ret_val |= IA32_LEA_ATTR_AMSC;
952
953         /* Check the different base-index combinations */
954
955         if (! is_noreg_base && ! is_noreg_index) {
956                 /* Assimilate if base is the lea and the LEA is just a Base + Offset calculation */
957                 if ((base == lea) && ! (am_flav & ia32_I ? 1 : 0)) {
958                         if (am_flav & ia32_O)
959                                 ret_val |= IA32_LEA_ATTR_OFFS;
960
961                         ret_val |= IA32_LEA_ATTR_BASE;
962                 }
963                 else
964                         return IA32_LEA_ATTR_NONE;
965         }
966         else if (! is_noreg_base && is_noreg_index) {
967                 /* Base is set but index not */
968                 if (base == lea) {
969                         /* Base points to LEA: assimilate everything */
970                         if (am_flav & ia32_O)
971                                 ret_val |= IA32_LEA_ATTR_OFFS;
972                         if (am_flav & ia32_S)
973                                 ret_val |= IA32_LEA_ATTR_SCALE;
974                         if (am_flav & ia32_I)
975                                 ret_val |= IA32_LEA_ATTR_INDEX;
976
977                         ret_val |= IA32_LEA_ATTR_BASE;
978                 }
979                 else if (am_flav & ia32_B ? 0 : 1) {
980                         /* Base is not the LEA but the LEA is an index only calculation: assimilate */
981                         if (am_flav & ia32_O)
982                                 ret_val |= IA32_LEA_ATTR_OFFS;
983                         if (am_flav & ia32_S)
984                                 ret_val |= IA32_LEA_ATTR_SCALE;
985
986                         ret_val |= IA32_LEA_ATTR_INDEX;
987                 }
988                 else
989                         return IA32_LEA_ATTR_NONE;
990         }
991         else if (is_noreg_base && ! is_noreg_index) {
992                 /* Index is set but not base */
993                 if (index == lea) {
994                         /* Index points to LEA: assimilate everything */
995                         if (am_flav & ia32_O)
996                                 ret_val |= IA32_LEA_ATTR_OFFS;
997                         if (am_flav & ia32_S)
998                                 ret_val |= IA32_LEA_ATTR_SCALE;
999                         if (am_flav & ia32_B)
1000                                 ret_val |= IA32_LEA_ATTR_BASE;
1001
1002                         ret_val |= IA32_LEA_ATTR_INDEX;
1003                 }
1004                 else if (am_flav & ia32_I ? 0 : 1) {
1005                         /* Index is not the LEA but the LEA is a base only calculation: assimilate */
1006                         if (am_flav & ia32_O)
1007                                 ret_val |= IA32_LEA_ATTR_OFFS;
1008                         if (am_flav & ia32_S)
1009                                 ret_val |= IA32_LEA_ATTR_SCALE;
1010
1011                         ret_val |= IA32_LEA_ATTR_BASE;
1012                 }
1013                 else
1014                         return IA32_LEA_ATTR_NONE;
1015         }
1016         else {
1017                 assert(0 && "There must have been set base or index");
1018         }
1019
1020         return ret_val;
1021 }
1022
1023 /**
1024  * Adds res before irn into schedule if irn was scheduled.
1025  * @param irn  The schedule point
1026  * @param res  The node to be scheduled
1027  */
1028 static INLINE void try_add_to_sched(ir_node *irn, ir_node *res) {
1029         if (sched_is_scheduled(irn))
1030                 sched_add_before(irn, res);
1031 }
1032
1033 /**
1034  * Removes irn from schedule if it was scheduled. If irn is a mode_T node
1035  * all it's Projs are removed as well.
1036  * @param irn  The irn to be removed from schedule
1037  */
1038 static INLINE void try_remove_from_sched(ir_node *irn) {
1039         int i, arity;
1040
1041         if (sched_is_scheduled(irn)) {
1042                 if (get_irn_mode(irn) == mode_T) {
1043                         const ir_edge_t *edge;
1044                         foreach_out_edge(irn, edge) {
1045                                 ir_node *proj = get_edge_src_irn(edge);
1046                                 if (sched_is_scheduled(proj)) {
1047                                         set_irn_n(proj, 0, new_Bad());
1048                                         sched_remove(proj);
1049                                 }
1050                         }
1051                 }
1052
1053                 arity = get_irn_arity(irn);
1054                 for(i = 0; i < arity; ++i) {
1055                         set_irn_n(irn, i, new_Bad());
1056                 }
1057                 sched_remove(irn);
1058         }
1059 }
1060
1061 /**
1062  * Folds Add or Sub to LEA if possible
1063  */
1064 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
1065         ir_graph   *irg        = get_irn_irg(irn);
1066         dbg_info   *dbg        = get_irn_dbg_info(irn);
1067         ir_node    *block      = get_nodes_block(irn);
1068         ir_node    *res        = irn;
1069         ir_node    *shift      = NULL;
1070         ir_node    *lea_o      = NULL;
1071         ir_node    *lea        = NULL;
1072         char       *offs       = NULL;
1073         const char *offs_cnst  = NULL;
1074         char       *offs_lea   = NULL;
1075         int         scale      = 0;
1076         int         isadd      = 0;
1077         int         dolea      = 0;
1078         int         have_am_sc = 0;
1079         int         am_sc_sign = 0;
1080         ident      *am_sc      = NULL;
1081         entity     *lea_ent    = NULL;
1082         ir_node    *left, *right, *temp;
1083         ir_node    *base, *index;
1084         int consumed_left_shift;
1085         ia32_am_flavour_t am_flav;
1086         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
1087
1088         if (is_ia32_Add(irn))
1089                 isadd = 1;
1090
1091         left  = get_irn_n(irn, 2);
1092         right = get_irn_n(irn, 3);
1093
1094         /* "normalize" arguments in case of add with two operands */
1095         if  (isadd && ! be_is_NoReg(cg, right)) {
1096                 /* put LEA == ia32_am_O as right operand */
1097                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
1098                         set_irn_n(irn, 2, right);
1099                         set_irn_n(irn, 3, left);
1100                         temp  = left;
1101                         left  = right;
1102                         right = temp;
1103                 }
1104
1105                 /* put LEA != ia32_am_O as left operand */
1106                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
1107                         set_irn_n(irn, 2, right);
1108                         set_irn_n(irn, 3, left);
1109                         temp  = left;
1110                         left  = right;
1111                         right = temp;
1112                 }
1113
1114                 /* put SHL as left operand iff left is NOT a LEA */
1115                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
1116                         set_irn_n(irn, 2, right);
1117                         set_irn_n(irn, 3, left);
1118                         temp  = left;
1119                         left  = right;
1120                         right = temp;
1121                 }
1122         }
1123
1124         base    = left;
1125         index   = noreg;
1126         offs    = NULL;
1127         scale   = 0;
1128         am_flav = 0;
1129
1130         /* check for operation with immediate */
1131         if (is_ia32_ImmConst(irn)) {
1132                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
1133
1134                 offs_cnst = get_ia32_cnst(irn);
1135                 dolea     = 1;
1136         }
1137         else if (is_ia32_ImmSymConst(irn)) {
1138                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
1139
1140                 have_am_sc = 1;
1141                 dolea      = 1;
1142                 am_sc      = get_ia32_id_cnst(irn);
1143                 am_sc_sign = is_ia32_am_sc_sign(irn);
1144         }
1145
1146         /* determine the operand which needs to be checked */
1147         temp = be_is_NoReg(cg, right) ? left : right;
1148
1149         /* check if right operand is AMConst (LEA with ia32_am_O)  */
1150         /* but we can only eat it up if there is no other symconst */
1151         /* because the linker won't accept two symconsts           */
1152         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
1153                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
1154
1155                 offs_lea   = get_ia32_am_offs(temp);
1156                 am_sc      = get_ia32_am_sc(temp);
1157                 am_sc_sign = is_ia32_am_sc_sign(temp);
1158                 have_am_sc = 1;
1159                 dolea      = 1;
1160                 lea_o      = temp;
1161
1162                 if (temp == base)
1163                         base = noreg;
1164                 else if (temp == right)
1165                         right = noreg;
1166         }
1167
1168         if (isadd) {
1169                 /* default for add -> make right operand to index */
1170                 index               = right;
1171                 dolea               = 1;
1172                 consumed_left_shift = -1;
1173
1174                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
1175
1176                 /* determine the operand which needs to be checked */
1177                 temp = left;
1178                 if (is_ia32_Lea(left)) {
1179                         temp = right;
1180                         consumed_left_shift = 0;
1181                 }
1182
1183                 /* check for SHL 1,2,3 */
1184                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
1185                         temp  = get_Proj_pred(temp);
1186                         shift = temp;
1187
1188                         if (get_ia32_Immop_tarval(temp)) {
1189                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
1190
1191                                 if (scale <= 3) {
1192                                         index               = get_irn_n(temp, 2);
1193                                         consumed_left_shift = consumed_left_shift < 0 ? 1 : 0;
1194
1195                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
1196                                 }
1197                                 else {
1198                                         scale = 0;
1199                                         shift = NULL;
1200                                 }
1201                         }
1202                 }
1203
1204                 /* fix base */
1205                 if (! be_is_NoReg(cg, index)) {
1206                         /* if we have index, but left == right -> no base */
1207                         if (left == right) {
1208                                 base = noreg;
1209                         }
1210                         else if (consumed_left_shift == 1) {
1211                                 /* -> base is right operand  */
1212                                 base = (right == lea_o) ? noreg : right;
1213                         }
1214                 }
1215         }
1216
1217         /* Try to assimilate a LEA as left operand */
1218         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
1219                 /* check if we can assimilate the LEA */
1220                 int take_attr = do_new_lea(irn, base, index, left, have_am_sc, cg);
1221
1222                 if (take_attr == IA32_LEA_ATTR_NONE) {
1223                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
1224                 }
1225                 else {
1226                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
1227                         lea = left; /* for statistics */
1228
1229                         if (take_attr & IA32_LEA_ATTR_OFFS)
1230                                 offs = get_ia32_am_offs(left);
1231
1232                         if (take_attr & IA32_LEA_ATTR_AMSC) {
1233                                 am_sc      = get_ia32_am_sc(left);
1234                                 have_am_sc = 1;
1235                                 am_sc_sign = is_ia32_am_sc_sign(left);
1236                         }
1237
1238                         if (take_attr & IA32_LEA_ATTR_SCALE)
1239                                 scale = get_ia32_am_scale(left);
1240
1241                         if (take_attr & IA32_LEA_ATTR_BASE)
1242                                 base = get_irn_n(left, 0);
1243
1244                         if (take_attr & IA32_LEA_ATTR_INDEX)
1245                                 index = get_irn_n(left, 1);
1246
1247                         if (take_attr & IA32_LEA_ATTR_FENT)
1248                                 lea_ent = get_ia32_frame_ent(left);
1249                 }
1250         }
1251
1252         /* ok, we can create a new LEA */
1253         if (dolea) {
1254                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
1255
1256                 /* add the old offset of a previous LEA */
1257                 if (offs) {
1258                         add_ia32_am_offs(res, offs);
1259                 }
1260
1261                 /* add the new offset */
1262                 if (isadd) {
1263                         if (offs_cnst) {
1264                                 add_ia32_am_offs(res, offs_cnst);
1265                         }
1266                         if (offs_lea) {
1267                                 add_ia32_am_offs(res, offs_lea);
1268                         }
1269                 }
1270                 else {
1271                         /* either lea_O-cnst, -cnst or -lea_O  */
1272                         if (offs_cnst) {
1273                                 if (offs_lea) {
1274                                         add_ia32_am_offs(res, offs_lea);
1275                                 }
1276
1277                                 sub_ia32_am_offs(res, offs_cnst);
1278                         }
1279                         else {
1280                                 sub_ia32_am_offs(res, offs_lea);
1281                         }
1282                 }
1283
1284                 /* set the address mode symconst */
1285                 if (have_am_sc) {
1286                         set_ia32_am_sc(res, am_sc);
1287                         if (am_sc_sign)
1288                                 set_ia32_am_sc_sign(res);
1289                 }
1290
1291                 /* copy the frame entity (could be set in case of Add */
1292                 /* which was a FrameAddr) */
1293                 if (lea_ent)
1294                         set_ia32_frame_ent(res, lea_ent);
1295                 else
1296                         set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
1297
1298                 if (get_ia32_frame_ent(res))
1299                         set_ia32_use_frame(res);
1300
1301                 /* set scale */
1302                 set_ia32_am_scale(res, scale);
1303
1304                 am_flav = ia32_am_N;
1305                 /* determine new am flavour */
1306                 if (offs || offs_cnst || offs_lea || have_am_sc) {
1307                         am_flav |= ia32_O;
1308                 }
1309                 if (! be_is_NoReg(cg, base)) {
1310                         am_flav |= ia32_B;
1311                 }
1312                 if (! be_is_NoReg(cg, index)) {
1313                         am_flav |= ia32_I;
1314                 }
1315                 if (scale > 0) {
1316                         am_flav |= ia32_S;
1317                 }
1318                 set_ia32_am_flavour(res, am_flav);
1319
1320                 set_ia32_op_type(res, ia32_AddrModeS);
1321
1322                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
1323
1324                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
1325
1326                 /* we will exchange it, report here before the Proj is created */
1327                 if (shift && lea && lea_o) {
1328                         try_remove_from_sched(shift);
1329                         try_remove_from_sched(lea);
1330                         try_remove_from_sched(lea_o);
1331                         DBG_OPT_LEA4(irn, lea_o, lea, shift, res);
1332                 }
1333                 else if (shift && lea) {
1334                         try_remove_from_sched(shift);
1335                         try_remove_from_sched(lea);
1336                         DBG_OPT_LEA3(irn, lea, shift, res);
1337                 }
1338                 else if (shift && lea_o) {
1339                         try_remove_from_sched(shift);
1340                         try_remove_from_sched(lea_o);
1341                         DBG_OPT_LEA3(irn, lea_o, shift, res);
1342                 }
1343                 else if (lea && lea_o) {
1344                         try_remove_from_sched(lea);
1345                         try_remove_from_sched(lea_o);
1346                         DBG_OPT_LEA3(irn, lea_o, lea, res);
1347                 }
1348                 else if (shift) {
1349                         try_remove_from_sched(shift);
1350                         DBG_OPT_LEA2(irn, shift, res);
1351                 }
1352                 else if (lea) {
1353                         try_remove_from_sched(lea);
1354                         DBG_OPT_LEA2(irn, lea, res);
1355                 }
1356                 else if (lea_o) {
1357                         try_remove_from_sched(lea_o);
1358                         DBG_OPT_LEA2(irn, lea_o, res);
1359                 }
1360                 else
1361                         DBG_OPT_LEA1(irn, res);
1362
1363                 /* get the result Proj of the Add/Sub */
1364                 try_add_to_sched(irn, res);
1365                 try_remove_from_sched(irn);
1366                 irn = ia32_get_res_proj(irn);
1367
1368                 assert(irn && "Couldn't find result proj");
1369
1370                 /* exchange the old op with the new LEA */
1371                 exchange(irn, res);
1372         }
1373
1374         return res;
1375 }
1376
1377
1378 /**
1379  * Merges a Load/Store node with a LEA.
1380  * @param irn The Load/Store node
1381  * @param lea The LEA
1382  */
1383 static void merge_loadstore_lea(ir_node *irn, ir_node *lea) {
1384         entity *irn_ent = get_ia32_frame_ent(irn);
1385         entity *lea_ent = get_ia32_frame_ent(lea);
1386
1387         /* If the irn and the LEA both have a different frame entity set: do not merge */
1388         if (irn_ent && lea_ent && (irn_ent != lea_ent))
1389                 return;
1390         else if (! irn_ent && lea_ent) {
1391                 set_ia32_frame_ent(irn, lea_ent);
1392                 set_ia32_use_frame(irn);
1393         }
1394
1395         /* get the AM attributes from the LEA */
1396         add_ia32_am_offs(irn, get_ia32_am_offs(lea));
1397         set_ia32_am_scale(irn, get_ia32_am_scale(lea));
1398         set_ia32_am_flavour(irn, get_ia32_am_flavour(lea));
1399
1400         set_ia32_am_sc(irn, get_ia32_am_sc(lea));
1401         if (is_ia32_am_sc_sign(lea))
1402                 set_ia32_am_sc_sign(irn);
1403
1404         set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1405
1406         /* set base and index */
1407         set_irn_n(irn, 0, get_irn_n(lea, 0));
1408         set_irn_n(irn, 1, get_irn_n(lea, 1));
1409
1410         try_remove_from_sched(lea);
1411
1412         /* clear remat flag */
1413         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1414
1415         if (is_ia32_Ld(irn))
1416                 DBG_OPT_LOAD_LEA(lea, irn);
1417         else
1418                 DBG_OPT_STORE_LEA(lea, irn);
1419
1420 }
1421
1422 /**
1423  * Sets new_right index of irn to right and new_left index to left.
1424  * Also exchange left and right
1425  */
1426 static void exchange_left_right(ir_node *irn, ir_node **left, ir_node **right, int new_left, int new_right) {
1427         ir_node *temp;
1428
1429         set_irn_n(irn, new_right, *right);
1430         set_irn_n(irn, new_left, *left);
1431
1432         temp   = *left;
1433         *left  = *right;
1434         *right = temp;
1435
1436         /* this is only needed for Compares, but currently ALL nodes
1437          * have this attribute :-) */
1438         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1439 }
1440
1441 /**
1442  * Performs address calculation optimization (create LEAs if possible)
1443  */
1444 static void optimize_lea(ir_node *irn, void *env) {
1445         ia32_code_gen_t *cg  = env;
1446         ir_node         *block, *noreg_gp, *left, *right;
1447
1448         if (! is_ia32_irn(irn))
1449                 return;
1450
1451         /* Following cases can occur:                                  */
1452         /* - Sub (l, imm) -> LEA [base - offset]                       */
1453         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
1454         /* - Add (l, imm) -> LEA [base + offset]                       */
1455         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
1456         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
1457         /* - Add (l, r) -> LEA [base + index * scale]                  */
1458         /*              with scale > 1 iff l/r == shl (1,2,3)          */
1459
1460         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
1461                 left     = get_irn_n(irn, 2);
1462                 right    = get_irn_n(irn, 3);
1463                 block    = get_nodes_block(irn);
1464                 noreg_gp = ia32_new_NoReg_gp(cg);
1465
1466             /* Do not try to create a LEA if one of the operands is a Load. */
1467                 /* check is irn is a candidate for address calculation */
1468                 if (is_addr_candidate(block, irn)) {
1469                         ir_node *res;
1470
1471                         DBG((cg->mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
1472                         res = fold_addr(cg, irn, noreg_gp);
1473
1474                         if (res != irn)
1475                                 DB((cg->mod, LEVEL_1, "transformed into %+F\n", res));
1476                         else
1477                                 DB((cg->mod, LEVEL_1, "not transformed\n"));
1478                 }
1479         }
1480         else if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
1481                 /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
1482                 /* - Store -> LEA into Store }       it might be better to keep the LEA             */
1483                 left = get_irn_n(irn, 0);
1484
1485                 if (is_ia32_Lea(left)) {
1486                         const ir_edge_t *edge, *ne;
1487                         ir_node *src;
1488
1489                         /* merge all Loads/Stores connected to this LEA with the LEA */
1490                         foreach_out_edge_safe(left, edge, ne) {
1491                                 src = get_edge_src_irn(edge);
1492
1493                                 if (src && (get_edge_src_pos(edge) == 0) && (is_ia32_Ld(src) || is_ia32_St(src) || is_ia32_Store8Bit(src))) {
1494                                         DBG((cg->mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1495                                         if (! is_ia32_got_lea(src))
1496                                                 merge_loadstore_lea(src, left);
1497                                         set_ia32_got_lea(src);
1498                                 }
1499                         }
1500                 }
1501         }
1502 }
1503
1504 /**
1505  * Checks for address mode patterns and performs the
1506  * necessary transformations.
1507  * This function is called by a walker.
1508  */
1509 static void optimize_am(ir_node *irn, void *env) {
1510         ia32_am_opt_env_t *am_opt_env = env;
1511         ia32_code_gen_t   *cg         = am_opt_env->cg;
1512         heights_t         *h          = am_opt_env->h;
1513         ir_node           *block, *left, *right;
1514         ir_node           *store, *load, *mem_proj;
1515         ir_node           *succ, *addr_b, *addr_i;
1516         int               check_am_src          = 0;
1517         int               need_exchange_on_fail = 0;
1518         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
1519
1520         if (! is_ia32_irn(irn) || is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn))
1521                 return;
1522
1523         block = get_nodes_block(irn);
1524
1525         DBG((mod, LEVEL_1, "checking for AM\n"));
1526
1527         /* fold following patterns:                                                         */
1528         /* - op -> Load into AMop with am_Source                                            */
1529         /*   conditions:                                                                    */
1530         /*     - op is am_Source capable AND                                                */
1531         /*     - the Load is only used by this op AND                                       */
1532         /*     - the Load is in the same block                                              */
1533         /* - Store -> op -> Load  into AMop with am_Dest                                    */
1534         /*   conditions:                                                                    */
1535         /*     - op is am_Dest capable AND                                                  */
1536         /*     - the Store uses the same address as the Load AND                            */
1537         /*     - the Load is only used by this op AND                                       */
1538         /*     - the Load and Store are in the same block AND                               */
1539         /*     - nobody else uses the result of the op                                      */
1540
1541         if ((get_ia32_am_support(irn) != ia32_am_None) && ! is_ia32_Lea(irn)) {
1542                 ia32_am_cand_t cand      = is_am_candidate(cg, h, block, irn);
1543                 ia32_am_cand_t orig_cand = cand;
1544
1545                 /* cand == 1: load is left;   cand == 2: load is right; */
1546
1547                 if (cand == IA32_AM_CAND_NONE)
1548                         return;
1549
1550                 DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1551
1552                 left  = get_irn_n(irn, 2);
1553                 if (get_irn_arity(irn) == 4) {
1554                         /* it's an "unary" operation */
1555                         right = left;
1556                         cand = IA32_AM_CAND_BOTH;
1557                 }
1558                 else {
1559                         right = get_irn_n(irn, 3);
1560                 }
1561
1562                 /* normalize commutative ops */
1563                 if (node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_RIGHT)) {
1564
1565                         /* Assure that left operand is always a Load if there is one    */
1566                         /* because non-commutative ops can only use Dest AM if the left */
1567                         /* operand is a load, so we only need to check left operand.    */
1568
1569                         exchange_left_right(irn, &left, &right, 3, 2);
1570                         need_exchange_on_fail = 1;
1571
1572                         /* now: load is right */
1573                         cand = IA32_AM_CAND_LEFT;
1574                 }
1575
1576                 /* check for Store -> op -> Load */
1577
1578                 /* Store -> op -> Load optimization is only possible if supported by op */
1579                 /* and if right operand is a Load                                       */
1580                 if ((get_ia32_am_support(irn) & ia32_am_Dest) && (cand & IA32_AM_CAND_LEFT))
1581                 {
1582                         /* An address mode capable op always has a result Proj.                  */
1583                         /* If this Proj is used by more than one other node, we don't need to    */
1584                         /* check further, otherwise we check for Store and remember the address, */
1585                         /* the Store points to. */
1586
1587                         succ = ia32_get_res_proj(irn);
1588                         assert(succ && "Couldn't find result proj");
1589
1590                         addr_b = NULL;
1591                         addr_i = NULL;
1592                         store  = NULL;
1593
1594                         /* now check for users and Store */
1595                         if (ia32_get_irn_n_edges(succ) == 1) {
1596                                 succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1597
1598                                 if (is_ia32_xStore(succ) || is_ia32_Store(succ)) {
1599                                         store  = succ;
1600                                         addr_b = get_irn_n(store, 0);
1601                                         addr_i = get_irn_n(store, 1);
1602                                 }
1603                         }
1604
1605                         if (store) {
1606                                 /* we found a Store as single user: Now check for Load */
1607
1608                                 /* skip the Proj for easier access */
1609                                 load = is_Proj(right) ? (is_ia32_Load(get_Proj_pred(right)) ? get_Proj_pred(right) : NULL) : NULL;
1610
1611                                 /* Extra check for commutative ops with two Loads */
1612                                 /* -> put the interesting Load left               */
1613                                 if (load && node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_BOTH)) {
1614                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1615                                                 /* We exchange left and right, so it's easier to kill     */
1616                                                 /* the correct Load later and to handle unary operations. */
1617                                                 exchange_left_right(irn, &left, &right, 3, 2);
1618                                                 need_exchange_on_fail ^= 1;
1619                                         }
1620                                 }
1621
1622                                 /* skip the Proj for easier access */
1623                                 load = get_Proj_pred(left);
1624
1625                                 /* Compare Load and Store address */
1626                                 if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1627                                         /* Left Load is from same address, so we can */
1628                                         /* disconnect the Load and Store here        */
1629
1630                                         /* set new base, index and attributes */
1631                                         set_irn_n(irn, 0, addr_b);
1632                                         set_irn_n(irn, 1, addr_i);
1633                                         add_ia32_am_offs(irn, get_ia32_am_offs(load));
1634                                         set_ia32_am_scale(irn, get_ia32_am_scale(load));
1635                                         set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1636                                         set_ia32_op_type(irn, ia32_AddrModeD);
1637                                         set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1638                                         set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1639
1640                                         set_ia32_am_sc(irn, get_ia32_am_sc(load));
1641                                         if (is_ia32_am_sc_sign(load))
1642                                                 set_ia32_am_sc_sign(irn);
1643
1644                                         if (is_ia32_use_frame(load))
1645                                                 set_ia32_use_frame(irn);
1646
1647                                         /* connect to Load memory and disconnect Load */
1648                                         if (get_irn_arity(irn) == 5) {
1649                                                 /* binary AMop */
1650                                                 set_irn_n(irn, 4, get_irn_n(load, 2));
1651                                                 set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1652                                         }
1653                                         else {
1654                                                 /* unary AMop */
1655                                                 set_irn_n(irn, 3, get_irn_n(load, 2));
1656                                                 set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1657                                         }
1658
1659                                         /* connect the memory Proj of the Store to the op */
1660                                         mem_proj = ia32_get_proj_for_mode(store, mode_M);
1661                                         set_Proj_pred(mem_proj, irn);
1662                                         set_Proj_proj(mem_proj, 1);
1663
1664                                         /* clear remat flag */
1665                                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1666
1667                                         try_remove_from_sched(load);
1668                                         try_remove_from_sched(store);
1669                                         DBG_OPT_AM_D(load, store, irn);
1670
1671                                         DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1672
1673                                         need_exchange_on_fail = 0;
1674                                 }
1675                         } /* if (store) */
1676                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1677                                 /* There was no store, check if we still can optimize for source address mode */
1678                                 check_am_src = 1;
1679                         }
1680                 } /* if (support AM Dest) */
1681                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1682                         /* op doesn't support am AM Dest -> check for AM Source */
1683                         check_am_src = 1;
1684                 }
1685
1686                 /* was exchanged but optimize failed: exchange back */
1687                 if (need_exchange_on_fail) {
1688                         exchange_left_right(irn, &left, &right, 3, 2);
1689                         cand = orig_cand;
1690                 }
1691
1692                 need_exchange_on_fail = 0;
1693
1694                 /* normalize commutative ops */
1695                 if (check_am_src && node_is_ia32_comm(irn) && (cand == IA32_AM_CAND_LEFT)) {
1696
1697                         /* Assure that right operand is always a Load if there is one  */
1698                         /* because non-commutative ops can only use Source AM if the   */
1699                         /* right operand is a Load, so we only need to check the right */
1700                         /* operand afterwards.                                         */
1701
1702                         exchange_left_right(irn, &left, &right, 3, 2);
1703                         need_exchange_on_fail = 1;
1704
1705                         /* now: load is left */
1706                         cand = IA32_AM_CAND_RIGHT;
1707                 }
1708
1709                 /* optimize op -> Load iff Load is only used by this op    */
1710                 /* and right operand is a Load which only used by this irn */
1711                 if (check_am_src                &&
1712                         (cand & IA32_AM_CAND_RIGHT) &&
1713                         (ia32_get_irn_n_edges(right) == 1))
1714                 {
1715                         ir_node *load = get_Proj_pred(right);
1716
1717                         addr_b = get_irn_n(load, 0);
1718                         addr_i = get_irn_n(load, 1);
1719
1720                         /* set new base, index and attributes */
1721                         set_irn_n(irn, 0, addr_b);
1722                         set_irn_n(irn, 1, addr_i);
1723                         add_ia32_am_offs(irn, get_ia32_am_offs(load));
1724                         set_ia32_am_scale(irn, get_ia32_am_scale(load));
1725                         set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1726                         set_ia32_op_type(irn, ia32_AddrModeS);
1727                         set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1728                         set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1729
1730                         set_ia32_am_sc(irn, get_ia32_am_sc(load));
1731                         if (is_ia32_am_sc_sign(load))
1732                                 set_ia32_am_sc_sign(irn);
1733
1734                         /* clear remat flag */
1735                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1736
1737                         if (is_ia32_use_frame(load))
1738                                 set_ia32_use_frame(irn);
1739
1740                         /* connect to Load memory and disconnect Load */
1741                         if (get_irn_arity(irn) == 5) {
1742                                 /* binary AMop */
1743                                 set_irn_n(irn, 4, get_irn_n(load, 2));
1744                                 set_irn_n(irn, 3, ia32_get_admissible_noreg(cg, irn, 3));
1745                         } else {
1746                                 assert(get_irn_arity(irn) == 4);
1747                                 /* unary AMop */
1748                                 set_irn_n(irn, 3, get_irn_n(load, 2));
1749                                 set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1750                         }
1751
1752                         /* this is only needed for Compares, but currently ALL nodes
1753                          * have this attribute :-) */
1754                         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1755
1756                         DBG_OPT_AM_S(load, irn);
1757
1758                         /* If Load has a memory Proj, connect it to the op */
1759                         mem_proj = ia32_get_proj_for_mode(load, mode_M);
1760                         if (mem_proj) {
1761                                 set_Proj_pred(mem_proj, irn);
1762                                 set_Proj_proj(mem_proj, 1);
1763                         }
1764
1765                         try_remove_from_sched(load);
1766
1767                         DB((mod, LEVEL_1, "merged with %+F into source AM\n", load));
1768                 }
1769                 else {
1770                         /* was exchanged but optimize failed: exchange back */
1771                         if (need_exchange_on_fail)
1772                                 exchange_left_right(irn, &left, &right, 3, 2);
1773                 }
1774         }
1775 }
1776
1777 /**
1778  * Performs address mode optimization.
1779  */
1780 void ia32_optimize_addressmode(ia32_code_gen_t *cg) {
1781         /* if we are supposed to do AM or LEA optimization: recalculate edges */
1782         if (cg->opt & (IA32_OPT_DOAM | IA32_OPT_LEA)) {
1783                 edges_deactivate(cg->irg);
1784                 edges_activate(cg->irg);
1785         }
1786         else {
1787                 /* no optimizations at all */
1788                 return;
1789         }
1790
1791         /* beware: we cannot optimize LEA and AM in one run because */
1792         /*         LEA optimization adds new nodes to the irg which */
1793         /*         invalidates the phase data                       */
1794
1795         if (cg->opt & IA32_OPT_LEA) {
1796                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_lea, cg);
1797         }
1798
1799         if (cg->dump)
1800                 be_dump(cg->irg, "-lea", dump_ir_block_graph_sched);
1801
1802         if (cg->opt & IA32_OPT_DOAM) {
1803                 /* we need height information for am optimization */
1804                 heights_t *h = heights_new(cg->irg);
1805                 ia32_am_opt_env_t env;
1806
1807                 env.cg = cg;
1808                 env.h  = h;
1809
1810                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_am, &env);
1811
1812                 heights_free(h);
1813         }
1814 }