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