6a88bda3d31d25d2d42964d302d9865d042b8b8e
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include "irnode.h"
6 #include "irprog_t.h"
7 #include "ircons.h"
8 #include "firm_types.h"
9 #include "iredges.h"
10 #include "tv.h"
11 #include "irgmod.h"
12
13 #include "../be_t.h"
14 #include "../beabi.h"
15 #include "../benode_t.h"
16 #include "../besched_t.h"
17
18 #include "ia32_new_nodes.h"
19 #include "bearch_ia32_t.h"
20 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
21 #include "ia32_transform.h"
22
23 /*----*/
24
25 #include "irhooks.h"
26 #include "dbginfo_t.h"
27 #include "firmstat.h"
28
29 /**
30  * Merge the debug info due to a LEA creation.
31  *
32  * @param oldn  the node
33  * @param n     the new constant holding the value
34  */
35 #define DBG_OPT_LEA(oldn, n)                                \
36   do {                                                          \
37           hook_merge_nodes(&n, 1, &oldn, 1, FS_BE_IA32_LEA);      \
38     __dbg_info_merge_pair(n, oldn, dbg_backend);                  \
39   } while(0)
40
41
42 #undef is_NoMem
43 #define is_NoMem(irn) (get_irn_op(irn) == op_NoMem)
44
45 typedef int is_op_func_t(const ir_node *n);
46
47 /**
48  * checks if a node represents the NOREG value
49  */
50 static int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
51   be_abi_irg_t *babi = cg->birg->abi;
52         const arch_register_t *fp_noreg = USE_SSE2(cg) ?
53                 &ia32_xmm_regs[REG_XMM_NOREG] : &ia32_vfp_regs[REG_VFP_NOREG];
54
55         return (be_abi_get_callee_save_irn(babi, &ia32_gp_regs[REG_GP_NOREG]) == irn) ||
56                (be_abi_get_callee_save_irn(babi, fp_noreg) == irn);
57 }
58
59
60
61 /*************************************************
62  *   _____                _              _
63  *  / ____|              | |            | |
64  * | |     ___  _ __  ___| |_ __ _ _ __ | |_ ___
65  * | |    / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
66  * | |___| (_) | | | \__ \ || (_| | | | | |_\__ \
67  *  \_____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
68  *
69  *************************************************/
70
71 /**
72  * creates a unique ident by adding a number to a tag
73  *
74  * @param tag   the tag string, must contain a %d if a number
75  *              should be added
76  */
77 static ident *unique_id(const char *tag)
78 {
79         static unsigned id = 0;
80         char str[256];
81
82         snprintf(str, sizeof(str), tag, ++id);
83         return new_id_from_str(str);
84 }
85
86
87
88 /**
89  * Transforms a SymConst.
90  *
91  * @param mod     the debug module
92  * @param block   the block the new node should belong to
93  * @param node    the ir SymConst node
94  * @param mode    mode of the SymConst
95  * @return the created ia32 Const node
96  */
97 static ir_node *gen_SymConst(ia32_transform_env_t *env) {
98         ir_node  *cnst;
99         dbg_info *dbg   = env->dbg;
100         ir_mode  *mode  = env->mode;
101         ir_graph *irg   = env->irg;
102         ir_node  *block = env->block;
103
104         if (mode_is_float(mode)) {
105                 if (USE_SSE2(env->cg))
106                         cnst = new_rd_ia32_fConst(dbg, irg, block, mode);
107                 else
108                         cnst = new_rd_ia32_vfConst(dbg, irg, block, mode);
109         }
110         else {
111                 cnst = new_rd_ia32_Const(dbg, irg, block, mode);
112         }
113         set_ia32_Const_attr(cnst, env->irn);
114         return cnst;
115 }
116
117 /**
118  * Get a primitive type for a mode.
119  */
120 static ir_type *get_prim_type(pmap *types, ir_mode *mode)
121 {
122         pmap_entry *e = pmap_find(types, mode);
123         ir_type *res;
124
125         if (! e) {
126                 char buf[64];
127                 snprintf(buf, sizeof(buf), "prim_type_%s", get_mode_name(mode));
128                 res = new_type_primitive(new_id_from_str(buf), mode);
129                 pmap_insert(types, mode, res);
130         }
131         else
132                 res = e->value;
133         return res;
134 }
135
136 /**
137  * Get an entity that is initialized with a tarval
138  */
139 static entity *get_entity_for_tv(ia32_code_gen_t *cg, ir_node *cnst)
140 {
141         tarval *tv    = get_Const_tarval(cnst);
142         pmap_entry *e = pmap_find(cg->isa->tv_ent, tv);
143         entity *res;
144         ir_graph *rem;
145
146         if (! e) {
147                 ir_mode *mode = get_irn_mode(cnst);
148                 ir_type *tp = get_Const_type(cnst);
149                 if (tp == firm_unknown_type)
150                         tp = get_prim_type(cg->isa->types, mode);
151
152                 res = new_entity(get_glob_type(), unique_id("ia32FloatCnst_%u"), tp);
153
154                 set_entity_ld_ident(res, get_entity_ident(res));
155                 set_entity_visibility(res, visibility_local);
156                 set_entity_variability(res, variability_constant);
157                 set_entity_allocation(res, allocation_static);
158
159                  /* we create a new entity here: It's initialization must resist on the
160                     const code irg */
161                 rem = current_ir_graph;
162                 current_ir_graph = get_const_code_irg();
163                 set_atomic_ent_value(res, new_Const_type(tv, tp));
164                 current_ir_graph = rem;
165
166                 pmap_insert(cg->isa->tv_ent, tv, res);
167         }
168         else
169                 res = e->value;
170         return res;
171 }
172
173 /**
174  * Transforms a Const.
175  *
176  * @param mod     the debug module
177  * @param block   the block the new node should belong to
178  * @param node    the ir Const node
179  * @param mode    mode of the Const
180  * @return the created ia32 Const node
181  */
182 static ir_node *gen_Const(ia32_transform_env_t *env) {
183         ir_node *cnst;
184         symconst_symbol sym;
185         ir_graph *irg   = env->irg;
186         ir_node  *block = env->block;
187         ir_node  *node  = env->irn;
188         dbg_info *dbg   = env->dbg;
189         ir_mode  *mode  = env->mode;
190
191         if (mode_is_float(mode)) {
192                 if (! USE_SSE2(env->cg)) {
193                         cnst_classify_t clss = classify_Const(node);
194
195                         if (clss == CNST_NULL)
196                                 return new_rd_ia32_vfldz(dbg, irg, block, mode);
197                         else if (clss == CNST_ONE)
198                                 return new_rd_ia32_vfld1(dbg, irg, block, mode);
199                 }
200                 sym.entity_p = get_entity_for_tv(env->cg, node);
201
202                 cnst = new_rd_SymConst(dbg, irg, block, sym, symconst_addr_ent);
203                 env->irn = cnst;
204                 cnst = gen_SymConst(env);
205         }
206         else {
207                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irn_mode(node));
208                 set_ia32_Const_attr(cnst, node);
209         }
210         return cnst;
211 }
212
213
214
215 /**
216  * Transforms (all) Const's into ia32_Const and places them in the
217  * block where they are used (or in the cfg-pred Block in case of Phi's).
218  * Additionally all reference nodes are changed into mode_Is nodes.
219  */
220 void ia32_place_consts_set_modes(ir_node *irn, void *env) {
221         ia32_code_gen_t      *cg = env;
222         ia32_transform_env_t  tenv;
223         ir_mode              *mode;
224         ir_node              *pred, *cnst;
225         int                   i;
226         opcode                opc;
227
228         if (is_Block(irn))
229                 return;
230
231         mode = get_irn_mode(irn);
232
233         /* transform all reference nodes into mode_Is nodes */
234         if (mode_is_reference(mode)) {
235                 mode = mode_Is;
236                 set_irn_mode(irn, mode);
237         }
238
239         tenv.block    = get_nodes_block(irn);
240         tenv.cg       = cg;
241         tenv.irg      = cg->irg;
242         DEBUG_ONLY(tenv.mod      = cg->mod;)
243
244         /* Loop over all predecessors and check for Sym/Const nodes */
245         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
246                 pred      = get_irn_n(irn, i);
247                 cnst      = NULL;
248                 opc       = get_irn_opcode(pred);
249                 tenv.irn  = pred;
250                 tenv.mode = get_irn_mode(pred);
251                 tenv.dbg  = get_irn_dbg_info(pred);
252
253                 /* If it's a Phi, then we need to create the */
254                 /* new Const in it's predecessor block       */
255                 if (is_Phi(irn)) {
256                         tenv.block = get_Block_cfgpred_block(get_nodes_block(irn), i);
257                 }
258
259                 /* put the const into the block where the original const was */
260                 if (! cg->opt.placecnst) {
261                         tenv.block = get_nodes_block(pred);
262                 }
263
264                 switch (opc) {
265                         case iro_Const:
266                                 cnst = gen_Const(&tenv);
267                                 break;
268                         case iro_SymConst:
269                                 cnst = gen_SymConst(&tenv);
270                                 break;
271                         default:
272                                 break;
273                 }
274
275                 /* if we found a const, then set it */
276                 if (cnst) {
277                         set_irn_n(irn, i, cnst);
278                 }
279         }
280 }
281
282
283
284 /********************************************************************************************************
285  *  _____                _           _         ____        _   _           _          _   _
286  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
287  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
288  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
289  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
290  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
291  *                | |                               | |
292  *                |_|                               |_|
293  ********************************************************************************************************/
294
295 /**
296  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
297  */
298
299 static int ia32_cnst_compare(ir_node *n1, ir_node *n2) {
300         return get_ia32_id_cnst(n1) == get_ia32_id_cnst(n2);
301 }
302
303 /**
304  * Checks for potential CJmp/CJmpAM optimization candidates.
305  */
306 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
307         ir_node *cand = NULL;
308         ir_node *prev = sched_prev(irn);
309
310         if (is_Block(prev)) {
311                 if (get_Block_n_cfgpreds(prev) == 1)
312                         prev = get_Block_cfgpred(prev, 0);
313                 else
314                         prev = NULL;
315         }
316
317         /* The predecessor must be a ProjX. */
318         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
319                 prev = get_Proj_pred(prev);
320
321                 if (is_op_func(prev))
322                         cand = prev;
323         }
324
325         return cand;
326 }
327
328 static int is_TestJmp_cand(const ir_node *irn) {
329         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
330 }
331
332 /**
333  * Checks if two consecutive arguments of cand matches
334  * the two arguments of irn (TestJmp).
335  */
336 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
337         ir_node *in1       = get_irn_n(irn, 0);
338         ir_node *in2       = get_irn_n(irn, 1);
339         int      i, n      = get_irn_arity(cand);
340         int      same_args = 0;
341
342         for (i = 0; i < n - 1; i++) {
343                 if (get_irn_n(cand, i)     == in1 &&
344                         get_irn_n(cand, i + 1) == in2)
345                 {
346                         same_args = 1;
347                         break;
348                 }
349         }
350
351         if (same_args)
352                 return ia32_cnst_compare(cand, irn);
353
354         return 0;
355 }
356
357 /**
358  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
359  */
360 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
361         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
362         int      replace = 0;
363
364         /* we found a possible candidate */
365         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
366
367         if (replace) {
368                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
369
370                 if (is_ia32_And(cand))
371                         set_irn_op(irn, op_ia32_CJmpAM);
372                 else
373                         set_irn_op(irn, op_ia32_CJmp);
374
375                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
376         }
377 }
378
379 static int is_CondJmp_cand(const ir_node *irn) {
380         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
381 }
382
383 /**
384  * Checks if the arguments of cand are the same of irn.
385  */
386 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
387         int i, n      = get_irn_arity(cand);
388         int same_args = 1;
389
390         for (i = 0; i < n; i++) {
391                 if (get_irn_n(cand, i) == get_irn_n(irn, i)) {
392                         same_args = 0;
393                         break;
394                 }
395         }
396
397         if (same_args)
398                 return ia32_cnst_compare(cand, irn);
399
400         return 0;
401 }
402
403 /**
404  * Tries to replace a CondJmp by a CJmpAM
405  */
406 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
407         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
408         int      replace = 0;
409
410         /* we found a possible candidate */
411         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
412
413         if (replace) {
414                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
415
416                 set_irn_op(irn, op_ia32_CJmp);
417
418                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
419         }
420 }
421
422 /**
423  * Tries to optimize two following IncSP.
424  */
425 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
426         ir_node *prev = be_get_IncSP_pred(irn);
427         int real_uses = get_irn_n_edges(prev);
428
429         if (be_is_IncSP(prev) && real_uses == 1) {
430                 /* first IncSP has only one IncSP user, kill the first one */
431                 unsigned       prev_offs = be_get_IncSP_offset(prev);
432                 be_stack_dir_t prev_dir  = be_get_IncSP_direction(prev);
433                 unsigned       curr_offs = be_get_IncSP_offset(irn);
434                 be_stack_dir_t curr_dir  = be_get_IncSP_direction(irn);
435
436                 int new_ofs = prev_offs * (prev_dir == be_stack_dir_expand ? -1 : +1) +
437                                     curr_offs * (curr_dir == be_stack_dir_expand ? -1 : +1);
438
439                 if (new_ofs < 0) {
440                         new_ofs  = -new_ofs;
441                         curr_dir = be_stack_dir_expand;
442                 }
443                 else
444                         curr_dir = be_stack_dir_shrink;
445                 be_set_IncSP_offset(prev, 0);
446                 be_set_IncSP_offset(irn, (unsigned)new_ofs);
447                 be_set_IncSP_direction(irn, curr_dir);
448         }
449 }
450
451 /**
452  * Performs Peephole Optimizations.
453  */
454 void ia32_peephole_optimization(ir_node *irn, void *env) {
455         ia32_code_gen_t *cg = env;
456
457         if (is_ia32_TestJmp(irn))
458                 ia32_optimize_TestJmp(irn, cg);
459         else if (is_ia32_CondJmp(irn))
460                 ia32_optimize_CondJmp(irn, cg);
461         else if (be_is_IncSP(irn))
462                 ia32_optimize_IncSP(irn, cg);
463 }
464
465
466
467 /******************************************************************
468  *              _     _                   __  __           _
469  *     /\      | |   | |                 |  \/  |         | |
470  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
471  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
472  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
473  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
474  *
475  ******************************************************************/
476
477 static int node_is_ia32_comm(const ir_node *irn) {
478         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
479 }
480
481 static int ia32_get_irn_n_edges(const ir_node *irn) {
482         const ir_edge_t *edge;
483         int cnt = 0;
484
485         foreach_out_edge(irn, edge) {
486                 cnt++;
487         }
488
489         return cnt;
490 }
491
492 /**
493  * Returns the first mode_M Proj connected to irn.
494  */
495 static ir_node *get_mem_proj(const ir_node *irn) {
496         const ir_edge_t *edge;
497         ir_node         *src;
498
499         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
500
501         foreach_out_edge(irn, edge) {
502                 src = get_edge_src_irn(edge);
503
504                 assert(is_Proj(src) && "Proj expected");
505
506                 if (get_irn_mode(src) == mode_M)
507                         return src;
508         }
509
510         return NULL;
511 }
512
513 /**
514  * Returns the first Proj with mode != mode_M connected to irn.
515  */
516 static ir_node *get_res_proj(const ir_node *irn) {
517         const ir_edge_t *edge;
518         ir_node         *src;
519
520         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
521
522         foreach_out_edge(irn, edge) {
523                 src = get_edge_src_irn(edge);
524
525                 assert(is_Proj(src) && "Proj expected");
526
527                 if (get_irn_mode(src) != mode_M)
528                         return src;
529         }
530
531         return NULL;
532 }
533
534 /**
535  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
536  *
537  * @param pred       The node to be checked
538  * @param is_op_func The check-function
539  * @return 1 if conditions are fulfilled, 0 otherwise
540  */
541 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
542         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
543                 return 1;
544         }
545
546         return 0;
547 }
548
549 /**
550  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
551  * and if the predecessor is in block bl.
552  *
553  * @param bl         The block
554  * @param pred       The node to be checked
555  * @param is_op_func The check-function
556  * @return 1 if conditions are fulfilled, 0 otherwise
557  */
558 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
559         int (*is_op_func)(const ir_node *n))
560 {
561         if (is_Proj(pred)) {
562                 pred = get_Proj_pred(pred);
563                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
564                         return 1;
565                 }
566         }
567
568         return 0;
569 }
570
571
572
573 /**
574  * Checks if irn is a candidate for address calculation or address mode.
575  *
576  * address calculation (AC):
577  * - none of the operand must be a Load  within the same block OR
578  * - all Loads must have more than one user                    OR
579  * - the irn has a frame entity (it's a former FrameAddr)
580  *
581  * address mode (AM):
582  * - at least one operand has to be a Load within the same block AND
583  * - the load must not have other users than the irn             AND
584  * - the irn must not have a frame entity set
585  *
586  * @param block       The block the Loads must/not be in
587  * @param irn         The irn to check
588  * @param check_addr  1 if to check for address calculation, 0 otherwise
589  * return 1 if irn is a candidate for AC or AM, 0 otherwise
590  */
591 static int is_candidate(const ir_node *block, const ir_node *irn, int check_addr) {
592         ir_node *in;
593         int      n, is_cand = check_addr;
594
595         in = get_irn_n(irn, 2);
596
597         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
598                 n         = ia32_get_irn_n_edges(in);
599                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
600         }
601
602         in = get_irn_n(irn, 3);
603
604         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
605                 n         = ia32_get_irn_n_edges(in);
606                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
607         }
608
609         is_cand = get_ia32_frame_ent(irn) ? (check_addr ? 1 : 0) : is_cand;
610
611         return is_cand;
612 }
613
614 /**
615  * Compares the base and index addr and the load/store entities
616  * and returns 1 if they are equal.
617  */
618 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
619                                                                         const ir_node *addr_b, const ir_node *addr_i)
620 {
621         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
622         entity *lent     = get_ia32_frame_ent(load);
623         entity *sent     = get_ia32_frame_ent(store);
624         ident  *lid      = get_ia32_am_sc(load);
625         ident  *sid      = get_ia32_am_sc(store);
626         char   *loffs    = get_ia32_am_offs(load);
627         char   *soffs    = get_ia32_am_offs(store);
628
629         /* are both entities set and equal? */
630         if (is_equal && (lent || sent))
631                 is_equal = lent && sent && (lent == sent);
632
633         /* are address mode idents set and equal? */
634         if (is_equal && (lid || sid))
635                 is_equal = lid && sid && (lid == sid);
636
637         /* are offsets set and equal */
638         if (is_equal && (loffs || soffs))
639                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
640
641         /* are the load and the store of the same mode? */
642         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
643
644         return is_equal;
645 }
646
647
648
649 /**
650  * Folds Add or Sub to LEA if possible
651  */
652 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
653         ir_graph   *irg        = get_irn_irg(irn);
654         dbg_info   *dbg        = get_irn_dbg_info(irn);
655         ir_node    *block      = get_nodes_block(irn);
656         ir_node    *res        = irn;
657         char       *offs       = NULL;
658         const char *offs_cnst  = NULL;
659         char       *offs_lea   = NULL;
660         int         scale      = 0;
661         int         isadd      = 0;
662         int         dolea      = 0;
663         int         have_am_sc = 0;
664         int         am_sc_sign = 0;
665         ident      *am_sc      = NULL;
666         ir_node    *left, *right, *temp;
667         ir_node    *base, *index;
668         ia32_am_flavour_t am_flav;
669         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
670
671         if (is_ia32_Add(irn))
672                 isadd = 1;
673
674         left  = get_irn_n(irn, 2);
675         right = get_irn_n(irn, 3);
676
677         /* "normalize" arguments in case of add with two operands */
678         if  (isadd && ! be_is_NoReg(cg, right)) {
679                 /* put LEA == ia32_am_O as right operand */
680                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
681                         set_irn_n(irn, 2, right);
682                         set_irn_n(irn, 3, left);
683                         temp  = left;
684                         left  = right;
685                         right = temp;
686                 }
687
688                 /* put LEA != ia32_am_O as left operand */
689                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
690                         set_irn_n(irn, 2, right);
691                         set_irn_n(irn, 3, left);
692                         temp  = left;
693                         left  = right;
694                         right = temp;
695                 }
696
697                 /* put SHL as left operand iff left is NOT a LEA */
698                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
699                         set_irn_n(irn, 2, right);
700                         set_irn_n(irn, 3, left);
701                         temp  = left;
702                         left  = right;
703                         right = temp;
704                 }
705         }
706
707         base    = left;
708         index   = noreg;
709         offs    = NULL;
710         scale   = 0;
711         am_flav = 0;
712
713         /* check for operation with immediate */
714         if (is_ia32_ImmConst(irn)) {
715                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
716
717                 offs_cnst = get_ia32_cnst(irn);
718                 dolea     = 1;
719         }
720         else if (is_ia32_ImmSymConst(irn)) {
721                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
722
723                 have_am_sc = 1;
724                 dolea      = 1;
725                 am_sc      = get_ia32_id_cnst(irn);
726                 am_sc_sign = is_ia32_am_sc_sign(irn);
727         }
728
729         /* determine the operand which needs to be checked */
730         if (be_is_NoReg(cg, right)) {
731                 temp = left;
732         }
733         else {
734                 temp = right;
735         }
736
737         /* check if right operand is AMConst (LEA with ia32_am_O)  */
738         /* but we can only eat it up if there is no other symconst */
739         /* because the linker won't accept two symconsts           */
740         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
741                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
742
743                 offs_lea   = get_ia32_am_offs(temp);
744                 am_sc      = get_ia32_am_sc(temp);
745                 am_sc_sign = is_ia32_am_sc_sign(temp);
746                 have_am_sc = 1;
747                 dolea      = 1;
748         }
749
750         if (isadd) {
751                 /* default for add -> make right operand to index */
752                 index = right;
753                 dolea = 1;
754
755                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
756
757                 /* determine the operand which needs to be checked */
758                 temp = left;
759                 if (is_ia32_Lea(left)) {
760                         temp = right;
761                 }
762
763                 /* check for SHL 1,2,3 */
764                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
765                         temp = get_Proj_pred(temp);
766
767                         if (get_ia32_Immop_tarval(temp)) {
768                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
769
770                                 if (scale <= 3) {
771                                         index = get_irn_n(temp, 2);
772
773                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
774                                 }
775                         }
776                 }
777
778                 /* fix base */
779                 if (! be_is_NoReg(cg, index)) {
780                         /* if we have index, but left == right -> no base */
781                         if (left == right) {
782                                 base = noreg;
783                         }
784                         else if (! is_ia32_Lea(left) && (index != right)) {
785                                 /* index != right -> we found a good Shl           */
786                                 /* left  != LEA   -> this Shl was the left operand */
787                                 /* -> base is right operand                        */
788                                 base = right;
789                         }
790                 }
791         }
792
793         /* Try to assimilate a LEA as left operand */
794         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
795                 ir_node *assim_lea_idx, *assim_lea_base;
796
797                 am_flav        = get_ia32_am_flavour(left);
798                 assim_lea_base = get_irn_n(left, 0);
799                 assim_lea_idx  = get_irn_n(left, 1);
800
801
802                 /* If we have an Add with a real right operand (not NoReg) and  */
803                 /* the LEA contains already an index calculation then we create */
804                 /* a new LEA.                                                   */
805                 /* If the LEA contains already a frame_entity then we also      */
806                 /* create a new one  otherwise we would loose it.               */
807                 if ((isadd && ! be_is_NoReg(cg, index) && (am_flav & ia32_I)) || /* no new LEA if index already set */
808                         get_ia32_frame_ent(left)                                  || /* no new LEA if stack access */
809                         (have_am_sc && get_ia32_am_sc(left))                      || /* no new LEA if AM symconst already present */
810                         /* at least on of the LEA operands must be NOREG */
811                         (!be_is_NoReg(cg, assim_lea_base) && !be_is_NoReg(cg, assim_lea_idx)))
812                 {
813                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
814                 }
815                 else {
816                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
817                         offs       = get_ia32_am_offs(left);
818                         am_sc      = have_am_sc ? am_sc : get_ia32_am_sc(left);
819                         have_am_sc = am_sc ? 1 : 0;
820                         am_sc_sign = is_ia32_am_sc_sign(left);
821                         scale      = get_ia32_am_scale(left);
822
823                         if (be_is_NoReg(cg, assim_lea_base) && ! be_is_NoReg(cg, assim_lea_idx)) {
824                                 /* assimilate index */
825                                 assert(be_is_NoReg(cg, index) && ! be_is_NoReg(cg, base) && "operand mismatch for LEA assimilation");
826                                 index = assim_lea_idx;
827                         }
828                         else if (! be_is_NoReg(cg, assim_lea_base) && be_is_NoReg(cg, assim_lea_idx)) {
829                                 /* assimilate base */
830                                 assert(! be_is_NoReg(cg, index) && (base == left) && "operand mismatch for LEA assimilation");
831                                 base = assim_lea_base;
832                         }
833                 }
834         }
835
836         /* ok, we can create a new LEA */
837         if (dolea) {
838                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
839
840                 /* add the old offset of a previous LEA */
841                 if (offs) {
842                         add_ia32_am_offs(res, offs);
843                 }
844
845                 /* add the new offset */
846                 if (isadd) {
847                         if (offs_cnst) {
848                                 add_ia32_am_offs(res, offs_cnst);
849                         }
850                         if (offs_lea) {
851                                 add_ia32_am_offs(res, offs_lea);
852                         }
853                 }
854                 else {
855                         /* either lea_O-cnst, -cnst or -lea_O  */
856                         if (offs_cnst) {
857                                 if (offs_lea) {
858                                         add_ia32_am_offs(res, offs_lea);
859                                 }
860
861                                 sub_ia32_am_offs(res, offs_cnst);
862                         }
863                         else {
864                                 sub_ia32_am_offs(res, offs_lea);
865                         }
866                 }
867
868                 /* set the address mode symconst */
869                 if (have_am_sc) {
870                         set_ia32_am_sc(res, am_sc);
871                         if (am_sc_sign)
872                                 set_ia32_am_sc_sign(res);
873                 }
874
875                 /* copy the frame entity (could be set in case of Add */
876                 /* which was a FrameAddr) */
877                 set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
878
879                 if (is_ia32_use_frame(irn))
880                         set_ia32_use_frame(res);
881
882                 /* set scale */
883                 set_ia32_am_scale(res, scale);
884
885                 am_flav = ia32_am_N;
886                 /* determine new am flavour */
887                 if (offs || offs_cnst || offs_lea) {
888                         am_flav |= ia32_O;
889                 }
890                 if (! be_is_NoReg(cg, base)) {
891                         am_flav |= ia32_B;
892                 }
893                 if (! be_is_NoReg(cg, index)) {
894                         am_flav |= ia32_I;
895                 }
896                 if (scale > 0) {
897                         am_flav |= ia32_S;
898                 }
899                 set_ia32_am_flavour(res, am_flav);
900
901                 set_ia32_op_type(res, ia32_AddrModeS);
902
903                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
904
905                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
906
907                 /* we will exchange it, report here before the Proj is created */
908                 DBG_OPT_LEA(irn, res);
909
910                 /* get the result Proj of the Add/Sub */
911                 irn = get_res_proj(irn);
912
913                 assert(irn && "Couldn't find result proj");
914
915                 /* exchange the old op with the new LEA */
916                 exchange(irn, res);
917         }
918
919         return res;
920 }
921
922 /**
923  * Optimizes a pattern around irn to address mode if possible.
924  */
925 void ia32_optimize_am(ir_node *irn, void *env) {
926         ia32_code_gen_t   *cg   = env;
927         ir_node           *res  = irn;
928         dbg_info          *dbg;
929         ir_mode           *mode;
930         ir_node           *block, *noreg_gp, *noreg_fp;
931         ir_node           *left, *right, *temp;
932         ir_node           *store, *load, *mem_proj;
933         ir_node           *succ, *addr_b, *addr_i;
934         int                check_am_src = 0;
935         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
936
937         if (! is_ia32_irn(irn))
938                 return;
939
940         dbg      = get_irn_dbg_info(irn);
941         mode     = get_irn_mode(irn);
942         block    = get_nodes_block(irn);
943         noreg_gp = ia32_new_NoReg_gp(cg);
944         noreg_fp = ia32_new_NoReg_fp(cg);
945
946         DBG((mod, LEVEL_1, "checking for AM\n"));
947
948         /* 1st part: check for address calculations and transform the into Lea */
949
950         /* Following cases can occur:                                  */
951         /* - Sub (l, imm) -> LEA [base - offset]                       */
952         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
953         /* - Add (l, imm) -> LEA [base + offset]                       */
954         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
955         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
956         /* - Add (l, r) -> LEA [base + index * scale]                  */
957         /*              with scale > 1 iff l/r == shl (1,2,3)          */
958
959         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
960                 left  = get_irn_n(irn, 2);
961                 right = get_irn_n(irn, 3);
962
963             /* Do not try to create a LEA if one of the operands is a Load. */
964                 /* check is irn is a candidate for address calculation */
965                 if (is_candidate(block, irn, 1)) {
966                         DBG((mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
967                         res = fold_addr(cg, irn, noreg_gp);
968
969                         if (res == irn)
970                                 DB((mod, LEVEL_1, "transformed into %+F\n", res));
971                         else
972                                 DB((mod, LEVEL_1, "not transformed\n"));
973                 }
974         }
975
976         /* 2nd part: fold following patterns:                                               */
977         /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
978         /* - Store -> LEA into Store }       it might be better to keep the LEA             */
979         /* - op -> Load into AMop with am_Source                                            */
980         /*   conditions:                                                                    */
981         /*     - op is am_Source capable AND                                                */
982         /*     - the Load is only used by this op AND                                       */
983         /*     - the Load is in the same block                                              */
984         /* - Store -> op -> Load  into AMop with am_Dest                                    */
985         /*   conditions:                                                                    */
986         /*     - op is am_Dest capable AND                                                  */
987         /*     - the Store uses the same address as the Load AND                            */
988         /*     - the Load is only used by this op AND                                       */
989         /*     - the Load and Store are in the same block AND                               */
990         /*     - nobody else uses the result of the op                                      */
991
992         if ((res == irn) && (get_ia32_am_support(irn) != ia32_am_None) && !is_ia32_Lea(irn)) {
993                 /* 1st: check for Load/Store -> LEA   */
994                 if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
995                         left = get_irn_n(irn, 0);
996
997                         if (is_ia32_Lea(left)) {
998                                 DBG((mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
999
1000                                 /* get the AM attributes from the LEA */
1001                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1002                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1003                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1004
1005                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
1006                                 if (is_ia32_am_sc_sign(left))
1007                                         set_ia32_am_sc_sign(irn);
1008
1009                                 set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1010
1011                                 /* set base and index */
1012                                 set_irn_n(irn, 0, get_irn_n(left, 0));
1013                                 set_irn_n(irn, 1, get_irn_n(left, 1));
1014
1015                                 /* clear remat flag */
1016                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1017                         }
1018                 }
1019                 /* check if the node is an address mode candidate */
1020                 else if (is_candidate(block, irn, 0)) {
1021                         DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1022
1023                         left  = get_irn_n(irn, 2);
1024                         if (get_irn_arity(irn) == 4) {
1025                                 /* it's an "unary" operation */
1026                                 right = left;
1027                         }
1028                         else {
1029                                 right = get_irn_n(irn, 3);
1030                         }
1031
1032                         /* normalize commutative ops */
1033                         if (node_is_ia32_comm(irn)) {
1034                                 /* Assure that right operand is always a Load if there is one    */
1035                                 /* because non-commutative ops can only use Dest AM if the right */
1036                                 /* operand is a load, so we only need to check right operand.    */
1037                                 if (pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1038                                 {
1039                                         set_irn_n(irn, 2, right);
1040                                         set_irn_n(irn, 3, left);
1041
1042                                         temp  = left;
1043                                         left  = right;
1044                                         right = temp;
1045                                 }
1046                         }
1047
1048                         /* check for Store -> op -> Load */
1049
1050                         /* Store -> op -> Load optimization is only possible if supported by op */
1051                         /* and if right operand is a Load                                       */
1052                         if ((get_ia32_am_support(irn) & ia32_am_Dest) &&
1053                                  pred_is_specific_nodeblock(block, right, is_ia32_Ld))
1054                         {
1055
1056                                 /* An address mode capable op always has a result Proj.                  */
1057                                 /* If this Proj is used by more than one other node, we don't need to    */
1058                                 /* check further, otherwise we check for Store and remember the address, */
1059                                 /* the Store points to. */
1060
1061                                 succ = get_res_proj(irn);
1062                                 assert(succ && "Couldn't find result proj");
1063
1064                                 addr_b = NULL;
1065                                 addr_i = NULL;
1066                                 store  = NULL;
1067
1068                                 /* now check for users and Store */
1069                                 if (ia32_get_irn_n_edges(succ) == 1) {
1070                                         succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1071
1072                                         if (is_ia32_fStore(succ) || is_ia32_Store(succ)) {
1073                                                 store  = succ;
1074                                                 addr_b = get_irn_n(store, 0);
1075
1076                                                 /* Could be that the Store is connected to the address    */
1077                                                 /* calculating LEA while the Load is already transformed. */
1078                                                 if (is_ia32_Lea(addr_b)) {
1079                                                         succ   = addr_b;
1080                                                         addr_b = get_irn_n(succ, 0);
1081                                                         addr_i = get_irn_n(succ, 1);
1082                                                 }
1083                                                 else {
1084                                                         addr_i = noreg_gp;
1085                                                 }
1086                                         }
1087                                 }
1088
1089                                 if (store) {
1090                                         /* we found a Store as single user: Now check for Load */
1091
1092                                         /* Extra check for commutative ops with two Loads */
1093                                         /* -> put the interesting Load right              */
1094                                         if (node_is_ia32_comm(irn) &&
1095                                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1096                                         {
1097                                                 if ((addr_b == get_irn_n(get_Proj_pred(left), 0)) &&
1098                                                         (addr_i == get_irn_n(get_Proj_pred(left), 1)))
1099                                                 {
1100                                                         /* We exchange left and right, so it's easier to kill     */
1101                                                         /* the correct Load later and to handle unary operations. */
1102                                                         set_irn_n(irn, 2, right);
1103                                                         set_irn_n(irn, 3, left);
1104
1105                                                         temp  = left;
1106                                                         left  = right;
1107                                                         right = temp;
1108                                                 }
1109                                         }
1110
1111                                         /* skip the Proj for easier access */
1112                                         load = get_Proj_pred(right);
1113
1114                                         /* Compare Load and Store address */
1115                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1116                                                 /* Right Load is from same address, so we can */
1117                                                 /* disconnect the Load and Store here        */
1118
1119                                                 /* set new base, index and attributes */
1120                                                 set_irn_n(irn, 0, addr_b);
1121                                                 set_irn_n(irn, 1, addr_i);
1122                                                 add_ia32_am_offs(irn, get_ia32_am_offs(load));
1123                                                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1124                                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1125                                                 set_ia32_op_type(irn, ia32_AddrModeD);
1126                                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1127                                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1128
1129                                                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1130                                                 if (is_ia32_am_sc_sign(load))
1131                                                         set_ia32_am_sc_sign(irn);
1132
1133                                                 if (is_ia32_use_frame(load))
1134                                                         set_ia32_use_frame(irn);
1135
1136                                                 /* connect to Load memory and disconnect Load */
1137                                                 if (get_irn_arity(irn) == 5) {
1138                                                         /* binary AMop */
1139                                                         set_irn_n(irn, 4, get_irn_n(load, 2));
1140                                                         set_irn_n(irn, 3, noreg_gp);
1141                                                 }
1142                                                 else {
1143                                                         /* unary AMop */
1144                                                         set_irn_n(irn, 3, get_irn_n(load, 2));
1145                                                         set_irn_n(irn, 2, noreg_gp);
1146                                                 }
1147
1148                                                 /* connect the memory Proj of the Store to the op */
1149                                                 mem_proj = get_mem_proj(store);
1150                                                 set_Proj_pred(mem_proj, irn);
1151                                                 set_Proj_proj(mem_proj, 1);
1152
1153                                                 /* clear remat flag */
1154                                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1155
1156                                                 DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1157                                         }
1158                                 } /* if (store) */
1159                                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1160                                         /* There was no store, check if we still can optimize for source address mode */
1161                                         check_am_src = 1;
1162                                 }
1163                         } /* if (support AM Dest) */
1164                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1165                                 /* op doesn't support am AM Dest -> check for AM Source */
1166                                 check_am_src = 1;
1167                         }
1168
1169                         /* normalize commutative ops */
1170                         if (node_is_ia32_comm(irn)) {
1171                                 /* Assure that left operand is always a Load if there is one */
1172                                 /* because non-commutative ops can only use Source AM if the */
1173                                 /* left operand is a Load, so we only need to check the left */
1174                                 /* operand afterwards.                                       */
1175                                 if (pred_is_specific_nodeblock(block, right, is_ia32_Ld))       {
1176                                         set_irn_n(irn, 2, right);
1177                                         set_irn_n(irn, 3, left);
1178
1179                                         temp  = left;
1180                                         left  = right;
1181                                         right = temp;
1182                                 }
1183                         }
1184
1185                         /* optimize op -> Load iff Load is only used by this op   */
1186                         /* and left operand is a Load which only used by this irn */
1187                         if (check_am_src                                        &&
1188                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld) &&
1189                                 (ia32_get_irn_n_edges(left) == 1))
1190                         {
1191                                 left = get_Proj_pred(left);
1192
1193                                 addr_b = get_irn_n(left, 0);
1194                                 addr_i = get_irn_n(left, 1);
1195
1196                                 /* set new base, index and attributes */
1197                                 set_irn_n(irn, 0, addr_b);
1198                                 set_irn_n(irn, 1, addr_i);
1199                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1200                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1201                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1202                                 set_ia32_op_type(irn, ia32_AddrModeS);
1203                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(left));
1204                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(left));
1205
1206                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
1207                                 if (is_ia32_am_sc_sign(left))
1208                                         set_ia32_am_sc_sign(irn);
1209
1210                                 /* clear remat flag */
1211                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1212
1213                                 if (is_ia32_use_frame(left))
1214                                         set_ia32_use_frame(irn);
1215
1216                                 /* connect to Load memory */
1217                                 if (get_irn_arity(irn) == 5) {
1218                                         /* binary AMop */
1219                                         set_irn_n(irn, 4, get_irn_n(left, 2));
1220                                 }
1221                                 else {
1222                                         /* unary AMop */
1223                                         set_irn_n(irn, 3, get_irn_n(left, 2));
1224                                 }
1225
1226                                 /* disconnect from Load */
1227                                 set_irn_n(irn, 2, noreg_gp);
1228
1229                                 /* If Load has a memory Proj, connect it to the op */
1230                                 mem_proj = get_mem_proj(left);
1231                                 if (mem_proj) {
1232                                         set_Proj_pred(mem_proj, irn);
1233                                         set_Proj_proj(mem_proj, 1);
1234                                 }
1235
1236                                 DB((mod, LEVEL_1, "merged with %+F into source AM\n", left));
1237                         }
1238                 }
1239         }
1240 }