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