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