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