1 /*
   2  * Copyright (c) 1997, 2024, 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 "classfile/vmSymbols.hpp"
  27 #include "interpreter/bytecodeStream.hpp"
  28 #include "logging/log.hpp"
  29 #include "logging/logStream.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/constantPool.hpp"
  33 #include "oops/generateOopMap.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "oops/symbol.hpp"
  36 #include "runtime/handles.inline.hpp"
  37 #include "runtime/java.hpp"
  38 #include "runtime/os.hpp"
  39 #include "runtime/relocator.hpp"
  40 #include "runtime/timerTrace.hpp"
  41 #include "utilities/bitMap.inline.hpp"
  42 #include "utilities/ostream.hpp"
  43 
  44 //
  45 //
  46 // Compute stack layouts for each instruction in method.
  47 //
  48 //  Problems:
  49 //  - What to do about jsr with different types of local vars?
  50 //  Need maps that are conditional on jsr path?
  51 //  - Jsr and exceptions should be done more efficiently (the retAddr stuff)
  52 //
  53 //  Alternative:
  54 //  - Could extend verifier to provide this information.
  55 //    For: one fewer abstract interpreter to maintain. Against: the verifier
  56 //    solves a bigger problem so slower (undesirable to force verification of
  57 //    everything?).
  58 //
  59 //  Algorithm:
  60 //    Partition bytecodes into basic blocks
  61 //    For each basic block: store entry state (vars, stack). For instructions
  62 //    inside basic blocks we do not store any state (instead we recompute it
  63 //    from state produced by previous instruction).
  64 //
  65 //    Perform abstract interpretation of bytecodes over this lattice:
  66 //
  67 //                _--'#'--_
  68 //               /  /  \   \
  69 //             /   /     \   \
  70 //            /    |     |     \
  71 //          'r'   'v'   'p'   ' '
  72 //           \     |     |     /
  73 //            \    \     /    /
  74 //              \   \   /    /
  75 //                -- '@' --
  76 //
  77 //    '#'  top, result of conflict merge
  78 //    'r'  reference type
  79 //    'v'  value type
  80 //    'p'  pc type for jsr/ret
  81 //    ' '  uninitialized; never occurs on operand stack in Java
  82 //    '@'  bottom/unexecuted; initial state each bytecode.
  83 //
  84 //    Basic block headers are the only merge points. We use this iteration to
  85 //    compute the information:
  86 //
  87 //    find basic blocks;
  88 //    initialize them with uninitialized state;
  89 //    initialize first BB according to method signature;
  90 //    mark first BB changed
  91 //    while (some BB is changed) do {
  92 //      perform abstract interpration of all bytecodes in BB;
  93 //      merge exit state of BB into entry state of all successor BBs,
  94 //      noting if any of these change;
  95 //    }
  96 //
  97 //  One additional complication is necessary. The jsr instruction pushes
  98 //  a return PC on the stack (a 'p' type in the abstract interpretation).
  99 //  To be able to process "ret" bytecodes, we keep track of these return
 100 //  PC's in a 'retAddrs' structure in abstract interpreter context (when
 101 //  processing a "ret" bytecodes, it is not sufficient to know that it gets
 102 //  an argument of the right type 'p'; we need to know which address it
 103 //  returns to).
 104 //
 105 // (Note this comment is borrowed form the original author of the algorithm)
 106 
 107 // ComputeCallStack
 108 //
 109 // Specialization of SignatureIterator - compute the effects of a call
 110 //
 111 class ComputeCallStack : public SignatureIterator {
 112   CellTypeState *_effect;
 113   int _idx;
 114 
 115   void setup();
 116   void set(CellTypeState state)         { _effect[_idx++] = state; }
 117   int  length()                         { return _idx; };
 118 
 119   friend class SignatureIterator;  // so do_parameters_on can call do_type
 120   void do_type(BasicType type, bool for_return = false) {
 121     if (for_return && type == T_VOID) {
 122       set(CellTypeState::bottom);
 123     } else if (is_reference_type(type)) {
 124       set(CellTypeState::ref);
 125     } else {
 126       assert(is_java_primitive(type), "");
 127       set(CellTypeState::value);
 128       if (is_double_word_type(type)) {
 129         set(CellTypeState::value);
 130       }
 131     }
 132   }
 133 
 134  public:
 135   ComputeCallStack(Symbol* signature) : SignatureIterator(signature) {};
 136 
 137   // Compute methods
 138   int compute_for_parameters(bool is_static, CellTypeState *effect) {
 139     _idx    = 0;
 140     _effect = effect;
 141 
 142     if (!is_static)
 143       effect[_idx++] = CellTypeState::ref;
 144 
 145     do_parameters_on(this);
 146 
 147     return length();
 148   };
 149 
 150   int compute_for_returntype(CellTypeState *effect) {
 151     _idx    = 0;
 152     _effect = effect;
 153     do_type(return_type(), true);
 154     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
 155 
 156     return length();
 157   }
 158 };
 159 
 160 //=========================================================================================
 161 // ComputeEntryStack
 162 //
 163 // Specialization of SignatureIterator - in order to set up first stack frame
 164 //
 165 class ComputeEntryStack : public SignatureIterator {
 166   CellTypeState *_effect;
 167   int _idx;
 168 
 169   void setup();
 170   void set(CellTypeState state)         { _effect[_idx++] = state; }
 171   int  length()                         { return _idx; };
 172 
 173   friend class SignatureIterator;  // so do_parameters_on can call do_type
 174   void do_type(BasicType type, bool for_return = false) {
 175     if (for_return && type == T_VOID) {
 176       set(CellTypeState::bottom);
 177     } else if (is_reference_type(type)) {
 178       set(CellTypeState::make_slot_ref(_idx));
 179     } else {
 180       assert(is_java_primitive(type), "");
 181       set(CellTypeState::value);
 182       if (is_double_word_type(type)) {
 183         set(CellTypeState::value);
 184       }
 185     }
 186   }
 187 
 188  public:
 189   ComputeEntryStack(Symbol* signature) : SignatureIterator(signature) {};
 190 
 191   // Compute methods
 192   int compute_for_parameters(bool is_static, CellTypeState *effect) {
 193     _idx    = 0;
 194     _effect = effect;
 195 
 196     if (!is_static)
 197       effect[_idx++] = CellTypeState::make_slot_ref(0);
 198 
 199     do_parameters_on(this);
 200 
 201     return length();
 202   };
 203 
 204   int compute_for_returntype(CellTypeState *effect) {
 205     _idx    = 0;
 206     _effect = effect;
 207     do_type(return_type(), true);
 208     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
 209 
 210     return length();
 211   }
 212 };
 213 
 214 //=====================================================================================
 215 //
 216 // Implementation of RetTable/RetTableEntry
 217 //
 218 // Contains function to itereate through all bytecodes
 219 // and find all return entry points
 220 //
 221 int RetTable::_init_nof_entries = 10;
 222 int RetTableEntry::_init_nof_jsrs = 5;
 223 
 224 RetTableEntry::RetTableEntry(int target, RetTableEntry *next) {
 225   _target_bci = target;
 226   _jsrs = new GrowableArray<int>(_init_nof_jsrs);
 227   _next = next;
 228 }
 229 
 230 void RetTableEntry::add_delta(int bci, int delta) {
 231   if (_target_bci > bci) _target_bci += delta;
 232 
 233   for (int k = 0; k < _jsrs->length(); k++) {
 234     int jsr = _jsrs->at(k);
 235     if (jsr > bci) _jsrs->at_put(k, jsr+delta);
 236   }
 237 }
 238 
 239 void RetTable::compute_ret_table(const methodHandle& method) {
 240   BytecodeStream i(method);
 241   Bytecodes::Code bytecode;
 242 
 243   while( (bytecode = i.next()) >= 0) {
 244     switch (bytecode) {
 245       case Bytecodes::_jsr:
 246         add_jsr(i.next_bci(), i.dest());
 247         break;
 248       case Bytecodes::_jsr_w:
 249         add_jsr(i.next_bci(), i.dest_w());
 250         break;
 251       default:
 252         break;
 253     }
 254   }
 255 }
 256 
 257 void RetTable::add_jsr(int return_bci, int target_bci) {
 258   RetTableEntry* entry = _first;
 259 
 260   // Scan table for entry
 261   for (;entry && entry->target_bci() != target_bci; entry = entry->next());
 262 
 263   if (!entry) {
 264     // Allocate new entry and put in list
 265     entry = new RetTableEntry(target_bci, _first);
 266     _first = entry;
 267   }
 268 
 269   // Now "entry" is set.  Make sure that the entry is initialized
 270   // and has room for the new jsr.
 271   entry->add_jsr(return_bci);
 272 }
 273 
 274 RetTableEntry* RetTable::find_jsrs_for_target(int targBci) {
 275   RetTableEntry *cur = _first;
 276 
 277   while(cur) {
 278     assert(cur->target_bci() != -1, "sanity check");
 279     if (cur->target_bci() == targBci)  return cur;
 280     cur = cur->next();
 281   }
 282   ShouldNotReachHere();
 283   return nullptr;
 284 }
 285 
 286 // The instruction at bci is changing size by "delta".  Update the return map.
 287 void RetTable::update_ret_table(int bci, int delta) {
 288   RetTableEntry *cur = _first;
 289   while(cur) {
 290     cur->add_delta(bci, delta);
 291     cur = cur->next();
 292   }
 293 }
 294 
 295 //
 296 // Celltype state
 297 //
 298 
 299 CellTypeState CellTypeState::bottom      = CellTypeState::make_bottom();
 300 CellTypeState CellTypeState::uninit      = CellTypeState::make_any(uninit_value);
 301 CellTypeState CellTypeState::ref         = CellTypeState::make_any(ref_conflict);
 302 CellTypeState CellTypeState::value       = CellTypeState::make_any(val_value);
 303 CellTypeState CellTypeState::refUninit   = CellTypeState::make_any(ref_conflict | uninit_value);
 304 CellTypeState CellTypeState::top         = CellTypeState::make_top();
 305 CellTypeState CellTypeState::addr        = CellTypeState::make_any(addr_conflict);
 306 
 307 // Commonly used constants
 308 static CellTypeState epsilonCTS[1] = { CellTypeState::bottom };
 309 static CellTypeState   refCTS   = CellTypeState::ref;
 310 static CellTypeState   valCTS   = CellTypeState::value;
 311 static CellTypeState    vCTS[2] = { CellTypeState::value, CellTypeState::bottom };
 312 static CellTypeState    rCTS[2] = { CellTypeState::ref,   CellTypeState::bottom };
 313 static CellTypeState   rrCTS[3] = { CellTypeState::ref,   CellTypeState::ref,   CellTypeState::bottom };
 314 static CellTypeState   vrCTS[3] = { CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 315 static CellTypeState   vvCTS[3] = { CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 316 static CellTypeState  rvrCTS[4] = { CellTypeState::ref,   CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 317 static CellTypeState  vvrCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 318 static CellTypeState  vvvCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 319 static CellTypeState vvvrCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 320 static CellTypeState vvvvCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 321 
 322 char CellTypeState::to_char() const {
 323   if (can_be_reference()) {
 324     if (can_be_value() || can_be_address())
 325       return '#';    // Conflict that needs to be rewritten
 326     else
 327       return 'r';
 328   } else if (can_be_value())
 329     return 'v';
 330   else if (can_be_address())
 331     return 'p';
 332   else if (can_be_uninit())
 333     return ' ';
 334   else
 335     return '@';
 336 }
 337 
 338 
 339 // Print a detailed CellTypeState.  Indicate all bits that are set.  If
 340 // the CellTypeState represents an address or a reference, print the
 341 // value of the additional information.
 342 void CellTypeState::print(outputStream *os) {
 343   if (can_be_address()) {
 344     os->print("(p");
 345   } else {
 346     os->print("( ");
 347   }
 348   if (can_be_reference()) {
 349     os->print("r");
 350   } else {
 351     os->print(" ");
 352   }
 353   if (can_be_value()) {
 354     os->print("v");
 355   } else {
 356     os->print(" ");
 357   }
 358   if (can_be_uninit()) {
 359     os->print("u|");
 360   } else {
 361     os->print(" |");
 362   }
 363   if (is_info_top()) {
 364     os->print("Top)");
 365   } else if (is_info_bottom()) {
 366     os->print("Bot)");
 367   } else {
 368     if (is_reference()) {
 369       int info = get_info();
 370       int data = info & ~(ref_not_lock_bit | ref_slot_bit);
 371       if (info & ref_not_lock_bit) {
 372         // Not a monitor lock reference.
 373         if (info & ref_slot_bit) {
 374           // slot
 375           os->print("slot%d)", data);
 376         } else {
 377           // line
 378           os->print("line%d)", data);
 379         }
 380       } else {
 381         // lock
 382         os->print("lock%d)", data);
 383       }
 384     } else {
 385       os->print("%d)", get_info());
 386     }
 387   }
 388 }
 389 
 390 //
 391 // Basicblock handling methods
 392 //
 393 
 394 void GenerateOopMap::initialize_bb() {
 395   _gc_points = 0;
 396   _bb_count  = 0;
 397   _bb_hdr_bits.reinitialize(method()->code_size());
 398 }
 399 
 400 void GenerateOopMap::bb_mark_fct(GenerateOopMap *c, int bci, int *data) {
 401   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
 402   if (c->is_bb_header(bci))
 403      return;
 404 
 405   if (TraceNewOopMapGeneration) {
 406      tty->print_cr("Basicblock#%d begins at: %d", c->_bb_count, bci);
 407   }
 408   c->set_bbmark_bit(bci);
 409   c->_bb_count++;
 410 }
 411 
 412 
 413 void GenerateOopMap::mark_bbheaders_and_count_gc_points() {
 414   initialize_bb();
 415 
 416   bool fellThrough = false;  // False to get first BB marked.
 417 
 418   // First mark all exception handlers as start of a basic-block
 419   ExceptionTable excps(method());
 420   for(int i = 0; i < excps.length(); i ++) {
 421     bb_mark_fct(this, excps.handler_pc(i), nullptr);
 422   }
 423 
 424   // Then iterate through the code
 425   BytecodeStream bcs(_method);
 426   Bytecodes::Code bytecode;
 427 
 428   while( (bytecode = bcs.next()) >= 0) {
 429     int bci = bcs.bci();
 430 
 431     if (!fellThrough)
 432         bb_mark_fct(this, bci, nullptr);
 433 
 434     fellThrough = jump_targets_do(&bcs, &GenerateOopMap::bb_mark_fct, nullptr);
 435 
 436      /* We will also mark successors of jsr's as basic block headers. */
 437     switch (bytecode) {
 438       case Bytecodes::_jsr:
 439       case Bytecodes::_jsr_w:
 440         assert(!fellThrough, "should not happen");
 441         // If this is the last bytecode, there is no successor to mark
 442         if (bci + Bytecodes::length_for(bytecode) < method()->code_size()) {
 443           bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), nullptr);
 444         }
 445         break;
 446       default:
 447         break;
 448     }
 449 
 450     if (possible_gc_point(&bcs))
 451       _gc_points++;
 452   }
 453 }
 454 
 455 void GenerateOopMap::set_bbmark_bit(int bci) {
 456   _bb_hdr_bits.at_put(bci, true);
 457 }
 458 
 459 void GenerateOopMap::reachable_basicblock(GenerateOopMap *c, int bci, int *data) {
 460   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
 461   BasicBlock* bb = c->get_basic_block_at(bci);
 462   if (bb->is_dead()) {
 463     bb->mark_as_alive();
 464     *data = 1; // Mark basicblock as changed
 465   }
 466 }
 467 
 468 
 469 void GenerateOopMap::mark_reachable_code() {
 470   int change = 1; // int to get function pointers to work
 471 
 472   // Mark entry basic block as alive and all exception handlers
 473   _basic_blocks[0].mark_as_alive();
 474   ExceptionTable excps(method());
 475   for(int i = 0; i < excps.length(); i++) {
 476     BasicBlock *bb = get_basic_block_at(excps.handler_pc(i));
 477     // If block is not already alive (due to multiple exception handlers to same bb), then
 478     // make it alive
 479     if (bb->is_dead()) bb->mark_as_alive();
 480   }
 481 
 482   BytecodeStream bcs(_method);
 483 
 484   // Iterate through all basic blocks until we reach a fixpoint
 485   while (change) {
 486     change = 0;
 487 
 488     for (int i = 0; i < _bb_count; i++) {
 489       BasicBlock *bb = &_basic_blocks[i];
 490       if (bb->is_alive()) {
 491         // Position bytecodestream at last bytecode in basicblock
 492         bcs.set_start(bb->_end_bci);
 493         bcs.next();
 494         Bytecodes::Code bytecode = bcs.code();
 495         int bci = bcs.bci();
 496         assert(bci == bb->_end_bci, "wrong bci");
 497 
 498         bool fell_through = jump_targets_do(&bcs, &GenerateOopMap::reachable_basicblock, &change);
 499 
 500         // We will also mark successors of jsr's as alive.
 501         switch (bytecode) {
 502           case Bytecodes::_jsr:
 503           case Bytecodes::_jsr_w:
 504             assert(!fell_through, "should not happen");
 505             // If this is the last bytecode, there is no successor to mark
 506             if (bci + Bytecodes::length_for(bytecode) < method()->code_size()) {
 507               reachable_basicblock(this, bci + Bytecodes::length_for(bytecode), &change);
 508             }
 509             break;
 510           default:
 511             break;
 512         }
 513         if (fell_through) {
 514           // Mark successor as alive
 515           if (bb[1].is_dead()) {
 516             bb[1].mark_as_alive();
 517             change = 1;
 518           }
 519         }
 520       }
 521     }
 522   }
 523 }
 524 
 525 /* If the current instruction in "c" has no effect on control flow,
 526    returns "true".  Otherwise, calls "jmpFct" one or more times, with
 527    "c", an appropriate "pcDelta", and "data" as arguments, then
 528    returns "false".  There is one exception: if the current
 529    instruction is a "ret", returns "false" without calling "jmpFct".
 530    Arrangements for tracking the control flow of a "ret" must be made
 531    externally. */
 532 bool GenerateOopMap::jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int *data) {
 533   int bci = bcs->bci();
 534 
 535   switch (bcs->code()) {
 536     case Bytecodes::_ifeq:
 537     case Bytecodes::_ifne:
 538     case Bytecodes::_iflt:
 539     case Bytecodes::_ifge:
 540     case Bytecodes::_ifgt:
 541     case Bytecodes::_ifle:
 542     case Bytecodes::_if_icmpeq:
 543     case Bytecodes::_if_icmpne:
 544     case Bytecodes::_if_icmplt:
 545     case Bytecodes::_if_icmpge:
 546     case Bytecodes::_if_icmpgt:
 547     case Bytecodes::_if_icmple:
 548     case Bytecodes::_if_acmpeq:
 549     case Bytecodes::_if_acmpne:
 550     case Bytecodes::_ifnull:
 551     case Bytecodes::_ifnonnull:
 552       (*jmpFct)(this, bcs->dest(), data);
 553       // Class files verified by the old verifier can have a conditional branch
 554       // as their last bytecode, provided the conditional branch is unreachable
 555       // during execution.  Check if this instruction is the method's last bytecode
 556       // and, if so, don't call the jmpFct.
 557       if (bci + 3 < method()->code_size()) {
 558         (*jmpFct)(this, bci + 3, data);
 559       }
 560       break;
 561 
 562     case Bytecodes::_goto:
 563       (*jmpFct)(this, bcs->dest(), data);
 564       break;
 565     case Bytecodes::_goto_w:
 566       (*jmpFct)(this, bcs->dest_w(), data);
 567       break;
 568     case Bytecodes::_tableswitch:
 569       { Bytecode_tableswitch tableswitch(method(), bcs->bcp());
 570         int len = tableswitch.length();
 571 
 572         (*jmpFct)(this, bci + tableswitch.default_offset(), data); /* Default. jump address */
 573         while (--len >= 0) {
 574           (*jmpFct)(this, bci + tableswitch.dest_offset_at(len), data);
 575         }
 576         break;
 577       }
 578 
 579     case Bytecodes::_lookupswitch:
 580       { Bytecode_lookupswitch lookupswitch(method(), bcs->bcp());
 581         int npairs = lookupswitch.number_of_pairs();
 582         (*jmpFct)(this, bci + lookupswitch.default_offset(), data); /* Default. */
 583         while(--npairs >= 0) {
 584           LookupswitchPair pair = lookupswitch.pair_at(npairs);
 585           (*jmpFct)(this, bci + pair.offset(), data);
 586         }
 587         break;
 588       }
 589     case Bytecodes::_jsr:
 590       assert(bcs->is_wide()==false, "sanity check");
 591       (*jmpFct)(this, bcs->dest(), data);
 592       break;
 593     case Bytecodes::_jsr_w:
 594       (*jmpFct)(this, bcs->dest_w(), data);
 595       break;
 596     case Bytecodes::_wide:
 597       ShouldNotReachHere();
 598       return true;
 599       break;
 600     case Bytecodes::_athrow:
 601     case Bytecodes::_ireturn:
 602     case Bytecodes::_lreturn:
 603     case Bytecodes::_freturn:
 604     case Bytecodes::_dreturn:
 605     case Bytecodes::_areturn:
 606     case Bytecodes::_return:
 607     case Bytecodes::_ret:
 608       break;
 609     default:
 610       return true;
 611   }
 612   return false;
 613 }
 614 
 615 /* Requires "pc" to be the head of a basic block; returns that basic
 616    block. */
 617 BasicBlock *GenerateOopMap::get_basic_block_at(int bci) const {
 618   BasicBlock* bb = get_basic_block_containing(bci);
 619   assert(bb->_bci == bci, "should have found BB");
 620   return bb;
 621 }
 622 
 623 // Requires "pc" to be the start of an instruction; returns the basic
 624 //   block containing that instruction. */
 625 BasicBlock  *GenerateOopMap::get_basic_block_containing(int bci) const {
 626   BasicBlock *bbs = _basic_blocks;
 627   int lo = 0, hi = _bb_count - 1;
 628 
 629   while (lo <= hi) {
 630     int m = (lo + hi) / 2;
 631     int mbci = bbs[m]._bci;
 632     int nbci;
 633 
 634     if ( m == _bb_count-1) {
 635       assert( bci >= mbci && bci < method()->code_size(), "sanity check failed");
 636       return bbs+m;
 637     } else {
 638       nbci = bbs[m+1]._bci;
 639     }
 640 
 641     if ( mbci <= bci && bci < nbci) {
 642       return bbs+m;
 643     } else if (mbci < bci) {
 644       lo = m + 1;
 645     } else {
 646       assert(mbci > bci, "sanity check");
 647       hi = m - 1;
 648     }
 649   }
 650 
 651   fatal("should have found BB");
 652   return nullptr;
 653 }
 654 
 655 void GenerateOopMap::restore_state(BasicBlock *bb)
 656 {
 657   memcpy(_state, bb->_state, _state_len*sizeof(CellTypeState));
 658   _stack_top = bb->_stack_top;
 659   _monitor_top = bb->_monitor_top;
 660 }
 661 
 662 int GenerateOopMap::next_bb_start_pc(BasicBlock *bb) {
 663  intptr_t bbNum = bb - _basic_blocks + 1;
 664  if (bbNum == _bb_count)
 665     return method()->code_size();
 666 
 667  return _basic_blocks[bbNum]._bci;
 668 }
 669 
 670 //
 671 // CellType handling methods
 672 //
 673 
 674 // Allocate memory and throw LinkageError if failure.
 675 #define ALLOC_RESOURCE_ARRAY(var, type, count)                           \
 676   var = NEW_RESOURCE_ARRAY_RETURN_NULL(type, count);                     \
 677   if (var == nullptr) {                                                  \
 678     report_error("Cannot reserve enough memory to analyze this method"); \
 679     return;                                                              \
 680   }
 681 
 682 
 683 void GenerateOopMap::init_state() {
 684   _state_len     = _max_locals + _max_stack + _max_monitors;
 685   ALLOC_RESOURCE_ARRAY(_state, CellTypeState, _state_len);
 686   memset(_state, 0, _state_len * sizeof(CellTypeState));
 687   int count = MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */;
 688   ALLOC_RESOURCE_ARRAY(_state_vec_buf, char, count);
 689 }
 690 
 691 void GenerateOopMap::make_context_uninitialized() {
 692   CellTypeState* vs = vars();
 693 
 694   for (int i = 0; i < _max_locals; i++)
 695       vs[i] = CellTypeState::uninit;
 696 
 697   _stack_top = 0;
 698   _monitor_top = 0;
 699 }
 700 
 701 int GenerateOopMap::methodsig_to_effect(Symbol* signature, bool is_static, CellTypeState* effect) {
 702   ComputeEntryStack ces(signature);
 703   return ces.compute_for_parameters(is_static, effect);
 704 }
 705 
 706 // Return result of merging cts1 and cts2.
 707 CellTypeState CellTypeState::merge(CellTypeState cts, int slot) const {
 708   CellTypeState result;
 709 
 710   assert(!is_bottom() && !cts.is_bottom(),
 711          "merge of bottom values is handled elsewhere");
 712 
 713   result._state = _state | cts._state;
 714 
 715   // If the top bit is set, we don't need to do any more work.
 716   if (!result.is_info_top()) {
 717     assert((result.can_be_address() || result.can_be_reference()),
 718            "only addresses and references have non-top info");
 719 
 720     if (!equal(cts)) {
 721       // The two values being merged are different.  Raise to top.
 722       if (result.is_reference()) {
 723         result = CellTypeState::make_slot_ref(slot);
 724       } else {
 725         result._state |= info_conflict;
 726       }
 727     }
 728   }
 729   assert(result.is_valid_state(), "checking that CTS merge maintains legal state");
 730 
 731   return result;
 732 }
 733 
 734 // Merge the variable state for locals and stack from cts into bbts.
 735 bool GenerateOopMap::merge_local_state_vectors(CellTypeState* cts,
 736                                                CellTypeState* bbts) {
 737   int i;
 738   int len = _max_locals + _stack_top;
 739   bool change = false;
 740 
 741   for (i = len - 1; i >= 0; i--) {
 742     CellTypeState v = cts[i].merge(bbts[i], i);
 743     change = change || !v.equal(bbts[i]);
 744     bbts[i] = v;
 745   }
 746 
 747   return change;
 748 }
 749 
 750 // Merge the monitor stack state from cts into bbts.
 751 bool GenerateOopMap::merge_monitor_state_vectors(CellTypeState* cts,
 752                                                  CellTypeState* bbts) {
 753   bool change = false;
 754   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
 755     // If there are no monitors in the program, or there has been
 756     // a monitor matching error before this point in the program,
 757     // then we do not merge in the monitor state.
 758 
 759     int base = _max_locals + _max_stack;
 760     int len = base + _monitor_top;
 761     for (int i = len - 1; i >= base; i--) {
 762       CellTypeState v = cts[i].merge(bbts[i], i);
 763 
 764       // Can we prove that, when there has been a change, it will already
 765       // have been detected at this point?  That would make this equal
 766       // check here unnecessary.
 767       change = change || !v.equal(bbts[i]);
 768       bbts[i] = v;
 769     }
 770   }
 771 
 772   return change;
 773 }
 774 
 775 void GenerateOopMap::copy_state(CellTypeState *dst, CellTypeState *src) {
 776   int len = _max_locals + _stack_top;
 777   for (int i = 0; i < len; i++) {
 778     if (src[i].is_nonlock_reference()) {
 779       dst[i] = CellTypeState::make_slot_ref(i);
 780     } else {
 781       dst[i] = src[i];
 782     }
 783   }
 784   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
 785     int base = _max_locals + _max_stack;
 786     len = base + _monitor_top;
 787     for (int i = base; i < len; i++) {
 788       dst[i] = src[i];
 789     }
 790   }
 791 }
 792 
 793 
 794 // Merge the states for the current block and the next.  As long as a
 795 // block is reachable the locals and stack must be merged.  If the
 796 // stack heights don't match then this is a verification error and
 797 // it's impossible to interpret the code.  Simultaneously monitor
 798 // states are being check to see if they nest statically.  If monitor
 799 // depths match up then their states are merged.  Otherwise the
 800 // mismatch is simply recorded and interpretation continues since
 801 // monitor matching is purely informational and doesn't say anything
 802 // about the correctness of the code.
 803 void GenerateOopMap::merge_state_into_bb(BasicBlock *bb) {
 804   guarantee(bb != nullptr, "null basicblock");
 805   assert(bb->is_alive(), "merging state into a dead basicblock");
 806 
 807   if (_stack_top == bb->_stack_top) {
 808     // always merge local state even if monitors don't match.
 809     if (merge_local_state_vectors(_state, bb->_state)) {
 810       bb->set_changed(true);
 811     }
 812     if (_monitor_top == bb->_monitor_top) {
 813       // monitors still match so continue merging monitor states.
 814       if (merge_monitor_state_vectors(_state, bb->_state)) {
 815         bb->set_changed(true);
 816       }
 817     } else {
 818       if (log_is_enabled(Info, monitormismatch)) {
 819         report_monitor_mismatch("monitor stack height merge conflict");
 820       }
 821       // When the monitor stacks are not matched, we set _monitor_top to
 822       // bad_monitors.  This signals that, from here on, the monitor stack cannot
 823       // be trusted.  In particular, monitorexit bytecodes may throw
 824       // exceptions.  We mark this block as changed so that the change
 825       // propagates properly.
 826       bb->_monitor_top = bad_monitors;
 827       bb->set_changed(true);
 828       _monitor_safe = false;
 829     }
 830   } else if (!bb->is_reachable()) {
 831     // First time we look at this  BB
 832     copy_state(bb->_state, _state);
 833     bb->_stack_top = _stack_top;
 834     bb->_monitor_top = _monitor_top;
 835     bb->set_changed(true);
 836   } else {
 837     verify_error("stack height conflict: %d vs. %d",  _stack_top, bb->_stack_top);
 838   }
 839 }
 840 
 841 void GenerateOopMap::merge_state(GenerateOopMap *gom, int bci, int* data) {
 842    gom->merge_state_into_bb(gom->get_basic_block_at(bci));
 843 }
 844 
 845 void GenerateOopMap::set_var(int localNo, CellTypeState cts) {
 846   assert(cts.is_reference() || cts.is_value() || cts.is_address(),
 847          "wrong celltypestate");
 848   if (localNo < 0 || localNo > _max_locals) {
 849     verify_error("variable write error: r%d", localNo);
 850     return;
 851   }
 852   vars()[localNo] = cts;
 853 }
 854 
 855 CellTypeState GenerateOopMap::get_var(int localNo) {
 856   assert(localNo < _max_locals + _nof_refval_conflicts, "variable read error");
 857   if (localNo < 0 || localNo > _max_locals) {
 858     verify_error("variable read error: r%d", localNo);
 859     return valCTS; // just to pick something;
 860   }
 861   return vars()[localNo];
 862 }
 863 
 864 CellTypeState GenerateOopMap::pop() {
 865   if ( _stack_top <= 0) {
 866     verify_error("stack underflow");
 867     return valCTS; // just to pick something
 868   }
 869   return  stack()[--_stack_top];
 870 }
 871 
 872 void GenerateOopMap::push(CellTypeState cts) {
 873   if ( _stack_top >= _max_stack) {
 874     verify_error("stack overflow");
 875     return;
 876   }
 877   stack()[_stack_top++] = cts;
 878 }
 879 
 880 CellTypeState GenerateOopMap::monitor_pop() {
 881   assert(_monitor_top != bad_monitors, "monitor_pop called on error monitor stack");
 882   if (_monitor_top == 0) {
 883     // We have detected a pop of an empty monitor stack.
 884     _monitor_safe = false;
 885      _monitor_top = bad_monitors;
 886 
 887     if (log_is_enabled(Info, monitormismatch)) {
 888       report_monitor_mismatch("monitor stack underflow");
 889     }
 890     return CellTypeState::ref; // just to keep the analysis going.
 891   }
 892   return  monitors()[--_monitor_top];
 893 }
 894 
 895 void GenerateOopMap::monitor_push(CellTypeState cts) {
 896   assert(_monitor_top != bad_monitors, "monitor_push called on error monitor stack");
 897   if (_monitor_top >= _max_monitors) {
 898     // Some monitorenter is being executed more than once.
 899     // This means that the monitor stack cannot be simulated.
 900     _monitor_safe = false;
 901     _monitor_top = bad_monitors;
 902 
 903     if (log_is_enabled(Info, monitormismatch)) {
 904       report_monitor_mismatch("monitor stack overflow");
 905     }
 906     return;
 907   }
 908   monitors()[_monitor_top++] = cts;
 909 }
 910 
 911 //
 912 // Interpretation handling methods
 913 //
 914 
 915 void GenerateOopMap::do_interpretation()
 916 {
 917   // "i" is just for debugging, so we can detect cases where this loop is
 918   // iterated more than once.
 919   int i = 0;
 920   do {
 921 #ifndef PRODUCT
 922     if (TraceNewOopMapGeneration) {
 923       tty->print("\n\nIteration #%d of do_interpretation loop, method:\n", i);
 924       method()->print_name(tty);
 925       tty->print("\n\n");
 926     }
 927 #endif
 928     _conflict = false;
 929     _monitor_safe = true;
 930     // init_state is now called from init_basic_blocks.  The length of a
 931     // state vector cannot be determined until we have made a pass through
 932     // the bytecodes counting the possible monitor entries.
 933     if (!_got_error) init_basic_blocks();
 934     if (!_got_error) setup_method_entry_state();
 935     if (!_got_error) interp_all();
 936     if (!_got_error) rewrite_refval_conflicts();
 937     i++;
 938   } while (_conflict && !_got_error);
 939 }
 940 
 941 void GenerateOopMap::init_basic_blocks() {
 942   // Note: Could consider reserving only the needed space for each BB's state
 943   // (entry stack may not be of maximal height for every basic block).
 944   // But cumbersome since we don't know the stack heights yet.  (Nor the
 945   // monitor stack heights...)
 946 
 947   ALLOC_RESOURCE_ARRAY(_basic_blocks, BasicBlock, _bb_count);
 948 
 949   // Make a pass through the bytecodes.  Count the number of monitorenters.
 950   // This can be used an upper bound on the monitor stack depth in programs
 951   // which obey stack discipline with their monitor usage.  Initialize the
 952   // known information about basic blocks.
 953   BytecodeStream j(_method);
 954   Bytecodes::Code bytecode;
 955 
 956   int bbNo = 0;
 957   int monitor_count = 0;
 958   int prev_bci = -1;
 959   while( (bytecode = j.next()) >= 0) {
 960     if (j.code() == Bytecodes::_monitorenter) {
 961       monitor_count++;
 962     }
 963 
 964     int bci = j.bci();
 965     if (is_bb_header(bci)) {
 966       // Initialize the basicblock structure
 967       BasicBlock *bb   = _basic_blocks + bbNo;
 968       bb->_bci         = bci;
 969       bb->_max_locals  = _max_locals;
 970       bb->_max_stack   = _max_stack;
 971       bb->set_changed(false);
 972       bb->_stack_top   = BasicBlock::_dead_basic_block; // Initialize all basicblocks are dead.
 973       bb->_monitor_top = bad_monitors;
 974 
 975       if (bbNo > 0) {
 976         _basic_blocks[bbNo - 1]._end_bci = prev_bci;
 977       }
 978 
 979       bbNo++;
 980     }
 981     // Remember previous bci.
 982     prev_bci = bci;
 983   }
 984   // Set
 985   _basic_blocks[bbNo-1]._end_bci = prev_bci;
 986 
 987 
 988   // Check that the correct number of basicblocks was found
 989   if (bbNo !=_bb_count) {
 990     if (bbNo < _bb_count) {
 991       verify_error("jump into the middle of instruction?");
 992       return;
 993     } else {
 994       verify_error("extra basic blocks - should not happen?");
 995       return;
 996     }
 997   }
 998 
 999   _max_monitors = monitor_count;
1000 
1001   // Now that we have a bound on the depth of the monitor stack, we can
1002   // initialize the CellTypeState-related information.
1003   init_state();
1004 
1005   // We allocate space for all state-vectors for all basicblocks in one huge
1006   // chunk.  Then in the next part of the code, we set a pointer in each
1007   // _basic_block that points to each piece.
1008 
1009   // The product of bbNo and _state_len can get large if there are lots of
1010   // basic blocks and stack/locals/monitors.  Need to check to make sure
1011   // we don't overflow the capacity of a pointer.
1012   if ((unsigned)bbNo > UINTPTR_MAX / sizeof(CellTypeState) / _state_len) {
1013     report_error("The amount of memory required to analyze this method "
1014                  "exceeds addressable range");
1015     return;
1016   }
1017 
1018   CellTypeState *basicBlockState;
1019   ALLOC_RESOURCE_ARRAY(basicBlockState, CellTypeState, bbNo * _state_len);
1020   memset(basicBlockState, 0, bbNo * _state_len * sizeof(CellTypeState));
1021 
1022   // Make a pass over the basicblocks and assign their state vectors.
1023   for (int blockNum=0; blockNum < bbNo; blockNum++) {
1024     BasicBlock *bb = _basic_blocks + blockNum;
1025     bb->_state = basicBlockState + blockNum * _state_len;
1026 
1027 #ifdef ASSERT
1028     if (blockNum + 1 < bbNo) {
1029       address bcp = _method->bcp_from(bb->_end_bci);
1030       int bc_len = Bytecodes::java_length_at(_method(), bcp);
1031       assert(bb->_end_bci + bc_len == bb[1]._bci, "unmatched bci info in basicblock");
1032     }
1033 #endif
1034   }
1035 #ifdef ASSERT
1036   { BasicBlock *bb = &_basic_blocks[bbNo-1];
1037     address bcp = _method->bcp_from(bb->_end_bci);
1038     int bc_len = Bytecodes::java_length_at(_method(), bcp);
1039     assert(bb->_end_bci + bc_len == _method->code_size(), "wrong end bci");
1040   }
1041 #endif
1042 
1043   // Mark all alive blocks
1044   mark_reachable_code();
1045 }
1046 
1047 void GenerateOopMap::setup_method_entry_state() {
1048 
1049     // Initialize all locals to 'uninit' and set stack-height to 0
1050     make_context_uninitialized();
1051 
1052     // Initialize CellState type of arguments
1053     methodsig_to_effect(method()->signature(), method()->is_static(), vars());
1054 
1055     // If some references must be pre-assigned to null, then set that up
1056     initialize_vars();
1057 
1058     // This is the start state
1059     merge_state_into_bb(&_basic_blocks[0]);
1060 
1061     assert(_basic_blocks[0].changed(), "we are not getting off the ground");
1062 }
1063 
1064 // The instruction at bci is changing size by "delta".  Update the basic blocks.
1065 void GenerateOopMap::update_basic_blocks(int bci, int delta,
1066                                          int new_method_size) {
1067   assert(new_method_size >= method()->code_size() + delta,
1068          "new method size is too small");
1069 
1070   _bb_hdr_bits.reinitialize(new_method_size);
1071 
1072   for(int k = 0; k < _bb_count; k++) {
1073     if (_basic_blocks[k]._bci > bci) {
1074       _basic_blocks[k]._bci     += delta;
1075       _basic_blocks[k]._end_bci += delta;
1076     }
1077     _bb_hdr_bits.at_put(_basic_blocks[k]._bci, true);
1078   }
1079 }
1080 
1081 //
1082 // Initvars handling
1083 //
1084 
1085 void GenerateOopMap::initialize_vars() {
1086   for (int k = 0; k < _init_vars->length(); k++)
1087     _state[_init_vars->at(k)] = CellTypeState::make_slot_ref(k);
1088 }
1089 
1090 void GenerateOopMap::add_to_ref_init_set(int localNo) {
1091 
1092   if (TraceNewOopMapGeneration)
1093     tty->print_cr("Added init vars: %d", localNo);
1094 
1095   // Is it already in the set?
1096   if (_init_vars->contains(localNo) )
1097     return;
1098 
1099    _init_vars->append(localNo);
1100 }
1101 
1102 //
1103 // Interpreration code
1104 //
1105 
1106 void GenerateOopMap::interp_all() {
1107   bool change = true;
1108 
1109   while (change && !_got_error) {
1110     change = false;
1111     for (int i = 0; i < _bb_count && !_got_error; i++) {
1112       BasicBlock *bb = &_basic_blocks[i];
1113       if (bb->changed()) {
1114          if (_got_error) return;
1115          change = true;
1116          bb->set_changed(false);
1117          interp_bb(bb);
1118       }
1119     }
1120   }
1121 }
1122 
1123 void GenerateOopMap::interp_bb(BasicBlock *bb) {
1124 
1125   // We do not want to do anything in case the basic-block has not been initialized. This
1126   // will happen in the case where there is dead-code hang around in a method.
1127   assert(bb->is_reachable(), "should be reachable or deadcode exist");
1128   restore_state(bb);
1129 
1130   BytecodeStream itr(_method);
1131 
1132   // Set iterator interval to be the current basicblock
1133   int lim_bci = next_bb_start_pc(bb);
1134   itr.set_interval(bb->_bci, lim_bci);
1135   assert(lim_bci != bb->_bci, "must be at least one instruction in a basicblock");
1136   itr.next(); // read first instruction
1137 
1138   // Iterates through all bytecodes except the last in a basic block.
1139   // We handle the last one special, since there is controlflow change.
1140   while(itr.next_bci() < lim_bci && !_got_error) {
1141     if (_has_exceptions || _monitor_top != 0) {
1142       // We do not need to interpret the results of exceptional
1143       // continuation from this instruction when the method has no
1144       // exception handlers and the monitor stack is currently
1145       // empty.
1146       do_exception_edge(&itr);
1147     }
1148     interp1(&itr);
1149     itr.next();
1150   }
1151 
1152   // Handle last instruction.
1153   if (!_got_error) {
1154     assert(itr.next_bci() == lim_bci, "must point to end");
1155     if (_has_exceptions || _monitor_top != 0) {
1156       do_exception_edge(&itr);
1157     }
1158     interp1(&itr);
1159 
1160     bool fall_through = jump_targets_do(&itr, GenerateOopMap::merge_state, nullptr);
1161     if (_got_error)  return;
1162 
1163     if (itr.code() == Bytecodes::_ret) {
1164       assert(!fall_through, "cannot be set if ret instruction");
1165       // Automatically handles 'wide' ret indices
1166       ret_jump_targets_do(&itr, GenerateOopMap::merge_state, itr.get_index(), nullptr);
1167     } else if (fall_through) {
1168      // Hit end of BB, but the instr. was a fall-through instruction,
1169      // so perform transition as if the BB ended in a "jump".
1170      if (lim_bci != bb[1]._bci) {
1171        verify_error("bytecodes fell through last instruction");
1172        return;
1173      }
1174      merge_state_into_bb(bb + 1);
1175     }
1176   }
1177 }
1178 
1179 void GenerateOopMap::do_exception_edge(BytecodeStream* itr) {
1180   // Only check exception edge, if bytecode can trap
1181   if (!Bytecodes::can_trap(itr->code())) return;
1182   switch (itr->code()) {
1183     case Bytecodes::_aload_0:
1184       // These bytecodes can trap for rewriting.  We need to assume that
1185       // they do not throw exceptions to make the monitor analysis work.
1186       return;
1187 
1188     case Bytecodes::_ireturn:
1189     case Bytecodes::_lreturn:
1190     case Bytecodes::_freturn:
1191     case Bytecodes::_dreturn:
1192     case Bytecodes::_areturn:
1193     case Bytecodes::_return:
1194       // If the monitor stack height is not zero when we leave the method,
1195       // then we are either exiting with a non-empty stack or we have
1196       // found monitor trouble earlier in our analysis.  In either case,
1197       // assume an exception could be taken here.
1198       if (_monitor_top == 0) {
1199         return;
1200       }
1201       break;
1202 
1203     case Bytecodes::_monitorexit:
1204       // If the monitor stack height is bad_monitors, then we have detected a
1205       // monitor matching problem earlier in the analysis.  If the
1206       // monitor stack height is 0, we are about to pop a monitor
1207       // off of an empty stack.  In either case, the bytecode
1208       // could throw an exception.
1209       if (_monitor_top != bad_monitors && _monitor_top != 0) {
1210         return;
1211       }
1212       break;
1213 
1214     default:
1215       break;
1216   }
1217 
1218   if (_has_exceptions) {
1219     int bci = itr->bci();
1220     ExceptionTable exct(method());
1221     for(int i = 0; i< exct.length(); i++) {
1222       int start_pc   = exct.start_pc(i);
1223       int end_pc     = exct.end_pc(i);
1224       int handler_pc = exct.handler_pc(i);
1225       int catch_type = exct.catch_type_index(i);
1226 
1227       if (start_pc <= bci && bci < end_pc) {
1228         BasicBlock *excBB = get_basic_block_at(handler_pc);
1229         guarantee(excBB != nullptr, "no basic block for exception");
1230         CellTypeState *excStk = excBB->stack();
1231         CellTypeState *cOpStck = stack();
1232         CellTypeState cOpStck_0 = cOpStck[0];
1233         int cOpStackTop = _stack_top;
1234 
1235         // Exception stacks are always the same.
1236         assert(method()->max_stack() > 0, "sanity check");
1237 
1238         // We remembered the size and first element of "cOpStck"
1239         // above; now we temporarily set them to the appropriate
1240         // values for an exception handler. */
1241         cOpStck[0] = CellTypeState::make_slot_ref(_max_locals);
1242         _stack_top = 1;
1243 
1244         merge_state_into_bb(excBB);
1245 
1246         // Now undo the temporary change.
1247         cOpStck[0] = cOpStck_0;
1248         _stack_top = cOpStackTop;
1249 
1250         // If this is a "catch all" handler, then we do not need to
1251         // consider any additional handlers.
1252         if (catch_type == 0) {
1253           return;
1254         }
1255       }
1256     }
1257   }
1258 
1259   // It is possible that none of the exception handlers would have caught
1260   // the exception.  In this case, we will exit the method.  We must
1261   // ensure that the monitor stack is empty in this case.
1262   if (_monitor_top == 0) {
1263     return;
1264   }
1265 
1266   // We pessimistically assume that this exception can escape the
1267   // method. (It is possible that it will always be caught, but
1268   // we don't care to analyse the types of the catch clauses.)
1269 
1270   // We don't set _monitor_top to bad_monitors because there are no successors
1271   // to this exceptional exit.
1272 
1273   if (log_is_enabled(Info, monitormismatch) && _monitor_safe) {
1274     // We check _monitor_safe so that we only report the first mismatched
1275     // exceptional exit.
1276     report_monitor_mismatch("non-empty monitor stack at exceptional exit");
1277   }
1278   _monitor_safe = false;
1279 
1280 }
1281 
1282 void GenerateOopMap::report_monitor_mismatch(const char *msg) {
1283   ResourceMark rm;
1284   LogStream ls(Log(monitormismatch)::info());
1285   ls.print("Monitor mismatch in method ");
1286   method()->print_short_name(&ls);
1287   ls.print_cr(": %s", msg);
1288 }
1289 
1290 void GenerateOopMap::print_states(outputStream *os,
1291                                   CellTypeState* vec, int num) {
1292   for (int i = 0; i < num; i++) {
1293     vec[i].print(tty);
1294   }
1295 }
1296 
1297 // Print the state values at the current bytecode.
1298 void GenerateOopMap::print_current_state(outputStream   *os,
1299                                          BytecodeStream *currentBC,
1300                                          bool            detailed) {
1301   if (detailed) {
1302     os->print("     %4d vars     = ", currentBC->bci());
1303     print_states(os, vars(), _max_locals);
1304     os->print("    %s", Bytecodes::name(currentBC->code()));
1305   } else {
1306     os->print("    %4d  vars = '%s' ", currentBC->bci(),  state_vec_to_string(vars(), _max_locals));
1307     os->print("     stack = '%s' ", state_vec_to_string(stack(), _stack_top));
1308     if (_monitor_top != bad_monitors) {
1309       os->print("  monitors = '%s'  \t%s", state_vec_to_string(monitors(), _monitor_top), Bytecodes::name(currentBC->code()));
1310     } else {
1311       os->print("  [bad monitor stack]");
1312     }
1313   }
1314 
1315   switch(currentBC->code()) {
1316     case Bytecodes::_invokevirtual:
1317     case Bytecodes::_invokespecial:
1318     case Bytecodes::_invokestatic:
1319     case Bytecodes::_invokedynamic:
1320     case Bytecodes::_invokeinterface: {
1321       int idx = currentBC->has_index_u4() ? currentBC->get_index_u4() : currentBC->get_index_u2();
1322       ConstantPool* cp      = method()->constants();
1323       int nameAndTypeIdx    = cp->name_and_type_ref_index_at(idx, currentBC->code());
1324       int signatureIdx      = cp->signature_ref_index_at(nameAndTypeIdx);
1325       Symbol* signature     = cp->symbol_at(signatureIdx);
1326       os->print("%s", signature->as_C_string());
1327     }
1328     default:
1329       break;
1330   }
1331 
1332   if (detailed) {
1333     os->cr();
1334     os->print("          stack    = ");
1335     print_states(os, stack(), _stack_top);
1336     os->cr();
1337     if (_monitor_top != bad_monitors) {
1338       os->print("          monitors = ");
1339       print_states(os, monitors(), _monitor_top);
1340     } else {
1341       os->print("          [bad monitor stack]");
1342     }
1343   }
1344 
1345   os->cr();
1346 }
1347 
1348 // Sets the current state to be the state after executing the
1349 // current instruction, starting in the current state.
1350 void GenerateOopMap::interp1(BytecodeStream *itr) {
1351   if (TraceNewOopMapGeneration) {
1352     print_current_state(tty, itr, TraceNewOopMapGenerationDetailed);
1353   }
1354 
1355   // Should we report the results? Result is reported *before* the instruction at the current bci is executed.
1356   // However, not for calls. For calls we do not want to include the arguments, so we postpone the reporting until
1357   // they have been popped (in method ppl).
1358   if (_report_result == true) {
1359     switch(itr->code()) {
1360       case Bytecodes::_invokevirtual:
1361       case Bytecodes::_invokespecial:
1362       case Bytecodes::_invokestatic:
1363       case Bytecodes::_invokedynamic:
1364       case Bytecodes::_invokeinterface:
1365         _itr_send = itr;
1366         _report_result_for_send = true;
1367         break;
1368       default:
1369        fill_stackmap_for_opcodes(itr, vars(), stack(), _stack_top);
1370        break;
1371     }
1372   }
1373 
1374   // abstract interpretation of current opcode
1375   switch(itr->code()) {
1376     case Bytecodes::_nop:                                           break;
1377     case Bytecodes::_goto:                                          break;
1378     case Bytecodes::_goto_w:                                        break;
1379     case Bytecodes::_iinc:                                          break;
1380     case Bytecodes::_return:            do_return_monitor_check();
1381                                         break;
1382 
1383     case Bytecodes::_aconst_null:
1384     case Bytecodes::_new:               ppush1(CellTypeState::make_line_ref(itr->bci()));
1385                                         break;
1386 
1387     case Bytecodes::_iconst_m1:
1388     case Bytecodes::_iconst_0:
1389     case Bytecodes::_iconst_1:
1390     case Bytecodes::_iconst_2:
1391     case Bytecodes::_iconst_3:
1392     case Bytecodes::_iconst_4:
1393     case Bytecodes::_iconst_5:
1394     case Bytecodes::_fconst_0:
1395     case Bytecodes::_fconst_1:
1396     case Bytecodes::_fconst_2:
1397     case Bytecodes::_bipush:
1398     case Bytecodes::_sipush:            ppush1(valCTS);             break;
1399 
1400     case Bytecodes::_lconst_0:
1401     case Bytecodes::_lconst_1:
1402     case Bytecodes::_dconst_0:
1403     case Bytecodes::_dconst_1:          ppush(vvCTS);               break;
1404 
1405     case Bytecodes::_ldc2_w:            ppush(vvCTS);               break;
1406 
1407     case Bytecodes::_ldc:               // fall through:
1408     case Bytecodes::_ldc_w:             do_ldc(itr->bci());         break;
1409 
1410     case Bytecodes::_iload:
1411     case Bytecodes::_fload:             ppload(vCTS, itr->get_index()); break;
1412 
1413     case Bytecodes::_lload:
1414     case Bytecodes::_dload:             ppload(vvCTS,itr->get_index()); break;
1415 
1416     case Bytecodes::_aload:             ppload(rCTS, itr->get_index()); break;
1417 
1418     case Bytecodes::_iload_0:
1419     case Bytecodes::_fload_0:           ppload(vCTS, 0);            break;
1420     case Bytecodes::_iload_1:
1421     case Bytecodes::_fload_1:           ppload(vCTS, 1);            break;
1422     case Bytecodes::_iload_2:
1423     case Bytecodes::_fload_2:           ppload(vCTS, 2);            break;
1424     case Bytecodes::_iload_3:
1425     case Bytecodes::_fload_3:           ppload(vCTS, 3);            break;
1426 
1427     case Bytecodes::_lload_0:
1428     case Bytecodes::_dload_0:           ppload(vvCTS, 0);           break;
1429     case Bytecodes::_lload_1:
1430     case Bytecodes::_dload_1:           ppload(vvCTS, 1);           break;
1431     case Bytecodes::_lload_2:
1432     case Bytecodes::_dload_2:           ppload(vvCTS, 2);           break;
1433     case Bytecodes::_lload_3:
1434     case Bytecodes::_dload_3:           ppload(vvCTS, 3);           break;
1435 
1436     case Bytecodes::_aload_0:           ppload(rCTS, 0);            break;
1437     case Bytecodes::_aload_1:           ppload(rCTS, 1);            break;
1438     case Bytecodes::_aload_2:           ppload(rCTS, 2);            break;
1439     case Bytecodes::_aload_3:           ppload(rCTS, 3);            break;
1440 
1441     case Bytecodes::_iaload:
1442     case Bytecodes::_faload:
1443     case Bytecodes::_baload:
1444     case Bytecodes::_caload:
1445     case Bytecodes::_saload:            pp(vrCTS, vCTS); break;
1446 
1447     case Bytecodes::_laload:            pp(vrCTS, vvCTS);  break;
1448     case Bytecodes::_daload:            pp(vrCTS, vvCTS); break;
1449 
1450     case Bytecodes::_aaload:            pp_new_ref(vrCTS, itr->bci()); break;
1451 
1452     case Bytecodes::_istore:
1453     case Bytecodes::_fstore:            ppstore(vCTS, itr->get_index()); break;
1454 
1455     case Bytecodes::_lstore:
1456     case Bytecodes::_dstore:            ppstore(vvCTS, itr->get_index()); break;
1457 
1458     case Bytecodes::_astore:            do_astore(itr->get_index());     break;
1459 
1460     case Bytecodes::_istore_0:
1461     case Bytecodes::_fstore_0:          ppstore(vCTS, 0);           break;
1462     case Bytecodes::_istore_1:
1463     case Bytecodes::_fstore_1:          ppstore(vCTS, 1);           break;
1464     case Bytecodes::_istore_2:
1465     case Bytecodes::_fstore_2:          ppstore(vCTS, 2);           break;
1466     case Bytecodes::_istore_3:
1467     case Bytecodes::_fstore_3:          ppstore(vCTS, 3);           break;
1468 
1469     case Bytecodes::_lstore_0:
1470     case Bytecodes::_dstore_0:          ppstore(vvCTS, 0);          break;
1471     case Bytecodes::_lstore_1:
1472     case Bytecodes::_dstore_1:          ppstore(vvCTS, 1);          break;
1473     case Bytecodes::_lstore_2:
1474     case Bytecodes::_dstore_2:          ppstore(vvCTS, 2);          break;
1475     case Bytecodes::_lstore_3:
1476     case Bytecodes::_dstore_3:          ppstore(vvCTS, 3);          break;
1477 
1478     case Bytecodes::_astore_0:          do_astore(0);               break;
1479     case Bytecodes::_astore_1:          do_astore(1);               break;
1480     case Bytecodes::_astore_2:          do_astore(2);               break;
1481     case Bytecodes::_astore_3:          do_astore(3);               break;
1482 
1483     case Bytecodes::_iastore:
1484     case Bytecodes::_fastore:
1485     case Bytecodes::_bastore:
1486     case Bytecodes::_castore:
1487     case Bytecodes::_sastore:           ppop(vvrCTS);               break;
1488     case Bytecodes::_lastore:
1489     case Bytecodes::_dastore:           ppop(vvvrCTS);              break;
1490     case Bytecodes::_aastore:           ppop(rvrCTS);               break;
1491 
1492     case Bytecodes::_pop:               ppop_any(1);                break;
1493     case Bytecodes::_pop2:              ppop_any(2);                break;
1494 
1495     case Bytecodes::_dup:               ppdupswap(1, "11");         break;
1496     case Bytecodes::_dup_x1:            ppdupswap(2, "121");        break;
1497     case Bytecodes::_dup_x2:            ppdupswap(3, "1321");       break;
1498     case Bytecodes::_dup2:              ppdupswap(2, "2121");       break;
1499     case Bytecodes::_dup2_x1:           ppdupswap(3, "21321");      break;
1500     case Bytecodes::_dup2_x2:           ppdupswap(4, "214321");     break;
1501     case Bytecodes::_swap:              ppdupswap(2, "12");         break;
1502 
1503     case Bytecodes::_iadd:
1504     case Bytecodes::_fadd:
1505     case Bytecodes::_isub:
1506     case Bytecodes::_fsub:
1507     case Bytecodes::_imul:
1508     case Bytecodes::_fmul:
1509     case Bytecodes::_idiv:
1510     case Bytecodes::_fdiv:
1511     case Bytecodes::_irem:
1512     case Bytecodes::_frem:
1513     case Bytecodes::_ishl:
1514     case Bytecodes::_ishr:
1515     case Bytecodes::_iushr:
1516     case Bytecodes::_iand:
1517     case Bytecodes::_ior:
1518     case Bytecodes::_ixor:
1519     case Bytecodes::_l2f:
1520     case Bytecodes::_l2i:
1521     case Bytecodes::_d2f:
1522     case Bytecodes::_d2i:
1523     case Bytecodes::_fcmpl:
1524     case Bytecodes::_fcmpg:             pp(vvCTS, vCTS); break;
1525 
1526     case Bytecodes::_ladd:
1527     case Bytecodes::_dadd:
1528     case Bytecodes::_lsub:
1529     case Bytecodes::_dsub:
1530     case Bytecodes::_lmul:
1531     case Bytecodes::_dmul:
1532     case Bytecodes::_ldiv:
1533     case Bytecodes::_ddiv:
1534     case Bytecodes::_lrem:
1535     case Bytecodes::_drem:
1536     case Bytecodes::_land:
1537     case Bytecodes::_lor:
1538     case Bytecodes::_lxor:              pp(vvvvCTS, vvCTS); break;
1539 
1540     case Bytecodes::_ineg:
1541     case Bytecodes::_fneg:
1542     case Bytecodes::_i2f:
1543     case Bytecodes::_f2i:
1544     case Bytecodes::_i2c:
1545     case Bytecodes::_i2s:
1546     case Bytecodes::_i2b:               pp(vCTS, vCTS); break;
1547 
1548     case Bytecodes::_lneg:
1549     case Bytecodes::_dneg:
1550     case Bytecodes::_l2d:
1551     case Bytecodes::_d2l:               pp(vvCTS, vvCTS); break;
1552 
1553     case Bytecodes::_lshl:
1554     case Bytecodes::_lshr:
1555     case Bytecodes::_lushr:             pp(vvvCTS, vvCTS); break;
1556 
1557     case Bytecodes::_i2l:
1558     case Bytecodes::_i2d:
1559     case Bytecodes::_f2l:
1560     case Bytecodes::_f2d:               pp(vCTS, vvCTS); break;
1561 
1562     case Bytecodes::_lcmp:              pp(vvvvCTS, vCTS); break;
1563     case Bytecodes::_dcmpl:
1564     case Bytecodes::_dcmpg:             pp(vvvvCTS, vCTS); break;
1565 
1566     case Bytecodes::_ifeq:
1567     case Bytecodes::_ifne:
1568     case Bytecodes::_iflt:
1569     case Bytecodes::_ifge:
1570     case Bytecodes::_ifgt:
1571     case Bytecodes::_ifle:
1572     case Bytecodes::_tableswitch:       ppop1(valCTS);
1573                                         break;
1574     case Bytecodes::_ireturn:
1575     case Bytecodes::_freturn:           do_return_monitor_check();
1576                                         ppop1(valCTS);
1577                                         break;
1578     case Bytecodes::_if_icmpeq:
1579     case Bytecodes::_if_icmpne:
1580     case Bytecodes::_if_icmplt:
1581     case Bytecodes::_if_icmpge:
1582     case Bytecodes::_if_icmpgt:
1583     case Bytecodes::_if_icmple:         ppop(vvCTS);
1584                                         break;
1585 
1586     case Bytecodes::_lreturn:           do_return_monitor_check();
1587                                         ppop(vvCTS);
1588                                         break;
1589 
1590     case Bytecodes::_dreturn:           do_return_monitor_check();
1591                                         ppop(vvCTS);
1592                                         break;
1593 
1594     case Bytecodes::_if_acmpeq:
1595     case Bytecodes::_if_acmpne:         ppop(rrCTS);                 break;
1596 
1597     case Bytecodes::_jsr:               do_jsr(itr->dest());         break;
1598     case Bytecodes::_jsr_w:             do_jsr(itr->dest_w());       break;
1599 
1600     case Bytecodes::_getstatic:         do_field(true,   true,  itr->get_index_u2(), itr->bci(), itr->code()); break;
1601     case Bytecodes::_putstatic:         do_field(false,  true,  itr->get_index_u2(), itr->bci(), itr->code()); break;
1602     case Bytecodes::_getfield:          do_field(true,   false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1603     case Bytecodes::_putfield:          do_field(false,  false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1604 
1605     case Bytecodes::_invokevirtual:
1606     case Bytecodes::_invokespecial:     do_method(false, false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1607     case Bytecodes::_invokestatic:      do_method(true,  false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1608     case Bytecodes::_invokedynamic:     do_method(true,  false, itr->get_index_u4(), itr->bci(), itr->code()); break;
1609     case Bytecodes::_invokeinterface:   do_method(false, true,  itr->get_index_u2(), itr->bci(), itr->code()); break;
1610     case Bytecodes::_newarray:
1611     case Bytecodes::_anewarray:         pp_new_ref(vCTS, itr->bci()); break;
1612     case Bytecodes::_checkcast:         do_checkcast(); break;
1613     case Bytecodes::_arraylength:
1614     case Bytecodes::_instanceof:        pp(rCTS, vCTS); break;
1615     case Bytecodes::_monitorenter:      do_monitorenter(itr->bci()); break;
1616     case Bytecodes::_monitorexit:       do_monitorexit(itr->bci()); break;
1617 
1618     case Bytecodes::_athrow:            // handled by do_exception_edge() BUT ...
1619                                         // vlh(apple): do_exception_edge() does not get
1620                                         // called if method has no exception handlers
1621                                         if ((!_has_exceptions) && (_monitor_top > 0)) {
1622                                           _monitor_safe = false;
1623                                         }
1624                                         break;
1625 
1626     case Bytecodes::_areturn:           do_return_monitor_check();
1627                                         ppop1(refCTS);
1628                                         break;
1629     case Bytecodes::_ifnull:
1630     case Bytecodes::_ifnonnull:         ppop1(refCTS); break;
1631     case Bytecodes::_multianewarray:    do_multianewarray(*(itr->bcp()+3), itr->bci()); break;
1632 
1633     case Bytecodes::_wide:              fatal("Iterator should skip this bytecode"); break;
1634     case Bytecodes::_ret:                                           break;
1635 
1636     // Java opcodes
1637     case Bytecodes::_lookupswitch:      ppop1(valCTS);             break;
1638 
1639     default:
1640          tty->print("unexpected opcode: %d\n", itr->code());
1641          ShouldNotReachHere();
1642     break;
1643   }
1644 }
1645 
1646 void GenerateOopMap::check_type(CellTypeState expected, CellTypeState actual) {
1647   if (!expected.equal_kind(actual)) {
1648     verify_error("wrong type on stack (found: %c expected: %c)", actual.to_char(), expected.to_char());
1649   }
1650 }
1651 
1652 void GenerateOopMap::ppstore(CellTypeState *in, int loc_no) {
1653   while(!(*in).is_bottom()) {
1654     CellTypeState expected =*in++;
1655     CellTypeState actual   = pop();
1656     check_type(expected, actual);
1657     assert(loc_no >= 0, "sanity check");
1658     set_var(loc_no++, actual);
1659   }
1660 }
1661 
1662 void GenerateOopMap::ppload(CellTypeState *out, int loc_no) {
1663   while(!(*out).is_bottom()) {
1664     CellTypeState out1 = *out++;
1665     CellTypeState vcts = get_var(loc_no);
1666     assert(out1.can_be_reference() || out1.can_be_value(),
1667            "can only load refs. and values.");
1668     if (out1.is_reference()) {
1669       assert(loc_no>=0, "sanity check");
1670       if (!vcts.is_reference()) {
1671         // We were asked to push a reference, but the type of the
1672         // variable can be something else
1673         _conflict = true;
1674         if (vcts.can_be_uninit()) {
1675           // It is a ref-uninit conflict (at least). If there are other
1676           // problems, we'll get them in the next round
1677           add_to_ref_init_set(loc_no);
1678           vcts = out1;
1679         } else {
1680           // It wasn't a ref-uninit conflict. So must be a
1681           // ref-val or ref-pc conflict. Split the variable.
1682           record_refval_conflict(loc_no);
1683           vcts = out1;
1684         }
1685         push(out1); // recover...
1686       } else {
1687         push(vcts); // preserve reference.
1688       }
1689       // Otherwise it is a conflict, but one that verification would
1690       // have caught if illegal. In particular, it can't be a topCTS
1691       // resulting from mergeing two difference pcCTS's since the verifier
1692       // would have rejected any use of such a merge.
1693     } else {
1694       push(out1); // handle val/init conflict
1695     }
1696     loc_no++;
1697   }
1698 }
1699 
1700 void GenerateOopMap::ppdupswap(int poplen, const char *out) {
1701   CellTypeState actual[5];
1702   assert(poplen < 5, "this must be less than length of actual vector");
1703 
1704   // Pop all arguments.
1705   for (int i = 0; i < poplen; i++) {
1706     actual[i] = pop();
1707   }
1708   // Field _state is uninitialized when calling push.
1709   for (int i = poplen; i < 5; i++) {
1710     actual[i] = CellTypeState::uninit;
1711   }
1712 
1713   // put them back
1714   char push_ch = *out++;
1715   while (push_ch != '\0') {
1716     int idx = push_ch - '1';
1717     assert(idx >= 0 && idx < poplen, "wrong arguments");
1718     push(actual[idx]);
1719     push_ch = *out++;
1720   }
1721 }
1722 
1723 void GenerateOopMap::ppop1(CellTypeState out) {
1724   CellTypeState actual = pop();
1725   check_type(out, actual);
1726 }
1727 
1728 void GenerateOopMap::ppop(CellTypeState *out) {
1729   while (!(*out).is_bottom()) {
1730     ppop1(*out++);
1731   }
1732 }
1733 
1734 void GenerateOopMap::ppush1(CellTypeState in) {
1735   assert(in.is_reference() || in.is_value(), "sanity check");
1736   push(in);
1737 }
1738 
1739 void GenerateOopMap::ppush(CellTypeState *in) {
1740   while (!(*in).is_bottom()) {
1741     ppush1(*in++);
1742   }
1743 }
1744 
1745 void GenerateOopMap::pp(CellTypeState *in, CellTypeState *out) {
1746   ppop(in);
1747   ppush(out);
1748 }
1749 
1750 void GenerateOopMap::pp_new_ref(CellTypeState *in, int bci) {
1751   ppop(in);
1752   ppush1(CellTypeState::make_line_ref(bci));
1753 }
1754 
1755 void GenerateOopMap::ppop_any(int poplen) {
1756   if (_stack_top >= poplen) {
1757     _stack_top -= poplen;
1758   } else {
1759     verify_error("stack underflow");
1760   }
1761 }
1762 
1763 // Replace all occurrences of the state 'match' with the state 'replace'
1764 // in our current state vector.
1765 void GenerateOopMap::replace_all_CTS_matches(CellTypeState match,
1766                                              CellTypeState replace) {
1767   int i;
1768   int len = _max_locals + _stack_top;
1769   bool change = false;
1770 
1771   for (i = len - 1; i >= 0; i--) {
1772     if (match.equal(_state[i])) {
1773       _state[i] = replace;
1774     }
1775   }
1776 
1777   if (_monitor_top > 0) {
1778     int base = _max_locals + _max_stack;
1779     len = base + _monitor_top;
1780     for (i = len - 1; i >= base; i--) {
1781       if (match.equal(_state[i])) {
1782         _state[i] = replace;
1783       }
1784     }
1785   }
1786 }
1787 
1788 void GenerateOopMap::do_checkcast() {
1789   CellTypeState actual = pop();
1790   check_type(refCTS, actual);
1791   push(actual);
1792 }
1793 
1794 void GenerateOopMap::do_monitorenter(int bci) {
1795   CellTypeState actual = pop();
1796   if (_monitor_top == bad_monitors) {
1797     return;
1798   }
1799 
1800   // Bail out when we get repeated locks on an identical monitor.  This case
1801   // isn't too hard to handle and can be made to work if supporting nested
1802   // redundant synchronized statements becomes a priority.
1803   //
1804   // See also "Note" in do_monitorexit(), below.
1805   if (actual.is_lock_reference()) {
1806     _monitor_top = bad_monitors;
1807     _monitor_safe = false;
1808 
1809     if (log_is_enabled(Info, monitormismatch)) {
1810       report_monitor_mismatch("nested redundant lock -- bailout...");
1811     }
1812     return;
1813   }
1814 
1815   CellTypeState lock = CellTypeState::make_lock_ref(bci);
1816   check_type(refCTS, actual);
1817   if (!actual.is_info_top()) {
1818     replace_all_CTS_matches(actual, lock);
1819     monitor_push(lock);
1820   }
1821 }
1822 
1823 void GenerateOopMap::do_monitorexit(int bci) {
1824   CellTypeState actual = pop();
1825   if (_monitor_top == bad_monitors) {
1826     return;
1827   }
1828   check_type(refCTS, actual);
1829   CellTypeState expected = monitor_pop();
1830   if (!actual.is_lock_reference() || !expected.equal(actual)) {
1831     // The monitor we are exiting is not verifiably the one
1832     // on the top of our monitor stack.  This causes a monitor
1833     // mismatch.
1834     _monitor_top = bad_monitors;
1835     _monitor_safe = false;
1836 
1837     // We need to mark this basic block as changed so that
1838     // this monitorexit will be visited again.  We need to
1839     // do this to ensure that we have accounted for the
1840     // possibility that this bytecode will throw an
1841     // exception.
1842     BasicBlock* bb = get_basic_block_containing(bci);
1843     guarantee(bb != nullptr, "no basic block for bci");
1844     bb->set_changed(true);
1845     bb->_monitor_top = bad_monitors;
1846 
1847     if (log_is_enabled(Info, monitormismatch)) {
1848       report_monitor_mismatch("improper monitor pair");
1849     }
1850   } else {
1851     // This code is a fix for the case where we have repeated
1852     // locking of the same object in straightline code.  We clear
1853     // out the lock when it is popped from the monitor stack
1854     // and replace it with an unobtrusive reference value that can
1855     // be locked again.
1856     //
1857     // Note: when generateOopMap is fixed to properly handle repeated,
1858     //       nested, redundant locks on the same object, then this
1859     //       fix will need to be removed at that time.
1860     replace_all_CTS_matches(actual, CellTypeState::make_line_ref(bci));
1861   }
1862 }
1863 
1864 void GenerateOopMap::do_return_monitor_check() {
1865   if (_monitor_top > 0) {
1866     // The monitor stack must be empty when we leave the method
1867     // for the monitors to be properly matched.
1868     _monitor_safe = false;
1869 
1870     // Since there are no successors to the *return bytecode, it
1871     // isn't necessary to set _monitor_top to bad_monitors.
1872 
1873     if (log_is_enabled(Info, monitormismatch)) {
1874       report_monitor_mismatch("non-empty monitor stack at return");
1875     }
1876   }
1877 }
1878 
1879 void GenerateOopMap::do_jsr(int targ_bci) {
1880   push(CellTypeState::make_addr(targ_bci));
1881 }
1882 
1883 
1884 
1885 void GenerateOopMap::do_ldc(int bci) {
1886   Bytecode_loadconstant ldc(methodHandle(Thread::current(), method()), bci);
1887   ConstantPool* cp  = method()->constants();
1888   constantTag tag = cp->tag_at(ldc.pool_index()); // idx is index in resolved_references
1889   BasicType       bt  = ldc.result_type();
1890 #ifdef ASSERT
1891   BasicType   tag_bt = (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) ? bt : tag.basic_type();
1892   assert(bt == tag_bt, "same result");
1893 #endif
1894   CellTypeState   cts;
1895   if (is_reference_type(bt)) {  // could be T_ARRAY with condy
1896     assert(!tag.is_string_index() && !tag.is_klass_index(), "Unexpected index tag");
1897     cts = CellTypeState::make_line_ref(bci);
1898   } else {
1899     cts = valCTS;
1900   }
1901   ppush1(cts);
1902 }
1903 
1904 void GenerateOopMap::do_multianewarray(int dims, int bci) {
1905   assert(dims >= 1, "sanity check");
1906   for(int i = dims -1; i >=0; i--) {
1907     ppop1(valCTS);
1908   }
1909   ppush1(CellTypeState::make_line_ref(bci));
1910 }
1911 
1912 void GenerateOopMap::do_astore(int idx) {
1913   CellTypeState r_or_p = pop();
1914   if (!r_or_p.is_address() && !r_or_p.is_reference()) {
1915     // We actually expected ref or pc, but we only report that we expected a ref. It does not
1916     // really matter (at least for now)
1917     verify_error("wrong type on stack (found: %c, expected: {pr})", r_or_p.to_char());
1918     return;
1919   }
1920   set_var(idx, r_or_p);
1921 }
1922 
1923 // Copies bottom/zero terminated CTS string from "src" into "dst".
1924 //   Does NOT terminate with a bottom. Returns the number of cells copied.
1925 int GenerateOopMap::copy_cts(CellTypeState *dst, CellTypeState *src) {
1926   int idx = 0;
1927   while (!src[idx].is_bottom()) {
1928     dst[idx] = src[idx];
1929     idx++;
1930   }
1931   return idx;
1932 }
1933 
1934 void GenerateOopMap::do_field(int is_get, int is_static, int idx, int bci, Bytecodes::Code bc) {
1935   // Dig up signature for field in constant pool
1936   ConstantPool* cp     = method()->constants();
1937   int nameAndTypeIdx     = cp->name_and_type_ref_index_at(idx, bc);
1938   int signatureIdx       = cp->signature_ref_index_at(nameAndTypeIdx);
1939   Symbol* signature      = cp->symbol_at(signatureIdx);
1940 
1941   CellTypeState temp[4];
1942   CellTypeState *eff  = signature_to_effect(signature, bci, temp);
1943 
1944   CellTypeState in[4];
1945   CellTypeState *out;
1946   int i =  0;
1947 
1948   if (is_get) {
1949     out = eff;
1950   } else {
1951     out = epsilonCTS;
1952     i   = copy_cts(in, eff);
1953   }
1954   if (!is_static) in[i++] = CellTypeState::ref;
1955   in[i] = CellTypeState::bottom;
1956   assert(i<=3, "sanity check");
1957   pp(in, out);
1958 }
1959 
1960 void GenerateOopMap::do_method(int is_static, int is_interface, int idx, int bci, Bytecodes::Code bc) {
1961  // Dig up signature for field in constant pool
1962   ConstantPool* cp  = _method->constants();
1963   Symbol* signature   = cp->signature_ref_at(idx, bc);
1964 
1965   // Parse method signature
1966   CellTypeState out[4];
1967   CellTypeState in[MAXARGSIZE+1];   // Includes result
1968   ComputeCallStack cse(signature);
1969 
1970   // Compute return type
1971   int res_length=  cse.compute_for_returntype(out);
1972 
1973   // Temporary hack.
1974   if (out[0].equal(CellTypeState::ref) && out[1].equal(CellTypeState::bottom)) {
1975     out[0] = CellTypeState::make_line_ref(bci);
1976   }
1977 
1978   assert(res_length<=4, "max value should be vv");
1979 
1980   // Compute arguments
1981   int arg_length = cse.compute_for_parameters(is_static != 0, in);
1982   assert(arg_length<=MAXARGSIZE, "too many locals");
1983 
1984   // Pop arguments
1985   for (int i = arg_length - 1; i >= 0; i--) ppop1(in[i]);// Do args in reverse order.
1986 
1987   // Report results
1988   if (_report_result_for_send == true) {
1989      fill_stackmap_for_opcodes(_itr_send, vars(), stack(), _stack_top);
1990      _report_result_for_send = false;
1991   }
1992 
1993   // Push return address
1994   ppush(out);
1995 }
1996 
1997 // This is used to parse the signature for fields, since they are very simple...
1998 CellTypeState *GenerateOopMap::signature_to_effect(const Symbol* sig, int bci, CellTypeState *out) {
1999   // Object and array
2000   BasicType bt = Signature::basic_type(sig);
2001   if (is_reference_type(bt)) {
2002     out[0] = CellTypeState::make_line_ref(bci);
2003     out[1] = CellTypeState::bottom;
2004     return out;
2005   }
2006   if (is_double_word_type(bt)) return vvCTS; // Long and Double
2007   if (bt == T_VOID) return epsilonCTS;       // Void
2008   return vCTS;                               // Otherwise
2009 }
2010 
2011 uint64_t GenerateOopMap::_total_byte_count = 0;
2012 elapsedTimer GenerateOopMap::_total_oopmap_time;
2013 
2014 // This function assumes "bcs" is at a "ret" instruction and that the vars
2015 // state is valid for that instruction. Furthermore, the ret instruction
2016 // must be the last instruction in "bb" (we store information about the
2017 // "ret" in "bb").
2018 void GenerateOopMap::ret_jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int varNo, int *data) {
2019   CellTypeState ra = vars()[varNo];
2020   if (!ra.is_good_address()) {
2021     verify_error("ret returns from two jsr subroutines?");
2022     return;
2023   }
2024   int target = ra.get_info();
2025 
2026   RetTableEntry* rtEnt = _rt.find_jsrs_for_target(target);
2027   int bci = bcs->bci();
2028   for (int i = 0; i < rtEnt->nof_jsrs(); i++) {
2029     int target_bci = rtEnt->jsrs(i);
2030     // Make sure a jrtRet does not set the changed bit for dead basicblock.
2031     BasicBlock* jsr_bb    = get_basic_block_containing(target_bci - 1);
2032     debug_only(BasicBlock* target_bb = &jsr_bb[1];)
2033     assert(target_bb  == get_basic_block_at(target_bci), "wrong calc. of successor basicblock");
2034     bool alive = jsr_bb->is_alive();
2035     if (TraceNewOopMapGeneration) {
2036       tty->print("pc = %d, ret -> %d alive: %s\n", bci, target_bci, alive ? "true" : "false");
2037     }
2038     if (alive) jmpFct(this, target_bci, data);
2039   }
2040 }
2041 
2042 //
2043 // Debug method
2044 //
2045 char* GenerateOopMap::state_vec_to_string(CellTypeState* vec, int len) {
2046 #ifdef ASSERT
2047   int checklen = MAX3(_max_locals, _max_stack, _max_monitors) + 1;
2048   assert(len < checklen, "state_vec_buf overflow");
2049 #endif
2050   for (int i = 0; i < len; i++) _state_vec_buf[i] = vec[i].to_char();
2051   _state_vec_buf[len] = 0;
2052   return _state_vec_buf;
2053 }
2054 
2055 void GenerateOopMap::print_time() {
2056   tty->print_cr ("Accumulated oopmap times:");
2057   tty->print_cr ("---------------------------");
2058   tty->print_cr ("  Total : %3.3f sec.", GenerateOopMap::_total_oopmap_time.seconds());
2059   tty->print_cr ("  (%3.0f bytecodes per sec) ",
2060   (double)GenerateOopMap::_total_byte_count / GenerateOopMap::_total_oopmap_time.seconds());
2061 }
2062 
2063 //
2064 //  ============ Main Entry Point ===========
2065 //
2066 GenerateOopMap::GenerateOopMap(const methodHandle& method) {
2067   // We have to initialize all variables here, that can be queried directly
2068   _method = method;
2069   _max_locals=0;
2070   _init_vars = nullptr;
2071 
2072 #ifndef PRODUCT
2073   // If we are doing a detailed trace, include the regular trace information.
2074   if (TraceNewOopMapGenerationDetailed) {
2075     TraceNewOopMapGeneration = true;
2076   }
2077 #endif
2078 }
2079 
2080 bool GenerateOopMap::compute_map(Thread* current) {
2081 #ifndef PRODUCT
2082   if (TimeOopMap2) {
2083     method()->print_short_name(tty);
2084     tty->print("  ");
2085   }
2086   if (TimeOopMap) {
2087     _total_byte_count += method()->code_size();
2088   }
2089 #endif
2090   TraceTime t_single("oopmap time", TimeOopMap2);
2091   TraceTime t_all(nullptr, &_total_oopmap_time, TimeOopMap);
2092 
2093   // Initialize values
2094   _got_error      = false;
2095   _conflict       = false;
2096   _max_locals     = method()->max_locals();
2097   _max_stack      = method()->max_stack();
2098   _has_exceptions = (method()->has_exception_handler());
2099   _nof_refval_conflicts = 0;
2100   _init_vars      = new GrowableArray<intptr_t>(5);  // There are seldom more than 5 init_vars
2101   _report_result  = false;
2102   _report_result_for_send = false;
2103   _new_var_map    = nullptr;
2104   _ret_adr_tos    = new GrowableArray<int>(5);  // 5 seems like a good number;
2105   _did_rewriting  = false;
2106   _did_relocation = false;
2107 
2108   if (TraceNewOopMapGeneration) {
2109     tty->print("Method name: %s\n", method()->name()->as_C_string());
2110     if (Verbose) {
2111       _method->print_codes();
2112       tty->print_cr("Exception table:");
2113       ExceptionTable excps(method());
2114       for(int i = 0; i < excps.length(); i ++) {
2115         tty->print_cr("[%d - %d] -> %d",
2116                       excps.start_pc(i), excps.end_pc(i), excps.handler_pc(i));
2117       }
2118     }
2119   }
2120 
2121   // if no code - do nothing
2122   // compiler needs info
2123   if (method()->code_size() == 0 || _max_locals + method()->max_stack() == 0) {
2124     fill_stackmap_prolog(0);
2125     fill_stackmap_epilog();
2126     return true;
2127   }
2128   // Step 1: Compute all jump targets and their return value
2129   if (!_got_error)
2130     _rt.compute_ret_table(_method);
2131 
2132   // Step 2: Find all basic blocks and count GC points
2133   if (!_got_error)
2134     mark_bbheaders_and_count_gc_points();
2135 
2136   // Step 3: Calculate stack maps
2137   if (!_got_error)
2138     do_interpretation();
2139 
2140   // Step 4:Return results
2141   if (!_got_error && report_results())
2142      report_result();
2143 
2144   return !_got_error;
2145 }
2146 
2147 // Error handling methods
2148 //
2149 // If we compute from a suitable JavaThread then we create an exception for the GenerateOopMap
2150 // calling code to retrieve (via exception()) and throw if desired (in most cases errors are ignored).
2151 // Otherwise it is considered a fatal error to hit malformed bytecode.
2152 void GenerateOopMap::error_work(const char *format, va_list ap) {
2153   _got_error = true;
2154   char msg_buffer[512];
2155   os::vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
2156   // Append method name
2157   char msg_buffer2[512];
2158   os::snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
2159   Thread* current = Thread::current();
2160   if (current->can_call_java()) {
2161     _exception = Exceptions::new_exception(JavaThread::cast(current),
2162                                            vmSymbols::java_lang_LinkageError(),
2163                                            msg_buffer2);
2164   } else {
2165     fatal("%s", msg_buffer2);
2166   }
2167 }
2168 
2169 void GenerateOopMap::report_error(const char *format, ...) {
2170   va_list ap;
2171   va_start(ap, format);
2172   error_work(format, ap);
2173 }
2174 
2175 void GenerateOopMap::verify_error(const char *format, ...) {
2176   // We do not distinguish between different types of errors for verification
2177   // errors.  Let the verifier give a better message.
2178   report_error("Illegal class file encountered. Try running with -Xverify:all");
2179 }
2180 
2181 //
2182 // Report result opcodes
2183 //
2184 void GenerateOopMap::report_result() {
2185 
2186   if (TraceNewOopMapGeneration) tty->print_cr("Report result pass");
2187 
2188   // We now want to report the result of the parse
2189   _report_result = true;
2190 
2191   // Prolog code
2192   fill_stackmap_prolog(_gc_points);
2193 
2194    // Mark everything changed, then do one interpretation pass.
2195   for (int i = 0; i<_bb_count; i++) {
2196     if (_basic_blocks[i].is_reachable()) {
2197       _basic_blocks[i].set_changed(true);
2198       interp_bb(&_basic_blocks[i]);
2199     }
2200   }
2201 
2202   // Note: Since we are skipping dead-code when we are reporting results, then
2203   // the no. of encountered gc-points might be fewer than the previously number
2204   // we have counted. (dead-code is a pain - it should be removed before we get here)
2205   fill_stackmap_epilog();
2206 
2207   // Report initvars
2208   fill_init_vars(_init_vars);
2209 
2210   _report_result = false;
2211 }
2212 
2213 void GenerateOopMap::result_for_basicblock(int bci) {
2214  if (TraceNewOopMapGeneration) tty->print_cr("Report result pass for basicblock");
2215 
2216   // We now want to report the result of the parse
2217   _report_result = true;
2218 
2219   // Find basicblock and report results
2220   BasicBlock* bb = get_basic_block_containing(bci);
2221   guarantee(bb != nullptr, "no basic block for bci");
2222   assert(bb->is_reachable(), "getting result from unreachable basicblock");
2223   bb->set_changed(true);
2224   interp_bb(bb);
2225 }
2226 
2227 //
2228 // Conflict handling code
2229 //
2230 
2231 void GenerateOopMap::record_refval_conflict(int varNo) {
2232   assert(varNo>=0 && varNo< _max_locals, "index out of range");
2233 
2234   if (TraceOopMapRewrites) {
2235      tty->print("### Conflict detected (local no: %d)\n", varNo);
2236   }
2237 
2238   if (!_new_var_map) {
2239     _new_var_map = NEW_RESOURCE_ARRAY(int, _max_locals);
2240     for (int k = 0; k < _max_locals; k++)  _new_var_map[k] = k;
2241   }
2242 
2243   if ( _new_var_map[varNo] == varNo) {
2244     // Check if max. number of locals has been reached
2245     if (_max_locals + _nof_refval_conflicts >= MAX_LOCAL_VARS) {
2246       report_error("Rewriting exceeded local variable limit");
2247       return;
2248     }
2249     _new_var_map[varNo] = _max_locals + _nof_refval_conflicts;
2250     _nof_refval_conflicts++;
2251   }
2252 }
2253 
2254 void GenerateOopMap::rewrite_refval_conflicts()
2255 {
2256   // We can get here two ways: Either a rewrite conflict was detected, or
2257   // an uninitialize reference was detected. In the second case, we do not
2258   // do any rewriting, we just want to recompute the reference set with the
2259   // new information
2260 
2261   int nof_conflicts = 0;              // Used for debugging only
2262 
2263   if ( _nof_refval_conflicts == 0 )
2264      return;
2265 
2266   // Check if rewrites are allowed in this parse.
2267   if (!allow_rewrites()) {
2268     fatal("Rewriting method not allowed at this stage");
2269   }
2270 
2271 
2272   // Tracing flag
2273   _did_rewriting = true;
2274 
2275   if (TraceOopMapRewrites) {
2276     tty->print_cr("ref/value conflict for method %s - bytecodes are getting rewritten", method()->name()->as_C_string());
2277     method()->print();
2278     method()->print_codes();
2279   }
2280 
2281   assert(_new_var_map!=nullptr, "nothing to rewrite");
2282   assert(_conflict==true, "We should not be here");
2283 
2284   compute_ret_adr_at_TOS();
2285   if (!_got_error) {
2286     for (int k = 0; k < _max_locals && !_got_error; k++) {
2287       if (_new_var_map[k] != k) {
2288         if (TraceOopMapRewrites) {
2289           tty->print_cr("Rewriting: %d -> %d", k, _new_var_map[k]);
2290         }
2291         rewrite_refval_conflict(k, _new_var_map[k]);
2292         if (_got_error) return;
2293         nof_conflicts++;
2294       }
2295     }
2296   }
2297 
2298   assert(nof_conflicts == _nof_refval_conflicts, "sanity check");
2299 
2300   // Adjust the number of locals
2301   method()->set_max_locals(_max_locals+_nof_refval_conflicts);
2302   _max_locals += _nof_refval_conflicts;
2303 
2304   // That was that...
2305   _new_var_map = nullptr;
2306   _nof_refval_conflicts = 0;
2307 }
2308 
2309 void GenerateOopMap::rewrite_refval_conflict(int from, int to) {
2310   bool startOver;
2311   do {
2312     // Make sure that the BytecodeStream is constructed in the loop, since
2313     // during rewriting a new method is going to be used, and the next time
2314     // around we want to use that.
2315     BytecodeStream bcs(_method);
2316     startOver = false;
2317 
2318     while( !startOver && !_got_error &&
2319            // test bcs in case method changed and it became invalid
2320            bcs.next() >=0) {
2321       startOver = rewrite_refval_conflict_inst(&bcs, from, to);
2322     }
2323   } while (startOver && !_got_error);
2324 }
2325 
2326 /* If the current instruction is one that uses local variable "from"
2327    in a ref way, change it to use "to". There's a subtle reason why we
2328    renumber the ref uses and not the non-ref uses: non-ref uses may be
2329    2 slots wide (double, long) which would necessitate keeping track of
2330    whether we should add one or two variables to the method. If the change
2331    affected the width of some instruction, returns "TRUE"; otherwise, returns "FALSE".
2332    Another reason for moving ref's value is for solving (addr, ref) conflicts, which
2333    both uses aload/astore methods.
2334 */
2335 bool GenerateOopMap::rewrite_refval_conflict_inst(BytecodeStream *itr, int from, int to) {
2336   Bytecodes::Code bc = itr->code();
2337   int index;
2338   int bci = itr->bci();
2339 
2340   if (is_aload(itr, &index) && index == from) {
2341     if (TraceOopMapRewrites) {
2342       tty->print_cr("Rewriting aload at bci: %d", bci);
2343     }
2344     return rewrite_load_or_store(itr, Bytecodes::_aload, Bytecodes::_aload_0, to);
2345   }
2346 
2347   if (is_astore(itr, &index) && index == from) {
2348     if (!stack_top_holds_ret_addr(bci)) {
2349       if (TraceOopMapRewrites) {
2350         tty->print_cr("Rewriting astore at bci: %d", bci);
2351       }
2352       return rewrite_load_or_store(itr, Bytecodes::_astore, Bytecodes::_astore_0, to);
2353     } else {
2354       if (TraceOopMapRewrites) {
2355         tty->print_cr("Suppress rewriting of astore at bci: %d", bci);
2356       }
2357     }
2358   }
2359 
2360   return false;
2361 }
2362 
2363 // The argument to this method is:
2364 // bc : Current bytecode
2365 // bcN : either _aload or _astore
2366 // bc0 : either _aload_0 or _astore_0
2367 bool GenerateOopMap::rewrite_load_or_store(BytecodeStream *bcs, Bytecodes::Code bcN, Bytecodes::Code bc0, unsigned int varNo) {
2368   assert(bcN == Bytecodes::_astore   || bcN == Bytecodes::_aload,   "wrong argument (bcN)");
2369   assert(bc0 == Bytecodes::_astore_0 || bc0 == Bytecodes::_aload_0, "wrong argument (bc0)");
2370   int ilen = Bytecodes::length_at(_method(), bcs->bcp());
2371   int newIlen;
2372 
2373   if (ilen == 4) {
2374     // Original instruction was wide; keep it wide for simplicity
2375     newIlen = 4;
2376   } else if (varNo < 4)
2377      newIlen = 1;
2378   else if (varNo >= 256)
2379      newIlen = 4;
2380   else
2381      newIlen = 2;
2382 
2383   // If we need to relocate in order to patch the byte, we
2384   // do the patching in a temp. buffer, that is passed to the reloc.
2385   // The patching of the bytecode stream is then done by the Relocator.
2386   // This is necessary, since relocating the instruction at a certain bci, might
2387   // also relocate that instruction, e.g., if a _goto before it gets widen to a _goto_w.
2388   // Hence, we do not know which bci to patch after relocation.
2389 
2390   assert(newIlen <= 4, "sanity check");
2391   u_char inst_buffer[4]; // Max. instruction size is 4.
2392   address bcp;
2393 
2394   if (newIlen != ilen) {
2395     // Relocation needed do patching in temp. buffer
2396     bcp = (address)inst_buffer;
2397   } else {
2398     bcp = _method->bcp_from(bcs->bci());
2399   }
2400 
2401   // Patch either directly in Method* or in temp. buffer
2402   if (newIlen == 1) {
2403     assert(varNo < 4, "varNo too large");
2404     *bcp = (u1)(bc0 + varNo);
2405   } else if (newIlen == 2) {
2406     assert(varNo < 256, "2-byte index needed!");
2407     *(bcp + 0) = bcN;
2408     *(bcp + 1) = (u1)varNo;
2409   } else {
2410     assert(newIlen == 4, "Wrong instruction length");
2411     *(bcp + 0) = Bytecodes::_wide;
2412     *(bcp + 1) = bcN;
2413     Bytes::put_Java_u2(bcp+2, (u2)varNo);
2414   }
2415 
2416   if (newIlen != ilen) {
2417     expand_current_instr(bcs->bci(), ilen, newIlen, inst_buffer);
2418   }
2419 
2420 
2421   return (newIlen != ilen);
2422 }
2423 
2424 class RelocCallback : public RelocatorListener {
2425  private:
2426   GenerateOopMap* _gom;
2427  public:
2428    RelocCallback(GenerateOopMap* gom) { _gom = gom; };
2429 
2430   // Callback method
2431   virtual void relocated(int bci, int delta, int new_code_length) {
2432     _gom->update_basic_blocks  (bci, delta, new_code_length);
2433     _gom->update_ret_adr_at_TOS(bci, delta);
2434     _gom->_rt.update_ret_table (bci, delta);
2435   }
2436 };
2437 
2438 // Returns true if expanding was successful. Otherwise, reports an error and
2439 // returns false.
2440 void GenerateOopMap::expand_current_instr(int bci, int ilen, int newIlen, u_char inst_buffer[]) {
2441   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2442   RelocCallback rcb(this);
2443   Relocator rc(_method, &rcb);
2444   methodHandle m= rc.insert_space_at(bci, newIlen, inst_buffer, THREAD);
2445   if (m.is_null() || HAS_PENDING_EXCEPTION) {
2446     report_error("could not rewrite method - exception occurred or bytecode buffer overflow");
2447     return;
2448   }
2449 
2450   // Relocator returns a new method.
2451   _did_relocation = true;
2452   _method = m;
2453 }
2454 
2455 
2456 bool GenerateOopMap::is_astore(BytecodeStream *itr, int *index) {
2457   Bytecodes::Code bc = itr->code();
2458   switch(bc) {
2459     case Bytecodes::_astore_0:
2460     case Bytecodes::_astore_1:
2461     case Bytecodes::_astore_2:
2462     case Bytecodes::_astore_3:
2463       *index = bc - Bytecodes::_astore_0;
2464       return true;
2465     case Bytecodes::_astore:
2466       *index = itr->get_index();
2467       return true;
2468     default:
2469       return false;
2470   }
2471 }
2472 
2473 bool GenerateOopMap::is_aload(BytecodeStream *itr, int *index) {
2474   Bytecodes::Code bc = itr->code();
2475   switch(bc) {
2476     case Bytecodes::_aload_0:
2477     case Bytecodes::_aload_1:
2478     case Bytecodes::_aload_2:
2479     case Bytecodes::_aload_3:
2480       *index = bc - Bytecodes::_aload_0;
2481       return true;
2482 
2483     case Bytecodes::_aload:
2484       *index = itr->get_index();
2485       return true;
2486 
2487     default:
2488       return false;
2489   }
2490 }
2491 
2492 
2493 // Return true iff the top of the operand stack holds a return address at
2494 // the current instruction
2495 bool GenerateOopMap::stack_top_holds_ret_addr(int bci) {
2496   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2497     if (_ret_adr_tos->at(i) == bci)
2498       return true;
2499   }
2500 
2501   return false;
2502 }
2503 
2504 void GenerateOopMap::compute_ret_adr_at_TOS() {
2505   assert(_ret_adr_tos != nullptr, "must be initialized");
2506   _ret_adr_tos->clear();
2507 
2508   for (int i = 0; i < bb_count(); i++) {
2509     BasicBlock* bb = &_basic_blocks[i];
2510 
2511     // Make sure to only check basicblocks that are reachable
2512     if (bb->is_reachable()) {
2513 
2514       // For each Basic block we check all instructions
2515       BytecodeStream bcs(_method);
2516       bcs.set_interval(bb->_bci, next_bb_start_pc(bb));
2517 
2518       restore_state(bb);
2519 
2520       while (bcs.next()>=0 && !_got_error) {
2521         // TDT: should this be is_good_address() ?
2522         if (_stack_top > 0 && stack()[_stack_top-1].is_address()) {
2523           _ret_adr_tos->append(bcs.bci());
2524           if (TraceNewOopMapGeneration) {
2525             tty->print_cr("Ret_adr TOS at bci: %d", bcs.bci());
2526           }
2527         }
2528         interp1(&bcs);
2529       }
2530     }
2531   }
2532 }
2533 
2534 void GenerateOopMap::update_ret_adr_at_TOS(int bci, int delta) {
2535   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2536     int v = _ret_adr_tos->at(i);
2537     if (v > bci)  _ret_adr_tos->at_put(i, v + delta);
2538   }
2539 }
2540 
2541 // ===================================================================
2542 
2543 #ifndef PRODUCT
2544 int ResolveOopMapConflicts::_nof_invocations  = 0;
2545 int ResolveOopMapConflicts::_nof_rewrites     = 0;
2546 int ResolveOopMapConflicts::_nof_relocations  = 0;
2547 #endif
2548 
2549 methodHandle ResolveOopMapConflicts::do_potential_rewrite(TRAPS) {
2550   if (!compute_map(THREAD)) {
2551     THROW_HANDLE_(exception(), methodHandle());
2552   }
2553 
2554 #ifndef PRODUCT
2555   // Tracking and statistics
2556   if (PrintRewrites) {
2557     _nof_invocations++;
2558     if (did_rewriting()) {
2559       _nof_rewrites++;
2560       if (did_relocation()) _nof_relocations++;
2561       tty->print("Method was rewritten %s: ", (did_relocation()) ? "and relocated" : "");
2562       method()->print_value(); tty->cr();
2563       tty->print_cr("Cand.: %d rewrts: %d (%d%%) reloc.: %d (%d%%)",
2564           _nof_invocations,
2565           _nof_rewrites,    (_nof_rewrites    * 100) / _nof_invocations,
2566           _nof_relocations, (_nof_relocations * 100) / _nof_invocations);
2567     }
2568   }
2569 #endif
2570   return methodHandle(THREAD, method());
2571 }