new enum for convenience: easier to guess
[libfirm] / ir / ir / iropt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ir/iropt.c
4  * Purpose:     iropt --- optimizations intertwined with IR construction.
5  * Author:      Christian Schaefer
6  * Modified by: Goetz Lindenmaier
7  * Created:
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1998-2005 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #ifdef HAVE_ALLOCA_H
18 #include <alloca.h>
19 #endif
20 #ifdef HAVE_MALLOC_H
21 #include <malloc.h>
22 #endif
23 #ifdef HAVE_STRING_H
24 #include <string.h>
25 #endif
26
27 # include "irnode_t.h"
28 # include "irgraph_t.h"
29 # include "iredges_t.h"
30 # include "irmode_t.h"
31 # include "iropt_t.h"
32 # include "ircons_t.h"
33 # include "irgmod.h"
34 # include "irvrfy.h"
35 # include "tv_t.h"
36 # include "dbginfo_t.h"
37 # include "iropt_dbg.h"
38 # include "irflag_t.h"
39 # include "irhooks.h"
40 # include "irarch.h"
41 # include "hashptr.h"
42 # include "archop.h"
43 # include "opt_polymorphy.h"
44
45 /* Make types visible to allow most efficient access */
46 # include "entity_t.h"
47
48 /**
49  * Trivial INLINEable routine for copy propagation.
50  * Does follow Ids, needed to optimize INLINEd code.
51  */
52 static INLINE ir_node *
53 follow_Id (ir_node *n)
54 {
55   while (get_irn_op (n) == op_Id) n = get_Id_pred (n);
56   return n;
57 }
58
59 /**
60  * return the value of a Constant
61  */
62 static tarval *computed_value_Const(ir_node *n)
63 {
64   return get_Const_tarval(n);
65 }
66
67 /**
68  * return the value of a 'sizeof' SymConst
69  */
70 static tarval *computed_value_SymConst(ir_node *n)
71 {
72   if ((get_SymConst_kind(n) == symconst_size) &&
73       (get_type_state(get_SymConst_type(n))) == layout_fixed)
74     return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(n)), get_irn_mode(n));
75   return tarval_bad;
76 }
77
78 /**
79  * return the value of an Add
80  */
81 static tarval *computed_value_Add(ir_node *n)
82 {
83   ir_node *a = get_Add_left(n);
84   ir_node *b = get_Add_right(n);
85
86   tarval *ta = value_of(a);
87   tarval *tb = value_of(b);
88
89   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b)))
90     return tarval_add(ta, tb);
91
92   return tarval_bad;
93 }
94
95 /**
96  * return the value of a Sub
97  * Special case: a - a
98  */
99 static tarval *computed_value_Sub(ir_node *n)
100 {
101   ir_node *a = get_Sub_left(n);
102   ir_node *b = get_Sub_right(n);
103   tarval *ta;
104   tarval *tb;
105
106   /* a - a */
107   if (a == b && !is_Bad(a))
108     return get_mode_null(get_irn_mode(n));
109
110   ta = value_of(a);
111   tb = value_of(b);
112
113   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b)))
114     return tarval_sub(ta, tb);
115
116   return tarval_bad;
117 }
118
119 /**
120  * return the value of an unary Minus
121  */
122 static tarval *computed_value_Minus(ir_node *n)
123 {
124   ir_node *a = get_Minus_op(n);
125   tarval *ta = value_of(a);
126
127   if ((ta != tarval_bad) && mode_is_signed(get_irn_mode(a)))
128     return tarval_neg(ta);
129
130   return tarval_bad;
131 }
132
133 /**
134  * return the value of a Mul
135  */
136 static tarval *computed_value_Mul(ir_node *n)
137 {
138   ir_node *a = get_Mul_left(n);
139   ir_node *b = get_Mul_right(n);
140
141   tarval *ta = value_of(a);
142   tarval *tb = value_of(b);
143
144   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b))) {
145     return tarval_mul(ta, tb);
146   } else {
147     /* a*0 = 0 or 0*b = 0:
148        calls computed_value recursive and returns the 0 with proper
149        mode. */
150     if ((ta != tarval_bad) && (ta == get_mode_null(get_tarval_mode(ta))))
151       return ta;
152     if ((tb != tarval_bad) && (tb == get_mode_null(get_tarval_mode(tb))))
153       return tb;
154   }
155   return tarval_bad;
156 }
157
158 /**
159  * return the value of a floating point Quot
160  */
161 static tarval *computed_value_Quot(ir_node *n)
162 {
163   ir_node *a = get_Quot_left(n);
164   ir_node *b = get_Quot_right(n);
165
166   tarval *ta = value_of(a);
167   tarval *tb = value_of(b);
168
169   /* This was missing in original implementation. Why? */
170   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b))) {
171     if (tb != get_mode_null(get_tarval_mode(tb)))   /* div by zero: return tarval_bad */
172       return tarval_quo(ta, tb);
173   }
174   return tarval_bad;
175 }
176
177 /**
178  * calculate the value of an integer Div of two nodes
179  * Special case: 0 / b
180  */
181 static tarval *do_computed_value_Div(ir_node *a, ir_node *b)
182 {
183   tarval *ta = value_of(a);
184   tarval *tb = value_of(b);
185
186   /* Compute c1 / c2 or 0 / a, a != 0 */
187   if (ta != tarval_bad) {
188     if ((tb != tarval_bad) && (tb != get_mode_null(get_irn_mode(b))))   /* div by zero: return tarval_bad */
189       return tarval_div(ta, tb);
190     else if (ta == get_mode_null(get_tarval_mode(ta)))  /* 0 / b == 0 */
191       return ta;
192   }
193   return tarval_bad;
194 }
195
196 /**
197  * return the value of an integer Div
198  */
199 static tarval *computed_value_Div(ir_node *n)
200 {
201   return do_computed_value_Div(get_Div_left(n), get_Div_right(n));
202 }
203
204 /**
205  * calculate the value of an integer Mod of two nodes
206  * Special case: a % 1
207  */
208 static tarval *do_computed_value_Mod(ir_node *a, ir_node *b)
209 {
210   tarval *ta = value_of(a);
211   tarval *tb = value_of(b);
212
213   /* Compute c1 % c2 or a % 1 */
214   if (tb != tarval_bad) {
215     if ((ta != tarval_bad) && (tb != get_mode_null(get_tarval_mode(tb))))   /* div by zero: return tarval_bad */
216       return tarval_mod(ta, tb);
217     else if (tb == get_mode_one(get_tarval_mode(tb)))    /* x mod 1 == 0 */
218       return get_mode_null(get_irn_mode(a));
219   }
220
221   return tarval_bad;
222 }
223
224 /**
225  * return the value of an integer Mod
226  */
227 static tarval *computed_value_Mod(ir_node *n)
228 {
229   return do_computed_value_Mod(get_Mod_left(n), get_Mod_right(n));
230 }
231
232 /**
233  * return the value of an Abs
234  */
235 static tarval *computed_value_Abs(ir_node *n)
236 {
237   ir_node *a = get_Abs_op(n);
238   tarval *ta = value_of(a);
239
240   if (ta != tarval_bad)
241     return tarval_abs(ta);
242
243   return tarval_bad;
244 }
245
246 /**
247  * return the value of an And
248  * Special case: a & 0, 0 & b
249  */
250 static tarval *computed_value_And(ir_node *n)
251 {
252   ir_node *a = get_And_left(n);
253   ir_node *b = get_And_right(n);
254
255   tarval *ta = value_of(a);
256   tarval *tb = value_of(b);
257
258   if ((ta != tarval_bad) && (tb != tarval_bad)) {
259     return tarval_and (ta, tb);
260   } else {
261     tarval *v;
262
263     if (   (classify_tarval ((v = ta)) == TV_CLASSIFY_NULL)
264         || (classify_tarval ((v = tb)) == TV_CLASSIFY_NULL)) {
265       return v;
266     }
267   }
268   return tarval_bad;
269 }
270
271 /**
272  * return the value of an Or
273  * Special case: a | 1...1, 1...1 | b
274  */
275 static tarval *computed_value_Or(ir_node *n)
276 {
277   ir_node *a = get_Or_left(n);
278   ir_node *b = get_Or_right(n);
279
280   tarval *ta = value_of(a);
281   tarval *tb = value_of(b);
282
283   if ((ta != tarval_bad) && (tb != tarval_bad)) {
284     return tarval_or (ta, tb);
285   } else {
286     tarval *v;
287     if (   (classify_tarval ((v = ta)) == TV_CLASSIFY_ALL_ONE)
288         || (classify_tarval ((v = tb)) == TV_CLASSIFY_ALL_ONE)) {
289       return v;
290     }
291   }
292   return tarval_bad;
293 }
294
295 /**
296  * return the value of an Eor
297  */
298 static tarval *computed_value_Eor(ir_node *n)
299 {
300   ir_node *a = get_Eor_left(n);
301   ir_node *b = get_Eor_right(n);
302
303   tarval *ta, *tb;
304
305   if (a == b)
306     return get_mode_null(get_irn_mode(n));
307
308   ta = value_of(a);
309   tb = value_of(b);
310
311   if ((ta != tarval_bad) && (tb != tarval_bad)) {
312     return tarval_eor (ta, tb);
313   }
314   return tarval_bad;
315 }
316
317 /**
318  * return the value of a Not
319  */
320 static tarval *computed_value_Not(ir_node *n)
321 {
322   ir_node *a = get_Not_op(n);
323   tarval *ta = value_of(a);
324
325   if (ta != tarval_bad)
326     return tarval_not(ta);
327
328   return tarval_bad;
329 }
330
331 /**
332  * return the value of a Shl
333  */
334 static tarval *computed_value_Shl(ir_node *n)
335 {
336   ir_node *a = get_Shl_left(n);
337   ir_node *b = get_Shl_right(n);
338
339   tarval *ta = value_of(a);
340   tarval *tb = value_of(b);
341
342   if ((ta != tarval_bad) && (tb != tarval_bad)) {
343     return tarval_shl (ta, tb);
344   }
345   return tarval_bad;
346 }
347
348 /**
349  * return the value of a Shr
350  */
351 static tarval *computed_value_Shr(ir_node *n)
352 {
353   ir_node *a = get_Shr_left(n);
354   ir_node *b = get_Shr_right(n);
355
356   tarval *ta = value_of(a);
357   tarval *tb = value_of(b);
358
359   if ((ta != tarval_bad) && (tb != tarval_bad)) {
360     return tarval_shr (ta, tb);
361   }
362   return tarval_bad;
363 }
364
365 /**
366  * return the value of a Shrs
367  */
368 static tarval *computed_value_Shrs(ir_node *n)
369 {
370   ir_node *a = get_Shrs_left(n);
371   ir_node *b = get_Shrs_right(n);
372
373   tarval *ta = value_of(a);
374   tarval *tb = value_of(b);
375
376   if ((ta != tarval_bad) && (tb != tarval_bad)) {
377     return tarval_shrs (ta, tb);
378   }
379   return tarval_bad;
380 }
381
382 /**
383  * return the value of a Rot
384  */
385 static tarval *computed_value_Rot(ir_node *n)
386 {
387   ir_node *a = get_Rot_left(n);
388   ir_node *b = get_Rot_right(n);
389
390   tarval *ta = value_of(a);
391   tarval *tb = value_of(b);
392
393   if ((ta != tarval_bad) && (tb != tarval_bad)) {
394     return tarval_rot (ta, tb);
395   }
396   return tarval_bad;
397 }
398
399 /**
400  * return the value of a Conv
401  */
402 static tarval *computed_value_Conv(ir_node *n)
403 {
404   ir_node *a = get_Conv_op(n);
405   tarval *ta = value_of(a);
406
407   if (ta != tarval_bad)
408     return tarval_convert_to(ta, get_irn_mode(n));
409
410   return tarval_bad;
411 }
412
413 /**
414  * return the value of a Proj(Cmp)
415  *
416  * This performs a first step of unreachable code elimination.
417  * Proj can not be computed, but folding a Cmp above the Proj here is
418  * not as wasteful as folding a Cmp into a Tuple of 16 Consts of which
419  * only 1 is used.
420  * There are several case where we can evaluate a Cmp node, see later.
421  */
422 static tarval *computed_value_Proj_Cmp(ir_node *n)
423 {
424   ir_node *a   = get_Proj_pred(n);
425   ir_node *aa  = get_Cmp_left(a);
426   ir_node *ab  = get_Cmp_right(a);
427   long proj_nr = get_Proj_proj(n);
428
429   /*
430    * BEWARE: a == a is NOT always True for floating Point values, as
431    * NaN != NaN is defined, so we must check this here.
432    */
433   if (aa == ab && (
434       !mode_is_float(get_irn_mode(aa)) || proj_nr == pn_Cmp_Lt ||  proj_nr == pn_Cmp_Gt)
435       ) { /* 1.: */
436
437     /* This is a trick with the bits used for encoding the Cmp
438        Proj numbers, the following statement is not the same:
439     return new_tarval_from_long (proj_nr == pn_Cmp_Eq, mode_b) */
440     return new_tarval_from_long (proj_nr & pn_Cmp_Eq, mode_b);
441   }
442   else {
443     tarval *taa = value_of(aa);
444     tarval *tab = value_of(ab);
445     ir_mode *mode = get_irn_mode(aa);
446
447     /*
448      * The predecessors of Cmp are target values.  We can evaluate
449      * the Cmp.
450      */
451     if ((taa != tarval_bad) && (tab != tarval_bad)) {
452       /* strange checks... */
453       pn_Cmp flags = tarval_cmp(taa, tab);
454       if (flags != pn_Cmp_False) {
455         return new_tarval_from_long (proj_nr & flags, mode_b);
456       }
457     }
458     /* for integer values, we can check against MIN/MAX */
459     else if (mode_is_int(mode)) {
460       /* MIN <=/> x.  This results in true/false. */
461       if (taa == get_mode_min(mode)) {
462         /* a compare with the MIN value */
463         if (proj_nr == pn_Cmp_Le)
464           return get_tarval_b_true();
465         else if (proj_nr == pn_Cmp_Gt)
466           return get_tarval_b_false();
467       }
468       /* x >=/< MIN.  This results in true/false. */
469       else
470       if (tab == get_mode_min(mode)) {
471         /* a compare with the MIN value */
472         if (proj_nr == pn_Cmp_Ge)
473           return get_tarval_b_true();
474         else if (proj_nr == pn_Cmp_Lt)
475           return get_tarval_b_false();
476       }
477       /* MAX >=/< x.  This results in true/false. */
478       else if (taa == get_mode_max(mode)) {
479         if (proj_nr == pn_Cmp_Ge)
480           return get_tarval_b_true();
481         else if (proj_nr == pn_Cmp_Lt)
482           return get_tarval_b_false();
483       }
484       /* x <=/> MAX.  This results in true/false. */
485       else if (tab == get_mode_max(mode)) {
486         if (proj_nr == pn_Cmp_Le)
487           return get_tarval_b_true();
488         else if (proj_nr == pn_Cmp_Gt)
489           return get_tarval_b_false();
490       }
491     }
492     /*
493      * The predecessors are Allocs or (void*)(0) constants.  Allocs never
494      * return NULL, they raise an exception.   Therefore we can predict
495      * the Cmp result.
496      */
497     else {
498       ir_node *aaa = skip_Id(skip_Proj(aa));
499       ir_node *aba = skip_Id(skip_Proj(ab));
500
501       if (   (   (/* aa is ProjP and aaa is Alloc */
502                      (get_irn_op(aa) == op_Proj)
503                   && (mode_is_reference(get_irn_mode(aa)))
504                   && (get_irn_op(aaa) == op_Alloc))
505               && (   (/* ab is NULL */
506                          (get_irn_op(ab) == op_Const)
507                       && (mode_is_reference(get_irn_mode(ab)))
508                       && (get_Const_tarval(ab) == get_mode_null(get_irn_mode(ab))))
509                   || (/* ab is other Alloc */
510                          (get_irn_op(ab) == op_Proj)
511                       && (mode_is_reference(get_irn_mode(ab)))
512                       && (get_irn_op(aba) == op_Alloc)
513                       && (aaa != aba))))
514           || (/* aa is NULL and aba is Alloc */
515                  (get_irn_op(aa) == op_Const)
516               && (mode_is_reference(get_irn_mode(aa)))
517               && (get_Const_tarval(aa) == get_mode_null(get_irn_mode(aa)))
518               && (get_irn_op(ab) == op_Proj)
519               && (mode_is_reference(get_irn_mode(ab)))
520               && (get_irn_op(aba) == op_Alloc)))
521         /* 3.: */
522         return new_tarval_from_long(proj_nr & pn_Cmp_Ne, mode_b);
523     }
524   }
525   return tarval_bad;
526 }
527
528 /**
529  * return the value of a Proj, handle Proj(Cmp), Proj(Div), Proj(Mod), Proj(DivMod)
530  */
531 static tarval *computed_value_Proj(ir_node *n)
532 {
533   ir_node *a = get_Proj_pred(n);
534   long proj_nr;
535
536   switch (get_irn_opcode(a)) {
537   case iro_Cmp:
538     return computed_value_Proj_Cmp(n);
539
540   case iro_DivMod:
541     /* compute either the Div or the Mod part */
542     proj_nr = get_Proj_proj(n);
543     if (proj_nr == pn_DivMod_res_div)
544       return do_computed_value_Div(get_DivMod_left(a), get_DivMod_right(a));
545     else if (proj_nr == pn_DivMod_res_mod)
546       return do_computed_value_Mod(get_DivMod_left(a), get_DivMod_right(a));
547     break;
548
549   case iro_Div:
550     if (get_Proj_proj(n) == pn_Div_res)
551       return computed_value(a);
552     break;
553
554   case iro_Mod:
555     if (get_Proj_proj(n) == pn_Mod_res)
556       return computed_value(a);
557     break;
558
559   default:
560     return tarval_bad;
561   }
562   return tarval_bad;
563 }
564
565 /**
566  * calculate the value of a Mux: can be evaluated, if the
567  * sel and the right input are known
568  */
569 static tarval *computed_value_Mux(ir_node *n)
570 {
571   ir_node *sel = get_Mux_sel(n);
572   tarval *ts = value_of(sel);
573
574   if (ts == get_tarval_b_true()) {
575     ir_node *v = get_Mux_true(n);
576     return value_of(v);
577   }
578   else if (ts == get_tarval_b_false()) {
579     ir_node *v = get_Mux_false(n);
580     return value_of(v);
581   }
582   return tarval_bad;
583 }
584
585 /**
586  * If the parameter n can be computed, return its value, else tarval_bad.
587  * Performs constant folding.
588  *
589  * @param n  The node this should be evaluated
590  */
591 tarval *computed_value(ir_node *n)
592 {
593   if (n->op->computed_value)
594     return n->op->computed_value(n);
595   return tarval_bad;
596 }
597
598 /**
599  * set the default computed_value evaluator
600  */
601 static ir_op *firm_set_default_computed_value(ir_op *op)
602 {
603 #define CASE(a)                               \
604   case iro_##a:                               \
605     op->computed_value  = computed_value_##a; \
606     break
607
608   switch (op->code) {
609   CASE(Const);
610   CASE(SymConst);
611   CASE(Add);
612   CASE(Sub);
613   CASE(Minus);
614   CASE(Mul);
615   CASE(Quot);
616   CASE(Div);
617   CASE(Mod);
618   CASE(Abs);
619   CASE(And);
620   CASE(Or);
621   CASE(Eor);
622   CASE(Not);
623   CASE(Shl);
624   CASE(Shr);
625   CASE(Shrs);
626   CASE(Rot);
627   CASE(Conv);
628   CASE(Proj);
629   CASE(Mux);
630   default:
631     op->computed_value  = NULL;
632   }
633
634   return op;
635 #undef CASE
636 }
637
638 #if 0
639 /* returns 1 if the a and b are pointers to different locations. */
640 static bool
641 different_identity (ir_node *a, ir_node *b)
642 {
643   assert (mode_is_reference(get_irn_mode (a))
644           && mode_is_reference(get_irn_mode (b)));
645
646   if (get_irn_op (a) == op_Proj && get_irn_op(b) == op_Proj) {
647     ir_node *a1 = get_Proj_pred (a);
648     ir_node *b1 = get_Proj_pred (b);
649     if (a1 != b1 && get_irn_op (a1) == op_Alloc
650                 && get_irn_op (b1) == op_Alloc)
651       return 1;
652   }
653   return 0;
654 }
655 #endif
656
657 /**
658  * Returns a equivalent block for another block.
659  * If the block has only one predecessor, this is
660  * the equivalent one. If the only predecessor of a block is
661  * the block itself, this is a dead block.
662  *
663  * If both predecessors of a block are the branches of a binary
664  * Cond, the equivalent block is Cond's block.
665  *
666  * If all predecessors of a block are bad or lies in a dead
667  * block, the current block is dead as well.
668  *
669  * Note, that blocks are NEVER turned into Bad's, instead
670  * the dead_block flag is set. So, never test for is_Bad(block),
671  * always use is_dead_Block(block).
672  */
673 static ir_node *equivalent_node_Block(ir_node *n)
674 {
675   ir_node *oldn = n;
676   int n_preds   = get_Block_n_cfgpreds(n);
677
678   /* The Block constructor does not call optimize, but mature_immBlock
679      calls the optimization. */
680   assert(get_Block_matured(n));
681
682   /* Straightening: a single entry Block following a single exit Block
683      can be merged, if it is not the Start block. */
684   /* !!! Beware, all Phi-nodes of n must have been optimized away.
685      This should be true, as the block is matured before optimize is called.
686      But what about Phi-cycles with the Phi0/Id that could not be resolved?
687      Remaining Phi nodes are just Ids. */
688    if ((n_preds == 1) && (get_irn_op(get_Block_cfgpred(n, 0)) == op_Jmp)) {
689      ir_node *predblock = get_nodes_block(get_Block_cfgpred(n, 0));
690      if (predblock == oldn) {
691        /* Jmp jumps into the block it is in -- deal self cycle. */
692        n = set_Block_dead(n);
693        DBG_OPT_DEAD(oldn, n);
694      } else if (get_opt_control_flow_straightening()) {
695        n = predblock;
696        DBG_OPT_STG(oldn, n);
697      }
698    }
699    else if ((n_preds == 1) &&
700             (get_irn_op(skip_Proj(get_Block_cfgpred(n, 0))) == op_Cond)) {
701      ir_node *predblock = get_nodes_block(get_Block_cfgpred(n, 0));
702      if (predblock == oldn) {
703        /* Jmp jumps into the block it is in -- deal self cycle. */
704        n = set_Block_dead(n);
705        DBG_OPT_DEAD(oldn, n);
706      }
707    }
708    else if ((n_preds == 2) &&
709             (get_opt_control_flow_weak_simplification())) {
710     /* Test whether Cond jumps twice to this block
711        @@@ we could do this also with two loops finding two preds from several ones. */
712     ir_node *a = get_Block_cfgpred(n, 0);
713     ir_node *b = get_Block_cfgpred(n, 1);
714
715     if ((get_irn_op(a) == op_Proj) &&
716         (get_irn_op(b) == op_Proj) &&
717         (get_Proj_pred(a) == get_Proj_pred(b)) &&
718         (get_irn_op(get_Proj_pred(a)) == op_Cond) &&
719         (get_irn_mode(get_Cond_selector(get_Proj_pred(a))) == mode_b)) {
720       /* Also a single entry Block following a single exit Block.  Phis have
721          twice the same operand and will be optimized away. */
722       n = get_nodes_block(a);
723       DBG_OPT_IFSIM(oldn, a, b, n);
724     }
725   } else if (get_opt_unreachable_code() &&
726              (n != current_ir_graph->start_block) &&
727              (n != current_ir_graph->end_block)     ) {
728     int i, n_cfg = get_Block_n_cfgpreds(n);
729
730     /* If all inputs are dead, this block is dead too, except if it is
731        the start or end block.  This is a step of unreachable code
732        elimination */
733     for (i = 0; i < n_cfg; i++) {
734       ir_node *pred = get_Block_cfgpred(n, i);
735       ir_node *pred_blk;
736
737       if (is_Bad(pred)) continue;
738       pred_blk = get_nodes_block(pred);
739
740       if (is_Block_dead(pred_blk)) continue;
741
742       if (pred_blk != n) {
743         /* really found a living input */
744         break;
745       }
746     }
747     if (i == n_cfg)
748       n = set_Block_dead(n);
749   }
750
751   return n;
752 }
753
754 /**
755  * Returns a equivalent node for a Jmp, a Bad :-)
756  * Of course this only happens if the Block of the Jmp is Bad.
757  */
758 static ir_node *equivalent_node_Jmp(ir_node *n)
759 {
760   /* GL: Why not same for op_Raise?? */
761   /* unreachable code elimination */
762   if (is_Block_dead(get_nodes_block(n)))
763     n = new_Bad();
764
765   return n;
766 }
767
768 static ir_node *equivalent_node_Cond(ir_node *n)
769 {
770   /* We do not evaluate Cond here as we replace it by a new node, a Jmp.
771      See cases for iro_Cond and iro_Proj in transform_node. */
772   return n;
773 }
774
775 /**
776  * optimize operations that are commutative and have neutral 0,
777  * so a op 0 = 0 op a = a.
778  */
779 static ir_node *equivalent_node_neutral_zero(ir_node *n)
780 {
781   ir_node *oldn = n;
782
783   ir_node *a = get_binop_left(n);
784   ir_node *b = get_binop_right(n);
785
786   tarval *tv;
787   ir_node *on;
788
789   /* After running compute_node there is only one constant predecessor.
790      Find this predecessors value and remember the other node: */
791   if ((tv = value_of(a)) != tarval_bad) {
792     on = b;
793   } else if ((tv = value_of(b)) != tarval_bad) {
794     on = a;
795   } else
796     return n;
797
798   /* If this predecessors constant value is zero, the operation is
799      unnecessary. Remove it: */
800   if (classify_tarval (tv) == TV_CLASSIFY_NULL) {
801     n = on;
802
803     DBG_OPT_ALGSIM1(oldn, a, b, n);
804   }
805
806   return n;
807 }
808
809 #define equivalent_node_Add  equivalent_node_neutral_zero
810 #define equivalent_node_Eor  equivalent_node_neutral_zero
811
812 /**
813  * optimize operations that are not commutative but have neutral 0 on left,
814  * so a op 0 = a.
815  */
816 static ir_node *equivalent_node_left_zero(ir_node *n)
817 {
818   ir_node *oldn = n;
819
820   ir_node *a = get_binop_left(n);
821   ir_node *b = get_binop_right(n);
822
823   if (classify_tarval(value_of(b)) == TV_CLASSIFY_NULL) {
824     n = a;
825
826     DBG_OPT_ALGSIM1(oldn, a, b, n);
827   }
828
829   return n;
830 }
831
832 #define equivalent_node_Sub   equivalent_node_left_zero
833 #define equivalent_node_Shl   equivalent_node_left_zero
834 #define equivalent_node_Shr   equivalent_node_left_zero
835 #define equivalent_node_Shrs  equivalent_node_left_zero
836 #define equivalent_node_Rot   equivalent_node_left_zero
837
838 /**
839  * Er, a "symmetic unop", ie op(op(n)) = n.
840  *
841  * @fixme -(-a) == a, but might overflow two times.
842  * We handle it anyway here but the better way would be a
843  * flag. This would be needed for Pascal for instance.
844  */
845 static ir_node *equivalent_node_symmetric_unop(ir_node *n)
846 {
847   ir_node *oldn = n;
848   ir_node *pred = get_unop_op(n);
849
850   /* optimize symmetric unop */
851   if (get_irn_op(pred) == get_irn_op(n)) {
852     n = get_unop_op(pred);
853     DBG_OPT_ALGSIM2(oldn, pred, n);
854   }
855   return n;
856 }
857
858 /* Not(Not(x)) == x */
859 #define equivalent_node_Not    equivalent_node_symmetric_unop
860
861 /* --x == x */  /* ??? Is this possible or can --x raise an
862                        out of bounds exception if min =! max? */
863 #define equivalent_node_Minus  equivalent_node_symmetric_unop
864
865 /**
866  * Optimize a * 1 = 1 * a = a.
867  */
868 static ir_node *equivalent_node_Mul(ir_node *n)
869 {
870   ir_node *oldn = n;
871
872   ir_node *a = get_Mul_left(n);
873   ir_node *b = get_Mul_right(n);
874
875   /* Mul is commutative and has again an other neutral element. */
876   if (classify_tarval(value_of(a)) == TV_CLASSIFY_ONE) {
877     n = b;
878     DBG_OPT_ALGSIM1(oldn, a, b, n);
879   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) {
880     n = a;
881     DBG_OPT_ALGSIM1(oldn, a, b, n);
882   }
883   return n;
884 }
885
886 /**
887  * Optimize a / 1 = a.
888  */
889 static ir_node *equivalent_node_Div(ir_node *n)
890 {
891   ir_node *a = get_Div_left(n);
892   ir_node *b = get_Div_right(n);
893
894   /* Div is not commutative. */
895   if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) { /* div(x, 1) == x */
896     /* Turn Div into a tuple (mem, bad, a) */
897     ir_node *mem = get_Div_mem(n);
898     turn_into_tuple(n, 3);
899     set_Tuple_pred(n, pn_Div_M,        mem);
900     set_Tuple_pred(n, pn_Div_X_except, new_Bad());        /* no exception */
901     set_Tuple_pred(n, pn_Div_res,      a);
902   }
903   return n;
904 }
905
906 /**
907  * Optimize a / 1 = a.
908  */
909 static ir_node *equivalent_node_DivMod(ir_node *n)
910 {
911   ir_node *a = get_DivMod_left(n);
912   ir_node *b = get_DivMod_right(n);
913
914   /* Div is not commutative. */
915   if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) { /* div(x, 1) == x */
916     /* Turn DivMod into a tuple (mem, bad, a, 0) */
917     ir_node *mem = get_Div_mem(n);
918     ir_mode *mode = get_irn_mode(b);
919
920     turn_into_tuple(n, 4);
921     set_Tuple_pred(n, pn_DivMod_M,        mem);
922     set_Tuple_pred(n, pn_DivMod_X_except, new_Bad());        /* no exception */
923     set_Tuple_pred(n, pn_DivMod_res_div,  a);
924     set_Tuple_pred(n, pn_DivMod_res_mod,  new_Const(mode, get_mode_null(mode)));
925   }
926   return n;
927 }
928
929 /**
930  * Use algebraic simplification a | a = a | 0 = 0 | a = a.
931  */
932 static ir_node *equivalent_node_Or(ir_node *n)
933 {
934   ir_node *oldn = n;
935
936   ir_node *a = get_Or_left(n);
937   ir_node *b = get_Or_right(n);
938
939   if (a == b) {
940     n = a;    /* Or has it's own neutral element */
941   } else if (classify_tarval(value_of(a)) == TV_CLASSIFY_NULL) {
942     n = b;
943     DBG_OPT_ALGSIM1(oldn, a, b, n);
944   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_NULL) {
945     n = a;
946     DBG_OPT_ALGSIM1(oldn, a, b, n);
947   }
948
949   return n;
950 }
951
952 /**
953  * Optimize a & 0b1...1 = 0b1...1 & a =  a & a = a.
954  */
955 static ir_node *equivalent_node_And(ir_node *n)
956 {
957   ir_node *oldn = n;
958
959   ir_node *a = get_And_left(n);
960   ir_node *b = get_And_right(n);
961
962   if (a == b) {
963     n = a;    /* And has it's own neutral element */
964   } else if (classify_tarval(value_of(a)) == TV_CLASSIFY_ALL_ONE) {
965     n = b;
966     DBG_OPT_ALGSIM1(oldn, a, b, n);
967   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_ALL_ONE) {
968     n = a;
969     DBG_OPT_ALGSIM1(oldn, a, b, n);
970   }
971   return n;
972 }
973
974 /**
975  * Try to remove useless conv's:
976  */
977 static ir_node *equivalent_node_Conv(ir_node *n)
978 {
979   ir_node *oldn = n;
980   ir_node *a = get_Conv_op(n);
981   ir_node *b;
982
983   ir_mode *n_mode = get_irn_mode(n);
984   ir_mode *a_mode = get_irn_mode(a);
985
986   if (n_mode == a_mode) { /* No Conv necessary */
987     n = a;
988     DBG_OPT_ALGSIM3(oldn, a, n);
989   } else if (get_irn_op(a) == op_Conv) { /* Conv(Conv(b)) */
990     ir_mode *b_mode;
991
992     b = get_Conv_op(a);
993     n_mode = get_irn_mode(n);
994     b_mode = get_irn_mode(b);
995
996     if (n_mode == b_mode) {
997       if (n_mode == mode_b) {
998         n = b; /* Convb(Conv*(xxxb(...))) == xxxb(...) */
999         DBG_OPT_ALGSIM1(oldn, a, b, n);
1000       }
1001       else if (mode_is_int(n_mode) || mode_is_character(n_mode)) {
1002         if (smaller_mode(b_mode, a_mode)){
1003           n = b;        /* ConvS(ConvL(xxxS(...))) == xxxS(...) */
1004           DBG_OPT_ALGSIM1(oldn, a, b, n);
1005         }
1006       }
1007     }
1008   }
1009   return n;
1010 }
1011
1012 /**
1013  * A Cast may be removed if the type of the previous node
1014  * is already the type of the Cast.
1015  */
1016 static ir_node *equivalent_node_Cast(ir_node *n) {
1017   ir_node *pred = get_Cast_op(n);
1018   if (get_irn_type(pred) == get_Cast_type(n))
1019     n = pred;
1020   return n;
1021 }
1022
1023 /* Several optimizations:
1024    - no Phi in start block.
1025    - remove Id operators that are inputs to Phi
1026    - fold Phi-nodes, iff they have only one predecessor except
1027            themselves.
1028 */
1029 static ir_node *equivalent_node_Phi(ir_node *n)
1030 {
1031   int i, n_preds;
1032
1033   ir_node *oldn = n;
1034   ir_node *block = NULL;     /* to shutup gcc */
1035   ir_node *first_val = NULL; /* to shutup gcc */
1036   ir_node *scnd_val = NULL;  /* to shutup gcc */
1037
1038   if (!get_opt_normalize()) return n;
1039
1040   n_preds = get_Phi_n_preds(n);
1041
1042   block = get_nodes_block(n);
1043   /* @@@ fliegt 'raus, sollte aber doch immer wahr sein!!!
1044      assert(get_irn_arity(block) == n_preds && "phi in wrong block!"); */
1045   if ((is_Block_dead(block)) ||                  /* Control dead */
1046       (block == current_ir_graph->start_block))  /* There should be no Phi nodes */
1047     return new_Bad();                            /* in the Start Block. */
1048
1049   if (n_preds == 0) return n;           /* Phi of dead Region without predecessors. */
1050
1051 #if 0
1052   /* first we test for a special case: */
1053   /* Confirm is a special node fixing additional information for a
1054      value that is known at a certain point.  This is useful for
1055      dataflow analysis. */
1056   if (n_preds == 2) {
1057     ir_node *a = get_Phi_pred(n, 0);
1058     ir_node *b = get_Phi_pred(n, 1);
1059     if (   (get_irn_op(a) == op_Confirm)
1060         && (get_irn_op(b) == op_Confirm)
1061         && follow_Id (get_irn_n(a, 0) == get_irn_n(b, 0))
1062         && (get_irn_n(a, 1) == get_irn_n (b, 1))
1063         && (a->data.num == (~b->data.num & irpn_True) )) {
1064       return get_irn_n(a, 0);
1065     }
1066   }
1067 #endif
1068
1069   /* If the Block has a Bad pred, we also have one. */
1070   for (i = 0;  i < n_preds;  ++i)
1071     if (is_Bad (get_Block_cfgpred(block, i)))
1072       set_Phi_pred(n, i, new_Bad());
1073
1074   /* Find first non-self-referencing input */
1075   for (i = 0;  i < n_preds;  ++i) {
1076     first_val = get_Phi_pred(n, i);
1077     if (   (first_val != n)                            /* not self pointer */
1078 #if 1
1079         && (get_irn_op(first_val) != op_Bad)
1080 #endif
1081            ) {        /* value not dead */
1082       break;          /* then found first value. */
1083     }
1084   }
1085
1086   /* A totally Bad or self-referencing Phi (we didn't break the above loop) */
1087   if (i >= n_preds) { return new_Bad(); }
1088
1089   scnd_val = NULL;
1090
1091   /* follow_Id () for rest of inputs, determine if any of these
1092      are non-self-referencing */
1093   while (++i < n_preds) {
1094     scnd_val = get_Phi_pred(n, i);
1095     if (   (scnd_val != n)
1096         && (scnd_val != first_val)
1097 #if 1
1098         && (get_irn_op(scnd_val) != op_Bad)
1099 #endif
1100            ) {
1101       break;
1102     }
1103   }
1104
1105   /* Fold, if no multiple distinct non-self-referencing inputs */
1106   if (i >= n_preds) {
1107     n = first_val;
1108     DBG_OPT_PHI(oldn, first_val, n);
1109   } else {
1110     /* skip the remaining Ids (done in get_Phi_pred). */
1111     /* superfluous, since we walk all to propagate Block's Bads.
1112        while (++i < n_preds) get_Phi_pred(n, i);     */
1113   }
1114   return n;
1115 }
1116
1117 /**
1118  * optimize Proj(Tuple) and gigo for ProjX in Bad block
1119  */
1120 static ir_node *equivalent_node_Proj(ir_node *n)
1121 {
1122   ir_node *oldn = n;
1123
1124   ir_node *a = get_Proj_pred(n);
1125
1126   if ( get_irn_op(a) == op_Tuple) {
1127     /* Remove the Tuple/Proj combination. */
1128     if ( get_Proj_proj(n) <= get_Tuple_n_preds(a) ) {
1129       n = get_Tuple_pred(a, get_Proj_proj(n));
1130       DBG_OPT_TUPLE(oldn, a, n);
1131     } else {
1132       assert(0); /* This should not happen! */
1133       n = new_Bad();
1134     }
1135   } else if (get_irn_mode(n) == mode_X &&
1136              is_Block_dead(get_nodes_block(n))) {
1137     /* Remove dead control flow -- early gigo. */
1138     n = new_Bad();
1139   }
1140   return n;
1141 }
1142
1143 /**
1144  * Remove Id's.
1145  */
1146 static ir_node *equivalent_node_Id(ir_node *n)
1147 {
1148   ir_node *oldn = n;
1149
1150   n = follow_Id(n);
1151   DBG_OPT_ID(oldn, n);
1152   return n;
1153 }
1154
1155 /**
1156  * optimize a Mux
1157  */
1158 static ir_node *equivalent_node_Mux(ir_node *n)
1159 {
1160   ir_node *oldn = n, *sel = get_Mux_sel(n);
1161   tarval *ts = value_of(sel);
1162
1163   /* Mux(true, f, t) == t */
1164   if (ts == get_tarval_b_true()) {
1165     n = get_Mux_true(n);
1166     DBG_OPT_ALGSIM0(oldn, n);
1167   }
1168   /* Mux(false, f, t) == f */
1169   else if (ts == get_tarval_b_false()) {
1170     n = get_Mux_false(n);
1171     DBG_OPT_ALGSIM0(oldn, n);
1172   }
1173   /* Mux(v, x, x) == x */
1174   else if (get_Mux_false(n) == get_Mux_true(n)) {
1175     n = get_Mux_true(n);
1176     DBG_OPT_ALGSIM0(oldn, n);
1177   }
1178   else if (get_irn_op(sel) == op_Proj && !mode_honor_signed_zeros(get_irn_mode(n))) {
1179     ir_node *cmp = get_Proj_pred(sel);
1180     long proj_nr = get_Proj_proj(sel);
1181     ir_node *b   = get_Mux_false(n);
1182     ir_node *a   = get_Mux_true(n);
1183
1184     /*
1185      * Note: normalization puts the constant on the right site,
1186      * so we check only one case.
1187      *
1188      * Note further that these optimization work even for floating point
1189      * with NaN's because -NaN == NaN.
1190      * However, if +0 and -0 is handled differently, we cannot use the first one.
1191      */
1192     if (get_irn_op(cmp) == op_Cmp && get_Cmp_left(cmp) == a) {
1193       if (classify_Const(get_Cmp_right(cmp)) == CNST_NULL) {
1194         /* Mux(a CMP 0, X, a) */
1195         if (get_irn_op(b) == op_Minus && get_Minus_op(b) == a) {
1196           /* Mux(a CMP 0, -a, a) */
1197           if (proj_nr == pn_Cmp_Eq) {
1198             /* Mux(a == 0, -a, a)  ==>  -a */
1199             n = b;
1200             DBG_OPT_ALGSIM0(oldn, n);
1201           }
1202           else if (proj_nr == pn_Cmp_Lg || proj_nr == pn_Cmp_Ne) {
1203             /* Mux(a != 0, -a, a)  ==> a */
1204             n = a;
1205             DBG_OPT_ALGSIM0(oldn, n);
1206           }
1207         }
1208         else if (classify_Const(b) == CNST_NULL) {
1209           /* Mux(a CMP 0, 0, a) */
1210           if (proj_nr == pn_Cmp_Lg || proj_nr == pn_Cmp_Ne) {
1211             /* Mux(a != 0, 0, a) ==> a */
1212             n = a;
1213             DBG_OPT_ALGSIM0(oldn, n);
1214           }
1215           else if (proj_nr == pn_Cmp_Eq) {
1216             /* Mux(a == 0, 0, a) ==> 0 */
1217             n = b;
1218             DBG_OPT_ALGSIM0(oldn, n);
1219           }
1220         }
1221       }
1222     }
1223   }
1224
1225   return n;
1226 }
1227
1228 /**
1229  * Optimize -a CMP -b into b CMP a.
1230  * This works only for for modes where unary Minus
1231  * cannot Overflow.
1232  * Note that two-complement integers can Overflow
1233  * so it will NOT work.
1234  */
1235 static ir_node *equivalent_node_Cmp(ir_node *n)
1236 {
1237   ir_node *left  = get_Cmp_left(n);
1238   ir_node *right = get_Cmp_right(n);
1239
1240   if (get_irn_op(left) == op_Minus && get_irn_op(right) == op_Minus &&
1241       !mode_overflow_on_unary_Minus(get_irn_mode(left))) {
1242     left  = get_Minus_op(left);
1243     right = get_Minus_op(right);
1244     set_Cmp_left(n, right);
1245     set_Cmp_right(n, left);
1246   }
1247   return n;
1248 }
1249
1250 /**
1251  * equivalent_node() returns a node equivalent to input n. It skips all nodes that
1252  * perform no actual computation, as, e.g., the Id nodes.  It does not create
1253  * new nodes.  It is therefore safe to free n if the node returned is not n.
1254  * If a node returns a Tuple we can not just skip it.  If the size of the
1255  * in array fits, we transform n into a tuple (e.g., Div).
1256  */
1257 ir_node *
1258 equivalent_node(ir_node *n)
1259 {
1260   if (n->op->equivalent_node)
1261     return n->op->equivalent_node(n);
1262   return n;
1263 }
1264
1265 /**
1266  * set the default equivalent node operation
1267  */
1268 static ir_op *firm_set_default_equivalent_node(ir_op *op)
1269 {
1270 #define CASE(a)                                 \
1271   case iro_##a:                                 \
1272     op->equivalent_node  = equivalent_node_##a; \
1273     break
1274
1275   switch (op->code) {
1276   CASE(Block);
1277   CASE(Jmp);
1278   CASE(Cond);
1279   CASE(Or);
1280   CASE(Add);
1281   CASE(Eor);
1282   CASE(Sub);
1283   CASE(Shl);
1284   CASE(Shr);
1285   CASE(Shrs);
1286   CASE(Rot);
1287   CASE(Not);
1288   CASE(Minus);
1289   CASE(Mul);
1290   CASE(Div);
1291   CASE(DivMod);
1292   CASE(And);
1293   CASE(Conv);
1294   CASE(Cast);
1295   CASE(Phi);
1296   CASE(Proj);
1297   CASE(Id);
1298   CASE(Mux);
1299   CASE(Cmp);
1300   default:
1301     op->equivalent_node  = NULL;
1302   }
1303
1304   return op;
1305 #undef CASE
1306 }
1307
1308 /**
1309  * Do node specific optimizations of nodes predecessors.
1310  */
1311 static void
1312 optimize_preds(ir_node *n) {
1313   ir_node *a = NULL, *b = NULL;
1314
1315   /* get the operands we will work on for simple cases. */
1316   if (is_binop(n)) {
1317     a = get_binop_left(n);
1318     b = get_binop_right(n);
1319   } else if (is_unop(n)) {
1320     a = get_unop_op(n);
1321   }
1322
1323   switch (get_irn_opcode(n)) {
1324
1325   case iro_Cmp:
1326     /* We don't want Cast as input to Cmp. */
1327     if (get_irn_op(a) == op_Cast) {
1328       a = get_Cast_op(a);
1329       set_Cmp_left(n, a);
1330     }
1331     if (get_irn_op(b) == op_Cast) {
1332       b = get_Cast_op(b);
1333       set_Cmp_right(n, b);
1334     }
1335     break;
1336
1337   default: break;
1338   } /* end switch */
1339 }
1340
1341 /**
1342  * Transform AddP(P, ConvIs(Iu)), AddP(P, ConvIu(Is)) and
1343  * SubP(P, ConvIs(Iu)), SubP(P, ConvIu(Is)).
1344  * If possible, remove the Conv's.
1345  */
1346 static ir_node *transform_node_AddSub(ir_node *n)
1347 {
1348   ir_mode *mode = get_irn_mode(n);
1349
1350   if (mode_is_reference(mode)) {
1351     ir_node *left  = get_binop_left(n);
1352     ir_node *right = get_binop_right(n);
1353     int ref_bits   = get_mode_size_bits(mode);
1354
1355     if (get_irn_op(left) == op_Conv) {
1356       ir_mode *mode = get_irn_mode(left);
1357       int bits      = get_mode_size_bits(mode);
1358
1359       if (ref_bits == bits &&
1360           mode_is_int(mode) &&
1361           get_mode_arithmetic(mode) == irma_twos_complement) {
1362         ir_node *pre      = get_Conv_op(left);
1363         ir_mode *pre_mode = get_irn_mode(pre);
1364
1365         if (mode_is_int(pre_mode) &&
1366             get_mode_size_bits(pre_mode) == bits &&
1367             get_mode_arithmetic(pre_mode) == irma_twos_complement) {
1368           /* ok, this conv just changes to sign, moreover the calculation
1369            * is done with same number of bits as our address mode, so
1370            * we can ignore the conv as address calculation can be viewed
1371            * as either signed or unsigned
1372            */
1373           set_binop_left(n, pre);
1374         }
1375       }
1376     }
1377
1378     if (get_irn_op(right) == op_Conv) {
1379       ir_mode *mode = get_irn_mode(right);
1380       int bits      = get_mode_size_bits(mode);
1381
1382       if (ref_bits == bits &&
1383           mode_is_int(mode) &&
1384           get_mode_arithmetic(mode) == irma_twos_complement) {
1385         ir_node *pre      = get_Conv_op(right);
1386         ir_mode *pre_mode = get_irn_mode(pre);
1387
1388         if (mode_is_int(pre_mode) &&
1389             get_mode_size_bits(pre_mode) == bits &&
1390             get_mode_arithmetic(pre_mode) == irma_twos_complement) {
1391           /* ok, this conv just changes to sign, moreover the calculation
1392            * is done with same number of bits as our address mode, so
1393            * we can ignore the conv as address calculation can be viewed
1394            * as either signed or unsigned
1395            */
1396           set_binop_right(n, pre);
1397         }
1398       }
1399     }
1400   }
1401   return n;
1402 }
1403
1404 /**
1405  * Do the AddSub optimization, then Transform Add(a,a) into Mul(a, 2)
1406  * if the mode is integer or float.
1407  * Transform Add(a,-b) into Sub(a,b).
1408  * Reassociation might fold this further.
1409  */
1410 static ir_node *transform_node_Add(ir_node *n)
1411 {
1412   ir_mode *mode;
1413   ir_node *oldn = n;
1414
1415   n = transform_node_AddSub(n);
1416
1417   mode = get_irn_mode(n);
1418   if (mode_is_num(mode)) {
1419     ir_node *a = get_Add_left(n);
1420
1421     if (a == get_Add_right(n)) {
1422       ir_node *block = get_nodes_block(n);
1423
1424       n = new_rd_Mul(
1425             get_irn_dbg_info(n),
1426             current_ir_graph,
1427             block,
1428             a,
1429             new_r_Const_long(current_ir_graph, block, mode, 2),
1430             mode);
1431       DBG_OPT_ALGSIM0(oldn, n);
1432     }
1433     else {
1434       ir_node *b = get_Add_right(n);
1435
1436       if (get_irn_op(a) == op_Minus) {
1437         n = new_rd_Sub(
1438             get_irn_dbg_info(n),
1439             current_ir_graph,
1440             get_nodes_block(n),
1441             b,
1442             get_Minus_op(a),
1443             mode);
1444         DBG_OPT_ALGSIM0(oldn, n);
1445       }
1446       else if (get_irn_op(b) == op_Minus) {
1447         n = new_rd_Sub(
1448             get_irn_dbg_info(n),
1449             current_ir_graph,
1450             get_nodes_block(n),
1451             a,
1452             get_Minus_op(b),
1453             mode);
1454         DBG_OPT_ALGSIM0(oldn, n);
1455       }
1456     }
1457   }
1458   return n;
1459 }
1460
1461 /**
1462  * Do the AddSub optimization, then Transform Sub(0,a) into Minus(a).
1463  */
1464 static ir_node *transform_node_Sub(ir_node *n)
1465 {
1466   ir_mode *mode;
1467   ir_node *oldn = n;
1468
1469   n = transform_node_AddSub(n);
1470
1471   mode = get_irn_mode(n);
1472   if (mode_is_num(mode) && (classify_Const(get_Sub_left(n)) == CNST_NULL)) {
1473     n = new_rd_Minus(
1474           get_irn_dbg_info(n),
1475           current_ir_graph,
1476           get_nodes_block(n),
1477           get_Sub_right(n),
1478           mode);
1479     DBG_OPT_ALGSIM0(oldn, n);
1480   }
1481
1482   return n;
1483 }
1484
1485 /**
1486   Transform Mul(a,-1) into -a.
1487  * Do architecture dependend optimizations on Mul nodes
1488  */
1489 static ir_node *transform_node_Mul(ir_node *n) {
1490   ir_node *oldn = n;
1491   ir_mode *mode = get_irn_mode(n);
1492
1493   if (mode_is_signed(mode)) {
1494     ir_node *r = NULL;
1495     ir_node *a = get_Mul_left(n);
1496     ir_node *b = get_Mul_right(n);
1497
1498     if (value_of(a) == get_mode_minus_one(mode))
1499       r = b;
1500     else if (value_of(b) == get_mode_minus_one(mode))
1501       r = a;
1502     if (r) {
1503       n = new_rd_Minus(get_irn_dbg_info(n), current_ir_graph, get_nodes_block(n), r, mode);
1504       DBG_OPT_ALGSIM1(oldn, a, b, n);
1505       return n;
1506     }
1507   }
1508   return arch_dep_replace_mul_with_shifts(n);
1509 }
1510
1511 /**
1512  * transform a Div Node
1513  */
1514 static ir_node *transform_node_Div(ir_node *n)
1515 {
1516   tarval *tv = value_of(n);
1517   ir_node *value = n;
1518
1519   /* BEWARE: it is NOT possible to optimize a/a to 1, as this may cause a exception */
1520
1521   if (tv != tarval_bad) {
1522     value = new_Const(get_tarval_mode(tv), tv);
1523
1524     DBG_OPT_CSTEVAL(n, value);
1525   }
1526   else /* Try architecture dependand optimization */
1527     value = arch_dep_replace_div_by_const(n);
1528
1529   if (value != n) {
1530     /* Turn Div into a tuple (mem, bad, value) */
1531     ir_node *mem = get_Div_mem(n);
1532
1533     turn_into_tuple(n, 3);
1534     set_Tuple_pred(n, pn_Div_M, mem);
1535     set_Tuple_pred(n, pn_Div_X_except, new_Bad());
1536     set_Tuple_pred(n, pn_Div_res, value);
1537   }
1538   return n;
1539 }
1540
1541 /**
1542  * transform a Mod node
1543  */
1544 static ir_node *transform_node_Mod(ir_node *n)
1545 {
1546   tarval *tv = value_of(n);
1547   ir_node *value = n;
1548
1549   /* BEWARE: it is NOT possible to optimize a%a to 0, as this may cause a exception */
1550
1551   if (tv != tarval_bad) {
1552     value = new_Const(get_tarval_mode(tv), tv);
1553
1554     DBG_OPT_CSTEVAL(n, value);
1555   }
1556   else /* Try architecture dependand optimization */
1557     value = arch_dep_replace_mod_by_const(n);
1558
1559   if (value != n) {
1560     /* Turn Mod into a tuple (mem, bad, value) */
1561     ir_node *mem = get_Mod_mem(n);
1562
1563     turn_into_tuple(n, 3);
1564     set_Tuple_pred(n, pn_Mod_M, mem);
1565     set_Tuple_pred(n, pn_Mod_X_except, new_Bad());
1566     set_Tuple_pred(n, pn_Mod_res, value);
1567   }
1568   return n;
1569 }
1570
1571 /**
1572  * transform a DivMod node
1573  */
1574 static ir_node *transform_node_DivMod(ir_node *n)
1575 {
1576   int evaluated = 0;
1577
1578   ir_node *a = get_DivMod_left(n);
1579   ir_node *b = get_DivMod_right(n);
1580   ir_mode *mode = get_irn_mode(a);
1581   tarval *ta = value_of(a);
1582   tarval *tb = value_of(b);
1583
1584   if (!(mode_is_int(mode) && mode_is_int(get_irn_mode(b))))
1585     return n;
1586
1587   /* BEWARE: it is NOT possible to optimize a/a to 1, as this may cause a exception */
1588
1589   if (tb != tarval_bad) {
1590     if (tb == get_mode_one(get_tarval_mode(tb))) {
1591       b = new_Const (mode, get_mode_null(mode));
1592       evaluated = 1;
1593
1594       DBG_OPT_CSTEVAL(n, b);
1595     }
1596     else if (ta != tarval_bad) {
1597       tarval *resa, *resb;
1598       resa = tarval_div (ta, tb);
1599       if (resa == tarval_bad) return n; /* Causes exception!!! Model by replacing through
1600                                         Jmp for X result!? */
1601       resb = tarval_mod (ta, tb);
1602       if (resb == tarval_bad) return n; /* Causes exception! */
1603       a = new_Const (mode, resa);
1604       b = new_Const (mode, resb);
1605       evaluated = 1;
1606
1607       DBG_OPT_CSTEVAL(n, a);
1608       DBG_OPT_CSTEVAL(n, b);
1609     }
1610     else { /* Try architecture dependand optimization */
1611       arch_dep_replace_divmod_by_const(&a, &b, n);
1612       evaluated = a != NULL;
1613     }
1614   } else if (ta == get_mode_null(mode)) {
1615     /* 0 / non-Const = 0 */
1616     b = a;
1617     evaluated = 1;
1618   }
1619
1620   if (evaluated) { /* replace by tuple */
1621     ir_node *mem = get_DivMod_mem(n);
1622     turn_into_tuple(n, 4);
1623     set_Tuple_pred(n, pn_DivMod_M,        mem);
1624     set_Tuple_pred(n, pn_DivMod_X_except, new_Bad());  /* no exception */
1625     set_Tuple_pred(n, pn_DivMod_res_div,  a);
1626     set_Tuple_pred(n, pn_DivMod_res_mod,  b);
1627     assert(get_nodes_block(n));
1628   }
1629
1630   return n;
1631 }
1632
1633 /**
1634  * transform a Cond node
1635  */
1636 static ir_node *transform_node_Cond(ir_node *n)
1637 {
1638   /* Replace the Cond by a Jmp if it branches on a constant
1639      condition. */
1640   ir_node *jmp;
1641   ir_node *a = get_Cond_selector(n);
1642   tarval *ta = value_of(a);
1643
1644   if ((ta != tarval_bad) &&
1645       (get_irn_mode(a) == mode_b) &&
1646       (get_opt_unreachable_code())) {
1647     /* It's a boolean Cond, branching on a boolean constant.
1648                Replace it by a tuple (Bad, Jmp) or (Jmp, Bad) */
1649     jmp = new_r_Jmp(current_ir_graph, get_nodes_block(n));
1650     turn_into_tuple(n, 2);
1651     if (ta == tarval_b_true) {
1652       set_Tuple_pred(n, pn_Cond_false, new_Bad());
1653       set_Tuple_pred(n, pn_Cond_true, jmp);
1654     } else {
1655       set_Tuple_pred(n, pn_Cond_false, jmp);
1656       set_Tuple_pred(n, pn_Cond_true, new_Bad());
1657     }
1658     /* We might generate an endless loop, so keep it alive. */
1659     add_End_keepalive(get_irg_end(current_ir_graph), get_nodes_block(n));
1660   } else if ((ta != tarval_bad) &&
1661              (get_irn_mode(a) == mode_Iu) &&
1662              (get_Cond_kind(n) == dense) &&
1663              (get_opt_unreachable_code())) {
1664     /* I don't want to allow Tuples smaller than the biggest Proj.
1665        Also this tuple might get really big...
1666        I generate the Jmp here, and remember it in link.  Link is used
1667        when optimizing Proj. */
1668     set_irn_link(n, new_r_Jmp(current_ir_graph, get_nodes_block(n)));
1669     /* We might generate an endless loop, so keep it alive. */
1670     add_End_keepalive(get_irg_end(current_ir_graph), get_nodes_block(n));
1671   } else if ((get_irn_op(a) == op_Eor)
1672              && (get_irn_mode(a) == mode_b)
1673              && (classify_tarval(value_of(get_Eor_right(a))) == TV_CLASSIFY_ONE)) {
1674     /* The Eor is a negate.  Generate a new Cond without the negate,
1675        simulate the negate by exchanging the results. */
1676     set_irn_link(n, new_r_Cond(current_ir_graph, get_nodes_block(n),
1677                                get_Eor_left(a)));
1678   } else if ((get_irn_op(a) == op_Not)
1679              && (get_irn_mode(a) == mode_b)) {
1680     /* A Not before the Cond.  Generate a new Cond without the Not,
1681        simulate the Not by exchanging the results. */
1682     set_irn_link(n, new_r_Cond(current_ir_graph, get_nodes_block(n),
1683                                get_Not_op(a)));
1684   }
1685   return n;
1686 }
1687
1688 /**
1689  * Transform an Eor.
1690  */
1691 static ir_node *transform_node_Eor(ir_node *n)
1692 {
1693   ir_node *oldn = n;
1694   ir_node *a = get_Eor_left(n);
1695   ir_node *b = get_Eor_right(n);
1696   ir_mode *mode = get_irn_mode(n);
1697
1698   if (a == b) {
1699     /* a ^ a = 0 */
1700     n = new_rd_Const(get_irn_dbg_info(n), current_ir_graph, get_nodes_block(n),
1701                      mode, get_mode_null(mode));
1702     DBG_OPT_ALGSIM0(oldn, n);
1703   }
1704   else if ((mode == mode_b)
1705       && (get_irn_op(a) == op_Proj)
1706       && (get_irn_mode(a) == mode_b)
1707       && (classify_tarval (value_of(b)) == TV_CLASSIFY_ONE)
1708       && (get_irn_op(get_Proj_pred(a)) == op_Cmp)) {
1709     /* The Eor negates a Cmp. The Cmp has the negated result anyways! */
1710     n = new_r_Proj(current_ir_graph, get_nodes_block(n), get_Proj_pred(a),
1711                    mode_b, get_negated_pnc(get_Proj_proj(a)));
1712
1713     DBG_OPT_ALGSIM0(oldn, n);
1714   }
1715   else if ((mode == mode_b)
1716         && (classify_tarval (value_of(b)) == TV_CLASSIFY_ONE)) {
1717     /* The Eor is a Not. Replace it by a Not. */
1718     /*   ????!!!Extend to bitfield 1111111. */
1719     n = new_r_Not(current_ir_graph, get_nodes_block(n), a, mode_b);
1720
1721     DBG_OPT_ALGSIM0(oldn, n);
1722   }
1723
1724   return n;
1725 }
1726
1727 /**
1728  * Transform a boolean Not.
1729  */
1730 static ir_node *transform_node_Not(ir_node *n)
1731 {
1732   ir_node *oldn = n;
1733   ir_node *a = get_Not_op(n);
1734
1735   if (   (get_irn_mode(n) == mode_b)
1736       && (get_irn_op(a) == op_Proj)
1737       && (get_irn_mode(a) == mode_b)
1738       && (get_irn_op(get_Proj_pred(a)) == op_Cmp)) {
1739     /* We negate a Cmp. The Cmp has the negated result anyways! */
1740     n = new_r_Proj(current_ir_graph, get_nodes_block(n), get_Proj_pred(a),
1741                    mode_b, get_negated_pnc(get_Proj_proj(a)));
1742     DBG_OPT_ALGSIM0(oldn, n);
1743   }
1744
1745   return n;
1746 }
1747
1748 /**
1749  * Transform a Cast of a Const into a new Const
1750  */
1751 static ir_node *transform_node_Cast(ir_node *n) {
1752   ir_node *oldn = n;
1753   ir_node *pred = get_Cast_op(n);
1754   type *tp = get_irn_type(n);
1755
1756   if (get_irn_op(pred) == op_Const && get_Const_type(pred) != tp) {
1757     n = new_rd_Const_type(NULL, current_ir_graph, get_nodes_block(pred), get_irn_mode(pred),
1758               get_Const_tarval(pred), tp);
1759     DBG_OPT_CSTEVAL(oldn, n);
1760   } else if ((get_irn_op(pred) == op_SymConst) && (get_SymConst_value_type(pred) != tp)) {
1761     n = new_rd_SymConst_type(NULL, current_ir_graph, get_nodes_block(pred), get_SymConst_symbol(pred),
1762                  get_SymConst_kind(pred), tp);
1763     DBG_OPT_CSTEVAL(oldn, n);
1764   }
1765
1766   return n;
1767 }
1768
1769 /**
1770  * Transform a Proj(Div) with a non-zero constant.
1771  * Removes the exceptions and routes the memory to the NoMem node.
1772  */
1773 static ir_node *transform_node_Proj_Div(ir_node *proj)
1774 {
1775   ir_node *n = get_Proj_pred(proj);
1776   ir_node *b;
1777   tarval *tb;
1778   long proj_nr;
1779
1780   b  = get_Div_right(n);
1781   tb = value_of(b);
1782
1783   if (tb != tarval_bad && classify_tarval(tb) != TV_CLASSIFY_NULL) {
1784     /* div(x, c) && c != 0 */
1785     proj_nr = get_Proj_proj(proj);
1786
1787     /* this node may float */
1788     set_irn_pinned(n, op_pin_state_floats);
1789
1790     if (proj_nr == pn_Div_X_except) {
1791       /* we found an exception handler, remove it */
1792       return new_Bad();
1793     } else {
1794       /* the memory Proj can be removed */
1795       ir_node *res = get_Div_mem(n);
1796       set_Div_mem(n, get_irg_no_mem(current_ir_graph));
1797       if (proj_nr == pn_Div_M)
1798         return res;
1799     }
1800   }
1801   return proj;
1802 }
1803
1804 /**
1805  * Transform a Proj(Mod) with a non-zero constant.
1806  * Removes the exceptions and routes the memory to the NoMem node.
1807  */
1808 static ir_node *transform_node_Proj_Mod(ir_node *proj)
1809 {
1810   ir_node *n = get_Proj_pred(proj);
1811   ir_node *b;
1812   tarval *tb;
1813   long proj_nr;
1814
1815   b  = get_Mod_right(n);
1816   tb = value_of(b);
1817
1818   if (tb != tarval_bad && classify_tarval(tb) != TV_CLASSIFY_NULL) {
1819     /* mod(x, c) && c != 0 */
1820     proj_nr = get_Proj_proj(proj);
1821
1822     /* this node may float */
1823     set_irn_pinned(n, op_pin_state_floats);
1824
1825     if (proj_nr == pn_Mod_X_except) {
1826       /* we found an exception handler, remove it */
1827       return new_Bad();
1828     } else {
1829       /* the memory Proj can be removed */
1830       ir_node *res = get_Mod_mem(n);
1831       set_Mod_mem(n, get_irg_no_mem(current_ir_graph));
1832       if (proj_nr == pn_Mod_M)
1833         return res;
1834     }
1835   }
1836   return proj;
1837 }
1838
1839 /**
1840  * Transform a Proj(DivMod) with a non-zero constant.
1841  * Removes the exceptions and routes the memory to the NoMem node.
1842  */
1843 static ir_node *transform_node_Proj_DivMod(ir_node *proj)
1844 {
1845   ir_node *n = get_Proj_pred(proj);
1846   ir_node *b;
1847   tarval *tb;
1848   long proj_nr;
1849
1850   b  = get_DivMod_right(n);
1851   tb = value_of(b);
1852
1853   if (tb != tarval_bad && classify_tarval(tb) != TV_CLASSIFY_NULL) {
1854     /* DivMod(x, c) && c != 0 */
1855     proj_nr = get_Proj_proj(proj);
1856
1857     /* this node may float */
1858     set_irn_pinned(n, op_pin_state_floats);
1859
1860     if (proj_nr == pn_DivMod_X_except) {
1861       /* we found an exception handler, remove it */
1862       return new_Bad();
1863     }
1864     else {
1865       /* the memory Proj can be removed */
1866       ir_node *res = get_DivMod_mem(n);
1867       set_DivMod_mem(n, get_irg_no_mem(current_ir_graph));
1868       if (proj_nr == pn_DivMod_M)
1869         return res;
1870     }
1871   }
1872   return proj;
1873 }
1874
1875 /**
1876  * Optimizes jump tables (CondIs or CondIu) by removing all impossible cases.
1877  */
1878 static ir_node *transform_node_Proj_Cond(ir_node *proj)
1879 {
1880   if (get_opt_unreachable_code()) {
1881     ir_node *n = get_Proj_pred(proj);
1882     ir_node *b = get_Cond_selector(n);
1883     tarval *tb = value_of(b);
1884
1885     if (tb != tarval_bad && mode_is_int(get_tarval_mode(tb))) {
1886       /* we have a constant switch */
1887       long num = get_Proj_proj(proj);
1888
1889       if (num != get_Cond_defaultProj(n)) { /* we cannot optimize default Proj's yet */
1890         if (get_tarval_long(tb) == num) {
1891           /* Do NOT create a jump here, or we will have 2 control flow ops
1892            * in a block. This case is optimized away in optimize_cf(). */
1893           return proj;
1894         }
1895         else {
1896           /* this case will NEVER be taken, kill it */
1897           return new_Bad();
1898         }
1899       }
1900     }
1901   }
1902   return proj;
1903 }
1904
1905 /**
1906  * Normalizes and optimizes Cmp nodes.
1907  */
1908 static ir_node *transform_node_Proj_Cmp(ir_node *proj)
1909 {
1910   if (get_opt_reassociation()) {
1911     ir_node *n     = get_Proj_pred(proj);
1912     ir_node *left  = get_Cmp_left(n);
1913     ir_node *right = get_Cmp_right(n);
1914     ir_node *c     = NULL;
1915     tarval *tv     = NULL;
1916     int changed    = 0;
1917     ir_mode *mode  = NULL;
1918     long proj_nr   = get_Proj_proj(proj);
1919
1920     /*
1921      * First step: normalize the compare op
1922      * by placing the constant on the right site
1923      * or moving the lower address node to the left.
1924      * We ignore the case that both are constants
1925      * this case should be optimized away.
1926      */
1927     if (get_irn_op(right) == op_Const)
1928       c = right;
1929     else if (get_irn_op(left) == op_Const) {
1930       c     = left;
1931       left  = right;
1932       right = c;
1933
1934       proj_nr = get_swapped_pnc(proj_nr);
1935       changed |= 1;
1936     }
1937     else if (left > right) {
1938       ir_node *t = left;
1939
1940       left  = right;
1941       right = t;
1942
1943       proj_nr = get_swapped_pnc(proj_nr);
1944       changed |= 1;
1945     }
1946
1947     /*
1948      * Second step: Try to reduce the magnitude
1949      * of a constant. This may help to generate better code
1950      * later and may help to normalize more compares.
1951      * Of course this is only possible for integer values.
1952      */
1953     if (c) {
1954       mode = get_irn_mode(c);
1955       tv = get_Const_tarval(c);
1956
1957       if (tv != tarval_bad) {
1958         /* the following optimization is possible on modes without Overflow
1959          * on Unary Minus or on == and !=:
1960          * -a CMP c  ==>  a swap(CMP) -c
1961          *
1962          * Beware: for two-complement Overflow may occur, so only == and != can
1963          * be optimized, see this:
1964          * -MININT < 0 =/=> MININT > 0 !!!
1965          */
1966         if (get_opt_constant_folding() && get_irn_op(left) == op_Minus &&
1967             (!mode_overflow_on_unary_Minus(mode) ||
1968              (mode_is_int(mode) && (proj_nr == pn_Cmp_Eq || proj_nr == pn_Cmp_Lg)))) {
1969           left = get_Minus_op(left);
1970           tv = tarval_sub(get_mode_null(mode), tv);
1971
1972           proj_nr = get_swapped_pnc(proj_nr);
1973           changed |= 2;
1974         }
1975
1976         /* for integer modes, we have more */
1977         if (mode_is_int(mode)) {
1978           /* Ne includes Unordered which is not possible on integers.
1979            * However, frontends often use this wrong, so fix it here */
1980           if (proj_nr == pn_Cmp_Ne) {
1981             proj_nr = pn_Cmp_Lg;
1982             set_Proj_proj(proj, proj_nr);
1983           }
1984
1985           /* c > 0 : a < c  ==>  a <= (c-1)    a >= c  ==>  a > (c-1) */
1986           if ((proj_nr == pn_Cmp_Lt || proj_nr == pn_Cmp_Ge) &&
1987               tarval_cmp(tv, get_mode_null(mode)) == pn_Cmp_Gt) {
1988             tv = tarval_sub(tv, get_mode_one(mode));
1989
1990             proj_nr ^= pn_Cmp_Eq;
1991             changed |= 2;
1992           }
1993           /* c < 0 : a > c  ==>  a >= (c+1)    a <= c  ==>  a < (c+1) */
1994           else if ((proj_nr == pn_Cmp_Gt || proj_nr == pn_Cmp_Le) &&
1995               tarval_cmp(tv, get_mode_null(mode)) == pn_Cmp_Lt) {
1996             tv = tarval_add(tv, get_mode_one(mode));
1997
1998             proj_nr ^= pn_Cmp_Eq;
1999             changed |= 2;
2000           }
2001
2002           /* the following reassociations work only for == and != */
2003           if (proj_nr == pn_Cmp_Eq || proj_nr == pn_Cmp_Lg) {
2004
2005             /* a-b == 0  ==>  a == b,  a-b != 0  ==>  a != b */
2006             if (classify_tarval(tv) == TV_CLASSIFY_NULL && get_irn_op(left) == op_Sub) {
2007               right = get_Sub_right(left);
2008               left  = get_Sub_left(left);
2009
2010               tv = value_of(right);
2011               changed = 1;
2012             }
2013
2014             if (tv != tarval_bad) {
2015               ir_op *op = get_irn_op(left);
2016
2017               /* a-c1 == c2  ==>  a == c2+c1,  a-c1 != c2  ==>  a != c2+c1 */
2018               if (op == op_Sub) {
2019                 ir_node *c1 = get_Sub_right(left);
2020                 tarval *tv2 = value_of(c1);
2021
2022                 if (tv2 != tarval_bad) {
2023                   tv2 = tarval_add(tv, value_of(c1));
2024
2025                   if (tv2 != tarval_bad) {
2026                     left    = get_Sub_left(left);
2027                     tv      = tv2;
2028                     changed |= 2;
2029                   }
2030                 }
2031               }
2032               /* a+c1 == c2  ==>  a == c2-c1,  a+c1 != c2  ==>  a != c2-c1 */
2033               else if (op == op_Add) {
2034                 ir_node *a_l = get_Add_left(left);
2035                 ir_node *a_r = get_Add_right(left);
2036                 ir_node *a;
2037                 tarval *tv2;
2038
2039                 if (get_irn_op(a_l) == op_Const) {
2040                   a = a_r;
2041                   tv2 = value_of(a_l);
2042                 }
2043                 else {
2044                   a = a_l;
2045                   tv2 = value_of(a_r);
2046                 }
2047
2048                 if (tv2 != tarval_bad) {
2049                   tv2 = tarval_sub(tv, tv2);
2050
2051                   if (tv2 != tarval_bad) {
2052                     left    = a;
2053                     tv      = tv2;
2054                     changed |= 2;
2055                   }
2056                 }
2057               }
2058               /* -a == c ==> a == -c, -a != c ==> a != -c */
2059               else if (op == op_Minus) {
2060                 tarval *tv2 = tarval_sub(get_mode_null(mode), tv);
2061
2062                 if (tv2 != tarval_bad) {
2063                   left    = get_Minus_op(left);
2064                   tv      = tv2;
2065                   changed |= 2;
2066                 }
2067               }
2068             }
2069           } /* == or != */
2070           /* the following reassociations work only for <= */
2071           else if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2072             if (tv != tarval_bad) {
2073               ir_op *op = get_irn_op(left);
2074
2075               /* c >= 0 : Abs(a) <= c  ==>  (unsigned)(a + c) <= 2*c */
2076               if (op == op_Abs) {
2077               }
2078             }
2079           }
2080         } /* mode_is_int */
2081       }
2082     }
2083
2084     if (changed) {
2085       ir_node *block = get_nodes_block(n);
2086
2087       if (changed & 2)      /* need a new Const */
2088         right = new_Const(mode, tv);
2089
2090       /* create a new compare */
2091       n = new_rd_Cmp(get_irn_dbg_info(n), current_ir_graph, block,
2092             left, right);
2093
2094       set_Proj_pred(proj, n);
2095       set_Proj_proj(proj, proj_nr);
2096     }
2097   }
2098   return proj;
2099 }
2100
2101 /**
2102  * Does all optimizations on nodes that must be done on it's Proj's
2103  * because of creating new nodes.
2104  */
2105 static ir_node *transform_node_Proj(ir_node *proj)
2106 {
2107   ir_node *n = get_Proj_pred(proj);
2108
2109   switch (get_irn_opcode(n)) {
2110   case iro_Div:
2111     return transform_node_Proj_Div(proj);
2112
2113   case iro_Mod:
2114     return transform_node_Proj_Mod(proj);
2115
2116   case iro_DivMod:
2117     return transform_node_Proj_DivMod(proj);
2118
2119   case iro_Cond:
2120     return transform_node_Proj_Cond(proj);
2121
2122   case iro_Cmp:
2123     return transform_node_Proj_Cmp(proj);
2124
2125   case iro_Tuple:
2126     /* should not happen, but if it does will be optimized away */
2127     return equivalent_node_Proj(proj);
2128
2129   default:
2130     /* do nothing */
2131     return proj;
2132   }
2133 }
2134
2135 /**
2136  * returns the operands of a commutative bin-op, if one operand is
2137  * a const, it is returned as the second one.
2138  */
2139 static void get_comm_Binop_Ops(ir_node *binop, ir_node **a, ir_node **c)
2140 {
2141   ir_node *op_a = get_binop_left(binop);
2142   ir_node *op_b = get_binop_right(binop);
2143
2144   assert(is_op_commutative(get_irn_op(binop)));
2145
2146   if (get_irn_op(op_a) == op_Const) {
2147     *a = op_b;
2148     *c = op_a;
2149   }
2150   else {
2151     *a = op_a;
2152     *c = op_b;
2153   }
2154 }
2155
2156 /**
2157  * Optimize a Or(And(Or(And(v,c4),c3),c2),c1) pattern if possible.
2158  * Such pattern may arise in bitfield stores.
2159  *
2160  * value  c4                  value      c4 & c2
2161  *    AND     c3                    AND           c1 | c3
2162  *        OR     c2      ===>               OR
2163  *           AND    c1
2164  *               OR
2165  */
2166 static ir_node *transform_node_Or_bf_store(ir_node *or)
2167 {
2168   ir_node *and, *c1;
2169   ir_node *or_l, *c2;
2170   ir_node *and_l, *c3;
2171   ir_node *value, *c4;
2172   ir_node *new_and, *new_const, *block;
2173   ir_mode *mode = get_irn_mode(or);
2174
2175   tarval *tv1, *tv2, *tv3, *tv4, *tv, *n_tv4, *n_tv2;
2176
2177   get_comm_Binop_Ops(or, &and, &c1);
2178   if ((get_irn_op(c1) != op_Const) || (get_irn_op(and) != op_And))
2179     return or;
2180
2181   get_comm_Binop_Ops(and, &or_l, &c2);
2182   if ((get_irn_op(c2) != op_Const) || (get_irn_op(or_l) != op_Or))
2183     return or;
2184
2185   get_comm_Binop_Ops(or_l, &and_l, &c3);
2186   if ((get_irn_op(c3) != op_Const) || (get_irn_op(and_l) != op_And))
2187     return or;
2188
2189   get_comm_Binop_Ops(and_l, &value, &c4);
2190   if (get_irn_op(c4) != op_Const)
2191     return or;
2192
2193   /* ok, found the pattern, check for conditions */
2194   assert(mode == get_irn_mode(and));
2195   assert(mode == get_irn_mode(or_l));
2196   assert(mode == get_irn_mode(and_l));
2197
2198   tv1 = get_Const_tarval(c1);
2199   tv2 = get_Const_tarval(c2);
2200   tv3 = get_Const_tarval(c3);
2201   tv4 = get_Const_tarval(c4);
2202
2203   tv = tarval_or(tv4, tv2);
2204   if (classify_tarval(tv) != TV_CLASSIFY_ALL_ONE) {
2205     /* have at least one 0 at the same bit position */
2206     return or;
2207   }
2208
2209   n_tv4 = tarval_not(tv4);
2210   if (tv3 != tarval_and(tv3, n_tv4)) {
2211     /* bit in the or_mask is outside the and_mask */
2212     return or;
2213   }
2214
2215   n_tv2 = tarval_not(tv2);
2216   if (tv1 != tarval_and(tv1, n_tv2)) {
2217     /* bit in the or_mask is outside the and_mask */
2218     return or;
2219   }
2220
2221   /* ok, all conditions met */
2222   block = get_nodes_block(or);
2223
2224   new_and = new_r_And(current_ir_graph, block,
2225       value, new_r_Const(current_ir_graph, block, mode, tarval_and(tv4, tv2)), mode);
2226
2227   new_const = new_r_Const(current_ir_graph, block, mode, tarval_or(tv3, tv1));
2228
2229   set_Or_left(or, new_and);
2230   set_Or_right(or, new_const);
2231
2232   /* check for more */
2233   return transform_node_Or_bf_store(or);
2234 }
2235
2236 /**
2237  * Optimize an Or(shl(x, c), shr(x, bits - c)) into a Rot
2238  */
2239 static ir_node *transform_node_Or_Rot(ir_node *or)
2240 {
2241   ir_mode *mode = get_irn_mode(or);
2242   ir_node *shl, *shr, *block;
2243   ir_node *irn, *x, *c1, *c2, *v, *sub, *n;
2244   tarval *tv1, *tv2;
2245
2246   if (! mode_is_int(mode))
2247     return or;
2248
2249   shl = get_binop_left(or);
2250   shr = get_binop_right(or);
2251
2252   if (get_irn_op(shl) == op_Shr) {
2253     if (get_irn_op(shr) != op_Shl)
2254       return or;
2255
2256     irn = shl;
2257     shl = shr;
2258     shr = irn;
2259   }
2260   else if (get_irn_op(shl) != op_Shl)
2261     return or;
2262   else if (get_irn_op(shr) != op_Shr)
2263     return or;
2264
2265   x = get_Shl_left(shl);
2266   if (x != get_Shr_left(shr))
2267     return or;
2268
2269   c1 = get_Shl_right(shl);
2270   c2 = get_Shr_right(shr);
2271   if (get_irn_op(c1) == op_Const && get_irn_op(c2) == op_Const) {
2272     tv1 = get_Const_tarval(c1);
2273     if (! tarval_is_long(tv1))
2274       return or;
2275
2276     tv2 = get_Const_tarval(c2);
2277     if (! tarval_is_long(tv2))
2278       return or;
2279
2280     if (get_tarval_long(tv1) + get_tarval_long(tv2)
2281         != get_mode_size_bits(mode))
2282       return or;
2283
2284     /* yet, condition met */
2285     block = get_nodes_block(or);
2286
2287     n = new_r_Rot(current_ir_graph, block, x, c1, mode);
2288
2289     DBG_OPT_ALGSIM1(or, shl, shr, n);
2290     return n;
2291   }
2292   else if (get_irn_op(c1) == op_Sub) {
2293     v   = c2;
2294     sub = c1;
2295
2296     if (get_Sub_right(sub) != v)
2297       return or;
2298
2299     c1 = get_Sub_left(sub);
2300     if (get_irn_op(c1) != op_Const)
2301       return or;
2302
2303     tv1 = get_Const_tarval(c1);
2304     if (! tarval_is_long(tv1))
2305       return or;
2306
2307     if (get_tarval_long(tv1) != get_mode_size_bits(mode))
2308       return or;
2309
2310     /* yet, condition met */
2311     block = get_nodes_block(or);
2312
2313     /* a Rot right is not supported, so use a rot left */
2314     n =  new_r_Rot(current_ir_graph, block, x, sub, mode);
2315
2316     DBG_OPT_ALGSIM0(or, n);
2317     return n;
2318   }
2319   else if (get_irn_op(c2) == op_Sub) {
2320     v   = c1;
2321     sub = c2;
2322
2323     c1 = get_Sub_left(sub);
2324     if (get_irn_op(c1) != op_Const)
2325       return or;
2326
2327     tv1 = get_Const_tarval(c1);
2328     if (! tarval_is_long(tv1))
2329       return or;
2330
2331     if (get_tarval_long(tv1) != get_mode_size_bits(mode))
2332       return or;
2333
2334     /* yet, condition met */
2335     block = get_nodes_block(or);
2336
2337     /* a Rot Left */
2338     n = new_r_Rot(current_ir_graph, block, x, v, mode);
2339
2340     DBG_OPT_ALGSIM0(or, n);
2341     return n;
2342   }
2343
2344   return or;
2345 }
2346
2347 /**
2348  * Optimize an Or
2349  */
2350 static ir_node *transform_node_Or(ir_node *or)
2351 {
2352   or = transform_node_Or_bf_store(or);
2353   or = transform_node_Or_Rot(or);
2354
2355   return or;
2356 }
2357
2358 /* forward */
2359 static ir_node *transform_node(ir_node *n);
2360
2361 /**
2362  * Optimize (a >> c1) >> c2), works for Shr, Shrs, Shl
2363  */
2364 static ir_node *transform_node_shift(ir_node *n)
2365 {
2366   ir_node *left, *right;
2367   tarval *tv1, *tv2, *res;
2368   ir_mode *mode;
2369   int modulo_shf, flag;
2370
2371   left = get_binop_left(n);
2372
2373   /* different operations */
2374   if (get_irn_op(left) != get_irn_op(n))
2375     return n;
2376
2377   right = get_binop_right(n);
2378   tv1 = value_of(right);
2379   if (tv1 == tarval_bad)
2380     return n;
2381
2382   tv2 = value_of(get_binop_right(left));
2383   if (tv2 == tarval_bad)
2384     return n;
2385
2386   res = tarval_add(tv1, tv2);
2387
2388   /* beware: a simple replacement works only, if res < modulo shift */
2389   mode = get_irn_mode(n);
2390
2391   flag = 0;
2392
2393   modulo_shf = get_mode_modulo_shift(mode);
2394   if (modulo_shf > 0) {
2395     tarval *modulo = new_tarval_from_long(modulo_shf, get_tarval_mode(res));
2396
2397     if (tarval_cmp(res, modulo) & pn_Cmp_Lt)
2398       flag = 1;
2399   }
2400   else
2401     flag = 1;
2402
2403   if (flag) {
2404     /* ok, we can replace it */
2405     ir_node *in[2], *irn, *block = get_nodes_block(n);
2406
2407     in[0] = get_binop_left(left);
2408     in[1] = new_r_Const(current_ir_graph, block, get_tarval_mode(res), res);
2409
2410     irn = new_ir_node(NULL, current_ir_graph, block, get_irn_op(n), mode, 2, in);
2411
2412     DBG_OPT_ALGSIM0(n, irn);
2413
2414     return transform_node(irn);
2415   }
2416   return n;
2417 }
2418
2419 #define transform_node_Shr  transform_node_shift
2420 #define transform_node_Shrs transform_node_shift
2421 #define transform_node_Shl  transform_node_shift
2422
2423 /**
2424  * Remove dead blocks in keepalive list.  We do not generate a new End node.
2425  */
2426 static ir_node *transform_node_End(ir_node *n) {
2427   int i, n_keepalives = get_End_n_keepalives(n);
2428
2429   for (i = 0; i < n_keepalives; ++i) {
2430     ir_node *ka = get_End_keepalive(n, i);
2431     if (is_Block(ka) && is_Block_dead(ka))
2432       set_End_keepalive(n, i, new_Bad());
2433   }
2434   return n;
2435 }
2436
2437 /**
2438  * Optimize a Mux into some simplier cases.
2439  */
2440 static ir_node *transform_node_Mux(ir_node *n)
2441 {
2442   ir_node *oldn = n, *sel = get_Mux_sel(n);
2443   ir_mode *mode = get_irn_mode(n);
2444
2445   if (get_irn_op(sel) == op_Proj && !mode_honor_signed_zeros(mode)) {
2446     ir_node *cmp = get_Proj_pred(sel);
2447     long proj_nr = get_Proj_proj(sel);
2448     ir_node *f   =  get_Mux_false(n);
2449     ir_node *t   = get_Mux_true(n);
2450
2451     if (get_irn_op(cmp) == op_Cmp && classify_Const(get_Cmp_right(cmp)) == CNST_NULL) {
2452       ir_node *block = get_nodes_block(n);
2453
2454       /*
2455        * Note: normalization puts the constant on the right site,
2456        * so we check only one case.
2457        *
2458        * Note further that these optimization work even for floating point
2459        * with NaN's because -NaN == NaN.
2460        * However, if +0 and -0 is handled differently, we cannot use the first one.
2461        */
2462       if (get_irn_op(f) == op_Minus &&
2463           get_Minus_op(f)   == t &&
2464           get_Cmp_left(cmp) == t) {
2465
2466         if (proj_nr == pn_Cmp_Ge || proj_nr == pn_Cmp_Gt) {
2467           /* Mux(a >=/> 0, -a, a)  ==>  Abs(a) */
2468           n = new_rd_Abs(get_irn_dbg_info(n),
2469                 current_ir_graph,
2470                 block,
2471                 t, mode);
2472           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2473           return n;
2474         }
2475         else if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2476           /* Mux(a <=/< 0, -a, a)  ==>  Minus(Abs(a)) */
2477           n = new_rd_Abs(get_irn_dbg_info(n),
2478                 current_ir_graph,
2479                 block,
2480                 t, mode);
2481           n = new_rd_Minus(get_irn_dbg_info(n),
2482                 current_ir_graph,
2483                 block,
2484                 n, mode);
2485
2486           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2487           return n;
2488         }
2489       }
2490       else if (get_irn_op(t) == op_Minus &&
2491           get_Minus_op(t)   == f &&
2492           get_Cmp_left(cmp) == f) {
2493
2494         if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2495           /* Mux(a <=/< 0, a, -a)  ==>  Abs(a) */
2496           n = new_rd_Abs(get_irn_dbg_info(n),
2497                 current_ir_graph,
2498                 block,
2499                 f, mode);
2500           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2501           return n;
2502         }
2503         else if (proj_nr == pn_Cmp_Ge || proj_nr == pn_Cmp_Gt) {
2504           /* Mux(a >=/> 0, a, -a)  ==>  Minus(Abs(a)) */
2505           n = new_rd_Abs(get_irn_dbg_info(n),
2506                 current_ir_graph,
2507                 block,
2508                 f, mode);
2509           n = new_rd_Minus(get_irn_dbg_info(n),
2510                 current_ir_graph,
2511                 block,
2512                 n, mode);
2513
2514           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2515           return n;
2516         }
2517       }
2518
2519       if (mode_is_int(mode) && mode_is_signed(mode) &&
2520           get_mode_arithmetic(mode) == irma_twos_complement) {
2521         ir_node *x = get_Cmp_left(cmp);
2522
2523         /* the following optimization works only with signed integer two-complement mode */
2524
2525         if (mode == get_irn_mode(x)) {
2526           /*
2527            * FIXME: this restriction is two rigid, as it would still
2528            * work if mode(x) = Hs and mode == Is, but at least it removes
2529            * all wrong cases.
2530            */
2531           if ((proj_nr == pn_Cmp_Lt || proj_nr == pn_Cmp_Le) &&
2532               classify_Const(t) == CNST_ALL_ONE &&
2533               classify_Const(f) == CNST_NULL) {
2534             /*
2535              * Mux(x:T </<= 0, 0, -1) -> Shrs(x, sizeof_bits(T) - 1)
2536              * Conditions:
2537              * T must be signed.
2538              */
2539             n = new_rd_Shrs(get_irn_dbg_info(n),
2540                   current_ir_graph, block, x,
2541                   new_r_Const_long(current_ir_graph, block, mode_Iu,
2542                     get_mode_size_bits(mode) - 1),
2543                   mode);
2544             DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2545             return n;
2546           }
2547           else if ((proj_nr == pn_Cmp_Gt || proj_nr == pn_Cmp_Ge) &&
2548                    classify_Const(t) == CNST_ONE &&
2549                    classify_Const(f) == CNST_NULL) {
2550             /*
2551              * Mux(x:T >/>= 0, 0, 1) -> Shr(-x, sizeof_bits(T) - 1)
2552              * Conditions:
2553              * T must be signed.
2554              */
2555             n = new_rd_Shr(get_irn_dbg_info(n),
2556                   current_ir_graph, block,
2557                   new_r_Minus(current_ir_graph, block, x, mode),
2558                   new_r_Const_long(current_ir_graph, block, mode_Iu,
2559                     get_mode_size_bits(mode) - 1),
2560                   mode);
2561             DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2562             return n;
2563           }
2564         }
2565       }
2566     }
2567   }
2568   return arch_transform_node_Mux(n);
2569 }
2570
2571 /**
2572  * Tries several [inplace] [optimizing] transformations and returns an
2573  * equivalent node.  The difference to equivalent_node() is that these
2574  * transformations _do_ generate new nodes, and thus the old node must
2575  * not be freed even if the equivalent node isn't the old one.
2576  */
2577 static ir_node *transform_node(ir_node *n)
2578 {
2579   if (n->op->transform_node)
2580     n = n->op->transform_node(n);
2581   return n;
2582 }
2583
2584 /**
2585  * set the default transform node operation
2586  */
2587 static ir_op *firm_set_default_transform_node(ir_op *op)
2588 {
2589 #define CASE(a)                                 \
2590   case iro_##a:                                 \
2591     op->transform_node  = transform_node_##a;   \
2592     break
2593
2594   switch (op->code) {
2595   CASE(Add);
2596   CASE(Sub);
2597   CASE(Mul);
2598   CASE(Div);
2599   CASE(Mod);
2600   CASE(DivMod);
2601   CASE(Cond);
2602   CASE(Eor);
2603   CASE(Not);
2604   CASE(Cast);
2605   CASE(Proj);
2606   CASE(Sel);
2607   CASE(Or);
2608   CASE(Shr);
2609   CASE(Shrs);
2610   CASE(Shl);
2611   CASE(End);
2612   CASE(Mux);
2613   default:
2614     op->transform_node = NULL;
2615   }
2616
2617   return op;
2618 #undef CASE
2619 }
2620
2621
2622 /* **************** Common Subexpression Elimination **************** */
2623
2624 /** The size of the hash table used, should estimate the number of nodes
2625     in a graph. */
2626 #define N_IR_NODES 512
2627
2628 /** Compares the attributes of two Const nodes. */
2629 static int node_cmp_attr_Const(ir_node *a, ir_node *b)
2630 {
2631   return (get_Const_tarval(a) != get_Const_tarval(b))
2632       || (get_Const_type(a) != get_Const_type(b));
2633 }
2634
2635 /** Compares the attributes of two Proj nodes. */
2636 static int node_cmp_attr_Proj(ir_node *a, ir_node *b)
2637 {
2638     return get_irn_proj_attr (a) != get_irn_proj_attr (b);
2639 }
2640
2641 /** Compares the attributes of two Filter nodes. */
2642 static int node_cmp_attr_Filter(ir_node *a, ir_node *b)
2643 {
2644     return get_Filter_proj(a) != get_Filter_proj(b);
2645 }
2646
2647 /** Compares the attributes of two Alloc nodes. */
2648 static int node_cmp_attr_Alloc(ir_node *a, ir_node *b)
2649 {
2650     return (get_irn_alloc_attr(a).where != get_irn_alloc_attr(b).where)
2651         || (get_irn_alloc_attr(a).type != get_irn_alloc_attr(b).type);
2652 }
2653
2654 /** Compares the attributes of two Free nodes. */
2655 static int node_cmp_attr_Free(ir_node *a, ir_node *b)
2656 {
2657     return (get_irn_free_attr(a).where != get_irn_free_attr(b).where)
2658         || (get_irn_free_attr(a).type != get_irn_free_attr(b).type);
2659 }
2660
2661 /** Compares the attributes of two SymConst nodes. */
2662 static int node_cmp_attr_SymConst(ir_node *a, ir_node *b)
2663 {
2664     return (get_irn_symconst_attr(a).num != get_irn_symconst_attr(b).num)
2665       || (get_irn_symconst_attr(a).sym.type_p != get_irn_symconst_attr(b).sym.type_p)
2666       || (get_irn_symconst_attr(a).tp != get_irn_symconst_attr(b).tp);
2667 }
2668
2669 /** Compares the attributes of two Call nodes. */
2670 static int node_cmp_attr_Call(ir_node *a, ir_node *b)
2671 {
2672     return (get_irn_call_attr(a) != get_irn_call_attr(b));
2673 }
2674
2675 /** Compares the attributes of two Sel nodes. */
2676 static int node_cmp_attr_Sel(ir_node *a, ir_node *b)
2677 {
2678     return (get_irn_sel_attr(a).ent->kind  != get_irn_sel_attr(b).ent->kind)
2679       || (get_irn_sel_attr(a).ent->name    != get_irn_sel_attr(b).ent->name)
2680       || (get_irn_sel_attr(a).ent->owner   != get_irn_sel_attr(b).ent->owner)
2681       || (get_irn_sel_attr(a).ent->ld_name != get_irn_sel_attr(b).ent->ld_name)
2682       || (get_irn_sel_attr(a).ent->type    != get_irn_sel_attr(b).ent->type);
2683 }
2684
2685 /** Compares the attributes of two Phi nodes. */
2686 static int node_cmp_attr_Phi(ir_node *a, ir_node *b)
2687 {
2688     return get_irn_phi_attr (a) != get_irn_phi_attr (b);
2689 }
2690
2691 /** Compares the attributes of two Cast nodes. */
2692 static int node_cmp_attr_Cast(ir_node *a, ir_node *b)
2693 {
2694     return get_Cast_type(a) != get_Cast_type(b);
2695 }
2696
2697 /** Compares the attributes of two Load nodes. */
2698 static int node_cmp_attr_Load(ir_node *a, ir_node *b)
2699 {
2700   if (get_Load_volatility(a) == volatility_is_volatile ||
2701       get_Load_volatility(b) == volatility_is_volatile)
2702     /* NEVER do CSE on volatile Loads */
2703     return 1;
2704
2705   return get_Load_mode(a) != get_Load_mode(b);
2706 }
2707
2708 /** Compares the attributes of two Store nodes. */
2709 static int node_cmp_attr_Store(ir_node *a, ir_node *b)
2710 {
2711   /* NEVER do CSE on volatile Stores */
2712   return (get_Store_volatility(a) == volatility_is_volatile ||
2713       get_Store_volatility(b) == volatility_is_volatile);
2714 }
2715
2716 /**
2717  * set the default node attribute compare operation
2718  */
2719 static ir_op *firm_set_default_node_cmp_attr(ir_op *op)
2720 {
2721 #define CASE(a)                             \
2722   case iro_##a:                             \
2723     op->node_cmp_attr  = node_cmp_attr_##a; \
2724     break
2725
2726   switch (op->code) {
2727   CASE(Const);
2728   CASE(Proj);
2729   CASE(Filter);
2730   CASE(Alloc);
2731   CASE(Free);
2732   CASE(SymConst);
2733   CASE(Call);
2734   CASE(Sel);
2735   CASE(Phi);
2736   CASE(Cast);
2737   CASE(Load);
2738   CASE(Store);
2739   default:
2740     op->node_cmp_attr  = NULL;
2741   }
2742
2743   return op;
2744 #undef CASE
2745 }
2746
2747 /**
2748  * Compare function for two nodes in the hash table. Gets two
2749  * nodes as parameters.  Returns 0 if the nodes are a cse.
2750  */
2751 static int
2752 vt_cmp (const void *elt, const void *key)
2753 {
2754   ir_node *a, *b;
2755   int i, irn_arity_a;
2756
2757   a = (void *)elt;
2758   b = (void *)key;
2759
2760   if (a == b) return 0;
2761
2762   if ((get_irn_op(a) != get_irn_op(b)) ||
2763       (get_irn_mode(a) != get_irn_mode(b))) return 1;
2764
2765   /* compare if a's in and b's in are of equal length */
2766   irn_arity_a = get_irn_intra_arity (a);
2767   if (irn_arity_a != get_irn_intra_arity(b))
2768     return 1;
2769
2770   /* for block-local cse and op_pin_state_pinned nodes: */
2771   if (!get_opt_global_cse() || (get_irn_pinned(a) == op_pin_state_pinned)) {
2772     if (get_irn_intra_n(a, -1) != get_irn_intra_n(b, -1))
2773       return 1;
2774   }
2775
2776   /* compare a->in[0..ins] with b->in[0..ins] */
2777   for (i = 0; i < irn_arity_a; i++)
2778     if (get_irn_intra_n(a, i) != get_irn_intra_n(b, i))
2779       return 1;
2780
2781   /*
2782    * here, we already now that the nodes are identical except their
2783    * attributes
2784    */
2785   if (a->op->node_cmp_attr)
2786     return a->op->node_cmp_attr(a, b);
2787
2788   return 0;
2789 }
2790
2791 /*
2792  * Calculate a hash value of a node.
2793  */
2794 unsigned
2795 ir_node_hash (ir_node *node)
2796 {
2797   unsigned h;
2798   int i, irn_arity;
2799
2800   if (node->op == op_Const) {
2801     /* special value for const, as they only differ in their tarval. */
2802     h = HASH_PTR(node->attr.con.tv);
2803     h = 9*h + HASH_PTR(get_irn_mode(node));
2804   } else if (node->op == op_SymConst) {
2805     /* special value for const, as they only differ in their symbol. */
2806     h = HASH_PTR(node->attr.i.sym.type_p);
2807     h = 9*h + HASH_PTR(get_irn_mode(node));
2808   } else {
2809
2810     /* hash table value = 9*(9*(9*(9*(9*arity+in[0])+in[1])+ ...)+mode)+code */
2811     h = irn_arity = get_irn_intra_arity(node);
2812
2813     /* consider all in nodes... except the block if not a control flow. */
2814     for (i =  is_cfop(node) ? -1 : 0;  i < irn_arity;  i++) {
2815       h = 9*h + HASH_PTR(get_irn_intra_n(node, i));
2816     }
2817
2818     /* ...mode,... */
2819     h = 9*h + HASH_PTR(get_irn_mode(node));
2820     /* ...and code */
2821     h = 9*h + HASH_PTR(get_irn_op(node));
2822   }
2823
2824   return h;
2825 }
2826
2827 pset *
2828 new_identities(void) {
2829   return new_pset(vt_cmp, N_IR_NODES);
2830 }
2831
2832 void
2833 del_identities(pset *value_table) {
2834   del_pset(value_table);
2835 }
2836
2837 /**
2838  * Return the canonical node computing the same value as n.
2839  * Looks up the node in a hash table.
2840  *
2841  * For Const nodes this is performed in the constructor, too.  Const
2842  * nodes are extremely time critical because of their frequent use in
2843  * constant string arrays.
2844  */
2845 static INLINE ir_node *
2846 identify (pset *value_table, ir_node *n)
2847 {
2848   ir_node *o = NULL;
2849
2850   if (!value_table) return n;
2851
2852   if (get_opt_reassociation()) {
2853     if (is_op_commutative(get_irn_op(n))) {
2854       ir_node *l = get_binop_left(n);
2855       ir_node *r = get_binop_right(n);
2856
2857       /* for commutative operators perform  a OP b == b OP a */
2858       if (l > r) {
2859         set_binop_left(n, r);
2860         set_binop_right(n, l);
2861       }
2862     }
2863   }
2864
2865   o = pset_find (value_table, n, ir_node_hash (n));
2866   if (!o) return n;
2867
2868   DBG_OPT_CSE(n, o);
2869
2870   return o;
2871 }
2872
2873 /**
2874  * During construction we set the op_pin_state_pinned flag in the graph right when the
2875  * optimization is performed.  The flag turning on procedure global cse could
2876  * be changed between two allocations.  This way we are safe.
2877  */
2878 static INLINE ir_node *
2879 identify_cons (pset *value_table, ir_node *n) {
2880   ir_node *old = n;
2881
2882   n = identify(value_table, n);
2883   if (get_irn_n(old, -1) != get_irn_n(n, -1))
2884     set_irg_pinned(current_ir_graph, op_pin_state_floats);
2885   return n;
2886 }
2887
2888 /**
2889  * Return the canonical node computing the same value as n.
2890  * Looks up the node in a hash table, enters it in the table
2891  * if it isn't there yet.
2892  */
2893 static ir_node *
2894 identify_remember (pset *value_table, ir_node *n)
2895 {
2896   ir_node *o = NULL;
2897
2898   if (!value_table) return n;
2899
2900   if (get_opt_reassociation()) {
2901     if (is_op_commutative(get_irn_op(n))) {
2902       ir_node *l = get_binop_left(n);
2903       ir_node *r = get_binop_right(n);
2904
2905       /* for commutative operators perform  a OP b == b OP a */
2906       if (l > r) {
2907         set_binop_left(n, r);
2908         set_binop_right(n, l);
2909       }
2910     }
2911   }
2912
2913   /* lookup or insert in hash table with given hash key. */
2914   o = pset_insert (value_table, n, ir_node_hash (n));
2915
2916   if (o != n) {
2917     DBG_OPT_CSE(n, o);
2918   }
2919
2920   return o;
2921 }
2922
2923 void
2924 add_identities (pset *value_table, ir_node *node) {
2925   if (get_opt_cse() && (get_irn_opcode(node) != iro_Block))
2926     identify_remember (value_table, node);
2927 }
2928
2929 /**
2930  * garbage in, garbage out. If a node has a dead input, i.e., the
2931  * Bad node is input to the node, return the Bad node.
2932  */
2933 static INLINE ir_node *
2934 gigo (ir_node *node)
2935 {
2936   int i, irn_arity;
2937   ir_op* op = get_irn_op(node);
2938
2939   /* remove garbage blocks by looking at control flow that leaves the block
2940      and replacing the control flow by Bad. */
2941   if (get_irn_mode(node) == mode_X) {
2942     ir_node *block = get_nodes_block(node);
2943     if (!get_Block_matured(block)) return node;  /* Don't optimize nodes in immature blocks. */
2944     if (op == op_End) return node;     /* Don't optimize End, may have Bads. */
2945
2946     if (get_irn_op(block) == op_Block && get_Block_matured(block)) {
2947       irn_arity = get_irn_arity(block);
2948       for (i = 0; i < irn_arity; i++) {
2949         if (!is_Bad(get_irn_n(block, i))) break;
2950       }
2951       if (i == irn_arity) return new_Bad();
2952     }
2953   }
2954
2955   /* Blocks, Phis and Tuples may have dead inputs, e.g., if one of the
2956      blocks predecessors is dead. */
2957   if ( op != op_Block && op != op_Phi && op != op_Tuple) {
2958     irn_arity = get_irn_arity(node);
2959
2960     if (is_Block_dead(get_nodes_block(node)))
2961       return new_Bad();
2962
2963     for (i = 0; i < irn_arity; i++) {
2964       if (is_Bad(get_irn_n(node, i))) {
2965         return new_Bad();
2966       }
2967     }
2968   }
2969 #if 0
2970   /* With this code we violate the agreement that local_optimize
2971      only leaves Bads in Block, Phi and Tuple nodes. */
2972   /* If Block has only Bads as predecessors it's garbage. */
2973   /* If Phi has only Bads as predecessors it's garbage. */
2974   if ((op == op_Block && get_Block_matured(node)) || op == op_Phi)  {
2975     irn_arity = get_irn_arity(node);
2976     for (i = 0; i < irn_arity; i++) {
2977       if (!is_Bad(get_irn_n(node, i))) break;
2978     }
2979     if (i == irn_arity) node = new_Bad();
2980   }
2981 #endif
2982   return node;
2983 }
2984
2985
2986 /**
2987  * These optimizations deallocate nodes from the obstack.
2988  * It can only be called if it is guaranteed that no other nodes
2989  * reference this one, i.e., right after construction of a node.
2990  */
2991 ir_node *
2992 optimize_node (ir_node *n)
2993 {
2994         tarval *tv;
2995         ir_node *oldn = n;
2996         opcode iro = get_irn_opcode(n);
2997
2998         type *old_tp = get_irn_type(n);
2999         {
3000                 int i, arity = get_irn_arity(n);
3001                 for (i = 0; i < arity && !old_tp; ++i)
3002                         old_tp = get_irn_type(get_irn_n(n, i));
3003         }
3004
3005         /* Always optimize Phi nodes: part of the construction. */
3006         if ((!get_opt_optimize()) && (iro != iro_Phi)) return n;
3007
3008         /* constant expression evaluation / constant folding */
3009         if (get_opt_constant_folding()) {
3010                 /* constants can not be evaluated */
3011                 if (iro != iro_Const) {
3012                         /* try to evaluate */
3013                         tv = computed_value(n);
3014                         if ((get_irn_mode(n) != mode_T) && (tv != tarval_bad)) {
3015                                 ir_node *nw;
3016
3017                                 /*
3018                                  * we MUST copy the node here temporary, because it's still needed
3019                                  * for DBG_OPT_CSTEVAL
3020                                  */
3021                                 int node_size = offsetof(ir_node, attr) +  n->op->attr_size;
3022                                 oldn = alloca(node_size);
3023
3024                                 memcpy(oldn, n, node_size);
3025                                 CLONE_ARR_A(ir_node *, oldn->in, n->in);
3026
3027                                 /* ARG, copy the in array, we need it for statistics */
3028                                 memcpy(oldn->in, n->in, ARR_LEN(n->in) * sizeof(n->in[0]));
3029
3030
3031                                 edges_node_deleted(n, current_ir_graph);
3032
3033                                 /* evaluation was successful -- replace the node. */
3034                                 obstack_free (current_ir_graph->obst, n);
3035                                 nw = new_Const (get_tarval_mode (tv), tv);
3036
3037                                 if (old_tp && get_type_mode(old_tp) == get_tarval_mode (tv))
3038                                         set_Const_type(nw, old_tp);
3039                                 DBG_OPT_CSTEVAL(oldn, nw);
3040                                 return nw;
3041                         }
3042                 }
3043         }
3044
3045         /* remove unnecessary nodes */
3046         if (get_opt_constant_folding() ||
3047                         (iro == iro_Phi)  ||   /* always optimize these nodes. */
3048                         (iro == iro_Id)   ||
3049                         (iro == iro_Proj) ||
3050                         (iro == iro_Block)  )  /* Flags tested local. */
3051                 n = equivalent_node (n);
3052
3053         optimize_preds(n);                  /* do node specific optimizations of nodes predecessors. */
3054
3055         /** common subexpression elimination **/
3056         /* Checks whether n is already available. */
3057         /* The block input is used to distinguish different subexpressions. Right
3058                  now all nodes are op_pin_state_pinned to blocks, i.e., the cse only finds common
3059                  subexpressions within a block. */
3060         if (get_opt_cse())
3061                 n = identify_cons (current_ir_graph->value_table, n);
3062
3063         if (n != oldn) {
3064                 edges_node_deleted(oldn, current_ir_graph);
3065
3066                 /* We found an existing, better node, so we can deallocate the old node. */
3067                 obstack_free (current_ir_graph->obst, oldn);
3068
3069                 return n;
3070         }
3071
3072         /* Some more constant expression evaluation that does not allow to
3073                  free the node. */
3074         iro = get_irn_opcode(n);
3075         if (get_opt_constant_folding() ||
3076             (iro == iro_Cond) ||
3077             (iro == iro_Proj) ||
3078             (iro == iro_Sel))     /* Flags tested local. */
3079           n = transform_node (n);
3080
3081         /* Remove nodes with dead (Bad) input.
3082            Run always for transformation induced Bads. */
3083         n = gigo (n);
3084
3085         /* Now we have a legal, useful node. Enter it in hash table for cse */
3086         if (get_opt_cse() && (get_irn_opcode(n) != iro_Block)) {
3087           n = identify_remember (current_ir_graph->value_table, n);
3088         }
3089
3090         return n;
3091 }
3092
3093
3094 /**
3095  * These optimizations never deallocate nodes (in place).  This can cause dead
3096  * nodes lying on the obstack.  Remove these by a dead node elimination,
3097  * i.e., a copying garbage collection.
3098  */
3099 ir_node *
3100 optimize_in_place_2 (ir_node *n)
3101 {
3102   tarval *tv;
3103   ir_node *oldn = n;
3104   opcode iro = get_irn_opcode(n);
3105
3106   type *old_tp = get_irn_type(n);
3107   {
3108     int i, arity = get_irn_arity(n);
3109     for (i = 0; i < arity && !old_tp; ++i)
3110       old_tp = get_irn_type(get_irn_n(n, i));
3111   }
3112
3113   if (!get_opt_optimize() && (get_irn_op(n) != op_Phi)) return n;
3114
3115   /* if not optimize return n */
3116   if (n == NULL) {
3117     assert(0);
3118     /* Here this is possible.  Why? */
3119     return n;
3120   }
3121
3122   /* constant expression evaluation / constant folding */
3123   if (get_opt_constant_folding()) {
3124     /* constants can not be evaluated */
3125     if (iro != iro_Const) {
3126       /* try to evaluate */
3127       tv = computed_value(n);
3128       if ((get_irn_mode(n) != mode_T) && (tv != tarval_bad)) {
3129         /* evaluation was successful -- replace the node. */
3130         n = new_Const (get_tarval_mode (tv), tv);
3131
3132     if (old_tp && get_type_mode(old_tp) == get_tarval_mode (tv))
3133       set_Const_type(n, old_tp);
3134
3135         DBG_OPT_CSTEVAL(oldn, n);
3136         return n;
3137       }
3138     }
3139   }
3140
3141   /* remove unnecessary nodes */
3142   if (get_opt_constant_folding() ||
3143       (iro == iro_Phi)  ||   /* always optimize these nodes. */
3144       (iro == iro_Id)   ||   /* ... */
3145       (iro == iro_Proj) ||   /* ... */
3146       (iro == iro_Block)  )  /* Flags tested local. */
3147     n = equivalent_node (n);
3148
3149   optimize_preds(n);                  /* do node specific optimizations of nodes predecessors. */
3150
3151   /** common subexpression elimination **/
3152   /* Checks whether n is already available. */
3153   /* The block input is used to distinguish different subexpressions.  Right
3154      now all nodes are op_pin_state_pinned to blocks, i.e., the cse only finds common
3155      subexpressions within a block. */
3156   if (get_opt_cse()) {
3157     n = identify (current_ir_graph->value_table, n);
3158   }
3159
3160   /* Some more constant expression evaluation. */
3161   iro = get_irn_opcode(n);
3162   if (get_opt_constant_folding() ||
3163       (iro == iro_Cond) ||
3164       (iro == iro_Proj) ||
3165       (iro == iro_Sel))     /* Flags tested local. */
3166     n = transform_node (n);
3167
3168   /* Remove nodes with dead (Bad) input.
3169      Run always for transformation induced Bads.  */
3170   n = gigo (n);
3171
3172   /* Now we can verify the node, as it has no dead inputs any more. */
3173   irn_vrfy(n);
3174
3175   /* Now we have a legal, useful node. Enter it in hash table for cse.
3176      Blocks should be unique anyways.  (Except the successor of start:
3177      is cse with the start block!) */
3178   if (get_opt_cse() && (get_irn_opcode(n) != iro_Block))
3179     n = identify_remember (current_ir_graph->value_table, n);
3180
3181   return n;
3182 }
3183
3184 /**
3185  * Wrapper for external use, set proper status bits after optimization.
3186  */
3187 ir_node *
3188 optimize_in_place (ir_node *n)
3189 {
3190   /* Handle graph state */
3191   assert(get_irg_phase_state(current_ir_graph) != phase_building);
3192
3193   if (get_opt_global_cse())
3194     set_irg_pinned(current_ir_graph, op_pin_state_floats);
3195   if (get_irg_outs_state(current_ir_graph) == outs_consistent)
3196     set_irg_outs_inconsistent(current_ir_graph);
3197
3198   /* Maybe we could also test whether optimizing the node can
3199      change the control graph. */
3200   if (get_irg_dom_state(current_ir_graph) == dom_consistent)
3201     set_irg_dom_inconsistent(current_ir_graph);
3202   return optimize_in_place_2 (n);
3203 }
3204
3205 /**
3206  * set the default ir op operations
3207  */
3208 ir_op *firm_set_default_operations(ir_op *op)
3209 {
3210   op = firm_set_default_computed_value(op);
3211   op = firm_set_default_equivalent_node(op);
3212   op = firm_set_default_transform_node(op);
3213   op = firm_set_default_node_cmp_attr(op);
3214   op = firm_set_default_get_type(op);
3215
3216   return op;
3217 }