c1_Canonicalizer.cpp revision 0:a61af66fc99e
1125410Sgrehan/*
2125410Sgrehan * Copyright 1999-2006 Sun Microsystems, Inc.  All Rights Reserved.
3125410Sgrehan * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4125410Sgrehan *
5125410Sgrehan * This code is free software; you can redistribute it and/or modify it
6125410Sgrehan * under the terms of the GNU General Public License version 2 only, as
7125410Sgrehan * published by the Free Software Foundation.
8125410Sgrehan *
9125410Sgrehan * This code is distributed in the hope that it will be useful, but WITHOUT
10125410Sgrehan * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11125410Sgrehan * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12125410Sgrehan * version 2 for more details (a copy is included in the LICENSE file that
13125410Sgrehan * accompanied this code).
14125410Sgrehan *
15125410Sgrehan * You should have received a copy of the GNU General Public License version
16125410Sgrehan * 2 along with this work; if not, write to the Free Software Foundation,
17125410Sgrehan * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18125410Sgrehan *
19125410Sgrehan * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20125410Sgrehan * CA 95054 USA or visit www.sun.com if you need additional information or
21125410Sgrehan * have any questions.
22125410Sgrehan *
23125410Sgrehan */
24125410Sgrehan
25125410Sgrehan#include "incls/_precompiled.incl"
26125410Sgrehan#include "incls/_c1_Canonicalizer.cpp.incl"
27125410Sgrehan
28125410Sgrehan
29125410Sgrehanstatic void do_print_value(Value* vp) {
30125410Sgrehan  (*vp)->print_line();
31125410Sgrehan}
32125410Sgrehan
33125410Sgrehanvoid Canonicalizer::set_canonical(Value x) {
34125410Sgrehan  assert(x != NULL, "value must exist");
35125410Sgrehan  // Note: we can not currently substitute root nodes which show up in
36125410Sgrehan  // the instruction stream (because the instruction list is embedded
37125410Sgrehan  // in the instructions).
38125410Sgrehan  if (canonical() != x) {
39125410Sgrehan    if (PrintCanonicalization) {
40125410Sgrehan      canonical()->input_values_do(do_print_value);
41125410Sgrehan      canonical()->print_line();
42125410Sgrehan      tty->print_cr("canonicalized to:");
43125410Sgrehan      x->input_values_do(do_print_value);
44170088Sdougb      x->print_line();
45125410Sgrehan      tty->cr();
46125410Sgrehan    }
47166250Smarcel    assert(_canonical->type()->tag() == x->type()->tag(), "types must match");
48166250Smarcel    _canonical = x;
49166250Smarcel  }
50166250Smarcel}
51125410Sgrehan
52125410Sgrehan
53125410Sgrehanvoid Canonicalizer::move_const_to_right(Op2* x) {
54125410Sgrehan  if (x->x()->type()->is_constant() && x->is_commutative()) x->swap_operands();
55125410Sgrehan}
56125410Sgrehan
57125410Sgrehan
58125410Sgrehanvoid Canonicalizer::do_Op2(Op2* x) {
59125410Sgrehan  if (x->x() == x->y()) {
60125410Sgrehan    switch (x->op()) {
61125410Sgrehan    case Bytecodes::_isub: set_constant(0); return;
62125410Sgrehan    case Bytecodes::_lsub: set_constant(jlong_cast(0)); return;
63125410Sgrehan    case Bytecodes::_iand: // fall through
64125410Sgrehan    case Bytecodes::_land: // fall through
65125410Sgrehan    case Bytecodes::_ior:  // fall through
66125410Sgrehan    case Bytecodes::_lor : set_canonical(x->x()); return;
67125410Sgrehan    case Bytecodes::_ixor: set_constant(0); return;
68125410Sgrehan    case Bytecodes::_lxor: set_constant(jlong_cast(0)); return;
69125410Sgrehan    }
70125410Sgrehan  }
71125410Sgrehan
72125410Sgrehan  if (x->x()->type()->is_constant() && x->y()->type()->is_constant()) {
73125410Sgrehan    // do constant folding for selected operations
74125410Sgrehan    switch (x->type()->tag()) {
75125410Sgrehan      case intTag:
76125410Sgrehan        { jint a = x->x()->type()->as_IntConstant()->value();
77125410Sgrehan          jint b = x->y()->type()->as_IntConstant()->value();
78125410Sgrehan          switch (x->op()) {
79125410Sgrehan            case Bytecodes::_iadd: set_constant(a + b); return;
80125410Sgrehan            case Bytecodes::_isub: set_constant(a - b); return;
81125410Sgrehan            case Bytecodes::_imul: set_constant(a * b); return;
82125410Sgrehan            case Bytecodes::_idiv:
83125410Sgrehan              if (b != 0) {
84125410Sgrehan                if (a == min_jint && b == -1) {
85125410Sgrehan                  set_constant(min_jint);
86125410Sgrehan                } else {
87125410Sgrehan                  set_constant(a / b);
88125410Sgrehan                }
89125410Sgrehan                return;
90125410Sgrehan              }
91125410Sgrehan              break;
92125410Sgrehan            case Bytecodes::_irem:
93125410Sgrehan              if (b != 0) {
94125410Sgrehan                if (a == min_jint && b == -1) {
95125410Sgrehan                  set_constant(0);
96125410Sgrehan                } else {
97125410Sgrehan                  set_constant(a % b);
98125410Sgrehan                }
99125410Sgrehan                return;
100125410Sgrehan              }
101125410Sgrehan              break;
102125410Sgrehan            case Bytecodes::_iand: set_constant(a & b); return;
103125410Sgrehan            case Bytecodes::_ior : set_constant(a | b); return;
104125410Sgrehan            case Bytecodes::_ixor: set_constant(a ^ b); return;
105125410Sgrehan          }
106125410Sgrehan        }
107125410Sgrehan        break;
108125410Sgrehan      case longTag:
109125410Sgrehan        { jlong a = x->x()->type()->as_LongConstant()->value();
110125410Sgrehan          jlong b = x->y()->type()->as_LongConstant()->value();
111125410Sgrehan          switch (x->op()) {
112125410Sgrehan            case Bytecodes::_ladd: set_constant(a + b); return;
113125410Sgrehan            case Bytecodes::_lsub: set_constant(a - b); return;
114125410Sgrehan            case Bytecodes::_lmul: set_constant(a * b); return;
115125410Sgrehan            case Bytecodes::_ldiv:
116125410Sgrehan              if (b != 0) {
117125410Sgrehan                set_constant(SharedRuntime::ldiv(b, a));
118125410Sgrehan                return;
119125410Sgrehan              }
120125410Sgrehan              break;
121125410Sgrehan            case Bytecodes::_lrem:
122125410Sgrehan              if (b != 0) {
123125410Sgrehan                set_constant(SharedRuntime::lrem(b, a));
124125410Sgrehan                return;
125125410Sgrehan              }
126125410Sgrehan              break;
127125410Sgrehan            case Bytecodes::_land: set_constant(a & b); return;
128125410Sgrehan            case Bytecodes::_lor : set_constant(a | b); return;
129125410Sgrehan            case Bytecodes::_lxor: set_constant(a ^ b); return;
130125410Sgrehan          }
131125410Sgrehan        }
132125410Sgrehan        break;
133125410Sgrehan      // other cases not implemented (must be extremely careful with floats & doubles!)
134125410Sgrehan    }
135125410Sgrehan  }
136125410Sgrehan  // make sure constant is on the right side, if any
137125410Sgrehan  move_const_to_right(x);
138125410Sgrehan
139125410Sgrehan  if (x->y()->type()->is_constant()) {
140125410Sgrehan    // do constant folding for selected operations
141125410Sgrehan    switch (x->type()->tag()) {
142125410Sgrehan      case intTag:
143125410Sgrehan        if (x->y()->type()->as_IntConstant()->value() == 0) {
144125410Sgrehan          switch (x->op()) {
145125410Sgrehan            case Bytecodes::_iadd: set_canonical(x->x()); return;
146125410Sgrehan            case Bytecodes::_isub: set_canonical(x->x()); return;
147125410Sgrehan            case Bytecodes::_imul: set_constant(0); return;
148125410Sgrehan              // Note: for div and rem, make sure that C semantics
149125410Sgrehan              //       corresponds to Java semantics!
150125410Sgrehan            case Bytecodes::_iand: set_constant(0); return;
151125410Sgrehan            case Bytecodes::_ior : set_canonical(x->x()); return;
152125410Sgrehan          }
153125410Sgrehan        }
154125410Sgrehan        break;
155125410Sgrehan      case longTag:
156125410Sgrehan        if (x->y()->type()->as_LongConstant()->value() == (jlong)0) {
157125410Sgrehan          switch (x->op()) {
158125410Sgrehan            case Bytecodes::_ladd: set_canonical(x->x()); return;
159125410Sgrehan            case Bytecodes::_lsub: set_canonical(x->x()); return;
160125410Sgrehan            case Bytecodes::_lmul: set_constant((jlong)0); return;
161125410Sgrehan              // Note: for div and rem, make sure that C semantics
162125410Sgrehan              //       corresponds to Java semantics!
163125410Sgrehan            case Bytecodes::_land: set_constant((jlong)0); return;
164125410Sgrehan            case Bytecodes::_lor : set_canonical(x->x()); return;
165125410Sgrehan          }
166125410Sgrehan        }
167125410Sgrehan        break;
168125410Sgrehan    }
169125410Sgrehan  }
170125410Sgrehan}
171125410Sgrehan
172125410Sgrehan
173125410Sgrehanvoid Canonicalizer::do_Phi            (Phi*             x) {}
174125410Sgrehanvoid Canonicalizer::do_Constant       (Constant*        x) {}
175125410Sgrehanvoid Canonicalizer::do_Local          (Local*           x) {}
176125410Sgrehanvoid Canonicalizer::do_LoadField      (LoadField*       x) {}
177125410Sgrehan
178125410Sgrehan// checks if v is in the block that is currently processed by
179125410Sgrehan// GraphBuilder. This is the only block that has not BlockEnd yet.
180125410Sgrehanstatic bool in_current_block(Value v) {
181125410Sgrehan  int max_distance = 4;
182125410Sgrehan  while (max_distance > 0 && v != NULL && v->as_BlockEnd() == NULL) {
183125410Sgrehan    v = v->next();
184125410Sgrehan    max_distance--;
185125410Sgrehan  }
186125410Sgrehan  return v == NULL;
187125410Sgrehan}
188125410Sgrehan
189125410Sgrehanvoid Canonicalizer::do_StoreField     (StoreField*      x) {
190125410Sgrehan  // If a value is going to be stored into a field or array some of
191125410Sgrehan  // the conversions emitted by javac are unneeded because the fields
192125410Sgrehan  // are packed to their natural size.
193125410Sgrehan  Convert* conv = x->value()->as_Convert();
194125410Sgrehan  if (conv) {
195125410Sgrehan    Value value = NULL;
196125410Sgrehan    BasicType type = x->field()->type()->basic_type();
197125410Sgrehan    switch (conv->op()) {
198125410Sgrehan    case Bytecodes::_i2b: if (type == T_BYTE)  value = conv->value(); break;
199125410Sgrehan    case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) value = conv->value(); break;
200125410Sgrehan    case Bytecodes::_i2c: if (type == T_CHAR  || type == T_BYTE)  value = conv->value(); break;
201125410Sgrehan    }
202125410Sgrehan    // limit this optimization to current block
203125410Sgrehan    if (value != NULL && in_current_block(conv)) {
204125410Sgrehan      set_canonical(new StoreField(x->obj(), x->offset(), x->field(), value, x->is_static(),
205125410Sgrehan                                   x->lock_stack(), x->state_before(), x->is_loaded(), x->is_initialized()));
206125410Sgrehan      return;
207125410Sgrehan    }
208125410Sgrehan  }
209125410Sgrehan
210125410Sgrehan}
211125410Sgrehan
212125410Sgrehanvoid Canonicalizer::do_ArrayLength    (ArrayLength*     x) {
213125410Sgrehan  NewArray* array = x->array()->as_NewArray();
214125410Sgrehan  if (array != NULL && array->length() != NULL) {
215125410Sgrehan    Constant* length = array->length()->as_Constant();
216125410Sgrehan    if (length != NULL) {
217125410Sgrehan      // do not use the Constant itself, but create a new Constant
218125410Sgrehan      // with same value Otherwise a Constant is live over multiple
219125410Sgrehan      // blocks without being registered in a state array.
220125410Sgrehan      assert(length->type()->as_IntConstant() != NULL, "array length must be integer");
221125410Sgrehan      set_constant(length->type()->as_IntConstant()->value());
222125410Sgrehan    }
223125410Sgrehan  } else {
224125410Sgrehan    LoadField* lf = x->array()->as_LoadField();
225125410Sgrehan    if (lf != NULL && lf->field()->is_constant()) {
226125410Sgrehan      ciObject* c = lf->field()->constant_value().as_object();
227125410Sgrehan      if (c->is_array()) {
228125410Sgrehan        ciArray* array = (ciArray*) c;
229125410Sgrehan        set_constant(array->length());
230125410Sgrehan      }
231125410Sgrehan    }
232125410Sgrehan  }
233125410Sgrehan}
234125410Sgrehan
235125410Sgrehanvoid Canonicalizer::do_LoadIndexed    (LoadIndexed*     x) {}
236125410Sgrehanvoid Canonicalizer::do_StoreIndexed   (StoreIndexed*    x) {
237125410Sgrehan  // If a value is going to be stored into a field or array some of
238125410Sgrehan  // the conversions emitted by javac are unneeded because the fields
239125410Sgrehan  // are packed to their natural size.
240125410Sgrehan  Convert* conv = x->value()->as_Convert();
241125410Sgrehan  if (conv) {
242125410Sgrehan    Value value = NULL;
243125410Sgrehan    BasicType type = x->elt_type();
244125410Sgrehan    switch (conv->op()) {
245125410Sgrehan    case Bytecodes::_i2b: if (type == T_BYTE)  value = conv->value(); break;
246125410Sgrehan    case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) value = conv->value(); break;
247125410Sgrehan    case Bytecodes::_i2c: if (type == T_CHAR  || type == T_BYTE) value = conv->value(); break;
248125410Sgrehan    }
249125410Sgrehan    // limit this optimization to current block
250125410Sgrehan    if (value != NULL && in_current_block(conv)) {
251125410Sgrehan      set_canonical(new StoreIndexed(x->array(), x->index(), x->length(),
252125410Sgrehan                                     x->elt_type(), value, x->lock_stack()));
253125410Sgrehan      return;
254125410Sgrehan    }
255125410Sgrehan  }
256125410Sgrehan
257125410Sgrehan
258125410Sgrehan}
259125410Sgrehan
260125410Sgrehan
261125410Sgrehanvoid Canonicalizer::do_NegateOp(NegateOp* x) {
262125410Sgrehan  ValueType* t = x->x()->type();
263125410Sgrehan  if (t->is_constant()) {
264125410Sgrehan    switch (t->tag()) {
265125410Sgrehan      case intTag   : set_constant(-t->as_IntConstant   ()->value()); return;
266125410Sgrehan      case longTag  : set_constant(-t->as_LongConstant  ()->value()); return;
267125410Sgrehan      case floatTag : set_constant(-t->as_FloatConstant ()->value()); return;
268125410Sgrehan      case doubleTag: set_constant(-t->as_DoubleConstant()->value()); return;
269125410Sgrehan      default       : ShouldNotReachHere();
270125410Sgrehan    }
271125410Sgrehan  }
272125410Sgrehan}
273125410Sgrehan
274125410Sgrehan
275125410Sgrehanvoid Canonicalizer::do_ArithmeticOp   (ArithmeticOp*    x) { do_Op2(x); }
276125410Sgrehan
277125410Sgrehan
278125410Sgrehanvoid Canonicalizer::do_ShiftOp        (ShiftOp*         x) {
279125410Sgrehan  ValueType* t = x->x()->type();
280125410Sgrehan  ValueType* t2 = x->y()->type();
281125410Sgrehan  if (t->is_constant()) {
282125410Sgrehan    switch (t->tag()) {
283125410Sgrehan    case intTag   : if (t->as_IntConstant()->value() == 0)         { set_constant(0); return; } break;
284125410Sgrehan    case longTag  : if (t->as_LongConstant()->value() == (jlong)0) { set_constant(jlong_cast(0)); return; } break;
285125410Sgrehan    default       : ShouldNotReachHere();
286125410Sgrehan    }
287125410Sgrehan    if (t2->is_constant()) {
288125410Sgrehan      if (t->tag() == intTag) {
289125410Sgrehan        int value = t->as_IntConstant()->value();
290125410Sgrehan        int shift = t2->as_IntConstant()->value() & 31;
291125410Sgrehan        jint mask = ~(~0 << (32 - shift));
292125410Sgrehan        if (shift == 0) mask = ~0;
293125410Sgrehan        switch (x->op()) {
294125410Sgrehan          case Bytecodes::_ishl:  set_constant(value << shift); return;
295125410Sgrehan          case Bytecodes::_ishr:  set_constant(value >> shift); return;
296125410Sgrehan          case Bytecodes::_iushr: set_constant((value >> shift) & mask); return;
297125410Sgrehan        }
298125410Sgrehan      } else if (t->tag() == longTag) {
299125410Sgrehan        jlong value = t->as_LongConstant()->value();
300125410Sgrehan        int shift = t2->as_IntConstant()->value() & 63;
301125410Sgrehan        jlong mask = ~(~jlong_cast(0) << (64 - shift));
302125410Sgrehan        if (shift == 0) mask = ~jlong_cast(0);
303125410Sgrehan        switch (x->op()) {
304125410Sgrehan          case Bytecodes::_lshl:  set_constant(value << shift); return;
305125410Sgrehan          case Bytecodes::_lshr:  set_constant(value >> shift); return;
306125410Sgrehan          case Bytecodes::_lushr: set_constant((value >> shift) & mask); return;
307125410Sgrehan        }
308125410Sgrehan      }
309125410Sgrehan    }
310  }
311  if (t2->is_constant()) {
312    switch (t2->tag()) {
313      case intTag   : if (t2->as_IntConstant()->value() == 0)  set_canonical(x->x()); return;
314      case longTag  : if (t2->as_IntConstant()->value() == 0)  set_canonical(x->x()); return;
315      default       : ShouldNotReachHere();
316    }
317  }
318}
319
320
321void Canonicalizer::do_LogicOp        (LogicOp*         x) { do_Op2(x); }
322void Canonicalizer::do_CompareOp      (CompareOp*       x) {
323  if (x->x() == x->y()) {
324    switch (x->x()->type()->tag()) {
325      case longTag: set_constant(0); break;
326      case floatTag: {
327        FloatConstant* fc = x->x()->type()->as_FloatConstant();
328        if (fc) {
329          if (g_isnan(fc->value())) {
330            set_constant(x->op() == Bytecodes::_fcmpl ? -1 : 1);
331          } else {
332            set_constant(0);
333          }
334        }
335        break;
336      }
337      case doubleTag: {
338        DoubleConstant* dc = x->x()->type()->as_DoubleConstant();
339        if (dc) {
340          if (g_isnan(dc->value())) {
341            set_constant(x->op() == Bytecodes::_dcmpl ? -1 : 1);
342          } else {
343            set_constant(0);
344          }
345        }
346        break;
347      }
348    }
349  } else if (x->x()->type()->is_constant() && x->y()->type()->is_constant()) {
350    switch (x->x()->type()->tag()) {
351      case longTag: {
352        jlong vx = x->x()->type()->as_LongConstant()->value();
353        jlong vy = x->y()->type()->as_LongConstant()->value();
354        if (vx == vy)
355          set_constant(0);
356        else if (vx < vy)
357          set_constant(-1);
358        else
359          set_constant(1);
360        break;
361      }
362
363      case floatTag: {
364        float vx = x->x()->type()->as_FloatConstant()->value();
365        float vy = x->y()->type()->as_FloatConstant()->value();
366        if (g_isnan(vx) || g_isnan(vy))
367          set_constant(x->op() == Bytecodes::_fcmpl ? -1 : 1);
368        else if (vx == vy)
369          set_constant(0);
370        else if (vx < vy)
371          set_constant(-1);
372        else
373          set_constant(1);
374        break;
375      }
376
377      case doubleTag: {
378        double vx = x->x()->type()->as_DoubleConstant()->value();
379        double vy = x->y()->type()->as_DoubleConstant()->value();
380        if (g_isnan(vx) || g_isnan(vy))
381          set_constant(x->op() == Bytecodes::_dcmpl ? -1 : 1);
382        else if (vx == vy)
383          set_constant(0);
384        else if (vx < vy)
385          set_constant(-1);
386        else
387          set_constant(1);
388        break;
389      }
390    }
391
392  }
393}
394
395
396void Canonicalizer::do_IfInstanceOf(IfInstanceOf*    x) {}
397
398void Canonicalizer::do_IfOp(IfOp* x) {
399  // Caution: do not use do_Op2(x) here for now since
400  //          we map the condition to the op for now!
401  move_const_to_right(x);
402}
403
404
405void Canonicalizer::do_Intrinsic      (Intrinsic*       x) {
406  switch (x->id()) {
407  case vmIntrinsics::_floatToRawIntBits   : {
408    FloatConstant* c = x->argument_at(0)->type()->as_FloatConstant();
409    if (c != NULL) {
410      JavaValue v;
411      v.set_jfloat(c->value());
412      set_constant(v.get_jint());
413    }
414    break;
415  }
416  case vmIntrinsics::_intBitsToFloat      : {
417    IntConstant* c = x->argument_at(0)->type()->as_IntConstant();
418    if (c != NULL) {
419      JavaValue v;
420      v.set_jint(c->value());
421      set_constant(v.get_jfloat());
422    }
423    break;
424  }
425  case vmIntrinsics::_doubleToRawLongBits : {
426    DoubleConstant* c = x->argument_at(0)->type()->as_DoubleConstant();
427    if (c != NULL) {
428      JavaValue v;
429      v.set_jdouble(c->value());
430      set_constant(v.get_jlong());
431    }
432    break;
433  }
434  case vmIntrinsics::_longBitsToDouble    : {
435    LongConstant* c = x->argument_at(0)->type()->as_LongConstant();
436    if (c != NULL) {
437      JavaValue v;
438      v.set_jlong(c->value());
439      set_constant(v.get_jdouble());
440    }
441    break;
442  }
443  }
444}
445
446void Canonicalizer::do_Convert        (Convert*         x) {
447  if (x->value()->type()->is_constant()) {
448    switch (x->op()) {
449    case Bytecodes::_i2b:  set_constant((int)((x->value()->type()->as_IntConstant()->value() << 24) >> 24)); break;
450    case Bytecodes::_i2s:  set_constant((int)((x->value()->type()->as_IntConstant()->value() << 16) >> 16)); break;
451    case Bytecodes::_i2c:  set_constant((int)(x->value()->type()->as_IntConstant()->value() & ((1<<16)-1))); break;
452    case Bytecodes::_i2l:  set_constant((jlong)(x->value()->type()->as_IntConstant()->value()));             break;
453    case Bytecodes::_i2f:  set_constant((float)(x->value()->type()->as_IntConstant()->value()));             break;
454    case Bytecodes::_i2d:  set_constant((double)(x->value()->type()->as_IntConstant()->value()));            break;
455    case Bytecodes::_l2i:  set_constant((int)(x->value()->type()->as_LongConstant()->value()));              break;
456    case Bytecodes::_l2f:  set_constant(SharedRuntime::l2f(x->value()->type()->as_LongConstant()->value())); break;
457    case Bytecodes::_l2d:  set_constant(SharedRuntime::l2d(x->value()->type()->as_LongConstant()->value())); break;
458    case Bytecodes::_f2d:  set_constant((double)(x->value()->type()->as_FloatConstant()->value()));          break;
459    case Bytecodes::_f2i:  set_constant(SharedRuntime::f2i(x->value()->type()->as_FloatConstant()->value())); break;
460    case Bytecodes::_f2l:  set_constant(SharedRuntime::f2l(x->value()->type()->as_FloatConstant()->value())); break;
461    case Bytecodes::_d2f:  set_constant((float)(x->value()->type()->as_DoubleConstant()->value()));          break;
462    case Bytecodes::_d2i:  set_constant(SharedRuntime::d2i(x->value()->type()->as_DoubleConstant()->value())); break;
463    case Bytecodes::_d2l:  set_constant(SharedRuntime::d2l(x->value()->type()->as_DoubleConstant()->value())); break;
464    default:
465      ShouldNotReachHere();
466    }
467  }
468
469  Value value = x->value();
470  BasicType type = T_ILLEGAL;
471  LoadField* lf = value->as_LoadField();
472  if (lf) {
473    type = lf->field_type();
474  } else {
475    LoadIndexed* li = value->as_LoadIndexed();
476    if (li) {
477      type = li->elt_type();
478    } else {
479      Convert* conv = value->as_Convert();
480      if (conv) {
481        switch (conv->op()) {
482          case Bytecodes::_i2b: type = T_BYTE;  break;
483          case Bytecodes::_i2s: type = T_SHORT; break;
484          case Bytecodes::_i2c: type = T_CHAR;  break;
485        }
486      }
487    }
488  }
489  if (type != T_ILLEGAL) {
490    switch (x->op()) {
491      case Bytecodes::_i2b: if (type == T_BYTE)                    set_canonical(x->value()); break;
492      case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) set_canonical(x->value()); break;
493      case Bytecodes::_i2c: if (type == T_CHAR)                    set_canonical(x->value()); break;
494    }
495  } else {
496    Op2* op2 = x->value()->as_Op2();
497    if (op2 && op2->op() == Bytecodes::_iand && op2->y()->type()->is_constant()) {
498      jint safebits = 0;
499      jint mask = op2->y()->type()->as_IntConstant()->value();
500      switch (x->op()) {
501        case Bytecodes::_i2b: safebits = 0x7f;   break;
502        case Bytecodes::_i2s: safebits = 0x7fff; break;
503        case Bytecodes::_i2c: safebits = 0xffff; break;
504      }
505      // When casting a masked integer to a smaller signed type, if
506      // the mask doesn't include the sign bit the cast isn't needed.
507      if (safebits && (mask & ~safebits) == 0) {
508        set_canonical(x->value());
509      }
510    }
511  }
512
513}
514
515void Canonicalizer::do_NullCheck      (NullCheck*       x) {
516  if (x->obj()->as_NewArray() != NULL || x->obj()->as_NewInstance() != NULL) {
517    set_canonical(x->obj());
518  } else {
519    Constant* con = x->obj()->as_Constant();
520    if (con) {
521      ObjectType* c = con->type()->as_ObjectType();
522      if (c && c->is_loaded()) {
523        ObjectConstant* oc = c->as_ObjectConstant();
524        if (!oc || !oc->value()->is_null_object()) {
525          set_canonical(con);
526        }
527      }
528    }
529  }
530}
531
532void Canonicalizer::do_Invoke         (Invoke*          x) {}
533void Canonicalizer::do_NewInstance    (NewInstance*     x) {}
534void Canonicalizer::do_NewTypeArray   (NewTypeArray*    x) {}
535void Canonicalizer::do_NewObjectArray (NewObjectArray*  x) {}
536void Canonicalizer::do_NewMultiArray  (NewMultiArray*   x) {}
537void Canonicalizer::do_CheckCast      (CheckCast*       x) {
538  if (x->klass()->is_loaded()) {
539    Value obj = x->obj();
540    ciType* klass = obj->exact_type();
541    if (klass == NULL) klass = obj->declared_type();
542    if (klass != NULL && klass->is_loaded() && klass->is_subtype_of(x->klass())) {
543      set_canonical(obj);
544      return;
545    }
546    // checkcast of null returns null
547    if (obj->as_Constant() && obj->type()->as_ObjectType()->constant_value()->is_null_object()) {
548      set_canonical(obj);
549    }
550  }
551}
552void Canonicalizer::do_InstanceOf     (InstanceOf*      x) {
553  if (x->klass()->is_loaded()) {
554    Value obj = x->obj();
555    ciType* exact = obj->exact_type();
556    if (exact != NULL && exact->is_loaded() && (obj->as_NewInstance() || obj->as_NewArray())) {
557      set_constant(exact->is_subtype_of(x->klass()) ? 1 : 0);
558      return;
559    }
560    // instanceof null returns false
561    if (obj->as_Constant() && obj->type()->as_ObjectType()->constant_value()->is_null_object()) {
562      set_constant(0);
563    }
564  }
565
566}
567void Canonicalizer::do_MonitorEnter   (MonitorEnter*    x) {}
568void Canonicalizer::do_MonitorExit    (MonitorExit*     x) {}
569void Canonicalizer::do_BlockBegin     (BlockBegin*      x) {}
570void Canonicalizer::do_Goto           (Goto*            x) {}
571
572
573static bool is_true(jlong x, If::Condition cond, jlong y) {
574  switch (cond) {
575    case If::eql: return x == y;
576    case If::neq: return x != y;
577    case If::lss: return x <  y;
578    case If::leq: return x <= y;
579    case If::gtr: return x >  y;
580    case If::geq: return x >= y;
581  }
582  ShouldNotReachHere();
583  return false;
584}
585
586
587void Canonicalizer::do_If(If* x) {
588  // move const to right
589  if (x->x()->type()->is_constant()) x->swap_operands();
590  // simplify
591  const Value l = x->x(); ValueType* lt = l->type();
592  const Value r = x->y(); ValueType* rt = r->type();
593
594  if (l == r && !lt->is_float_kind()) {
595    // pattern: If (a cond a) => simplify to Goto
596    BlockBegin* sux;
597    switch (x->cond()) {
598    case If::eql: sux = x->sux_for(true);  break;
599    case If::neq: sux = x->sux_for(false); break;
600    case If::lss: sux = x->sux_for(false); break;
601    case If::leq: sux = x->sux_for(true);  break;
602    case If::gtr: sux = x->sux_for(false); break;
603    case If::geq: sux = x->sux_for(true);  break;
604    }
605    // If is a safepoint then the debug information should come from the state_before of the If.
606    set_canonical(new Goto(sux, x->state_before(), x->is_safepoint()));
607    return;
608  }
609
610  if (lt->is_constant() && rt->is_constant()) {
611    if (x->x()->as_Constant() != NULL) {
612      // pattern: If (lc cond rc) => simplify to: Goto
613      BlockBegin* sux = x->x()->as_Constant()->compare(x->cond(), x->y(),
614                                                       x->sux_for(true),
615                                                       x->sux_for(false));
616      if (sux != NULL) {
617        // If is a safepoint then the debug information should come from the state_before of the If.
618        set_canonical(new Goto(sux, x->state_before(), x->is_safepoint()));
619      }
620    }
621  } else if (rt->as_IntConstant() != NULL) {
622    // pattern: If (l cond rc) => investigate further
623    const jint rc = rt->as_IntConstant()->value();
624    if (l->as_CompareOp() != NULL) {
625      // pattern: If ((a cmp b) cond rc) => simplify to: If (x cond y) or: Goto
626      CompareOp* cmp = l->as_CompareOp();
627      bool unordered_is_less = cmp->op() == Bytecodes::_fcmpl || cmp->op() == Bytecodes::_dcmpl;
628      BlockBegin* lss_sux = x->sux_for(is_true(-1, x->cond(), rc)); // successor for a < b
629      BlockBegin* eql_sux = x->sux_for(is_true( 0, x->cond(), rc)); // successor for a = b
630      BlockBegin* gtr_sux = x->sux_for(is_true(+1, x->cond(), rc)); // successor for a > b
631      BlockBegin* nan_sux = unordered_is_less ? lss_sux : gtr_sux ; // successor for unordered
632      // Note: At this point all successors (lss_sux, eql_sux, gtr_sux, nan_sux) are
633      //       equal to x->tsux() or x->fsux(). Furthermore, nan_sux equals either
634      //       lss_sux or gtr_sux.
635      if (lss_sux == eql_sux && eql_sux == gtr_sux) {
636        // all successors identical => simplify to: Goto
637        set_canonical(new Goto(lss_sux, x->state_before(), x->is_safepoint()));
638      } else {
639        // two successors differ and two successors are the same => simplify to: If (x cmp y)
640        // determine new condition & successors
641        If::Condition cond;
642        BlockBegin* tsux = NULL;
643        BlockBegin* fsux = NULL;
644             if (lss_sux == eql_sux) { cond = If::leq; tsux = lss_sux; fsux = gtr_sux; }
645        else if (lss_sux == gtr_sux) { cond = If::neq; tsux = lss_sux; fsux = eql_sux; }
646        else if (eql_sux == gtr_sux) { cond = If::geq; tsux = eql_sux; fsux = lss_sux; }
647        else                         { ShouldNotReachHere();                           }
648           If* canon = new If(cmp->x(), cond, nan_sux == tsux, cmp->y(), tsux, fsux, cmp->state_before(), x->is_safepoint());
649        if (cmp->x() == cmp->y()) {
650          do_If(canon);
651        } else {
652          set_canonical(canon);
653          set_bci(cmp->bci());
654        }
655      }
656    } else if (l->as_InstanceOf() != NULL) {
657      // NOTE: Code permanently disabled for now since it leaves the old InstanceOf
658      //       instruction in the graph (it is pinned). Need to fix this at some point.
659      return;
660      // pattern: If ((obj instanceof klass) cond rc) => simplify to: IfInstanceOf or: Goto
661      InstanceOf* inst = l->as_InstanceOf();
662      BlockBegin* is_inst_sux = x->sux_for(is_true(1, x->cond(), rc)); // successor for instanceof == 1
663      BlockBegin* no_inst_sux = x->sux_for(is_true(0, x->cond(), rc)); // successor for instanceof == 0
664      if (is_inst_sux == no_inst_sux && inst->is_loaded()) {
665        // both successors identical and klass is loaded => simplify to: Goto
666        set_canonical(new Goto(is_inst_sux, x->state_before(), x->is_safepoint()));
667      } else {
668        // successors differ => simplify to: IfInstanceOf
669        set_canonical(new IfInstanceOf(inst->klass(), inst->obj(), true, inst->bci(), is_inst_sux, no_inst_sux));
670      }
671    }
672  } else if (rt == objectNull && (l->as_NewInstance() || l->as_NewArray())) {
673    if (x->cond() == Instruction::eql) {
674      set_canonical(new Goto(x->fsux(), x->state_before(), x->is_safepoint()));
675    } else {
676      assert(x->cond() == Instruction::neq, "only other valid case");
677      set_canonical(new Goto(x->tsux(), x->state_before(), x->is_safepoint()));
678    }
679  }
680}
681
682
683void Canonicalizer::do_TableSwitch(TableSwitch* x) {
684  if (x->tag()->type()->is_constant()) {
685    int v = x->tag()->type()->as_IntConstant()->value();
686    BlockBegin* sux = x->default_sux();
687    if (v >= x->lo_key() && v <= x->hi_key()) {
688      sux = x->sux_at(v - x->lo_key());
689    }
690    set_canonical(new Goto(sux, x->state_before(), x->is_safepoint()));
691  } else if (x->number_of_sux() == 1) {
692    // NOTE: Code permanently disabled for now since the switch statement's
693    //       tag expression may produce side-effects in which case it must
694    //       be executed.
695    return;
696    // simplify to Goto
697    set_canonical(new Goto(x->default_sux(), x->state_before(), x->is_safepoint()));
698  } else if (x->number_of_sux() == 2) {
699    // NOTE: Code permanently disabled for now since it produces two new nodes
700    //       (Constant & If) and the Canonicalizer cannot return them correctly
701    //       yet. For now we copied the corresponding code directly into the
702    //       GraphBuilder (i.e., we should never reach here).
703    return;
704    // simplify to If
705    assert(x->lo_key() == x->hi_key(), "keys must be the same");
706    Constant* key = new Constant(new IntConstant(x->lo_key()));
707    set_canonical(new If(x->tag(), If::eql, true, key, x->sux_at(0), x->default_sux(), x->state_before(), x->is_safepoint()));
708  }
709}
710
711
712void Canonicalizer::do_LookupSwitch(LookupSwitch* x) {
713  if (x->tag()->type()->is_constant()) {
714    int v = x->tag()->type()->as_IntConstant()->value();
715    BlockBegin* sux = x->default_sux();
716    for (int i = 0; i < x->length(); i++) {
717      if (v == x->key_at(i)) {
718        sux = x->sux_at(i);
719      }
720    }
721    set_canonical(new Goto(sux, x->state_before(), x->is_safepoint()));
722  } else if (x->number_of_sux() == 1) {
723    // NOTE: Code permanently disabled for now since the switch statement's
724    //       tag expression may produce side-effects in which case it must
725    //       be executed.
726    return;
727    // simplify to Goto
728    set_canonical(new Goto(x->default_sux(), x->state_before(), x->is_safepoint()));
729  } else if (x->number_of_sux() == 2) {
730    // NOTE: Code permanently disabled for now since it produces two new nodes
731    //       (Constant & If) and the Canonicalizer cannot return them correctly
732    //       yet. For now we copied the corresponding code directly into the
733    //       GraphBuilder (i.e., we should never reach here).
734    return;
735    // simplify to If
736    assert(x->length() == 1, "length must be the same");
737    Constant* key = new Constant(new IntConstant(x->key_at(0)));
738    set_canonical(new If(x->tag(), If::eql, true, key, x->sux_at(0), x->default_sux(), x->state_before(), x->is_safepoint()));
739  }
740}
741
742
743void Canonicalizer::do_Return         (Return*          x) {}
744void Canonicalizer::do_Throw          (Throw*           x) {}
745void Canonicalizer::do_Base           (Base*            x) {}
746void Canonicalizer::do_OsrEntry       (OsrEntry*        x) {}
747void Canonicalizer::do_ExceptionObject(ExceptionObject* x) {}
748
749static bool match_index_and_scale(Instruction*  instr,
750                                  Instruction** index,
751                                  int*          log2_scale,
752                                  Instruction** instr_to_unpin) {
753  *instr_to_unpin = NULL;
754
755  // Skip conversion ops
756  Convert* convert = instr->as_Convert();
757  if (convert != NULL) {
758    instr = convert->value();
759  }
760
761  ShiftOp* shift = instr->as_ShiftOp();
762  if (shift != NULL) {
763    if (shift->is_pinned()) {
764      *instr_to_unpin = shift;
765    }
766    // Constant shift value?
767    Constant* con = shift->y()->as_Constant();
768    if (con == NULL) return false;
769    // Well-known type and value?
770    IntConstant* val = con->type()->as_IntConstant();
771    if (val == NULL) return false;
772    if (shift->x()->type() != intType) return false;
773    *index = shift->x();
774    int tmp_scale = val->value();
775    if (tmp_scale >= 0 && tmp_scale < 4) {
776      *log2_scale = tmp_scale;
777      return true;
778    } else {
779      return false;
780    }
781  }
782
783  ArithmeticOp* arith = instr->as_ArithmeticOp();
784  if (arith != NULL) {
785    if (arith->is_pinned()) {
786      *instr_to_unpin = arith;
787    }
788    // Check for integer multiply
789    if (arith->op() == Bytecodes::_imul) {
790      // See if either arg is a known constant
791      Constant* con = arith->x()->as_Constant();
792      if (con != NULL) {
793        *index = arith->y();
794      } else {
795        con = arith->y()->as_Constant();
796        if (con == NULL) return false;
797        *index = arith->x();
798      }
799      if ((*index)->type() != intType) return false;
800      // Well-known type and value?
801      IntConstant* val = con->type()->as_IntConstant();
802      if (val == NULL) return false;
803      switch (val->value()) {
804      case 1: *log2_scale = 0; return true;
805      case 2: *log2_scale = 1; return true;
806      case 4: *log2_scale = 2; return true;
807      case 8: *log2_scale = 3; return true;
808      default:            return false;
809      }
810    }
811  }
812
813  // Unknown instruction sequence; don't touch it
814  return false;
815}
816
817
818static bool match(UnsafeRawOp* x,
819                  Instruction** base,
820                  Instruction** index,
821                  int*          log2_scale) {
822  Instruction* instr_to_unpin = NULL;
823  ArithmeticOp* root = x->base()->as_ArithmeticOp();
824  if (root == NULL) return false;
825  // Limit ourselves to addition for now
826  if (root->op() != Bytecodes::_ladd) return false;
827  // Try to find shift or scale op
828  if (match_index_and_scale(root->y(), index, log2_scale, &instr_to_unpin)) {
829    *base = root->x();
830  } else if (match_index_and_scale(root->x(), index, log2_scale, &instr_to_unpin)) {
831    *base = root->y();
832  } else if (root->y()->as_Convert() != NULL) {
833    Convert* convert = root->y()->as_Convert();
834    if (convert->op() == Bytecodes::_i2l && convert->value()->type() == intType) {
835      // pick base and index, setting scale at 1
836      *base  = root->x();
837      *index = convert->value();
838      *log2_scale = 0;
839    } else {
840      return false;
841    }
842  } else {
843    // doesn't match any expected sequences
844    return false;
845  }
846
847  // If the value is pinned then it will be always be computed so
848  // there's no profit to reshaping the expression.
849  return !root->is_pinned();
850}
851
852
853void Canonicalizer::do_UnsafeRawOp(UnsafeRawOp* x) {
854  Instruction* base = NULL;
855  Instruction* index = NULL;
856  int          log2_scale;
857
858  if (match(x, &base, &index, &log2_scale)) {
859    x->set_base(base);
860    x->set_index(index);
861    x->set_log2_scale(log2_scale);
862    if (PrintUnsafeOptimization) {
863      tty->print_cr("Canonicalizer: UnsafeRawOp id %d: base = id %d, index = id %d, log2_scale = %d",
864                    x->id(), x->base()->id(), x->index()->id(), x->log2_scale());
865    }
866  }
867}
868
869void Canonicalizer::do_RoundFP(RoundFP* x) {}
870void Canonicalizer::do_UnsafeGetRaw(UnsafeGetRaw* x) { if (OptimizeUnsafes) do_UnsafeRawOp(x); }
871void Canonicalizer::do_UnsafePutRaw(UnsafePutRaw* x) { if (OptimizeUnsafes) do_UnsafeRawOp(x); }
872void Canonicalizer::do_UnsafeGetObject(UnsafeGetObject* x) {}
873void Canonicalizer::do_UnsafePutObject(UnsafePutObject* x) {}
874void Canonicalizer::do_UnsafePrefetchRead (UnsafePrefetchRead*  x) {}
875void Canonicalizer::do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) {}
876void Canonicalizer::do_ProfileCall(ProfileCall* x) {}
877void Canonicalizer::do_ProfileCounter(ProfileCounter* x) {}
878