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