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