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