- removed old if 0'ed code
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 /*
2  * Copyright (C) 1995-2008 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      Matthias Braun, 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 "irtools.h"
34 #include "firm_types.h"
35 #include "iredges.h"
36 #include "tv.h"
37 #include "irgmod.h"
38 #include "irgwalk.h"
39 #include "height.h"
40 #include "irbitset.h"
41 #include "irprintf.h"
42 #include "error.h"
43
44 #include "../be_t.h"
45 #include "../beabi.h"
46 #include "../benode_t.h"
47 #include "../besched_t.h"
48 #include "../bepeephole.h"
49
50 #include "ia32_new_nodes.h"
51 #include "ia32_optimize.h"
52 #include "bearch_ia32_t.h"
53 #include "gen_ia32_regalloc_if.h"
54 #include "ia32_transform.h"
55 #include "ia32_dbg_stat.h"
56 #include "ia32_util.h"
57 #include "ia32_architecture.h"
58
59 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
60
61 static const arch_env_t *arch_env;
62 static ia32_code_gen_t  *cg;
63
64 /**
65  * Returns non-zero if the given node produces
66  * a zero flag.
67  *
68  * @param node  the node to check
69  * @param pn    if >= 0, the projection number of the used result
70  */
71 static int produces_zero_flag(ir_node *node, int pn)
72 {
73         ir_node                     *count;
74         const ia32_immediate_attr_t *imm_attr;
75
76         if (!is_ia32_irn(node))
77                 return 0;
78
79         if (pn >= 0) {
80                 if (pn != pn_ia32_res)
81                         return 0;
82         }
83
84         switch (get_ia32_irn_opcode(node)) {
85         case iro_ia32_Add:
86         case iro_ia32_Adc:
87         case iro_ia32_And:
88         case iro_ia32_Or:
89         case iro_ia32_Xor:
90         case iro_ia32_Sub:
91         case iro_ia32_Sbb:
92         case iro_ia32_Neg:
93         case iro_ia32_Inc:
94         case iro_ia32_Dec:
95                 return 1;
96
97         case iro_ia32_ShlD:
98         case iro_ia32_ShrD:
99         case iro_ia32_Shl:
100         case iro_ia32_Shr:
101         case iro_ia32_Sar:
102                 assert(n_ia32_ShlD_count == n_ia32_ShrD_count);
103                 assert(n_ia32_Shl_count == n_ia32_Shr_count
104                                 && n_ia32_Shl_count == n_ia32_Sar_count);
105                 if (is_ia32_ShlD(node) || is_ia32_ShrD(node)) {
106                         count = get_irn_n(node, n_ia32_ShlD_count);
107                 } else {
108                         count = get_irn_n(node, n_ia32_Shl_count);
109                 }
110                 /* when shift count is zero the flags are not affected, so we can only
111                  * do this for constants != 0 */
112                 if (!is_ia32_Immediate(count))
113                         return 0;
114
115                 imm_attr = get_ia32_immediate_attr_const(count);
116                 if (imm_attr->symconst != NULL)
117                         return 0;
118                 if ((imm_attr->offset & 0x1f) == 0)
119                         return 0;
120                 return 1;
121
122         default:
123                 break;
124         }
125         return 0;
126 }
127
128 /**
129  * If the given node has not mode_T, creates a mode_T version (with a result Proj).
130  *
131  * @param node  the node to change
132  *
133  * @return the new mode_T node (if the mode was changed) or node itself
134  */
135 static ir_node *turn_into_mode_t(ir_node *node)
136 {
137         ir_node               *block;
138         ir_node               *res_proj;
139         ir_node               *new_node;
140         const arch_register_t *reg;
141
142         if(get_irn_mode(node) == mode_T)
143                 return node;
144
145         assert(get_irn_mode(node) == mode_Iu);
146
147         new_node = exact_copy(node);
148         set_irn_mode(new_node, mode_T);
149
150         block    = get_nodes_block(new_node);
151         res_proj = new_r_Proj(current_ir_graph, block, new_node, mode_Iu,
152                               pn_ia32_res);
153
154         reg = arch_get_irn_register(arch_env, node);
155         arch_set_irn_register(arch_env, res_proj, reg);
156
157         be_peephole_before_exchange(node, res_proj);
158         sched_add_before(node, new_node);
159         sched_remove(node);
160         exchange(node, res_proj);
161         be_peephole_after_exchange(res_proj);
162
163         return new_node;
164 }
165
166 /**
167  * Peephole optimization for Test instructions.
168  * We can remove the Test, if a zero flags was produced which is still
169  * live.
170  */
171 static void peephole_ia32_Test(ir_node *node)
172 {
173         ir_node         *left  = get_irn_n(node, n_ia32_Test_left);
174         ir_node         *right = get_irn_n(node, n_ia32_Test_right);
175         ir_node         *flags_proj;
176         ir_node         *block;
177         ir_mode         *flags_mode;
178         int              pn    = -1;
179         ir_node         *schedpoint;
180         const ir_edge_t *edge;
181
182         assert(n_ia32_Test_left == n_ia32_Test8Bit_left
183                         && n_ia32_Test_right == n_ia32_Test8Bit_right);
184
185         /* we need a test for 0 */
186         if(left != right)
187                 return;
188
189         block = get_nodes_block(node);
190         if(get_nodes_block(left) != block)
191                 return;
192
193         if(is_Proj(left)) {
194                 pn   = get_Proj_proj(left);
195                 left = get_Proj_pred(left);
196         }
197
198         /* happens rarely, but if it does code will panic' */
199         if (is_ia32_Unknown_GP(left))
200                 return;
201
202         /* walk schedule up and abort when we find left or some other node destroys
203            the flags */
204         schedpoint = sched_prev(node);
205         while(schedpoint != left) {
206                 schedpoint = sched_prev(schedpoint);
207                 if(arch_irn_is(arch_env, schedpoint, modify_flags))
208                         return;
209                 if(schedpoint == block)
210                         panic("couldn't find left");
211         }
212
213         /* make sure only Lg/Eq tests are used */
214         foreach_out_edge(node, edge) {
215                 ir_node *user = get_edge_src_irn(edge);
216                 int      pnc  = get_ia32_condcode(user);
217
218                 if(pnc != pn_Cmp_Eq && pnc != pn_Cmp_Lg) {
219                         return;
220                 }
221         }
222
223         if(!produces_zero_flag(left, pn))
224                 return;
225
226         left = turn_into_mode_t(left);
227
228         flags_mode = ia32_reg_classes[CLASS_ia32_flags].mode;
229         flags_proj = new_r_Proj(current_ir_graph, block, left, flags_mode,
230                                 pn_ia32_flags);
231         arch_set_irn_register(arch_env, flags_proj, &ia32_flags_regs[REG_EFLAGS]);
232
233         assert(get_irn_mode(node) != mode_T);
234
235         be_peephole_before_exchange(node, flags_proj);
236         exchange(node, flags_proj);
237         sched_remove(node);
238         be_peephole_after_exchange(flags_proj);
239 }
240
241 /**
242  * AMD Athlon works faster when RET is not destination of
243  * conditional jump or directly preceded by other jump instruction.
244  * Can be avoided by placing a Rep prefix before the return.
245  */
246 static void peephole_ia32_Return(ir_node *node) {
247         ir_node *block, *irn;
248
249         if (!ia32_cg_config.use_pad_return)
250                 return;
251
252         block = get_nodes_block(node);
253
254         if (get_Block_n_cfgpreds(block) == 1) {
255                 ir_node *pred = get_Block_cfgpred(block, 0);
256
257                 if (is_Jmp(pred)) {
258                         /* The block of the return has only one predecessor,
259                            which jumps directly to this block.
260                            This jump will be encoded as a fall through, so we
261                            ignore it here.
262                            However, the predecessor might be empty, so it must be
263                            ensured that empty blocks are gone away ... */
264                         return;
265                 }
266         }
267
268         /* check if this return is the first on the block */
269         sched_foreach_reverse_from(node, irn) {
270                 switch (get_irn_opcode(irn)) {
271                 case beo_Return:
272                         /* the return node itself, ignore */
273                         continue;
274                 case beo_Barrier:
275                         /* ignore the barrier, no code generated */
276                         continue;
277                 case beo_IncSP:
278                         /* arg, IncSP 0 nodes might occur, ignore these */
279                         if (be_get_IncSP_offset(irn) == 0)
280                                 continue;
281                         return;
282                 case iro_Phi:
283                         continue;
284                 default:
285                         return;
286                 }
287         }
288         /* yep, return is the first real instruction in this block */
289 #if 0
290         {
291                 /* add an rep prefix to the return */
292                 ir_node *rep = new_rd_ia32_RepPrefix(get_irn_dbg_info(node), current_ir_graph, block);
293                 keep_alive(rep);
294                 sched_add_before(node, rep);
295         }
296 #else
297         /* ensure, that the 3 byte return is generated */
298         be_Return_set_emit_pop(node, 1);
299 #endif
300 }
301
302 /* only optimize up to 48 stores behind IncSPs */
303 #define MAXPUSH_OPTIMIZE        48
304
305 /**
306  * Tries to create Push's from IncSP, Store combinations.
307  * The Stores are replaced by Push's, the IncSP is modified
308  * (possibly into IncSP 0, but not removed).
309  */
310 static void peephole_IncSP_Store_to_push(ir_node *irn)
311 {
312         int     i, maxslot, inc_ofs;
313         ir_node *node;
314         ir_node *stores[MAXPUSH_OPTIMIZE];
315         ir_node *block = get_nodes_block(irn);
316         ir_graph *irg = cg->irg;
317         ir_node *curr_sp;
318         ir_mode *spmode = get_irn_mode(irn);
319
320         memset(stores, 0, sizeof(stores));
321
322         assert(be_is_IncSP(irn));
323
324         inc_ofs = be_get_IncSP_offset(irn);
325         if (inc_ofs < 4)
326                 return;
327
328         /*
329          * We first walk the schedule after the IncSP node as long as we find
330          * suitable stores that could be transformed to a push.
331          * We save them into the stores array which is sorted by the frame offset/4
332          * attached to the node
333          */
334         maxslot = -1;
335         for (node = sched_next(irn); !sched_is_end(node); node = sched_next(node)) {
336                 ir_node *mem;
337                 int offset;
338                 int storeslot;
339
340                 /* it has to be a Store */
341                 if (!is_ia32_Store(node))
342                         break;
343
344                 /* it has to use our sp value */
345                 if (get_irn_n(node, n_ia32_base) != irn)
346                         continue;
347                 /* Store has to be attached to NoMem */
348                 mem = get_irn_n(node, n_ia32_mem);
349                 if (!is_NoMem(mem))
350                         continue;
351
352                 /* unfortunately we can't support the full AMs possible for push at the
353                  * moment. TODO: fix this */
354                 if (get_ia32_am_scale(node) > 0 || !is_ia32_NoReg_GP(get_irn_n(node, n_ia32_index)))
355                         break;
356
357                 offset = get_ia32_am_offs_int(node);
358                 /* we should NEVER access uninitialized stack BELOW the current SP */
359                 assert(offset >= 0);
360
361                 offset = inc_ofs - 4 - offset;
362
363                 /* storing at half-slots is bad */
364                 if ((offset & 3) != 0)
365                         break;
366
367                 if (offset < 0 || offset >= MAXPUSH_OPTIMIZE * 4)
368                         continue;
369                 storeslot = offset >> 2;
370
371                 /* storing into the same slot twice is bad (and shouldn't happen...) */
372                 if (stores[storeslot] != NULL)
373                         break;
374
375                 stores[storeslot] = node;
376                 if (storeslot > maxslot)
377                         maxslot = storeslot;
378         }
379
380         curr_sp = be_get_IncSP_pred(irn);
381
382         /* walk through the stores and create Pushs for them */
383         for (i = 0; i <= maxslot; ++i) {
384                 const arch_register_t *spreg;
385                 ir_node *push;
386                 ir_node *val, *mem, *mem_proj;
387                 ir_node *store = stores[i];
388                 ir_node *noreg = ia32_new_NoReg_gp(cg);
389
390                 if (store == NULL)
391                         break;
392
393                 val = get_irn_n(store, n_ia32_unary_op);
394                 mem = get_irn_n(store, n_ia32_mem);
395                 spreg = arch_get_irn_register(cg->arch_env, curr_sp);
396
397                 push = new_rd_ia32_Push(get_irn_dbg_info(store), irg, block, noreg, noreg, mem, val, curr_sp);
398
399                 sched_add_before(irn, push);
400
401                 /* create stackpointer Proj */
402                 curr_sp = new_r_Proj(irg, block, push, spmode, pn_ia32_Push_stack);
403                 arch_set_irn_register(cg->arch_env, curr_sp, spreg);
404
405                 /* create memory Proj */
406                 mem_proj = new_r_Proj(irg, block, push, mode_M, pn_ia32_Push_M);
407
408                 /* use the memproj now */
409                 exchange(store, mem_proj);
410
411                 /* we can remove the store now */
412                 sched_remove(store);
413
414                 inc_ofs -= 4;
415         }
416
417         be_set_IncSP_offset(irn, inc_ofs);
418         be_set_IncSP_pred(irn, curr_sp);
419 }
420
421 /**
422  * Find a free GP register if possible, else return NULL.
423  */
424 static const arch_register_t *get_free_gp_reg(void)
425 {
426         int i;
427
428         for(i = 0; i < N_ia32_gp_REGS; ++i) {
429                 const arch_register_t *reg = &ia32_gp_regs[i];
430                 if(arch_register_type_is(reg, ignore))
431                         continue;
432
433                 if(be_peephole_get_value(CLASS_ia32_gp, i) == NULL)
434                         return &ia32_gp_regs[i];
435         }
436
437         return NULL;
438 }
439
440 /**
441  * Creates a Pop instruction before the given schedule point.
442  *
443  * @param dbgi        debug info
444  * @param irg         the graph
445  * @param block       the block
446  * @param stack       the previous stack value
447  * @param schedpoint  the new node is added before this node
448  * @param reg         the register to pop
449  *
450  * @return the new stack value
451  */
452 static ir_node *create_pop(dbg_info *dbgi, ir_graph *irg, ir_node *block,
453                            ir_node *stack, ir_node *schedpoint,
454                            const arch_register_t *reg)
455 {
456         const arch_register_t *esp = &ia32_gp_regs[REG_ESP];
457         ir_node *pop;
458         ir_node *keep;
459         ir_node *val;
460         ir_node *in[1];
461
462         pop   = new_rd_ia32_Pop(dbgi, irg, block, new_NoMem(), stack);
463
464         stack = new_r_Proj(irg, block, pop, mode_Iu, pn_ia32_Pop_stack);
465         arch_set_irn_register(arch_env, stack, esp);
466         val   = new_r_Proj(irg, block, pop, mode_Iu, pn_ia32_Pop_res);
467         arch_set_irn_register(arch_env, val, reg);
468
469         sched_add_before(schedpoint, pop);
470
471         in[0] = val;
472         keep = be_new_Keep(&ia32_reg_classes[CLASS_ia32_gp], irg, block, 1, in);
473         sched_add_before(schedpoint, keep);
474
475         return stack;
476 }
477
478 /**
479  * Creates a Push instruction before the given schedule point.
480  *
481  * @param dbgi        debug info
482  * @param irg         the graph
483  * @param block       the block
484  * @param stack       the previous stack value
485  * @param schedpoint  the new node is added before this node
486  * @param reg         the register to pop
487  *
488  * @return the new stack value
489  */
490 static ir_node *create_push(dbg_info *dbgi, ir_graph *irg, ir_node *block,
491                             ir_node *stack, ir_node *schedpoint,
492                             const arch_register_t *reg)
493 {
494         const arch_register_t *esp = &ia32_gp_regs[REG_ESP];
495         ir_node *noreg, *nomem, *push, *val;
496
497         val  = new_rd_ia32_ProduceVal(NULL, irg, block);
498         arch_set_irn_register(arch_env, val, reg);
499         sched_add_before(schedpoint, val);
500
501         noreg = ia32_new_NoReg_gp(cg);
502         nomem = get_irg_no_mem(irg);
503         push  = new_rd_ia32_Push(dbgi, irg, block, noreg, noreg, nomem, val, stack);
504         sched_add_before(schedpoint, push);
505
506         stack = new_r_Proj(irg, block, push, mode_Iu, pn_ia32_Push_stack);
507         arch_set_irn_register(arch_env, stack, esp);
508
509         return stack;
510 }
511
512 /**
513  * Optimize an IncSp by replacing it with Push/Pop.
514  */
515 static void peephole_be_IncSP(ir_node *node)
516 {
517         const arch_register_t *esp = &ia32_gp_regs[REG_ESP];
518         const arch_register_t *reg;
519         ir_graph              *irg = current_ir_graph;
520         dbg_info              *dbgi;
521         ir_node               *block;
522         ir_node               *stack;
523         int                    offset;
524
525         /* first optimize incsp->incsp combinations */
526         be_peephole_IncSP_IncSP(node);
527
528         /* transform IncSP->Store combinations to Push where possible */
529         peephole_IncSP_Store_to_push(node);
530
531         if (arch_get_irn_register(arch_env, node) != esp)
532                 return;
533
534         /* replace IncSP -4 by Pop freereg when possible */
535         offset = be_get_IncSP_offset(node);
536         if ((offset != -8 || ia32_cg_config.use_add_esp_8) &&
537             (offset != -4 || ia32_cg_config.use_add_esp_4) &&
538             (offset != +4 || ia32_cg_config.use_sub_esp_4) &&
539             (offset != +8 || ia32_cg_config.use_sub_esp_8))
540                 return;
541
542         if (offset < 0) {
543                 /* we need a free register for pop */
544                 reg = get_free_gp_reg();
545                 if (reg == NULL)
546                         return;
547
548                 dbgi  = get_irn_dbg_info(node);
549                 block = get_nodes_block(node);
550                 stack = be_get_IncSP_pred(node);
551
552                 stack = create_pop(dbgi, irg, block, stack, node, reg);
553
554                 if (offset == -8) {
555                         stack = create_pop(dbgi, irg, block, stack, node, reg);
556                 }
557         } else {
558                 dbgi  = get_irn_dbg_info(node);
559                 block = get_nodes_block(node);
560                 stack = be_get_IncSP_pred(node);
561                 reg   = &ia32_gp_regs[REG_EAX];
562
563                 stack = create_push(dbgi, irg, block, stack, node, reg);
564
565                 if (offset == +8) {
566                         stack = create_push(dbgi, irg, block, stack, node, reg);
567                 }
568         }
569
570         be_peephole_before_exchange(node, stack);
571         sched_remove(node);
572         exchange(node, stack);
573         be_peephole_after_exchange(stack);
574 }
575
576 /**
577  * Peephole optimisation for ia32_Const's
578  */
579 static void peephole_ia32_Const(ir_node *node)
580 {
581         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
582         const arch_register_t       *reg;
583         ir_graph                    *irg = current_ir_graph;
584         ir_node                     *block;
585         dbg_info                    *dbgi;
586         ir_node                     *produceval;
587         ir_node                     *xor;
588         ir_node                     *noreg;
589
590         /* try to transform a mov 0, reg to xor reg reg */
591         if (attr->offset != 0 || attr->symconst != NULL)
592                 return;
593         if (ia32_cg_config.use_mov_0)
594                 return;
595         /* xor destroys the flags, so no-one must be using them */
596         if (be_peephole_get_value(CLASS_ia32_flags, REG_EFLAGS) != NULL)
597                 return;
598
599         reg = arch_get_irn_register(arch_env, node);
600         assert(be_peephole_get_reg_value(reg) == NULL);
601
602         /* create xor(produceval, produceval) */
603         block      = get_nodes_block(node);
604         dbgi       = get_irn_dbg_info(node);
605         produceval = new_rd_ia32_ProduceVal(dbgi, irg, block);
606         arch_set_irn_register(arch_env, produceval, reg);
607
608         noreg = ia32_new_NoReg_gp(cg);
609         xor   = new_rd_ia32_Xor(dbgi, irg, block, noreg, noreg, new_NoMem(),
610                                 produceval, produceval);
611         arch_set_irn_register(arch_env, xor, reg);
612
613         sched_add_before(node, produceval);
614         sched_add_before(node, xor);
615
616         be_peephole_before_exchange(node, xor);
617         exchange(node, xor);
618         sched_remove(node);
619         be_peephole_after_exchange(xor);
620 }
621
622 static INLINE int is_noreg(ia32_code_gen_t *cg, const ir_node *node)
623 {
624         return node == cg->noreg_gp;
625 }
626
627 static ir_node *create_immediate_from_int(ia32_code_gen_t *cg, int val)
628 {
629         ir_graph *irg         = current_ir_graph;
630         ir_node  *start_block = get_irg_start_block(irg);
631         ir_node  *immediate   = new_rd_ia32_Immediate(NULL, irg, start_block, NULL,
632                                                       0, val);
633         arch_set_irn_register(cg->arch_env, immediate, &ia32_gp_regs[REG_GP_NOREG]);
634
635         return immediate;
636 }
637
638 static ir_node *create_immediate_from_am(ia32_code_gen_t *cg,
639                                          const ir_node *node)
640 {
641         ir_graph  *irg     = get_irn_irg(node);
642         ir_node   *block   = get_nodes_block(node);
643         int        offset  = get_ia32_am_offs_int(node);
644         int        sc_sign = is_ia32_am_sc_sign(node);
645         ir_entity *entity  = get_ia32_am_sc(node);
646         ir_node   *res;
647
648         res = new_rd_ia32_Immediate(NULL, irg, block, entity, sc_sign, offset);
649         arch_set_irn_register(cg->arch_env, res, &ia32_gp_regs[REG_GP_NOREG]);
650         return res;
651 }
652
653 static int is_am_one(const ir_node *node)
654 {
655         int        offset  = get_ia32_am_offs_int(node);
656         ir_entity *entity  = get_ia32_am_sc(node);
657
658         return offset == 1 && entity == NULL;
659 }
660
661 static int is_am_minus_one(const ir_node *node)
662 {
663         int        offset  = get_ia32_am_offs_int(node);
664         ir_entity *entity  = get_ia32_am_sc(node);
665
666         return offset == -1 && entity == NULL;
667 }
668
669 /**
670  * Transforms a LEA into an Add or SHL if possible.
671  */
672 static void peephole_ia32_Lea(ir_node *node)
673 {
674         const arch_env_t      *arch_env = cg->arch_env;
675         ir_graph              *irg      = current_ir_graph;
676         ir_node               *base;
677         ir_node               *index;
678         const arch_register_t *base_reg;
679         const arch_register_t *index_reg;
680         const arch_register_t *out_reg;
681         int                    scale;
682         int                    has_immediates;
683         ir_node               *op1;
684         ir_node               *op2;
685         dbg_info              *dbgi;
686         ir_node               *block;
687         ir_node               *res;
688         ir_node               *noreg;
689         ir_node               *nomem;
690
691         assert(is_ia32_Lea(node));
692
693         /* we can only do this if are allowed to globber the flags */
694         if(be_peephole_get_value(CLASS_ia32_flags, REG_EFLAGS) != NULL)
695                 return;
696
697         base  = get_irn_n(node, n_ia32_Lea_base);
698         index = get_irn_n(node, n_ia32_Lea_index);
699
700         if(is_noreg(cg, base)) {
701                 base     = NULL;
702                 base_reg = NULL;
703         } else {
704                 base_reg = arch_get_irn_register(arch_env, base);
705         }
706         if(is_noreg(cg, index)) {
707                 index     = NULL;
708                 index_reg = NULL;
709         } else {
710                 index_reg = arch_get_irn_register(arch_env, index);
711         }
712
713         if(base == NULL && index == NULL) {
714                 /* we shouldn't construct these in the first place... */
715 #ifdef DEBUG_libfirm
716                 ir_fprintf(stderr, "Optimisation warning: found immediate only lea\n");
717 #endif
718                 return;
719         }
720
721         out_reg = arch_get_irn_register(arch_env, node);
722         scale   = get_ia32_am_scale(node);
723         assert(!is_ia32_need_stackent(node) || get_ia32_frame_ent(node) != NULL);
724         /* check if we have immediates values (frame entities should already be
725          * expressed in the offsets) */
726         if(get_ia32_am_offs_int(node) != 0 || get_ia32_am_sc(node) != NULL) {
727                 has_immediates = 1;
728         } else {
729                 has_immediates = 0;
730         }
731
732         /* we can transform leas where the out register is the same as either the
733          * base or index register back to an Add or Shl */
734         if(out_reg == base_reg) {
735                 if(index == NULL) {
736 #ifdef DEBUG_libfirm
737                         if(!has_immediates) {
738                                 ir_fprintf(stderr, "Optimisation warning: found lea which is "
739                                            "just a copy\n");
740                         }
741 #endif
742                         op1 = base;
743                         goto make_add_immediate;
744                 }
745                 if(scale == 0 && !has_immediates) {
746                         op1 = base;
747                         op2 = index;
748                         goto make_add;
749                 }
750                 /* can't create an add */
751                 return;
752         } else if(out_reg == index_reg) {
753                 if(base == NULL) {
754                         if(has_immediates && scale == 0) {
755                                 op1 = index;
756                                 goto make_add_immediate;
757                         } else if(!has_immediates && scale > 0) {
758                                 op1 = index;
759                                 op2 = create_immediate_from_int(cg, scale);
760                                 goto make_shl;
761                         } else if(!has_immediates) {
762 #ifdef DEBUG_libfirm
763                                 ir_fprintf(stderr, "Optimisation warning: found lea which is "
764                                            "just a copy\n");
765 #endif
766                         }
767                 } else if(scale == 0 && !has_immediates) {
768                         op1 = index;
769                         op2 = base;
770                         goto make_add;
771                 }
772                 /* can't create an add */
773                 return;
774         } else {
775                 /* can't create an add */
776                 return;
777         }
778
779 make_add_immediate:
780         if(ia32_cg_config.use_incdec) {
781                 if(is_am_one(node)) {
782                         dbgi  = get_irn_dbg_info(node);
783                         block = get_nodes_block(node);
784                         res   = new_rd_ia32_Inc(dbgi, irg, block, op1);
785                         arch_set_irn_register(arch_env, res, out_reg);
786                         goto exchange;
787                 }
788                 if(is_am_minus_one(node)) {
789                         dbgi  = get_irn_dbg_info(node);
790                         block = get_nodes_block(node);
791                         res   = new_rd_ia32_Dec(dbgi, irg, block, op1);
792                         arch_set_irn_register(arch_env, res, out_reg);
793                         goto exchange;
794                 }
795         }
796         op2 = create_immediate_from_am(cg, node);
797
798 make_add:
799         dbgi  = get_irn_dbg_info(node);
800         block = get_nodes_block(node);
801         noreg = ia32_new_NoReg_gp(cg);
802         nomem = new_NoMem();
803         res   = new_rd_ia32_Add(dbgi, irg, block, noreg, noreg, nomem, op1, op2);
804         arch_set_irn_register(arch_env, res, out_reg);
805         set_ia32_commutative(res);
806         goto exchange;
807
808 make_shl:
809         dbgi  = get_irn_dbg_info(node);
810         block = get_nodes_block(node);
811         noreg = ia32_new_NoReg_gp(cg);
812         nomem = new_NoMem();
813         res   = new_rd_ia32_Shl(dbgi, irg, block, op1, op2);
814         arch_set_irn_register(arch_env, res, out_reg);
815         goto exchange;
816
817 exchange:
818         SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, node));
819
820         /* add new ADD/SHL to schedule */
821         DBG_OPT_LEA2ADD(node, res);
822
823         /* exchange the Add and the LEA */
824         be_peephole_before_exchange(node, res);
825         sched_add_before(node, res);
826         sched_remove(node);
827         exchange(node, res);
828         be_peephole_after_exchange(res);
829 }
830
831 /**
832  * Split a Imul mem, imm into a Load mem and Imul reg, imm if possible.
833  */
834 static void peephole_ia32_Imul_split(ir_node *imul) {
835         const ir_node         *right = get_irn_n(imul, n_ia32_IMul_right);
836         const arch_register_t *reg;
837         ir_node               *load, *block, *base, *index, *mem, *res, *noreg;
838         dbg_info              *dbgi;
839         ir_graph              *irg;
840
841         if (! is_ia32_Immediate(right) || get_ia32_op_type(imul) != ia32_AddrModeS) {
842                 /* no memory, imm form ignore */
843                 return;
844         }
845         /* we need a free register */
846         reg = get_free_gp_reg();
847         if (reg == NULL)
848                 return;
849
850         /* fine, we can rebuild it */
851         dbgi  = get_irn_dbg_info(imul);
852         block = get_nodes_block(imul);
853         irg   = current_ir_graph;
854         base  = get_irn_n(imul, n_ia32_IMul_base);
855         index = get_irn_n(imul, n_ia32_IMul_index);
856         mem   = get_irn_n(imul, n_ia32_IMul_mem);
857         load = new_rd_ia32_Load(dbgi, irg, block, base, index, mem);
858
859         /* copy all attributes */
860         set_irn_pinned(load, get_irn_pinned(imul));
861         set_ia32_op_type(load, ia32_AddrModeS);
862         set_ia32_ls_mode(load, get_ia32_ls_mode(imul));
863
864         set_ia32_am_scale(load, get_ia32_am_scale(imul));
865         set_ia32_am_sc(load, get_ia32_am_sc(imul));
866         set_ia32_am_offs_int(load, get_ia32_am_offs_int(imul));
867         if (is_ia32_am_sc_sign(imul))
868                 set_ia32_am_sc_sign(load);
869         if (is_ia32_use_frame(imul))
870                 set_ia32_use_frame(load);
871         set_ia32_frame_ent(load, get_ia32_frame_ent(imul));
872
873         sched_add_before(imul, load);
874
875         mem = new_rd_Proj(dbgi, irg, block, load, mode_M, pn_ia32_Load_M);
876         res = new_rd_Proj(dbgi, irg, block, load, mode_Iu, pn_ia32_Load_res);
877
878         arch_set_irn_register(arch_env, res, reg);
879         be_peephole_after_exchange(res);
880
881         set_irn_n(imul, n_ia32_IMul_mem, mem);
882         noreg = get_irn_n(imul, n_ia32_IMul_left);
883         set_irn_n(imul, n_ia32_IMul_left, res);
884         set_ia32_op_type(imul, ia32_Normal);
885 }
886
887 /**
888  * Replace xorps r,r and xorpd r,r by pxor r,r
889  */
890 static void peephole_ia32_xZero(ir_node *xor) {
891         set_irn_op(xor, op_ia32_xPzero);
892 }
893
894 /**
895  * Register a peephole optimisation function.
896  */
897 static void register_peephole_optimisation(ir_op *op, peephole_opt_func func) {
898         assert(op->ops.generic == NULL);
899         op->ops.generic = (op_func)func;
900 }
901
902 /* Perform peephole-optimizations. */
903 void ia32_peephole_optimization(ia32_code_gen_t *new_cg)
904 {
905         cg       = new_cg;
906         arch_env = cg->arch_env;
907
908         /* register peephole optimisations */
909         clear_irp_opcodes_generic_func();
910         register_peephole_optimisation(op_ia32_Const, peephole_ia32_Const);
911         register_peephole_optimisation(op_be_IncSP, peephole_be_IncSP);
912         register_peephole_optimisation(op_ia32_Lea, peephole_ia32_Lea);
913         register_peephole_optimisation(op_ia32_Test, peephole_ia32_Test);
914         register_peephole_optimisation(op_ia32_Test8Bit, peephole_ia32_Test);
915         register_peephole_optimisation(op_be_Return, peephole_ia32_Return);
916         if (! ia32_cg_config.use_imul_mem_imm32)
917                 register_peephole_optimisation(op_ia32_IMul, peephole_ia32_Imul_split);
918         if (ia32_cg_config.use_pxor)
919                 register_peephole_optimisation(op_ia32_xZero, peephole_ia32_xZero);
920
921         be_peephole_opt(cg->birg);
922 }
923
924 /**
925  * Removes node from schedule if it is not used anymore. If irn is a mode_T node
926  * all it's Projs are removed as well.
927  * @param irn  The irn to be removed from schedule
928  */
929 static INLINE void try_kill(ir_node *node)
930 {
931         if(get_irn_mode(node) == mode_T) {
932                 const ir_edge_t *edge, *next;
933                 foreach_out_edge_safe(node, edge, next) {
934                         ir_node *proj = get_edge_src_irn(edge);
935                         try_kill(proj);
936                 }
937         }
938
939         if(get_irn_n_edges(node) != 0)
940                 return;
941
942         if (sched_is_scheduled(node)) {
943                 sched_remove(node);
944         }
945
946         be_kill_node(node);
947 }
948
949 static void optimize_conv_store(ir_node *node)
950 {
951         ir_node *pred;
952         ir_node *pred_proj;
953         ir_mode *conv_mode;
954         ir_mode *store_mode;
955
956         if(!is_ia32_Store(node) && !is_ia32_Store8Bit(node))
957                 return;
958
959         assert(n_ia32_Store_val == n_ia32_Store8Bit_val);
960         pred_proj = get_irn_n(node, n_ia32_Store_val);
961         if(is_Proj(pred_proj)) {
962                 pred = get_Proj_pred(pred_proj);
963         } else {
964                 pred = pred_proj;
965         }
966         if(!is_ia32_Conv_I2I(pred) && !is_ia32_Conv_I2I8Bit(pred))
967                 return;
968         if(get_ia32_op_type(pred) != ia32_Normal)
969                 return;
970
971         /* the store only stores the lower bits, so we only need the conv
972          * it it shrinks the mode */
973         conv_mode  = get_ia32_ls_mode(pred);
974         store_mode = get_ia32_ls_mode(node);
975         if(get_mode_size_bits(conv_mode) < get_mode_size_bits(store_mode))
976                 return;
977
978         set_irn_n(node, n_ia32_Store_val, get_irn_n(pred, n_ia32_Conv_I2I_val));
979         if(get_irn_n_edges(pred_proj) == 0) {
980                 be_kill_node(pred_proj);
981                 if(pred != pred_proj)
982                         be_kill_node(pred);
983         }
984 }
985
986 static void optimize_load_conv(ir_node *node)
987 {
988         ir_node *pred, *predpred;
989         ir_mode *load_mode;
990         ir_mode *conv_mode;
991
992         if (!is_ia32_Conv_I2I(node) && !is_ia32_Conv_I2I8Bit(node))
993                 return;
994
995         assert(n_ia32_Conv_I2I_val == n_ia32_Conv_I2I8Bit_val);
996         pred = get_irn_n(node, n_ia32_Conv_I2I_val);
997         if(!is_Proj(pred))
998                 return;
999
1000         predpred = get_Proj_pred(pred);
1001         if(!is_ia32_Load(predpred))
1002                 return;
1003
1004         /* the load is sign extending the upper bits, so we only need the conv
1005          * if it shrinks the mode */
1006         load_mode = get_ia32_ls_mode(predpred);
1007         conv_mode = get_ia32_ls_mode(node);
1008         if(get_mode_size_bits(conv_mode) < get_mode_size_bits(load_mode))
1009                 return;
1010
1011         if(get_mode_sign(conv_mode) != get_mode_sign(load_mode)) {
1012                 /* change the load if it has only 1 user */
1013                 if(get_irn_n_edges(pred) == 1) {
1014                         ir_mode *newmode;
1015                         if(get_mode_sign(conv_mode)) {
1016                                 newmode = find_signed_mode(load_mode);
1017                         } else {
1018                                 newmode = find_unsigned_mode(load_mode);
1019                         }
1020                         assert(newmode != NULL);
1021                         set_ia32_ls_mode(predpred, newmode);
1022                 } else {
1023                         /* otherwise we have to keep the conv */
1024                         return;
1025                 }
1026         }
1027
1028         /* kill the conv */
1029         exchange(node, pred);
1030 }
1031
1032 static void optimize_conv_conv(ir_node *node)
1033 {
1034         ir_node *pred_proj, *pred, *result_conv;
1035         ir_mode *pred_mode, *conv_mode;
1036         int      conv_mode_bits;
1037         int      pred_mode_bits;
1038
1039         if (!is_ia32_Conv_I2I(node) && !is_ia32_Conv_I2I8Bit(node))
1040                 return;
1041
1042         assert(n_ia32_Conv_I2I_val == n_ia32_Conv_I2I8Bit_val);
1043         pred_proj = get_irn_n(node, n_ia32_Conv_I2I_val);
1044         if(is_Proj(pred_proj))
1045                 pred = get_Proj_pred(pred_proj);
1046         else
1047                 pred = pred_proj;
1048
1049         if(!is_ia32_Conv_I2I(pred) && !is_ia32_Conv_I2I8Bit(pred))
1050                 return;
1051
1052         /* we know that after a conv, the upper bits are sign extended
1053          * so we only need the 2nd conv if it shrinks the mode */
1054         conv_mode      = get_ia32_ls_mode(node);
1055         conv_mode_bits = get_mode_size_bits(conv_mode);
1056         pred_mode      = get_ia32_ls_mode(pred);
1057         pred_mode_bits = get_mode_size_bits(pred_mode);
1058
1059         if(conv_mode_bits == pred_mode_bits
1060                         && get_mode_sign(conv_mode) == get_mode_sign(pred_mode)) {
1061                 result_conv = pred_proj;
1062         } else if(conv_mode_bits <= pred_mode_bits) {
1063                 /* if 2nd conv is smaller then first conv, then we can always take the
1064                  * 2nd conv */
1065                 if(get_irn_n_edges(pred_proj) == 1) {
1066                         result_conv = pred_proj;
1067                         set_ia32_ls_mode(pred, conv_mode);
1068
1069                         /* Argh:We must change the opcode to 8bit AND copy the register constraints */
1070                         if (get_mode_size_bits(conv_mode) == 8) {
1071                                 set_irn_op(pred, op_ia32_Conv_I2I8Bit);
1072                                 set_ia32_in_req_all(pred, get_ia32_in_req_all(node));
1073                         }
1074                 } else {
1075                         /* we don't want to end up with 2 loads, so we better do nothing */
1076                         if(get_irn_mode(pred) == mode_T) {
1077                                 return;
1078                         }
1079
1080                         result_conv = exact_copy(pred);
1081                         set_ia32_ls_mode(result_conv, conv_mode);
1082
1083                         /* Argh:We must change the opcode to 8bit AND copy the register constraints */
1084                         if (get_mode_size_bits(conv_mode) == 8) {
1085                                 set_irn_op(result_conv, op_ia32_Conv_I2I8Bit);
1086                                 set_ia32_in_req_all(result_conv, get_ia32_in_req_all(node));
1087                         }
1088                 }
1089         } else {
1090                 /* if both convs have the same sign, then we can take the smaller one */
1091                 if(get_mode_sign(conv_mode) == get_mode_sign(pred_mode)) {
1092                         result_conv = pred_proj;
1093                 } else {
1094                         /* no optimisation possible if smaller conv is sign-extend */
1095                         if(mode_is_signed(pred_mode)) {
1096                                 return;
1097                         }
1098                         /* we can take the smaller conv if it is unsigned */
1099                         result_conv = pred_proj;
1100                 }
1101         }
1102
1103         /* kill the conv */
1104         exchange(node, result_conv);
1105
1106         if(get_irn_n_edges(pred_proj) == 0) {
1107                 be_kill_node(pred_proj);
1108                 if(pred != pred_proj)
1109                         be_kill_node(pred);
1110         }
1111         optimize_conv_conv(result_conv);
1112 }
1113
1114 static void optimize_node(ir_node *node, void *env)
1115 {
1116         (void) env;
1117
1118         optimize_load_conv(node);
1119         optimize_conv_store(node);
1120         optimize_conv_conv(node);
1121 }
1122
1123 /**
1124  * Performs conv and address mode optimization.
1125  */
1126 void ia32_optimize_graph(ia32_code_gen_t *cg)
1127 {
1128         irg_walk_blkwise_graph(cg->irg, NULL, optimize_node, cg);
1129
1130         if (cg->dump)
1131                 be_dump(cg->irg, "-opt", dump_ir_block_graph_sched);
1132 }
1133
1134 void ia32_init_optimize(void)
1135 {
1136         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.optimize");
1137 }