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