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