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