62707894315114e609764c3bc8c5031bc2c8a304
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Implements several optimizations for IA32.
23  * @author      Christian Wuerdig
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "irnode.h"
31 #include "irprog_t.h"
32 #include "ircons.h"
33 #include "firm_types.h"
34 #include "iredges.h"
35 #include "tv.h"
36 #include "irgmod.h"
37 #include "irgwalk.h"
38 #include "height.h"
39 #include "irbitset.h"
40
41 #include "../be_t.h"
42 #include "../beabi.h"
43 #include "../benode_t.h"
44 #include "../besched_t.h"
45
46 #include "ia32_new_nodes.h"
47 #include "bearch_ia32_t.h"
48 #include "gen_ia32_regalloc_if_t.h"
49 #include "ia32_transform.h"
50 #include "ia32_dbg_stat.h"
51 #include "ia32_util.h"
52
53 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
54
55 #define AGGRESSIVE_AM
56
57 typedef enum {
58         IA32_AM_CAND_NONE  = 0,  /**< no addressmode possible with irn inputs */
59         IA32_AM_CAND_LEFT  = 1,  /**< addressmode possible with left input */
60         IA32_AM_CAND_RIGHT = 2,  /**< addressmode possible with right input */
61         IA32_AM_CAND_BOTH  = 3   /**< addressmode possible with both inputs */
62 } ia32_am_cand_t;
63
64 typedef int is_op_func_t(const ir_node *n);
65 typedef ir_node *load_func_t(dbg_info *db, ir_graph *irg, ir_node *block, ir_node *base, ir_node *index, ir_node *mem);
66
67 /**
68  * checks if a node represents the NOREG value
69  */
70 static INLINE int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
71         return irn == cg->noreg_gp || irn == cg->noreg_xmm || irn == cg->noreg_vfp;
72 }
73
74 /********************************************************************************************************
75  *  _____                _           _         ____        _   _           _          _   _
76  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
77  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
78  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
79  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
80  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
81  *                | |                               | |
82  *                |_|                               |_|
83  ********************************************************************************************************/
84
85 /**
86  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
87  */
88
89 static int ia32_const_equal(const ir_node *n1, const ir_node *n2) {
90         if(get_ia32_immop_type(n1) != get_ia32_immop_type(n2))
91                 return 0;
92
93         if(get_ia32_immop_type(n1) == ia32_ImmConst) {
94                 return get_ia32_Immop_tarval(n1) == get_ia32_Immop_tarval(n2);
95         } else if(get_ia32_immop_type(n1) == ia32_ImmSymConst) {
96                 return get_ia32_Immop_symconst(n1) == get_ia32_Immop_symconst(n2);
97         }
98
99         assert(get_ia32_immop_type(n1) == ia32_ImmNone);
100         return 1;
101 }
102
103 /**
104  * Checks for potential CJmp/CJmpAM optimization candidates.
105  */
106 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
107         ir_node *cand = NULL;
108         ir_node *prev = sched_prev(irn);
109
110         if (is_Block(prev)) {
111                 if (get_Block_n_cfgpreds(prev) == 1)
112                         prev = get_Block_cfgpred(prev, 0);
113                 else
114                         prev = NULL;
115         }
116
117         /* The predecessor must be a ProjX. */
118         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
119                 prev = get_Proj_pred(prev);
120
121                 if (is_op_func(prev))
122                         cand = prev;
123         }
124
125         return cand;
126 }
127
128 static int is_TestJmp_cand(const ir_node *irn) {
129         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
130 }
131
132 /**
133  * Checks if two consecutive arguments of cand matches
134  * the two arguments of irn (TestJmp).
135  */
136 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
137         ir_node *in1       = get_irn_n(irn, 0);
138         ir_node *in2       = get_irn_n(irn, 1);
139         int      i, n      = get_irn_arity(cand);
140         int      same_args = 0;
141
142         for (i = 0; i < n - 1; i++) {
143                 if (get_irn_n(cand, i)     == in1 &&
144                         get_irn_n(cand, i + 1) == in2)
145                 {
146                         same_args = 1;
147                         break;
148                 }
149         }
150
151         if (!same_args)
152                 return 0;
153
154         return ia32_const_equal(cand, irn);
155 }
156
157 /**
158  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
159  */
160 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
161         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
162         int      replace = 0;
163
164         /* we found a possible candidate */
165         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
166
167         if (replace) {
168                 DBG((dbg, LEVEL_1, "replacing %+F by ", irn));
169
170                 if (is_ia32_And(cand))
171                         set_irn_op(irn, op_ia32_CJmpAM);
172                 else
173                         set_irn_op(irn, op_ia32_CJmp);
174
175                 DB((dbg, LEVEL_1, "%+F\n", irn));
176         }
177 }
178
179 static int is_CondJmp_cand(const ir_node *irn) {
180         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
181 }
182
183 /**
184  * Checks if the arguments of cand are the same of irn.
185  */
186 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
187         int i, arity;
188
189         arity = get_irn_arity(cand);
190         for (i = 0; i < arity; i++) {
191                 if (get_irn_n(cand, i) != get_irn_n(irn, i)) {
192                         return 0;
193                 }
194         }
195
196         return ia32_const_equal(cand, irn);
197 }
198
199 /**
200  * Tries to replace a CondJmp by a CJmpAM
201  */
202 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
203         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
204         int      replace = 0;
205
206         /* we found a possible candidate */
207         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
208
209         if (replace) {
210                 DBG((dbg, LEVEL_1, "replacing %+F by ", irn));
211                 DBG_OPT_CJMP(irn);
212
213                 set_irn_op(irn, op_ia32_CJmpAM);
214
215                 DB((dbg, LEVEL_1, "%+F\n", irn));
216         }
217 }
218
219 // only optimize up to 48 stores behind IncSPs
220 #define MAXPUSH_OPTIMIZE        48
221
222 /**
223  * Tries to create pushs from IncSP,Store combinations
224  */
225 static void ia32_create_Pushs(ir_node *irn, ia32_code_gen_t *cg) {
226         int i;
227         int offset;
228         ir_node *node;
229         ir_node *stores[MAXPUSH_OPTIMIZE];
230         ir_node *block = get_nodes_block(irn);
231         ir_graph *irg = cg->irg;
232         ir_node *curr_sp;
233         ir_mode *spmode = get_irn_mode(irn);
234
235         memset(stores, 0, sizeof(stores));
236
237         assert(be_is_IncSP(irn));
238
239         offset = be_get_IncSP_offset(irn);
240         if(offset < 4)
241                 return;
242
243         /*
244          * We first walk the schedule after the IncSP node as long as we find
245          * suitable stores that could be transformed to a push.
246          * We save them into the stores array which is sorted by the frame offset/4
247          * attached to the node
248          */
249         for(node = sched_next(irn); !sched_is_end(node); node = sched_next(node)) {
250                 ir_node *mem;
251                 int offset;
252                 int storeslot;
253
254                 // it has to be a store
255                 if(!is_ia32_Store(node))
256                         break;
257
258                 // it has to use our sp value
259                 if(get_irn_n(node, 0) != irn)
260                         continue;
261                 // store has to be attached to NoMem
262                 mem = get_irn_n(node, 3);
263                 if(!is_NoMem(mem)) {
264                         continue;
265                 }
266
267                 if( (get_ia32_am_flavour(node) & ia32_am_IS) != 0)
268                         break;
269
270                 offset = get_ia32_am_offs_int(node);
271
272                 storeslot = offset / 4;
273                 if(storeslot >= MAXPUSH_OPTIMIZE)
274                         continue;
275
276                 // storing into the same slot twice is bad (and shouldn't happen...)
277                 if(stores[storeslot] != NULL)
278                         break;
279
280                 // storing at half-slots is bad
281                 if(offset % 4 != 0)
282                         break;
283
284                 stores[storeslot] = node;
285         }
286
287         curr_sp = get_irn_n(irn, 0);
288
289         // walk the stores in inverse order and create pushs for them
290         i = (offset / 4) - 1;
291         if(i >= MAXPUSH_OPTIMIZE) {
292                 i = MAXPUSH_OPTIMIZE - 1;
293         }
294
295         for( ; i >= 0; --i) {
296                 const arch_register_t *spreg;
297                 ir_node *push;
298                 ir_node *val, *mem, *mem_proj;
299                 ir_node *store = stores[i];
300                 ir_node *noreg = ia32_new_NoReg_gp(cg);
301
302                 if(store == NULL || is_Bad(store))
303                         break;
304
305                 val = get_irn_n(store, 2);
306                 mem = get_irn_n(store, 3);
307                 spreg = arch_get_irn_register(cg->arch_env, curr_sp);
308
309                 // create a push
310                 push = new_rd_ia32_Push(NULL, irg, block, noreg, noreg, val, curr_sp, mem);
311
312                 set_ia32_am_support(push, ia32_am_Source);
313                 copy_ia32_Immop_attr(push, store);
314
315                 sched_add_before(irn, push);
316
317                 // create stackpointer proj
318                 curr_sp = new_r_Proj(irg, block, push, spmode, pn_ia32_Push_stack);
319                 arch_set_irn_register(cg->arch_env, curr_sp, spreg);
320                 sched_add_before(irn, curr_sp);
321
322                 // create memory proj
323                 mem_proj = new_r_Proj(irg, block, push, mode_M, pn_ia32_Push_M);
324
325                 // use the memproj now
326                 exchange(store, mem_proj);
327
328                 // we can remove the store now
329                 sched_remove(store);
330
331                 offset -= 4;
332         }
333
334         be_set_IncSP_offset(irn, offset);
335
336         // can we remove the IncSP now?
337         if(offset == 0) {
338                 const ir_edge_t *edge, *next;
339
340                 foreach_out_edge_safe(irn, edge, next) {
341                         ir_node *arg = get_edge_src_irn(edge);
342                         int pos = get_edge_src_pos(edge);
343
344                         set_irn_n(arg, pos, curr_sp);
345                 }
346
347                 set_irn_n(irn, 0, new_Bad());
348                 sched_remove(irn);
349         } else {
350                 set_irn_n(irn, 0, curr_sp);
351         }
352 }
353
354 #if 0
355 /**
356  * Tries to optimize two following IncSP.
357  */
358 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
359         ir_node *prev = be_get_IncSP_pred(irn);
360         int real_uses = get_irn_n_edges(prev);
361
362         if (be_is_IncSP(prev) && real_uses == 1) {
363                 /* first IncSP has only one IncSP user, kill the first one */
364                 int prev_offs = be_get_IncSP_offset(prev);
365                 int curr_offs = be_get_IncSP_offset(irn);
366
367                 be_set_IncSP_offset(prev, prev_offs + curr_offs);
368
369                 /* Omit the optimized IncSP */
370                 be_set_IncSP_pred(irn, be_get_IncSP_pred(prev));
371
372                 set_irn_n(prev, 0, new_Bad());
373                 sched_remove(prev);
374         }
375 }
376 #endif
377
378 /**
379  * Performs Peephole Optimizations.
380  */
381 static void ia32_peephole_optimize_node(ir_node *irn, void *env) {
382         ia32_code_gen_t *cg = env;
383
384         /* AMD CPUs want explicit compare before conditional jump  */
385         if (! ARCH_AMD(cg->opt_arch)) {
386                 if (is_ia32_TestJmp(irn))
387                         ia32_optimize_TestJmp(irn, cg);
388                 else if (is_ia32_CondJmp(irn))
389                         ia32_optimize_CondJmp(irn, cg);
390         }
391
392         if (be_is_IncSP(irn)) {
393                 // optimize_IncSP doesn't respect dependency edges yet...
394                 //ia32_optimize_IncSP(irn, cg);
395
396                 if (cg->opt & IA32_OPT_PUSHARGS)
397                         ia32_create_Pushs(irn, cg);
398         }
399 }
400
401 void ia32_peephole_optimization(ir_graph *irg, ia32_code_gen_t *cg) {
402         irg_walk_graph(irg, ia32_peephole_optimize_node, NULL, cg);
403 }
404
405 /******************************************************************
406  *              _     _                   __  __           _
407  *     /\      | |   | |                 |  \/  |         | |
408  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
409  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
410  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
411  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
412  *
413  ******************************************************************/
414
415 typedef struct {
416         ia32_code_gen_t *cg;
417         heights_t       *h;
418 } ia32_am_opt_env_t;
419
420 static int node_is_ia32_comm(const ir_node *irn) {
421         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
422 }
423
424 static int ia32_get_irn_n_edges(const ir_node *irn) {
425         const ir_edge_t *edge;
426         int cnt = 0;
427
428         foreach_out_edge(irn, edge) {
429                 cnt++;
430         }
431
432         return cnt;
433 }
434
435 /**
436  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
437  *
438  * @param pred       The node to be checked
439  * @param is_op_func The check-function
440  * @return 1 if conditions are fulfilled, 0 otherwise
441  */
442 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
443         return is_op_func(pred);
444 }
445
446 /**
447  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
448  * and if the predecessor is in block bl.
449  *
450  * @param bl         The block
451  * @param pred       The node to be checked
452  * @param is_op_func The check-function
453  * @return 1 if conditions are fulfilled, 0 otherwise
454  */
455 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
456         int (*is_op_func)(const ir_node *n))
457 {
458         if (is_Proj(pred)) {
459                 pred = get_Proj_pred(pred);
460                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
461                         return 1;
462                 }
463         }
464
465         return 0;
466 }
467
468 /**
469  * Checks if irn is a candidate for address calculation. We avoid transforming
470  * adds to leas if they have a load as pred, because then we can use AM mode
471  * for the add later.
472  *
473  * - none of the operand must be a Load  within the same block OR
474  * - all Loads must have more than one user                    OR
475  *
476  * @param block   The block the Loads must/mustnot be in
477  * @param irn     The irn to check
478  * return 1 if irn is a candidate, 0 otherwise
479  */
480 static int is_addr_candidate(const ir_node *irn) {
481 #ifndef AGGRESSIVE_AM
482         const ir_node *block = get_nodes_block(irn);
483         ir_node *left, *right;
484         int      n;
485
486         left  = get_irn_n(irn, 2);
487         right = get_irn_n(irn, 3);
488
489         if (pred_is_specific_nodeblock(block, left, is_ia32_Ld)) {
490                 n         = ia32_get_irn_n_edges(left);
491                 /* load with only one user: don't create LEA */
492                 if(n == 1)
493                         return 0;
494         }
495
496         if (pred_is_specific_nodeblock(block, right, is_ia32_Ld)) {
497                 n         = ia32_get_irn_n_edges(right);
498                 if(n == 1)
499                         return 0;
500         }
501 #endif
502
503         return 1;
504 }
505
506 /**
507  * Checks if irn is a candidate for address mode.
508  *
509  * address mode (AM):
510  * - at least one operand has to be a Load within the same block AND
511  * - the load must not have other users than the irn             AND
512  * - the irn must not have a frame entity set
513  *
514  * @param cg          The ia32 code generator
515  * @param h           The height information of the irg
516  * @param block       The block the Loads must/mustnot be in
517  * @param irn         The irn to check
518  * return 0 if irn is no candidate, 1 if left load can be used, 2 if right one, 3 for both
519  */
520 static ia32_am_cand_t is_am_candidate(ia32_code_gen_t *cg, heights_t *h, const ir_node *block, ir_node *irn) {
521         ir_node *in, *load, *other, *left, *right;
522         int      is_cand = 0, cand;
523         int arity;
524
525         if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn) || is_ia32_vfild(irn) || is_ia32_vfist(irn) ||
526                 is_ia32_GetST0(irn) || is_ia32_SetST0(irn) || is_ia32_xStoreSimple(irn))
527                 return 0;
528
529         if(get_ia32_frame_ent(irn) != NULL)
530                 return IA32_AM_CAND_NONE;
531
532         left  = get_irn_n(irn, 2);
533         arity = get_irn_arity(irn);
534         assert(arity == 5 || arity == 4);
535         if(arity == 5) {
536                 /* binary op */
537                 right = get_irn_n(irn, 3);
538         } else {
539                 /* unary op */
540                 right = left;
541         }
542
543         in = left;
544
545         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
546 #ifndef AGGRESSIVE_AM
547                 int n;
548                 n         = ia32_get_irn_n_edges(in);
549                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
550 #else
551                 is_cand   = 1;
552 #endif
553
554                 load  = get_Proj_pred(in);
555                 other = right;
556
557                 /* 8bit Loads are not supported (for binary ops),
558                  * they cannot be used with every register */
559                 if (get_irn_arity(irn) != 4 && get_mode_size_bits(get_ia32_ls_mode(load)) < 16) {
560                         assert(get_irn_arity(irn) == 5);
561                         is_cand = 0;
562                 }
563
564                 /* If there is a data dependency of other irn from load: cannot use AM */
565                 if (is_cand && get_nodes_block(other) == block) {
566                         other   = skip_Proj(other);
567                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
568                         /* this could happen in loops */
569                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
570                 }
571         }
572
573         cand    = is_cand ? IA32_AM_CAND_LEFT : IA32_AM_CAND_NONE;
574         in      = right;
575         is_cand = 0;
576
577         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
578 #ifndef AGGRESSIVE_AM
579                 int n;
580                 n         = ia32_get_irn_n_edges(in);
581                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
582 #else
583                 is_cand = 1;
584 #endif
585
586                 load  = get_Proj_pred(in);
587                 other = left;
588
589                 /* 8bit Loads are not supported, they cannot be used with every register */
590                 if (get_mode_size_bits(get_ia32_ls_mode(load)) < 16)
591                         is_cand = 0;
592
593                 /* If there is a data dependency of other irn from load: cannot use load */
594                 if (is_cand && get_nodes_block(other) == block) {
595                         other   = skip_Proj(other);
596                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
597                         /* this could happen in loops */
598                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
599                 }
600         }
601
602         cand = is_cand ? (cand | IA32_AM_CAND_RIGHT) : cand;
603
604         /* if the irn has a frame entity: we do not use address mode */
605         return cand;
606 }
607
608 /**
609  * Compares the base and index addr and the load/store entities
610  * and returns 1 if they are equal.
611  */
612 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
613                                                                         const ir_node *addr_b, const ir_node *addr_i)
614 {
615         if(get_irn_n(load, 0) != addr_b)
616                 return 0;
617         if(get_irn_n(load, 1) != addr_i)
618                 return 0;
619
620         if(get_ia32_frame_ent(load) != get_ia32_frame_ent(store))
621                 return 0;
622
623         if(get_ia32_am_sc(load) != get_ia32_am_sc(store))
624                 return 0;
625         if(is_ia32_am_sc_sign(load) != is_ia32_am_sc_sign(store))
626                 return 0;
627         if(get_ia32_am_offs_int(load) != get_ia32_am_offs_int(store))
628                 return 0;
629         if(get_ia32_ls_mode(load) != get_ia32_ls_mode(store))
630                 return 0;
631
632         return 1;
633 }
634
635 typedef enum _ia32_take_lea_attr {
636         IA32_LEA_ATTR_NONE  = 0,
637         IA32_LEA_ATTR_BASE  = (1 << 0),
638         IA32_LEA_ATTR_INDEX = (1 << 1),
639         IA32_LEA_ATTR_OFFS  = (1 << 2),
640         IA32_LEA_ATTR_SCALE = (1 << 3),
641         IA32_LEA_ATTR_AMSC  = (1 << 4),
642         IA32_LEA_ATTR_FENT  = (1 << 5)
643 } ia32_take_lea_attr;
644
645 /**
646  * Decides if we have to keep the LEA operand or if we can assimilate it.
647  */
648 static int do_new_lea(ir_node *irn, ir_node *base, ir_node *index, ir_node *lea,
649                 int have_am_sc, ia32_code_gen_t *cg)
650 {
651         ir_entity *irn_ent  = get_ia32_frame_ent(irn);
652         ir_entity *lea_ent  = get_ia32_frame_ent(lea);
653         int        ret_val  = 0;
654         int        is_noreg_base  = be_is_NoReg(cg, base);
655         int        is_noreg_index = be_is_NoReg(cg, index);
656         ia32_am_flavour_t am_flav = get_ia32_am_flavour(lea);
657
658         /* If the Add and the LEA both have a different frame entity set: keep */
659         if (irn_ent && lea_ent && (irn_ent != lea_ent))
660                 return IA32_LEA_ATTR_NONE;
661         else if (! irn_ent && lea_ent)
662                 ret_val |= IA32_LEA_ATTR_FENT;
663
664         /* If the Add and the LEA both have already an address mode symconst: keep */
665         if (have_am_sc && get_ia32_am_sc(lea))
666                 return IA32_LEA_ATTR_NONE;
667         else if (get_ia32_am_sc(lea))
668                 ret_val |= IA32_LEA_ATTR_AMSC;
669
670         /* Check the different base-index combinations */
671
672         if (! is_noreg_base && ! is_noreg_index) {
673                 /* Assimilate if base is the lea and the LEA is just a Base + Offset calculation */
674                 if ((base == lea) && ! (am_flav & ia32_I ? 1 : 0)) {
675                         if (am_flav & ia32_O)
676                                 ret_val |= IA32_LEA_ATTR_OFFS;
677
678                         ret_val |= IA32_LEA_ATTR_BASE;
679                 }
680                 else
681                         return IA32_LEA_ATTR_NONE;
682         }
683         else if (! is_noreg_base && is_noreg_index) {
684                 /* Base is set but index not */
685                 if (base == lea) {
686                         /* Base points to LEA: assimilate everything */
687                         if (am_flav & ia32_O)
688                                 ret_val |= IA32_LEA_ATTR_OFFS;
689                         if (am_flav & ia32_S)
690                                 ret_val |= IA32_LEA_ATTR_SCALE;
691                         if (am_flav & ia32_I)
692                                 ret_val |= IA32_LEA_ATTR_INDEX;
693
694                         ret_val |= IA32_LEA_ATTR_BASE;
695                 }
696                 else if (am_flav & ia32_B ? 0 : 1) {
697                         /* Base is not the LEA but the LEA is an index only calculation: assimilate */
698                         if (am_flav & ia32_O)
699                                 ret_val |= IA32_LEA_ATTR_OFFS;
700                         if (am_flav & ia32_S)
701                                 ret_val |= IA32_LEA_ATTR_SCALE;
702
703                         ret_val |= IA32_LEA_ATTR_INDEX;
704                 }
705                 else
706                         return IA32_LEA_ATTR_NONE;
707         }
708         else if (is_noreg_base && ! is_noreg_index) {
709                 /* Index is set but not base */
710                 if (index == lea) {
711                         /* Index points to LEA: assimilate everything */
712                         if (am_flav & ia32_O)
713                                 ret_val |= IA32_LEA_ATTR_OFFS;
714                         if (am_flav & ia32_S)
715                                 ret_val |= IA32_LEA_ATTR_SCALE;
716                         if (am_flav & ia32_B)
717                                 ret_val |= IA32_LEA_ATTR_BASE;
718
719                         ret_val |= IA32_LEA_ATTR_INDEX;
720                 }
721                 else if (am_flav & ia32_I ? 0 : 1) {
722                         /* Index is not the LEA but the LEA is a base only calculation: assimilate */
723                         if (am_flav & ia32_O)
724                                 ret_val |= IA32_LEA_ATTR_OFFS;
725                         if (am_flav & ia32_S)
726                                 ret_val |= IA32_LEA_ATTR_SCALE;
727
728                         ret_val |= IA32_LEA_ATTR_BASE;
729                 }
730                 else
731                         return IA32_LEA_ATTR_NONE;
732         }
733         else {
734                 assert(0 && "There must have been set base or index");
735         }
736
737         return ret_val;
738 }
739
740 /**
741  * Adds res before irn into schedule if irn was scheduled.
742  * @param irn  The schedule point
743  * @param res  The node to be scheduled
744  */
745 static INLINE void try_add_to_sched(ir_node *irn, ir_node *res) {
746         if (sched_is_scheduled(irn))
747                 sched_add_before(irn, res);
748 }
749
750 /**
751  * Removes node from schedule if it is not used anymore. If irn is a mode_T node
752  * all it's Projs are removed as well.
753  * @param irn  The irn to be removed from schedule
754  */
755 static INLINE void try_remove_from_sched(ir_node *node) {
756         int i, arity;
757
758         if(get_irn_mode(node) == mode_T) {
759                 const ir_edge_t *edge, *next;
760                 foreach_out_edge_safe(node, edge, next) {
761                         ir_node *proj = get_edge_src_irn(edge);
762                         try_remove_from_sched(proj);
763                 }
764         }
765
766         if(get_irn_n_edges(node) != 0)
767                 return;
768
769         if (sched_is_scheduled(node)) {
770                 sched_remove(node);
771         }
772
773         arity = get_irn_arity(node);
774         for(i = 0; i < arity; ++i) {
775                 set_irn_n(node, i, new_Bad());
776         }
777 }
778
779 /**
780  * Folds Add or Sub to LEA if possible
781  */
782 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn) {
783         ir_graph   *irg        = get_irn_irg(irn);
784         dbg_info   *dbg_info   = get_irn_dbg_info(irn);
785         ir_node    *block      = get_nodes_block(irn);
786         ir_node    *res        = irn;
787         ir_node    *shift      = NULL;
788         ir_node    *lea_o      = NULL;
789         ir_node    *lea        = NULL;
790         long        offs       = 0;
791         long        offs_cnst  = 0;
792         long        offs_lea   = 0;
793         int         scale      = 0;
794         int         isadd      = 0;
795         int         dolea      = 0;
796         int         have_am_sc = 0;
797         int         am_sc_sign = 0;
798         ir_entity  *am_sc      = NULL;
799         ir_entity  *lea_ent    = NULL;
800         ir_node    *noreg      = ia32_new_NoReg_gp(cg);
801         ir_node    *left, *right, *temp;
802         ir_node    *base, *index;
803         int consumed_left_shift;
804         ia32_am_flavour_t am_flav;
805
806         if (is_ia32_Add(irn))
807                 isadd = 1;
808
809         left  = get_irn_n(irn, 2);
810         right = get_irn_n(irn, 3);
811
812         /* "normalize" arguments in case of add with two operands */
813         if  (isadd && ! be_is_NoReg(cg, right)) {
814                 /* put LEA == ia32_am_O as right operand */
815                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
816                         set_irn_n(irn, 2, right);
817                         set_irn_n(irn, 3, left);
818                         temp  = left;
819                         left  = right;
820                         right = temp;
821                 }
822
823                 /* put LEA != ia32_am_O as left operand */
824                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
825                         set_irn_n(irn, 2, right);
826                         set_irn_n(irn, 3, left);
827                         temp  = left;
828                         left  = right;
829                         right = temp;
830                 }
831
832                 /* put SHL as left operand iff left is NOT a LEA */
833                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
834                         set_irn_n(irn, 2, right);
835                         set_irn_n(irn, 3, left);
836                         temp  = left;
837                         left  = right;
838                         right = temp;
839                 }
840         }
841
842         base    = left;
843         index   = noreg;
844         offs    = 0;
845         scale   = 0;
846         am_flav = 0;
847
848         /* check for operation with immediate */
849         if (is_ia32_ImmConst(irn)) {
850                 tarval *tv = get_ia32_Immop_tarval(irn);
851
852                 DBG((dbg, LEVEL_1, "\tfound op with imm const"));
853
854                 offs_cnst = get_tarval_long(tv);
855                 dolea     = 1;
856         }
857         else if (isadd && is_ia32_ImmSymConst(irn)) {
858                 DBG((dbg, LEVEL_1, "\tfound op with imm symconst"));
859
860                 have_am_sc = 1;
861                 dolea      = 1;
862                 am_sc      = get_ia32_Immop_symconst(irn);
863                 am_sc_sign = is_ia32_am_sc_sign(irn);
864         }
865
866         /* determine the operand which needs to be checked */
867         temp = be_is_NoReg(cg, right) ? left : right;
868
869         /* check if right operand is AMConst (LEA with ia32_am_O)  */
870         /* but we can only eat it up if there is no other symconst */
871         /* because the linker won't accept two symconsts           */
872         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
873                 DBG((dbg, LEVEL_1, "\tgot op with LEA am_O"));
874
875                 offs_lea   = get_ia32_am_offs_int(temp);
876                 am_sc      = get_ia32_am_sc(temp);
877                 am_sc_sign = is_ia32_am_sc_sign(temp);
878                 have_am_sc = 1;
879                 dolea      = 1;
880                 lea_o      = temp;
881
882                 if (temp == base)
883                         base = noreg;
884                 else if (temp == right)
885                         right = noreg;
886         }
887
888         if (isadd) {
889                 /* default for add -> make right operand to index */
890                 index               = right;
891                 dolea               = 1;
892                 consumed_left_shift = -1;
893
894                 DBG((dbg, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
895
896                 /* determine the operand which needs to be checked */
897                 temp = left;
898                 if (is_ia32_Lea(left)) {
899                         temp = right;
900                         consumed_left_shift = 0;
901                 }
902
903                 /* check for SHL 1,2,3 */
904                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
905
906                         if (is_ia32_ImmConst(temp)) {
907                                 long shiftval = get_tarval_long(get_ia32_Immop_tarval(temp));
908
909                                 if (shiftval <= 3) {
910                                         index               = get_irn_n(temp, 2);
911                                         consumed_left_shift = consumed_left_shift < 0 ? 1 : 0;
912                                         shift = temp;
913                                         scale = shiftval;
914
915                                         DBG((dbg, LEVEL_1, "\tgot scaled index %+F\n", index));
916                                 }
917                         }
918                 }
919
920                 /* fix base */
921                 if (! be_is_NoReg(cg, index)) {
922                         /* if we have index, but left == right -> no base */
923                         if (left == right) {
924                                 base = noreg;
925                         }
926                         else if (consumed_left_shift == 1) {
927                                 /* -> base is right operand  */
928                                 base = (right == lea_o) ? noreg : right;
929                         }
930                 }
931         }
932
933         /* Try to assimilate a LEA as left operand */
934         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
935                 /* check if we can assimilate the LEA */
936                 int take_attr = do_new_lea(irn, base, index, left, have_am_sc, cg);
937
938                 if (take_attr == IA32_LEA_ATTR_NONE) {
939                         DBG((dbg, LEVEL_1, "\tleave old LEA, creating new one\n"));
940                 }
941                 else {
942                         DBG((dbg, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
943                         lea = left; /* for statistics */
944
945                         if (take_attr & IA32_LEA_ATTR_OFFS)
946                                 offs = get_ia32_am_offs_int(left);
947
948                         if (take_attr & IA32_LEA_ATTR_AMSC) {
949                                 am_sc      = get_ia32_am_sc(left);
950                                 have_am_sc = 1;
951                                 am_sc_sign = is_ia32_am_sc_sign(left);
952                         }
953
954                         if (take_attr & IA32_LEA_ATTR_SCALE)
955                                 scale = get_ia32_am_scale(left);
956
957                         if (take_attr & IA32_LEA_ATTR_BASE)
958                                 base = get_irn_n(left, 0);
959
960                         if (take_attr & IA32_LEA_ATTR_INDEX)
961                                 index = get_irn_n(left, 1);
962
963                         if (take_attr & IA32_LEA_ATTR_FENT)
964                                 lea_ent = get_ia32_frame_ent(left);
965                 }
966         }
967
968         /* ok, we can create a new LEA */
969         if (dolea) {
970                 res = new_rd_ia32_Lea(dbg_info, irg, block, base, index);
971                 /* we don't want stuff before the barrier... */
972                 if(be_is_NoReg(cg, base) && be_is_NoReg(cg, index)) {
973                         add_irn_dep(res, get_irg_frame(irg));
974                 }
975
976                 /* add the old offset of a previous LEA */
977                 add_ia32_am_offs_int(res, offs);
978
979                 /* add the new offset */
980                 if (isadd) {
981                         add_ia32_am_offs_int(res, offs_cnst);
982                         add_ia32_am_offs_int(res, offs_lea);
983                 } else {
984                         /* either lea_O-cnst, -cnst or -lea_O  */
985                         if (offs_cnst != 0) {
986                                 add_ia32_am_offs_int(res, offs_lea);
987                                 add_ia32_am_offs_int(res, -offs_cnst);
988                         } else {
989                                 add_ia32_am_offs_int(res, offs_lea);
990                         }
991                 }
992
993                 /* set the address mode symconst */
994                 if (have_am_sc) {
995                         set_ia32_am_sc(res, am_sc);
996                         if (am_sc_sign)
997                                 set_ia32_am_sc_sign(res);
998                 }
999
1000                 /* copy the frame entity (could be set in case of Add */
1001                 /* which was a FrameAddr) */
1002                 if (lea_ent != NULL) {
1003                         set_ia32_frame_ent(res, lea_ent);
1004                         set_ia32_use_frame(res);
1005                 } else {
1006                         set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
1007                         if(is_ia32_use_frame(irn))
1008                                 set_ia32_use_frame(res);
1009                 }
1010
1011                 /* set scale */
1012                 set_ia32_am_scale(res, scale);
1013
1014                 am_flav = ia32_am_N;
1015                 /* determine new am flavour */
1016                 if (offs || offs_cnst || offs_lea || have_am_sc) {
1017                         am_flav |= ia32_O;
1018                 }
1019                 if (! be_is_NoReg(cg, base)) {
1020                         am_flav |= ia32_B;
1021                 }
1022                 if (! be_is_NoReg(cg, index)) {
1023                         am_flav |= ia32_I;
1024                 }
1025                 if (scale > 0) {
1026                         am_flav |= ia32_S;
1027                 }
1028                 set_ia32_am_flavour(res, am_flav);
1029
1030                 set_ia32_op_type(res, ia32_AddrModeS);
1031
1032                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
1033
1034                 DBG((dbg, LEVEL_1, "\tLEA [%+F + %+F * %d + %d]\n", base, index, scale, get_ia32_am_offs_int(res)));
1035
1036                 assert(irn && "Couldn't find result proj");
1037
1038                 /* get the result Proj of the Add/Sub */
1039                 try_add_to_sched(irn, res);
1040
1041                 /* exchange the old op with the new LEA */
1042                 try_remove_from_sched(irn);
1043                 exchange(irn, res);
1044
1045                 /* we will exchange it, report here before the Proj is created */
1046                 if (shift && lea && lea_o) {
1047                         try_remove_from_sched(shift);
1048                         try_remove_from_sched(lea);
1049                         try_remove_from_sched(lea_o);
1050                         DBG_OPT_LEA4(irn, lea_o, lea, shift, res);
1051                 } else if (shift && lea) {
1052                         try_remove_from_sched(shift);
1053                         try_remove_from_sched(lea);
1054                         DBG_OPT_LEA3(irn, lea, shift, res);
1055                 } else if (shift && lea_o) {
1056                         try_remove_from_sched(shift);
1057                         try_remove_from_sched(lea_o);
1058                         DBG_OPT_LEA3(irn, lea_o, shift, res);
1059                 } else if (lea && lea_o) {
1060                         try_remove_from_sched(lea);
1061                         try_remove_from_sched(lea_o);
1062                         DBG_OPT_LEA3(irn, lea_o, lea, res);
1063                 } else if (shift) {
1064                         try_remove_from_sched(shift);
1065                         DBG_OPT_LEA2(irn, shift, res);
1066                 } else if (lea) {
1067                         try_remove_from_sched(lea);
1068                         DBG_OPT_LEA2(irn, lea, res);
1069                 } else if (lea_o) {
1070                         try_remove_from_sched(lea_o);
1071                         DBG_OPT_LEA2(irn, lea_o, res);
1072                 } else {
1073                         DBG_OPT_LEA1(irn, res);
1074                 }
1075         }
1076
1077         return res;
1078 }
1079
1080
1081 /**
1082  * Merges a Load/Store node with a LEA.
1083  * @param irn The Load/Store node
1084  * @param lea The LEA
1085  */
1086 static void merge_loadstore_lea(ir_node *irn, ir_node *lea) {
1087         ir_entity *irn_ent = get_ia32_frame_ent(irn);
1088         ir_entity *lea_ent = get_ia32_frame_ent(lea);
1089
1090         /* If the irn and the LEA both have a different frame entity set: do not merge */
1091         if (irn_ent != NULL && lea_ent != NULL && (irn_ent != lea_ent))
1092                 return;
1093         else if (irn_ent == NULL && lea_ent != NULL) {
1094                 set_ia32_frame_ent(irn, lea_ent);
1095                 set_ia32_use_frame(irn);
1096         }
1097
1098         /* get the AM attributes from the LEA */
1099         add_ia32_am_offs_int(irn, get_ia32_am_offs_int(lea));
1100         set_ia32_am_scale(irn, get_ia32_am_scale(lea));
1101         set_ia32_am_flavour(irn, get_ia32_am_flavour(lea));
1102
1103         set_ia32_am_sc(irn, get_ia32_am_sc(lea));
1104         if (is_ia32_am_sc_sign(lea))
1105                 set_ia32_am_sc_sign(irn);
1106
1107         set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1108
1109         /* set base and index */
1110         set_irn_n(irn, 0, get_irn_n(lea, 0));
1111         set_irn_n(irn, 1, get_irn_n(lea, 1));
1112
1113         try_remove_from_sched(lea);
1114
1115         /* clear remat flag */
1116         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1117
1118         if (is_ia32_Ld(irn))
1119                 DBG_OPT_LOAD_LEA(lea, irn);
1120         else
1121                 DBG_OPT_STORE_LEA(lea, irn);
1122
1123 }
1124
1125 /**
1126  * Sets new_right index of irn to right and new_left index to left.
1127  * Also exchange left and right
1128  */
1129 static void exchange_left_right(ir_node *irn, ir_node **left, ir_node **right, int new_left, int new_right) {
1130         ir_node *temp;
1131
1132         set_irn_n(irn, new_right, *right);
1133         set_irn_n(irn, new_left, *left);
1134
1135         temp   = *left;
1136         *left  = *right;
1137         *right = temp;
1138
1139         /* this is only needed for Compares, but currently ALL nodes
1140          * have this attribute :-) */
1141         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1142 }
1143
1144 /**
1145  * Performs address calculation optimization (create LEAs if possible)
1146  */
1147 static void optimize_lea(ia32_code_gen_t *cg, ir_node *irn) {
1148         if (! is_ia32_irn(irn))
1149                 return;
1150
1151         /* Following cases can occur:                                  */
1152         /* - Sub (l, imm) -> LEA [base - offset]                       */
1153         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
1154         /* - Add (l, imm) -> LEA [base + offset]                       */
1155         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
1156         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
1157         /* - Add (l, r) -> LEA [base + index * scale]                  */
1158         /*              with scale > 1 iff l/r == shl (1,2,3)          */
1159         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
1160                 ir_node *res;
1161
1162                 if(!is_addr_candidate(irn))
1163                         return;
1164
1165                 DBG((dbg, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
1166                 res = fold_addr(cg, irn);
1167
1168                 if (res != irn)
1169                         DB((dbg, LEVEL_1, "transformed into %+F\n", res));
1170                 else
1171                         DB((dbg, LEVEL_1, "not transformed\n"));
1172         } else if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
1173                 /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
1174                 /* - Store -> LEA into Store }       it might be better to keep the LEA             */
1175                 ir_node *left = get_irn_n(irn, 0);
1176
1177                 if (is_ia32_Lea(left)) {
1178                         const ir_edge_t *edge, *ne;
1179                         ir_node *src;
1180
1181                         /* merge all Loads/Stores connected to this LEA with the LEA */
1182                         foreach_out_edge_safe(left, edge, ne) {
1183                                 src = get_edge_src_irn(edge);
1184
1185                                 if (src && (get_edge_src_pos(edge) == 0) && (is_ia32_Ld(src) || is_ia32_St(src) || is_ia32_Store8Bit(src))) {
1186                                         DBG((dbg, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1187                                         if (! is_ia32_got_lea(src))
1188                                                 merge_loadstore_lea(src, left);
1189                                         set_ia32_got_lea(src);
1190                                 }
1191                         }
1192                 }
1193         }
1194 }
1195
1196 static void optimize_conv_store(ia32_code_gen_t *cg, ir_node *node)
1197 {
1198         ir_node *pred;
1199         ir_mode *conv_mode;
1200         ir_mode *store_mode;
1201
1202         if(!is_ia32_Store(node) && !is_ia32_Store8Bit(node))
1203                 return;
1204
1205         pred = get_irn_n(node, 2);
1206         if(!is_ia32_Conv_I2I(pred) && !is_ia32_Conv_I2I8Bit(pred))
1207                 return;
1208
1209         /* the store only stores the lower bits, so we only need the conv
1210          * it it shrinks the mode */
1211         conv_mode  = get_ia32_ls_mode(pred);
1212         store_mode = get_ia32_ls_mode(node);
1213         if(get_mode_size_bits(conv_mode) < get_mode_size_bits(store_mode))
1214                 return;
1215
1216         set_irn_n(node, 2, get_irn_n(pred, 2));
1217         if(get_irn_n_edges(pred) == 0) {
1218                 be_kill_node(pred);
1219         }
1220 }
1221
1222 static void optimize_load_conv(ia32_code_gen_t *cg, ir_node *node)
1223 {
1224         ir_node *pred, *predpred;
1225         ir_mode *load_mode;
1226         ir_mode *conv_mode;
1227
1228         if (!is_ia32_Conv_I2I(node) && !is_ia32_Conv_I2I8Bit(node))
1229                 return;
1230
1231         pred = get_irn_n(node, 2);
1232         if(!is_Proj(pred))
1233                 return;
1234
1235         predpred = get_Proj_pred(pred);
1236         if(!is_ia32_Load(predpred))
1237                 return;
1238
1239         /* the load is sign extending the upper bits, so we only need the conv
1240          * if it shrinks the mode */
1241         load_mode = get_ia32_ls_mode(predpred);
1242         conv_mode = get_ia32_ls_mode(node);
1243         if(get_mode_size_bits(conv_mode) < get_mode_size_bits(load_mode))
1244                 return;
1245
1246         if(get_mode_sign(conv_mode) != get_mode_sign(load_mode)) {
1247                 /* change the load if it has only 1 user */
1248                 if(get_irn_n_edges(pred) == 1) {
1249                         ir_mode *newmode;
1250                         if(get_mode_sign(conv_mode)) {
1251                                 newmode = find_signed_mode(load_mode);
1252                         } else {
1253                                 newmode = find_unsigned_mode(load_mode);
1254                         }
1255                         assert(newmode != NULL);
1256                         set_ia32_ls_mode(predpred, newmode);
1257                 } else {
1258                         /* otherwise we have to keep the conv */
1259                         return;
1260                 }
1261         }
1262
1263         /* kill the conv */
1264         exchange(node, pred);
1265 }
1266
1267 static void optimize_conv_conv(ia32_code_gen_t *cg, ir_node *node)
1268 {
1269         ir_node *pred;
1270         ir_mode *pred_mode;
1271         ir_mode *conv_mode;
1272
1273         if (!is_ia32_Conv_I2I(node) && !is_ia32_Conv_I2I8Bit(node))
1274                 return;
1275
1276         assert(n_ia32_Conv_I2I_val == n_ia32_Conv_I2I8Bit_val);
1277         pred = get_irn_n(node, n_ia32_Conv_I2I_val);
1278         if(!is_ia32_Conv_I2I(pred) && !is_ia32_Conv_I2I8Bit(pred))
1279                 return;
1280
1281         /* we know that after a conv, the upper bits are sign extended
1282          * so we only need the 2nd conv if it shrinks the mode */
1283         conv_mode = get_ia32_ls_mode(node);
1284         pred_mode = get_ia32_ls_mode(pred);
1285         if(get_mode_size_bits(conv_mode) < get_mode_size_bits(pred_mode))
1286                 return;
1287
1288         /* we can't eliminate an upconv signed->unsigned  */
1289         if (get_mode_size_bits(conv_mode) != get_mode_size_bits(pred_mode) &&
1290                 !get_mode_sign(conv_mode) && get_mode_sign(pred_mode))
1291                 return;
1292
1293         /* kill the conv */
1294         exchange(node, pred);
1295 }
1296
1297 static void optimize_node(ir_node *node, void *env)
1298 {
1299         ia32_code_gen_t *cg = env;
1300
1301         optimize_load_conv(cg, node);
1302         optimize_conv_store(cg, node);
1303         optimize_conv_conv(cg, node);
1304         optimize_lea(cg, node);
1305 }
1306
1307 /**
1308  * Checks for address mode patterns and performs the
1309  * necessary transformations.
1310  * This function is called by a walker.
1311  */
1312 static void optimize_am(ir_node *irn, void *env) {
1313         ia32_am_opt_env_t *am_opt_env = env;
1314         ia32_code_gen_t   *cg         = am_opt_env->cg;
1315         ir_graph          *irg        = get_irn_irg(irn);
1316         heights_t         *h          = am_opt_env->h;
1317         ir_node           *block, *left, *right;
1318         ir_node           *store, *load, *mem_proj;
1319         ir_node           *addr_b, *addr_i;
1320         int               need_exchange_on_fail = 0;
1321         ia32_am_type_t    am_support;
1322         ia32_am_cand_t cand;
1323         ia32_am_cand_t orig_cand;
1324         int               dest_possible;
1325         int               source_possible;
1326
1327         static const arch_register_req_t dest_out_reg_req_0 = {
1328                 arch_register_req_type_none,
1329                 NULL,        /* regclass */
1330                 NULL,        /* limit bitset */
1331                 -1,          /* same pos */
1332                 -1           /* different pos */
1333         };
1334         static const arch_register_req_t *dest_am_out_reqs[] = {
1335                 &dest_out_reg_req_0
1336         };
1337
1338         if (!is_ia32_irn(irn) || is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn))
1339                 return;
1340         if (is_ia32_Lea(irn))
1341                 return;
1342
1343         am_support = get_ia32_am_support(irn);
1344         block = get_nodes_block(irn);
1345
1346         /* fold following patterns:                                                         */
1347         /* - op -> Load into AMop with am_Source                                            */
1348         /*   conditions:                                                                    */
1349         /*     - op is am_Source capable AND                                                */
1350         /*     - the Load is only used by this op AND                                       */
1351         /*     - the Load is in the same block                                              */
1352         /* - Store -> op -> Load  into AMop with am_Dest                                    */
1353         /*   conditions:                                                                    */
1354         /*     - op is am_Dest capable AND                                                  */
1355         /*     - the Store uses the same address as the Load AND                            */
1356         /*     - the Load is only used by this op AND                                       */
1357         /*     - the Load and Store are in the same block AND                               */
1358         /*     - nobody else uses the result of the op                                      */
1359         if (get_ia32_am_support(irn) == ia32_am_None)
1360                 return;
1361
1362         cand = is_am_candidate(cg, h, block, irn);
1363         if (cand == IA32_AM_CAND_NONE)
1364                 return;
1365
1366         orig_cand = cand;
1367         DBG((dbg, LEVEL_1, "\tfound address mode candidate %+F (candleft %d candright %d)... \n", irn,
1368              cand & IA32_AM_CAND_LEFT, cand & IA32_AM_CAND_RIGHT));
1369
1370         left  = get_irn_n(irn, 2);
1371         if (get_irn_arity(irn) == 4) {
1372                 /* it's an "unary" operation */
1373                 right = left;
1374                 assert(cand == IA32_AM_CAND_BOTH);
1375         } else {
1376                 right = get_irn_n(irn, 3);
1377         }
1378
1379         dest_possible = am_support & ia32_am_Dest ? 1 : 0;
1380         source_possible = am_support & ia32_am_Source ? 1 : 0;
1381
1382         DBG((dbg, LEVEL_2, "\tdest_possible %d source_possible %d ... \n", dest_possible, source_possible));
1383
1384         if (dest_possible) {
1385                 addr_b = NULL;
1386                 addr_i = NULL;
1387                 store  = NULL;
1388
1389                 /* we should only have 1 user which is a store */
1390                 if (ia32_get_irn_n_edges(irn) == 1) {
1391                         ir_node *succ = get_edge_src_irn(get_irn_out_edge_first(irn));
1392
1393                         if (is_ia32_xStore(succ) || is_ia32_Store(succ)) {
1394                                 store  = succ;
1395                                 addr_b = get_irn_n(store, 0);
1396                                 addr_i = get_irn_n(store, 1);
1397                         }
1398                 }
1399
1400                 if (store == NULL) {
1401                         DBG((dbg, LEVEL_2, "\tno store found, not using dest_mode\n"));
1402                         dest_possible = 0;
1403                 }
1404         }
1405
1406         if (dest_possible) {
1407                 /* normalize nodes, we need the interesting load on the left side */
1408                 if (cand & IA32_AM_CAND_RIGHT) {
1409                         load = get_Proj_pred(right);
1410                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)
1411                                         && node_is_ia32_comm(irn)) {
1412                                 DBG((dbg, LEVEL_2, "\texchanging left/right\n"));
1413                                 exchange_left_right(irn, &left, &right, 3, 2);
1414                                 need_exchange_on_fail ^= 1;
1415                                 if (cand == IA32_AM_CAND_RIGHT)
1416                                         cand = IA32_AM_CAND_LEFT;
1417                         }
1418                 }
1419         }
1420
1421         if (dest_possible) {
1422                 if(cand & IA32_AM_CAND_LEFT && is_Proj(left)) {
1423                         load = get_Proj_pred(left);
1424
1425 #ifndef AGGRESSIVE_AM
1426                         /* we have to be the only user of the load */
1427                         if (get_irn_n_edges(left) > 1) {
1428                                 DBG((dbg, LEVEL_2, "\tmatching load has too may users, not using dest_mode\n"));
1429                                 dest_possible = 0;
1430                         }
1431 #endif
1432                 } else {
1433                         DBG((dbg, LEVEL_2, "\tno matching load found, not using dest_mode"));
1434                         dest_possible = 0;
1435                 }
1436         }
1437
1438         if (dest_possible) {
1439                 /* the store has to use the loads memory or the same memory
1440                  * as the load */
1441                 ir_node *loadmem = get_irn_n(load, 2);
1442                 ir_node *storemem = get_irn_n(store, 3);
1443                 assert(get_irn_mode(loadmem) == mode_M);
1444                 assert(get_irn_mode(storemem) == mode_M);
1445                 /* TODO there could be a sync between store and load... */
1446                 if(storemem != loadmem && (!is_Proj(storemem) || get_Proj_pred(storemem) != load)) {
1447                         DBG((dbg, LEVEL_2, "\tload/store using different memories, not using dest_mode"));
1448                         dest_possible = 0;
1449                 }
1450         }
1451
1452         if (dest_possible) {
1453                 /* Compare Load and Store address */
1454                 if (!load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1455                         DBG((dbg, LEVEL_2, "\taddresses not equal, not using dest_mode"));
1456                         dest_possible = 0;
1457                 }
1458         }
1459
1460         if (dest_possible) {
1461                 ir_mode *lsmode = get_ia32_ls_mode(load);
1462                 if(get_mode_size_bits(lsmode) != 32) {
1463                         dest_possible = 0;
1464                 }
1465         }
1466
1467         if (dest_possible) {
1468                 /* all conditions fullfilled, do the transformation */
1469                 assert(cand & IA32_AM_CAND_LEFT);
1470
1471                 /* set new base, index and attributes */
1472                 set_irn_n(irn, 0, addr_b);
1473                 set_irn_n(irn, 1, addr_i);
1474                 add_ia32_am_offs_int(irn, get_ia32_am_offs_int(load));
1475                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1476                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1477                 set_ia32_op_type(irn, ia32_AddrModeD);
1478                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1479                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1480
1481                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1482                 if (is_ia32_am_sc_sign(load))
1483                         set_ia32_am_sc_sign(irn);
1484
1485                 /* connect to Load memory and disconnect Load */
1486                 if (get_irn_arity(irn) == 5) {
1487                         /* binary AMop */
1488                         set_irn_n(irn, 4, get_irn_n(load, 2));
1489                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1490                 } else {
1491                         /* unary AMop */
1492                         set_irn_n(irn, 3, get_irn_n(load, 2));
1493                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1494                 }
1495
1496                 /* change node mode and out register requirements */
1497                 set_irn_mode(irn, mode_M);
1498                 set_ia32_out_req_all(irn, dest_am_out_reqs);
1499
1500                 /* connect the memory Proj of the Store to the op */
1501                 edges_reroute(store, irn, irg);
1502
1503                 /* clear remat flag */
1504                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1505
1506                 try_remove_from_sched(store);
1507                 try_remove_from_sched(load);
1508                 DBG_OPT_AM_D(load, store, irn);
1509
1510                 DB((dbg, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1511                 need_exchange_on_fail = 0;
1512                 source_possible = 0;
1513         }
1514
1515         if (source_possible) {
1516                 /* normalize ops, we need the load on the right */
1517                 if(cand == IA32_AM_CAND_LEFT) {
1518                         if(node_is_ia32_comm(irn)) {
1519                                 exchange_left_right(irn, &left, &right, 3, 2);
1520                                 need_exchange_on_fail ^= 1;
1521                                 cand = IA32_AM_CAND_RIGHT;
1522                         } else {
1523                                 source_possible = 0;
1524                         }
1525                 }
1526         }
1527
1528         if (source_possible) {
1529                 /* all conditions fullfilled, do transform */
1530                 assert(cand & IA32_AM_CAND_RIGHT);
1531                 load = get_Proj_pred(right);
1532
1533                 if(get_irn_n_edges(load) > 1) {
1534                         source_possible = 0;
1535                 }
1536         }
1537
1538         if (source_possible) {
1539                 ir_mode *ls_mode = get_ia32_ls_mode(load);
1540                 if(get_mode_size_bits(ls_mode) != 32)
1541                         source_possible = 0;
1542
1543         }
1544
1545         if (source_possible) {
1546                 addr_b = get_irn_n(load, 0);
1547                 addr_i = get_irn_n(load, 1);
1548
1549                 /* set new base, index and attributes */
1550                 set_irn_n(irn, 0, addr_b);
1551                 set_irn_n(irn, 1, addr_i);
1552                 add_ia32_am_offs_int(irn, get_ia32_am_offs_int(load));
1553                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1554                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1555                 set_ia32_op_type(irn, ia32_AddrModeS);
1556                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1557                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1558
1559                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1560                 if (is_ia32_am_sc_sign(load))
1561                         set_ia32_am_sc_sign(irn);
1562
1563                 /* clear remat flag */
1564                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1565
1566                 if (is_ia32_use_frame(load)) {
1567                         if(get_ia32_frame_ent(load) == NULL) {
1568                                 set_ia32_need_stackent(irn);
1569                         }
1570                         set_ia32_use_frame(irn);
1571                 }
1572
1573                 /* connect to Load memory and disconnect Load */
1574                 if (get_irn_arity(irn) == 5) {
1575                         /* binary AMop */
1576                         set_irn_n(irn, 3, ia32_get_admissible_noreg(cg, irn, 3));
1577                         set_irn_n(irn, 4, get_irn_n(load, 2));
1578                 } else {
1579                         assert(get_irn_arity(irn) == 4);
1580                         /* unary AMop */
1581                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1582                         set_irn_n(irn, 3, get_irn_n(load, 2));
1583                 }
1584
1585                 DBG_OPT_AM_S(load, irn);
1586
1587                 /* If Load has a memory Proj, connect it to the op */
1588                 mem_proj = ia32_get_proj_for_mode(load, mode_M);
1589                 if (mem_proj != NULL) {
1590                         ir_node *res_proj;
1591                         ir_mode *mode = get_irn_mode(irn);
1592
1593                         res_proj = new_rd_Proj(get_irn_dbg_info(irn), irg,
1594                                                get_nodes_block(irn), new_Unknown(mode_T),
1595                                                                    mode, 0);
1596                         set_irn_mode(irn, mode_T);
1597                         edges_reroute(irn, res_proj, irg);
1598                         set_Proj_pred(res_proj, irn);
1599
1600                         set_Proj_pred(mem_proj, irn);
1601                         set_Proj_proj(mem_proj, 1);
1602
1603                         if(sched_is_scheduled(irn)) {
1604                                 sched_add_after(irn, res_proj);
1605                                 sched_add_after(irn, mem_proj);
1606                         }
1607                 }
1608
1609                 if(get_irn_n_edges(load) == 0) {
1610                         try_remove_from_sched(load);
1611                 }
1612                 need_exchange_on_fail = 0;
1613
1614                 DB((dbg, LEVEL_1, "merged with %+F into source AM\n", load));
1615         }
1616
1617         /* was exchanged but optimize failed: exchange back */
1618         if (need_exchange_on_fail) {
1619                 exchange_left_right(irn, &left, &right, 3, 2);
1620         }
1621 }
1622
1623 /**
1624  * Performs conv and address mode optimization.
1625  */
1626 void ia32_optimize_graph(ia32_code_gen_t *cg) {
1627         /* if we are supposed to do AM or LEA optimization: recalculate edges */
1628         if (! (cg->opt & (IA32_OPT_DOAM | IA32_OPT_LEA))) {
1629                 /* no optimizations at all */
1630                 return;
1631         }
1632
1633         /* beware: we cannot optimize LEA and AM in one run because */
1634         /*         LEA optimization adds new nodes to the irg which */
1635         /*         invalidates the phase data                       */
1636
1637         if (cg->opt & IA32_OPT_LEA) {
1638                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_node, cg);
1639         }
1640
1641         if (cg->dump)
1642                 be_dump(cg->irg, "-lea", dump_ir_block_graph_sched);
1643
1644         /* hack for now, so these don't get created during optimize, because then
1645          * they will be unknown to the heights module
1646          */
1647         ia32_new_NoReg_gp(cg);
1648         ia32_new_NoReg_fp(cg);
1649         ia32_new_NoReg_vfp(cg);
1650
1651         if (cg->opt & IA32_OPT_DOAM) {
1652                 /* we need height information for am optimization */
1653                 heights_t *h = heights_new(cg->irg);
1654                 ia32_am_opt_env_t env;
1655
1656                 env.cg = cg;
1657                 env.h  = h;
1658
1659                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_am, &env);
1660
1661                 heights_free(h);
1662         }
1663 }
1664
1665 void ia32_init_optimize(void)
1666 {
1667         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.optimize");
1668 }