1 /*
   2  * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "c1/c1_Canonicalizer.hpp"
  27 #include "c1/c1_InstructionPrinter.hpp"
  28 #include "c1/c1_ValueStack.hpp"
  29 #include "ci/ciArray.hpp"
  30 #include "runtime/sharedRuntime.hpp"
  31 
  32 
  33 class PrintValueVisitor: public ValueVisitor {
  34   void visit(Value* vp) {
  35     (*vp)->print_line();
  36   }
  37 };
  38 
  39 void Canonicalizer::set_canonical(Value x) {
  40   assert(x != NULL, "value must exist");
  41   // Note: we can not currently substitute root nodes which show up in
  42   // the instruction stream (because the instruction list is embedded
  43   // in the instructions).
  44   if (canonical() != x) {
  45 #ifndef PRODUCT
  46     if (!x->has_printable_bci()) {
  47       x->set_printable_bci(bci());
  48     }
  49 #endif
  50     if (PrintCanonicalization) {
  51       PrintValueVisitor do_print_value;
  52       canonical()->input_values_do(&do_print_value);
  53       canonical()->print_line();
  54       tty->print_cr("canonicalized to:");
  55       x->input_values_do(&do_print_value);
  56       x->print_line();
  57       tty->cr();
  58     }
  59     assert(_canonical->type()->tag() == x->type()->tag(), "types must match");
  60     _canonical = x;
  61   }
  62 }
  63 
  64 
  65 void Canonicalizer::move_const_to_right(Op2* x) {
  66   if (x->x()->type()->is_constant() && x->is_commutative()) x->swap_operands();
  67 }
  68 
  69 
  70 void Canonicalizer::do_Op2(Op2* x) {
  71   if (x->x() == x->y()) {
  72     switch (x->op()) {
  73     case Bytecodes::_isub: set_constant(0); return;
  74     case Bytecodes::_lsub: set_constant(jlong_cast(0)); return;
  75     case Bytecodes::_iand: // fall through
  76     case Bytecodes::_land: // fall through
  77     case Bytecodes::_ior:  // fall through
  78     case Bytecodes::_lor : set_canonical(x->x()); return;
  79     case Bytecodes::_ixor: set_constant(0); return;
  80     case Bytecodes::_lxor: set_constant(jlong_cast(0)); return;
  81     }
  82   }
  83 
  84   if (x->x()->type()->is_constant() && x->y()->type()->is_constant()) {
  85     // do constant folding for selected operations
  86     switch (x->type()->tag()) {
  87       case intTag:
  88         { jint a = x->x()->type()->as_IntConstant()->value();
  89           jint b = x->y()->type()->as_IntConstant()->value();
  90           switch (x->op()) {
  91             case Bytecodes::_iadd: set_constant(a + b); return;
  92             case Bytecodes::_isub: set_constant(a - b); return;
  93             case Bytecodes::_imul: set_constant(a * b); return;
  94             case Bytecodes::_idiv:
  95               if (b != 0) {
  96                 if (a == min_jint && b == -1) {
  97                   set_constant(min_jint);
  98                 } else {
  99                   set_constant(a / b);
 100                 }
 101                 return;
 102               }
 103               break;
 104             case Bytecodes::_irem:
 105               if (b != 0) {
 106                 if (a == min_jint && b == -1) {
 107                   set_constant(0);
 108                 } else {
 109                   set_constant(a % b);
 110                 }
 111                 return;
 112               }
 113               break;
 114             case Bytecodes::_iand: set_constant(a & b); return;
 115             case Bytecodes::_ior : set_constant(a | b); return;
 116             case Bytecodes::_ixor: set_constant(a ^ b); return;
 117           }
 118         }
 119         break;
 120       case longTag:
 121         { jlong a = x->x()->type()->as_LongConstant()->value();
 122           jlong b = x->y()->type()->as_LongConstant()->value();
 123           switch (x->op()) {
 124             case Bytecodes::_ladd: set_constant(a + b); return;
 125             case Bytecodes::_lsub: set_constant(a - b); return;
 126             case Bytecodes::_lmul: set_constant(a * b); return;
 127             case Bytecodes::_ldiv:
 128               if (b != 0) {
 129                 set_constant(SharedRuntime::ldiv(b, a));
 130                 return;
 131               }
 132               break;
 133             case Bytecodes::_lrem:
 134               if (b != 0) {
 135                 set_constant(SharedRuntime::lrem(b, a));
 136                 return;
 137               }
 138               break;
 139             case Bytecodes::_land: set_constant(a & b); return;
 140             case Bytecodes::_lor : set_constant(a | b); return;
 141             case Bytecodes::_lxor: set_constant(a ^ b); return;
 142           }
 143         }
 144         break;
 145       // other cases not implemented (must be extremely careful with floats & doubles!)
 146     }
 147   }
 148   // make sure constant is on the right side, if any
 149   move_const_to_right(x);
 150 
 151   if (x->y()->type()->is_constant()) {
 152     // do constant folding for selected operations
 153     switch (x->type()->tag()) {
 154       case intTag:
 155         if (x->y()->type()->as_IntConstant()->value() == 0) {
 156           switch (x->op()) {
 157             case Bytecodes::_iadd: set_canonical(x->x()); return;
 158             case Bytecodes::_isub: set_canonical(x->x()); return;
 159             case Bytecodes::_imul: set_constant(0); return;
 160               // Note: for div and rem, make sure that C semantics
 161               //       corresponds to Java semantics!
 162             case Bytecodes::_iand: set_constant(0); return;
 163             case Bytecodes::_ior : set_canonical(x->x()); return;
 164           }
 165         }
 166         break;
 167       case longTag:
 168         if (x->y()->type()->as_LongConstant()->value() == (jlong)0) {
 169           switch (x->op()) {
 170             case Bytecodes::_ladd: set_canonical(x->x()); return;
 171             case Bytecodes::_lsub: set_canonical(x->x()); return;
 172             case Bytecodes::_lmul: set_constant((jlong)0); return;
 173               // Note: for div and rem, make sure that C semantics
 174               //       corresponds to Java semantics!
 175             case Bytecodes::_land: set_constant((jlong)0); return;
 176             case Bytecodes::_lor : set_canonical(x->x()); return;
 177           }
 178         }
 179         break;
 180     }
 181   }
 182 }
 183 
 184 
 185 void Canonicalizer::do_Phi            (Phi*             x) {}
 186 void Canonicalizer::do_Constant       (Constant*        x) {}
 187 void Canonicalizer::do_Local          (Local*           x) {}
 188 void Canonicalizer::do_LoadField      (LoadField*       x) {}
 189 
 190 // checks if v is in the block that is currently processed by
 191 // GraphBuilder. This is the only block that has not BlockEnd yet.
 192 static bool in_current_block(Value v) {
 193   int max_distance = 4;
 194   while (max_distance > 0 && v != NULL && v->as_BlockEnd() == NULL) {
 195     v = v->next();
 196     max_distance--;
 197   }
 198   return v == NULL;
 199 }
 200 
 201 void Canonicalizer::do_StoreField     (StoreField*      x) {
 202   // If a value is going to be stored into a field or array some of
 203   // the conversions emitted by javac are unneeded because the fields
 204   // are packed to their natural size.
 205   Convert* conv = x->value()->as_Convert();
 206   if (conv) {
 207     Value value = NULL;
 208     BasicType type = x->field()->type()->basic_type();
 209     switch (conv->op()) {
 210     case Bytecodes::_i2b: if (type == T_BYTE)  value = conv->value(); break;
 211     case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) value = conv->value(); break;
 212     case Bytecodes::_i2c: if (type == T_CHAR  || type == T_BYTE)  value = conv->value(); break;
 213     }
 214     // limit this optimization to current block
 215     if (value != NULL && in_current_block(conv)) {
 216       set_canonical(new StoreField(x->obj(), x->offset(), x->field(), value, x->is_static(),
 217                                    x->state_before(), x->needs_patching()));
 218       return;
 219     }
 220   }
 221 
 222 }
 223 
 224 void Canonicalizer::do_ArrayLength    (ArrayLength*     x) {
 225   NewArray*  na;
 226   Constant*  ct;
 227   LoadField* lf;
 228 
 229   if ((na = x->array()->as_NewArray()) != NULL) {
 230     // New arrays might have the known length.
 231     // Do not use the Constant itself, but create a new Constant
 232     // with same value Otherwise a Constant is live over multiple
 233     // blocks without being registered in a state array.
 234     Constant* length;
 235     if (na->length() != NULL &&
 236         (length = na->length()->as_Constant()) != NULL) {
 237       assert(length->type()->as_IntConstant() != NULL, "array length must be integer");
 238       set_constant(length->type()->as_IntConstant()->value());
 239     }
 240 
 241   } else if ((ct = x->array()->as_Constant()) != NULL) {
 242     // Constant arrays have constant lengths.
 243     ArrayConstant* cnst = ct->type()->as_ArrayConstant();
 244     if (cnst != NULL) {
 245       set_constant(cnst->value()->length());
 246     }
 247 
 248   } else if ((lf = x->array()->as_LoadField()) != NULL) {
 249     ciField* field = lf->field();
 250     if (field->is_constant() && field->is_static()) {
 251       assert(PatchALot || ScavengeRootsInCode < 2, "Constant field loads are folded during parsing");
 252       ciObject* c = field->constant_value().as_object();
 253       if (!c->is_null_object()) {
 254         set_constant(c->as_array()->length());
 255       }
 256     }
 257   }
 258 }
 259 
 260 void Canonicalizer::do_LoadIndexed    (LoadIndexed*     x) {}
 261 void Canonicalizer::do_StoreIndexed   (StoreIndexed*    x) {
 262   // If a value is going to be stored into a field or array some of
 263   // the conversions emitted by javac are unneeded because the fields
 264   // are packed to their natural size.
 265   Convert* conv = x->value()->as_Convert();
 266   if (conv) {
 267     Value value = NULL;
 268     BasicType type = x->elt_type();
 269     switch (conv->op()) {
 270     case Bytecodes::_i2b: if (type == T_BYTE)  value = conv->value(); break;
 271     case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) value = conv->value(); break;
 272     case Bytecodes::_i2c: if (type == T_CHAR  || type == T_BYTE) value = conv->value(); break;
 273     }
 274     // limit this optimization to current block
 275     if (value != NULL && in_current_block(conv)) {
 276       set_canonical(new StoreIndexed(x->array(), x->index(), x->length(),
 277                                      x->elt_type(), value, x->state_before()));
 278       return;
 279     }
 280   }
 281 
 282 
 283 }
 284 
 285 
 286 void Canonicalizer::do_NegateOp(NegateOp* x) {
 287   ValueType* t = x->x()->type();
 288   if (t->is_constant()) {
 289     switch (t->tag()) {
 290       case intTag   : set_constant(-t->as_IntConstant   ()->value()); return;
 291       case longTag  : set_constant(-t->as_LongConstant  ()->value()); return;
 292       case floatTag : set_constant(-t->as_FloatConstant ()->value()); return;
 293       case doubleTag: set_constant(-t->as_DoubleConstant()->value()); return;
 294       default       : ShouldNotReachHere();
 295     }
 296   }
 297 }
 298 
 299 
 300 void Canonicalizer::do_ArithmeticOp   (ArithmeticOp*    x) { do_Op2(x); }
 301 
 302 
 303 void Canonicalizer::do_ShiftOp        (ShiftOp*         x) {
 304   ValueType* t = x->x()->type();
 305   ValueType* t2 = x->y()->type();
 306   if (t->is_constant()) {
 307     switch (t->tag()) {
 308     case intTag   : if (t->as_IntConstant()->value() == 0)         { set_constant(0); return; } break;
 309     case longTag  : if (t->as_LongConstant()->value() == (jlong)0) { set_constant(jlong_cast(0)); return; } break;
 310     default       : ShouldNotReachHere();
 311     }
 312     if (t2->is_constant()) {
 313       if (t->tag() == intTag) {
 314         int value = t->as_IntConstant()->value();
 315         int shift = t2->as_IntConstant()->value() & 31;
 316         jint mask = ~(~0 << (32 - shift));
 317         if (shift == 0) mask = ~0;
 318         switch (x->op()) {
 319           case Bytecodes::_ishl:  set_constant(value << shift); return;
 320           case Bytecodes::_ishr:  set_constant(value >> shift); return;
 321           case Bytecodes::_iushr: set_constant((value >> shift) & mask); return;
 322         }
 323       } else if (t->tag() == longTag) {
 324         jlong value = t->as_LongConstant()->value();
 325         int shift = t2->as_IntConstant()->value() & 63;
 326         jlong mask = ~(~jlong_cast(0) << (64 - shift));
 327         if (shift == 0) mask = ~jlong_cast(0);
 328         switch (x->op()) {
 329           case Bytecodes::_lshl:  set_constant(value << shift); return;
 330           case Bytecodes::_lshr:  set_constant(value >> shift); return;
 331           case Bytecodes::_lushr: set_constant((value >> shift) & mask); return;
 332         }
 333       }
 334     }
 335   }
 336   if (t2->is_constant()) {
 337     switch (t2->tag()) {
 338       case intTag   : if (t2->as_IntConstant()->value() == 0)  set_canonical(x->x()); return;
 339       case longTag  : if (t2->as_LongConstant()->value() == (jlong)0)  set_canonical(x->x()); return;
 340       default       : ShouldNotReachHere();
 341     }
 342   }
 343 }
 344 
 345 
 346 void Canonicalizer::do_LogicOp        (LogicOp*         x) { do_Op2(x); }
 347 void Canonicalizer::do_CompareOp      (CompareOp*       x) {
 348   if (x->x() == x->y()) {
 349     switch (x->x()->type()->tag()) {
 350       case longTag: set_constant(0); break;
 351       case floatTag: {
 352         FloatConstant* fc = x->x()->type()->as_FloatConstant();
 353         if (fc) {
 354           if (g_isnan(fc->value())) {
 355             set_constant(x->op() == Bytecodes::_fcmpl ? -1 : 1);
 356           } else {
 357             set_constant(0);
 358           }
 359         }
 360         break;
 361       }
 362       case doubleTag: {
 363         DoubleConstant* dc = x->x()->type()->as_DoubleConstant();
 364         if (dc) {
 365           if (g_isnan(dc->value())) {
 366             set_constant(x->op() == Bytecodes::_dcmpl ? -1 : 1);
 367           } else {
 368             set_constant(0);
 369           }
 370         }
 371         break;
 372       }
 373     }
 374   } else if (x->x()->type()->is_constant() && x->y()->type()->is_constant()) {
 375     switch (x->x()->type()->tag()) {
 376       case longTag: {
 377         jlong vx = x->x()->type()->as_LongConstant()->value();
 378         jlong vy = x->y()->type()->as_LongConstant()->value();
 379         if (vx == vy)
 380           set_constant(0);
 381         else if (vx < vy)
 382           set_constant(-1);
 383         else
 384           set_constant(1);
 385         break;
 386       }
 387 
 388       case floatTag: {
 389         float vx = x->x()->type()->as_FloatConstant()->value();
 390         float vy = x->y()->type()->as_FloatConstant()->value();
 391         if (g_isnan(vx) || g_isnan(vy))
 392           set_constant(x->op() == Bytecodes::_fcmpl ? -1 : 1);
 393         else if (vx == vy)
 394           set_constant(0);
 395         else if (vx < vy)
 396           set_constant(-1);
 397         else
 398           set_constant(1);
 399         break;
 400       }
 401 
 402       case doubleTag: {
 403         double vx = x->x()->type()->as_DoubleConstant()->value();
 404         double vy = x->y()->type()->as_DoubleConstant()->value();
 405         if (g_isnan(vx) || g_isnan(vy))
 406           set_constant(x->op() == Bytecodes::_dcmpl ? -1 : 1);
 407         else if (vx == vy)
 408           set_constant(0);
 409         else if (vx < vy)
 410           set_constant(-1);
 411         else
 412           set_constant(1);
 413         break;
 414       }
 415     }
 416 
 417   }
 418 }
 419 
 420 
 421 void Canonicalizer::do_IfInstanceOf(IfInstanceOf*    x) {}
 422 
 423 void Canonicalizer::do_IfOp(IfOp* x) {
 424   // Caution: do not use do_Op2(x) here for now since
 425   //          we map the condition to the op for now!
 426   move_const_to_right(x);
 427 }
 428 
 429 
 430 void Canonicalizer::do_Intrinsic      (Intrinsic*       x) {
 431   switch (x->id()) {
 432   case vmIntrinsics::_floatToRawIntBits   : {
 433     FloatConstant* c = x->argument_at(0)->type()->as_FloatConstant();
 434     if (c != NULL) {
 435       JavaValue v;
 436       v.set_jfloat(c->value());
 437       set_constant(v.get_jint());
 438     }
 439     break;
 440   }
 441   case vmIntrinsics::_intBitsToFloat      : {
 442     IntConstant* c = x->argument_at(0)->type()->as_IntConstant();
 443     if (c != NULL) {
 444       JavaValue v;
 445       v.set_jint(c->value());
 446       set_constant(v.get_jfloat());
 447     }
 448     break;
 449   }
 450   case vmIntrinsics::_doubleToRawLongBits : {
 451     DoubleConstant* c = x->argument_at(0)->type()->as_DoubleConstant();
 452     if (c != NULL) {
 453       JavaValue v;
 454       v.set_jdouble(c->value());
 455       set_constant(v.get_jlong());
 456     }
 457     break;
 458   }
 459   case vmIntrinsics::_longBitsToDouble    : {
 460     LongConstant* c = x->argument_at(0)->type()->as_LongConstant();
 461     if (c != NULL) {
 462       JavaValue v;
 463       v.set_jlong(c->value());
 464       set_constant(v.get_jdouble());
 465     }
 466     break;
 467   }
 468   case vmIntrinsics::_isInstance          : {
 469     assert(x->number_of_arguments() == 2, "wrong type");
 470 
 471     InstanceConstant* c = x->argument_at(0)->type()->as_InstanceConstant();
 472     if (c != NULL && !c->value()->is_null_object()) {
 473       // ciInstance::java_mirror_type() returns non-NULL only for Java mirrors
 474       ciType* t = c->value()->as_instance()->java_mirror_type();
 475       if (t->is_klass()) {
 476         // substitute cls.isInstance(obj) of a constant Class into
 477         // an InstantOf instruction
 478         InstanceOf* i = new InstanceOf(t->as_klass(), x->argument_at(1), x->state_before());
 479         set_canonical(i);
 480         // and try to canonicalize even further
 481         do_InstanceOf(i);
 482       } else {
 483         assert(t->is_primitive_type(), "should be a primitive type");
 484         // cls.isInstance(obj) always returns false for primitive classes
 485         set_constant(0);
 486       }
 487     }
 488     break;
 489   }
 490   case vmIntrinsics::_isPrimitive        : {
 491     assert(x->number_of_arguments() == 1, "wrong type");
 492 
 493     // Class.isPrimitive is known on constant classes:
 494     InstanceConstant* c = x->argument_at(0)->type()->as_InstanceConstant();
 495     if (c != NULL && !c->value()->is_null_object()) {
 496       ciType* t = c->value()->as_instance()->java_mirror_type();
 497       set_constant(t->is_klass() ? 0 : 1);
 498     }
 499     break;
 500   }
 501   }
 502 }
 503 
 504 void Canonicalizer::do_Convert        (Convert*         x) {
 505   if (x->value()->type()->is_constant()) {
 506     switch (x->op()) {
 507     case Bytecodes::_i2b:  set_constant((int)((x->value()->type()->as_IntConstant()->value() << 24) >> 24)); break;
 508     case Bytecodes::_i2s:  set_constant((int)((x->value()->type()->as_IntConstant()->value() << 16) >> 16)); break;
 509     case Bytecodes::_i2c:  set_constant((int)(x->value()->type()->as_IntConstant()->value() & ((1<<16)-1))); break;
 510     case Bytecodes::_i2l:  set_constant((jlong)(x->value()->type()->as_IntConstant()->value()));             break;
 511     case Bytecodes::_i2f:  set_constant((float)(x->value()->type()->as_IntConstant()->value()));             break;
 512     case Bytecodes::_i2d:  set_constant((double)(x->value()->type()->as_IntConstant()->value()));            break;
 513     case Bytecodes::_l2i:  set_constant((int)(x->value()->type()->as_LongConstant()->value()));              break;
 514     case Bytecodes::_l2f:  set_constant(SharedRuntime::l2f(x->value()->type()->as_LongConstant()->value())); break;
 515     case Bytecodes::_l2d:  set_constant(SharedRuntime::l2d(x->value()->type()->as_LongConstant()->value())); break;
 516     case Bytecodes::_f2d:  set_constant((double)(x->value()->type()->as_FloatConstant()->value()));          break;
 517     case Bytecodes::_f2i:  set_constant(SharedRuntime::f2i(x->value()->type()->as_FloatConstant()->value())); break;
 518     case Bytecodes::_f2l:  set_constant(SharedRuntime::f2l(x->value()->type()->as_FloatConstant()->value())); break;
 519     case Bytecodes::_d2f:  set_constant((float)(x->value()->type()->as_DoubleConstant()->value()));          break;
 520     case Bytecodes::_d2i:  set_constant(SharedRuntime::d2i(x->value()->type()->as_DoubleConstant()->value())); break;
 521     case Bytecodes::_d2l:  set_constant(SharedRuntime::d2l(x->value()->type()->as_DoubleConstant()->value())); break;
 522     default:
 523       ShouldNotReachHere();
 524     }
 525   }
 526 
 527   Value value = x->value();
 528   BasicType type = T_ILLEGAL;
 529   LoadField* lf = value->as_LoadField();
 530   if (lf) {
 531     type = lf->field_type();
 532   } else {
 533     LoadIndexed* li = value->as_LoadIndexed();
 534     if (li) {
 535       type = li->elt_type();
 536     } else {
 537       Convert* conv = value->as_Convert();
 538       if (conv) {
 539         switch (conv->op()) {
 540           case Bytecodes::_i2b: type = T_BYTE;  break;
 541           case Bytecodes::_i2s: type = T_SHORT; break;
 542           case Bytecodes::_i2c: type = T_CHAR;  break;
 543         }
 544       }
 545     }
 546   }
 547   if (type != T_ILLEGAL) {
 548     switch (x->op()) {
 549       case Bytecodes::_i2b: if (type == T_BYTE)                    set_canonical(x->value()); break;
 550       case Bytecodes::_i2s: if (type == T_SHORT || type == T_BYTE) set_canonical(x->value()); break;
 551       case Bytecodes::_i2c: if (type == T_CHAR)                    set_canonical(x->value()); break;
 552     }
 553   } else {
 554     Op2* op2 = x->value()->as_Op2();
 555     if (op2 && op2->op() == Bytecodes::_iand && op2->y()->type()->is_constant()) {
 556       jint safebits = 0;
 557       jint mask = op2->y()->type()->as_IntConstant()->value();
 558       switch (x->op()) {
 559         case Bytecodes::_i2b: safebits = 0x7f;   break;
 560         case Bytecodes::_i2s: safebits = 0x7fff; break;
 561         case Bytecodes::_i2c: safebits = 0xffff; break;
 562       }
 563       // When casting a masked integer to a smaller signed type, if
 564       // the mask doesn't include the sign bit the cast isn't needed.
 565       if (safebits && (mask & ~safebits) == 0) {
 566         set_canonical(x->value());
 567       }
 568     }
 569   }
 570 
 571 }
 572 
 573 void Canonicalizer::do_NullCheck      (NullCheck*       x) {
 574   if (x->obj()->as_NewArray() != NULL || x->obj()->as_NewInstance() != NULL) {
 575     set_canonical(x->obj());
 576   } else {
 577     Constant* con = x->obj()->as_Constant();
 578     if (con) {
 579       ObjectType* c = con->type()->as_ObjectType();
 580       if (c && c->is_loaded()) {
 581         ObjectConstant* oc = c->as_ObjectConstant();
 582         if (!oc || !oc->value()->is_null_object()) {
 583           set_canonical(con);
 584         }
 585       }
 586     }
 587   }
 588 }
 589 
 590 void Canonicalizer::do_TypeCast       (TypeCast*        x) {}
 591 void Canonicalizer::do_Invoke         (Invoke*          x) {}
 592 void Canonicalizer::do_NewInstance    (NewInstance*     x) {}
 593 void Canonicalizer::do_NewTypeArray   (NewTypeArray*    x) {}
 594 void Canonicalizer::do_NewObjectArray (NewObjectArray*  x) {}
 595 void Canonicalizer::do_NewMultiArray  (NewMultiArray*   x) {}
 596 void Canonicalizer::do_CheckCast      (CheckCast*       x) {
 597   if (x->klass()->is_loaded()) {
 598     Value obj = x->obj();
 599     ciType* klass = obj->exact_type();
 600     if (klass == NULL) klass = obj->declared_type();
 601     if (klass != NULL && klass->is_loaded() && klass->is_subtype_of(x->klass())) {
 602       set_canonical(obj);
 603       return;
 604     }
 605     // checkcast of null returns null
 606     if (obj->as_Constant() && obj->type()->as_ObjectType()->constant_value()->is_null_object()) {
 607       set_canonical(obj);
 608     }
 609   }
 610 }
 611 void Canonicalizer::do_InstanceOf     (InstanceOf*      x) {
 612   if (x->klass()->is_loaded()) {
 613     Value obj = x->obj();
 614     ciType* exact = obj->exact_type();
 615     if (exact != NULL && exact->is_loaded() && (obj->as_NewInstance() || obj->as_NewArray())) {
 616       set_constant(exact->is_subtype_of(x->klass()) ? 1 : 0);
 617       return;
 618     }
 619     // instanceof null returns false
 620     if (obj->as_Constant() && obj->type()->as_ObjectType()->constant_value()->is_null_object()) {
 621       set_constant(0);
 622     }
 623   }
 624 
 625 }
 626 void Canonicalizer::do_MonitorEnter   (MonitorEnter*    x) {}
 627 void Canonicalizer::do_MonitorExit    (MonitorExit*     x) {}
 628 void Canonicalizer::do_BlockBegin     (BlockBegin*      x) {}
 629 void Canonicalizer::do_Goto           (Goto*            x) {}
 630 
 631 
 632 static bool is_true(jlong x, If::Condition cond, jlong y) {
 633   switch (cond) {
 634     case If::eql: return x == y;
 635     case If::neq: return x != y;
 636     case If::lss: return x <  y;
 637     case If::leq: return x <= y;
 638     case If::gtr: return x >  y;
 639     case If::geq: return x >= y;
 640   }
 641   ShouldNotReachHere();
 642   return false;
 643 }
 644 
 645 static bool is_safepoint(BlockEnd* x, BlockBegin* sux) {
 646   // An Instruction with multiple successors, x, is replaced by a Goto
 647   // to a single successor, sux. Is a safepoint check needed = was the
 648   // instruction being replaced a safepoint and the single remaining
 649   // successor a back branch?
 650   return x->is_safepoint() && (sux->bci() < x->state_before()->bci());
 651 }
 652 
 653 void Canonicalizer::do_If(If* x) {
 654   // move const to right
 655   if (x->x()->type()->is_constant()) x->swap_operands();
 656   // simplify
 657   const Value l = x->x(); ValueType* lt = l->type();
 658   const Value r = x->y(); ValueType* rt = r->type();
 659 
 660   if (l == r && !lt->is_float_kind()) {
 661     // pattern: If (a cond a) => simplify to Goto
 662     BlockBegin* sux = NULL;
 663     switch (x->cond()) {
 664     case If::eql: sux = x->sux_for(true);  break;
 665     case If::neq: sux = x->sux_for(false); break;
 666     case If::lss: sux = x->sux_for(false); break;
 667     case If::leq: sux = x->sux_for(true);  break;
 668     case If::gtr: sux = x->sux_for(false); break;
 669     case If::geq: sux = x->sux_for(true);  break;
 670     default: ShouldNotReachHere();
 671     }
 672     // If is a safepoint then the debug information should come from the state_before of the If.
 673     set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 674     return;
 675   }
 676 
 677   if (lt->is_constant() && rt->is_constant()) {
 678     if (x->x()->as_Constant() != NULL) {
 679       // pattern: If (lc cond rc) => simplify to: Goto
 680       BlockBegin* sux = x->x()->as_Constant()->compare(x->cond(), x->y(),
 681                                                        x->sux_for(true),
 682                                                        x->sux_for(false));
 683       if (sux != NULL) {
 684         // If is a safepoint then the debug information should come from the state_before of the If.
 685         set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 686       }
 687     }
 688   } else if (rt->as_IntConstant() != NULL) {
 689     // pattern: If (l cond rc) => investigate further
 690     const jint rc = rt->as_IntConstant()->value();
 691     if (l->as_CompareOp() != NULL) {
 692       // pattern: If ((a cmp b) cond rc) => simplify to: If (x cond y) or: Goto
 693       CompareOp* cmp = l->as_CompareOp();
 694       bool unordered_is_less = cmp->op() == Bytecodes::_fcmpl || cmp->op() == Bytecodes::_dcmpl;
 695       BlockBegin* lss_sux = x->sux_for(is_true(-1, x->cond(), rc)); // successor for a < b
 696       BlockBegin* eql_sux = x->sux_for(is_true( 0, x->cond(), rc)); // successor for a = b
 697       BlockBegin* gtr_sux = x->sux_for(is_true(+1, x->cond(), rc)); // successor for a > b
 698       BlockBegin* nan_sux = unordered_is_less ? lss_sux : gtr_sux ; // successor for unordered
 699       // Note: At this point all successors (lss_sux, eql_sux, gtr_sux, nan_sux) are
 700       //       equal to x->tsux() or x->fsux(). Furthermore, nan_sux equals either
 701       //       lss_sux or gtr_sux.
 702       if (lss_sux == eql_sux && eql_sux == gtr_sux) {
 703         // all successors identical => simplify to: Goto
 704         set_canonical(new Goto(lss_sux, x->state_before(), x->is_safepoint()));
 705       } else {
 706         // two successors differ and two successors are the same => simplify to: If (x cmp y)
 707         // determine new condition & successors
 708         If::Condition cond = If::eql;
 709         BlockBegin* tsux = NULL;
 710         BlockBegin* fsux = NULL;
 711              if (lss_sux == eql_sux) { cond = If::leq; tsux = lss_sux; fsux = gtr_sux; }
 712         else if (lss_sux == gtr_sux) { cond = If::neq; tsux = lss_sux; fsux = eql_sux; }
 713         else if (eql_sux == gtr_sux) { cond = If::geq; tsux = eql_sux; fsux = lss_sux; }
 714         else                         { ShouldNotReachHere();                           }
 715         If* canon = new If(cmp->x(), cond, nan_sux == tsux, cmp->y(), tsux, fsux, cmp->state_before(), x->is_safepoint());
 716         if (cmp->x() == cmp->y()) {
 717           do_If(canon);
 718         } else {
 719           if (compilation()->profile_branches()) {
 720             // TODO: If profiling, leave floating point comparisons unoptimized.
 721             // We currently do not support profiling of the unordered case.
 722             switch(cmp->op()) {
 723               case Bytecodes::_fcmpl: case Bytecodes::_fcmpg:
 724               case Bytecodes::_dcmpl: case Bytecodes::_dcmpg:
 725                 set_canonical(x);
 726                 return;
 727             }
 728           }
 729           set_bci(cmp->state_before()->bci());
 730           set_canonical(canon);
 731         }
 732       }
 733     } else if (l->as_InstanceOf() != NULL) {
 734       // NOTE: Code permanently disabled for now since it leaves the old InstanceOf
 735       //       instruction in the graph (it is pinned). Need to fix this at some point.
 736       //       It should also be left in the graph when generating a profiled method version or Goto
 737       //       has to know that it was an InstanceOf.
 738       return;
 739       // pattern: If ((obj instanceof klass) cond rc) => simplify to: IfInstanceOf or: Goto
 740       InstanceOf* inst = l->as_InstanceOf();
 741       BlockBegin* is_inst_sux = x->sux_for(is_true(1, x->cond(), rc)); // successor for instanceof == 1
 742       BlockBegin* no_inst_sux = x->sux_for(is_true(0, x->cond(), rc)); // successor for instanceof == 0
 743       if (is_inst_sux == no_inst_sux && inst->is_loaded()) {
 744         // both successors identical and klass is loaded => simplify to: Goto
 745         set_canonical(new Goto(is_inst_sux, x->state_before(), x->is_safepoint()));
 746       } else {
 747         // successors differ => simplify to: IfInstanceOf
 748         set_canonical(new IfInstanceOf(inst->klass(), inst->obj(), true, inst->state_before()->bci(), is_inst_sux, no_inst_sux));
 749       }
 750     }
 751   } else if (rt == objectNull &&
 752            (l->as_NewInstance() || l->as_NewArray() ||
 753              (l->as_Local() && l->as_Local()->is_receiver()))) {
 754     if (x->cond() == Instruction::eql) {
 755       BlockBegin* sux = x->fsux();
 756       set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 757     } else {
 758       assert(x->cond() == Instruction::neq, "only other valid case");
 759       BlockBegin* sux = x->tsux();
 760       set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 761     }
 762   }
 763 }
 764 
 765 
 766 void Canonicalizer::do_TableSwitch(TableSwitch* x) {
 767   if (x->tag()->type()->is_constant()) {
 768     int v = x->tag()->type()->as_IntConstant()->value();
 769     BlockBegin* sux = x->default_sux();
 770     if (v >= x->lo_key() && v <= x->hi_key()) {
 771       sux = x->sux_at(v - x->lo_key());
 772     }
 773     set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 774   } else if (x->number_of_sux() == 1) {
 775     // NOTE: Code permanently disabled for now since the switch statement's
 776     //       tag expression may produce side-effects in which case it must
 777     //       be executed.
 778     return;
 779     // simplify to Goto
 780     set_canonical(new Goto(x->default_sux(), x->state_before(), x->is_safepoint()));
 781   } else if (x->number_of_sux() == 2) {
 782     // NOTE: Code permanently disabled for now since it produces two new nodes
 783     //       (Constant & If) and the Canonicalizer cannot return them correctly
 784     //       yet. For now we copied the corresponding code directly into the
 785     //       GraphBuilder (i.e., we should never reach here).
 786     return;
 787     // simplify to If
 788     assert(x->lo_key() == x->hi_key(), "keys must be the same");
 789     Constant* key = new Constant(new IntConstant(x->lo_key()));
 790     set_canonical(new If(x->tag(), If::eql, true, key, x->sux_at(0), x->default_sux(), x->state_before(), x->is_safepoint()));
 791   }
 792 }
 793 
 794 
 795 void Canonicalizer::do_LookupSwitch(LookupSwitch* x) {
 796   if (x->tag()->type()->is_constant()) {
 797     int v = x->tag()->type()->as_IntConstant()->value();
 798     BlockBegin* sux = x->default_sux();
 799     for (int i = 0; i < x->length(); i++) {
 800       if (v == x->key_at(i)) {
 801         sux = x->sux_at(i);
 802       }
 803     }
 804     set_canonical(new Goto(sux, x->state_before(), is_safepoint(x, sux)));
 805   } else if (x->number_of_sux() == 1) {
 806     // NOTE: Code permanently disabled for now since the switch statement's
 807     //       tag expression may produce side-effects in which case it must
 808     //       be executed.
 809     return;
 810     // simplify to Goto
 811     set_canonical(new Goto(x->default_sux(), x->state_before(), x->is_safepoint()));
 812   } else if (x->number_of_sux() == 2) {
 813     // NOTE: Code permanently disabled for now since it produces two new nodes
 814     //       (Constant & If) and the Canonicalizer cannot return them correctly
 815     //       yet. For now we copied the corresponding code directly into the
 816     //       GraphBuilder (i.e., we should never reach here).
 817     return;
 818     // simplify to If
 819     assert(x->length() == 1, "length must be the same");
 820     Constant* key = new Constant(new IntConstant(x->key_at(0)));
 821     set_canonical(new If(x->tag(), If::eql, true, key, x->sux_at(0), x->default_sux(), x->state_before(), x->is_safepoint()));
 822   }
 823 }
 824 
 825 
 826 void Canonicalizer::do_Return         (Return*          x) {}
 827 void Canonicalizer::do_Throw          (Throw*           x) {}
 828 void Canonicalizer::do_Base           (Base*            x) {}
 829 void Canonicalizer::do_OsrEntry       (OsrEntry*        x) {}
 830 void Canonicalizer::do_ExceptionObject(ExceptionObject* x) {}
 831 
 832 static bool match_index_and_scale(Instruction*  instr,
 833                                   Instruction** index,
 834                                   int*          log2_scale) {
 835   // Skip conversion ops. This works only on 32bit because of the implicit l2i that the
 836   // unsafe performs.
 837 #ifndef _LP64
 838   Convert* convert = instr->as_Convert();
 839   if (convert != NULL && convert->op() == Bytecodes::_i2l) {
 840     assert(convert->value()->type() == intType, "invalid input type");
 841     instr = convert->value();
 842   }
 843 #endif
 844 
 845   ShiftOp* shift = instr->as_ShiftOp();
 846   if (shift != NULL) {
 847     if (shift->op() == Bytecodes::_lshl) {
 848       assert(shift->x()->type() == longType, "invalid input type");
 849     } else {
 850 #ifndef _LP64
 851       if (shift->op() == Bytecodes::_ishl) {
 852         assert(shift->x()->type() == intType, "invalid input type");
 853       } else {
 854         return false;
 855       }
 856 #else
 857       return false;
 858 #endif
 859     }
 860 
 861 
 862     // Constant shift value?
 863     Constant* con = shift->y()->as_Constant();
 864     if (con == NULL) return false;
 865     // Well-known type and value?
 866     IntConstant* val = con->type()->as_IntConstant();
 867     assert(val != NULL, "Should be an int constant");
 868 
 869     *index = shift->x();
 870     int tmp_scale = val->value();
 871     if (tmp_scale >= 0 && tmp_scale < 4) {
 872       *log2_scale = tmp_scale;
 873       return true;
 874     } else {
 875       return false;
 876     }
 877   }
 878 
 879   ArithmeticOp* arith = instr->as_ArithmeticOp();
 880   if (arith != NULL) {
 881     // See if either arg is a known constant
 882     Constant* con = arith->x()->as_Constant();
 883     if (con != NULL) {
 884       *index = arith->y();
 885     } else {
 886       con = arith->y()->as_Constant();
 887       if (con == NULL) return false;
 888       *index = arith->x();
 889     }
 890     long const_value;
 891     // Check for integer multiply
 892     if (arith->op() == Bytecodes::_lmul) {
 893       assert((*index)->type() == longType, "invalid input type");
 894       LongConstant* val = con->type()->as_LongConstant();
 895       assert(val != NULL, "expecting a long constant");
 896       const_value = val->value();
 897     } else {
 898 #ifndef _LP64
 899       if (arith->op() == Bytecodes::_imul) {
 900         assert((*index)->type() == intType, "invalid input type");
 901         IntConstant* val = con->type()->as_IntConstant();
 902         assert(val != NULL, "expecting an int constant");
 903         const_value = val->value();
 904       } else {
 905         return false;
 906       }
 907 #else
 908       return false;
 909 #endif
 910     }
 911     switch (const_value) {
 912     case 1: *log2_scale = 0; return true;
 913     case 2: *log2_scale = 1; return true;
 914     case 4: *log2_scale = 2; return true;
 915     case 8: *log2_scale = 3; return true;
 916     default:            return false;
 917     }
 918   }
 919 
 920   // Unknown instruction sequence; don't touch it
 921   return false;
 922 }
 923 
 924 
 925 static bool match(UnsafeRawOp* x,
 926                   Instruction** base,
 927                   Instruction** index,
 928                   int*          log2_scale) {
 929   ArithmeticOp* root = x->base()->as_ArithmeticOp();
 930   if (root == NULL) return false;
 931   // Limit ourselves to addition for now
 932   if (root->op() != Bytecodes::_ladd) return false;
 933 
 934   bool match_found = false;
 935   // Try to find shift or scale op
 936   if (match_index_and_scale(root->y(), index, log2_scale)) {
 937     *base = root->x();
 938     match_found = true;
 939   } else if (match_index_and_scale(root->x(), index, log2_scale)) {
 940     *base = root->y();
 941     match_found = true;
 942   } else if (NOT_LP64(root->y()->as_Convert() != NULL) LP64_ONLY(false)) {
 943     // Skipping i2l works only on 32bit because of the implicit l2i that the unsafe performs.
 944     // 64bit needs a real sign-extending conversion.
 945     Convert* convert = root->y()->as_Convert();
 946     if (convert->op() == Bytecodes::_i2l) {
 947       assert(convert->value()->type() == intType, "should be an int");
 948       // pick base and index, setting scale at 1
 949       *base  = root->x();
 950       *index = convert->value();
 951       *log2_scale = 0;
 952       match_found = true;
 953     }
 954   }
 955   // The default solution
 956   if (!match_found) {
 957     *base = root->x();
 958     *index = root->y();
 959     *log2_scale = 0;
 960   }
 961 
 962   // If the value is pinned then it will be always be computed so
 963   // there's no profit to reshaping the expression.
 964   return !root->is_pinned();
 965 }
 966 
 967 
 968 void Canonicalizer::do_UnsafeRawOp(UnsafeRawOp* x) {
 969   Instruction* base = NULL;
 970   Instruction* index = NULL;
 971   int          log2_scale;
 972 
 973   if (match(x, &base, &index, &log2_scale)) {
 974     x->set_base(base);
 975     x->set_index(index);
 976     x->set_log2_scale(log2_scale);
 977     if (PrintUnsafeOptimization) {
 978       tty->print_cr("Canonicalizer: UnsafeRawOp id %d: base = id %d, index = id %d, log2_scale = %d",
 979                     x->id(), x->base()->id(), x->index()->id(), x->log2_scale());
 980     }
 981   }
 982 }
 983 
 984 void Canonicalizer::do_RoundFP(RoundFP* x) {}
 985 void Canonicalizer::do_UnsafeGetRaw(UnsafeGetRaw* x) { if (OptimizeUnsafes) do_UnsafeRawOp(x); }
 986 void Canonicalizer::do_UnsafePutRaw(UnsafePutRaw* x) { if (OptimizeUnsafes) do_UnsafeRawOp(x); }
 987 void Canonicalizer::do_UnsafeGetObject(UnsafeGetObject* x) {}
 988 void Canonicalizer::do_UnsafePutObject(UnsafePutObject* x) {}
 989 void Canonicalizer::do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) {}
 990 void Canonicalizer::do_ProfileCall(ProfileCall* x) {}
 991 void Canonicalizer::do_ProfileReturnType(ProfileReturnType* x) {}
 992 void Canonicalizer::do_ProfileInvoke(ProfileInvoke* x) {}
 993 void Canonicalizer::do_RuntimeCall(RuntimeCall* x) {}
 994 void Canonicalizer::do_RangeCheckPredicate(RangeCheckPredicate* x) {}
 995 #ifdef ASSERT
 996 void Canonicalizer::do_Assert(Assert* x) {}
 997 #endif
 998 void Canonicalizer::do_MemBar(MemBar* x) {}