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   ProfileBooleanNode* profile = NULL;
 769 
 770   if (btest != BoolTest::eq && btest != BoolTest::ne) {
 771     // Only ::eq and ::ne are supported for profile injection.
 772     return false;
 773   }
 774 
 775   if (test->is_Cmp()) {
 776     Node* n = test->in(1);
 777     switch (n->Opcode()) {
 778       case Op_ProfileBoolean:
 779         profile = (ProfileBooleanNode*) n;
 780         break;
 781       case Op_AndI:
 782         // Look for the following shape: AndI (ProfileBoolean) (ConI 1))
 783         const TypeInt* t = NULL;
 784         if (n->in(1)->Opcode() == Op_ProfileBoolean &&
 785             n->in(2)->is_Con() &&
 786             (t = n->in(2)->bottom_type()->isa_int()) != NULL &&
 787             t->get_con() == 1) {
 788           profile = (ProfileBooleanNode*) n->in(1);
 789         }
 790         break;
 791     }
 792   }
 793   if (profile != NULL) {
 794     int false_cnt = profile->false_count();
 795     int  true_cnt = profile->true_count();
 796 
 797     // Counts matching depends on the actual test operation (::eq or ::ne).
 798     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
 799     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
 800 
 801     profile->consume();
 802     return true;
 803   }
 804   return false;
 805 }
 806 //--------------------------dynamic_branch_prediction--------------------------
 807 // Try to gather dynamic branch prediction behavior.  Return a probability
 808 // of the branch being taken and set the "cnt" field.  Returns a -1.0
 809 // if we need to use static prediction for some reason.
 810 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
 811   ResourceMark rm;
 812 
 813   cnt  = COUNT_UNKNOWN;
 814 
 815   int     taken = 0;
 816   int not_taken = 0;
 817 
 818   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
 819 
 820   if (use_mdo) {
 821     // Use MethodData information if it is available
 822     // FIXME: free the ProfileData structure
 823     ciMethodData* methodData = method()->method_data();
 824     if (!methodData->is_mature())  return PROB_UNKNOWN;
 825     ciProfileData* data = methodData->bci_to_data(bci());
 826     if (!data->is_JumpData())  return PROB_UNKNOWN;
 827 
 828     // get taken and not taken values
 829     taken = data->as_JumpData()->taken();
 830     not_taken = 0;
 831     if (data->is_BranchData()) {
 832       not_taken = data->as_BranchData()->not_taken();
 833     }
 834 
 835     // scale the counts to be commensurate with invocation counts:
 836     taken = method()->scale_count(taken);
 837     not_taken = method()->scale_count(not_taken);
 838   }
 839 
 840   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
 841   // We also check that individual counters are positive first, otherwise the sum can become positive.
 842   if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
 843     if (C->log() != NULL) {
 844       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
 845     }
 846     return PROB_UNKNOWN;
 847   }
 848 
 849   // Compute frequency that we arrive here
 850   float sum = taken + not_taken;
 851   // Adjust, if this block is a cloned private block but the
 852   // Jump counts are shared.  Taken the private counts for
 853   // just this path instead of the shared counts.
 854   if( block()->count() > 0 )
 855     sum = block()->count();
 856   cnt = sum / FreqCountInvocations;
 857 
 858   // Pin probability to sane limits
 859   float prob;
 860   if( !taken )
 861     prob = (0+PROB_MIN) / 2;
 862   else if( !not_taken )
 863     prob = (1+PROB_MAX) / 2;
 864   else {                         // Compute probability of true path
 865     prob = (float)taken / (float)(taken + not_taken);
 866     if (prob > PROB_MAX)  prob = PROB_MAX;
 867     if (prob < PROB_MIN)   prob = PROB_MIN;
 868   }
 869 
 870   assert((cnt > 0.0f) && (prob > 0.0f),
 871          "Bad frequency assignment in if");
 872 
 873   if (C->log() != NULL) {
 874     const char* prob_str = NULL;
 875     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
 876     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
 877     char prob_str_buf[30];
 878     if (prob_str == NULL) {
 879       sprintf(prob_str_buf, "%g", prob);
 880       prob_str = prob_str_buf;
 881     }
 882     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%g' prob='%s'",
 883                    iter().get_dest(), taken, not_taken, cnt, prob_str);
 884   }
 885   return prob;
 886 }
 887 
 888 //-----------------------------branch_prediction-------------------------------
 889 float Parse::branch_prediction(float& cnt,
 890                                BoolTest::mask btest,
 891                                int target_bci,
 892                                Node* test) {
 893   float prob = dynamic_branch_prediction(cnt, btest, test);
 894   // If prob is unknown, switch to static prediction
 895   if (prob != PROB_UNKNOWN)  return prob;
 896 
 897   prob = PROB_FAIR;                   // Set default value
 898   if (btest == BoolTest::eq)          // Exactly equal test?
 899     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
 900   else if (btest == BoolTest::ne)
 901     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
 902 
 903   // If this is a conditional test guarding a backwards branch,
 904   // assume its a loop-back edge.  Make it a likely taken branch.
 905   if (target_bci < bci()) {
 906     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
 907       // Since it's an OSR, we probably have profile data, but since
 908       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
 909       // Let's make a special check here for completely zero counts.
 910       ciMethodData* methodData = method()->method_data();
 911       if (!methodData->is_empty()) {
 912         ciProfileData* data = methodData->bci_to_data(bci());
 913         // Only stop for truly zero counts, which mean an unknown part
 914         // of the OSR-ed method, and we want to deopt to gather more stats.
 915         // If you have ANY counts, then this loop is simply 'cold' relative
 916         // to the OSR loop.
 917         if (data->as_BranchData()->taken() +
 918             data->as_BranchData()->not_taken() == 0 ) {
 919           // This is the only way to return PROB_UNKNOWN:
 920           return PROB_UNKNOWN;
 921         }
 922       }
 923     }
 924     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
 925   }
 926 
 927   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
 928   return prob;
 929 }
 930 
 931 // The magic constants are chosen so as to match the output of
 932 // branch_prediction() when the profile reports a zero taken count.
 933 // It is important to distinguish zero counts unambiguously, because
 934 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
 935 // very small but nonzero probabilities, which if confused with zero
 936 // counts would keep the program recompiling indefinitely.
 937 bool Parse::seems_never_taken(float prob) const {
 938   return prob < PROB_MIN;
 939 }
 940 
 941 // True if the comparison seems to be the kind that will not change its
 942 // statistics from true to false.  See comments in adjust_map_after_if.
 943 // This question is only asked along paths which are already
 944 // classifed as untaken (by seems_never_taken), so really,
 945 // if a path is never taken, its controlling comparison is
 946 // already acting in a stable fashion.  If the comparison
 947 // seems stable, we will put an expensive uncommon trap
 948 // on the untaken path.
 949 bool Parse::seems_stable_comparison() const {
 950   if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
 951     return false;
 952   }
 953   return true;
 954 }
 955 
 956 //-------------------------------repush_if_args--------------------------------
 957 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
 958 inline int Parse::repush_if_args() {
 959 #ifndef PRODUCT
 960   if (PrintOpto && WizardMode) {
 961     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
 962                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
 963     method()->print_name(); tty->cr();
 964   }
 965 #endif
 966   int bc_depth = - Bytecodes::depth(iter().cur_bc());
 967   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
 968   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
 969   assert(argument(0) != NULL, "must exist");
 970   assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
 971   inc_sp(bc_depth);
 972   return bc_depth;
 973 }
 974 
 975 //----------------------------------do_ifnull----------------------------------
 976 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
 977   int target_bci = iter().get_dest();
 978 
 979   Block* branch_block = successor_for_bci(target_bci);
 980   Block* next_block   = successor_for_bci(iter().next_bci());
 981 
 982   float cnt;
 983   float prob = branch_prediction(cnt, btest, target_bci, c);
 984   if (prob == PROB_UNKNOWN) {
 985     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
 986 #ifndef PRODUCT
 987     if (PrintOpto && Verbose)
 988       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
 989 #endif
 990     repush_if_args(); // to gather stats on loop
 991     // We need to mark this branch as taken so that if we recompile we will
 992     // see that it is possible. In the tiered system the interpreter doesn't
 993     // do profiling and by the time we get to the lower tier from the interpreter
 994     // the path may be cold again. Make sure it doesn't look untaken
 995     profile_taken_branch(target_bci, !ProfileInterpreter);
 996     uncommon_trap(Deoptimization::Reason_unreached,
 997                   Deoptimization::Action_reinterpret,
 998                   NULL, "cold");
 999     if (C->eliminate_boxing()) {
1000       // Mark the successor blocks as parsed
1001       branch_block->next_path_num();
1002       next_block->next_path_num();
1003     }
1004     return;
1005   }
1006 
1007   explicit_null_checks_inserted++;
1008 
1009   // Generate real control flow
1010   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
1011 
1012   // Sanity check the probability value
1013   assert(prob > 0.0f,"Bad probability in Parser");
1014  // Need xform to put node in hash table
1015   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1016   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1017   // True branch
1018   { PreserveJVMState pjvms(this);
1019     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1020     set_control(iftrue);
1021 
1022     if (stopped()) {            // Path is dead?
1023       explicit_null_checks_elided++;
1024       if (C->eliminate_boxing()) {
1025         // Mark the successor block as parsed
1026         branch_block->next_path_num();
1027       }
1028     } else {                    // Path is live.
1029       // Update method data
1030       profile_taken_branch(target_bci);
1031       adjust_map_after_if(btest, c, prob, branch_block, next_block);
1032       if (!stopped()) {
1033         merge(target_bci);
1034       }
1035     }
1036   }
1037 
1038   // False branch
1039   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1040   set_control(iffalse);
1041 
1042   if (stopped()) {              // Path is dead?
1043     explicit_null_checks_elided++;
1044     if (C->eliminate_boxing()) {
1045       // Mark the successor block as parsed
1046       next_block->next_path_num();
1047     }
1048   } else  {                     // Path is live.
1049     // Update method data
1050     profile_not_taken_branch();
1051     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob,
1052                         next_block, branch_block);
1053   }
1054 }
1055 
1056 //------------------------------------do_if------------------------------------
1057 void Parse::do_if(BoolTest::mask btest, Node* c) {
1058   int target_bci = iter().get_dest();
1059 
1060   Block* branch_block = successor_for_bci(target_bci);
1061   Block* next_block   = successor_for_bci(iter().next_bci());
1062 
1063   float cnt;
1064   float prob = branch_prediction(cnt, btest, target_bci, c);
1065   float untaken_prob = 1.0 - prob;
1066 
1067   if (prob == PROB_UNKNOWN) {
1068 #ifndef PRODUCT
1069     if (PrintOpto && Verbose)
1070       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
1071 #endif
1072     repush_if_args(); // to gather stats on loop
1073     // We need to mark this branch as taken so that if we recompile we will
1074     // see that it is possible. In the tiered system the interpreter doesn't
1075     // do profiling and by the time we get to the lower tier from the interpreter
1076     // the path may be cold again. Make sure it doesn't look untaken
1077     profile_taken_branch(target_bci, !ProfileInterpreter);
1078     uncommon_trap(Deoptimization::Reason_unreached,
1079                   Deoptimization::Action_reinterpret,
1080                   NULL, "cold");
1081     if (C->eliminate_boxing()) {
1082       // Mark the successor blocks as parsed
1083       branch_block->next_path_num();
1084       next_block->next_path_num();
1085     }
1086     return;
1087   }
1088 
1089   // Sanity check the probability value
1090   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1091 
1092   bool taken_if_true = true;
1093   // Convert BoolTest to canonical form:
1094   if (!BoolTest(btest).is_canonical()) {
1095     btest         = BoolTest(btest).negate();
1096     taken_if_true = false;
1097     // prob is NOT updated here; it remains the probability of the taken
1098     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1099   }
1100   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1101 
1102   Node* tst0 = new BoolNode(c, btest);
1103   Node* tst = _gvn.transform(tst0);
1104   BoolTest::mask taken_btest   = BoolTest::illegal;
1105   BoolTest::mask untaken_btest = BoolTest::illegal;
1106 
1107   if (tst->is_Bool()) {
1108     // Refresh c from the transformed bool node, since it may be
1109     // simpler than the original c.  Also re-canonicalize btest.
1110     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)).
1111     // That can arise from statements like: if (x instanceof C) ...
1112     if (tst != tst0) {
1113       // Canonicalize one more time since transform can change it.
1114       btest = tst->as_Bool()->_test._test;
1115       if (!BoolTest(btest).is_canonical()) {
1116         // Reverse edges one more time...
1117         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1118         btest = tst->as_Bool()->_test._test;
1119         assert(BoolTest(btest).is_canonical(), "sanity");
1120         taken_if_true = !taken_if_true;
1121       }
1122       c = tst->in(1);
1123     }
1124     BoolTest::mask neg_btest = BoolTest(btest).negate();
1125     taken_btest   = taken_if_true ?     btest : neg_btest;
1126     untaken_btest = taken_if_true ? neg_btest :     btest;
1127   }
1128 
1129   // Generate real control flow
1130   float true_prob = (taken_if_true ? prob : untaken_prob);
1131   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1132   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1133   Node* taken_branch   = new IfTrueNode(iff);
1134   Node* untaken_branch = new IfFalseNode(iff);
1135   if (!taken_if_true) {  // Finish conversion to canonical form
1136     Node* tmp      = taken_branch;
1137     taken_branch   = untaken_branch;
1138     untaken_branch = tmp;
1139   }
1140 
1141   // Branch is taken:
1142   { PreserveJVMState pjvms(this);
1143     taken_branch = _gvn.transform(taken_branch);
1144     set_control(taken_branch);
1145 
1146     if (stopped()) {
1147       if (C->eliminate_boxing()) {
1148         // Mark the successor block as parsed
1149         branch_block->next_path_num();
1150       }
1151     } else {
1152       // Update method data
1153       profile_taken_branch(target_bci);
1154       adjust_map_after_if(taken_btest, c, prob, branch_block, next_block);
1155       if (!stopped()) {
1156         merge(target_bci);
1157       }
1158     }
1159   }
1160 
1161   untaken_branch = _gvn.transform(untaken_branch);
1162   set_control(untaken_branch);
1163 
1164   // Branch not taken.
1165   if (stopped()) {
1166     if (C->eliminate_boxing()) {
1167       // Mark the successor block as parsed
1168       next_block->next_path_num();
1169     }
1170   } else {
1171     // Update method data
1172     profile_not_taken_branch();
1173     adjust_map_after_if(untaken_btest, c, untaken_prob,
1174                         next_block, branch_block);
1175   }
1176 }
1177 
1178 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1179   // Don't want to speculate on uncommon traps when running with -Xcomp
1180   if (!UseInterpreter) {
1181     return false;
1182   }
1183   return (seems_never_taken(prob) && seems_stable_comparison());
1184 }
1185 
1186 //----------------------------adjust_map_after_if------------------------------
1187 // Adjust the JVM state to reflect the result of taking this path.
1188 // Basically, it means inspecting the CmpNode controlling this
1189 // branch, seeing how it constrains a tested value, and then
1190 // deciding if it's worth our while to encode this constraint
1191 // as graph nodes in the current abstract interpretation map.
1192 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
1193                                 Block* path, Block* other_path) {
1194   if (stopped() || !c->is_Cmp() || btest == BoolTest::illegal)
1195     return;                             // nothing to do
1196 
1197   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1198 
1199   if (path_is_suitable_for_uncommon_trap(prob)) {
1200     repush_if_args();
1201     uncommon_trap(Deoptimization::Reason_unstable_if,
1202                   Deoptimization::Action_reinterpret,
1203                   NULL,
1204                   (is_fallthrough ? "taken always" : "taken never"));
1205     return;
1206   }
1207 
1208   Node* val = c->in(1);
1209   Node* con = c->in(2);
1210   const Type* tcon = _gvn.type(con);
1211   const Type* tval = _gvn.type(val);
1212   bool have_con = tcon->singleton();
1213   if (tval->singleton()) {
1214     if (!have_con) {
1215       // Swap, so constant is in con.
1216       con  = val;
1217       tcon = tval;
1218       val  = c->in(2);
1219       tval = _gvn.type(val);
1220       btest = BoolTest(btest).commute();
1221       have_con = true;
1222     } else {
1223       // Do we have two constants?  Then leave well enough alone.
1224       have_con = false;
1225     }
1226   }
1227   if (!have_con)                        // remaining adjustments need a con
1228     return;
1229 
1230   sharpen_type_after_if(btest, con, tcon, val, tval);
1231 }
1232 
1233 
1234 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1235   Node* ldk;
1236   if (n->is_DecodeNKlass()) {
1237     if (n->in(1)->Opcode() != Op_LoadNKlass) {
1238       return NULL;
1239     } else {
1240       ldk = n->in(1);
1241     }
1242   } else if (n->Opcode() != Op_LoadKlass) {
1243     return NULL;
1244   } else {
1245     ldk = n;
1246   }
1247   assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1248 
1249   Node* adr = ldk->in(MemNode::Address);
1250   intptr_t off = 0;
1251   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1252   if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1253     return NULL;
1254   const TypePtr* tp = gvn->type(obj)->is_ptr();
1255   if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1256     return NULL;
1257 
1258   return obj;
1259 }
1260 
1261 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1262                                   Node* con, const Type* tcon,
1263                                   Node* val, const Type* tval) {
1264   // Look for opportunities to sharpen the type of a node
1265   // whose klass is compared with a constant klass.
1266   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1267     Node* obj = extract_obj_from_klass_load(&_gvn, val);
1268     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1269     if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1270        // Found:
1271        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1272        // or the narrowOop equivalent.
1273        const Type* obj_type = _gvn.type(obj);
1274        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1275        if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
1276            tboth->higher_equal(obj_type)) {
1277           // obj has to be of the exact type Foo if the CmpP succeeds.
1278           int obj_in_map = map()->find_edge(obj);
1279           JVMState* jvms = this->jvms();
1280           if (obj_in_map >= 0 &&
1281               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1282             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1283             const Type* tcc = ccast->as_Type()->type();
1284             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1285             // Delay transform() call to allow recovery of pre-cast value
1286             // at the control merge.
1287             _gvn.set_type_bottom(ccast);
1288             record_for_igvn(ccast);
1289             // Here's the payoff.
1290             replace_in_map(obj, ccast);
1291           }
1292        }
1293     }
1294   }
1295 
1296   int val_in_map = map()->find_edge(val);
1297   if (val_in_map < 0)  return;          // replace_in_map would be useless
1298   {
1299     JVMState* jvms = this->jvms();
1300     if (!(jvms->is_loc(val_in_map) ||
1301           jvms->is_stk(val_in_map)))
1302       return;                           // again, it would be useless
1303   }
1304 
1305   // Check for a comparison to a constant, and "know" that the compared
1306   // value is constrained on this path.
1307   assert(tcon->singleton(), "");
1308   ConstraintCastNode* ccast = NULL;
1309   Node* cast = NULL;
1310 
1311   switch (btest) {
1312   case BoolTest::eq:                    // Constant test?
1313     {
1314       const Type* tboth = tcon->join_speculative(tval);
1315       if (tboth == tval)  break;        // Nothing to gain.
1316       if (tcon->isa_int()) {
1317         ccast = new CastIINode(val, tboth);
1318       } else if (tcon == TypePtr::NULL_PTR) {
1319         // Cast to null, but keep the pointer identity temporarily live.
1320         ccast = new CastPPNode(val, tboth);
1321       } else {
1322         const TypeF* tf = tcon->isa_float_constant();
1323         const TypeD* td = tcon->isa_double_constant();
1324         // Exclude tests vs float/double 0 as these could be
1325         // either +0 or -0.  Just because you are equal to +0
1326         // doesn't mean you ARE +0!
1327         // Note, following code also replaces Long and Oop values.
1328         if ((!tf || tf->_f != 0.0) &&
1329             (!td || td->_d != 0.0))
1330           cast = con;                   // Replace non-constant val by con.
1331       }
1332     }
1333     break;
1334 
1335   case BoolTest::ne:
1336     if (tcon == TypePtr::NULL_PTR) {
1337       cast = cast_not_null(val, false);
1338     }
1339     break;
1340 
1341   default:
1342     // (At this point we could record int range types with CastII.)
1343     break;
1344   }
1345 
1346   if (ccast != NULL) {
1347     const Type* tcc = ccast->as_Type()->type();
1348     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1349     // Delay transform() call to allow recovery of pre-cast value
1350     // at the control merge.
1351     ccast->set_req(0, control());
1352     _gvn.set_type_bottom(ccast);
1353     record_for_igvn(ccast);
1354     cast = ccast;
1355   }
1356 
1357   if (cast != NULL) {                   // Here's the payoff.
1358     replace_in_map(val, cast);
1359   }
1360 }
1361 
1362 /**
1363  * Use speculative type to optimize CmpP node: if comparison is
1364  * against the low level class, cast the object to the speculative
1365  * type if any. CmpP should then go away.
1366  *
1367  * @param c  expected CmpP node
1368  * @return   result of CmpP on object casted to speculative type
1369  *
1370  */
1371 Node* Parse::optimize_cmp_with_klass(Node* c) {
1372   // If this is transformed by the _gvn to a comparison with the low
1373   // level klass then we may be able to use speculation
1374   if (c->Opcode() == Op_CmpP &&
1375       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1376       c->in(2)->is_Con()) {
1377     Node* load_klass = NULL;
1378     Node* decode = NULL;
1379     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1380       decode = c->in(1);
1381       load_klass = c->in(1)->in(1);
1382     } else {
1383       load_klass = c->in(1);
1384     }
1385     if (load_klass->in(2)->is_AddP()) {
1386       Node* addp = load_klass->in(2);
1387       Node* obj = addp->in(AddPNode::Address);
1388       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1389       if (obj_type->speculative_type_not_null() != NULL) {
1390         ciKlass* k = obj_type->speculative_type();
1391         inc_sp(2);
1392         obj = maybe_cast_profiled_obj(obj, k);
1393         dec_sp(2);
1394         // Make the CmpP use the casted obj
1395         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1396         load_klass = load_klass->clone();
1397         load_klass->set_req(2, addp);
1398         load_klass = _gvn.transform(load_klass);
1399         if (decode != NULL) {
1400           decode = decode->clone();
1401           decode->set_req(1, load_klass);
1402           load_klass = _gvn.transform(decode);
1403         }
1404         c = c->clone();
1405         c->set_req(1, load_klass);
1406         c = _gvn.transform(c);
1407       }
1408     }
1409   }
1410   return c;
1411 }
1412 
1413 //------------------------------do_one_bytecode--------------------------------
1414 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1415 void Parse::do_one_bytecode() {
1416   Node *a, *b, *c, *d;          // Handy temps
1417   BoolTest::mask btest;
1418   int i;
1419 
1420   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1421 
1422   if (C->check_node_count(NodeLimitFudgeFactor * 5,
1423                           "out of nodes parsing method")) {
1424     return;
1425   }
1426 
1427 #ifdef ASSERT
1428   // for setting breakpoints
1429   if (TraceOptoParse) {
1430     tty->print(" @");
1431     dump_bci(bci());
1432     tty->cr();
1433   }
1434 #endif
1435 
1436   switch (bc()) {
1437   case Bytecodes::_nop:
1438     // do nothing
1439     break;
1440   case Bytecodes::_lconst_0:
1441     push_pair(longcon(0));
1442     break;
1443 
1444   case Bytecodes::_lconst_1:
1445     push_pair(longcon(1));
1446     break;
1447 
1448   case Bytecodes::_fconst_0:
1449     push(zerocon(T_FLOAT));
1450     break;
1451 
1452   case Bytecodes::_fconst_1:
1453     push(makecon(TypeF::ONE));
1454     break;
1455 
1456   case Bytecodes::_fconst_2:
1457     push(makecon(TypeF::make(2.0f)));
1458     break;
1459 
1460   case Bytecodes::_dconst_0:
1461     push_pair(zerocon(T_DOUBLE));
1462     break;
1463 
1464   case Bytecodes::_dconst_1:
1465     push_pair(makecon(TypeD::ONE));
1466     break;
1467 
1468   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1469   case Bytecodes::_iconst_0: push(intcon( 0)); break;
1470   case Bytecodes::_iconst_1: push(intcon( 1)); break;
1471   case Bytecodes::_iconst_2: push(intcon( 2)); break;
1472   case Bytecodes::_iconst_3: push(intcon( 3)); break;
1473   case Bytecodes::_iconst_4: push(intcon( 4)); break;
1474   case Bytecodes::_iconst_5: push(intcon( 5)); break;
1475   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
1476   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
1477   case Bytecodes::_aconst_null: push(null());  break;
1478   case Bytecodes::_ldc:
1479   case Bytecodes::_ldc_w:
1480   case Bytecodes::_ldc2_w:
1481     // If the constant is unresolved, run this BC once in the interpreter.
1482     {
1483       ciConstant constant = iter().get_constant();
1484       if (constant.basic_type() == T_OBJECT &&
1485           !constant.as_object()->is_loaded()) {
1486         int index = iter().get_constant_pool_index();
1487         constantTag tag = iter().get_constant_pool_tag(index);
1488         uncommon_trap(Deoptimization::make_trap_request
1489                       (Deoptimization::Reason_unloaded,
1490                        Deoptimization::Action_reinterpret,
1491                        index),
1492                       NULL, tag.internal_name());
1493         break;
1494       }
1495       assert(constant.basic_type() != T_OBJECT || constant.as_object()->is_instance(),
1496              "must be java_mirror of klass");
1497       bool pushed = push_constant(constant, true);
1498       guarantee(pushed, "must be possible to push this constant");
1499     }
1500 
1501     break;
1502 
1503   case Bytecodes::_aload_0:
1504     push( local(0) );
1505     break;
1506   case Bytecodes::_aload_1:
1507     push( local(1) );
1508     break;
1509   case Bytecodes::_aload_2:
1510     push( local(2) );
1511     break;
1512   case Bytecodes::_aload_3:
1513     push( local(3) );
1514     break;
1515   case Bytecodes::_aload:
1516     push( local(iter().get_index()) );
1517     break;
1518 
1519   case Bytecodes::_fload_0:
1520   case Bytecodes::_iload_0:
1521     push( local(0) );
1522     break;
1523   case Bytecodes::_fload_1:
1524   case Bytecodes::_iload_1:
1525     push( local(1) );
1526     break;
1527   case Bytecodes::_fload_2:
1528   case Bytecodes::_iload_2:
1529     push( local(2) );
1530     break;
1531   case Bytecodes::_fload_3:
1532   case Bytecodes::_iload_3:
1533     push( local(3) );
1534     break;
1535   case Bytecodes::_fload:
1536   case Bytecodes::_iload:
1537     push( local(iter().get_index()) );
1538     break;
1539   case Bytecodes::_lload_0:
1540     push_pair_local( 0 );
1541     break;
1542   case Bytecodes::_lload_1:
1543     push_pair_local( 1 );
1544     break;
1545   case Bytecodes::_lload_2:
1546     push_pair_local( 2 );
1547     break;
1548   case Bytecodes::_lload_3:
1549     push_pair_local( 3 );
1550     break;
1551   case Bytecodes::_lload:
1552     push_pair_local( iter().get_index() );
1553     break;
1554 
1555   case Bytecodes::_dload_0:
1556     push_pair_local(0);
1557     break;
1558   case Bytecodes::_dload_1:
1559     push_pair_local(1);
1560     break;
1561   case Bytecodes::_dload_2:
1562     push_pair_local(2);
1563     break;
1564   case Bytecodes::_dload_3:
1565     push_pair_local(3);
1566     break;
1567   case Bytecodes::_dload:
1568     push_pair_local(iter().get_index());
1569     break;
1570   case Bytecodes::_fstore_0:
1571   case Bytecodes::_istore_0:
1572   case Bytecodes::_astore_0:
1573     set_local( 0, pop() );
1574     break;
1575   case Bytecodes::_fstore_1:
1576   case Bytecodes::_istore_1:
1577   case Bytecodes::_astore_1:
1578     set_local( 1, pop() );
1579     break;
1580   case Bytecodes::_fstore_2:
1581   case Bytecodes::_istore_2:
1582   case Bytecodes::_astore_2:
1583     set_local( 2, pop() );
1584     break;
1585   case Bytecodes::_fstore_3:
1586   case Bytecodes::_istore_3:
1587   case Bytecodes::_astore_3:
1588     set_local( 3, pop() );
1589     break;
1590   case Bytecodes::_fstore:
1591   case Bytecodes::_istore:
1592   case Bytecodes::_astore:
1593     set_local( iter().get_index(), pop() );
1594     break;
1595   // long stores
1596   case Bytecodes::_lstore_0:
1597     set_pair_local( 0, pop_pair() );
1598     break;
1599   case Bytecodes::_lstore_1:
1600     set_pair_local( 1, pop_pair() );
1601     break;
1602   case Bytecodes::_lstore_2:
1603     set_pair_local( 2, pop_pair() );
1604     break;
1605   case Bytecodes::_lstore_3:
1606     set_pair_local( 3, pop_pair() );
1607     break;
1608   case Bytecodes::_lstore:
1609     set_pair_local( iter().get_index(), pop_pair() );
1610     break;
1611 
1612   // double stores
1613   case Bytecodes::_dstore_0:
1614     set_pair_local( 0, dstore_rounding(pop_pair()) );
1615     break;
1616   case Bytecodes::_dstore_1:
1617     set_pair_local( 1, dstore_rounding(pop_pair()) );
1618     break;
1619   case Bytecodes::_dstore_2:
1620     set_pair_local( 2, dstore_rounding(pop_pair()) );
1621     break;
1622   case Bytecodes::_dstore_3:
1623     set_pair_local( 3, dstore_rounding(pop_pair()) );
1624     break;
1625   case Bytecodes::_dstore:
1626     set_pair_local( iter().get_index(), dstore_rounding(pop_pair()) );
1627     break;
1628 
1629   case Bytecodes::_pop:  dec_sp(1);   break;
1630   case Bytecodes::_pop2: dec_sp(2);   break;
1631   case Bytecodes::_swap:
1632     a = pop();
1633     b = pop();
1634     push(a);
1635     push(b);
1636     break;
1637   case Bytecodes::_dup:
1638     a = pop();
1639     push(a);
1640     push(a);
1641     break;
1642   case Bytecodes::_dup_x1:
1643     a = pop();
1644     b = pop();
1645     push( a );
1646     push( b );
1647     push( a );
1648     break;
1649   case Bytecodes::_dup_x2:
1650     a = pop();
1651     b = pop();
1652     c = pop();
1653     push( a );
1654     push( c );
1655     push( b );
1656     push( a );
1657     break;
1658   case Bytecodes::_dup2:
1659     a = pop();
1660     b = pop();
1661     push( b );
1662     push( a );
1663     push( b );
1664     push( a );
1665     break;
1666 
1667   case Bytecodes::_dup2_x1:
1668     // before: .. c, b, a
1669     // after:  .. b, a, c, b, a
1670     // not tested
1671     a = pop();
1672     b = pop();
1673     c = pop();
1674     push( b );
1675     push( a );
1676     push( c );
1677     push( b );
1678     push( a );
1679     break;
1680   case Bytecodes::_dup2_x2:
1681     // before: .. d, c, b, a
1682     // after:  .. b, a, d, c, b, a
1683     // not tested
1684     a = pop();
1685     b = pop();
1686     c = pop();
1687     d = pop();
1688     push( b );
1689     push( a );
1690     push( d );
1691     push( c );
1692     push( b );
1693     push( a );
1694     break;
1695 
1696   case Bytecodes::_arraylength: {
1697     // Must do null-check with value on expression stack
1698     Node *ary = null_check(peek(), T_ARRAY);
1699     // Compile-time detect of null-exception?
1700     if (stopped())  return;
1701     a = pop();
1702     push(load_array_length(a));
1703     break;
1704   }
1705 
1706   case Bytecodes::_baload: array_load(T_BYTE);   break;
1707   case Bytecodes::_caload: array_load(T_CHAR);   break;
1708   case Bytecodes::_iaload: array_load(T_INT);    break;
1709   case Bytecodes::_saload: array_load(T_SHORT);  break;
1710   case Bytecodes::_faload: array_load(T_FLOAT);  break;
1711   case Bytecodes::_aaload: array_load(T_OBJECT); break;
1712   case Bytecodes::_laload: {
1713     a = array_addressing(T_LONG, 0);
1714     if (stopped())  return;     // guaranteed null or range check
1715     dec_sp(2);                  // Pop array and index
1716     push_pair(make_load(control(), a, TypeLong::LONG, T_LONG, TypeAryPtr::LONGS, MemNode::unordered));
1717     break;
1718   }
1719   case Bytecodes::_daload: {
1720     a = array_addressing(T_DOUBLE, 0);
1721     if (stopped())  return;     // guaranteed null or range check
1722     dec_sp(2);                  // Pop array and index
1723     push_pair(make_load(control(), a, Type::DOUBLE, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered));
1724     break;
1725   }
1726   case Bytecodes::_bastore: array_store(T_BYTE);  break;
1727   case Bytecodes::_castore: array_store(T_CHAR);  break;
1728   case Bytecodes::_iastore: array_store(T_INT);   break;
1729   case Bytecodes::_sastore: array_store(T_SHORT); break;
1730   case Bytecodes::_fastore: array_store(T_FLOAT); break;
1731   case Bytecodes::_aastore: {
1732     d = array_addressing(T_OBJECT, 1);
1733     if (stopped())  return;     // guaranteed null or range check
1734     array_store_check();
1735     c = pop();                  // Oop to store
1736     b = pop();                  // index (already used)
1737     a = pop();                  // the array itself
1738     const TypeOopPtr* elemtype  = _gvn.type(a)->is_aryptr()->elem()->make_oopptr();
1739     const TypeAryPtr* adr_type = TypeAryPtr::OOPS;
1740     Node* store = store_oop_to_array(control(), a, d, adr_type, c, elemtype, T_OBJECT, MemNode::release);
1741     break;
1742   }
1743   case Bytecodes::_lastore: {
1744     a = array_addressing(T_LONG, 2);
1745     if (stopped())  return;     // guaranteed null or range check
1746     c = pop_pair();
1747     dec_sp(2);                  // Pop array and index
1748     store_to_memory(control(), a, c, T_LONG, TypeAryPtr::LONGS, MemNode::unordered);
1749     break;
1750   }
1751   case Bytecodes::_dastore: {
1752     a = array_addressing(T_DOUBLE, 2);
1753     if (stopped())  return;     // guaranteed null or range check
1754     c = pop_pair();
1755     dec_sp(2);                  // Pop array and index
1756     c = dstore_rounding(c);
1757     store_to_memory(control(), a, c, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered);
1758     break;
1759   }
1760   case Bytecodes::_getfield:
1761     do_getfield();
1762     break;
1763 
1764   case Bytecodes::_getstatic:
1765     do_getstatic();
1766     break;
1767 
1768   case Bytecodes::_putfield:
1769     do_putfield();
1770     break;
1771 
1772   case Bytecodes::_putstatic:
1773     do_putstatic();
1774     break;
1775 
1776   case Bytecodes::_irem:
1777     do_irem();
1778     break;
1779   case Bytecodes::_idiv:
1780     // Must keep both values on the expression-stack during null-check
1781     zero_check_int(peek());
1782     // Compile-time detect of null-exception?
1783     if (stopped())  return;
1784     b = pop();
1785     a = pop();
1786     push( _gvn.transform( new DivINode(control(),a,b) ) );
1787     break;
1788   case Bytecodes::_imul:
1789     b = pop(); a = pop();
1790     push( _gvn.transform( new MulINode(a,b) ) );
1791     break;
1792   case Bytecodes::_iadd:
1793     b = pop(); a = pop();
1794     push( _gvn.transform( new AddINode(a,b) ) );
1795     break;
1796   case Bytecodes::_ineg:
1797     a = pop();
1798     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
1799     break;
1800   case Bytecodes::_isub:
1801     b = pop(); a = pop();
1802     push( _gvn.transform( new SubINode(a,b) ) );
1803     break;
1804   case Bytecodes::_iand:
1805     b = pop(); a = pop();
1806     push( _gvn.transform( new AndINode(a,b) ) );
1807     break;
1808   case Bytecodes::_ior:
1809     b = pop(); a = pop();
1810     push( _gvn.transform( new OrINode(a,b) ) );
1811     break;
1812   case Bytecodes::_ixor:
1813     b = pop(); a = pop();
1814     push( _gvn.transform( new XorINode(a,b) ) );
1815     break;
1816   case Bytecodes::_ishl:
1817     b = pop(); a = pop();
1818     push( _gvn.transform( new LShiftINode(a,b) ) );
1819     break;
1820   case Bytecodes::_ishr:
1821     b = pop(); a = pop();
1822     push( _gvn.transform( new RShiftINode(a,b) ) );
1823     break;
1824   case Bytecodes::_iushr:
1825     b = pop(); a = pop();
1826     push( _gvn.transform( new URShiftINode(a,b) ) );
1827     break;
1828 
1829   case Bytecodes::_fneg:
1830     a = pop();
1831     b = _gvn.transform(new NegFNode (a));
1832     push(b);
1833     break;
1834 
1835   case Bytecodes::_fsub:
1836     b = pop();
1837     a = pop();
1838     c = _gvn.transform( new SubFNode(a,b) );
1839     d = precision_rounding(c);
1840     push( d );
1841     break;
1842 
1843   case Bytecodes::_fadd:
1844     b = pop();
1845     a = pop();
1846     c = _gvn.transform( new AddFNode(a,b) );
1847     d = precision_rounding(c);
1848     push( d );
1849     break;
1850 
1851   case Bytecodes::_fmul:
1852     b = pop();
1853     a = pop();
1854     c = _gvn.transform( new MulFNode(a,b) );
1855     d = precision_rounding(c);
1856     push( d );
1857     break;
1858 
1859   case Bytecodes::_fdiv:
1860     b = pop();
1861     a = pop();
1862     c = _gvn.transform( new DivFNode(0,a,b) );
1863     d = precision_rounding(c);
1864     push( d );
1865     break;
1866 
1867   case Bytecodes::_frem:
1868     if (Matcher::has_match_rule(Op_ModF)) {
1869       // Generate a ModF node.
1870       b = pop();
1871       a = pop();
1872       c = _gvn.transform( new ModFNode(0,a,b) );
1873       d = precision_rounding(c);
1874       push( d );
1875     }
1876     else {
1877       // Generate a call.
1878       modf();
1879     }
1880     break;
1881 
1882   case Bytecodes::_fcmpl:
1883     b = pop();
1884     a = pop();
1885     c = _gvn.transform( new CmpF3Node( a, b));
1886     push(c);
1887     break;
1888   case Bytecodes::_fcmpg:
1889     b = pop();
1890     a = pop();
1891 
1892     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
1893     // which negates the result sign except for unordered.  Flip the unordered
1894     // as well by using CmpF3 which implements unordered-lesser instead of
1895     // unordered-greater semantics.  Finally, commute the result bits.  Result
1896     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
1897     c = _gvn.transform( new CmpF3Node( b, a));
1898     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
1899     push(c);
1900     break;
1901 
1902   case Bytecodes::_f2i:
1903     a = pop();
1904     push(_gvn.transform(new ConvF2INode(a)));
1905     break;
1906 
1907   case Bytecodes::_d2i:
1908     a = pop_pair();
1909     b = _gvn.transform(new ConvD2INode(a));
1910     push( b );
1911     break;
1912 
1913   case Bytecodes::_f2d:
1914     a = pop();
1915     b = _gvn.transform( new ConvF2DNode(a));
1916     push_pair( b );
1917     break;
1918 
1919   case Bytecodes::_d2f:
1920     a = pop_pair();
1921     b = _gvn.transform( new ConvD2FNode(a));
1922     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
1923     //b = _gvn.transform(new RoundFloatNode(0, b) );
1924     push( b );
1925     break;
1926 
1927   case Bytecodes::_l2f:
1928     if (Matcher::convL2FSupported()) {
1929       a = pop_pair();
1930       b = _gvn.transform( new ConvL2FNode(a));
1931       // For i486.ad, FILD doesn't restrict precision to 24 or 53 bits.
1932       // Rather than storing the result into an FP register then pushing
1933       // out to memory to round, the machine instruction that implements
1934       // ConvL2D is responsible for rounding.
1935       // c = precision_rounding(b);
1936       c = _gvn.transform(b);
1937       push(c);
1938     } else {
1939       l2f();
1940     }
1941     break;
1942 
1943   case Bytecodes::_l2d:
1944     a = pop_pair();
1945     b = _gvn.transform( new ConvL2DNode(a));
1946     // For i486.ad, rounding is always necessary (see _l2f above).
1947     // c = dprecision_rounding(b);
1948     c = _gvn.transform(b);
1949     push_pair(c);
1950     break;
1951 
1952   case Bytecodes::_f2l:
1953     a = pop();
1954     b = _gvn.transform( new ConvF2LNode(a));
1955     push_pair(b);
1956     break;
1957 
1958   case Bytecodes::_d2l:
1959     a = pop_pair();
1960     b = _gvn.transform( new ConvD2LNode(a));
1961     push_pair(b);
1962     break;
1963 
1964   case Bytecodes::_dsub:
1965     b = pop_pair();
1966     a = pop_pair();
1967     c = _gvn.transform( new SubDNode(a,b) );
1968     d = dprecision_rounding(c);
1969     push_pair( d );
1970     break;
1971 
1972   case Bytecodes::_dadd:
1973     b = pop_pair();
1974     a = pop_pair();
1975     c = _gvn.transform( new AddDNode(a,b) );
1976     d = dprecision_rounding(c);
1977     push_pair( d );
1978     break;
1979 
1980   case Bytecodes::_dmul:
1981     b = pop_pair();
1982     a = pop_pair();
1983     c = _gvn.transform( new MulDNode(a,b) );
1984     d = dprecision_rounding(c);
1985     push_pair( d );
1986     break;
1987 
1988   case Bytecodes::_ddiv:
1989     b = pop_pair();
1990     a = pop_pair();
1991     c = _gvn.transform( new DivDNode(0,a,b) );
1992     d = dprecision_rounding(c);
1993     push_pair( d );
1994     break;
1995 
1996   case Bytecodes::_dneg:
1997     a = pop_pair();
1998     b = _gvn.transform(new NegDNode (a));
1999     push_pair(b);
2000     break;
2001 
2002   case Bytecodes::_drem:
2003     if (Matcher::has_match_rule(Op_ModD)) {
2004       // Generate a ModD node.
2005       b = pop_pair();
2006       a = pop_pair();
2007       // a % b
2008 
2009       c = _gvn.transform( new ModDNode(0,a,b) );
2010       d = dprecision_rounding(c);
2011       push_pair( d );
2012     }
2013     else {
2014       // Generate a call.
2015       modd();
2016     }
2017     break;
2018 
2019   case Bytecodes::_dcmpl:
2020     b = pop_pair();
2021     a = pop_pair();
2022     c = _gvn.transform( new CmpD3Node( a, b));
2023     push(c);
2024     break;
2025 
2026   case Bytecodes::_dcmpg:
2027     b = pop_pair();
2028     a = pop_pair();
2029     // Same as dcmpl but need to flip the unordered case.
2030     // Commute the inputs, which negates the result sign except for unordered.
2031     // Flip the unordered as well by using CmpD3 which implements
2032     // unordered-lesser instead of unordered-greater semantics.
2033     // Finally, negate the result bits.  Result is same as using a
2034     // CmpD3Greater except we did it with CmpD3 alone.
2035     c = _gvn.transform( new CmpD3Node( b, a));
2036     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2037     push(c);
2038     break;
2039 
2040 
2041     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2042   case Bytecodes::_land:
2043     b = pop_pair();
2044     a = pop_pair();
2045     c = _gvn.transform( new AndLNode(a,b) );
2046     push_pair(c);
2047     break;
2048   case Bytecodes::_lor:
2049     b = pop_pair();
2050     a = pop_pair();
2051     c = _gvn.transform( new OrLNode(a,b) );
2052     push_pair(c);
2053     break;
2054   case Bytecodes::_lxor:
2055     b = pop_pair();
2056     a = pop_pair();
2057     c = _gvn.transform( new XorLNode(a,b) );
2058     push_pair(c);
2059     break;
2060 
2061   case Bytecodes::_lshl:
2062     b = pop();                  // the shift count
2063     a = pop_pair();             // value to be shifted
2064     c = _gvn.transform( new LShiftLNode(a,b) );
2065     push_pair(c);
2066     break;
2067   case Bytecodes::_lshr:
2068     b = pop();                  // the shift count
2069     a = pop_pair();             // value to be shifted
2070     c = _gvn.transform( new RShiftLNode(a,b) );
2071     push_pair(c);
2072     break;
2073   case Bytecodes::_lushr:
2074     b = pop();                  // the shift count
2075     a = pop_pair();             // value to be shifted
2076     c = _gvn.transform( new URShiftLNode(a,b) );
2077     push_pair(c);
2078     break;
2079   case Bytecodes::_lmul:
2080     b = pop_pair();
2081     a = pop_pair();
2082     c = _gvn.transform( new MulLNode(a,b) );
2083     push_pair(c);
2084     break;
2085 
2086   case Bytecodes::_lrem:
2087     // Must keep both values on the expression-stack during null-check
2088     assert(peek(0) == top(), "long word order");
2089     zero_check_long(peek(1));
2090     // Compile-time detect of null-exception?
2091     if (stopped())  return;
2092     b = pop_pair();
2093     a = pop_pair();
2094     c = _gvn.transform( new ModLNode(control(),a,b) );
2095     push_pair(c);
2096     break;
2097 
2098   case Bytecodes::_ldiv:
2099     // Must keep both values on the expression-stack during null-check
2100     assert(peek(0) == top(), "long word order");
2101     zero_check_long(peek(1));
2102     // Compile-time detect of null-exception?
2103     if (stopped())  return;
2104     b = pop_pair();
2105     a = pop_pair();
2106     c = _gvn.transform( new DivLNode(control(),a,b) );
2107     push_pair(c);
2108     break;
2109 
2110   case Bytecodes::_ladd:
2111     b = pop_pair();
2112     a = pop_pair();
2113     c = _gvn.transform( new AddLNode(a,b) );
2114     push_pair(c);
2115     break;
2116   case Bytecodes::_lsub:
2117     b = pop_pair();
2118     a = pop_pair();
2119     c = _gvn.transform( new SubLNode(a,b) );
2120     push_pair(c);
2121     break;
2122   case Bytecodes::_lcmp:
2123     // Safepoints are now inserted _before_ branches.  The long-compare
2124     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2125     // slew of control flow.  These are usually followed by a CmpI vs zero and
2126     // a branch; this pattern then optimizes to the obvious long-compare and
2127     // branch.  However, if the branch is backwards there's a Safepoint
2128     // inserted.  The inserted Safepoint captures the JVM state at the
2129     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
2130     // long-compare is used to control a loop the debug info will force
2131     // computation of the 3-way value, even though the generated code uses a
2132     // long-compare and branch.  We try to rectify the situation by inserting
2133     // a SafePoint here and have it dominate and kill the safepoint added at a
2134     // following backwards branch.  At this point the JVM state merely holds 2
2135     // longs but not the 3-way value.
2136     if( UseLoopSafepoints ) {
2137       switch( iter().next_bc() ) {
2138       case Bytecodes::_ifgt:
2139       case Bytecodes::_iflt:
2140       case Bytecodes::_ifge:
2141       case Bytecodes::_ifle:
2142       case Bytecodes::_ifne:
2143       case Bytecodes::_ifeq:
2144         // If this is a backwards branch in the bytecodes, add Safepoint
2145         maybe_add_safepoint(iter().next_get_dest());
2146       }
2147     }
2148     b = pop_pair();
2149     a = pop_pair();
2150     c = _gvn.transform( new CmpL3Node( a, b ));
2151     push(c);
2152     break;
2153 
2154   case Bytecodes::_lneg:
2155     a = pop_pair();
2156     b = _gvn.transform( new SubLNode(longcon(0),a));
2157     push_pair(b);
2158     break;
2159   case Bytecodes::_l2i:
2160     a = pop_pair();
2161     push( _gvn.transform( new ConvL2INode(a)));
2162     break;
2163   case Bytecodes::_i2l:
2164     a = pop();
2165     b = _gvn.transform( new ConvI2LNode(a));
2166     push_pair(b);
2167     break;
2168   case Bytecodes::_i2b:
2169     // Sign extend
2170     a = pop();
2171     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(24)) );
2172     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(24)) );
2173     push( a );
2174     break;
2175   case Bytecodes::_i2s:
2176     a = pop();
2177     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(16)) );
2178     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(16)) );
2179     push( a );
2180     break;
2181   case Bytecodes::_i2c:
2182     a = pop();
2183     push( _gvn.transform( new AndINode(a,_gvn.intcon(0xFFFF)) ) );
2184     break;
2185 
2186   case Bytecodes::_i2f:
2187     a = pop();
2188     b = _gvn.transform( new ConvI2FNode(a) ) ;
2189     c = precision_rounding(b);
2190     push (b);
2191     break;
2192 
2193   case Bytecodes::_i2d:
2194     a = pop();
2195     b = _gvn.transform( new ConvI2DNode(a));
2196     push_pair(b);
2197     break;
2198 
2199   case Bytecodes::_iinc:        // Increment local
2200     i = iter().get_index();     // Get local index
2201     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2202     break;
2203 
2204   // Exit points of synchronized methods must have an unlock node
2205   case Bytecodes::_return:
2206     return_current(NULL);
2207     break;
2208 
2209   case Bytecodes::_ireturn:
2210   case Bytecodes::_areturn:
2211   case Bytecodes::_freturn:
2212     return_current(pop());
2213     break;
2214   case Bytecodes::_lreturn:
2215     return_current(pop_pair());
2216     break;
2217   case Bytecodes::_dreturn:
2218     return_current(pop_pair());
2219     break;
2220 
2221   case Bytecodes::_athrow:
2222     // null exception oop throws NULL pointer exception
2223     null_check(peek());
2224     if (stopped())  return;
2225     // Hook the thrown exception directly to subsequent handlers.
2226     if (BailoutToInterpreterForThrows) {
2227       // Keep method interpreted from now on.
2228       uncommon_trap(Deoptimization::Reason_unhandled,
2229                     Deoptimization::Action_make_not_compilable);
2230       return;
2231     }
2232     if (env()->jvmti_can_post_on_exceptions()) {
2233       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2234       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2235     }
2236     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2237     add_exception_state(make_exception_state(peek()));
2238     break;
2239 
2240   case Bytecodes::_goto:   // fall through
2241   case Bytecodes::_goto_w: {
2242     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2243 
2244     // If this is a backwards branch in the bytecodes, add Safepoint
2245     maybe_add_safepoint(target_bci);
2246 
2247     // Update method data
2248     profile_taken_branch(target_bci);
2249 
2250     // Merge the current control into the target basic block
2251     merge(target_bci);
2252 
2253     // See if we can get some profile data and hand it off to the next block
2254     Block *target_block = block()->successor_for_bci(target_bci);
2255     if (target_block->pred_count() != 1)  break;
2256     ciMethodData* methodData = method()->method_data();
2257     if (!methodData->is_mature())  break;
2258     ciProfileData* data = methodData->bci_to_data(bci());
2259     assert( data->is_JumpData(), "" );
2260     int taken = ((ciJumpData*)data)->taken();
2261     taken = method()->scale_count(taken);
2262     target_block->set_count(taken);
2263     break;
2264   }
2265 
2266   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
2267   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2268   handle_if_null:
2269     // If this is a backwards branch in the bytecodes, add Safepoint
2270     maybe_add_safepoint(iter().get_dest());
2271     a = null();
2272     b = pop();
2273     if (!_gvn.type(b)->speculative_maybe_null() &&
2274         !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2275       inc_sp(1);
2276       Node* null_ctl = top();
2277       b = null_check_oop(b, &null_ctl, true, true, true);
2278       assert(null_ctl->is_top(), "no null control here");
2279       dec_sp(1);
2280     }
2281     c = _gvn.transform( new CmpPNode(b, a) );
2282     do_ifnull(btest, c);
2283     break;
2284 
2285   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2286   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2287   handle_if_acmp:
2288     // If this is a backwards branch in the bytecodes, add Safepoint
2289     maybe_add_safepoint(iter().get_dest());
2290     a = pop();
2291     b = pop();
2292     c = _gvn.transform( new CmpPNode(b, a) );
2293     c = optimize_cmp_with_klass(c);
2294     do_if(btest, c);
2295     break;
2296 
2297   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2298   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2299   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2300   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2301   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2302   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2303   handle_ifxx:
2304     // If this is a backwards branch in the bytecodes, add Safepoint
2305     maybe_add_safepoint(iter().get_dest());
2306     a = _gvn.intcon(0);
2307     b = pop();
2308     c = _gvn.transform( new CmpINode(b, a) );
2309     do_if(btest, c);
2310     break;
2311 
2312   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2313   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2314   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2315   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2316   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2317   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2318   handle_if_icmp:
2319     // If this is a backwards branch in the bytecodes, add Safepoint
2320     maybe_add_safepoint(iter().get_dest());
2321     a = pop();
2322     b = pop();
2323     c = _gvn.transform( new CmpINode( b, a ) );
2324     do_if(btest, c);
2325     break;
2326 
2327   case Bytecodes::_tableswitch:
2328     do_tableswitch();
2329     break;
2330 
2331   case Bytecodes::_lookupswitch:
2332     do_lookupswitch();
2333     break;
2334 
2335   case Bytecodes::_invokestatic:
2336   case Bytecodes::_invokedynamic:
2337   case Bytecodes::_invokespecial:
2338   case Bytecodes::_invokevirtual:
2339   case Bytecodes::_invokeinterface:
2340     do_call();
2341     break;
2342   case Bytecodes::_checkcast:
2343     do_checkcast();
2344     break;
2345   case Bytecodes::_instanceof:
2346     do_instanceof();
2347     break;
2348   case Bytecodes::_anewarray:
2349     do_anewarray();
2350     break;
2351   case Bytecodes::_newarray:
2352     do_newarray((BasicType)iter().get_index());
2353     break;
2354   case Bytecodes::_multianewarray:
2355     do_multianewarray();
2356     break;
2357   case Bytecodes::_new:
2358     do_new();
2359     break;
2360 
2361   case Bytecodes::_jsr:
2362   case Bytecodes::_jsr_w:
2363     do_jsr();
2364     break;
2365 
2366   case Bytecodes::_ret:
2367     do_ret();
2368     break;
2369 
2370 
2371   case Bytecodes::_monitorenter:
2372     do_monitor_enter();
2373     break;
2374 
2375   case Bytecodes::_monitorexit:
2376     do_monitor_exit();
2377     break;
2378 
2379   case Bytecodes::_breakpoint:
2380     // Breakpoint set concurrently to compile
2381     // %%% use an uncommon trap?
2382     C->record_failure("breakpoint in method");
2383     return;
2384 
2385   default:
2386 #ifndef PRODUCT
2387     map()->dump(99);
2388 #endif
2389     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2390     ShouldNotReachHere();
2391   }
2392 
2393 #ifndef PRODUCT
2394   IdealGraphPrinter *printer = IdealGraphPrinter::printer();
2395   if (printer && printer->should_print(_method)) {
2396     char buffer[256];
2397     sprintf(buffer, "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2398     bool old = printer->traverse_outs();
2399     printer->set_traverse_outs(true);
2400     printer->print_method(C, buffer, 4);
2401     printer->set_traverse_outs(old);
2402   }
2403 #endif
2404 }