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