1 /*
   2  * Copyright (c) 1998, 2014, 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 "ci/ciMethodData.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileLog.hpp"
  30 #include "interpreter/linkResolver.hpp"
  31 #include "memory/universe.inline.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/convertnode.hpp"
  35 #include "opto/divnode.hpp"
  36 #include "opto/idealGraphPrinter.hpp"
  37 #include "opto/matcher.hpp"
  38 #include "opto/memnode.hpp"
  39 #include "opto/mulnode.hpp"
  40 #include "opto/opaquenode.hpp"
  41 #include "opto/parse.hpp"
  42 #include "opto/runtime.hpp"
  43 #include "runtime/deoptimization.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 
  46 extern int explicit_null_checks_inserted,
  47            explicit_null_checks_elided;
  48 
  49 //---------------------------------array_load----------------------------------
  50 void Parse::array_load(BasicType elem_type) {
  51   const Type* elem = Type::TOP;
  52   Node* adr = array_addressing(elem_type, 0, &elem);
  53   if (stopped())  return;     // guaranteed null or range check
  54   dec_sp(2);                  // Pop array and index
  55   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
  56   Node* ld = make_load(control(), adr, elem, elem_type, adr_type, MemNode::unordered);
  57   push(ld);
  58 }
  59 
  60 
  61 //--------------------------------array_store----------------------------------
  62 void Parse::array_store(BasicType elem_type) {
  63   Node* adr = array_addressing(elem_type, 1);
  64   if (stopped())  return;     // guaranteed null or range check
  65   Node* val = pop();
  66   dec_sp(2);                  // Pop array and index
  67   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
  68   store_to_memory(control(), adr, val, elem_type, adr_type, StoreNode::release_if_reference(elem_type));
  69 }
  70 
  71 
  72 //------------------------------array_addressing-------------------------------
  73 // Pull array and index from the stack.  Compute pointer-to-element.
  74 Node* Parse::array_addressing(BasicType type, int vals, const Type* *result2) {
  75   Node *idx   = peek(0+vals);   // Get from stack without popping
  76   Node *ary   = peek(1+vals);   // in case of exception
  77 
  78   // Null check the array base, with correct stack contents
  79   ary = null_check(ary, T_ARRAY);
  80   // Compile-time detect of null-exception?
  81   if (stopped())  return top();
  82 
  83   const TypeAryPtr* arytype  = _gvn.type(ary)->is_aryptr();
  84   const TypeInt*    sizetype = arytype->size();
  85   const Type*       elemtype = arytype->elem();
  86 
  87   if (UseUniqueSubclasses && result2 != NULL) {
  88     const Type* el = elemtype->make_ptr();
  89     if (el && el->isa_instptr()) {
  90       const TypeInstPtr* toop = el->is_instptr();
  91       if (toop->klass()->as_instance_klass()->unique_concrete_subklass()) {
  92         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
  93         const Type* subklass = Type::get_const_type(toop->klass());
  94         elemtype = subklass->join_speculative(el);
  95       }
  96     }
  97   }
  98 
  99   // Check for big class initializers with all constant offsets
 100   // feeding into a known-size array.
 101   const TypeInt* idxtype = _gvn.type(idx)->is_int();
 102   // See if the highest idx value is less than the lowest array bound,
 103   // and if the idx value cannot be negative:
 104   bool need_range_check = true;
 105   if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
 106     need_range_check = false;
 107     if (C->log() != NULL)   C->log()->elem("observe that='!need_range_check'");
 108   }
 109 
 110   ciKlass * arytype_klass = arytype->klass();
 111   if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
 112     // Only fails for some -Xcomp runs
 113     // The class is unloaded.  We have to run this bytecode in the interpreter.
 114     uncommon_trap(Deoptimization::Reason_unloaded,
 115                   Deoptimization::Action_reinterpret,
 116                   arytype->klass(), "!loaded array");
 117     return top();
 118   }
 119 
 120   // Do the range check
 121   if (GenerateRangeChecks && need_range_check) {
 122     Node* tst;
 123     if (sizetype->_hi <= 0) {
 124       // The greatest array bound is negative, so we can conclude that we're
 125       // compiling unreachable code, but the unsigned compare trick used below
 126       // only works with non-negative lengths.  Instead, hack "tst" to be zero so
 127       // the uncommon_trap path will always be taken.
 128       tst = _gvn.intcon(0);
 129     } else {
 130       // Range is constant in array-oop, so we can use the original state of mem
 131       Node* len = load_array_length(ary);
 132 
 133       // Test length vs index (standard trick using unsigned compare)
 134       Node* chk = _gvn.transform( new CmpUNode(idx, len) );
 135       BoolTest::mask btest = BoolTest::lt;
 136       tst = _gvn.transform( new BoolNode(chk, btest) );
 137     }
 138     // Branch to failure if out of bounds
 139     { BuildCutout unless(this, tst, PROB_MAX);
 140       if (C->allow_range_check_smearing()) {
 141         // Do not use builtin_throw, since range checks are sometimes
 142         // made more stringent by an optimistic transformation.
 143         // This creates "tentative" range checks at this point,
 144         // which are not guaranteed to throw exceptions.
 145         // See IfNode::Ideal, is_range_check, adjust_check.
 146         uncommon_trap(Deoptimization::Reason_range_check,
 147                       Deoptimization::Action_make_not_entrant,
 148                       NULL, "range_check");
 149       } else {
 150         // If we have already recompiled with the range-check-widening
 151         // heroic optimization turned off, then we must really be throwing
 152         // range check exceptions.
 153         builtin_throw(Deoptimization::Reason_range_check, idx);
 154       }
 155     }
 156   }
 157   // Check for always knowing you are throwing a range-check exception
 158   if (stopped())  return top();
 159 
 160   Node* ptr = array_element_address(ary, idx, type, sizetype);
 161 
 162   if (result2 != NULL)  *result2 = elemtype;
 163 
 164   assert(ptr != top(), "top should go hand-in-hand with stopped");
 165 
 166   return ptr;
 167 }
 168 
 169 
 170 // returns IfNode
 171 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask) {
 172   Node   *cmp = _gvn.transform( new CmpINode( a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
 173   Node   *tst = _gvn.transform( new BoolNode( cmp, mask));
 174   IfNode *iff = create_and_map_if( control(), tst, ((mask == BoolTest::eq) ? PROB_STATIC_INFREQUENT : PROB_FAIR), COUNT_UNKNOWN );
 175   return iff;
 176 }
 177 
 178 // return Region node
 179 Node* Parse::jump_if_join(Node* iffalse, Node* iftrue) {
 180   Node *region  = new RegionNode(3); // 2 results
 181   record_for_igvn(region);
 182   region->init_req(1, iffalse);
 183   region->init_req(2, iftrue );
 184   _gvn.set_type(region, Type::CONTROL);
 185   region = _gvn.transform(region);
 186   set_control (region);
 187   return region;
 188 }
 189 
 190 
 191 //------------------------------helper for tableswitch-------------------------
 192 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index) {
 193   // True branch, use existing map info
 194   { PreserveJVMState pjvms(this);
 195     Node *iftrue  = _gvn.transform( new IfTrueNode (iff) );
 196     set_control( iftrue );
 197     profile_switch_case(prof_table_index);
 198     merge_new_path(dest_bci_if_true);
 199   }
 200 
 201   // False branch
 202   Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
 203   set_control( iffalse );
 204 }
 205 
 206 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index) {
 207   // True branch, use existing map info
 208   { PreserveJVMState pjvms(this);
 209     Node *iffalse  = _gvn.transform( new IfFalseNode (iff) );
 210     set_control( iffalse );
 211     profile_switch_case(prof_table_index);
 212     merge_new_path(dest_bci_if_true);
 213   }
 214 
 215   // False branch
 216   Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
 217   set_control( iftrue );
 218 }
 219 
 220 void Parse::jump_if_always_fork(int dest_bci, int prof_table_index) {
 221   // False branch, use existing map and control()
 222   profile_switch_case(prof_table_index);
 223   merge_new_path(dest_bci);
 224 }
 225 
 226 
 227 extern "C" {
 228   static int jint_cmp(const void *i, const void *j) {
 229     int a = *(jint *)i;
 230     int b = *(jint *)j;
 231     return a > b ? 1 : a < b ? -1 : 0;
 232   }
 233 }
 234 
 235 
 236 // Default value for methodData switch indexing. Must be a negative value to avoid
 237 // conflict with any legal switch index.
 238 #define NullTableIndex -1
 239 
 240 class SwitchRange : public StackObj {
 241   // a range of integers coupled with a bci destination
 242   jint _lo;                     // inclusive lower limit
 243   jint _hi;                     // inclusive upper limit
 244   int _dest;
 245   int _table_index;             // index into method data table
 246 
 247 public:
 248   jint lo() const              { return _lo;   }
 249   jint hi() const              { return _hi;   }
 250   int  dest() const            { return _dest; }
 251   int  table_index() const     { return _table_index; }
 252   bool is_singleton() const    { return _lo == _hi; }
 253 
 254   void setRange(jint lo, jint hi, int dest, int table_index) {
 255     assert(lo <= hi, "must be a non-empty range");
 256     _lo = lo, _hi = hi; _dest = dest; _table_index = table_index;
 257   }
 258   bool adjoinRange(jint lo, jint hi, int dest, int table_index) {
 259     assert(lo <= hi, "must be a non-empty range");
 260     if (lo == _hi+1 && dest == _dest && table_index == _table_index) {
 261       _hi = hi;
 262       return true;
 263     }
 264     return false;
 265   }
 266 
 267   void set (jint value, int dest, int table_index) {
 268     setRange(value, value, dest, table_index);
 269   }
 270   bool adjoin(jint value, int dest, int table_index) {
 271     return adjoinRange(value, value, dest, table_index);
 272   }
 273 
 274   void print() {
 275     if (is_singleton())
 276       tty->print(" {%d}=>%d", lo(), dest());
 277     else if (lo() == min_jint)
 278       tty->print(" {..%d}=>%d", hi(), dest());
 279     else if (hi() == max_jint)
 280       tty->print(" {%d..}=>%d", lo(), dest());
 281     else
 282       tty->print(" {%d..%d}=>%d", lo(), hi(), dest());
 283   }
 284 };
 285 
 286 
 287 //-------------------------------do_tableswitch--------------------------------
 288 void Parse::do_tableswitch() {
 289   Node* lookup = pop();
 290 
 291   // Get information about tableswitch
 292   int default_dest = iter().get_dest_table(0);
 293   int lo_index     = iter().get_int_table(1);
 294   int hi_index     = iter().get_int_table(2);
 295   int len          = hi_index - lo_index + 1;
 296 
 297   if (len < 1) {
 298     // If this is a backward branch, add safepoint
 299     maybe_add_safepoint(default_dest);
 300     merge(default_dest);
 301     return;
 302   }
 303 
 304   // generate decision tree, using trichotomy when possible
 305   int rnum = len+2;
 306   bool makes_backward_branch = false;
 307   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 308   int rp = -1;
 309   if (lo_index != min_jint) {
 310     ranges[++rp].setRange(min_jint, lo_index-1, default_dest, NullTableIndex);
 311   }
 312   for (int j = 0; j < len; j++) {
 313     jint match_int = lo_index+j;
 314     int  dest      = iter().get_dest_table(j+3);
 315     makes_backward_branch |= (dest <= bci());
 316     int  table_index = method_data_update() ? j : NullTableIndex;
 317     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index)) {
 318       ranges[++rp].set(match_int, dest, table_index);
 319     }
 320   }
 321   jint highest = lo_index+(len-1);
 322   assert(ranges[rp].hi() == highest, "");
 323   if (highest != max_jint
 324       && !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex)) {
 325     ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex);
 326   }
 327   assert(rp < len+2, "not too many ranges");
 328 
 329   // Safepoint in case if backward branch observed
 330   if( makes_backward_branch && UseLoopSafepoints )
 331     add_safepoint();
 332 
 333   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 334 }
 335 
 336 
 337 //------------------------------do_lookupswitch--------------------------------
 338 void Parse::do_lookupswitch() {
 339   Node *lookup = pop();         // lookup value
 340   // Get information about lookupswitch
 341   int default_dest = iter().get_dest_table(0);
 342   int len          = iter().get_int_table(1);
 343 
 344   if (len < 1) {    // If this is a backward branch, add safepoint
 345     maybe_add_safepoint(default_dest);
 346     merge(default_dest);
 347     return;
 348   }
 349 
 350   // generate decision tree, using trichotomy when possible
 351   jint* table = NEW_RESOURCE_ARRAY(jint, len*2);
 352   {
 353     for( int j = 0; j < len; j++ ) {
 354       table[j+j+0] = iter().get_int_table(2+j+j);
 355       table[j+j+1] = iter().get_dest_table(2+j+j+1);
 356     }
 357     qsort( table, len, 2*sizeof(table[0]), jint_cmp );
 358   }
 359 
 360   int rnum = len*2+1;
 361   bool makes_backward_branch = false;
 362   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 363   int rp = -1;
 364   for( int j = 0; j < len; j++ ) {
 365     jint match_int   = table[j+j+0];
 366     int  dest        = table[j+j+1];
 367     int  next_lo     = rp < 0 ? min_jint : ranges[rp].hi()+1;
 368     int  table_index = method_data_update() ? j : NullTableIndex;
 369     makes_backward_branch |= (dest <= bci());
 370     if( match_int != next_lo ) {
 371       ranges[++rp].setRange(next_lo, match_int-1, default_dest, NullTableIndex);
 372     }
 373     if( rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index) ) {
 374       ranges[++rp].set(match_int, dest, table_index);
 375     }
 376   }
 377   jint highest = table[2*(len-1)];
 378   assert(ranges[rp].hi() == highest, "");
 379   if( highest != max_jint
 380       && !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex) ) {
 381     ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex);
 382   }
 383   assert(rp < rnum, "not too many ranges");
 384 
 385   // Safepoint in case backward branch observed
 386   if( makes_backward_branch && UseLoopSafepoints )
 387     add_safepoint();
 388 
 389   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 390 }
 391 
 392 //----------------------------create_jump_tables-------------------------------
 393 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
 394   // Are jumptables enabled
 395   if (!UseJumpTables)  return false;
 396 
 397   // Are jumptables supported
 398   if (!Matcher::has_match_rule(Op_Jump))  return false;
 399 
 400   // Don't make jump table if profiling
 401   if (method_data_update())  return false;
 402 
 403   // Decide if a guard is needed to lop off big ranges at either (or
 404   // both) end(s) of the input set. We'll call this the default target
 405   // even though we can't be sure that it is the true "default".
 406 
 407   bool needs_guard = false;
 408   int default_dest;
 409   int64_t total_outlier_size = 0;
 410   int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
 411   int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
 412 
 413   if (lo->dest() == hi->dest()) {
 414     total_outlier_size = hi_size + lo_size;
 415     default_dest = lo->dest();
 416   } else if (lo_size > hi_size) {
 417     total_outlier_size = lo_size;
 418     default_dest = lo->dest();
 419   } else {
 420     total_outlier_size = hi_size;
 421     default_dest = hi->dest();
 422   }
 423 
 424   // If a guard test will eliminate very sparse end ranges, then
 425   // it is worth the cost of an extra jump.
 426   if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
 427     needs_guard = true;
 428     if (default_dest == lo->dest()) lo++;
 429     if (default_dest == hi->dest()) hi--;
 430   }
 431 
 432   // Find the total number of cases and ranges
 433   int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
 434   int num_range = hi - lo + 1;
 435 
 436   // Don't create table if: too large, too small, or too sparse.
 437   if (num_cases < MinJumpTableSize || num_cases > MaxJumpTableSize)
 438     return false;
 439   if (num_cases > (MaxJumpTableSparseness * num_range))
 440     return false;
 441 
 442   // Normalize table lookups to zero
 443   int lowval = lo->lo();
 444   key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
 445 
 446   // Generate a guard to protect against input keyvals that aren't
 447   // in the switch domain.
 448   if (needs_guard) {
 449     Node*   size = _gvn.intcon(num_cases);
 450     Node*   cmp = _gvn.transform( new CmpUNode(key_val, size) );
 451     Node*   tst = _gvn.transform( new BoolNode(cmp, BoolTest::ge) );
 452     IfNode* iff = create_and_map_if( control(), tst, PROB_FAIR, COUNT_UNKNOWN);
 453     jump_if_true_fork(iff, default_dest, NullTableIndex);
 454   }
 455 
 456   // Create an ideal node JumpTable that has projections
 457   // of all possible ranges for a switch statement
 458   // The key_val input must be converted to a pointer offset and scaled.
 459   // Compare Parse::array_addressing above.
 460 #ifdef _LP64
 461   // Clean the 32-bit int into a real 64-bit offset.
 462   // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
 463   const TypeLong* lkeytype = TypeLong::make(CONST64(0), num_cases-1, Type::WidenMin);
 464   key_val       = _gvn.transform( new ConvI2LNode(key_val, lkeytype) );
 465 #endif
 466   // Shift the value by wordsize so we have an index into the table, rather
 467   // than a switch value
 468   Node *shiftWord = _gvn.MakeConX(wordSize);
 469   key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
 470 
 471   // Create the JumpNode
 472   Node* jtn = _gvn.transform( new JumpNode(control(), key_val, num_cases) );
 473 
 474   // These are the switch destinations hanging off the jumpnode
 475   int i = 0;
 476   for (SwitchRange* r = lo; r <= hi; r++) {
 477     for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
 478       Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
 479       {
 480         PreserveJVMState pjvms(this);
 481         set_control(input);
 482         jump_if_always_fork(r->dest(), r->table_index());
 483       }
 484     }
 485   }
 486   assert(i == num_cases, "miscount of cases");
 487   stop_and_kill_map();  // no more uses for this JVMS
 488   return true;
 489 }
 490 
 491 //----------------------------jump_switch_ranges-------------------------------
 492 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
 493   Block* switch_block = block();
 494 
 495   if (switch_depth == 0) {
 496     // Do special processing for the top-level call.
 497     assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
 498     assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
 499 
 500     // Decrement pred-numbers for the unique set of nodes.
 501 #ifdef ASSERT
 502     // Ensure that the block's successors are a (duplicate-free) set.
 503     int successors_counted = 0;  // block occurrences in [hi..lo]
 504     int unique_successors = switch_block->num_successors();
 505     for (int i = 0; i < unique_successors; i++) {
 506       Block* target = switch_block->successor_at(i);
 507 
 508       // Check that the set of successors is the same in both places.
 509       int successors_found = 0;
 510       for (SwitchRange* p = lo; p <= hi; p++) {
 511         if (p->dest() == target->start())  successors_found++;
 512       }
 513       assert(successors_found > 0, "successor must be known");
 514       successors_counted += successors_found;
 515     }
 516     assert(successors_counted == (hi-lo)+1, "no unexpected successors");
 517 #endif
 518 
 519     // Maybe prune the inputs, based on the type of key_val.
 520     jint min_val = min_jint;
 521     jint max_val = max_jint;
 522     const TypeInt* ti = key_val->bottom_type()->isa_int();
 523     if (ti != NULL) {
 524       min_val = ti->_lo;
 525       max_val = ti->_hi;
 526       assert(min_val <= max_val, "invalid int type");
 527     }
 528     while (lo->hi() < min_val)  lo++;
 529     if (lo->lo() < min_val)  lo->setRange(min_val, lo->hi(), lo->dest(), lo->table_index());
 530     while (hi->lo() > max_val)  hi--;
 531     if (hi->hi() > max_val)  hi->setRange(hi->lo(), max_val, hi->dest(), hi->table_index());
 532   }
 533 
 534 #ifndef PRODUCT
 535   if (switch_depth == 0) {
 536     _max_switch_depth = 0;
 537     _est_switch_depth = log2_intptr((hi-lo+1)-1)+1;
 538   }
 539 #endif
 540 
 541   assert(lo <= hi, "must be a non-empty set of ranges");
 542   if (lo == hi) {
 543     jump_if_always_fork(lo->dest(), lo->table_index());
 544   } else {
 545     assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
 546     assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
 547 
 548     if (create_jump_tables(key_val, lo, hi)) return;
 549 
 550     int nr = hi - lo + 1;
 551 
 552     SwitchRange* mid = lo + nr/2;
 553     // if there is an easy choice, pivot at a singleton:
 554     if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton())  mid--;
 555 
 556     assert(lo < mid && mid <= hi, "good pivot choice");
 557     assert(nr != 2 || mid == hi,   "should pick higher of 2");
 558     assert(nr != 3 || mid == hi-1, "should pick middle of 3");
 559 
 560     Node *test_val = _gvn.intcon(mid->lo());
 561 
 562     if (mid->is_singleton()) {
 563       IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne);
 564       jump_if_false_fork(iff_ne, mid->dest(), mid->table_index());
 565 
 566       // Special Case:  If there are exactly three ranges, and the high
 567       // and low range each go to the same place, omit the "gt" test,
 568       // since it will not discriminate anything.
 569       bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest());
 570       if (eq_test_only) {
 571         assert(mid == hi-1, "");
 572       }
 573 
 574       // if there is a higher range, test for it and process it:
 575       if (mid < hi && !eq_test_only) {
 576         // two comparisons of same values--should enable 1 test for 2 branches
 577         // Use BoolTest::le instead of BoolTest::gt
 578         IfNode *iff_le  = jump_if_fork_int(key_val, test_val, BoolTest::le);
 579         Node   *iftrue  = _gvn.transform( new IfTrueNode(iff_le) );
 580         Node   *iffalse = _gvn.transform( new IfFalseNode(iff_le) );
 581         { PreserveJVMState pjvms(this);
 582           set_control(iffalse);
 583           jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
 584         }
 585         set_control(iftrue);
 586       }
 587 
 588     } else {
 589       // mid is a range, not a singleton, so treat mid..hi as a unit
 590       IfNode *iff_ge = jump_if_fork_int(key_val, test_val, BoolTest::ge);
 591 
 592       // if there is a higher range, test for it and process it:
 593       if (mid == hi) {
 594         jump_if_true_fork(iff_ge, mid->dest(), mid->table_index());
 595       } else {
 596         Node *iftrue  = _gvn.transform( new IfTrueNode(iff_ge) );
 597         Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
 598         { PreserveJVMState pjvms(this);
 599           set_control(iftrue);
 600           jump_switch_ranges(key_val, mid, hi, switch_depth+1);
 601         }
 602         set_control(iffalse);
 603       }
 604     }
 605 
 606     // in any case, process the lower range
 607     jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
 608   }
 609 
 610   // Decrease pred_count for each successor after all is done.
 611   if (switch_depth == 0) {
 612     int unique_successors = switch_block->num_successors();
 613     for (int i = 0; i < unique_successors; i++) {
 614       Block* target = switch_block->successor_at(i);
 615       // Throw away the pre-allocated path for each unique successor.
 616       target->next_path_num();
 617     }
 618   }
 619 
 620 #ifndef PRODUCT
 621   _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
 622   if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
 623     SwitchRange* r;
 624     int nsing = 0;
 625     for( r = lo; r <= hi; r++ ) {
 626       if( r->is_singleton() )  nsing++;
 627     }
 628     tty->print(">>> ");
 629     _method->print_short_name();
 630     tty->print_cr(" switch decision tree");
 631     tty->print_cr("    %d ranges (%d singletons), max_depth=%d, est_depth=%d",
 632                   (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
 633     if (_max_switch_depth > _est_switch_depth) {
 634       tty->print_cr("******** BAD SWITCH DEPTH ********");
 635     }
 636     tty->print("   ");
 637     for( r = lo; r <= hi; r++ ) {
 638       r->print();
 639     }
 640     tty->cr();
 641   }
 642 #endif
 643 }
 644 
 645 void Parse::modf() {
 646   Node *f2 = pop();
 647   Node *f1 = pop();
 648   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
 649                               CAST_FROM_FN_PTR(address, SharedRuntime::frem),
 650                               "frem", NULL, //no memory effects
 651                               f1, f2);
 652   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
 653 
 654   push(res);
 655 }
 656 
 657 void Parse::modd() {
 658   Node *d2 = pop_pair();
 659   Node *d1 = pop_pair();
 660   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
 661                               CAST_FROM_FN_PTR(address, SharedRuntime::drem),
 662                               "drem", NULL, //no memory effects
 663                               d1, top(), d2, top());
 664   Node* res_d   = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
 665 
 666 #ifdef ASSERT
 667   Node* res_top = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 1));
 668   assert(res_top == top(), "second value must be top");
 669 #endif
 670 
 671   push_pair(res_d);
 672 }
 673 
 674 void Parse::l2f() {
 675   Node* f2 = pop();
 676   Node* f1 = pop();
 677   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
 678                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
 679                               "l2f", NULL, //no memory effects
 680                               f1, f2);
 681   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
 682 
 683   push(res);
 684 }
 685 
 686 void Parse::do_irem() {
 687   // Must keep both values on the expression-stack during null-check
 688   zero_check_int(peek());
 689   // Compile-time detect of null-exception?
 690   if (stopped())  return;
 691 
 692   Node* b = pop();
 693   Node* a = pop();
 694 
 695   const Type *t = _gvn.type(b);
 696   if (t != Type::TOP) {
 697     const TypeInt *ti = t->is_int();
 698     if (ti->is_con()) {
 699       int divisor = ti->get_con();
 700       // check for positive power of 2
 701       if (divisor > 0 &&
 702           (divisor & ~(divisor-1)) == divisor) {
 703         // yes !
 704         Node *mask = _gvn.intcon((divisor - 1));
 705         // Sigh, must handle negative dividends
 706         Node *zero = _gvn.intcon(0);
 707         IfNode *ifff = jump_if_fork_int(a, zero, BoolTest::lt);
 708         Node *iff = _gvn.transform( new IfFalseNode(ifff) );
 709         Node *ift = _gvn.transform( new IfTrueNode (ifff) );
 710         Node *reg = jump_if_join(ift, iff);
 711         Node *phi = PhiNode::make(reg, NULL, TypeInt::INT);
 712         // Negative path; negate/and/negate
 713         Node *neg = _gvn.transform( new SubINode(zero, a) );
 714         Node *andn= _gvn.transform( new AndINode(neg, mask) );
 715         Node *negn= _gvn.transform( new SubINode(zero, andn) );
 716         phi->init_req(1, negn);
 717         // Fast positive case
 718         Node *andx = _gvn.transform( new AndINode(a, mask) );
 719         phi->init_req(2, andx);
 720         // Push the merge
 721         push( _gvn.transform(phi) );
 722         return;
 723       }
 724     }
 725   }
 726   // Default case
 727   push( _gvn.transform( new ModINode(control(),a,b) ) );
 728 }
 729 
 730 // Handle jsr and jsr_w bytecode
 731 void Parse::do_jsr() {
 732   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
 733 
 734   // Store information about current state, tagged with new _jsr_bci
 735   int return_bci = iter().next_bci();
 736   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
 737 
 738   // Update method data
 739   profile_taken_branch(jsr_bci);
 740 
 741   // The way we do things now, there is only one successor block
 742   // for the jsr, because the target code is cloned by ciTypeFlow.
 743   Block* target = successor_for_bci(jsr_bci);
 744 
 745   // What got pushed?
 746   const Type* ret_addr = target->peek();
 747   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
 748 
 749   // Effect on jsr on stack
 750   push(_gvn.makecon(ret_addr));
 751 
 752   // Flow to the jsr.
 753   merge(jsr_bci);
 754 }
 755 
 756 // Handle ret bytecode
 757 void Parse::do_ret() {
 758   // Find to whom we return.
 759   assert(block()->num_successors() == 1, "a ret can only go one place now");
 760   Block* target = block()->successor_at(0);
 761   assert(!target->is_ready(), "our arrival must be expected");
 762   profile_ret(target->flow()->start());
 763   int pnum = target->next_path_num();
 764   merge_common(target, pnum);
 765 }
 766 
 767 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
 768   if (btest != BoolTest::eq && btest != BoolTest::ne) {
 769     // Only ::eq and ::ne are supported for profile injection.
 770     return false;
 771   }
 772   if (test->is_Cmp() &&
 773       test->in(1)->Opcode() == Op_ProfileBoolean) {
 774     ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
 775     int false_cnt = profile->false_count();
 776     int  true_cnt = profile->true_count();
 777 
 778     // Counts matching depends on the actual test operation (::eq or ::ne).
 779     // No need to scale the counts because profile injection was designed
 780     // to feed exact counts into VM.
 781     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
 782     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
 783 
 784     profile->consume();
 785     return true;
 786   }
 787   return false;
 788 }
 789 //--------------------------dynamic_branch_prediction--------------------------
 790 // Try to gather dynamic branch prediction behavior.  Return a probability
 791 // of the branch being taken and set the "cnt" field.  Returns a -1.0
 792 // if we need to use static prediction for some reason.
 793 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
 794   ResourceMark rm;
 795 
 796   cnt  = COUNT_UNKNOWN;
 797 
 798   int     taken = 0;
 799   int not_taken = 0;
 800 
 801   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
 802 
 803   if (use_mdo) {
 804     // Use MethodData information if it is available
 805     // FIXME: free the ProfileData structure
 806     ciMethodData* methodData = method()->method_data();
 807     if (!methodData->is_mature())  return PROB_UNKNOWN;
 808     ciProfileData* data = methodData->bci_to_data(bci());
 809     if (!data->is_JumpData())  return PROB_UNKNOWN;
 810 
 811     // get taken and not taken values
 812     taken = data->as_JumpData()->taken();
 813     not_taken = 0;
 814     if (data->is_BranchData()) {
 815       not_taken = data->as_BranchData()->not_taken();
 816     }
 817 
 818     // scale the counts to be commensurate with invocation counts:
 819     taken = method()->scale_count(taken);
 820     not_taken = method()->scale_count(not_taken);
 821   }
 822 
 823   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
 824   // We also check that individual counters are positive first, otherwise the sum can become positive.
 825   if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
 826     if (C->log() != NULL) {
 827       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
 828     }
 829     return PROB_UNKNOWN;
 830   }
 831 
 832   // Compute frequency that we arrive here
 833   float sum = taken + not_taken;
 834   // Adjust, if this block is a cloned private block but the
 835   // Jump counts are shared.  Taken the private counts for
 836   // just this path instead of the shared counts.
 837   if( block()->count() > 0 )
 838     sum = block()->count();
 839   cnt = sum / FreqCountInvocations;
 840 
 841   // Pin probability to sane limits
 842   float prob;
 843   if( !taken )
 844     prob = (0+PROB_MIN) / 2;
 845   else if( !not_taken )
 846     prob = (1+PROB_MAX) / 2;
 847   else {                         // Compute probability of true path
 848     prob = (float)taken / (float)(taken + not_taken);
 849     if (prob > PROB_MAX)  prob = PROB_MAX;
 850     if (prob < PROB_MIN)   prob = PROB_MIN;
 851   }
 852 
 853   assert((cnt > 0.0f) && (prob > 0.0f),
 854          "Bad frequency assignment in if");
 855 
 856   if (C->log() != NULL) {
 857     const char* prob_str = NULL;
 858     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
 859     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
 860     char prob_str_buf[30];
 861     if (prob_str == NULL) {
 862       sprintf(prob_str_buf, "%g", prob);
 863       prob_str = prob_str_buf;
 864     }
 865     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%g' prob='%s'",
 866                    iter().get_dest(), taken, not_taken, cnt, prob_str);
 867   }
 868   return prob;
 869 }
 870 
 871 //-----------------------------branch_prediction-------------------------------
 872 float Parse::branch_prediction(float& cnt,
 873                                BoolTest::mask btest,
 874                                int target_bci,
 875                                Node* test) {
 876   float prob = dynamic_branch_prediction(cnt, btest, test);
 877   // If prob is unknown, switch to static prediction
 878   if (prob != PROB_UNKNOWN)  return prob;
 879 
 880   prob = PROB_FAIR;                   // Set default value
 881   if (btest == BoolTest::eq)          // Exactly equal test?
 882     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
 883   else if (btest == BoolTest::ne)
 884     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
 885 
 886   // If this is a conditional test guarding a backwards branch,
 887   // assume its a loop-back edge.  Make it a likely taken branch.
 888   if (target_bci < bci()) {
 889     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
 890       // Since it's an OSR, we probably have profile data, but since
 891       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
 892       // Let's make a special check here for completely zero counts.
 893       ciMethodData* methodData = method()->method_data();
 894       if (!methodData->is_empty()) {
 895         ciProfileData* data = methodData->bci_to_data(bci());
 896         // Only stop for truly zero counts, which mean an unknown part
 897         // of the OSR-ed method, and we want to deopt to gather more stats.
 898         // If you have ANY counts, then this loop is simply 'cold' relative
 899         // to the OSR loop.
 900         if (data->as_BranchData()->taken() +
 901             data->as_BranchData()->not_taken() == 0 ) {
 902           // This is the only way to return PROB_UNKNOWN:
 903           return PROB_UNKNOWN;
 904         }
 905       }
 906     }
 907     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
 908   }
 909 
 910   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
 911   return prob;
 912 }
 913 
 914 // The magic constants are chosen so as to match the output of
 915 // branch_prediction() when the profile reports a zero taken count.
 916 // It is important to distinguish zero counts unambiguously, because
 917 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
 918 // very small but nonzero probabilities, which if confused with zero
 919 // counts would keep the program recompiling indefinitely.
 920 bool Parse::seems_never_taken(float prob) const {
 921   return prob < PROB_MIN;
 922 }
 923 
 924 // True if the comparison seems to be the kind that will not change its
 925 // statistics from true to false.  See comments in adjust_map_after_if.
 926 // This question is only asked along paths which are already
 927 // classifed as untaken (by seems_never_taken), so really,
 928 // if a path is never taken, its controlling comparison is
 929 // already acting in a stable fashion.  If the comparison
 930 // seems stable, we will put an expensive uncommon trap
 931 // on the untaken path.
 932 bool Parse::seems_stable_comparison() const {
 933   if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
 934     return false;
 935   }
 936   return true;
 937 }
 938 
 939 //-------------------------------repush_if_args--------------------------------
 940 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
 941 inline int Parse::repush_if_args() {
 942 #ifndef PRODUCT
 943   if (PrintOpto && WizardMode) {
 944     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
 945                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
 946     method()->print_name(); tty->cr();
 947   }
 948 #endif
 949   int bc_depth = - Bytecodes::depth(iter().cur_bc());
 950   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
 951   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
 952   assert(argument(0) != NULL, "must exist");
 953   assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
 954   inc_sp(bc_depth);
 955   return bc_depth;
 956 }
 957 
 958 //----------------------------------do_ifnull----------------------------------
 959 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
 960   int target_bci = iter().get_dest();
 961 
 962   Block* branch_block = successor_for_bci(target_bci);
 963   Block* next_block   = successor_for_bci(iter().next_bci());
 964 
 965   float cnt;
 966   float prob = branch_prediction(cnt, btest, target_bci, c);
 967   if (prob == PROB_UNKNOWN) {
 968     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
 969 #ifndef PRODUCT
 970     if (PrintOpto && Verbose)
 971       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
 972 #endif
 973     repush_if_args(); // to gather stats on loop
 974     // We need to mark this branch as taken so that if we recompile we will
 975     // see that it is possible. In the tiered system the interpreter doesn't
 976     // do profiling and by the time we get to the lower tier from the interpreter
 977     // the path may be cold again. Make sure it doesn't look untaken
 978     profile_taken_branch(target_bci, !ProfileInterpreter);
 979     uncommon_trap(Deoptimization::Reason_unreached,
 980                   Deoptimization::Action_reinterpret,
 981                   NULL, "cold");
 982     if (C->eliminate_boxing()) {
 983       // Mark the successor blocks as parsed
 984       branch_block->next_path_num();
 985       next_block->next_path_num();
 986     }
 987     return;
 988   }
 989 
 990   explicit_null_checks_inserted++;
 991 
 992   // Generate real control flow
 993   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
 994 
 995   // Sanity check the probability value
 996   assert(prob > 0.0f,"Bad probability in Parser");
 997  // Need xform to put node in hash table
 998   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
 999   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1000   // True branch
1001   { PreserveJVMState pjvms(this);
1002     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1003     set_control(iftrue);
1004 
1005     if (stopped()) {            // Path is dead?
1006       explicit_null_checks_elided++;
1007       if (C->eliminate_boxing()) {
1008         // Mark the successor block as parsed
1009         branch_block->next_path_num();
1010       }
1011     } else {                    // Path is live.
1012       // Update method data
1013       profile_taken_branch(target_bci);
1014       adjust_map_after_if(btest, c, prob, branch_block, next_block);
1015       if (!stopped()) {
1016         merge(target_bci);
1017       }
1018     }
1019   }
1020 
1021   // False branch
1022   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1023   set_control(iffalse);
1024 
1025   if (stopped()) {              // Path is dead?
1026     explicit_null_checks_elided++;
1027     if (C->eliminate_boxing()) {
1028       // Mark the successor block as parsed
1029       next_block->next_path_num();
1030     }
1031   } else  {                     // Path is live.
1032     // Update method data
1033     profile_not_taken_branch();
1034     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob,
1035                         next_block, branch_block);
1036   }
1037 }
1038 
1039 //------------------------------------do_if------------------------------------
1040 void Parse::do_if(BoolTest::mask btest, Node* c) {
1041   int target_bci = iter().get_dest();
1042 
1043   Block* branch_block = successor_for_bci(target_bci);
1044   Block* next_block   = successor_for_bci(iter().next_bci());
1045 
1046   float cnt;
1047   float prob = branch_prediction(cnt, btest, target_bci, c);
1048   float untaken_prob = 1.0 - prob;
1049 
1050   if (prob == PROB_UNKNOWN) {
1051 #ifndef PRODUCT
1052     if (PrintOpto && Verbose)
1053       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
1054 #endif
1055     repush_if_args(); // to gather stats on loop
1056     // We need to mark this branch as taken so that if we recompile we will
1057     // see that it is possible. In the tiered system the interpreter doesn't
1058     // do profiling and by the time we get to the lower tier from the interpreter
1059     // the path may be cold again. Make sure it doesn't look untaken
1060     profile_taken_branch(target_bci, !ProfileInterpreter);
1061     uncommon_trap(Deoptimization::Reason_unreached,
1062                   Deoptimization::Action_reinterpret,
1063                   NULL, "cold");
1064     if (C->eliminate_boxing()) {
1065       // Mark the successor blocks as parsed
1066       branch_block->next_path_num();
1067       next_block->next_path_num();
1068     }
1069     return;
1070   }
1071 
1072   // Sanity check the probability value
1073   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1074 
1075   bool taken_if_true = true;
1076   // Convert BoolTest to canonical form:
1077   if (!BoolTest(btest).is_canonical()) {
1078     btest         = BoolTest(btest).negate();
1079     taken_if_true = false;
1080     // prob is NOT updated here; it remains the probability of the taken
1081     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1082   }
1083   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1084 
1085   Node* tst0 = new BoolNode(c, btest);
1086   Node* tst = _gvn.transform(tst0);
1087   BoolTest::mask taken_btest   = BoolTest::illegal;
1088   BoolTest::mask untaken_btest = BoolTest::illegal;
1089 
1090   if (tst->is_Bool()) {
1091     // Refresh c from the transformed bool node, since it may be
1092     // simpler than the original c.  Also re-canonicalize btest.
1093     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)).
1094     // That can arise from statements like: if (x instanceof C) ...
1095     if (tst != tst0) {
1096       // Canonicalize one more time since transform can change it.
1097       btest = tst->as_Bool()->_test._test;
1098       if (!BoolTest(btest).is_canonical()) {
1099         // Reverse edges one more time...
1100         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1101         btest = tst->as_Bool()->_test._test;
1102         assert(BoolTest(btest).is_canonical(), "sanity");
1103         taken_if_true = !taken_if_true;
1104       }
1105       c = tst->in(1);
1106     }
1107     BoolTest::mask neg_btest = BoolTest(btest).negate();
1108     taken_btest   = taken_if_true ?     btest : neg_btest;
1109     untaken_btest = taken_if_true ? neg_btest :     btest;
1110   }
1111 
1112   // Generate real control flow
1113   float true_prob = (taken_if_true ? prob : untaken_prob);
1114   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1115   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1116   Node* taken_branch   = new IfTrueNode(iff);
1117   Node* untaken_branch = new IfFalseNode(iff);
1118   if (!taken_if_true) {  // Finish conversion to canonical form
1119     Node* tmp      = taken_branch;
1120     taken_branch   = untaken_branch;
1121     untaken_branch = tmp;
1122   }
1123 
1124   // Branch is taken:
1125   { PreserveJVMState pjvms(this);
1126     taken_branch = _gvn.transform(taken_branch);
1127     set_control(taken_branch);
1128 
1129     if (stopped()) {
1130       if (C->eliminate_boxing()) {
1131         // Mark the successor block as parsed
1132         branch_block->next_path_num();
1133       }
1134     } else {
1135       // Update method data
1136       profile_taken_branch(target_bci);
1137       adjust_map_after_if(taken_btest, c, prob, branch_block, next_block);
1138       if (!stopped()) {
1139         merge(target_bci);
1140       }
1141     }
1142   }
1143 
1144   untaken_branch = _gvn.transform(untaken_branch);
1145   set_control(untaken_branch);
1146 
1147   // Branch not taken.
1148   if (stopped()) {
1149     if (C->eliminate_boxing()) {
1150       // Mark the successor block as parsed
1151       next_block->next_path_num();
1152     }
1153   } else {
1154     // Update method data
1155     profile_not_taken_branch();
1156     adjust_map_after_if(untaken_btest, c, untaken_prob,
1157                         next_block, branch_block);
1158   }
1159 }
1160 
1161 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1162   // Don't want to speculate on uncommon traps when running with -Xcomp
1163   if (!UseInterpreter) {
1164     return false;
1165   }
1166   return (seems_never_taken(prob) && seems_stable_comparison());
1167 }
1168 
1169 //----------------------------adjust_map_after_if------------------------------
1170 // Adjust the JVM state to reflect the result of taking this path.
1171 // Basically, it means inspecting the CmpNode controlling this
1172 // branch, seeing how it constrains a tested value, and then
1173 // deciding if it's worth our while to encode this constraint
1174 // as graph nodes in the current abstract interpretation map.
1175 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
1176                                 Block* path, Block* other_path) {
1177   if (stopped() || !c->is_Cmp() || btest == BoolTest::illegal)
1178     return;                             // nothing to do
1179 
1180   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1181 
1182   if (path_is_suitable_for_uncommon_trap(prob)) {
1183     repush_if_args();
1184     uncommon_trap(Deoptimization::Reason_unstable_if,
1185                   Deoptimization::Action_reinterpret,
1186                   NULL,
1187                   (is_fallthrough ? "taken always" : "taken never"));
1188     return;
1189   }
1190 
1191   Node* val = c->in(1);
1192   Node* con = c->in(2);
1193   const Type* tcon = _gvn.type(con);
1194   const Type* tval = _gvn.type(val);
1195   bool have_con = tcon->singleton();
1196   if (tval->singleton()) {
1197     if (!have_con) {
1198       // Swap, so constant is in con.
1199       con  = val;
1200       tcon = tval;
1201       val  = c->in(2);
1202       tval = _gvn.type(val);
1203       btest = BoolTest(btest).commute();
1204       have_con = true;
1205     } else {
1206       // Do we have two constants?  Then leave well enough alone.
1207       have_con = false;
1208     }
1209   }
1210   if (!have_con)                        // remaining adjustments need a con
1211     return;
1212 
1213   sharpen_type_after_if(btest, con, tcon, val, tval);
1214 }
1215 
1216 
1217 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1218   Node* ldk;
1219   if (n->is_DecodeNKlass()) {
1220     if (n->in(1)->Opcode() != Op_LoadNKlass) {
1221       return NULL;
1222     } else {
1223       ldk = n->in(1);
1224     }
1225   } else if (n->Opcode() != Op_LoadKlass) {
1226     return NULL;
1227   } else {
1228     ldk = n;
1229   }
1230   assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1231 
1232   Node* adr = ldk->in(MemNode::Address);
1233   intptr_t off = 0;
1234   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1235   if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1236     return NULL;
1237   const TypePtr* tp = gvn->type(obj)->is_ptr();
1238   if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1239     return NULL;
1240 
1241   return obj;
1242 }
1243 
1244 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1245                                   Node* con, const Type* tcon,
1246                                   Node* val, const Type* tval) {
1247   // Look for opportunities to sharpen the type of a node
1248   // whose klass is compared with a constant klass.
1249   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1250     Node* obj = extract_obj_from_klass_load(&_gvn, val);
1251     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1252     if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1253        // Found:
1254        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1255        // or the narrowOop equivalent.
1256        const Type* obj_type = _gvn.type(obj);
1257        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1258        if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
1259            tboth->higher_equal(obj_type)) {
1260           // obj has to be of the exact type Foo if the CmpP succeeds.
1261           int obj_in_map = map()->find_edge(obj);
1262           JVMState* jvms = this->jvms();
1263           if (obj_in_map >= 0 &&
1264               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1265             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1266             const Type* tcc = ccast->as_Type()->type();
1267             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1268             // Delay transform() call to allow recovery of pre-cast value
1269             // at the control merge.
1270             _gvn.set_type_bottom(ccast);
1271             record_for_igvn(ccast);
1272             // Here's the payoff.
1273             replace_in_map(obj, ccast);
1274           }
1275        }
1276     }
1277   }
1278 
1279   int val_in_map = map()->find_edge(val);
1280   if (val_in_map < 0)  return;          // replace_in_map would be useless
1281   {
1282     JVMState* jvms = this->jvms();
1283     if (!(jvms->is_loc(val_in_map) ||
1284           jvms->is_stk(val_in_map)))
1285       return;                           // again, it would be useless
1286   }
1287 
1288   // Check for a comparison to a constant, and "know" that the compared
1289   // value is constrained on this path.
1290   assert(tcon->singleton(), "");
1291   ConstraintCastNode* ccast = NULL;
1292   Node* cast = NULL;
1293 
1294   switch (btest) {
1295   case BoolTest::eq:                    // Constant test?
1296     {
1297       const Type* tboth = tcon->join_speculative(tval);
1298       if (tboth == tval)  break;        // Nothing to gain.
1299       if (tcon->isa_int()) {
1300         ccast = new CastIINode(val, tboth);
1301       } else if (tcon == TypePtr::NULL_PTR) {
1302         // Cast to null, but keep the pointer identity temporarily live.
1303         ccast = new CastPPNode(val, tboth);
1304       } else {
1305         const TypeF* tf = tcon->isa_float_constant();
1306         const TypeD* td = tcon->isa_double_constant();
1307         // Exclude tests vs float/double 0 as these could be
1308         // either +0 or -0.  Just because you are equal to +0
1309         // doesn't mean you ARE +0!
1310         // Note, following code also replaces Long and Oop values.
1311         if ((!tf || tf->_f != 0.0) &&
1312             (!td || td->_d != 0.0))
1313           cast = con;                   // Replace non-constant val by con.
1314       }
1315     }
1316     break;
1317 
1318   case BoolTest::ne:
1319     if (tcon == TypePtr::NULL_PTR) {
1320       cast = cast_not_null(val, false);
1321     }
1322     break;
1323 
1324   default:
1325     // (At this point we could record int range types with CastII.)
1326     break;
1327   }
1328 
1329   if (ccast != NULL) {
1330     const Type* tcc = ccast->as_Type()->type();
1331     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1332     // Delay transform() call to allow recovery of pre-cast value
1333     // at the control merge.
1334     ccast->set_req(0, control());
1335     _gvn.set_type_bottom(ccast);
1336     record_for_igvn(ccast);
1337     cast = ccast;
1338   }
1339 
1340   if (cast != NULL) {                   // Here's the payoff.
1341     replace_in_map(val, cast);
1342   }
1343 }
1344 
1345 /**
1346  * Use speculative type to optimize CmpP node: if comparison is
1347  * against the low level class, cast the object to the speculative
1348  * type if any. CmpP should then go away.
1349  *
1350  * @param c  expected CmpP node
1351  * @return   result of CmpP on object casted to speculative type
1352  *
1353  */
1354 Node* Parse::optimize_cmp_with_klass(Node* c) {
1355   // If this is transformed by the _gvn to a comparison with the low
1356   // level klass then we may be able to use speculation
1357   if (c->Opcode() == Op_CmpP &&
1358       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1359       c->in(2)->is_Con()) {
1360     Node* load_klass = NULL;
1361     Node* decode = NULL;
1362     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1363       decode = c->in(1);
1364       load_klass = c->in(1)->in(1);
1365     } else {
1366       load_klass = c->in(1);
1367     }
1368     if (load_klass->in(2)->is_AddP()) {
1369       Node* addp = load_klass->in(2);
1370       Node* obj = addp->in(AddPNode::Address);
1371       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1372       if (obj_type->speculative_type_not_null() != NULL) {
1373         ciKlass* k = obj_type->speculative_type();
1374         inc_sp(2);
1375         obj = maybe_cast_profiled_obj(obj, k);
1376         dec_sp(2);
1377         // Make the CmpP use the casted obj
1378         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1379         load_klass = load_klass->clone();
1380         load_klass->set_req(2, addp);
1381         load_klass = _gvn.transform(load_klass);
1382         if (decode != NULL) {
1383           decode = decode->clone();
1384           decode->set_req(1, load_klass);
1385           load_klass = _gvn.transform(decode);
1386         }
1387         c = c->clone();
1388         c->set_req(1, load_klass);
1389         c = _gvn.transform(c);
1390       }
1391     }
1392   }
1393   return c;
1394 }
1395 
1396 //------------------------------do_one_bytecode--------------------------------
1397 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1398 void Parse::do_one_bytecode() {
1399   Node *a, *b, *c, *d;          // Handy temps
1400   BoolTest::mask btest;
1401   int i;
1402 
1403   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1404 
1405   if (C->check_node_count(NodeLimitFudgeFactor * 5,
1406                           "out of nodes parsing method")) {
1407     return;
1408   }
1409 
1410 #ifdef ASSERT
1411   // for setting breakpoints
1412   if (TraceOptoParse) {
1413     tty->print(" @");
1414     dump_bci(bci());
1415     tty->cr();
1416   }
1417 #endif
1418 
1419   switch (bc()) {
1420   case Bytecodes::_nop:
1421     // do nothing
1422     break;
1423   case Bytecodes::_lconst_0:
1424     push_pair(longcon(0));
1425     break;
1426 
1427   case Bytecodes::_lconst_1:
1428     push_pair(longcon(1));
1429     break;
1430 
1431   case Bytecodes::_fconst_0:
1432     push(zerocon(T_FLOAT));
1433     break;
1434 
1435   case Bytecodes::_fconst_1:
1436     push(makecon(TypeF::ONE));
1437     break;
1438 
1439   case Bytecodes::_fconst_2:
1440     push(makecon(TypeF::make(2.0f)));
1441     break;
1442 
1443   case Bytecodes::_dconst_0:
1444     push_pair(zerocon(T_DOUBLE));
1445     break;
1446 
1447   case Bytecodes::_dconst_1:
1448     push_pair(makecon(TypeD::ONE));
1449     break;
1450 
1451   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1452   case Bytecodes::_iconst_0: push(intcon( 0)); break;
1453   case Bytecodes::_iconst_1: push(intcon( 1)); break;
1454   case Bytecodes::_iconst_2: push(intcon( 2)); break;
1455   case Bytecodes::_iconst_3: push(intcon( 3)); break;
1456   case Bytecodes::_iconst_4: push(intcon( 4)); break;
1457   case Bytecodes::_iconst_5: push(intcon( 5)); break;
1458   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
1459   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
1460   case Bytecodes::_aconst_null: push(null());  break;
1461   case Bytecodes::_ldc:
1462   case Bytecodes::_ldc_w:
1463   case Bytecodes::_ldc2_w:
1464     // If the constant is unresolved, run this BC once in the interpreter.
1465     {
1466       ciConstant constant = iter().get_constant();
1467       if (constant.basic_type() == T_OBJECT &&
1468           !constant.as_object()->is_loaded()) {
1469         int index = iter().get_constant_pool_index();
1470         constantTag tag = iter().get_constant_pool_tag(index);
1471         uncommon_trap(Deoptimization::make_trap_request
1472                       (Deoptimization::Reason_unloaded,
1473                        Deoptimization::Action_reinterpret,
1474                        index),
1475                       NULL, tag.internal_name());
1476         break;
1477       }
1478       assert(constant.basic_type() != T_OBJECT || constant.as_object()->is_instance(),
1479              "must be java_mirror of klass");
1480       bool pushed = push_constant(constant, true);
1481       guarantee(pushed, "must be possible to push this constant");
1482     }
1483 
1484     break;
1485 
1486   case Bytecodes::_aload_0:
1487     push( local(0) );
1488     break;
1489   case Bytecodes::_aload_1:
1490     push( local(1) );
1491     break;
1492   case Bytecodes::_aload_2:
1493     push( local(2) );
1494     break;
1495   case Bytecodes::_aload_3:
1496     push( local(3) );
1497     break;
1498   case Bytecodes::_aload:
1499     push( local(iter().get_index()) );
1500     break;
1501 
1502   case Bytecodes::_fload_0:
1503   case Bytecodes::_iload_0:
1504     push( local(0) );
1505     break;
1506   case Bytecodes::_fload_1:
1507   case Bytecodes::_iload_1:
1508     push( local(1) );
1509     break;
1510   case Bytecodes::_fload_2:
1511   case Bytecodes::_iload_2:
1512     push( local(2) );
1513     break;
1514   case Bytecodes::_fload_3:
1515   case Bytecodes::_iload_3:
1516     push( local(3) );
1517     break;
1518   case Bytecodes::_fload:
1519   case Bytecodes::_iload:
1520     push( local(iter().get_index()) );
1521     break;
1522   case Bytecodes::_lload_0:
1523     push_pair_local( 0 );
1524     break;
1525   case Bytecodes::_lload_1:
1526     push_pair_local( 1 );
1527     break;
1528   case Bytecodes::_lload_2:
1529     push_pair_local( 2 );
1530     break;
1531   case Bytecodes::_lload_3:
1532     push_pair_local( 3 );
1533     break;
1534   case Bytecodes::_lload:
1535     push_pair_local( iter().get_index() );
1536     break;
1537 
1538   case Bytecodes::_dload_0:
1539     push_pair_local(0);
1540     break;
1541   case Bytecodes::_dload_1:
1542     push_pair_local(1);
1543     break;
1544   case Bytecodes::_dload_2:
1545     push_pair_local(2);
1546     break;
1547   case Bytecodes::_dload_3:
1548     push_pair_local(3);
1549     break;
1550   case Bytecodes::_dload:
1551     push_pair_local(iter().get_index());
1552     break;
1553   case Bytecodes::_fstore_0:
1554   case Bytecodes::_istore_0:
1555   case Bytecodes::_astore_0:
1556     set_local( 0, pop() );
1557     break;
1558   case Bytecodes::_fstore_1:
1559   case Bytecodes::_istore_1:
1560   case Bytecodes::_astore_1:
1561     set_local( 1, pop() );
1562     break;
1563   case Bytecodes::_fstore_2:
1564   case Bytecodes::_istore_2:
1565   case Bytecodes::_astore_2:
1566     set_local( 2, pop() );
1567     break;
1568   case Bytecodes::_fstore_3:
1569   case Bytecodes::_istore_3:
1570   case Bytecodes::_astore_3:
1571     set_local( 3, pop() );
1572     break;
1573   case Bytecodes::_fstore:
1574   case Bytecodes::_istore:
1575   case Bytecodes::_astore:
1576     set_local( iter().get_index(), pop() );
1577     break;
1578   // long stores
1579   case Bytecodes::_lstore_0:
1580     set_pair_local( 0, pop_pair() );
1581     break;
1582   case Bytecodes::_lstore_1:
1583     set_pair_local( 1, pop_pair() );
1584     break;
1585   case Bytecodes::_lstore_2:
1586     set_pair_local( 2, pop_pair() );
1587     break;
1588   case Bytecodes::_lstore_3:
1589     set_pair_local( 3, pop_pair() );
1590     break;
1591   case Bytecodes::_lstore:
1592     set_pair_local( iter().get_index(), pop_pair() );
1593     break;
1594 
1595   // double stores
1596   case Bytecodes::_dstore_0:
1597     set_pair_local( 0, dstore_rounding(pop_pair()) );
1598     break;
1599   case Bytecodes::_dstore_1:
1600     set_pair_local( 1, dstore_rounding(pop_pair()) );
1601     break;
1602   case Bytecodes::_dstore_2:
1603     set_pair_local( 2, dstore_rounding(pop_pair()) );
1604     break;
1605   case Bytecodes::_dstore_3:
1606     set_pair_local( 3, dstore_rounding(pop_pair()) );
1607     break;
1608   case Bytecodes::_dstore:
1609     set_pair_local( iter().get_index(), dstore_rounding(pop_pair()) );
1610     break;
1611 
1612   case Bytecodes::_pop:  dec_sp(1);   break;
1613   case Bytecodes::_pop2: dec_sp(2);   break;
1614   case Bytecodes::_swap:
1615     a = pop();
1616     b = pop();
1617     push(a);
1618     push(b);
1619     break;
1620   case Bytecodes::_dup:
1621     a = pop();
1622     push(a);
1623     push(a);
1624     break;
1625   case Bytecodes::_dup_x1:
1626     a = pop();
1627     b = pop();
1628     push( a );
1629     push( b );
1630     push( a );
1631     break;
1632   case Bytecodes::_dup_x2:
1633     a = pop();
1634     b = pop();
1635     c = pop();
1636     push( a );
1637     push( c );
1638     push( b );
1639     push( a );
1640     break;
1641   case Bytecodes::_dup2:
1642     a = pop();
1643     b = pop();
1644     push( b );
1645     push( a );
1646     push( b );
1647     push( a );
1648     break;
1649 
1650   case Bytecodes::_dup2_x1:
1651     // before: .. c, b, a
1652     // after:  .. b, a, c, b, a
1653     // not tested
1654     a = pop();
1655     b = pop();
1656     c = pop();
1657     push( b );
1658     push( a );
1659     push( c );
1660     push( b );
1661     push( a );
1662     break;
1663   case Bytecodes::_dup2_x2:
1664     // before: .. d, c, b, a
1665     // after:  .. b, a, d, c, b, a
1666     // not tested
1667     a = pop();
1668     b = pop();
1669     c = pop();
1670     d = pop();
1671     push( b );
1672     push( a );
1673     push( d );
1674     push( c );
1675     push( b );
1676     push( a );
1677     break;
1678 
1679   case Bytecodes::_arraylength: {
1680     // Must do null-check with value on expression stack
1681     Node *ary = null_check(peek(), T_ARRAY);
1682     // Compile-time detect of null-exception?
1683     if (stopped())  return;
1684     a = pop();
1685     push(load_array_length(a));
1686     break;
1687   }
1688 
1689   case Bytecodes::_baload: array_load(T_BYTE);   break;
1690   case Bytecodes::_caload: array_load(T_CHAR);   break;
1691   case Bytecodes::_iaload: array_load(T_INT);    break;
1692   case Bytecodes::_saload: array_load(T_SHORT);  break;
1693   case Bytecodes::_faload: array_load(T_FLOAT);  break;
1694   case Bytecodes::_aaload: array_load(T_OBJECT); break;
1695   case Bytecodes::_laload: {
1696     a = array_addressing(T_LONG, 0);
1697     if (stopped())  return;     // guaranteed null or range check
1698     dec_sp(2);                  // Pop array and index
1699     push_pair(make_load(control(), a, TypeLong::LONG, T_LONG, TypeAryPtr::LONGS, MemNode::unordered));
1700     break;
1701   }
1702   case Bytecodes::_daload: {
1703     a = array_addressing(T_DOUBLE, 0);
1704     if (stopped())  return;     // guaranteed null or range check
1705     dec_sp(2);                  // Pop array and index
1706     push_pair(make_load(control(), a, Type::DOUBLE, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered));
1707     break;
1708   }
1709   case Bytecodes::_bastore: array_store(T_BYTE);  break;
1710   case Bytecodes::_castore: array_store(T_CHAR);  break;
1711   case Bytecodes::_iastore: array_store(T_INT);   break;
1712   case Bytecodes::_sastore: array_store(T_SHORT); break;
1713   case Bytecodes::_fastore: array_store(T_FLOAT); break;
1714   case Bytecodes::_aastore: {
1715     d = array_addressing(T_OBJECT, 1);
1716     if (stopped())  return;     // guaranteed null or range check
1717     array_store_check();
1718     c = pop();                  // Oop to store
1719     b = pop();                  // index (already used)
1720     a = pop();                  // the array itself
1721     const TypeOopPtr* elemtype  = _gvn.type(a)->is_aryptr()->elem()->make_oopptr();
1722     const TypeAryPtr* adr_type = TypeAryPtr::OOPS;
1723     Node* store = store_oop_to_array(control(), a, d, adr_type, c, elemtype, T_OBJECT, MemNode::release);
1724     break;
1725   }
1726   case Bytecodes::_lastore: {
1727     a = array_addressing(T_LONG, 2);
1728     if (stopped())  return;     // guaranteed null or range check
1729     c = pop_pair();
1730     dec_sp(2);                  // Pop array and index
1731     store_to_memory(control(), a, c, T_LONG, TypeAryPtr::LONGS, MemNode::unordered);
1732     break;
1733   }
1734   case Bytecodes::_dastore: {
1735     a = array_addressing(T_DOUBLE, 2);
1736     if (stopped())  return;     // guaranteed null or range check
1737     c = pop_pair();
1738     dec_sp(2);                  // Pop array and index
1739     c = dstore_rounding(c);
1740     store_to_memory(control(), a, c, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered);
1741     break;
1742   }
1743   case Bytecodes::_getfield:
1744     do_getfield();
1745     break;
1746 
1747   case Bytecodes::_getstatic:
1748     do_getstatic();
1749     break;
1750 
1751   case Bytecodes::_putfield:
1752     do_putfield();
1753     break;
1754 
1755   case Bytecodes::_putstatic:
1756     do_putstatic();
1757     break;
1758 
1759   case Bytecodes::_irem:
1760     do_irem();
1761     break;
1762   case Bytecodes::_idiv:
1763     // Must keep both values on the expression-stack during null-check
1764     zero_check_int(peek());
1765     // Compile-time detect of null-exception?
1766     if (stopped())  return;
1767     b = pop();
1768     a = pop();
1769     push( _gvn.transform( new DivINode(control(),a,b) ) );
1770     break;
1771   case Bytecodes::_imul:
1772     b = pop(); a = pop();
1773     push( _gvn.transform( new MulINode(a,b) ) );
1774     break;
1775   case Bytecodes::_iadd:
1776     b = pop(); a = pop();
1777     push( _gvn.transform( new AddINode(a,b) ) );
1778     break;
1779   case Bytecodes::_ineg:
1780     a = pop();
1781     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
1782     break;
1783   case Bytecodes::_isub:
1784     b = pop(); a = pop();
1785     push( _gvn.transform( new SubINode(a,b) ) );
1786     break;
1787   case Bytecodes::_iand:
1788     b = pop(); a = pop();
1789     push( _gvn.transform( new AndINode(a,b) ) );
1790     break;
1791   case Bytecodes::_ior:
1792     b = pop(); a = pop();
1793     push( _gvn.transform( new OrINode(a,b) ) );
1794     break;
1795   case Bytecodes::_ixor:
1796     b = pop(); a = pop();
1797     push( _gvn.transform( new XorINode(a,b) ) );
1798     break;
1799   case Bytecodes::_ishl:
1800     b = pop(); a = pop();
1801     push( _gvn.transform( new LShiftINode(a,b) ) );
1802     break;
1803   case Bytecodes::_ishr:
1804     b = pop(); a = pop();
1805     push( _gvn.transform( new RShiftINode(a,b) ) );
1806     break;
1807   case Bytecodes::_iushr:
1808     b = pop(); a = pop();
1809     push( _gvn.transform( new URShiftINode(a,b) ) );
1810     break;
1811 
1812   case Bytecodes::_fneg:
1813     a = pop();
1814     b = _gvn.transform(new NegFNode (a));
1815     push(b);
1816     break;
1817 
1818   case Bytecodes::_fsub:
1819     b = pop();
1820     a = pop();
1821     c = _gvn.transform( new SubFNode(a,b) );
1822     d = precision_rounding(c);
1823     push( d );
1824     break;
1825 
1826   case Bytecodes::_fadd:
1827     b = pop();
1828     a = pop();
1829     c = _gvn.transform( new AddFNode(a,b) );
1830     d = precision_rounding(c);
1831     push( d );
1832     break;
1833 
1834   case Bytecodes::_fmul:
1835     b = pop();
1836     a = pop();
1837     c = _gvn.transform( new MulFNode(a,b) );
1838     d = precision_rounding(c);
1839     push( d );
1840     break;
1841 
1842   case Bytecodes::_fdiv:
1843     b = pop();
1844     a = pop();
1845     c = _gvn.transform( new DivFNode(0,a,b) );
1846     d = precision_rounding(c);
1847     push( d );
1848     break;
1849 
1850   case Bytecodes::_frem:
1851     if (Matcher::has_match_rule(Op_ModF)) {
1852       // Generate a ModF node.
1853       b = pop();
1854       a = pop();
1855       c = _gvn.transform( new ModFNode(0,a,b) );
1856       d = precision_rounding(c);
1857       push( d );
1858     }
1859     else {
1860       // Generate a call.
1861       modf();
1862     }
1863     break;
1864 
1865   case Bytecodes::_fcmpl:
1866     b = pop();
1867     a = pop();
1868     c = _gvn.transform( new CmpF3Node( a, b));
1869     push(c);
1870     break;
1871   case Bytecodes::_fcmpg:
1872     b = pop();
1873     a = pop();
1874 
1875     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
1876     // which negates the result sign except for unordered.  Flip the unordered
1877     // as well by using CmpF3 which implements unordered-lesser instead of
1878     // unordered-greater semantics.  Finally, commute the result bits.  Result
1879     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
1880     c = _gvn.transform( new CmpF3Node( b, a));
1881     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
1882     push(c);
1883     break;
1884 
1885   case Bytecodes::_f2i:
1886     a = pop();
1887     push(_gvn.transform(new ConvF2INode(a)));
1888     break;
1889 
1890   case Bytecodes::_d2i:
1891     a = pop_pair();
1892     b = _gvn.transform(new ConvD2INode(a));
1893     push( b );
1894     break;
1895 
1896   case Bytecodes::_f2d:
1897     a = pop();
1898     b = _gvn.transform( new ConvF2DNode(a));
1899     push_pair( b );
1900     break;
1901 
1902   case Bytecodes::_d2f:
1903     a = pop_pair();
1904     b = _gvn.transform( new ConvD2FNode(a));
1905     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
1906     //b = _gvn.transform(new RoundFloatNode(0, b) );
1907     push( b );
1908     break;
1909 
1910   case Bytecodes::_l2f:
1911     if (Matcher::convL2FSupported()) {
1912       a = pop_pair();
1913       b = _gvn.transform( new ConvL2FNode(a));
1914       // For i486.ad, FILD doesn't restrict precision to 24 or 53 bits.
1915       // Rather than storing the result into an FP register then pushing
1916       // out to memory to round, the machine instruction that implements
1917       // ConvL2D is responsible for rounding.
1918       // c = precision_rounding(b);
1919       c = _gvn.transform(b);
1920       push(c);
1921     } else {
1922       l2f();
1923     }
1924     break;
1925 
1926   case Bytecodes::_l2d:
1927     a = pop_pair();
1928     b = _gvn.transform( new ConvL2DNode(a));
1929     // For i486.ad, rounding is always necessary (see _l2f above).
1930     // c = dprecision_rounding(b);
1931     c = _gvn.transform(b);
1932     push_pair(c);
1933     break;
1934 
1935   case Bytecodes::_f2l:
1936     a = pop();
1937     b = _gvn.transform( new ConvF2LNode(a));
1938     push_pair(b);
1939     break;
1940 
1941   case Bytecodes::_d2l:
1942     a = pop_pair();
1943     b = _gvn.transform( new ConvD2LNode(a));
1944     push_pair(b);
1945     break;
1946 
1947   case Bytecodes::_dsub:
1948     b = pop_pair();
1949     a = pop_pair();
1950     c = _gvn.transform( new SubDNode(a,b) );
1951     d = dprecision_rounding(c);
1952     push_pair( d );
1953     break;
1954 
1955   case Bytecodes::_dadd:
1956     b = pop_pair();
1957     a = pop_pair();
1958     c = _gvn.transform( new AddDNode(a,b) );
1959     d = dprecision_rounding(c);
1960     push_pair( d );
1961     break;
1962 
1963   case Bytecodes::_dmul:
1964     b = pop_pair();
1965     a = pop_pair();
1966     c = _gvn.transform( new MulDNode(a,b) );
1967     d = dprecision_rounding(c);
1968     push_pair( d );
1969     break;
1970 
1971   case Bytecodes::_ddiv:
1972     b = pop_pair();
1973     a = pop_pair();
1974     c = _gvn.transform( new DivDNode(0,a,b) );
1975     d = dprecision_rounding(c);
1976     push_pair( d );
1977     break;
1978 
1979   case Bytecodes::_dneg:
1980     a = pop_pair();
1981     b = _gvn.transform(new NegDNode (a));
1982     push_pair(b);
1983     break;
1984 
1985   case Bytecodes::_drem:
1986     if (Matcher::has_match_rule(Op_ModD)) {
1987       // Generate a ModD node.
1988       b = pop_pair();
1989       a = pop_pair();
1990       // a % b
1991 
1992       c = _gvn.transform( new ModDNode(0,a,b) );
1993       d = dprecision_rounding(c);
1994       push_pair( d );
1995     }
1996     else {
1997       // Generate a call.
1998       modd();
1999     }
2000     break;
2001 
2002   case Bytecodes::_dcmpl:
2003     b = pop_pair();
2004     a = pop_pair();
2005     c = _gvn.transform( new CmpD3Node( a, b));
2006     push(c);
2007     break;
2008 
2009   case Bytecodes::_dcmpg:
2010     b = pop_pair();
2011     a = pop_pair();
2012     // Same as dcmpl but need to flip the unordered case.
2013     // Commute the inputs, which negates the result sign except for unordered.
2014     // Flip the unordered as well by using CmpD3 which implements
2015     // unordered-lesser instead of unordered-greater semantics.
2016     // Finally, negate the result bits.  Result is same as using a
2017     // CmpD3Greater except we did it with CmpD3 alone.
2018     c = _gvn.transform( new CmpD3Node( b, a));
2019     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2020     push(c);
2021     break;
2022 
2023 
2024     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2025   case Bytecodes::_land:
2026     b = pop_pair();
2027     a = pop_pair();
2028     c = _gvn.transform( new AndLNode(a,b) );
2029     push_pair(c);
2030     break;
2031   case Bytecodes::_lor:
2032     b = pop_pair();
2033     a = pop_pair();
2034     c = _gvn.transform( new OrLNode(a,b) );
2035     push_pair(c);
2036     break;
2037   case Bytecodes::_lxor:
2038     b = pop_pair();
2039     a = pop_pair();
2040     c = _gvn.transform( new XorLNode(a,b) );
2041     push_pair(c);
2042     break;
2043 
2044   case Bytecodes::_lshl:
2045     b = pop();                  // the shift count
2046     a = pop_pair();             // value to be shifted
2047     c = _gvn.transform( new LShiftLNode(a,b) );
2048     push_pair(c);
2049     break;
2050   case Bytecodes::_lshr:
2051     b = pop();                  // the shift count
2052     a = pop_pair();             // value to be shifted
2053     c = _gvn.transform( new RShiftLNode(a,b) );
2054     push_pair(c);
2055     break;
2056   case Bytecodes::_lushr:
2057     b = pop();                  // the shift count
2058     a = pop_pair();             // value to be shifted
2059     c = _gvn.transform( new URShiftLNode(a,b) );
2060     push_pair(c);
2061     break;
2062   case Bytecodes::_lmul:
2063     b = pop_pair();
2064     a = pop_pair();
2065     c = _gvn.transform( new MulLNode(a,b) );
2066     push_pair(c);
2067     break;
2068 
2069   case Bytecodes::_lrem:
2070     // Must keep both values on the expression-stack during null-check
2071     assert(peek(0) == top(), "long word order");
2072     zero_check_long(peek(1));
2073     // Compile-time detect of null-exception?
2074     if (stopped())  return;
2075     b = pop_pair();
2076     a = pop_pair();
2077     c = _gvn.transform( new ModLNode(control(),a,b) );
2078     push_pair(c);
2079     break;
2080 
2081   case Bytecodes::_ldiv:
2082     // Must keep both values on the expression-stack during null-check
2083     assert(peek(0) == top(), "long word order");
2084     zero_check_long(peek(1));
2085     // Compile-time detect of null-exception?
2086     if (stopped())  return;
2087     b = pop_pair();
2088     a = pop_pair();
2089     c = _gvn.transform( new DivLNode(control(),a,b) );
2090     push_pair(c);
2091     break;
2092 
2093   case Bytecodes::_ladd:
2094     b = pop_pair();
2095     a = pop_pair();
2096     c = _gvn.transform( new AddLNode(a,b) );
2097     push_pair(c);
2098     break;
2099   case Bytecodes::_lsub:
2100     b = pop_pair();
2101     a = pop_pair();
2102     c = _gvn.transform( new SubLNode(a,b) );
2103     push_pair(c);
2104     break;
2105   case Bytecodes::_lcmp:
2106     // Safepoints are now inserted _before_ branches.  The long-compare
2107     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2108     // slew of control flow.  These are usually followed by a CmpI vs zero and
2109     // a branch; this pattern then optimizes to the obvious long-compare and
2110     // branch.  However, if the branch is backwards there's a Safepoint
2111     // inserted.  The inserted Safepoint captures the JVM state at the
2112     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
2113     // long-compare is used to control a loop the debug info will force
2114     // computation of the 3-way value, even though the generated code uses a
2115     // long-compare and branch.  We try to rectify the situation by inserting
2116     // a SafePoint here and have it dominate and kill the safepoint added at a
2117     // following backwards branch.  At this point the JVM state merely holds 2
2118     // longs but not the 3-way value.
2119     if( UseLoopSafepoints ) {
2120       switch( iter().next_bc() ) {
2121       case Bytecodes::_ifgt:
2122       case Bytecodes::_iflt:
2123       case Bytecodes::_ifge:
2124       case Bytecodes::_ifle:
2125       case Bytecodes::_ifne:
2126       case Bytecodes::_ifeq:
2127         // If this is a backwards branch in the bytecodes, add Safepoint
2128         maybe_add_safepoint(iter().next_get_dest());
2129       }
2130     }
2131     b = pop_pair();
2132     a = pop_pair();
2133     c = _gvn.transform( new CmpL3Node( a, b ));
2134     push(c);
2135     break;
2136 
2137   case Bytecodes::_lneg:
2138     a = pop_pair();
2139     b = _gvn.transform( new SubLNode(longcon(0),a));
2140     push_pair(b);
2141     break;
2142   case Bytecodes::_l2i:
2143     a = pop_pair();
2144     push( _gvn.transform( new ConvL2INode(a)));
2145     break;
2146   case Bytecodes::_i2l:
2147     a = pop();
2148     b = _gvn.transform( new ConvI2LNode(a));
2149     push_pair(b);
2150     break;
2151   case Bytecodes::_i2b:
2152     // Sign extend
2153     a = pop();
2154     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(24)) );
2155     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(24)) );
2156     push( a );
2157     break;
2158   case Bytecodes::_i2s:
2159     a = pop();
2160     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(16)) );
2161     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(16)) );
2162     push( a );
2163     break;
2164   case Bytecodes::_i2c:
2165     a = pop();
2166     push( _gvn.transform( new AndINode(a,_gvn.intcon(0xFFFF)) ) );
2167     break;
2168 
2169   case Bytecodes::_i2f:
2170     a = pop();
2171     b = _gvn.transform( new ConvI2FNode(a) ) ;
2172     c = precision_rounding(b);
2173     push (b);
2174     break;
2175 
2176   case Bytecodes::_i2d:
2177     a = pop();
2178     b = _gvn.transform( new ConvI2DNode(a));
2179     push_pair(b);
2180     break;
2181 
2182   case Bytecodes::_iinc:        // Increment local
2183     i = iter().get_index();     // Get local index
2184     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2185     break;
2186 
2187   // Exit points of synchronized methods must have an unlock node
2188   case Bytecodes::_return:
2189     return_current(NULL);
2190     break;
2191 
2192   case Bytecodes::_ireturn:
2193   case Bytecodes::_areturn:
2194   case Bytecodes::_freturn:
2195     return_current(pop());
2196     break;
2197   case Bytecodes::_lreturn:
2198     return_current(pop_pair());
2199     break;
2200   case Bytecodes::_dreturn:
2201     return_current(pop_pair());
2202     break;
2203 
2204   case Bytecodes::_athrow:
2205     // null exception oop throws NULL pointer exception
2206     null_check(peek());
2207     if (stopped())  return;
2208     // Hook the thrown exception directly to subsequent handlers.
2209     if (BailoutToInterpreterForThrows) {
2210       // Keep method interpreted from now on.
2211       uncommon_trap(Deoptimization::Reason_unhandled,
2212                     Deoptimization::Action_make_not_compilable);
2213       return;
2214     }
2215     if (env()->jvmti_can_post_on_exceptions()) {
2216       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2217       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2218     }
2219     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2220     add_exception_state(make_exception_state(peek()));
2221     break;
2222 
2223   case Bytecodes::_goto:   // fall through
2224   case Bytecodes::_goto_w: {
2225     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2226 
2227     // If this is a backwards branch in the bytecodes, add Safepoint
2228     maybe_add_safepoint(target_bci);
2229 
2230     // Update method data
2231     profile_taken_branch(target_bci);
2232 
2233     // Merge the current control into the target basic block
2234     merge(target_bci);
2235 
2236     // See if we can get some profile data and hand it off to the next block
2237     Block *target_block = block()->successor_for_bci(target_bci);
2238     if (target_block->pred_count() != 1)  break;
2239     ciMethodData* methodData = method()->method_data();
2240     if (!methodData->is_mature())  break;
2241     ciProfileData* data = methodData->bci_to_data(bci());
2242     assert( data->is_JumpData(), "" );
2243     int taken = ((ciJumpData*)data)->taken();
2244     taken = method()->scale_count(taken);
2245     target_block->set_count(taken);
2246     break;
2247   }
2248 
2249   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
2250   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2251   handle_if_null:
2252     // If this is a backwards branch in the bytecodes, add Safepoint
2253     maybe_add_safepoint(iter().get_dest());
2254     a = null();
2255     b = pop();
2256     if (!_gvn.type(b)->speculative_maybe_null() &&
2257         !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2258       inc_sp(1);
2259       Node* null_ctl = top();
2260       b = null_check_oop(b, &null_ctl, true, true, true);
2261       assert(null_ctl->is_top(), "no null control here");
2262       dec_sp(1);
2263     }
2264     c = _gvn.transform( new CmpPNode(b, a) );
2265     do_ifnull(btest, c);
2266     break;
2267 
2268   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2269   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2270   handle_if_acmp:
2271     // If this is a backwards branch in the bytecodes, add Safepoint
2272     maybe_add_safepoint(iter().get_dest());
2273     a = pop();
2274     b = pop();
2275     c = _gvn.transform( new CmpPNode(b, a) );
2276     c = optimize_cmp_with_klass(c);
2277     do_if(btest, c);
2278     break;
2279 
2280   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2281   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2282   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2283   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2284   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2285   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2286   handle_ifxx:
2287     // If this is a backwards branch in the bytecodes, add Safepoint
2288     maybe_add_safepoint(iter().get_dest());
2289     a = _gvn.intcon(0);
2290     b = pop();
2291     c = _gvn.transform( new CmpINode(b, a) );
2292     do_if(btest, c);
2293     break;
2294 
2295   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2296   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2297   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2298   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2299   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2300   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2301   handle_if_icmp:
2302     // If this is a backwards branch in the bytecodes, add Safepoint
2303     maybe_add_safepoint(iter().get_dest());
2304     a = pop();
2305     b = pop();
2306     c = _gvn.transform( new CmpINode( b, a ) );
2307     do_if(btest, c);
2308     break;
2309 
2310   case Bytecodes::_tableswitch:
2311     do_tableswitch();
2312     break;
2313 
2314   case Bytecodes::_lookupswitch:
2315     do_lookupswitch();
2316     break;
2317 
2318   case Bytecodes::_invokestatic:
2319   case Bytecodes::_invokedynamic:
2320   case Bytecodes::_invokespecial:
2321   case Bytecodes::_invokevirtual:
2322   case Bytecodes::_invokeinterface:
2323     do_call();
2324     break;
2325   case Bytecodes::_checkcast:
2326     do_checkcast();
2327     break;
2328   case Bytecodes::_instanceof:
2329     do_instanceof();
2330     break;
2331   case Bytecodes::_anewarray:
2332     do_anewarray();
2333     break;
2334   case Bytecodes::_newarray:
2335     do_newarray((BasicType)iter().get_index());
2336     break;
2337   case Bytecodes::_multianewarray:
2338     do_multianewarray();
2339     break;
2340   case Bytecodes::_new:
2341     do_new();
2342     break;
2343 
2344   case Bytecodes::_jsr:
2345   case Bytecodes::_jsr_w:
2346     do_jsr();
2347     break;
2348 
2349   case Bytecodes::_ret:
2350     do_ret();
2351     break;
2352 
2353 
2354   case Bytecodes::_monitorenter:
2355     do_monitor_enter();
2356     break;
2357 
2358   case Bytecodes::_monitorexit:
2359     do_monitor_exit();
2360     break;
2361 
2362   case Bytecodes::_breakpoint:
2363     // Breakpoint set concurrently to compile
2364     // %%% use an uncommon trap?
2365     C->record_failure("breakpoint in method");
2366     return;
2367 
2368   default:
2369 #ifndef PRODUCT
2370     map()->dump(99);
2371 #endif
2372     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2373     ShouldNotReachHere();
2374   }
2375 
2376 #ifndef PRODUCT
2377   IdealGraphPrinter *printer = IdealGraphPrinter::printer();
2378   if (printer && printer->should_print(_method)) {
2379     char buffer[256];
2380     sprintf(buffer, "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2381     bool old = printer->traverse_outs();
2382     printer->set_traverse_outs(true);
2383     printer->print_method(C, buffer, 4);
2384     printer->set_traverse_outs(old);
2385   }
2386 #endif
2387 }