1 /*
   2  * Copyright (c) 1999, 2021, 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 "c1/c1_CFGPrinter.hpp"
  27 #include "c1/c1_Canonicalizer.hpp"
  28 #include "c1/c1_Compilation.hpp"
  29 #include "c1/c1_GraphBuilder.hpp"
  30 #include "c1/c1_InstructionPrinter.hpp"
  31 #include "ci/ciCallSite.hpp"
  32 #include "ci/ciField.hpp"
  33 #include "ci/ciKlass.hpp"
  34 #include "ci/ciMemberName.hpp"
  35 #include "ci/ciSymbols.hpp"
  36 #include "ci/ciUtilities.inline.hpp"
  37 #include "compiler/compilationPolicy.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/compilerEvent.hpp"
  40 #include "interpreter/bytecode.hpp"
  41 #include "jfr/jfrEvents.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/vm_version.hpp"
  46 #include "utilities/bitMap.inline.hpp"
  47 #include "utilities/powerOfTwo.hpp"
  48 
  49 class BlockListBuilder {
  50  private:
  51   Compilation* _compilation;
  52   IRScope*     _scope;
  53 
  54   BlockList    _blocks;                // internal list of all blocks
  55   BlockList*   _bci2block;             // mapping from bci to blocks for GraphBuilder
  56   GrowableArray<BlockList> _bci2block_successors; // Mapping bcis to their blocks successors while we dont have a blockend
  57 
  58   // fields used by mark_loops
  59   ResourceBitMap _active;              // for iteration of control flow graph
  60   ResourceBitMap _visited;             // for iteration of control flow graph
  61   intArray       _loop_map;            // caches the information if a block is contained in a loop
  62   int            _next_loop_index;     // next free loop number
  63   int            _next_block_number;   // for reverse postorder numbering of blocks
  64 
  65   // accessors
  66   Compilation*  compilation() const              { return _compilation; }
  67   IRScope*      scope() const                    { return _scope; }
  68   ciMethod*     method() const                   { return scope()->method(); }
  69   XHandlers*    xhandlers() const                { return scope()->xhandlers(); }
  70 
  71   // unified bailout support
  72   void          bailout(const char* msg) const   { compilation()->bailout(msg); }
  73   bool          bailed_out() const               { return compilation()->bailed_out(); }
  74 
  75   // helper functions
  76   BlockBegin* make_block_at(int bci, BlockBegin* predecessor);
  77   void handle_exceptions(BlockBegin* current, int cur_bci);
  78   void handle_jsr(BlockBegin* current, int sr_bci, int next_bci);
  79   void store_one(BlockBegin* current, int local);
  80   void store_two(BlockBegin* current, int local);
  81   void set_entries(int osr_bci);
  82   void set_leaders();
  83 
  84   void make_loop_header(BlockBegin* block);
  85   void mark_loops();
  86   int  mark_loops(BlockBegin* b, bool in_subroutine);
  87 
  88   // debugging
  89 #ifndef PRODUCT
  90   void print();
  91 #endif
  92 
  93   int number_of_successors(BlockBegin* block);
  94   BlockBegin* successor_at(BlockBegin* block, int i);
  95   void add_successor(BlockBegin* block, BlockBegin* sux);
  96   bool is_successor(BlockBegin* block, BlockBegin* sux);
  97 
  98  public:
  99   // creation
 100   BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci);
 101 
 102   // accessors for GraphBuilder
 103   BlockList*    bci2block() const                { return _bci2block; }
 104 };
 105 
 106 
 107 // Implementation of BlockListBuilder
 108 
 109 BlockListBuilder::BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci)
 110  : _compilation(compilation)
 111  , _scope(scope)
 112  , _blocks(16)
 113  , _bci2block(new BlockList(scope->method()->code_size(), NULL))
 114  , _bci2block_successors(scope->method()->code_size())
 115  , _active()         // size not known yet
 116  , _visited()        // size not known yet
 117  , _loop_map() // size not known yet
 118  , _next_loop_index(0)
 119  , _next_block_number(0)
 120 {
 121   set_entries(osr_bci);
 122   set_leaders();
 123   CHECK_BAILOUT();
 124 
 125   mark_loops();
 126   NOT_PRODUCT(if (PrintInitialBlockList) print());
 127 
 128   // _bci2block still contains blocks with _end == null and > 0 sux in _bci2block_successors.
 129 
 130 #ifndef PRODUCT
 131   if (PrintCFGToFile) {
 132     stringStream title;
 133     title.print("BlockListBuilder ");
 134     scope->method()->print_name(&title);
 135     CFGPrinter::print_cfg(_bci2block, title.as_string(), false, false);
 136   }
 137 #endif
 138 }
 139 
 140 
 141 void BlockListBuilder::set_entries(int osr_bci) {
 142   // generate start blocks
 143   BlockBegin* std_entry = make_block_at(0, NULL);
 144   if (scope()->caller() == NULL) {
 145     std_entry->set(BlockBegin::std_entry_flag);
 146   }
 147   if (osr_bci != -1) {
 148     BlockBegin* osr_entry = make_block_at(osr_bci, NULL);
 149     osr_entry->set(BlockBegin::osr_entry_flag);
 150   }
 151 
 152   // generate exception entry blocks
 153   XHandlers* list = xhandlers();
 154   const int n = list->length();
 155   for (int i = 0; i < n; i++) {
 156     XHandler* h = list->handler_at(i);
 157     BlockBegin* entry = make_block_at(h->handler_bci(), NULL);
 158     entry->set(BlockBegin::exception_entry_flag);
 159     h->set_entry_block(entry);
 160   }
 161 }
 162 
 163 
 164 BlockBegin* BlockListBuilder::make_block_at(int cur_bci, BlockBegin* predecessor) {
 165   assert(method()->bci_block_start().at(cur_bci), "wrong block starts of MethodLivenessAnalyzer");
 166 
 167   BlockBegin* block = _bci2block->at(cur_bci);
 168   if (block == NULL) {
 169     block = new BlockBegin(cur_bci);
 170     block->init_stores_to_locals(method()->max_locals());
 171     _bci2block->at_put(cur_bci, block);
 172     _bci2block_successors.at_put_grow(cur_bci, BlockList());
 173     _blocks.append(block);
 174 
 175     assert(predecessor == NULL || predecessor->bci() < cur_bci, "targets for backward branches must already exist");
 176   }
 177 
 178   if (predecessor != NULL) {
 179     if (block->is_set(BlockBegin::exception_entry_flag)) {
 180       BAILOUT_("Exception handler can be reached by both normal and exceptional control flow", block);
 181     }
 182 
 183     add_successor(predecessor, block);
 184     block->increment_total_preds();
 185   }
 186 
 187   return block;
 188 }
 189 
 190 
 191 inline void BlockListBuilder::store_one(BlockBegin* current, int local) {
 192   current->stores_to_locals().set_bit(local);
 193 }
 194 inline void BlockListBuilder::store_two(BlockBegin* current, int local) {
 195   store_one(current, local);
 196   store_one(current, local + 1);
 197 }
 198 
 199 
 200 void BlockListBuilder::handle_exceptions(BlockBegin* current, int cur_bci) {
 201   // Draws edges from a block to its exception handlers
 202   XHandlers* list = xhandlers();
 203   const int n = list->length();
 204 
 205   for (int i = 0; i < n; i++) {
 206     XHandler* h = list->handler_at(i);
 207 
 208     if (h->covers(cur_bci)) {
 209       BlockBegin* entry = h->entry_block();
 210       assert(entry != NULL && entry == _bci2block->at(h->handler_bci()), "entry must be set");
 211       assert(entry->is_set(BlockBegin::exception_entry_flag), "flag must be set");
 212 
 213       // add each exception handler only once
 214       if(!is_successor(current, entry)) {
 215         add_successor(current, entry);
 216         entry->increment_total_preds();
 217       }
 218 
 219       // stop when reaching catchall
 220       if (h->catch_type() == 0) break;
 221     }
 222   }
 223 }
 224 
 225 void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) {
 226   // start a new block after jsr-bytecode and link this block into cfg
 227   make_block_at(next_bci, current);
 228 
 229   // start a new block at the subroutine entry at mark it with special flag
 230   BlockBegin* sr_block = make_block_at(sr_bci, current);
 231   if (!sr_block->is_set(BlockBegin::subroutine_entry_flag)) {
 232     sr_block->set(BlockBegin::subroutine_entry_flag);
 233   }
 234 }
 235 
 236 
 237 void BlockListBuilder::set_leaders() {
 238   bool has_xhandlers = xhandlers()->has_handlers();
 239   BlockBegin* current = NULL;
 240 
 241   // The information which bci starts a new block simplifies the analysis
 242   // Without it, backward branches could jump to a bci where no block was created
 243   // during bytecode iteration. This would require the creation of a new block at the
 244   // branch target and a modification of the successor lists.
 245   const BitMap& bci_block_start = method()->bci_block_start();
 246 
 247   ciBytecodeStream s(method());
 248   while (s.next() != ciBytecodeStream::EOBC()) {
 249     int cur_bci = s.cur_bci();
 250 
 251     if (bci_block_start.at(cur_bci)) {
 252       current = make_block_at(cur_bci, current);
 253     }
 254     assert(current != NULL, "must have current block");
 255 
 256     if (has_xhandlers && GraphBuilder::can_trap(method(), s.cur_bc())) {
 257       handle_exceptions(current, cur_bci);
 258     }
 259 
 260     switch (s.cur_bc()) {
 261       // track stores to local variables for selective creation of phi functions
 262       case Bytecodes::_iinc:     store_one(current, s.get_index()); break;
 263       case Bytecodes::_istore:   store_one(current, s.get_index()); break;
 264       case Bytecodes::_lstore:   store_two(current, s.get_index()); break;
 265       case Bytecodes::_fstore:   store_one(current, s.get_index()); break;
 266       case Bytecodes::_dstore:   store_two(current, s.get_index()); break;
 267       case Bytecodes::_astore:   store_one(current, s.get_index()); break;
 268       case Bytecodes::_istore_0: store_one(current, 0); break;
 269       case Bytecodes::_istore_1: store_one(current, 1); break;
 270       case Bytecodes::_istore_2: store_one(current, 2); break;
 271       case Bytecodes::_istore_3: store_one(current, 3); break;
 272       case Bytecodes::_lstore_0: store_two(current, 0); break;
 273       case Bytecodes::_lstore_1: store_two(current, 1); break;
 274       case Bytecodes::_lstore_2: store_two(current, 2); break;
 275       case Bytecodes::_lstore_3: store_two(current, 3); break;
 276       case Bytecodes::_fstore_0: store_one(current, 0); break;
 277       case Bytecodes::_fstore_1: store_one(current, 1); break;
 278       case Bytecodes::_fstore_2: store_one(current, 2); break;
 279       case Bytecodes::_fstore_3: store_one(current, 3); break;
 280       case Bytecodes::_dstore_0: store_two(current, 0); break;
 281       case Bytecodes::_dstore_1: store_two(current, 1); break;
 282       case Bytecodes::_dstore_2: store_two(current, 2); break;
 283       case Bytecodes::_dstore_3: store_two(current, 3); break;
 284       case Bytecodes::_astore_0: store_one(current, 0); break;
 285       case Bytecodes::_astore_1: store_one(current, 1); break;
 286       case Bytecodes::_astore_2: store_one(current, 2); break;
 287       case Bytecodes::_astore_3: store_one(current, 3); break;
 288 
 289       // track bytecodes that affect the control flow
 290       case Bytecodes::_athrow:  // fall through
 291       case Bytecodes::_ret:     // fall through
 292       case Bytecodes::_ireturn: // fall through
 293       case Bytecodes::_lreturn: // fall through
 294       case Bytecodes::_freturn: // fall through
 295       case Bytecodes::_dreturn: // fall through
 296       case Bytecodes::_areturn: // fall through
 297       case Bytecodes::_return:
 298         current = NULL;
 299         break;
 300 
 301       case Bytecodes::_ifeq:      // fall through
 302       case Bytecodes::_ifne:      // fall through
 303       case Bytecodes::_iflt:      // fall through
 304       case Bytecodes::_ifge:      // fall through
 305       case Bytecodes::_ifgt:      // fall through
 306       case Bytecodes::_ifle:      // fall through
 307       case Bytecodes::_if_icmpeq: // fall through
 308       case Bytecodes::_if_icmpne: // fall through
 309       case Bytecodes::_if_icmplt: // fall through
 310       case Bytecodes::_if_icmpge: // fall through
 311       case Bytecodes::_if_icmpgt: // fall through
 312       case Bytecodes::_if_icmple: // fall through
 313       case Bytecodes::_if_acmpeq: // fall through
 314       case Bytecodes::_if_acmpne: // fall through
 315       case Bytecodes::_ifnull:    // fall through
 316       case Bytecodes::_ifnonnull:
 317         make_block_at(s.next_bci(), current);
 318         make_block_at(s.get_dest(), current);
 319         current = NULL;
 320         break;
 321 
 322       case Bytecodes::_goto:
 323         make_block_at(s.get_dest(), current);
 324         current = NULL;
 325         break;
 326 
 327       case Bytecodes::_goto_w:
 328         make_block_at(s.get_far_dest(), current);
 329         current = NULL;
 330         break;
 331 
 332       case Bytecodes::_jsr:
 333         handle_jsr(current, s.get_dest(), s.next_bci());
 334         current = NULL;
 335         break;
 336 
 337       case Bytecodes::_jsr_w:
 338         handle_jsr(current, s.get_far_dest(), s.next_bci());
 339         current = NULL;
 340         break;
 341 
 342       case Bytecodes::_tableswitch: {
 343         // set block for each case
 344         Bytecode_tableswitch sw(&s);
 345         int l = sw.length();
 346         for (int i = 0; i < l; i++) {
 347           make_block_at(cur_bci + sw.dest_offset_at(i), current);
 348         }
 349         make_block_at(cur_bci + sw.default_offset(), current);
 350         current = NULL;
 351         break;
 352       }
 353 
 354       case Bytecodes::_lookupswitch: {
 355         // set block for each case
 356         Bytecode_lookupswitch sw(&s);
 357         int l = sw.number_of_pairs();
 358         for (int i = 0; i < l; i++) {
 359           make_block_at(cur_bci + sw.pair_at(i).offset(), current);
 360         }
 361         make_block_at(cur_bci + sw.default_offset(), current);
 362         current = NULL;
 363         break;
 364       }
 365 
 366       default:
 367         break;
 368     }
 369   }
 370 }
 371 
 372 
 373 void BlockListBuilder::mark_loops() {
 374   ResourceMark rm;
 375 
 376   _active.initialize(BlockBegin::number_of_blocks());
 377   _visited.initialize(BlockBegin::number_of_blocks());
 378   _loop_map = intArray(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), 0);
 379   _next_loop_index = 0;
 380   _next_block_number = _blocks.length();
 381 
 382   // recursively iterate the control flow graph
 383   mark_loops(_bci2block->at(0), false);
 384   assert(_next_block_number >= 0, "invalid block numbers");
 385 
 386   // Remove dangling Resource pointers before the ResourceMark goes out-of-scope.
 387   _active.resize(0);
 388   _visited.resize(0);
 389 }
 390 
 391 void BlockListBuilder::make_loop_header(BlockBegin* block) {
 392   if (block->is_set(BlockBegin::exception_entry_flag)) {
 393     // exception edges may look like loops but don't mark them as such
 394     // since it screws up block ordering.
 395     return;
 396   }
 397   if (!block->is_set(BlockBegin::parser_loop_header_flag)) {
 398     block->set(BlockBegin::parser_loop_header_flag);
 399 
 400     assert(_loop_map.at(block->block_id()) == 0, "must not be set yet");
 401     assert(0 <= _next_loop_index && _next_loop_index < BitsPerInt, "_next_loop_index is used as a bit-index in integer");
 402     _loop_map.at_put(block->block_id(), 1 << _next_loop_index);
 403     if (_next_loop_index < 31) _next_loop_index++;
 404   } else {
 405     // block already marked as loop header
 406     assert(is_power_of_2((unsigned int)_loop_map.at(block->block_id())), "exactly one bit must be set");
 407   }
 408 }
 409 
 410 int BlockListBuilder::mark_loops(BlockBegin* block, bool in_subroutine) {
 411   int block_id = block->block_id();
 412 
 413   if (_visited.at(block_id)) {
 414     if (_active.at(block_id)) {
 415       // reached block via backward branch
 416       make_loop_header(block);
 417     }
 418     // return cached loop information for this block
 419     return _loop_map.at(block_id);
 420   }
 421 
 422   if (block->is_set(BlockBegin::subroutine_entry_flag)) {
 423     in_subroutine = true;
 424   }
 425 
 426   // set active and visited bits before successors are processed
 427   _visited.set_bit(block_id);
 428   _active.set_bit(block_id);
 429 
 430   intptr_t loop_state = 0;
 431   for (int i = number_of_successors(block) - 1; i >= 0; i--) {
 432     // recursively process all successors
 433     loop_state |= mark_loops(successor_at(block, i), in_subroutine);
 434   }
 435 
 436   // clear active-bit after all successors are processed
 437   _active.clear_bit(block_id);
 438 
 439   // reverse-post-order numbering of all blocks
 440   block->set_depth_first_number(_next_block_number);
 441   _next_block_number--;
 442 
 443   if (loop_state != 0 || in_subroutine ) {
 444     // block is contained at least in one loop, so phi functions are necessary
 445     // phi functions are also necessary for all locals stored in a subroutine
 446     scope()->requires_phi_function().set_union(block->stores_to_locals());
 447   }
 448 
 449   if (block->is_set(BlockBegin::parser_loop_header_flag)) {
 450     int header_loop_state = _loop_map.at(block_id);
 451     assert(is_power_of_2((unsigned)header_loop_state), "exactly one bit must be set");
 452 
 453     // If the highest bit is set (i.e. when integer value is negative), the method
 454     // has 32 or more loops. This bit is never cleared because it is used for multiple loops
 455     if (header_loop_state >= 0) {
 456       clear_bits(loop_state, header_loop_state);
 457     }
 458   }
 459 
 460   // cache and return loop information for this block
 461   _loop_map.at_put(block_id, loop_state);
 462   return loop_state;
 463 }
 464 
 465 inline int BlockListBuilder::number_of_successors(BlockBegin* block)
 466 {
 467   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 468   return _bci2block_successors.at(block->bci()).length();
 469 }
 470 
 471 inline BlockBegin* BlockListBuilder::successor_at(BlockBegin* block, int i)
 472 {
 473   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 474   return _bci2block_successors.at(block->bci()).at(i);
 475 }
 476 
 477 inline void BlockListBuilder::add_successor(BlockBegin* block, BlockBegin* sux)
 478 {
 479   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 480   _bci2block_successors.at(block->bci()).append(sux);
 481 }
 482 
 483 inline bool BlockListBuilder::is_successor(BlockBegin* block, BlockBegin* sux) {
 484   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 485   return _bci2block_successors.at(block->bci()).contains(sux);
 486 }
 487 
 488 #ifndef PRODUCT
 489 
 490 int compare_depth_first(BlockBegin** a, BlockBegin** b) {
 491   return (*a)->depth_first_number() - (*b)->depth_first_number();
 492 }
 493 
 494 void BlockListBuilder::print() {
 495   tty->print("----- initial block list of BlockListBuilder for method ");
 496   method()->print_short_name();
 497   tty->cr();
 498 
 499   // better readability if blocks are sorted in processing order
 500   _blocks.sort(compare_depth_first);
 501 
 502   for (int i = 0; i < _blocks.length(); i++) {
 503     BlockBegin* cur = _blocks.at(i);
 504     tty->print("%4d: B%-4d bci: %-4d  preds: %-4d ", cur->depth_first_number(), cur->block_id(), cur->bci(), cur->total_preds());
 505 
 506     tty->print(cur->is_set(BlockBegin::std_entry_flag)               ? " std" : "    ");
 507     tty->print(cur->is_set(BlockBegin::osr_entry_flag)               ? " osr" : "    ");
 508     tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
 509     tty->print(cur->is_set(BlockBegin::subroutine_entry_flag)        ? " sr" : "   ");
 510     tty->print(cur->is_set(BlockBegin::parser_loop_header_flag)      ? " lh" : "   ");
 511 
 512     if (number_of_successors(cur) > 0) {
 513       tty->print("    sux: ");
 514       for (int j = 0; j < number_of_successors(cur); j++) {
 515         BlockBegin* sux = successor_at(cur, j);
 516         tty->print("B%d ", sux->block_id());
 517       }
 518     }
 519     tty->cr();
 520   }
 521 }
 522 
 523 #endif
 524 
 525 
 526 // A simple growable array of Values indexed by ciFields
 527 class FieldBuffer: public CompilationResourceObj {
 528  private:
 529   GrowableArray<Value> _values;
 530 
 531  public:
 532   FieldBuffer() {}
 533 
 534   void kill() {
 535     _values.trunc_to(0);
 536   }
 537 
 538   Value at(ciField* field) {
 539     assert(field->holder()->is_loaded(), "must be a loaded field");
 540     int offset = field->offset();
 541     if (offset < _values.length()) {
 542       return _values.at(offset);
 543     } else {
 544       return NULL;
 545     }
 546   }
 547 
 548   void at_put(ciField* field, Value value) {
 549     assert(field->holder()->is_loaded(), "must be a loaded field");
 550     int offset = field->offset();
 551     _values.at_put_grow(offset, value, NULL);
 552   }
 553 
 554 };
 555 
 556 
 557 // MemoryBuffer is fairly simple model of the current state of memory.
 558 // It partitions memory into several pieces.  The first piece is
 559 // generic memory where little is known about the owner of the memory.
 560 // This is conceptually represented by the tuple <O, F, V> which says
 561 // that the field F of object O has value V.  This is flattened so
 562 // that F is represented by the offset of the field and the parallel
 563 // arrays _objects and _values are used for O and V.  Loads of O.F can
 564 // simply use V.  Newly allocated objects are kept in a separate list
 565 // along with a parallel array for each object which represents the
 566 // current value of its fields.  Stores of the default value to fields
 567 // which have never been stored to before are eliminated since they
 568 // are redundant.  Once newly allocated objects are stored into
 569 // another object or they are passed out of the current compile they
 570 // are treated like generic memory.
 571 
 572 class MemoryBuffer: public CompilationResourceObj {
 573  private:
 574   FieldBuffer                 _values;
 575   GrowableArray<Value>        _objects;
 576   GrowableArray<Value>        _newobjects;
 577   GrowableArray<FieldBuffer*> _fields;
 578 
 579  public:
 580   MemoryBuffer() {}
 581 
 582   StoreField* store(StoreField* st) {
 583     if (!EliminateFieldAccess) {
 584       return st;
 585     }
 586 
 587     Value object = st->obj();
 588     Value value = st->value();
 589     ciField* field = st->field();
 590     if (field->holder()->is_loaded()) {
 591       int offset = field->offset();
 592       int index = _newobjects.find(object);
 593       if (index != -1) {
 594         // newly allocated object with no other stores performed on this field
 595         FieldBuffer* buf = _fields.at(index);
 596         if (buf->at(field) == NULL && is_default_value(value)) {
 597 #ifndef PRODUCT
 598           if (PrintIRDuringConstruction && Verbose) {
 599             tty->print_cr("Eliminated store for object %d:", index);
 600             st->print_line();
 601           }
 602 #endif
 603           return NULL;
 604         } else {
 605           buf->at_put(field, value);
 606         }
 607       } else {
 608         _objects.at_put_grow(offset, object, NULL);
 609         _values.at_put(field, value);
 610       }
 611 
 612       store_value(value);
 613     } else {
 614       // if we held onto field names we could alias based on names but
 615       // we don't know what's being stored to so kill it all.
 616       kill();
 617     }
 618     return st;
 619   }
 620 
 621 
 622   // return true if this value correspond to the default value of a field.
 623   bool is_default_value(Value value) {
 624     Constant* con = value->as_Constant();
 625     if (con) {
 626       switch (con->type()->tag()) {
 627         case intTag:    return con->type()->as_IntConstant()->value() == 0;
 628         case longTag:   return con->type()->as_LongConstant()->value() == 0;
 629         case floatTag:  return jint_cast(con->type()->as_FloatConstant()->value()) == 0;
 630         case doubleTag: return jlong_cast(con->type()->as_DoubleConstant()->value()) == jlong_cast(0);
 631         case objectTag: return con->type() == objectNull;
 632         default:  ShouldNotReachHere();
 633       }
 634     }
 635     return false;
 636   }
 637 
 638 
 639   // return either the actual value of a load or the load itself
 640   Value load(LoadField* load) {
 641     if (!EliminateFieldAccess) {
 642       return load;
 643     }
 644 
 645     if (strict_fp_requires_explicit_rounding && load->type()->is_float_kind()) {
 646 #ifdef IA32
 647       if (UseSSE < 2) {
 648         // can't skip load since value might get rounded as a side effect
 649         return load;
 650       }
 651 #else
 652       Unimplemented();
 653 #endif // IA32
 654     }
 655 
 656     ciField* field = load->field();
 657     Value object   = load->obj();
 658     if (field->holder()->is_loaded() && !field->is_volatile()) {
 659       int offset = field->offset();
 660       Value result = NULL;
 661       int index = _newobjects.find(object);
 662       if (index != -1) {
 663         result = _fields.at(index)->at(field);
 664       } else if (_objects.at_grow(offset, NULL) == object) {
 665         result = _values.at(field);
 666       }
 667       if (result != NULL) {
 668 #ifndef PRODUCT
 669         if (PrintIRDuringConstruction && Verbose) {
 670           tty->print_cr("Eliminated load: ");
 671           load->print_line();
 672         }
 673 #endif
 674         assert(result->type()->tag() == load->type()->tag(), "wrong types");
 675         return result;
 676       }
 677     }
 678     return load;
 679   }
 680 
 681   // Record this newly allocated object
 682   void new_instance(NewInstance* object) {
 683     int index = _newobjects.length();
 684     _newobjects.append(object);
 685     if (_fields.at_grow(index, NULL) == NULL) {
 686       _fields.at_put(index, new FieldBuffer());
 687     } else {
 688       _fields.at(index)->kill();
 689     }
 690   }
 691 
 692   void store_value(Value value) {
 693     int index = _newobjects.find(value);
 694     if (index != -1) {
 695       // stored a newly allocated object into another object.
 696       // Assume we've lost track of it as separate slice of memory.
 697       // We could do better by keeping track of whether individual
 698       // fields could alias each other.
 699       _newobjects.remove_at(index);
 700       // pull out the field info and store it at the end up the list
 701       // of field info list to be reused later.
 702       _fields.append(_fields.at(index));
 703       _fields.remove_at(index);
 704     }
 705   }
 706 
 707   void kill() {
 708     _newobjects.trunc_to(0);
 709     _objects.trunc_to(0);
 710     _values.kill();
 711   }
 712 };
 713 
 714 
 715 // Implementation of GraphBuilder's ScopeData
 716 
 717 GraphBuilder::ScopeData::ScopeData(ScopeData* parent)
 718   : _parent(parent)
 719   , _bci2block(NULL)
 720   , _scope(NULL)
 721   , _has_handler(false)
 722   , _stream(NULL)
 723   , _work_list(NULL)
 724   , _caller_stack_size(-1)
 725   , _continuation(NULL)
 726   , _parsing_jsr(false)
 727   , _jsr_xhandlers(NULL)
 728   , _num_returns(0)
 729   , _cleanup_block(NULL)
 730   , _cleanup_return_prev(NULL)
 731   , _cleanup_state(NULL)
 732   , _ignore_return(false)
 733 {
 734   if (parent != NULL) {
 735     _max_inline_size = (intx) ((float) NestedInliningSizeRatio * (float) parent->max_inline_size() / 100.0f);
 736   } else {
 737     _max_inline_size = C1MaxInlineSize;
 738   }
 739   if (_max_inline_size < C1MaxTrivialSize) {
 740     _max_inline_size = C1MaxTrivialSize;
 741   }
 742 }
 743 
 744 
 745 void GraphBuilder::kill_all() {
 746   if (UseLocalValueNumbering) {
 747     vmap()->kill_all();
 748   }
 749   _memory->kill();
 750 }
 751 
 752 
 753 BlockBegin* GraphBuilder::ScopeData::block_at(int bci) {
 754   if (parsing_jsr()) {
 755     // It is necessary to clone all blocks associated with a
 756     // subroutine, including those for exception handlers in the scope
 757     // of the method containing the jsr (because those exception
 758     // handlers may contain ret instructions in some cases).
 759     BlockBegin* block = bci2block()->at(bci);
 760     if (block != NULL && block == parent()->bci2block()->at(bci)) {
 761       BlockBegin* new_block = new BlockBegin(block->bci());
 762       if (PrintInitialBlockList) {
 763         tty->print_cr("CFG: cloned block %d (bci %d) as block %d for jsr",
 764                       block->block_id(), block->bci(), new_block->block_id());
 765       }
 766       // copy data from cloned blocked
 767       new_block->set_depth_first_number(block->depth_first_number());
 768       if (block->is_set(BlockBegin::parser_loop_header_flag)) new_block->set(BlockBegin::parser_loop_header_flag);
 769       // Preserve certain flags for assertion checking
 770       if (block->is_set(BlockBegin::subroutine_entry_flag)) new_block->set(BlockBegin::subroutine_entry_flag);
 771       if (block->is_set(BlockBegin::exception_entry_flag))  new_block->set(BlockBegin::exception_entry_flag);
 772 
 773       // copy was_visited_flag to allow early detection of bailouts
 774       // if a block that is used in a jsr has already been visited before,
 775       // it is shared between the normal control flow and a subroutine
 776       // BlockBegin::try_merge returns false when the flag is set, this leads
 777       // to a compilation bailout
 778       if (block->is_set(BlockBegin::was_visited_flag))  new_block->set(BlockBegin::was_visited_flag);
 779 
 780       bci2block()->at_put(bci, new_block);
 781       block = new_block;
 782     }
 783     return block;
 784   } else {
 785     return bci2block()->at(bci);
 786   }
 787 }
 788 
 789 
 790 XHandlers* GraphBuilder::ScopeData::xhandlers() const {
 791   if (_jsr_xhandlers == NULL) {
 792     assert(!parsing_jsr(), "");
 793     return scope()->xhandlers();
 794   }
 795   assert(parsing_jsr(), "");
 796   return _jsr_xhandlers;
 797 }
 798 
 799 
 800 void GraphBuilder::ScopeData::set_scope(IRScope* scope) {
 801   _scope = scope;
 802   bool parent_has_handler = false;
 803   if (parent() != NULL) {
 804     parent_has_handler = parent()->has_handler();
 805   }
 806   _has_handler = parent_has_handler || scope->xhandlers()->has_handlers();
 807 }
 808 
 809 
 810 void GraphBuilder::ScopeData::set_inline_cleanup_info(BlockBegin* block,
 811                                                       Instruction* return_prev,
 812                                                       ValueStack* return_state) {
 813   _cleanup_block       = block;
 814   _cleanup_return_prev = return_prev;
 815   _cleanup_state       = return_state;
 816 }
 817 
 818 
 819 void GraphBuilder::ScopeData::add_to_work_list(BlockBegin* block) {
 820   if (_work_list == NULL) {
 821     _work_list = new BlockList();
 822   }
 823 
 824   if (!block->is_set(BlockBegin::is_on_work_list_flag)) {
 825     // Do not start parsing the continuation block while in a
 826     // sub-scope
 827     if (parsing_jsr()) {
 828       if (block == jsr_continuation()) {
 829         return;
 830       }
 831     } else {
 832       if (block == continuation()) {
 833         return;
 834       }
 835     }
 836     block->set(BlockBegin::is_on_work_list_flag);
 837     _work_list->push(block);
 838 
 839     sort_top_into_worklist(_work_list, block);
 840   }
 841 }
 842 
 843 
 844 void GraphBuilder::sort_top_into_worklist(BlockList* worklist, BlockBegin* top) {
 845   assert(worklist->top() == top, "");
 846   // sort block descending into work list
 847   const int dfn = top->depth_first_number();
 848   assert(dfn != -1, "unknown depth first number");
 849   int i = worklist->length()-2;
 850   while (i >= 0) {
 851     BlockBegin* b = worklist->at(i);
 852     if (b->depth_first_number() < dfn) {
 853       worklist->at_put(i+1, b);
 854     } else {
 855       break;
 856     }
 857     i --;
 858   }
 859   if (i >= -1) worklist->at_put(i + 1, top);
 860 }
 861 
 862 
 863 BlockBegin* GraphBuilder::ScopeData::remove_from_work_list() {
 864   if (is_work_list_empty()) {
 865     return NULL;
 866   }
 867   return _work_list->pop();
 868 }
 869 
 870 
 871 bool GraphBuilder::ScopeData::is_work_list_empty() const {
 872   return (_work_list == NULL || _work_list->length() == 0);
 873 }
 874 
 875 
 876 void GraphBuilder::ScopeData::setup_jsr_xhandlers() {
 877   assert(parsing_jsr(), "");
 878   // clone all the exception handlers from the scope
 879   XHandlers* handlers = new XHandlers(scope()->xhandlers());
 880   const int n = handlers->length();
 881   for (int i = 0; i < n; i++) {
 882     // The XHandlers need to be adjusted to dispatch to the cloned
 883     // handler block instead of the default one but the synthetic
 884     // unlocker needs to be handled specially.  The synthetic unlocker
 885     // should be left alone since there can be only one and all code
 886     // should dispatch to the same one.
 887     XHandler* h = handlers->handler_at(i);
 888     assert(h->handler_bci() != SynchronizationEntryBCI, "must be real");
 889     h->set_entry_block(block_at(h->handler_bci()));
 890   }
 891   _jsr_xhandlers = handlers;
 892 }
 893 
 894 
 895 int GraphBuilder::ScopeData::num_returns() {
 896   if (parsing_jsr()) {
 897     return parent()->num_returns();
 898   }
 899   return _num_returns;
 900 }
 901 
 902 
 903 void GraphBuilder::ScopeData::incr_num_returns() {
 904   if (parsing_jsr()) {
 905     parent()->incr_num_returns();
 906   } else {
 907     ++_num_returns;
 908   }
 909 }
 910 
 911 
 912 // Implementation of GraphBuilder
 913 
 914 #define INLINE_BAILOUT(msg)        { inline_bailout(msg); return false; }
 915 
 916 
 917 void GraphBuilder::load_constant() {
 918   ciConstant con = stream()->get_constant();
 919   if (con.basic_type() == T_ILLEGAL) {
 920     // FIXME: an unresolved Dynamic constant can get here,
 921     // and that should not terminate the whole compilation.
 922     BAILOUT("could not resolve a constant");
 923   } else {
 924     ValueType* t = illegalType;
 925     ValueStack* patch_state = NULL;
 926     switch (con.basic_type()) {
 927       case T_BOOLEAN: t = new IntConstant     (con.as_boolean()); break;
 928       case T_BYTE   : t = new IntConstant     (con.as_byte   ()); break;
 929       case T_CHAR   : t = new IntConstant     (con.as_char   ()); break;
 930       case T_SHORT  : t = new IntConstant     (con.as_short  ()); break;
 931       case T_INT    : t = new IntConstant     (con.as_int    ()); break;
 932       case T_LONG   : t = new LongConstant    (con.as_long   ()); break;
 933       case T_FLOAT  : t = new FloatConstant   (con.as_float  ()); break;
 934       case T_DOUBLE : t = new DoubleConstant  (con.as_double ()); break;
 935       case T_ARRAY  : t = new ArrayConstant   (con.as_object ()->as_array   ()); break;
 936       case T_OBJECT :
 937        {
 938         ciObject* obj = con.as_object();
 939         if (!obj->is_loaded()
 940             || (PatchALot && obj->klass() != ciEnv::current()->String_klass())) {
 941           // A Class, MethodType, MethodHandle, or String.
 942           // Unloaded condy nodes show up as T_ILLEGAL, above.
 943           patch_state = copy_state_before();
 944           t = new ObjectConstant(obj);
 945         } else {
 946           // Might be a Class, MethodType, MethodHandle, or Dynamic constant
 947           // result, which might turn out to be an array.
 948           if (obj->is_null_object())
 949             t = objectNull;
 950           else if (obj->is_array())
 951             t = new ArrayConstant(obj->as_array());
 952           else
 953             t = new InstanceConstant(obj->as_instance());
 954         }
 955         break;
 956        }
 957       default       : ShouldNotReachHere();
 958     }
 959     Value x;
 960     if (patch_state != NULL) {
 961       x = new Constant(t, patch_state);
 962     } else {
 963       x = new Constant(t);
 964     }
 965     push(t, append(x));
 966   }
 967 }
 968 
 969 
 970 void GraphBuilder::load_local(ValueType* type, int index) {
 971   Value x = state()->local_at(index);
 972   assert(x != NULL && !x->type()->is_illegal(), "access of illegal local variable");
 973   push(type, x);
 974 }
 975 
 976 
 977 void GraphBuilder::store_local(ValueType* type, int index) {
 978   Value x = pop(type);
 979   store_local(state(), x, index);
 980 }
 981 
 982 
 983 void GraphBuilder::store_local(ValueStack* state, Value x, int index) {
 984   if (parsing_jsr()) {
 985     // We need to do additional tracking of the location of the return
 986     // address for jsrs since we don't handle arbitrary jsr/ret
 987     // constructs. Here we are figuring out in which circumstances we
 988     // need to bail out.
 989     if (x->type()->is_address()) {
 990       scope_data()->set_jsr_return_address_local(index);
 991 
 992       // Also check parent jsrs (if any) at this time to see whether
 993       // they are using this local. We don't handle skipping over a
 994       // ret.
 995       for (ScopeData* cur_scope_data = scope_data()->parent();
 996            cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
 997            cur_scope_data = cur_scope_data->parent()) {
 998         if (cur_scope_data->jsr_return_address_local() == index) {
 999           BAILOUT("subroutine overwrites return address from previous subroutine");
1000         }
1001       }
1002     } else if (index == scope_data()->jsr_return_address_local()) {
1003       scope_data()->set_jsr_return_address_local(-1);
1004     }
1005   }
1006 
1007   state->store_local(index, round_fp(x));
1008 }
1009 
1010 
1011 void GraphBuilder::load_indexed(BasicType type) {
1012   // In case of in block code motion in range check elimination
1013   ValueStack* state_before = copy_state_indexed_access();
1014   compilation()->set_has_access_indexed(true);
1015   Value index = ipop();
1016   Value array = apop();
1017   Value length = NULL;
1018   if (CSEArrayLength ||
1019       (array->as_Constant() != NULL) ||
1020       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1021       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1022       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1023     length = append(new ArrayLength(array, state_before));
1024   }
1025   push(as_ValueType(type), append(new LoadIndexed(array, index, length, type, state_before)));
1026 }
1027 
1028 
1029 void GraphBuilder::store_indexed(BasicType type) {
1030   // In case of in block code motion in range check elimination
1031   ValueStack* state_before = copy_state_indexed_access();
1032   compilation()->set_has_access_indexed(true);
1033   Value value = pop(as_ValueType(type));
1034   Value index = ipop();
1035   Value array = apop();
1036   Value length = NULL;
1037   if (CSEArrayLength ||
1038       (array->as_Constant() != NULL) ||
1039       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1040       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1041       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1042     length = append(new ArrayLength(array, state_before));
1043   }
1044   ciType* array_type = array->declared_type();
1045   bool check_boolean = false;
1046   if (array_type != NULL) {
1047     if (array_type->is_loaded() &&
1048       array_type->as_array_klass()->element_type()->basic_type() == T_BOOLEAN) {
1049       assert(type == T_BYTE, "boolean store uses bastore");
1050       Value mask = append(new Constant(new IntConstant(1)));
1051       value = append(new LogicOp(Bytecodes::_iand, value, mask));
1052     }
1053   } else if (type == T_BYTE) {
1054     check_boolean = true;
1055   }
1056   StoreIndexed* result = new StoreIndexed(array, index, length, type, value, state_before, check_boolean);
1057   append(result);
1058   _memory->store_value(value);
1059 
1060   if (type == T_OBJECT && is_profiling()) {
1061     // Note that we'd collect profile data in this method if we wanted it.
1062     compilation()->set_would_profile(true);
1063 
1064     if (profile_checkcasts()) {
1065       result->set_profiled_method(method());
1066       result->set_profiled_bci(bci());
1067       result->set_should_profile(true);
1068     }
1069   }
1070 }
1071 
1072 
1073 void GraphBuilder::stack_op(Bytecodes::Code code) {
1074   switch (code) {
1075     case Bytecodes::_pop:
1076       { state()->raw_pop();
1077       }
1078       break;
1079     case Bytecodes::_pop2:
1080       { state()->raw_pop();
1081         state()->raw_pop();
1082       }
1083       break;
1084     case Bytecodes::_dup:
1085       { Value w = state()->raw_pop();
1086         state()->raw_push(w);
1087         state()->raw_push(w);
1088       }
1089       break;
1090     case Bytecodes::_dup_x1:
1091       { Value w1 = state()->raw_pop();
1092         Value w2 = state()->raw_pop();
1093         state()->raw_push(w1);
1094         state()->raw_push(w2);
1095         state()->raw_push(w1);
1096       }
1097       break;
1098     case Bytecodes::_dup_x2:
1099       { Value w1 = state()->raw_pop();
1100         Value w2 = state()->raw_pop();
1101         Value w3 = state()->raw_pop();
1102         state()->raw_push(w1);
1103         state()->raw_push(w3);
1104         state()->raw_push(w2);
1105         state()->raw_push(w1);
1106       }
1107       break;
1108     case Bytecodes::_dup2:
1109       { Value w1 = state()->raw_pop();
1110         Value w2 = state()->raw_pop();
1111         state()->raw_push(w2);
1112         state()->raw_push(w1);
1113         state()->raw_push(w2);
1114         state()->raw_push(w1);
1115       }
1116       break;
1117     case Bytecodes::_dup2_x1:
1118       { Value w1 = state()->raw_pop();
1119         Value w2 = state()->raw_pop();
1120         Value w3 = state()->raw_pop();
1121         state()->raw_push(w2);
1122         state()->raw_push(w1);
1123         state()->raw_push(w3);
1124         state()->raw_push(w2);
1125         state()->raw_push(w1);
1126       }
1127       break;
1128     case Bytecodes::_dup2_x2:
1129       { Value w1 = state()->raw_pop();
1130         Value w2 = state()->raw_pop();
1131         Value w3 = state()->raw_pop();
1132         Value w4 = state()->raw_pop();
1133         state()->raw_push(w2);
1134         state()->raw_push(w1);
1135         state()->raw_push(w4);
1136         state()->raw_push(w3);
1137         state()->raw_push(w2);
1138         state()->raw_push(w1);
1139       }
1140       break;
1141     case Bytecodes::_swap:
1142       { Value w1 = state()->raw_pop();
1143         Value w2 = state()->raw_pop();
1144         state()->raw_push(w1);
1145         state()->raw_push(w2);
1146       }
1147       break;
1148     default:
1149       ShouldNotReachHere();
1150       break;
1151   }
1152 }
1153 
1154 
1155 void GraphBuilder::arithmetic_op(ValueType* type, Bytecodes::Code code, ValueStack* state_before) {
1156   Value y = pop(type);
1157   Value x = pop(type);
1158   Value res = new ArithmeticOp(code, x, y, state_before);
1159   // Note: currently single-precision floating-point rounding on Intel is handled at the LIRGenerator level
1160   res = append(res);
1161   res = round_fp(res);
1162   push(type, res);
1163 }
1164 
1165 
1166 void GraphBuilder::negate_op(ValueType* type) {
1167   push(type, append(new NegateOp(pop(type))));
1168 }
1169 
1170 
1171 void GraphBuilder::shift_op(ValueType* type, Bytecodes::Code code) {
1172   Value s = ipop();
1173   Value x = pop(type);
1174   // try to simplify
1175   // Note: This code should go into the canonicalizer as soon as it can
1176   //       can handle canonicalized forms that contain more than one node.
1177   if (CanonicalizeNodes && code == Bytecodes::_iushr) {
1178     // pattern: x >>> s
1179     IntConstant* s1 = s->type()->as_IntConstant();
1180     if (s1 != NULL) {
1181       // pattern: x >>> s1, with s1 constant
1182       ShiftOp* l = x->as_ShiftOp();
1183       if (l != NULL && l->op() == Bytecodes::_ishl) {
1184         // pattern: (a << b) >>> s1
1185         IntConstant* s0 = l->y()->type()->as_IntConstant();
1186         if (s0 != NULL) {
1187           // pattern: (a << s0) >>> s1
1188           const int s0c = s0->value() & 0x1F; // only the low 5 bits are significant for shifts
1189           const int s1c = s1->value() & 0x1F; // only the low 5 bits are significant for shifts
1190           if (s0c == s1c) {
1191             if (s0c == 0) {
1192               // pattern: (a << 0) >>> 0 => simplify to: a
1193               ipush(l->x());
1194             } else {
1195               // pattern: (a << s0c) >>> s0c => simplify to: a & m, with m constant
1196               assert(0 < s0c && s0c < BitsPerInt, "adjust code below to handle corner cases");
1197               const int m = (1 << (BitsPerInt - s0c)) - 1;
1198               Value s = append(new Constant(new IntConstant(m)));
1199               ipush(append(new LogicOp(Bytecodes::_iand, l->x(), s)));
1200             }
1201             return;
1202           }
1203         }
1204       }
1205     }
1206   }
1207   // could not simplify
1208   push(type, append(new ShiftOp(code, x, s)));
1209 }
1210 
1211 
1212 void GraphBuilder::logic_op(ValueType* type, Bytecodes::Code code) {
1213   Value y = pop(type);
1214   Value x = pop(type);
1215   push(type, append(new LogicOp(code, x, y)));
1216 }
1217 
1218 
1219 void GraphBuilder::compare_op(ValueType* type, Bytecodes::Code code) {
1220   ValueStack* state_before = copy_state_before();
1221   Value y = pop(type);
1222   Value x = pop(type);
1223   ipush(append(new CompareOp(code, x, y, state_before)));
1224 }
1225 
1226 
1227 void GraphBuilder::convert(Bytecodes::Code op, BasicType from, BasicType to) {
1228   push(as_ValueType(to), append(new Convert(op, pop(as_ValueType(from)), as_ValueType(to))));
1229 }
1230 
1231 
1232 void GraphBuilder::increment() {
1233   int index = stream()->get_index();
1234   int delta = stream()->is_wide() ? (signed short)Bytes::get_Java_u2(stream()->cur_bcp() + 4) : (signed char)(stream()->cur_bcp()[2]);
1235   load_local(intType, index);
1236   ipush(append(new Constant(new IntConstant(delta))));
1237   arithmetic_op(intType, Bytecodes::_iadd);
1238   store_local(intType, index);
1239 }
1240 
1241 
1242 void GraphBuilder::_goto(int from_bci, int to_bci) {
1243   Goto *x = new Goto(block_at(to_bci), to_bci <= from_bci);
1244   if (is_profiling()) {
1245     compilation()->set_would_profile(true);
1246     x->set_profiled_bci(bci());
1247     if (profile_branches()) {
1248       x->set_profiled_method(method());
1249       x->set_should_profile(true);
1250     }
1251   }
1252   append(x);
1253 }
1254 
1255 
1256 void GraphBuilder::if_node(Value x, If::Condition cond, Value y, ValueStack* state_before) {
1257   BlockBegin* tsux = block_at(stream()->get_dest());
1258   BlockBegin* fsux = block_at(stream()->next_bci());
1259   bool is_bb = tsux->bci() < stream()->cur_bci() || fsux->bci() < stream()->cur_bci();
1260   // In case of loop invariant code motion or predicate insertion
1261   // before the body of a loop the state is needed
1262   Instruction *i = append(new If(x, cond, false, y, tsux, fsux, (is_bb || compilation()->is_optimistic()) ? state_before : NULL, is_bb));
1263 
1264   assert(i->as_Goto() == NULL ||
1265          (i->as_Goto()->sux_at(0) == tsux  && i->as_Goto()->is_safepoint() == tsux->bci() < stream()->cur_bci()) ||
1266          (i->as_Goto()->sux_at(0) == fsux  && i->as_Goto()->is_safepoint() == fsux->bci() < stream()->cur_bci()),
1267          "safepoint state of Goto returned by canonicalizer incorrect");
1268 
1269   if (is_profiling()) {
1270     If* if_node = i->as_If();
1271     if (if_node != NULL) {
1272       // Note that we'd collect profile data in this method if we wanted it.
1273       compilation()->set_would_profile(true);
1274       // At level 2 we need the proper bci to count backedges
1275       if_node->set_profiled_bci(bci());
1276       if (profile_branches()) {
1277         // Successors can be rotated by the canonicalizer, check for this case.
1278         if_node->set_profiled_method(method());
1279         if_node->set_should_profile(true);
1280         if (if_node->tsux() == fsux) {
1281           if_node->set_swapped(true);
1282         }
1283       }
1284       return;
1285     }
1286 
1287     // Check if this If was reduced to Goto.
1288     Goto *goto_node = i->as_Goto();
1289     if (goto_node != NULL) {
1290       compilation()->set_would_profile(true);
1291       goto_node->set_profiled_bci(bci());
1292       if (profile_branches()) {
1293         goto_node->set_profiled_method(method());
1294         goto_node->set_should_profile(true);
1295         // Find out which successor is used.
1296         if (goto_node->default_sux() == tsux) {
1297           goto_node->set_direction(Goto::taken);
1298         } else if (goto_node->default_sux() == fsux) {
1299           goto_node->set_direction(Goto::not_taken);
1300         } else {
1301           ShouldNotReachHere();
1302         }
1303       }
1304       return;
1305     }
1306   }
1307 }
1308 
1309 
1310 void GraphBuilder::if_zero(ValueType* type, If::Condition cond) {
1311   Value y = append(new Constant(intZero));
1312   ValueStack* state_before = copy_state_before();
1313   Value x = ipop();
1314   if_node(x, cond, y, state_before);
1315 }
1316 
1317 
1318 void GraphBuilder::if_null(ValueType* type, If::Condition cond) {
1319   Value y = append(new Constant(objectNull));
1320   ValueStack* state_before = copy_state_before();
1321   Value x = apop();
1322   if_node(x, cond, y, state_before);
1323 }
1324 
1325 
1326 void GraphBuilder::if_same(ValueType* type, If::Condition cond) {
1327   ValueStack* state_before = copy_state_before();
1328   Value y = pop(type);
1329   Value x = pop(type);
1330   if_node(x, cond, y, state_before);
1331 }
1332 
1333 
1334 void GraphBuilder::jsr(int dest) {
1335   // We only handle well-formed jsrs (those which are "block-structured").
1336   // If the bytecodes are strange (jumping out of a jsr block) then we
1337   // might end up trying to re-parse a block containing a jsr which
1338   // has already been activated. Watch for this case and bail out.
1339   for (ScopeData* cur_scope_data = scope_data();
1340        cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
1341        cur_scope_data = cur_scope_data->parent()) {
1342     if (cur_scope_data->jsr_entry_bci() == dest) {
1343       BAILOUT("too-complicated jsr/ret structure");
1344     }
1345   }
1346 
1347   push(addressType, append(new Constant(new AddressConstant(next_bci()))));
1348   if (!try_inline_jsr(dest)) {
1349     return; // bailed out while parsing and inlining subroutine
1350   }
1351 }
1352 
1353 
1354 void GraphBuilder::ret(int local_index) {
1355   if (!parsing_jsr()) BAILOUT("ret encountered while not parsing subroutine");
1356 
1357   if (local_index != scope_data()->jsr_return_address_local()) {
1358     BAILOUT("can not handle complicated jsr/ret constructs");
1359   }
1360 
1361   // Rets simply become (NON-SAFEPOINT) gotos to the jsr continuation
1362   append(new Goto(scope_data()->jsr_continuation(), false));
1363 }
1364 
1365 
1366 void GraphBuilder::table_switch() {
1367   Bytecode_tableswitch sw(stream());
1368   const int l = sw.length();
1369   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1370     // total of 2 successors => use If instead of switch
1371     // Note: This code should go into the canonicalizer as soon as it can
1372     //       can handle canonicalized forms that contain more than one node.
1373     Value key = append(new Constant(new IntConstant(sw.low_key())));
1374     BlockBegin* tsux = block_at(bci() + sw.dest_offset_at(0));
1375     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1376     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1377     // In case of loop invariant code motion or predicate insertion
1378     // before the body of a loop the state is needed
1379     ValueStack* state_before = copy_state_if_bb(is_bb);
1380     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1381   } else {
1382     // collect successors
1383     BlockList* sux = new BlockList(l + 1, NULL);
1384     int i;
1385     bool has_bb = false;
1386     for (i = 0; i < l; i++) {
1387       sux->at_put(i, block_at(bci() + sw.dest_offset_at(i)));
1388       if (sw.dest_offset_at(i) < 0) has_bb = true;
1389     }
1390     // add default successor
1391     if (sw.default_offset() < 0) has_bb = true;
1392     sux->at_put(i, block_at(bci() + sw.default_offset()));
1393     // In case of loop invariant code motion or predicate insertion
1394     // before the body of a loop the state is needed
1395     ValueStack* state_before = copy_state_if_bb(has_bb);
1396     Instruction* res = append(new TableSwitch(ipop(), sux, sw.low_key(), state_before, has_bb));
1397 #ifdef ASSERT
1398     if (res->as_Goto()) {
1399       for (i = 0; i < l; i++) {
1400         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1401           assert(res->as_Goto()->is_safepoint() == sw.dest_offset_at(i) < 0, "safepoint state of Goto returned by canonicalizer incorrect");
1402         }
1403       }
1404     }
1405 #endif
1406   }
1407 }
1408 
1409 
1410 void GraphBuilder::lookup_switch() {
1411   Bytecode_lookupswitch sw(stream());
1412   const int l = sw.number_of_pairs();
1413   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1414     // total of 2 successors => use If instead of switch
1415     // Note: This code should go into the canonicalizer as soon as it can
1416     //       can handle canonicalized forms that contain more than one node.
1417     // simplify to If
1418     LookupswitchPair pair = sw.pair_at(0);
1419     Value key = append(new Constant(new IntConstant(pair.match())));
1420     BlockBegin* tsux = block_at(bci() + pair.offset());
1421     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1422     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1423     // In case of loop invariant code motion or predicate insertion
1424     // before the body of a loop the state is needed
1425     ValueStack* state_before = copy_state_if_bb(is_bb);;
1426     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1427   } else {
1428     // collect successors & keys
1429     BlockList* sux = new BlockList(l + 1, NULL);
1430     intArray* keys = new intArray(l, l, 0);
1431     int i;
1432     bool has_bb = false;
1433     for (i = 0; i < l; i++) {
1434       LookupswitchPair pair = sw.pair_at(i);
1435       if (pair.offset() < 0) has_bb = true;
1436       sux->at_put(i, block_at(bci() + pair.offset()));
1437       keys->at_put(i, pair.match());
1438     }
1439     // add default successor
1440     if (sw.default_offset() < 0) has_bb = true;
1441     sux->at_put(i, block_at(bci() + sw.default_offset()));
1442     // In case of loop invariant code motion or predicate insertion
1443     // before the body of a loop the state is needed
1444     ValueStack* state_before = copy_state_if_bb(has_bb);
1445     Instruction* res = append(new LookupSwitch(ipop(), sux, keys, state_before, has_bb));
1446 #ifdef ASSERT
1447     if (res->as_Goto()) {
1448       for (i = 0; i < l; i++) {
1449         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1450           assert(res->as_Goto()->is_safepoint() == sw.pair_at(i).offset() < 0, "safepoint state of Goto returned by canonicalizer incorrect");
1451         }
1452       }
1453     }
1454 #endif
1455   }
1456 }
1457 
1458 void GraphBuilder::call_register_finalizer() {
1459   // If the receiver requires finalization then emit code to perform
1460   // the registration on return.
1461 
1462   // Gather some type information about the receiver
1463   Value receiver = state()->local_at(0);
1464   assert(receiver != NULL, "must have a receiver");
1465   ciType* declared_type = receiver->declared_type();
1466   ciType* exact_type = receiver->exact_type();
1467   if (exact_type == NULL &&
1468       receiver->as_Local() &&
1469       receiver->as_Local()->java_index() == 0) {
1470     ciInstanceKlass* ik = compilation()->method()->holder();
1471     if (ik->is_final()) {
1472       exact_type = ik;
1473     } else if (UseCHA && !(ik->has_subklass() || ik->is_interface())) {
1474       // test class is leaf class
1475       compilation()->dependency_recorder()->assert_leaf_type(ik);
1476       exact_type = ik;
1477     } else {
1478       declared_type = ik;
1479     }
1480   }
1481 
1482   // see if we know statically that registration isn't required
1483   bool needs_check = true;
1484   if (exact_type != NULL) {
1485     needs_check = exact_type->as_instance_klass()->has_finalizer();
1486   } else if (declared_type != NULL) {
1487     ciInstanceKlass* ik = declared_type->as_instance_klass();
1488     if (!Dependencies::has_finalizable_subclass(ik)) {
1489       compilation()->dependency_recorder()->assert_has_no_finalizable_subclasses(ik);
1490       needs_check = false;
1491     }
1492   }
1493 
1494   if (needs_check) {
1495     // Perform the registration of finalizable objects.
1496     ValueStack* state_before = copy_state_for_exception();
1497     load_local(objectType, 0);
1498     append_split(new Intrinsic(voidType, vmIntrinsics::_Object_init,
1499                                state()->pop_arguments(1),
1500                                true, state_before, true));
1501   }
1502 }
1503 
1504 
1505 void GraphBuilder::method_return(Value x, bool ignore_return) {
1506   if (RegisterFinalizersAtInit &&
1507       method()->intrinsic_id() == vmIntrinsics::_Object_init) {
1508     call_register_finalizer();
1509   }
1510 
1511   // The conditions for a memory barrier are described in Parse::do_exits().
1512   bool need_mem_bar = false;
1513   if (method()->name() == ciSymbols::object_initializer_name() &&
1514        (scope()->wrote_final() ||
1515          (AlwaysSafeConstructors && scope()->wrote_fields()) ||
1516          (support_IRIW_for_not_multiple_copy_atomic_cpu && scope()->wrote_volatile()))) {
1517     need_mem_bar = true;
1518   }
1519 
1520   BasicType bt = method()->return_type()->basic_type();
1521   switch (bt) {
1522     case T_BYTE:
1523     {
1524       Value shift = append(new Constant(new IntConstant(24)));
1525       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1526       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1527       break;
1528     }
1529     case T_SHORT:
1530     {
1531       Value shift = append(new Constant(new IntConstant(16)));
1532       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1533       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1534       break;
1535     }
1536     case T_CHAR:
1537     {
1538       Value mask = append(new Constant(new IntConstant(0xFFFF)));
1539       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1540       break;
1541     }
1542     case T_BOOLEAN:
1543     {
1544       Value mask = append(new Constant(new IntConstant(1)));
1545       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1546       break;
1547     }
1548     default:
1549       break;
1550   }
1551 
1552   // Check to see whether we are inlining. If so, Return
1553   // instructions become Gotos to the continuation point.
1554   if (continuation() != NULL) {
1555 
1556     int invoke_bci = state()->caller_state()->bci();
1557 
1558     if (x != NULL  && !ignore_return) {
1559       ciMethod* caller = state()->scope()->caller()->method();
1560       Bytecodes::Code invoke_raw_bc = caller->raw_code_at_bci(invoke_bci);
1561       if (invoke_raw_bc == Bytecodes::_invokehandle || invoke_raw_bc == Bytecodes::_invokedynamic) {
1562         ciType* declared_ret_type = caller->get_declared_signature_at_bci(invoke_bci)->return_type();
1563         if (declared_ret_type->is_klass() && x->exact_type() == NULL &&
1564             x->declared_type() != declared_ret_type && declared_ret_type != compilation()->env()->Object_klass()) {
1565           x = append(new TypeCast(declared_ret_type->as_klass(), x, copy_state_before()));
1566         }
1567       }
1568     }
1569 
1570     assert(!method()->is_synchronized() || InlineSynchronizedMethods, "can not inline synchronized methods yet");
1571 
1572     if (compilation()->env()->dtrace_method_probes()) {
1573       // Report exit from inline methods
1574       Values* args = new Values(1);
1575       args->push(append(new Constant(new MethodConstant(method()))));
1576       append(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args));
1577     }
1578 
1579     // If the inlined method is synchronized, the monitor must be
1580     // released before we jump to the continuation block.
1581     if (method()->is_synchronized()) {
1582       assert(state()->locks_size() == 1, "receiver must be locked here");
1583       monitorexit(state()->lock_at(0), SynchronizationEntryBCI);
1584     }
1585 
1586     if (need_mem_bar) {
1587       append(new MemBar(lir_membar_storestore));
1588     }
1589 
1590     // State at end of inlined method is the state of the caller
1591     // without the method parameters on stack, including the
1592     // return value, if any, of the inlined method on operand stack.
1593     set_state(state()->caller_state()->copy_for_parsing());
1594     if (x != NULL) {
1595       if (!ignore_return) {
1596         state()->push(x->type(), x);
1597       }
1598       if (profile_return() && x->type()->is_object_kind()) {
1599         ciMethod* caller = state()->scope()->method();
1600         profile_return_type(x, method(), caller, invoke_bci);
1601       }
1602     }
1603     Goto* goto_callee = new Goto(continuation(), false);
1604 
1605     // See whether this is the first return; if so, store off some
1606     // of the state for later examination
1607     if (num_returns() == 0) {
1608       set_inline_cleanup_info();
1609     }
1610 
1611     // The current bci() is in the wrong scope, so use the bci() of
1612     // the continuation point.
1613     append_with_bci(goto_callee, scope_data()->continuation()->bci());
1614     incr_num_returns();
1615     return;
1616   }
1617 
1618   state()->truncate_stack(0);
1619   if (method()->is_synchronized()) {
1620     // perform the unlocking before exiting the method
1621     Value receiver;
1622     if (!method()->is_static()) {
1623       receiver = _initial_state->local_at(0);
1624     } else {
1625       receiver = append(new Constant(new ClassConstant(method()->holder())));
1626     }
1627     append_split(new MonitorExit(receiver, state()->unlock()));
1628   }
1629 
1630   if (need_mem_bar) {
1631       append(new MemBar(lir_membar_storestore));
1632   }
1633 
1634   assert(!ignore_return, "Ignoring return value works only for inlining");
1635   append(new Return(x));
1636 }
1637 
1638 Value GraphBuilder::make_constant(ciConstant field_value, ciField* field) {
1639   if (!field_value.is_valid())  return NULL;
1640 
1641   BasicType field_type = field_value.basic_type();
1642   ValueType* value = as_ValueType(field_value);
1643 
1644   // Attach dimension info to stable arrays.
1645   if (FoldStableValues &&
1646       field->is_stable() && field_type == T_ARRAY && !field_value.is_null_or_zero()) {
1647     ciArray* array = field_value.as_object()->as_array();
1648     jint dimension = field->type()->as_array_klass()->dimension();
1649     value = new StableArrayConstant(array, dimension);
1650   }
1651 
1652   switch (field_type) {
1653     case T_ARRAY:
1654     case T_OBJECT:
1655       if (field_value.as_object()->should_be_constant()) {
1656         return new Constant(value);
1657       }
1658       return NULL; // Not a constant.
1659     default:
1660       return new Constant(value);
1661   }
1662 }
1663 
1664 void GraphBuilder::access_field(Bytecodes::Code code) {
1665   bool will_link;
1666   ciField* field = stream()->get_field(will_link);
1667   ciInstanceKlass* holder = field->holder();
1668   BasicType field_type = field->type()->basic_type();
1669   ValueType* type = as_ValueType(field_type);
1670   // call will_link again to determine if the field is valid.
1671   const bool needs_patching = !holder->is_loaded() ||
1672                               !field->will_link(method(), code) ||
1673                               PatchALot;
1674 
1675   ValueStack* state_before = NULL;
1676   if (!holder->is_initialized() || needs_patching) {
1677     // save state before instruction for debug info when
1678     // deoptimization happens during patching
1679     state_before = copy_state_before();
1680   }
1681 
1682   Value obj = NULL;
1683   if (code == Bytecodes::_getstatic || code == Bytecodes::_putstatic) {
1684     if (state_before != NULL) {
1685       // build a patching constant
1686       obj = new Constant(new InstanceConstant(holder->java_mirror()), state_before);
1687     } else {
1688       obj = new Constant(new InstanceConstant(holder->java_mirror()));
1689     }
1690   }
1691 
1692   if (field->is_final() && (code == Bytecodes::_putfield)) {
1693     scope()->set_wrote_final();
1694   }
1695 
1696   if (code == Bytecodes::_putfield) {
1697     scope()->set_wrote_fields();
1698     if (field->is_volatile()) {
1699       scope()->set_wrote_volatile();
1700     }
1701   }
1702 
1703   const int offset = !needs_patching ? field->offset() : -1;
1704   switch (code) {
1705     case Bytecodes::_getstatic: {
1706       // check for compile-time constants, i.e., initialized static final fields
1707       Value constant = NULL;
1708       if (field->is_static_constant() && !PatchALot) {
1709         ciConstant field_value = field->constant_value();
1710         assert(!field->is_stable() || !field_value.is_null_or_zero(),
1711                "stable static w/ default value shouldn't be a constant");
1712         constant = make_constant(field_value, field);
1713       }
1714       if (constant != NULL) {
1715         push(type, append(constant));
1716       } else {
1717         if (state_before == NULL) {
1718           state_before = copy_state_for_exception();
1719         }
1720         push(type, append(new LoadField(append(obj), offset, field, true,
1721                                         state_before, needs_patching)));
1722       }
1723       break;
1724     }
1725     case Bytecodes::_putstatic: {
1726       Value val = pop(type);
1727       if (state_before == NULL) {
1728         state_before = copy_state_for_exception();
1729       }
1730       if (field->type()->basic_type() == T_BOOLEAN) {
1731         Value mask = append(new Constant(new IntConstant(1)));
1732         val = append(new LogicOp(Bytecodes::_iand, val, mask));
1733       }
1734       append(new StoreField(append(obj), offset, field, val, true, state_before, needs_patching));
1735       break;
1736     }
1737     case Bytecodes::_getfield: {
1738       // Check for compile-time constants, i.e., trusted final non-static fields.
1739       Value constant = NULL;
1740       obj = apop();
1741       ObjectType* obj_type = obj->type()->as_ObjectType();
1742       if (field->is_constant() && obj_type->is_constant() && !PatchALot) {
1743         ciObject* const_oop = obj_type->constant_value();
1744         if (!const_oop->is_null_object() && const_oop->is_loaded()) {
1745           ciConstant field_value = field->constant_value_of(const_oop);
1746           if (field_value.is_valid()) {
1747             constant = make_constant(field_value, field);
1748             // For CallSite objects add a dependency for invalidation of the optimization.
1749             if (field->is_call_site_target()) {
1750               ciCallSite* call_site = const_oop->as_call_site();
1751               if (!call_site->is_fully_initialized_constant_call_site()) {
1752                 ciMethodHandle* target = field_value.as_object()->as_method_handle();
1753                 dependency_recorder()->assert_call_site_target_value(call_site, target);
1754               }
1755             }
1756           }
1757         }
1758       }
1759       if (constant != NULL) {
1760         push(type, append(constant));
1761       } else {
1762         if (state_before == NULL) {
1763           state_before = copy_state_for_exception();
1764         }
1765         LoadField* load = new LoadField(obj, offset, field, false, state_before, needs_patching);
1766         Value replacement = !needs_patching ? _memory->load(load) : load;
1767         if (replacement != load) {
1768           assert(replacement->is_linked() || !replacement->can_be_linked(), "should already by linked");
1769           // Writing an (integer) value to a boolean, byte, char or short field includes an implicit narrowing
1770           // conversion. Emit an explicit conversion here to get the correct field value after the write.
1771           BasicType bt = field->type()->basic_type();
1772           switch (bt) {
1773           case T_BOOLEAN:
1774           case T_BYTE:
1775             replacement = append(new Convert(Bytecodes::_i2b, replacement, as_ValueType(bt)));
1776             break;
1777           case T_CHAR:
1778             replacement = append(new Convert(Bytecodes::_i2c, replacement, as_ValueType(bt)));
1779             break;
1780           case T_SHORT:
1781             replacement = append(new Convert(Bytecodes::_i2s, replacement, as_ValueType(bt)));
1782             break;
1783           default:
1784             break;
1785           }
1786           push(type, replacement);
1787         } else {
1788           push(type, append(load));
1789         }
1790       }
1791       break;
1792     }
1793     case Bytecodes::_putfield: {
1794       Value val = pop(type);
1795       obj = apop();
1796       if (state_before == NULL) {
1797         state_before = copy_state_for_exception();
1798       }
1799       if (field->type()->basic_type() == T_BOOLEAN) {
1800         Value mask = append(new Constant(new IntConstant(1)));
1801         val = append(new LogicOp(Bytecodes::_iand, val, mask));
1802       }
1803       StoreField* store = new StoreField(obj, offset, field, val, false, state_before, needs_patching);
1804       if (!needs_patching) store = _memory->store(store);
1805       if (store != NULL) {
1806         append(store);
1807       }
1808       break;
1809     }
1810     default:
1811       ShouldNotReachHere();
1812       break;
1813   }
1814 }
1815 
1816 
1817 Dependencies* GraphBuilder::dependency_recorder() const {
1818   assert(DeoptC1, "need debug information");
1819   return compilation()->dependency_recorder();
1820 }
1821 
1822 // How many arguments do we want to profile?
1823 Values* GraphBuilder::args_list_for_profiling(ciMethod* target, int& start, bool may_have_receiver) {
1824   int n = 0;
1825   bool has_receiver = may_have_receiver && Bytecodes::has_receiver(method()->java_code_at_bci(bci()));
1826   start = has_receiver ? 1 : 0;
1827   if (profile_arguments()) {
1828     ciProfileData* data = method()->method_data()->bci_to_data(bci());
1829     if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
1830       n = data->is_CallTypeData() ? data->as_CallTypeData()->number_of_arguments() : data->as_VirtualCallTypeData()->number_of_arguments();
1831     }
1832   }
1833   // If we are inlining then we need to collect arguments to profile parameters for the target
1834   if (profile_parameters() && target != NULL) {
1835     if (target->method_data() != NULL && target->method_data()->parameters_type_data() != NULL) {
1836       // The receiver is profiled on method entry so it's included in
1837       // the number of parameters but here we're only interested in
1838       // actual arguments.
1839       n = MAX2(n, target->method_data()->parameters_type_data()->number_of_parameters() - start);
1840     }
1841   }
1842   if (n > 0) {
1843     return new Values(n);
1844   }
1845   return NULL;
1846 }
1847 
1848 void GraphBuilder::check_args_for_profiling(Values* obj_args, int expected) {
1849 #ifdef ASSERT
1850   bool ignored_will_link;
1851   ciSignature* declared_signature = NULL;
1852   ciMethod* real_target = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1853   assert(expected == obj_args->max_length() || real_target->is_method_handle_intrinsic(), "missed on arg?");
1854 #endif
1855 }
1856 
1857 // Collect arguments that we want to profile in a list
1858 Values* GraphBuilder::collect_args_for_profiling(Values* args, ciMethod* target, bool may_have_receiver) {
1859   int start = 0;
1860   Values* obj_args = args_list_for_profiling(target, start, may_have_receiver);
1861   if (obj_args == NULL) {
1862     return NULL;
1863   }
1864   int s = obj_args->max_length();
1865   // if called through method handle invoke, some arguments may have been popped
1866   for (int i = start, j = 0; j < s && i < args->length(); i++) {
1867     if (args->at(i)->type()->is_object_kind()) {
1868       obj_args->push(args->at(i));
1869       j++;
1870     }
1871   }
1872   check_args_for_profiling(obj_args, s);
1873   return obj_args;
1874 }
1875 
1876 
1877 void GraphBuilder::invoke(Bytecodes::Code code) {
1878   bool will_link;
1879   ciSignature* declared_signature = NULL;
1880   ciMethod*             target = stream()->get_method(will_link, &declared_signature);
1881   ciKlass*              holder = stream()->get_declared_method_holder();
1882   const Bytecodes::Code bc_raw = stream()->cur_bc_raw();
1883   assert(declared_signature != NULL, "cannot be null");
1884   assert(will_link == target->is_loaded(), "");
1885 
1886   ciInstanceKlass* klass = target->holder();
1887   assert(!target->is_loaded() || klass->is_loaded(), "loaded target must imply loaded klass");
1888 
1889   // check if CHA possible: if so, change the code to invoke_special
1890   ciInstanceKlass* calling_klass = method()->holder();
1891   ciInstanceKlass* callee_holder = ciEnv::get_instance_klass_for_declared_method_holder(holder);
1892   ciInstanceKlass* actual_recv = callee_holder;
1893 
1894   CompileLog* log = compilation()->log();
1895   if (log != NULL)
1896       log->elem("call method='%d' instr='%s'",
1897                 log->identify(target),
1898                 Bytecodes::name(code));
1899 
1900   // Some methods are obviously bindable without any type checks so
1901   // convert them directly to an invokespecial or invokestatic.
1902   if (target->is_loaded() && !target->is_abstract() && target->can_be_statically_bound()) {
1903     switch (bc_raw) {
1904     case Bytecodes::_invokeinterface:
1905       // convert to invokespecial if the target is the private interface method.
1906       if (target->is_private()) {
1907         assert(holder->is_interface(), "How did we get a non-interface method here!");
1908         code = Bytecodes::_invokespecial;
1909       }
1910       break;
1911     case Bytecodes::_invokevirtual:
1912       code = Bytecodes::_invokespecial;
1913       break;
1914     case Bytecodes::_invokehandle:
1915       code = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokespecial;
1916       break;
1917     default:
1918       break;
1919     }
1920   } else {
1921     if (bc_raw == Bytecodes::_invokehandle) {
1922       assert(!will_link, "should come here only for unlinked call");
1923       code = Bytecodes::_invokespecial;
1924     }
1925   }
1926 
1927   if (code == Bytecodes::_invokespecial) {
1928     // Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.
1929     ciKlass* receiver_constraint = nullptr;
1930 
1931     if (bc_raw == Bytecodes::_invokeinterface) {
1932       receiver_constraint = holder;
1933     } else if (bc_raw == Bytecodes::_invokespecial && !target->is_object_initializer() && calling_klass->is_interface()) {
1934       receiver_constraint = calling_klass;
1935     }
1936 
1937     if (receiver_constraint != nullptr) {
1938       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
1939       Value receiver = state()->stack_at(index);
1940       CheckCast* c = new CheckCast(receiver_constraint, receiver, copy_state_before());
1941       // go to uncommon_trap when checkcast fails
1942       c->set_invokespecial_receiver_check();
1943       state()->stack_at_put(index, append_split(c));
1944     }
1945   }
1946 
1947   // Push appendix argument (MethodType, CallSite, etc.), if one.
1948   bool patch_for_appendix = false;
1949   int patching_appendix_arg = 0;
1950   if (Bytecodes::has_optional_appendix(bc_raw) && (!will_link || PatchALot)) {
1951     Value arg = append(new Constant(new ObjectConstant(compilation()->env()->unloaded_ciinstance()), copy_state_before()));
1952     apush(arg);
1953     patch_for_appendix = true;
1954     patching_appendix_arg = (will_link && stream()->has_appendix()) ? 0 : 1;
1955   } else if (stream()->has_appendix()) {
1956     ciObject* appendix = stream()->get_appendix();
1957     Value arg = append(new Constant(new ObjectConstant(appendix)));
1958     apush(arg);
1959   }
1960 
1961   ciMethod* cha_monomorphic_target = NULL;
1962   ciMethod* exact_target = NULL;
1963   Value better_receiver = NULL;
1964   if (UseCHA && DeoptC1 && target->is_loaded() &&
1965       !(// %%% FIXME: Are both of these relevant?
1966         target->is_method_handle_intrinsic() ||
1967         target->is_compiled_lambda_form()) &&
1968       !patch_for_appendix) {
1969     Value receiver = NULL;
1970     ciInstanceKlass* receiver_klass = NULL;
1971     bool type_is_exact = false;
1972     // try to find a precise receiver type
1973     if (will_link && !target->is_static()) {
1974       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
1975       receiver = state()->stack_at(index);
1976       ciType* type = receiver->exact_type();
1977       if (type != NULL && type->is_loaded() &&
1978           type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
1979         receiver_klass = (ciInstanceKlass*) type;
1980         type_is_exact = true;
1981       }
1982       if (type == NULL) {
1983         type = receiver->declared_type();
1984         if (type != NULL && type->is_loaded() &&
1985             type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
1986           receiver_klass = (ciInstanceKlass*) type;
1987           if (receiver_klass->is_leaf_type() && !receiver_klass->is_final()) {
1988             // Insert a dependency on this type since
1989             // find_monomorphic_target may assume it's already done.
1990             dependency_recorder()->assert_leaf_type(receiver_klass);
1991             type_is_exact = true;
1992           }
1993         }
1994       }
1995     }
1996     if (receiver_klass != NULL && type_is_exact &&
1997         receiver_klass->is_loaded() && code != Bytecodes::_invokespecial) {
1998       // If we have the exact receiver type we can bind directly to
1999       // the method to call.
2000       exact_target = target->resolve_invoke(calling_klass, receiver_klass);
2001       if (exact_target != NULL) {
2002         target = exact_target;
2003         code = Bytecodes::_invokespecial;
2004       }
2005     }
2006     if (receiver_klass != NULL &&
2007         receiver_klass->is_subtype_of(actual_recv) &&
2008         actual_recv->is_initialized()) {
2009       actual_recv = receiver_klass;
2010     }
2011 
2012     if ((code == Bytecodes::_invokevirtual && callee_holder->is_initialized()) ||
2013         (code == Bytecodes::_invokeinterface && callee_holder->is_initialized() && !actual_recv->is_interface())) {
2014       // Use CHA on the receiver to select a more precise method.
2015       cha_monomorphic_target = target->find_monomorphic_target(calling_klass, callee_holder, actual_recv);
2016     } else if (code == Bytecodes::_invokeinterface && callee_holder->is_loaded() && receiver != NULL) {
2017       assert(callee_holder->is_interface(), "invokeinterface to non interface?");
2018       // If there is only one implementor of this interface then we
2019       // may be able bind this invoke directly to the implementing
2020       // klass but we need both a dependence on the single interface
2021       // and on the method we bind to.  Additionally since all we know
2022       // about the receiver type is the it's supposed to implement the
2023       // interface we have to insert a check that it's the class we
2024       // expect.  Interface types are not checked by the verifier so
2025       // they are roughly equivalent to Object.
2026       // The number of implementors for declared_interface is less or
2027       // equal to the number of implementors for target->holder() so
2028       // if number of implementors of target->holder() == 1 then
2029       // number of implementors for decl_interface is 0 or 1. If
2030       // it's 0 then no class implements decl_interface and there's
2031       // no point in inlining.
2032       ciInstanceKlass* declared_interface = callee_holder;
2033       ciInstanceKlass* singleton = declared_interface->unique_implementor();
2034       if (singleton != NULL) {
2035         assert(singleton != declared_interface, "not a unique implementor");
2036         cha_monomorphic_target = target->find_monomorphic_target(calling_klass, declared_interface, singleton);
2037         if (cha_monomorphic_target != NULL) {
2038           if (cha_monomorphic_target->holder() != compilation()->env()->Object_klass()) {
2039             // If CHA is able to bind this invoke then update the class
2040             // to match that class, otherwise klass will refer to the
2041             // interface.
2042             klass = cha_monomorphic_target->holder();
2043             actual_recv = declared_interface;
2044 
2045             // insert a check it's really the expected class.
2046             CheckCast* c = new CheckCast(klass, receiver, copy_state_for_exception());
2047             c->set_incompatible_class_change_check();
2048             c->set_direct_compare(klass->is_final());
2049             // pass the result of the checkcast so that the compiler has
2050             // more accurate type info in the inlinee
2051             better_receiver = append_split(c);
2052           } else {
2053             cha_monomorphic_target = NULL; // subtype check against Object is useless
2054           }
2055         }
2056       }
2057     }
2058   }
2059 
2060   if (cha_monomorphic_target != NULL) {
2061     assert(!target->can_be_statically_bound() || target == cha_monomorphic_target, "");
2062     assert(!cha_monomorphic_target->is_abstract(), "");
2063     if (!cha_monomorphic_target->can_be_statically_bound(actual_recv)) {
2064       // If we inlined because CHA revealed only a single target method,
2065       // then we are dependent on that target method not getting overridden
2066       // by dynamic class loading.  Be sure to test the "static" receiver
2067       // dest_method here, as opposed to the actual receiver, which may
2068       // falsely lead us to believe that the receiver is final or private.
2069       dependency_recorder()->assert_unique_concrete_method(actual_recv, cha_monomorphic_target, callee_holder, target);
2070     }
2071     code = Bytecodes::_invokespecial;
2072   }
2073 
2074   // check if we could do inlining
2075   if (!PatchALot && Inline && target->is_loaded() && !patch_for_appendix &&
2076       callee_holder->is_loaded()) { // the effect of symbolic reference resolution
2077 
2078     // callee is known => check if we have static binding
2079     if ((code == Bytecodes::_invokestatic && klass->is_initialized()) || // invokestatic involves an initialization barrier on declaring class
2080         code == Bytecodes::_invokespecial ||
2081         (code == Bytecodes::_invokevirtual && target->is_final_method()) ||
2082         code == Bytecodes::_invokedynamic) {
2083       // static binding => check if callee is ok
2084       ciMethod* inline_target = (cha_monomorphic_target != NULL) ? cha_monomorphic_target : target;
2085       bool holder_known = (cha_monomorphic_target != NULL) || (exact_target != NULL);
2086       bool success = try_inline(inline_target, holder_known, false /* ignore_return */, code, better_receiver);
2087 
2088       CHECK_BAILOUT();
2089       clear_inline_bailout();
2090 
2091       if (success) {
2092         // Register dependence if JVMTI has either breakpoint
2093         // setting or hotswapping of methods capabilities since they may
2094         // cause deoptimization.
2095         if (compilation()->env()->jvmti_can_hotswap_or_post_breakpoint()) {
2096           dependency_recorder()->assert_evol_method(inline_target);
2097         }
2098         return;
2099       }
2100     } else {
2101       print_inlining(target, "no static binding", /*success*/ false);
2102     }
2103   } else {
2104     print_inlining(target, "not inlineable", /*success*/ false);
2105   }
2106 
2107   // If we attempted an inline which did not succeed because of a
2108   // bailout during construction of the callee graph, the entire
2109   // compilation has to be aborted. This is fairly rare and currently
2110   // seems to only occur for jasm-generated classes which contain
2111   // jsr/ret pairs which are not associated with finally clauses and
2112   // do not have exception handlers in the containing method, and are
2113   // therefore not caught early enough to abort the inlining without
2114   // corrupting the graph. (We currently bail out with a non-empty
2115   // stack at a ret in these situations.)
2116   CHECK_BAILOUT();
2117 
2118   // inlining not successful => standard invoke
2119   ValueType* result_type = as_ValueType(declared_signature->return_type());
2120   ValueStack* state_before = copy_state_exhandling();
2121 
2122   // The bytecode (code) might change in this method so we are checking this very late.
2123   const bool has_receiver =
2124     code == Bytecodes::_invokespecial   ||
2125     code == Bytecodes::_invokevirtual   ||
2126     code == Bytecodes::_invokeinterface;
2127   Values* args = state()->pop_arguments(target->arg_size_no_receiver() + patching_appendix_arg);
2128   Value recv = has_receiver ? apop() : NULL;
2129 
2130   // A null check is required here (when there is a receiver) for any of the following cases
2131   // - invokespecial, always need a null check.
2132   // - invokevirtual, when the target is final and loaded. Calls to final targets will become optimized
2133   //   and require null checking. If the target is loaded a null check is emitted here.
2134   //   If the target isn't loaded the null check must happen after the call resolution. We achieve that
2135   //   by using the target methods unverified entry point (see CompiledIC::compute_monomorphic_entry).
2136   //   (The JVM specification requires that LinkageError must be thrown before a NPE. An unloaded target may
2137   //   potentially fail, and can't have the null check before the resolution.)
2138   // - A call that will be profiled. (But we can't add a null check when the target is unloaded, by the same
2139   //   reason as above, so calls with a receiver to unloaded targets can't be profiled.)
2140   //
2141   // Normal invokevirtual will perform the null check during lookup
2142 
2143   bool need_null_check = (code == Bytecodes::_invokespecial) ||
2144       (target->is_loaded() && (target->is_final_method() || (is_profiling() && profile_calls())));
2145 
2146   if (need_null_check) {
2147     if (recv != NULL) {
2148       null_check(recv);
2149     }
2150 
2151     if (is_profiling()) {
2152       // Note that we'd collect profile data in this method if we wanted it.
2153       compilation()->set_would_profile(true);
2154 
2155       if (profile_calls()) {
2156         assert(cha_monomorphic_target == NULL || exact_target == NULL, "both can not be set");
2157         ciKlass* target_klass = NULL;
2158         if (cha_monomorphic_target != NULL) {
2159           target_klass = cha_monomorphic_target->holder();
2160         } else if (exact_target != NULL) {
2161           target_klass = exact_target->holder();
2162         }
2163         profile_call(target, recv, target_klass, collect_args_for_profiling(args, NULL, false), false);
2164       }
2165     }
2166   }
2167 
2168   Invoke* result = new Invoke(code, result_type, recv, args, target, state_before);
2169   // push result
2170   append_split(result);
2171 
2172   if (result_type != voidType) {
2173     push(result_type, round_fp(result));
2174   }
2175   if (profile_return() && result_type->is_object_kind()) {
2176     profile_return_type(result, target);
2177   }
2178 }
2179 
2180 
2181 void GraphBuilder::new_instance(int klass_index) {
2182   ValueStack* state_before = copy_state_exhandling();
2183   bool will_link;
2184   ciKlass* klass = stream()->get_klass(will_link);
2185   assert(klass->is_instance_klass(), "must be an instance klass");
2186   NewInstance* new_instance = new NewInstance(klass->as_instance_klass(), state_before, stream()->is_unresolved_klass());
2187   _memory->new_instance(new_instance);
2188   apush(append_split(new_instance));
2189 }
2190 
2191 
2192 void GraphBuilder::new_type_array() {
2193   ValueStack* state_before = copy_state_exhandling();
2194   apush(append_split(new NewTypeArray(ipop(), (BasicType)stream()->get_index(), state_before)));
2195 }
2196 
2197 
2198 void GraphBuilder::new_object_array() {
2199   bool will_link;
2200   ciKlass* klass = stream()->get_klass(will_link);
2201   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2202   NewArray* n = new NewObjectArray(klass, ipop(), state_before);
2203   apush(append_split(n));
2204 }
2205 
2206 
2207 bool GraphBuilder::direct_compare(ciKlass* k) {
2208   if (k->is_loaded() && k->is_instance_klass() && !UseSlowPath) {
2209     ciInstanceKlass* ik = k->as_instance_klass();
2210     if (ik->is_final()) {
2211       return true;
2212     } else {
2213       if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {
2214         // test class is leaf class
2215         dependency_recorder()->assert_leaf_type(ik);
2216         return true;
2217       }
2218     }
2219   }
2220   return false;
2221 }
2222 
2223 
2224 void GraphBuilder::check_cast(int klass_index) {
2225   bool will_link;
2226   ciKlass* klass = stream()->get_klass(will_link);
2227   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_for_exception();
2228   CheckCast* c = new CheckCast(klass, apop(), state_before);
2229   apush(append_split(c));
2230   c->set_direct_compare(direct_compare(klass));
2231 
2232   if (is_profiling()) {
2233     // Note that we'd collect profile data in this method if we wanted it.
2234     compilation()->set_would_profile(true);
2235 
2236     if (profile_checkcasts()) {
2237       c->set_profiled_method(method());
2238       c->set_profiled_bci(bci());
2239       c->set_should_profile(true);
2240     }
2241   }
2242 }
2243 
2244 
2245 void GraphBuilder::instance_of(int klass_index) {
2246   bool will_link;
2247   ciKlass* klass = stream()->get_klass(will_link);
2248   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2249   InstanceOf* i = new InstanceOf(klass, apop(), state_before);
2250   ipush(append_split(i));
2251   i->set_direct_compare(direct_compare(klass));
2252 
2253   if (is_profiling()) {
2254     // Note that we'd collect profile data in this method if we wanted it.
2255     compilation()->set_would_profile(true);
2256 
2257     if (profile_checkcasts()) {
2258       i->set_profiled_method(method());
2259       i->set_profiled_bci(bci());
2260       i->set_should_profile(true);
2261     }
2262   }
2263 }
2264 
2265 
2266 void GraphBuilder::monitorenter(Value x, int bci) {
2267   // save state before locking in case of deoptimization after a NullPointerException
2268   ValueStack* state_before = copy_state_for_exception_with_bci(bci);
2269   compilation()->set_has_monitors(true);
2270   append_with_bci(new MonitorEnter(x, state()->lock(x), state_before), bci);
2271   kill_all();
2272 }
2273 
2274 
2275 void GraphBuilder::monitorexit(Value x, int bci) {
2276   append_with_bci(new MonitorExit(x, state()->unlock()), bci);
2277   kill_all();
2278 }
2279 
2280 
2281 void GraphBuilder::new_multi_array(int dimensions) {
2282   bool will_link;
2283   ciKlass* klass = stream()->get_klass(will_link);
2284   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2285 
2286   Values* dims = new Values(dimensions, dimensions, NULL);
2287   // fill in all dimensions
2288   int i = dimensions;
2289   while (i-- > 0) dims->at_put(i, ipop());
2290   // create array
2291   NewArray* n = new NewMultiArray(klass, dims, state_before);
2292   apush(append_split(n));
2293 }
2294 
2295 
2296 void GraphBuilder::throw_op(int bci) {
2297   // We require that the debug info for a Throw be the "state before"
2298   // the Throw (i.e., exception oop is still on TOS)
2299   ValueStack* state_before = copy_state_before_with_bci(bci);
2300   Throw* t = new Throw(apop(), state_before);
2301   // operand stack not needed after a throw
2302   state()->truncate_stack(0);
2303   append_with_bci(t, bci);
2304 }
2305 
2306 
2307 Value GraphBuilder::round_fp(Value fp_value) {
2308   if (strict_fp_requires_explicit_rounding) {
2309 #ifdef IA32
2310     // no rounding needed if SSE2 is used
2311     if (UseSSE < 2) {
2312       // Must currently insert rounding node for doubleword values that
2313       // are results of expressions (i.e., not loads from memory or
2314       // constants)
2315       if (fp_value->type()->tag() == doubleTag &&
2316           fp_value->as_Constant() == NULL &&
2317           fp_value->as_Local() == NULL &&       // method parameters need no rounding
2318           fp_value->as_RoundFP() == NULL) {
2319         return append(new RoundFP(fp_value));
2320       }
2321     }
2322 #else
2323     Unimplemented();
2324 #endif // IA32
2325   }
2326   return fp_value;
2327 }
2328 
2329 
2330 Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) {
2331   Canonicalizer canon(compilation(), instr, bci);
2332   Instruction* i1 = canon.canonical();
2333   if (i1->is_linked() || !i1->can_be_linked()) {
2334     // Canonicalizer returned an instruction which was already
2335     // appended so simply return it.
2336     return i1;
2337   }
2338 
2339   if (UseLocalValueNumbering) {
2340     // Lookup the instruction in the ValueMap and add it to the map if
2341     // it's not found.
2342     Instruction* i2 = vmap()->find_insert(i1);
2343     if (i2 != i1) {
2344       // found an entry in the value map, so just return it.
2345       assert(i2->is_linked(), "should already be linked");
2346       return i2;
2347     }
2348     ValueNumberingEffects vne(vmap());
2349     i1->visit(&vne);
2350   }
2351 
2352   // i1 was not eliminated => append it
2353   assert(i1->next() == NULL, "shouldn't already be linked");
2354   _last = _last->set_next(i1, canon.bci());
2355 
2356   if (++_instruction_count >= InstructionCountCutoff && !bailed_out()) {
2357     // set the bailout state but complete normal processing.  We
2358     // might do a little more work before noticing the bailout so we
2359     // want processing to continue normally until it's noticed.
2360     bailout("Method and/or inlining is too large");
2361   }
2362 
2363 #ifndef PRODUCT
2364   if (PrintIRDuringConstruction) {
2365     InstructionPrinter ip;
2366     ip.print_line(i1);
2367     if (Verbose) {
2368       state()->print();
2369     }
2370   }
2371 #endif
2372 
2373   // save state after modification of operand stack for StateSplit instructions
2374   StateSplit* s = i1->as_StateSplit();
2375   if (s != NULL) {
2376     if (EliminateFieldAccess) {
2377       Intrinsic* intrinsic = s->as_Intrinsic();
2378       if (s->as_Invoke() != NULL || (intrinsic && !intrinsic->preserves_state())) {
2379         _memory->kill();
2380       }
2381     }
2382     s->set_state(state()->copy(ValueStack::StateAfter, canon.bci()));
2383   }
2384 
2385   // set up exception handlers for this instruction if necessary
2386   if (i1->can_trap()) {
2387     i1->set_exception_handlers(handle_exception(i1));
2388     assert(i1->exception_state() != NULL || !i1->needs_exception_state() || bailed_out(), "handle_exception must set exception state");
2389   }
2390   return i1;
2391 }
2392 
2393 
2394 Instruction* GraphBuilder::append(Instruction* instr) {
2395   assert(instr->as_StateSplit() == NULL || instr->as_BlockEnd() != NULL, "wrong append used");
2396   return append_with_bci(instr, bci());
2397 }
2398 
2399 
2400 Instruction* GraphBuilder::append_split(StateSplit* instr) {
2401   return append_with_bci(instr, bci());
2402 }
2403 
2404 
2405 void GraphBuilder::null_check(Value value) {
2406   if (value->as_NewArray() != NULL || value->as_NewInstance() != NULL) {
2407     return;
2408   } else {
2409     Constant* con = value->as_Constant();
2410     if (con) {
2411       ObjectType* c = con->type()->as_ObjectType();
2412       if (c && c->is_loaded()) {
2413         ObjectConstant* oc = c->as_ObjectConstant();
2414         if (!oc || !oc->value()->is_null_object()) {
2415           return;
2416         }
2417       }
2418     }
2419   }
2420   append(new NullCheck(value, copy_state_for_exception()));
2421 }
2422 
2423 
2424 
2425 XHandlers* GraphBuilder::handle_exception(Instruction* instruction) {
2426   if (!has_handler() && (!instruction->needs_exception_state() || instruction->exception_state() != NULL)) {
2427     assert(instruction->exception_state() == NULL
2428            || instruction->exception_state()->kind() == ValueStack::EmptyExceptionState
2429            || (instruction->exception_state()->kind() == ValueStack::ExceptionState && _compilation->env()->should_retain_local_variables()),
2430            "exception_state should be of exception kind");
2431     return new XHandlers();
2432   }
2433 
2434   XHandlers*  exception_handlers = new XHandlers();
2435   ScopeData*  cur_scope_data = scope_data();
2436   ValueStack* cur_state = instruction->state_before();
2437   ValueStack* prev_state = NULL;
2438   int scope_count = 0;
2439 
2440   assert(cur_state != NULL, "state_before must be set");
2441   do {
2442     int cur_bci = cur_state->bci();
2443     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2444     assert(cur_bci == SynchronizationEntryBCI || cur_bci == cur_scope_data->stream()->cur_bci(), "invalid bci");
2445 
2446     // join with all potential exception handlers
2447     XHandlers* list = cur_scope_data->xhandlers();
2448     const int n = list->length();
2449     for (int i = 0; i < n; i++) {
2450       XHandler* h = list->handler_at(i);
2451       if (h->covers(cur_bci)) {
2452         // h is a potential exception handler => join it
2453         compilation()->set_has_exception_handlers(true);
2454 
2455         BlockBegin* entry = h->entry_block();
2456         if (entry == block()) {
2457           // It's acceptable for an exception handler to cover itself
2458           // but we don't handle that in the parser currently.  It's
2459           // very rare so we bailout instead of trying to handle it.
2460           BAILOUT_("exception handler covers itself", exception_handlers);
2461         }
2462         assert(entry->bci() == h->handler_bci(), "must match");
2463         assert(entry->bci() == -1 || entry == cur_scope_data->block_at(entry->bci()), "blocks must correspond");
2464 
2465         // previously this was a BAILOUT, but this is not necessary
2466         // now because asynchronous exceptions are not handled this way.
2467         assert(entry->state() == NULL || cur_state->total_locks_size() == entry->state()->total_locks_size(), "locks do not match");
2468 
2469         // xhandler start with an empty expression stack
2470         if (cur_state->stack_size() != 0) {
2471           cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());
2472         }
2473         if (instruction->exception_state() == NULL) {
2474           instruction->set_exception_state(cur_state);
2475         }
2476 
2477         // Note: Usually this join must work. However, very
2478         // complicated jsr-ret structures where we don't ret from
2479         // the subroutine can cause the objects on the monitor
2480         // stacks to not match because blocks can be parsed twice.
2481         // The only test case we've seen so far which exhibits this
2482         // problem is caught by the infinite recursion test in
2483         // GraphBuilder::jsr() if the join doesn't work.
2484         if (!entry->try_merge(cur_state)) {
2485           BAILOUT_("error while joining with exception handler, prob. due to complicated jsr/rets", exception_handlers);
2486         }
2487 
2488         // add current state for correct handling of phi functions at begin of xhandler
2489         int phi_operand = entry->add_exception_state(cur_state);
2490 
2491         // add entry to the list of xhandlers of this block
2492         _block->add_exception_handler(entry);
2493 
2494         // add back-edge from xhandler entry to this block
2495         if (!entry->is_predecessor(_block)) {
2496           entry->add_predecessor(_block);
2497         }
2498 
2499         // clone XHandler because phi_operand and scope_count can not be shared
2500         XHandler* new_xhandler = new XHandler(h);
2501         new_xhandler->set_phi_operand(phi_operand);
2502         new_xhandler->set_scope_count(scope_count);
2503         exception_handlers->append(new_xhandler);
2504 
2505         // fill in exception handler subgraph lazily
2506         assert(!entry->is_set(BlockBegin::was_visited_flag), "entry must not be visited yet");
2507         cur_scope_data->add_to_work_list(entry);
2508 
2509         // stop when reaching catchall
2510         if (h->catch_type() == 0) {
2511           return exception_handlers;
2512         }
2513       }
2514     }
2515 
2516     if (exception_handlers->length() == 0) {
2517       // This scope and all callees do not handle exceptions, so the local
2518       // variables of this scope are not needed. However, the scope itself is
2519       // required for a correct exception stack trace -> clear out the locals.
2520       if (_compilation->env()->should_retain_local_variables()) {
2521         cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());
2522       } else {
2523         cur_state = cur_state->copy(ValueStack::EmptyExceptionState, cur_state->bci());
2524       }
2525       if (prev_state != NULL) {
2526         prev_state->set_caller_state(cur_state);
2527       }
2528       if (instruction->exception_state() == NULL) {
2529         instruction->set_exception_state(cur_state);
2530       }
2531     }
2532 
2533     // Set up iteration for next time.
2534     // If parsing a jsr, do not grab exception handlers from the
2535     // parent scopes for this method (already got them, and they
2536     // needed to be cloned)
2537 
2538     while (cur_scope_data->parsing_jsr()) {
2539       cur_scope_data = cur_scope_data->parent();
2540     }
2541 
2542     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2543     assert(cur_state->locks_size() == 0 || cur_state->locks_size() == 1, "unlocking must be done in a catchall exception handler");
2544 
2545     prev_state = cur_state;
2546     cur_state = cur_state->caller_state();
2547     cur_scope_data = cur_scope_data->parent();
2548     scope_count++;
2549   } while (cur_scope_data != NULL);
2550 
2551   return exception_handlers;
2552 }
2553 
2554 
2555 // Helper class for simplifying Phis.
2556 class PhiSimplifier : public BlockClosure {
2557  private:
2558   bool _has_substitutions;
2559   Value simplify(Value v);
2560 
2561  public:
2562   PhiSimplifier(BlockBegin* start) : _has_substitutions(false) {
2563     start->iterate_preorder(this);
2564     if (_has_substitutions) {
2565       SubstitutionResolver sr(start);
2566     }
2567   }
2568   void block_do(BlockBegin* b);
2569   bool has_substitutions() const { return _has_substitutions; }
2570 };
2571 
2572 
2573 Value PhiSimplifier::simplify(Value v) {
2574   Phi* phi = v->as_Phi();
2575 
2576   if (phi == NULL) {
2577     // no phi function
2578     return v;
2579   } else if (v->has_subst()) {
2580     // already substituted; subst can be phi itself -> simplify
2581     return simplify(v->subst());
2582   } else if (phi->is_set(Phi::cannot_simplify)) {
2583     // already tried to simplify phi before
2584     return phi;
2585   } else if (phi->is_set(Phi::visited)) {
2586     // break cycles in phi functions
2587     return phi;
2588   } else if (phi->type()->is_illegal()) {
2589     // illegal phi functions are ignored anyway
2590     return phi;
2591 
2592   } else {
2593     // mark phi function as processed to break cycles in phi functions
2594     phi->set(Phi::visited);
2595 
2596     // simplify x = [y, x] and x = [y, y] to y
2597     Value subst = NULL;
2598     int opd_count = phi->operand_count();
2599     for (int i = 0; i < opd_count; i++) {
2600       Value opd = phi->operand_at(i);
2601       assert(opd != NULL, "Operand must exist!");
2602 
2603       if (opd->type()->is_illegal()) {
2604         // if one operand is illegal, the entire phi function is illegal
2605         phi->make_illegal();
2606         phi->clear(Phi::visited);
2607         return phi;
2608       }
2609 
2610       Value new_opd = simplify(opd);
2611       assert(new_opd != NULL, "Simplified operand must exist!");
2612 
2613       if (new_opd != phi && new_opd != subst) {
2614         if (subst == NULL) {
2615           subst = new_opd;
2616         } else {
2617           // no simplification possible
2618           phi->set(Phi::cannot_simplify);
2619           phi->clear(Phi::visited);
2620           return phi;
2621         }
2622       }
2623     }
2624 
2625     // sucessfully simplified phi function
2626     assert(subst != NULL, "illegal phi function");
2627     _has_substitutions = true;
2628     phi->clear(Phi::visited);
2629     phi->set_subst(subst);
2630 
2631 #ifndef PRODUCT
2632     if (PrintPhiFunctions) {
2633       tty->print_cr("simplified phi function %c%d to %c%d (Block B%d)", phi->type()->tchar(), phi->id(), subst->type()->tchar(), subst->id(), phi->block()->block_id());
2634     }
2635 #endif
2636 
2637     return subst;
2638   }
2639 }
2640 
2641 
2642 void PhiSimplifier::block_do(BlockBegin* b) {
2643   for_each_phi_fun(b, phi,
2644     simplify(phi);
2645   );
2646 
2647 #ifdef ASSERT
2648   for_each_phi_fun(b, phi,
2649                    assert(phi->operand_count() != 1 || phi->subst() != phi || phi->is_illegal(), "missed trivial simplification");
2650   );
2651 
2652   ValueStack* state = b->state()->caller_state();
2653   for_each_state_value(state, value,
2654     Phi* phi = value->as_Phi();
2655     assert(phi == NULL || phi->block() != b, "must not have phi function to simplify in caller state");
2656   );
2657 #endif
2658 }
2659 
2660 // This method is called after all blocks are filled with HIR instructions
2661 // It eliminates all Phi functions of the form x = [y, y] and x = [y, x]
2662 void GraphBuilder::eliminate_redundant_phis(BlockBegin* start) {
2663   PhiSimplifier simplifier(start);
2664 }
2665 
2666 
2667 void GraphBuilder::connect_to_end(BlockBegin* beg) {
2668   // setup iteration
2669   kill_all();
2670   _block = beg;
2671   _state = beg->state()->copy_for_parsing();
2672   _last  = beg;
2673   iterate_bytecodes_for_block(beg->bci());
2674 }
2675 
2676 
2677 BlockEnd* GraphBuilder::iterate_bytecodes_for_block(int bci) {
2678 #ifndef PRODUCT
2679   if (PrintIRDuringConstruction) {
2680     tty->cr();
2681     InstructionPrinter ip;
2682     ip.print_instr(_block); tty->cr();
2683     ip.print_stack(_block->state()); tty->cr();
2684     ip.print_inline_level(_block);
2685     ip.print_head();
2686     tty->print_cr("locals size: %d stack size: %d", state()->locals_size(), state()->stack_size());
2687   }
2688 #endif
2689   _skip_block = false;
2690   assert(state() != NULL, "ValueStack missing!");
2691   CompileLog* log = compilation()->log();
2692   ciBytecodeStream s(method());
2693   s.reset_to_bci(bci);
2694   int prev_bci = bci;
2695   scope_data()->set_stream(&s);
2696   // iterate
2697   Bytecodes::Code code = Bytecodes::_illegal;
2698   bool push_exception = false;
2699 
2700   if (block()->is_set(BlockBegin::exception_entry_flag) && block()->next() == NULL) {
2701     // first thing in the exception entry block should be the exception object.
2702     push_exception = true;
2703   }
2704 
2705   bool ignore_return = scope_data()->ignore_return();
2706 
2707   while (!bailed_out() && last()->as_BlockEnd() == NULL &&
2708          (code = stream()->next()) != ciBytecodeStream::EOBC() &&
2709          (block_at(s.cur_bci()) == NULL || block_at(s.cur_bci()) == block())) {
2710     assert(state()->kind() == ValueStack::Parsing, "invalid state kind");
2711 
2712     if (log != NULL)
2713       log->set_context("bc code='%d' bci='%d'", (int)code, s.cur_bci());
2714 
2715     // Check for active jsr during OSR compilation
2716     if (compilation()->is_osr_compile()
2717         && scope()->is_top_scope()
2718         && parsing_jsr()
2719         && s.cur_bci() == compilation()->osr_bci()) {
2720       bailout("OSR not supported while a jsr is active");
2721     }
2722 
2723     if (push_exception) {
2724       apush(append(new ExceptionObject()));
2725       push_exception = false;
2726     }
2727 
2728     // handle bytecode
2729     switch (code) {
2730       case Bytecodes::_nop            : /* nothing to do */ break;
2731       case Bytecodes::_aconst_null    : apush(append(new Constant(objectNull            ))); break;
2732       case Bytecodes::_iconst_m1      : ipush(append(new Constant(new IntConstant   (-1)))); break;
2733       case Bytecodes::_iconst_0       : ipush(append(new Constant(intZero               ))); break;
2734       case Bytecodes::_iconst_1       : ipush(append(new Constant(intOne                ))); break;
2735       case Bytecodes::_iconst_2       : ipush(append(new Constant(new IntConstant   ( 2)))); break;
2736       case Bytecodes::_iconst_3       : ipush(append(new Constant(new IntConstant   ( 3)))); break;
2737       case Bytecodes::_iconst_4       : ipush(append(new Constant(new IntConstant   ( 4)))); break;
2738       case Bytecodes::_iconst_5       : ipush(append(new Constant(new IntConstant   ( 5)))); break;
2739       case Bytecodes::_lconst_0       : lpush(append(new Constant(new LongConstant  ( 0)))); break;
2740       case Bytecodes::_lconst_1       : lpush(append(new Constant(new LongConstant  ( 1)))); break;
2741       case Bytecodes::_fconst_0       : fpush(append(new Constant(new FloatConstant ( 0)))); break;
2742       case Bytecodes::_fconst_1       : fpush(append(new Constant(new FloatConstant ( 1)))); break;
2743       case Bytecodes::_fconst_2       : fpush(append(new Constant(new FloatConstant ( 2)))); break;
2744       case Bytecodes::_dconst_0       : dpush(append(new Constant(new DoubleConstant( 0)))); break;
2745       case Bytecodes::_dconst_1       : dpush(append(new Constant(new DoubleConstant( 1)))); break;
2746       case Bytecodes::_bipush         : ipush(append(new Constant(new IntConstant(((signed char*)s.cur_bcp())[1])))); break;
2747       case Bytecodes::_sipush         : ipush(append(new Constant(new IntConstant((short)Bytes::get_Java_u2(s.cur_bcp()+1))))); break;
2748       case Bytecodes::_ldc            : // fall through
2749       case Bytecodes::_ldc_w          : // fall through
2750       case Bytecodes::_ldc2_w         : load_constant(); break;
2751       case Bytecodes::_iload          : load_local(intType     , s.get_index()); break;
2752       case Bytecodes::_lload          : load_local(longType    , s.get_index()); break;
2753       case Bytecodes::_fload          : load_local(floatType   , s.get_index()); break;
2754       case Bytecodes::_dload          : load_local(doubleType  , s.get_index()); break;
2755       case Bytecodes::_aload          : load_local(instanceType, s.get_index()); break;
2756       case Bytecodes::_iload_0        : load_local(intType   , 0); break;
2757       case Bytecodes::_iload_1        : load_local(intType   , 1); break;
2758       case Bytecodes::_iload_2        : load_local(intType   , 2); break;
2759       case Bytecodes::_iload_3        : load_local(intType   , 3); break;
2760       case Bytecodes::_lload_0        : load_local(longType  , 0); break;
2761       case Bytecodes::_lload_1        : load_local(longType  , 1); break;
2762       case Bytecodes::_lload_2        : load_local(longType  , 2); break;
2763       case Bytecodes::_lload_3        : load_local(longType  , 3); break;
2764       case Bytecodes::_fload_0        : load_local(floatType , 0); break;
2765       case Bytecodes::_fload_1        : load_local(floatType , 1); break;
2766       case Bytecodes::_fload_2        : load_local(floatType , 2); break;
2767       case Bytecodes::_fload_3        : load_local(floatType , 3); break;
2768       case Bytecodes::_dload_0        : load_local(doubleType, 0); break;
2769       case Bytecodes::_dload_1        : load_local(doubleType, 1); break;
2770       case Bytecodes::_dload_2        : load_local(doubleType, 2); break;
2771       case Bytecodes::_dload_3        : load_local(doubleType, 3); break;
2772       case Bytecodes::_aload_0        : load_local(objectType, 0); break;
2773       case Bytecodes::_aload_1        : load_local(objectType, 1); break;
2774       case Bytecodes::_aload_2        : load_local(objectType, 2); break;
2775       case Bytecodes::_aload_3        : load_local(objectType, 3); break;
2776       case Bytecodes::_iaload         : load_indexed(T_INT   ); break;
2777       case Bytecodes::_laload         : load_indexed(T_LONG  ); break;
2778       case Bytecodes::_faload         : load_indexed(T_FLOAT ); break;
2779       case Bytecodes::_daload         : load_indexed(T_DOUBLE); break;
2780       case Bytecodes::_aaload         : load_indexed(T_OBJECT); break;
2781       case Bytecodes::_baload         : load_indexed(T_BYTE  ); break;
2782       case Bytecodes::_caload         : load_indexed(T_CHAR  ); break;
2783       case Bytecodes::_saload         : load_indexed(T_SHORT ); break;
2784       case Bytecodes::_istore         : store_local(intType   , s.get_index()); break;
2785       case Bytecodes::_lstore         : store_local(longType  , s.get_index()); break;
2786       case Bytecodes::_fstore         : store_local(floatType , s.get_index()); break;
2787       case Bytecodes::_dstore         : store_local(doubleType, s.get_index()); break;
2788       case Bytecodes::_astore         : store_local(objectType, s.get_index()); break;
2789       case Bytecodes::_istore_0       : store_local(intType   , 0); break;
2790       case Bytecodes::_istore_1       : store_local(intType   , 1); break;
2791       case Bytecodes::_istore_2       : store_local(intType   , 2); break;
2792       case Bytecodes::_istore_3       : store_local(intType   , 3); break;
2793       case Bytecodes::_lstore_0       : store_local(longType  , 0); break;
2794       case Bytecodes::_lstore_1       : store_local(longType  , 1); break;
2795       case Bytecodes::_lstore_2       : store_local(longType  , 2); break;
2796       case Bytecodes::_lstore_3       : store_local(longType  , 3); break;
2797       case Bytecodes::_fstore_0       : store_local(floatType , 0); break;
2798       case Bytecodes::_fstore_1       : store_local(floatType , 1); break;
2799       case Bytecodes::_fstore_2       : store_local(floatType , 2); break;
2800       case Bytecodes::_fstore_3       : store_local(floatType , 3); break;
2801       case Bytecodes::_dstore_0       : store_local(doubleType, 0); break;
2802       case Bytecodes::_dstore_1       : store_local(doubleType, 1); break;
2803       case Bytecodes::_dstore_2       : store_local(doubleType, 2); break;
2804       case Bytecodes::_dstore_3       : store_local(doubleType, 3); break;
2805       case Bytecodes::_astore_0       : store_local(objectType, 0); break;
2806       case Bytecodes::_astore_1       : store_local(objectType, 1); break;
2807       case Bytecodes::_astore_2       : store_local(objectType, 2); break;
2808       case Bytecodes::_astore_3       : store_local(objectType, 3); break;
2809       case Bytecodes::_iastore        : store_indexed(T_INT   ); break;
2810       case Bytecodes::_lastore        : store_indexed(T_LONG  ); break;
2811       case Bytecodes::_fastore        : store_indexed(T_FLOAT ); break;
2812       case Bytecodes::_dastore        : store_indexed(T_DOUBLE); break;
2813       case Bytecodes::_aastore        : store_indexed(T_OBJECT); break;
2814       case Bytecodes::_bastore        : store_indexed(T_BYTE  ); break;
2815       case Bytecodes::_castore        : store_indexed(T_CHAR  ); break;
2816       case Bytecodes::_sastore        : store_indexed(T_SHORT ); break;
2817       case Bytecodes::_pop            : // fall through
2818       case Bytecodes::_pop2           : // fall through
2819       case Bytecodes::_dup            : // fall through
2820       case Bytecodes::_dup_x1         : // fall through
2821       case Bytecodes::_dup_x2         : // fall through
2822       case Bytecodes::_dup2           : // fall through
2823       case Bytecodes::_dup2_x1        : // fall through
2824       case Bytecodes::_dup2_x2        : // fall through
2825       case Bytecodes::_swap           : stack_op(code); break;
2826       case Bytecodes::_iadd           : arithmetic_op(intType   , code); break;
2827       case Bytecodes::_ladd           : arithmetic_op(longType  , code); break;
2828       case Bytecodes::_fadd           : arithmetic_op(floatType , code); break;
2829       case Bytecodes::_dadd           : arithmetic_op(doubleType, code); break;
2830       case Bytecodes::_isub           : arithmetic_op(intType   , code); break;
2831       case Bytecodes::_lsub           : arithmetic_op(longType  , code); break;
2832       case Bytecodes::_fsub           : arithmetic_op(floatType , code); break;
2833       case Bytecodes::_dsub           : arithmetic_op(doubleType, code); break;
2834       case Bytecodes::_imul           : arithmetic_op(intType   , code); break;
2835       case Bytecodes::_lmul           : arithmetic_op(longType  , code); break;
2836       case Bytecodes::_fmul           : arithmetic_op(floatType , code); break;
2837       case Bytecodes::_dmul           : arithmetic_op(doubleType, code); break;
2838       case Bytecodes::_idiv           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
2839       case Bytecodes::_ldiv           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
2840       case Bytecodes::_fdiv           : arithmetic_op(floatType , code); break;
2841       case Bytecodes::_ddiv           : arithmetic_op(doubleType, code); break;
2842       case Bytecodes::_irem           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
2843       case Bytecodes::_lrem           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
2844       case Bytecodes::_frem           : arithmetic_op(floatType , code); break;
2845       case Bytecodes::_drem           : arithmetic_op(doubleType, code); break;
2846       case Bytecodes::_ineg           : negate_op(intType   ); break;
2847       case Bytecodes::_lneg           : negate_op(longType  ); break;
2848       case Bytecodes::_fneg           : negate_op(floatType ); break;
2849       case Bytecodes::_dneg           : negate_op(doubleType); break;
2850       case Bytecodes::_ishl           : shift_op(intType , code); break;
2851       case Bytecodes::_lshl           : shift_op(longType, code); break;
2852       case Bytecodes::_ishr           : shift_op(intType , code); break;
2853       case Bytecodes::_lshr           : shift_op(longType, code); break;
2854       case Bytecodes::_iushr          : shift_op(intType , code); break;
2855       case Bytecodes::_lushr          : shift_op(longType, code); break;
2856       case Bytecodes::_iand           : logic_op(intType , code); break;
2857       case Bytecodes::_land           : logic_op(longType, code); break;
2858       case Bytecodes::_ior            : logic_op(intType , code); break;
2859       case Bytecodes::_lor            : logic_op(longType, code); break;
2860       case Bytecodes::_ixor           : logic_op(intType , code); break;
2861       case Bytecodes::_lxor           : logic_op(longType, code); break;
2862       case Bytecodes::_iinc           : increment(); break;
2863       case Bytecodes::_i2l            : convert(code, T_INT   , T_LONG  ); break;
2864       case Bytecodes::_i2f            : convert(code, T_INT   , T_FLOAT ); break;
2865       case Bytecodes::_i2d            : convert(code, T_INT   , T_DOUBLE); break;
2866       case Bytecodes::_l2i            : convert(code, T_LONG  , T_INT   ); break;
2867       case Bytecodes::_l2f            : convert(code, T_LONG  , T_FLOAT ); break;
2868       case Bytecodes::_l2d            : convert(code, T_LONG  , T_DOUBLE); break;
2869       case Bytecodes::_f2i            : convert(code, T_FLOAT , T_INT   ); break;
2870       case Bytecodes::_f2l            : convert(code, T_FLOAT , T_LONG  ); break;
2871       case Bytecodes::_f2d            : convert(code, T_FLOAT , T_DOUBLE); break;
2872       case Bytecodes::_d2i            : convert(code, T_DOUBLE, T_INT   ); break;
2873       case Bytecodes::_d2l            : convert(code, T_DOUBLE, T_LONG  ); break;
2874       case Bytecodes::_d2f            : convert(code, T_DOUBLE, T_FLOAT ); break;
2875       case Bytecodes::_i2b            : convert(code, T_INT   , T_BYTE  ); break;
2876       case Bytecodes::_i2c            : convert(code, T_INT   , T_CHAR  ); break;
2877       case Bytecodes::_i2s            : convert(code, T_INT   , T_SHORT ); break;
2878       case Bytecodes::_lcmp           : compare_op(longType  , code); break;
2879       case Bytecodes::_fcmpl          : compare_op(floatType , code); break;
2880       case Bytecodes::_fcmpg          : compare_op(floatType , code); break;
2881       case Bytecodes::_dcmpl          : compare_op(doubleType, code); break;
2882       case Bytecodes::_dcmpg          : compare_op(doubleType, code); break;
2883       case Bytecodes::_ifeq           : if_zero(intType   , If::eql); break;
2884       case Bytecodes::_ifne           : if_zero(intType   , If::neq); break;
2885       case Bytecodes::_iflt           : if_zero(intType   , If::lss); break;
2886       case Bytecodes::_ifge           : if_zero(intType   , If::geq); break;
2887       case Bytecodes::_ifgt           : if_zero(intType   , If::gtr); break;
2888       case Bytecodes::_ifle           : if_zero(intType   , If::leq); break;
2889       case Bytecodes::_if_icmpeq      : if_same(intType   , If::eql); break;
2890       case Bytecodes::_if_icmpne      : if_same(intType   , If::neq); break;
2891       case Bytecodes::_if_icmplt      : if_same(intType   , If::lss); break;
2892       case Bytecodes::_if_icmpge      : if_same(intType   , If::geq); break;
2893       case Bytecodes::_if_icmpgt      : if_same(intType   , If::gtr); break;
2894       case Bytecodes::_if_icmple      : if_same(intType   , If::leq); break;
2895       case Bytecodes::_if_acmpeq      : if_same(objectType, If::eql); break;
2896       case Bytecodes::_if_acmpne      : if_same(objectType, If::neq); break;
2897       case Bytecodes::_goto           : _goto(s.cur_bci(), s.get_dest()); break;
2898       case Bytecodes::_jsr            : jsr(s.get_dest()); break;
2899       case Bytecodes::_ret            : ret(s.get_index()); break;
2900       case Bytecodes::_tableswitch    : table_switch(); break;
2901       case Bytecodes::_lookupswitch   : lookup_switch(); break;
2902       case Bytecodes::_ireturn        : method_return(ipop(), ignore_return); break;
2903       case Bytecodes::_lreturn        : method_return(lpop(), ignore_return); break;
2904       case Bytecodes::_freturn        : method_return(fpop(), ignore_return); break;
2905       case Bytecodes::_dreturn        : method_return(dpop(), ignore_return); break;
2906       case Bytecodes::_areturn        : method_return(apop(), ignore_return); break;
2907       case Bytecodes::_return         : method_return(NULL  , ignore_return); break;
2908       case Bytecodes::_getstatic      : // fall through
2909       case Bytecodes::_putstatic      : // fall through
2910       case Bytecodes::_getfield       : // fall through
2911       case Bytecodes::_putfield       : access_field(code); break;
2912       case Bytecodes::_invokevirtual  : // fall through
2913       case Bytecodes::_invokespecial  : // fall through
2914       case Bytecodes::_invokestatic   : // fall through
2915       case Bytecodes::_invokedynamic  : // fall through
2916       case Bytecodes::_invokeinterface: invoke(code); break;
2917       case Bytecodes::_new            : new_instance(s.get_index_u2()); break;
2918       case Bytecodes::_newarray       : new_type_array(); break;
2919       case Bytecodes::_anewarray      : new_object_array(); break;
2920       case Bytecodes::_arraylength    : { ValueStack* state_before = copy_state_for_exception(); ipush(append(new ArrayLength(apop(), state_before))); break; }
2921       case Bytecodes::_athrow         : throw_op(s.cur_bci()); break;
2922       case Bytecodes::_checkcast      : check_cast(s.get_index_u2()); break;
2923       case Bytecodes::_instanceof     : instance_of(s.get_index_u2()); break;
2924       case Bytecodes::_monitorenter   : monitorenter(apop(), s.cur_bci()); break;
2925       case Bytecodes::_monitorexit    : monitorexit (apop(), s.cur_bci()); break;
2926       case Bytecodes::_wide           : ShouldNotReachHere(); break;
2927       case Bytecodes::_multianewarray : new_multi_array(s.cur_bcp()[3]); break;
2928       case Bytecodes::_ifnull         : if_null(objectType, If::eql); break;
2929       case Bytecodes::_ifnonnull      : if_null(objectType, If::neq); break;
2930       case Bytecodes::_goto_w         : _goto(s.cur_bci(), s.get_far_dest()); break;
2931       case Bytecodes::_jsr_w          : jsr(s.get_far_dest()); break;
2932       case Bytecodes::_breakpoint     : BAILOUT_("concurrent setting of breakpoint", NULL);
2933       default                         : ShouldNotReachHere(); break;
2934     }
2935 
2936     if (log != NULL)
2937       log->clear_context(); // skip marker if nothing was printed
2938 
2939     // save current bci to setup Goto at the end
2940     prev_bci = s.cur_bci();
2941 
2942   }
2943   CHECK_BAILOUT_(NULL);
2944   // stop processing of this block (see try_inline_full)
2945   if (_skip_block) {
2946     _skip_block = false;
2947     assert(_last && _last->as_BlockEnd(), "");
2948     return _last->as_BlockEnd();
2949   }
2950   // if there are any, check if last instruction is a BlockEnd instruction
2951   BlockEnd* end = last()->as_BlockEnd();
2952   if (end == NULL) {
2953     // all blocks must end with a BlockEnd instruction => add a Goto
2954     end = new Goto(block_at(s.cur_bci()), false);
2955     append(end);
2956   }
2957   assert(end == last()->as_BlockEnd(), "inconsistency");
2958 
2959   assert(end->state() != NULL, "state must already be present");
2960   assert(end->as_Return() == NULL || end->as_Throw() == NULL || end->state()->stack_size() == 0, "stack not needed for return and throw");
2961 
2962   // connect to begin & set state
2963   // NOTE that inlining may have changed the block we are parsing
2964   block()->set_end(end);
2965   // propagate state
2966   for (int i = end->number_of_sux() - 1; i >= 0; i--) {
2967     BlockBegin* sux = end->sux_at(i);
2968     assert(sux->is_predecessor(block()), "predecessor missing");
2969     // be careful, bailout if bytecodes are strange
2970     if (!sux->try_merge(end->state())) BAILOUT_("block join failed", NULL);
2971     scope_data()->add_to_work_list(end->sux_at(i));
2972   }
2973 
2974   scope_data()->set_stream(NULL);
2975 
2976   // done
2977   return end;
2978 }
2979 
2980 
2981 void GraphBuilder::iterate_all_blocks(bool start_in_current_block_for_inlining) {
2982   do {
2983     if (start_in_current_block_for_inlining && !bailed_out()) {
2984       iterate_bytecodes_for_block(0);
2985       start_in_current_block_for_inlining = false;
2986     } else {
2987       BlockBegin* b;
2988       while ((b = scope_data()->remove_from_work_list()) != NULL) {
2989         if (!b->is_set(BlockBegin::was_visited_flag)) {
2990           if (b->is_set(BlockBegin::osr_entry_flag)) {
2991             // we're about to parse the osr entry block, so make sure
2992             // we setup the OSR edge leading into this block so that
2993             // Phis get setup correctly.
2994             setup_osr_entry_block();
2995             // this is no longer the osr entry block, so clear it.
2996             b->clear(BlockBegin::osr_entry_flag);
2997           }
2998           b->set(BlockBegin::was_visited_flag);
2999           connect_to_end(b);
3000         }
3001       }
3002     }
3003   } while (!bailed_out() && !scope_data()->is_work_list_empty());
3004 }
3005 
3006 
3007 bool GraphBuilder::_can_trap      [Bytecodes::number_of_java_codes];
3008 
3009 void GraphBuilder::initialize() {
3010   // the following bytecodes are assumed to potentially
3011   // throw exceptions in compiled code - note that e.g.
3012   // monitorexit & the return bytecodes do not throw
3013   // exceptions since monitor pairing proved that they
3014   // succeed (if monitor pairing succeeded)
3015   Bytecodes::Code can_trap_list[] =
3016     { Bytecodes::_ldc
3017     , Bytecodes::_ldc_w
3018     , Bytecodes::_ldc2_w
3019     , Bytecodes::_iaload
3020     , Bytecodes::_laload
3021     , Bytecodes::_faload
3022     , Bytecodes::_daload
3023     , Bytecodes::_aaload
3024     , Bytecodes::_baload
3025     , Bytecodes::_caload
3026     , Bytecodes::_saload
3027     , Bytecodes::_iastore
3028     , Bytecodes::_lastore
3029     , Bytecodes::_fastore
3030     , Bytecodes::_dastore
3031     , Bytecodes::_aastore
3032     , Bytecodes::_bastore
3033     , Bytecodes::_castore
3034     , Bytecodes::_sastore
3035     , Bytecodes::_idiv
3036     , Bytecodes::_ldiv
3037     , Bytecodes::_irem
3038     , Bytecodes::_lrem
3039     , Bytecodes::_getstatic
3040     , Bytecodes::_putstatic
3041     , Bytecodes::_getfield
3042     , Bytecodes::_putfield
3043     , Bytecodes::_invokevirtual
3044     , Bytecodes::_invokespecial
3045     , Bytecodes::_invokestatic
3046     , Bytecodes::_invokedynamic
3047     , Bytecodes::_invokeinterface
3048     , Bytecodes::_new
3049     , Bytecodes::_newarray
3050     , Bytecodes::_anewarray
3051     , Bytecodes::_arraylength
3052     , Bytecodes::_athrow
3053     , Bytecodes::_checkcast
3054     , Bytecodes::_instanceof
3055     , Bytecodes::_monitorenter
3056     , Bytecodes::_multianewarray
3057     };
3058 
3059   // inititialize trap tables
3060   for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
3061     _can_trap[i] = false;
3062   }
3063   // set standard trap info
3064   for (uint j = 0; j < ARRAY_SIZE(can_trap_list); j++) {
3065     _can_trap[can_trap_list[j]] = true;
3066   }
3067 }
3068 
3069 
3070 BlockBegin* GraphBuilder::header_block(BlockBegin* entry, BlockBegin::Flag f, ValueStack* state) {
3071   assert(entry->is_set(f), "entry/flag mismatch");
3072   // create header block
3073   BlockBegin* h = new BlockBegin(entry->bci());
3074   h->set_depth_first_number(0);
3075 
3076   Value l = h;
3077   BlockEnd* g = new Goto(entry, false);
3078   l->set_next(g, entry->bci());
3079   h->set_end(g);
3080   h->set(f);
3081   // setup header block end state
3082   ValueStack* s = state->copy(ValueStack::StateAfter, entry->bci()); // can use copy since stack is empty (=> no phis)
3083   assert(s->stack_is_empty(), "must have empty stack at entry point");
3084   g->set_state(s);
3085   return h;
3086 }
3087 
3088 
3089 
3090 BlockBegin* GraphBuilder::setup_start_block(int osr_bci, BlockBegin* std_entry, BlockBegin* osr_entry, ValueStack* state) {
3091   BlockBegin* start = new BlockBegin(0);
3092 
3093   // This code eliminates the empty start block at the beginning of
3094   // each method.  Previously, each method started with the
3095   // start-block created below, and this block was followed by the
3096   // header block that was always empty.  This header block is only
3097   // necessary if std_entry is also a backward branch target because
3098   // then phi functions may be necessary in the header block.  It's
3099   // also necessary when profiling so that there's a single block that
3100   // can increment the the counters.
3101   // In addition, with range check elimination, we may need a valid block
3102   // that dominates all the rest to insert range predicates.
3103   BlockBegin* new_header_block;
3104   if (std_entry->number_of_preds() > 0 || is_profiling() || RangeCheckElimination) {
3105     new_header_block = header_block(std_entry, BlockBegin::std_entry_flag, state);
3106   } else {
3107     new_header_block = std_entry;
3108   }
3109 
3110   // setup start block (root for the IR graph)
3111   Base* base =
3112     new Base(
3113       new_header_block,
3114       osr_entry
3115     );
3116   start->set_next(base, 0);
3117   start->set_end(base);
3118   // create & setup state for start block
3119   start->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3120   base->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3121 
3122   if (base->std_entry()->state() == NULL) {
3123     // setup states for header blocks
3124     base->std_entry()->merge(state);
3125   }
3126 
3127   assert(base->std_entry()->state() != NULL, "");
3128   return start;
3129 }
3130 
3131 
3132 void GraphBuilder::setup_osr_entry_block() {
3133   assert(compilation()->is_osr_compile(), "only for osrs");
3134 
3135   int osr_bci = compilation()->osr_bci();
3136   ciBytecodeStream s(method());
3137   s.reset_to_bci(osr_bci);
3138   s.next();
3139   scope_data()->set_stream(&s);
3140 
3141   // create a new block to be the osr setup code
3142   _osr_entry = new BlockBegin(osr_bci);
3143   _osr_entry->set(BlockBegin::osr_entry_flag);
3144   _osr_entry->set_depth_first_number(0);
3145   BlockBegin* target = bci2block()->at(osr_bci);
3146   assert(target != NULL && target->is_set(BlockBegin::osr_entry_flag), "must be there");
3147   // the osr entry has no values for locals
3148   ValueStack* state = target->state()->copy();
3149   _osr_entry->set_state(state);
3150 
3151   kill_all();
3152   _block = _osr_entry;
3153   _state = _osr_entry->state()->copy();
3154   assert(_state->bci() == osr_bci, "mismatch");
3155   _last  = _osr_entry;
3156   Value e = append(new OsrEntry());
3157   e->set_needs_null_check(false);
3158 
3159   // OSR buffer is
3160   //
3161   // locals[nlocals-1..0]
3162   // monitors[number_of_locks-1..0]
3163   //
3164   // locals is a direct copy of the interpreter frame so in the osr buffer
3165   // so first slot in the local array is the last local from the interpreter
3166   // and last slot is local[0] (receiver) from the interpreter
3167   //
3168   // Similarly with locks. The first lock slot in the osr buffer is the nth lock
3169   // from the interpreter frame, the nth lock slot in the osr buffer is 0th lock
3170   // in the interpreter frame (the method lock if a sync method)
3171 
3172   // Initialize monitors in the compiled activation.
3173 
3174   int index;
3175   Value local;
3176 
3177   // find all the locals that the interpreter thinks contain live oops
3178   const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci);
3179 
3180   // compute the offset into the locals so that we can treat the buffer
3181   // as if the locals were still in the interpreter frame
3182   int locals_offset = BytesPerWord * (method()->max_locals() - 1);
3183   for_each_local_value(state, index, local) {
3184     int offset = locals_offset - (index + local->type()->size() - 1) * BytesPerWord;
3185     Value get;
3186     if (local->type()->is_object_kind() && !live_oops.at(index)) {
3187       // The interpreter thinks this local is dead but the compiler
3188       // doesn't so pretend that the interpreter passed in null.
3189       get = append(new Constant(objectNull));
3190     } else {
3191       Value off_val = append(new Constant(new IntConstant(offset)));
3192       get = append(new UnsafeGet(as_BasicType(local->type()), e,
3193                                  off_val,
3194                                  false/*is_volatile*/,
3195                                  true/*is_raw*/));
3196     }
3197     _state->store_local(index, get);
3198   }
3199 
3200   // the storage for the OSR buffer is freed manually in the LIRGenerator.
3201 
3202   assert(state->caller_state() == NULL, "should be top scope");
3203   state->clear_locals();
3204   Goto* g = new Goto(target, false);
3205   append(g);
3206   _osr_entry->set_end(g);
3207   target->merge(_osr_entry->end()->state());
3208 
3209   scope_data()->set_stream(NULL);
3210 }
3211 
3212 
3213 ValueStack* GraphBuilder::state_at_entry() {
3214   ValueStack* state = new ValueStack(scope(), NULL);
3215 
3216   // Set up locals for receiver
3217   int idx = 0;
3218   if (!method()->is_static()) {
3219     // we should always see the receiver
3220     state->store_local(idx, new Local(method()->holder(), objectType, idx, true));
3221     idx = 1;
3222   }
3223 
3224   // Set up locals for incoming arguments
3225   ciSignature* sig = method()->signature();
3226   for (int i = 0; i < sig->count(); i++) {
3227     ciType* type = sig->type_at(i);
3228     BasicType basic_type = type->basic_type();
3229     // don't allow T_ARRAY to propagate into locals types
3230     if (is_reference_type(basic_type)) basic_type = T_OBJECT;
3231     ValueType* vt = as_ValueType(basic_type);
3232     state->store_local(idx, new Local(type, vt, idx, false));
3233     idx += type->size();
3234   }
3235 
3236   // lock synchronized method
3237   if (method()->is_synchronized()) {
3238     state->lock(NULL);
3239   }
3240 
3241   return state;
3242 }
3243 
3244 
3245 GraphBuilder::GraphBuilder(Compilation* compilation, IRScope* scope)
3246   : _scope_data(NULL)
3247   , _compilation(compilation)
3248   , _memory(new MemoryBuffer())
3249   , _inline_bailout_msg(NULL)
3250   , _instruction_count(0)
3251   , _osr_entry(NULL)
3252 {
3253   int osr_bci = compilation->osr_bci();
3254 
3255   // determine entry points and bci2block mapping
3256   BlockListBuilder blm(compilation, scope, osr_bci);
3257   CHECK_BAILOUT();
3258 
3259   BlockList* bci2block = blm.bci2block();
3260   BlockBegin* start_block = bci2block->at(0);
3261 
3262   push_root_scope(scope, bci2block, start_block);
3263 
3264   // setup state for std entry
3265   _initial_state = state_at_entry();
3266   start_block->merge(_initial_state);
3267 
3268   // End nulls still exist here
3269 
3270   // complete graph
3271   _vmap        = new ValueMap();
3272   switch (scope->method()->intrinsic_id()) {
3273   case vmIntrinsics::_dabs          : // fall through
3274   case vmIntrinsics::_dsqrt         : // fall through
3275   case vmIntrinsics::_dsqrt_strict  : // fall through
3276   case vmIntrinsics::_dsin          : // fall through
3277   case vmIntrinsics::_dcos          : // fall through
3278   case vmIntrinsics::_dtan          : // fall through
3279   case vmIntrinsics::_dlog          : // fall through
3280   case vmIntrinsics::_dlog10        : // fall through
3281   case vmIntrinsics::_dexp          : // fall through
3282   case vmIntrinsics::_dpow          : // fall through
3283     {
3284       // Compiles where the root method is an intrinsic need a special
3285       // compilation environment because the bytecodes for the method
3286       // shouldn't be parsed during the compilation, only the special
3287       // Intrinsic node should be emitted.  If this isn't done the the
3288       // code for the inlined version will be different than the root
3289       // compiled version which could lead to monotonicity problems on
3290       // intel.
3291       if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3292         BAILOUT("failed to inline intrinsic, method not annotated");
3293       }
3294 
3295       // Set up a stream so that appending instructions works properly.
3296       ciBytecodeStream s(scope->method());
3297       s.reset_to_bci(0);
3298       scope_data()->set_stream(&s);
3299       s.next();
3300 
3301       // setup the initial block state
3302       _block = start_block;
3303       _state = start_block->state()->copy_for_parsing();
3304       _last  = start_block;
3305       load_local(doubleType, 0);
3306       if (scope->method()->intrinsic_id() == vmIntrinsics::_dpow) {
3307         load_local(doubleType, 2);
3308       }
3309 
3310       // Emit the intrinsic node.
3311       bool result = try_inline_intrinsics(scope->method());
3312       if (!result) BAILOUT("failed to inline intrinsic");
3313       method_return(dpop());
3314 
3315       // connect the begin and end blocks and we're all done.
3316       BlockEnd* end = last()->as_BlockEnd();
3317       block()->set_end(end);
3318       break;
3319     }
3320 
3321   case vmIntrinsics::_Reference_get:
3322     {
3323       {
3324         // With java.lang.ref.reference.get() we must go through the
3325         // intrinsic - when G1 is enabled - even when get() is the root
3326         // method of the compile so that, if necessary, the value in
3327         // the referent field of the reference object gets recorded by
3328         // the pre-barrier code.
3329         // Specifically, if G1 is enabled, the value in the referent
3330         // field is recorded by the G1 SATB pre barrier. This will
3331         // result in the referent being marked live and the reference
3332         // object removed from the list of discovered references during
3333         // reference processing.
3334         if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3335           BAILOUT("failed to inline intrinsic, method not annotated");
3336         }
3337 
3338         // Also we need intrinsic to prevent commoning reads from this field
3339         // across safepoint since GC can change its value.
3340 
3341         // Set up a stream so that appending instructions works properly.
3342         ciBytecodeStream s(scope->method());
3343         s.reset_to_bci(0);
3344         scope_data()->set_stream(&s);
3345         s.next();
3346 
3347         // setup the initial block state
3348         _block = start_block;
3349         _state = start_block->state()->copy_for_parsing();
3350         _last  = start_block;
3351         load_local(objectType, 0);
3352 
3353         // Emit the intrinsic node.
3354         bool result = try_inline_intrinsics(scope->method());
3355         if (!result) BAILOUT("failed to inline intrinsic");
3356         method_return(apop());
3357 
3358         // connect the begin and end blocks and we're all done.
3359         BlockEnd* end = last()->as_BlockEnd();
3360         block()->set_end(end);
3361         break;
3362       }
3363       // Otherwise, fall thru
3364     }
3365 
3366   default:
3367     scope_data()->add_to_work_list(start_block);
3368     iterate_all_blocks();
3369     break;
3370   }
3371   CHECK_BAILOUT();
3372 
3373 # ifdef ASSERT
3374   //All blocks reachable from start_block have _end != NULL
3375   {
3376     BlockList processed;
3377     BlockList to_go;
3378     to_go.append(start_block);
3379     while(to_go.length() > 0) {
3380       BlockBegin* current = to_go.pop();
3381       assert(current != NULL, "Should not happen.");
3382       assert(current->end() != NULL, "All blocks reachable from start_block should have end() != NULL.");
3383       processed.append(current);
3384       for(int i = 0; i < current->number_of_sux(); i++) {
3385         BlockBegin* s = current->sux_at(i);
3386         if (!processed.contains(s)) {
3387           to_go.append(s);
3388         }
3389       }
3390     }
3391   }
3392 #endif // ASSERT
3393 
3394   _start = setup_start_block(osr_bci, start_block, _osr_entry, _initial_state);
3395 
3396   eliminate_redundant_phis(_start);
3397 
3398   NOT_PRODUCT(if (PrintValueNumbering && Verbose) print_stats());
3399   // for osr compile, bailout if some requirements are not fulfilled
3400   if (osr_bci != -1) {
3401     BlockBegin* osr_block = blm.bci2block()->at(osr_bci);
3402     if (!osr_block->is_set(BlockBegin::was_visited_flag)) {
3403       BAILOUT("osr entry must have been visited for osr compile");
3404     }
3405 
3406     // check if osr entry point has empty stack - we cannot handle non-empty stacks at osr entry points
3407     if (!osr_block->state()->stack_is_empty()) {
3408       BAILOUT("stack not empty at OSR entry point");
3409     }
3410   }
3411 #ifndef PRODUCT
3412   if (PrintCompilation && Verbose) tty->print_cr("Created %d Instructions", _instruction_count);
3413 #endif
3414 }
3415 
3416 
3417 ValueStack* GraphBuilder::copy_state_before() {
3418   return copy_state_before_with_bci(bci());
3419 }
3420 
3421 ValueStack* GraphBuilder::copy_state_exhandling() {
3422   return copy_state_exhandling_with_bci(bci());
3423 }
3424 
3425 ValueStack* GraphBuilder::copy_state_for_exception() {
3426   return copy_state_for_exception_with_bci(bci());
3427 }
3428 
3429 ValueStack* GraphBuilder::copy_state_before_with_bci(int bci) {
3430   return state()->copy(ValueStack::StateBefore, bci);
3431 }
3432 
3433 ValueStack* GraphBuilder::copy_state_exhandling_with_bci(int bci) {
3434   if (!has_handler()) return NULL;
3435   return state()->copy(ValueStack::StateBefore, bci);
3436 }
3437 
3438 ValueStack* GraphBuilder::copy_state_for_exception_with_bci(int bci) {
3439   ValueStack* s = copy_state_exhandling_with_bci(bci);
3440   if (s == NULL) {
3441     if (_compilation->env()->should_retain_local_variables()) {
3442       s = state()->copy(ValueStack::ExceptionState, bci);
3443     } else {
3444       s = state()->copy(ValueStack::EmptyExceptionState, bci);
3445     }
3446   }
3447   return s;
3448 }
3449 
3450 int GraphBuilder::recursive_inline_level(ciMethod* cur_callee) const {
3451   int recur_level = 0;
3452   for (IRScope* s = scope(); s != NULL; s = s->caller()) {
3453     if (s->method() == cur_callee) {
3454       ++recur_level;
3455     }
3456   }
3457   return recur_level;
3458 }
3459 
3460 
3461 bool GraphBuilder::try_inline(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
3462   const char* msg = NULL;
3463 
3464   // clear out any existing inline bailout condition
3465   clear_inline_bailout();
3466 
3467   // exclude methods we don't want to inline
3468   msg = should_not_inline(callee);
3469   if (msg != NULL) {
3470     print_inlining(callee, msg, /*success*/ false);
3471     return false;
3472   }
3473 
3474   // method handle invokes
3475   if (callee->is_method_handle_intrinsic()) {
3476     if (try_method_handle_inline(callee, ignore_return)) {
3477       if (callee->has_reserved_stack_access()) {
3478         compilation()->set_has_reserved_stack_access(true);
3479       }
3480       return true;
3481     }
3482     return false;
3483   }
3484 
3485   // handle intrinsics
3486   if (callee->intrinsic_id() != vmIntrinsics::_none &&
3487       callee->check_intrinsic_candidate()) {
3488     if (try_inline_intrinsics(callee, ignore_return)) {
3489       print_inlining(callee, "intrinsic");
3490       if (callee->has_reserved_stack_access()) {
3491         compilation()->set_has_reserved_stack_access(true);
3492       }
3493       return true;
3494     }
3495     // try normal inlining
3496   }
3497 
3498   // certain methods cannot be parsed at all
3499   msg = check_can_parse(callee);
3500   if (msg != NULL) {
3501     print_inlining(callee, msg, /*success*/ false);
3502     return false;
3503   }
3504 
3505   // If bytecode not set use the current one.
3506   if (bc == Bytecodes::_illegal) {
3507     bc = code();
3508   }
3509   if (try_inline_full(callee, holder_known, ignore_return, bc, receiver)) {
3510     if (callee->has_reserved_stack_access()) {
3511       compilation()->set_has_reserved_stack_access(true);
3512     }
3513     return true;
3514   }
3515 
3516   // Entire compilation could fail during try_inline_full call.
3517   // In that case printing inlining decision info is useless.
3518   if (!bailed_out())
3519     print_inlining(callee, _inline_bailout_msg, /*success*/ false);
3520 
3521   return false;
3522 }
3523 
3524 
3525 const char* GraphBuilder::check_can_parse(ciMethod* callee) const {
3526   // Certain methods cannot be parsed at all:
3527   if ( callee->is_native())            return "native method";
3528   if ( callee->is_abstract())          return "abstract method";
3529   if (!callee->can_be_parsed())        return "cannot be parsed";
3530   return NULL;
3531 }
3532 
3533 // negative filter: should callee NOT be inlined?  returns NULL, ok to inline, or rejection msg
3534 const char* GraphBuilder::should_not_inline(ciMethod* callee) const {
3535   if ( compilation()->directive()->should_not_inline(callee)) return "disallowed by CompileCommand";
3536   if ( callee->dont_inline())          return "don't inline by annotation";
3537   return NULL;
3538 }
3539 
3540 void GraphBuilder::build_graph_for_intrinsic(ciMethod* callee, bool ignore_return) {
3541   vmIntrinsics::ID id = callee->intrinsic_id();
3542   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
3543 
3544   // Some intrinsics need special IR nodes.
3545   switch(id) {
3546   case vmIntrinsics::_getReference           : append_unsafe_get(callee, T_OBJECT,  false); return;
3547   case vmIntrinsics::_getBoolean             : append_unsafe_get(callee, T_BOOLEAN, false); return;
3548   case vmIntrinsics::_getByte                : append_unsafe_get(callee, T_BYTE,    false); return;
3549   case vmIntrinsics::_getShort               : append_unsafe_get(callee, T_SHORT,   false); return;
3550   case vmIntrinsics::_getChar                : append_unsafe_get(callee, T_CHAR,    false); return;
3551   case vmIntrinsics::_getInt                 : append_unsafe_get(callee, T_INT,     false); return;
3552   case vmIntrinsics::_getLong                : append_unsafe_get(callee, T_LONG,    false); return;
3553   case vmIntrinsics::_getFloat               : append_unsafe_get(callee, T_FLOAT,   false); return;
3554   case vmIntrinsics::_getDouble              : append_unsafe_get(callee, T_DOUBLE,  false); return;
3555   case vmIntrinsics::_putReference           : append_unsafe_put(callee, T_OBJECT,  false); return;
3556   case vmIntrinsics::_putBoolean             : append_unsafe_put(callee, T_BOOLEAN, false); return;
3557   case vmIntrinsics::_putByte                : append_unsafe_put(callee, T_BYTE,    false); return;
3558   case vmIntrinsics::_putShort               : append_unsafe_put(callee, T_SHORT,   false); return;
3559   case vmIntrinsics::_putChar                : append_unsafe_put(callee, T_CHAR,    false); return;
3560   case vmIntrinsics::_putInt                 : append_unsafe_put(callee, T_INT,     false); return;
3561   case vmIntrinsics::_putLong                : append_unsafe_put(callee, T_LONG,    false); return;
3562   case vmIntrinsics::_putFloat               : append_unsafe_put(callee, T_FLOAT,   false); return;
3563   case vmIntrinsics::_putDouble              : append_unsafe_put(callee, T_DOUBLE,  false); return;
3564   case vmIntrinsics::_getShortUnaligned      : append_unsafe_get(callee, T_SHORT,   false); return;
3565   case vmIntrinsics::_getCharUnaligned       : append_unsafe_get(callee, T_CHAR,    false); return;
3566   case vmIntrinsics::_getIntUnaligned        : append_unsafe_get(callee, T_INT,     false); return;
3567   case vmIntrinsics::_getLongUnaligned       : append_unsafe_get(callee, T_LONG,    false); return;
3568   case vmIntrinsics::_putShortUnaligned      : append_unsafe_put(callee, T_SHORT,   false); return;
3569   case vmIntrinsics::_putCharUnaligned       : append_unsafe_put(callee, T_CHAR,    false); return;
3570   case vmIntrinsics::_putIntUnaligned        : append_unsafe_put(callee, T_INT,     false); return;
3571   case vmIntrinsics::_putLongUnaligned       : append_unsafe_put(callee, T_LONG,    false); return;
3572   case vmIntrinsics::_getReferenceVolatile   : append_unsafe_get(callee, T_OBJECT,  true); return;
3573   case vmIntrinsics::_getBooleanVolatile     : append_unsafe_get(callee, T_BOOLEAN, true); return;
3574   case vmIntrinsics::_getByteVolatile        : append_unsafe_get(callee, T_BYTE,    true); return;
3575   case vmIntrinsics::_getShortVolatile       : append_unsafe_get(callee, T_SHORT,   true); return;
3576   case vmIntrinsics::_getCharVolatile        : append_unsafe_get(callee, T_CHAR,    true); return;
3577   case vmIntrinsics::_getIntVolatile         : append_unsafe_get(callee, T_INT,     true); return;
3578   case vmIntrinsics::_getLongVolatile        : append_unsafe_get(callee, T_LONG,    true); return;
3579   case vmIntrinsics::_getFloatVolatile       : append_unsafe_get(callee, T_FLOAT,   true); return;
3580   case vmIntrinsics::_getDoubleVolatile      : append_unsafe_get(callee, T_DOUBLE,  true); return;
3581   case vmIntrinsics::_putReferenceVolatile   : append_unsafe_put(callee, T_OBJECT,  true); return;
3582   case vmIntrinsics::_putBooleanVolatile     : append_unsafe_put(callee, T_BOOLEAN, true); return;
3583   case vmIntrinsics::_putByteVolatile        : append_unsafe_put(callee, T_BYTE,    true); return;
3584   case vmIntrinsics::_putShortVolatile       : append_unsafe_put(callee, T_SHORT,   true); return;
3585   case vmIntrinsics::_putCharVolatile        : append_unsafe_put(callee, T_CHAR,    true); return;
3586   case vmIntrinsics::_putIntVolatile         : append_unsafe_put(callee, T_INT,     true); return;
3587   case vmIntrinsics::_putLongVolatile        : append_unsafe_put(callee, T_LONG,    true); return;
3588   case vmIntrinsics::_putFloatVolatile       : append_unsafe_put(callee, T_FLOAT,   true); return;
3589   case vmIntrinsics::_putDoubleVolatile      : append_unsafe_put(callee, T_DOUBLE,  true); return;
3590   case vmIntrinsics::_compareAndSetLong:
3591   case vmIntrinsics::_compareAndSetInt:
3592   case vmIntrinsics::_compareAndSetReference : append_unsafe_CAS(callee); return;
3593   case vmIntrinsics::_getAndAddInt:
3594   case vmIntrinsics::_getAndAddLong          : append_unsafe_get_and_set(callee, true); return;
3595   case vmIntrinsics::_getAndSetInt           :
3596   case vmIntrinsics::_getAndSetLong          :
3597   case vmIntrinsics::_getAndSetReference     : append_unsafe_get_and_set(callee, false); return;
3598   case vmIntrinsics::_getCharStringU         : append_char_access(callee, false); return;
3599   case vmIntrinsics::_putCharStringU         : append_char_access(callee, true); return;
3600   default:
3601     break;
3602   }
3603 
3604   // create intrinsic node
3605   const bool has_receiver = !callee->is_static();
3606   ValueType* result_type = as_ValueType(callee->return_type());
3607   ValueStack* state_before = copy_state_for_exception();
3608 
3609   Values* args = state()->pop_arguments(callee->arg_size());
3610 
3611   if (is_profiling()) {
3612     // Don't profile in the special case where the root method
3613     // is the intrinsic
3614     if (callee != method()) {
3615       // Note that we'd collect profile data in this method if we wanted it.
3616       compilation()->set_would_profile(true);
3617       if (profile_calls()) {
3618         Value recv = NULL;
3619         if (has_receiver) {
3620           recv = args->at(0);
3621           null_check(recv);
3622         }
3623         profile_call(callee, recv, NULL, collect_args_for_profiling(args, callee, true), true);
3624       }
3625     }
3626   }
3627 
3628   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(),
3629                                     args, has_receiver, state_before,
3630                                     vmIntrinsics::preserves_state(id),
3631                                     vmIntrinsics::can_trap(id));
3632   // append instruction & push result
3633   Value value = append_split(result);
3634   if (result_type != voidType && !ignore_return) {
3635     push(result_type, value);
3636   }
3637 
3638   if (callee != method() && profile_return() && result_type->is_object_kind()) {
3639     profile_return_type(result, callee);
3640   }
3641 }
3642 
3643 bool GraphBuilder::try_inline_intrinsics(ciMethod* callee, bool ignore_return) {
3644   // For calling is_intrinsic_available we need to transition to
3645   // the '_thread_in_vm' state because is_intrinsic_available()
3646   // accesses critical VM-internal data.
3647   bool is_available = false;
3648   {
3649     VM_ENTRY_MARK;
3650     methodHandle mh(THREAD, callee->get_Method());
3651     is_available = _compilation->compiler()->is_intrinsic_available(mh, _compilation->directive());
3652   }
3653 
3654   if (!is_available) {
3655     if (!InlineNatives) {
3656       // Return false and also set message that the inlining of
3657       // intrinsics has been disabled in general.
3658       INLINE_BAILOUT("intrinsic method inlining disabled");
3659     } else {
3660       return false;
3661     }
3662   }
3663   build_graph_for_intrinsic(callee, ignore_return);
3664   return true;
3665 }
3666 
3667 
3668 bool GraphBuilder::try_inline_jsr(int jsr_dest_bci) {
3669   // Introduce a new callee continuation point - all Ret instructions
3670   // will be replaced with Gotos to this point.
3671   BlockBegin* cont = block_at(next_bci());
3672   assert(cont != NULL, "continuation must exist (BlockListBuilder starts a new block after a jsr");
3673 
3674   // Note: can not assign state to continuation yet, as we have to
3675   // pick up the state from the Ret instructions.
3676 
3677   // Push callee scope
3678   push_scope_for_jsr(cont, jsr_dest_bci);
3679 
3680   // Temporarily set up bytecode stream so we can append instructions
3681   // (only using the bci of this stream)
3682   scope_data()->set_stream(scope_data()->parent()->stream());
3683 
3684   BlockBegin* jsr_start_block = block_at(jsr_dest_bci);
3685   assert(jsr_start_block != NULL, "jsr start block must exist");
3686   assert(!jsr_start_block->is_set(BlockBegin::was_visited_flag), "should not have visited jsr yet");
3687   Goto* goto_sub = new Goto(jsr_start_block, false);
3688   // Must copy state to avoid wrong sharing when parsing bytecodes
3689   assert(jsr_start_block->state() == NULL, "should have fresh jsr starting block");
3690   jsr_start_block->set_state(copy_state_before_with_bci(jsr_dest_bci));
3691   append(goto_sub);
3692   _block->set_end(goto_sub);
3693   _last = _block = jsr_start_block;
3694 
3695   // Clear out bytecode stream
3696   scope_data()->set_stream(NULL);
3697 
3698   scope_data()->add_to_work_list(jsr_start_block);
3699 
3700   // Ready to resume parsing in subroutine
3701   iterate_all_blocks();
3702 
3703   // If we bailed out during parsing, return immediately (this is bad news)
3704   CHECK_BAILOUT_(false);
3705 
3706   // Detect whether the continuation can actually be reached. If not,
3707   // it has not had state set by the join() operations in
3708   // iterate_bytecodes_for_block()/ret() and we should not touch the
3709   // iteration state. The calling activation of
3710   // iterate_bytecodes_for_block will then complete normally.
3711   if (cont->state() != NULL) {
3712     if (!cont->is_set(BlockBegin::was_visited_flag)) {
3713       // add continuation to work list instead of parsing it immediately
3714       scope_data()->parent()->add_to_work_list(cont);
3715     }
3716   }
3717 
3718   assert(jsr_continuation() == cont, "continuation must not have changed");
3719   assert(!jsr_continuation()->is_set(BlockBegin::was_visited_flag) ||
3720          jsr_continuation()->is_set(BlockBegin::parser_loop_header_flag),
3721          "continuation can only be visited in case of backward branches");
3722   assert(_last && _last->as_BlockEnd(), "block must have end");
3723 
3724   // continuation is in work list, so end iteration of current block
3725   _skip_block = true;
3726   pop_scope_for_jsr();
3727 
3728   return true;
3729 }
3730 
3731 
3732 // Inline the entry of a synchronized method as a monitor enter and
3733 // register the exception handler which releases the monitor if an
3734 // exception is thrown within the callee. Note that the monitor enter
3735 // cannot throw an exception itself, because the receiver is
3736 // guaranteed to be non-null by the explicit null check at the
3737 // beginning of inlining.
3738 void GraphBuilder::inline_sync_entry(Value lock, BlockBegin* sync_handler) {
3739   assert(lock != NULL && sync_handler != NULL, "lock or handler missing");
3740 
3741   monitorenter(lock, SynchronizationEntryBCI);
3742   assert(_last->as_MonitorEnter() != NULL, "monitor enter expected");
3743   _last->set_needs_null_check(false);
3744 
3745   sync_handler->set(BlockBegin::exception_entry_flag);
3746   sync_handler->set(BlockBegin::is_on_work_list_flag);
3747 
3748   ciExceptionHandler* desc = new ciExceptionHandler(method()->holder(), 0, method()->code_size(), -1, 0);
3749   XHandler* h = new XHandler(desc);
3750   h->set_entry_block(sync_handler);
3751   scope_data()->xhandlers()->append(h);
3752   scope_data()->set_has_handler();
3753 }
3754 
3755 
3756 // If an exception is thrown and not handled within an inlined
3757 // synchronized method, the monitor must be released before the
3758 // exception is rethrown in the outer scope. Generate the appropriate
3759 // instructions here.
3760 void GraphBuilder::fill_sync_handler(Value lock, BlockBegin* sync_handler, bool default_handler) {
3761   BlockBegin* orig_block = _block;
3762   ValueStack* orig_state = _state;
3763   Instruction* orig_last = _last;
3764   _last = _block = sync_handler;
3765   _state = sync_handler->state()->copy();
3766 
3767   assert(sync_handler != NULL, "handler missing");
3768   assert(!sync_handler->is_set(BlockBegin::was_visited_flag), "is visited here");
3769 
3770   assert(lock != NULL || default_handler, "lock or handler missing");
3771 
3772   XHandler* h = scope_data()->xhandlers()->remove_last();
3773   assert(h->entry_block() == sync_handler, "corrupt list of handlers");
3774 
3775   block()->set(BlockBegin::was_visited_flag);
3776   Value exception = append_with_bci(new ExceptionObject(), SynchronizationEntryBCI);
3777   assert(exception->is_pinned(), "must be");
3778 
3779   int bci = SynchronizationEntryBCI;
3780   if (compilation()->env()->dtrace_method_probes()) {
3781     // Report exit from inline methods.  We don't have a stream here
3782     // so pass an explicit bci of SynchronizationEntryBCI.
3783     Values* args = new Values(1);
3784     args->push(append_with_bci(new Constant(new MethodConstant(method())), bci));
3785     append_with_bci(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args), bci);
3786   }
3787 
3788   if (lock) {
3789     assert(state()->locks_size() > 0 && state()->lock_at(state()->locks_size() - 1) == lock, "lock is missing");
3790     if (!lock->is_linked()) {
3791       lock = append_with_bci(lock, bci);
3792     }
3793 
3794     // exit the monitor in the context of the synchronized method
3795     monitorexit(lock, bci);
3796 
3797     // exit the context of the synchronized method
3798     if (!default_handler) {
3799       pop_scope();
3800       bci = _state->caller_state()->bci();
3801       _state = _state->caller_state()->copy_for_parsing();
3802     }
3803   }
3804 
3805   // perform the throw as if at the the call site
3806   apush(exception);
3807   throw_op(bci);
3808 
3809   BlockEnd* end = last()->as_BlockEnd();
3810   block()->set_end(end);
3811 
3812   _block = orig_block;
3813   _state = orig_state;
3814   _last = orig_last;
3815 }
3816 
3817 
3818 bool GraphBuilder::try_inline_full(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
3819   assert(!callee->is_native(), "callee must not be native");
3820   if (CompilationPolicy::should_not_inline(compilation()->env(), callee)) {
3821     INLINE_BAILOUT("inlining prohibited by policy");
3822   }
3823   // first perform tests of things it's not possible to inline
3824   if (callee->has_exception_handlers() &&
3825       !InlineMethodsWithExceptionHandlers) INLINE_BAILOUT("callee has exception handlers");
3826   if (callee->is_synchronized() &&
3827       !InlineSynchronizedMethods         ) INLINE_BAILOUT("callee is synchronized");
3828   if (!callee->holder()->is_linked())      INLINE_BAILOUT("callee's klass not linked yet");
3829   if (bc == Bytecodes::_invokestatic &&
3830       !callee->holder()->is_initialized()) INLINE_BAILOUT("callee's klass not initialized yet");
3831   if (!callee->has_balanced_monitors())    INLINE_BAILOUT("callee's monitors do not match");
3832 
3833   // Proper inlining of methods with jsrs requires a little more work.
3834   if (callee->has_jsrs()                 ) INLINE_BAILOUT("jsrs not handled properly by inliner yet");
3835 
3836   if (is_profiling() && !callee->ensure_method_data()) {
3837     INLINE_BAILOUT("mdo allocation failed");
3838   }
3839 
3840   const bool is_invokedynamic = (bc == Bytecodes::_invokedynamic);
3841   const bool has_receiver = (bc != Bytecodes::_invokestatic && !is_invokedynamic);
3842 
3843   const int args_base = state()->stack_size() - callee->arg_size();
3844   assert(args_base >= 0, "stack underflow during inlining");
3845 
3846   Value recv = NULL;
3847   if (has_receiver) {
3848     assert(!callee->is_static(), "callee must not be static");
3849     assert(callee->arg_size() > 0, "must have at least a receiver");
3850 
3851     recv = state()->stack_at(args_base);
3852     if (recv->is_null_obj()) {
3853       INLINE_BAILOUT("receiver is always null");
3854     }
3855   }
3856 
3857   // now perform tests that are based on flag settings
3858   bool inlinee_by_directive = compilation()->directive()->should_inline(callee);
3859   if (callee->force_inline() || inlinee_by_directive) {
3860     if (inline_level() > MaxForceInlineLevel                      ) INLINE_BAILOUT("MaxForceInlineLevel");
3861     if (recursive_inline_level(callee) > C1MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");
3862 
3863     const char* msg = "";
3864     if (callee->force_inline())  msg = "force inline by annotation";
3865     if (inlinee_by_directive)    msg = "force inline by CompileCommand";
3866     print_inlining(callee, msg);
3867   } else {
3868     // use heuristic controls on inlining
3869     if (inline_level() > C1MaxInlineLevel                       ) INLINE_BAILOUT("inlining too deep");
3870     int callee_recursive_level = recursive_inline_level(callee);
3871     if (callee_recursive_level > C1MaxRecursiveInlineLevel      ) INLINE_BAILOUT("recursive inlining too deep");
3872     if (callee->code_size_for_inlining() > max_inline_size()    ) INLINE_BAILOUT("callee is too large");
3873     // Additional condition to limit stack usage for non-recursive calls.
3874     if ((callee_recursive_level == 0) &&
3875         (callee->max_stack() + callee->max_locals() - callee->size_of_parameters() > C1InlineStackLimit)) {
3876       INLINE_BAILOUT("callee uses too much stack");
3877     }
3878 
3879     // don't inline throwable methods unless the inlining tree is rooted in a throwable class
3880     if (callee->name() == ciSymbols::object_initializer_name() &&
3881         callee->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
3882       // Throwable constructor call
3883       IRScope* top = scope();
3884       while (top->caller() != NULL) {
3885         top = top->caller();
3886       }
3887       if (!top->method()->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
3888         INLINE_BAILOUT("don't inline Throwable constructors");
3889       }
3890     }
3891 
3892     if (compilation()->env()->num_inlined_bytecodes() > DesiredMethodLimit) {
3893       INLINE_BAILOUT("total inlining greater than DesiredMethodLimit");
3894     }
3895     // printing
3896     print_inlining(callee, "inline", /*success*/ true);
3897   }
3898 
3899   assert(bc != Bytecodes::_invokestatic || callee->holder()->is_initialized(), "required");
3900 
3901   // NOTE: Bailouts from this point on, which occur at the
3902   // GraphBuilder level, do not cause bailout just of the inlining but
3903   // in fact of the entire compilation.
3904 
3905   BlockBegin* orig_block = block();
3906 
3907   // Insert null check if necessary
3908   if (has_receiver) {
3909     // note: null check must happen even if first instruction of callee does
3910     //       an implicit null check since the callee is in a different scope
3911     //       and we must make sure exception handling does the right thing
3912     null_check(recv);
3913   }
3914 
3915   if (is_profiling()) {
3916     // Note that we'd collect profile data in this method if we wanted it.
3917     // this may be redundant here...
3918     compilation()->set_would_profile(true);
3919 
3920     if (profile_calls()) {
3921       int start = 0;
3922       Values* obj_args = args_list_for_profiling(callee, start, has_receiver);
3923       if (obj_args != NULL) {
3924         int s = obj_args->max_length();
3925         // if called through method handle invoke, some arguments may have been popped
3926         for (int i = args_base+start, j = 0; j < obj_args->max_length() && i < state()->stack_size(); ) {
3927           Value v = state()->stack_at_inc(i);
3928           if (v->type()->is_object_kind()) {
3929             obj_args->push(v);
3930             j++;
3931           }
3932         }
3933         check_args_for_profiling(obj_args, s);
3934       }
3935       profile_call(callee, recv, holder_known ? callee->holder() : NULL, obj_args, true);
3936     }
3937   }
3938 
3939   // Introduce a new callee continuation point - if the callee has
3940   // more than one return instruction or the return does not allow
3941   // fall-through of control flow, all return instructions of the
3942   // callee will need to be replaced by Goto's pointing to this
3943   // continuation point.
3944   BlockBegin* cont = block_at(next_bci());
3945   bool continuation_existed = true;
3946   if (cont == NULL) {
3947     cont = new BlockBegin(next_bci());
3948     // low number so that continuation gets parsed as early as possible
3949     cont->set_depth_first_number(0);
3950     if (PrintInitialBlockList) {
3951       tty->print_cr("CFG: created block %d (bci %d) as continuation for inline at bci %d",
3952                     cont->block_id(), cont->bci(), bci());
3953     }
3954     continuation_existed = false;
3955   }
3956   // Record number of predecessors of continuation block before
3957   // inlining, to detect if inlined method has edges to its
3958   // continuation after inlining.
3959   int continuation_preds = cont->number_of_preds();
3960 
3961   // Push callee scope
3962   push_scope(callee, cont);
3963 
3964   // the BlockListBuilder for the callee could have bailed out
3965   if (bailed_out())
3966       return false;
3967 
3968   // Temporarily set up bytecode stream so we can append instructions
3969   // (only using the bci of this stream)
3970   scope_data()->set_stream(scope_data()->parent()->stream());
3971 
3972   // Pass parameters into callee state: add assignments
3973   // note: this will also ensure that all arguments are computed before being passed
3974   ValueStack* callee_state = state();
3975   ValueStack* caller_state = state()->caller_state();
3976   for (int i = args_base; i < caller_state->stack_size(); ) {
3977     const int arg_no = i - args_base;
3978     Value arg = caller_state->stack_at_inc(i);
3979     store_local(callee_state, arg, arg_no);
3980   }
3981 
3982   // Remove args from stack.
3983   // Note that we preserve locals state in case we can use it later
3984   // (see use of pop_scope() below)
3985   caller_state->truncate_stack(args_base);
3986   assert(callee_state->stack_size() == 0, "callee stack must be empty");
3987 
3988   Value lock = NULL;
3989   BlockBegin* sync_handler = NULL;
3990 
3991   // Inline the locking of the receiver if the callee is synchronized
3992   if (callee->is_synchronized()) {
3993     lock = callee->is_static() ? append(new Constant(new InstanceConstant(callee->holder()->java_mirror())))
3994                                : state()->local_at(0);
3995     sync_handler = new BlockBegin(SynchronizationEntryBCI);
3996     inline_sync_entry(lock, sync_handler);
3997   }
3998 
3999   if (compilation()->env()->dtrace_method_probes()) {
4000     Values* args = new Values(1);
4001     args->push(append(new Constant(new MethodConstant(method()))));
4002     append(new RuntimeCall(voidType, "dtrace_method_entry", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), args));
4003   }
4004 
4005   if (profile_inlined_calls()) {
4006     profile_invocation(callee, copy_state_before_with_bci(SynchronizationEntryBCI));
4007   }
4008 
4009   BlockBegin* callee_start_block = block_at(0);
4010   if (callee_start_block != NULL) {
4011     assert(callee_start_block->is_set(BlockBegin::parser_loop_header_flag), "must be loop header");
4012     Goto* goto_callee = new Goto(callee_start_block, false);
4013     // The state for this goto is in the scope of the callee, so use
4014     // the entry bci for the callee instead of the call site bci.
4015     append_with_bci(goto_callee, 0);
4016     _block->set_end(goto_callee);
4017     callee_start_block->merge(callee_state);
4018 
4019     _last = _block = callee_start_block;
4020 
4021     scope_data()->add_to_work_list(callee_start_block);
4022   }
4023 
4024   // Clear out bytecode stream
4025   scope_data()->set_stream(NULL);
4026   scope_data()->set_ignore_return(ignore_return);
4027 
4028   CompileLog* log = compilation()->log();
4029   if (log != NULL) log->head("parse method='%d'", log->identify(callee));
4030 
4031   // Ready to resume parsing in callee (either in the same block we
4032   // were in before or in the callee's start block)
4033   iterate_all_blocks(callee_start_block == NULL);
4034 
4035   if (log != NULL) log->done("parse");
4036 
4037   // If we bailed out during parsing, return immediately (this is bad news)
4038   if (bailed_out())
4039       return false;
4040 
4041   // iterate_all_blocks theoretically traverses in random order; in
4042   // practice, we have only traversed the continuation if we are
4043   // inlining into a subroutine
4044   assert(continuation_existed ||
4045          !continuation()->is_set(BlockBegin::was_visited_flag),
4046          "continuation should not have been parsed yet if we created it");
4047 
4048   // At this point we are almost ready to return and resume parsing of
4049   // the caller back in the GraphBuilder. The only thing we want to do
4050   // first is an optimization: during parsing of the callee we
4051   // generated at least one Goto to the continuation block. If we
4052   // generated exactly one, and if the inlined method spanned exactly
4053   // one block (and we didn't have to Goto its entry), then we snip
4054   // off the Goto to the continuation, allowing control to fall
4055   // through back into the caller block and effectively performing
4056   // block merging. This allows load elimination and CSE to take place
4057   // across multiple callee scopes if they are relatively simple, and
4058   // is currently essential to making inlining profitable.
4059   if (num_returns() == 1
4060       && block() == orig_block
4061       && block() == inline_cleanup_block()) {
4062     _last  = inline_cleanup_return_prev();
4063     _state = inline_cleanup_state();
4064   } else if (continuation_preds == cont->number_of_preds()) {
4065     // Inlining caused that the instructions after the invoke in the
4066     // caller are not reachable any more. So skip filling this block
4067     // with instructions!
4068     assert(cont == continuation(), "");
4069     assert(_last && _last->as_BlockEnd(), "");
4070     _skip_block = true;
4071   } else {
4072     // Resume parsing in continuation block unless it was already parsed.
4073     // Note that if we don't change _last here, iteration in
4074     // iterate_bytecodes_for_block will stop when we return.
4075     if (!continuation()->is_set(BlockBegin::was_visited_flag)) {
4076       // add continuation to work list instead of parsing it immediately
4077       assert(_last && _last->as_BlockEnd(), "");
4078       scope_data()->parent()->add_to_work_list(continuation());
4079       _skip_block = true;
4080     }
4081   }
4082 
4083   // Fill the exception handler for synchronized methods with instructions
4084   if (callee->is_synchronized() && sync_handler->state() != NULL) {
4085     fill_sync_handler(lock, sync_handler);
4086   } else {
4087     pop_scope();
4088   }
4089 
4090   compilation()->notice_inlined_method(callee);
4091 
4092   return true;
4093 }
4094 
4095 
4096 bool GraphBuilder::try_method_handle_inline(ciMethod* callee, bool ignore_return) {
4097   ValueStack* state_before = copy_state_before();
4098   vmIntrinsics::ID iid = callee->intrinsic_id();
4099   switch (iid) {
4100   case vmIntrinsics::_invokeBasic:
4101     {
4102       // get MethodHandle receiver
4103       const int args_base = state()->stack_size() - callee->arg_size();
4104       ValueType* type = state()->stack_at(args_base)->type();
4105       if (type->is_constant()) {
4106         ciMethod* target = type->as_ObjectType()->constant_value()->as_method_handle()->get_vmtarget();
4107         // We don't do CHA here so only inline static and statically bindable methods.
4108         if (target->is_static() || target->can_be_statically_bound()) {
4109           if (ciMethod::is_consistent_info(callee, target)) {
4110             Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4111             ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4112             if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4113               return true;
4114             }
4115           } else {
4116             print_inlining(target, "signatures mismatch", /*success*/ false);
4117           }
4118         } else {
4119           print_inlining(target, "not static or statically bindable", /*success*/ false);
4120         }
4121       } else {
4122         print_inlining(callee, "receiver not constant", /*success*/ false);
4123       }
4124     }
4125     break;
4126 
4127   case vmIntrinsics::_linkToVirtual:
4128   case vmIntrinsics::_linkToStatic:
4129   case vmIntrinsics::_linkToSpecial:
4130   case vmIntrinsics::_linkToInterface:
4131     {
4132       // pop MemberName argument
4133       const int args_base = state()->stack_size() - callee->arg_size();
4134       ValueType* type = apop()->type();
4135       if (type->is_constant()) {
4136         ciMethod* target = type->as_ObjectType()->constant_value()->as_member_name()->get_vmtarget();
4137         ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4138         // If the target is another method handle invoke, try to recursively get
4139         // a better target.
4140         if (target->is_method_handle_intrinsic()) {
4141           if (try_method_handle_inline(target, ignore_return)) {
4142             return true;
4143           }
4144         } else if (!ciMethod::is_consistent_info(callee, target)) {
4145           print_inlining(target, "signatures mismatch", /*success*/ false);
4146         } else {
4147           ciSignature* signature = target->signature();
4148           const int receiver_skip = target->is_static() ? 0 : 1;
4149           // Cast receiver to its type.
4150           if (!target->is_static()) {
4151             ciKlass* tk = signature->accessing_klass();
4152             Value obj = state()->stack_at(args_base);
4153             if (obj->exact_type() == NULL &&
4154                 obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4155               TypeCast* c = new TypeCast(tk, obj, state_before);
4156               append(c);
4157               state()->stack_at_put(args_base, c);
4158             }
4159           }
4160           // Cast reference arguments to its type.
4161           for (int i = 0, j = 0; i < signature->count(); i++) {
4162             ciType* t = signature->type_at(i);
4163             if (t->is_klass()) {
4164               ciKlass* tk = t->as_klass();
4165               Value obj = state()->stack_at(args_base + receiver_skip + j);
4166               if (obj->exact_type() == NULL &&
4167                   obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4168                 TypeCast* c = new TypeCast(t, obj, state_before);
4169                 append(c);
4170                 state()->stack_at_put(args_base + receiver_skip + j, c);
4171               }
4172             }
4173             j += t->size();  // long and double take two slots
4174           }
4175           // We don't do CHA here so only inline static and statically bindable methods.
4176           if (target->is_static() || target->can_be_statically_bound()) {
4177             Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4178             if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4179               return true;
4180             }
4181           } else {
4182             print_inlining(target, "not static or statically bindable", /*success*/ false);
4183           }
4184         }
4185       } else {
4186         print_inlining(callee, "MemberName not constant", /*success*/ false);
4187       }
4188     }
4189     break;
4190 
4191   case vmIntrinsics::_linkToNative:
4192     break; // TODO: NYI
4193 
4194   default:
4195     fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
4196     break;
4197   }
4198   set_state(state_before->copy_for_parsing());
4199   return false;
4200 }
4201 
4202 
4203 void GraphBuilder::inline_bailout(const char* msg) {
4204   assert(msg != NULL, "inline bailout msg must exist");
4205   _inline_bailout_msg = msg;
4206 }
4207 
4208 
4209 void GraphBuilder::clear_inline_bailout() {
4210   _inline_bailout_msg = NULL;
4211 }
4212 
4213 
4214 void GraphBuilder::push_root_scope(IRScope* scope, BlockList* bci2block, BlockBegin* start) {
4215   ScopeData* data = new ScopeData(NULL);
4216   data->set_scope(scope);
4217   data->set_bci2block(bci2block);
4218   _scope_data = data;
4219   _block = start;
4220 }
4221 
4222 
4223 void GraphBuilder::push_scope(ciMethod* callee, BlockBegin* continuation) {
4224   IRScope* callee_scope = new IRScope(compilation(), scope(), bci(), callee, -1, false);
4225   scope()->add_callee(callee_scope);
4226 
4227   BlockListBuilder blb(compilation(), callee_scope, -1);
4228   CHECK_BAILOUT();
4229 
4230   if (!blb.bci2block()->at(0)->is_set(BlockBegin::parser_loop_header_flag)) {
4231     // this scope can be inlined directly into the caller so remove
4232     // the block at bci 0.
4233     blb.bci2block()->at_put(0, NULL);
4234   }
4235 
4236   set_state(new ValueStack(callee_scope, state()->copy(ValueStack::CallerState, bci())));
4237 
4238   ScopeData* data = new ScopeData(scope_data());
4239   data->set_scope(callee_scope);
4240   data->set_bci2block(blb.bci2block());
4241   data->set_continuation(continuation);
4242   _scope_data = data;
4243 }
4244 
4245 
4246 void GraphBuilder::push_scope_for_jsr(BlockBegin* jsr_continuation, int jsr_dest_bci) {
4247   ScopeData* data = new ScopeData(scope_data());
4248   data->set_parsing_jsr();
4249   data->set_jsr_entry_bci(jsr_dest_bci);
4250   data->set_jsr_return_address_local(-1);
4251   // Must clone bci2block list as we will be mutating it in order to
4252   // properly clone all blocks in jsr region as well as exception
4253   // handlers containing rets
4254   BlockList* new_bci2block = new BlockList(bci2block()->length());
4255   new_bci2block->appendAll(bci2block());
4256   data->set_bci2block(new_bci2block);
4257   data->set_scope(scope());
4258   data->setup_jsr_xhandlers();
4259   data->set_continuation(continuation());
4260   data->set_jsr_continuation(jsr_continuation);
4261   _scope_data = data;
4262 }
4263 
4264 
4265 void GraphBuilder::pop_scope() {
4266   int number_of_locks = scope()->number_of_locks();
4267   _scope_data = scope_data()->parent();
4268   // accumulate minimum number of monitor slots to be reserved
4269   scope()->set_min_number_of_locks(number_of_locks);
4270 }
4271 
4272 
4273 void GraphBuilder::pop_scope_for_jsr() {
4274   _scope_data = scope_data()->parent();
4275 }
4276 
4277 void GraphBuilder::append_unsafe_get(ciMethod* callee, BasicType t, bool is_volatile) {
4278   Values* args = state()->pop_arguments(callee->arg_size());
4279   null_check(args->at(0));
4280   Instruction* offset = args->at(2);
4281 #ifndef _LP64
4282   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4283 #endif
4284   Instruction* op = append(new UnsafeGet(t, args->at(1), offset, is_volatile));
4285   push(op->type(), op);
4286   compilation()->set_has_unsafe_access(true);
4287 }
4288 
4289 
4290 void GraphBuilder::append_unsafe_put(ciMethod* callee, BasicType t, bool is_volatile) {
4291   Values* args = state()->pop_arguments(callee->arg_size());
4292   null_check(args->at(0));
4293   Instruction* offset = args->at(2);
4294 #ifndef _LP64
4295   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4296 #endif
4297   Value val = args->at(3);
4298   if (t == T_BOOLEAN) {
4299     Value mask = append(new Constant(new IntConstant(1)));
4300     val = append(new LogicOp(Bytecodes::_iand, val, mask));
4301   }
4302   Instruction* op = append(new UnsafePut(t, args->at(1), offset, val, is_volatile));
4303   compilation()->set_has_unsafe_access(true);
4304   kill_all();
4305 }
4306 
4307 void GraphBuilder::append_unsafe_CAS(ciMethod* callee) {
4308   ValueStack* state_before = copy_state_for_exception();
4309   ValueType* result_type = as_ValueType(callee->return_type());
4310   assert(result_type->is_int(), "int result");
4311   Values* args = state()->pop_arguments(callee->arg_size());
4312 
4313   // Pop off some args to specially handle, then push back
4314   Value newval = args->pop();
4315   Value cmpval = args->pop();
4316   Value offset = args->pop();
4317   Value src = args->pop();
4318   Value unsafe_obj = args->pop();
4319 
4320   // Separately handle the unsafe arg. It is not needed for code
4321   // generation, but must be null checked
4322   null_check(unsafe_obj);
4323 
4324 #ifndef _LP64
4325   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4326 #endif
4327 
4328   args->push(src);
4329   args->push(offset);
4330   args->push(cmpval);
4331   args->push(newval);
4332 
4333   // An unsafe CAS can alias with other field accesses, but we don't
4334   // know which ones so mark the state as no preserved.  This will
4335   // cause CSE to invalidate memory across it.
4336   bool preserves_state = false;
4337   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(), args, false, state_before, preserves_state);
4338   append_split(result);
4339   push(result_type, result);
4340   compilation()->set_has_unsafe_access(true);
4341 }
4342 
4343 void GraphBuilder::append_char_access(ciMethod* callee, bool is_store) {
4344   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
4345   // correctly requires matched array shapes.
4346   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
4347           "sanity: byte[] and char[] bases agree");
4348   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
4349           "sanity: byte[] and char[] scales agree");
4350 
4351   ValueStack* state_before = copy_state_indexed_access();
4352   compilation()->set_has_access_indexed(true);
4353   Values* args = state()->pop_arguments(callee->arg_size());
4354   Value array = args->at(0);
4355   Value index = args->at(1);
4356   if (is_store) {
4357     Value value = args->at(2);
4358     Instruction* store = append(new StoreIndexed(array, index, NULL, T_CHAR, value, state_before, false, true));
4359     store->set_flag(Instruction::NeedsRangeCheckFlag, false);
4360     _memory->store_value(value);
4361   } else {
4362     Instruction* load = append(new LoadIndexed(array, index, NULL, T_CHAR, state_before, true));
4363     load->set_flag(Instruction::NeedsRangeCheckFlag, false);
4364     push(load->type(), load);
4365   }
4366 }
4367 
4368 void GraphBuilder::print_inlining(ciMethod* callee, const char* msg, bool success) {
4369   CompileLog* log = compilation()->log();
4370   if (log != NULL) {
4371     assert(msg != NULL, "inlining msg should not be null!");
4372     if (success) {
4373       log->inline_success(msg);
4374     } else {
4375       log->inline_fail(msg);
4376     }
4377   }
4378   EventCompilerInlining event;
4379   if (event.should_commit()) {
4380     CompilerEvent::InlineEvent::post(event, compilation()->env()->task()->compile_id(), method()->get_Method(), callee, success, msg, bci());
4381   }
4382 
4383   CompileTask::print_inlining_ul(callee, scope()->level(), bci(), msg);
4384 
4385   if (!compilation()->directive()->PrintInliningOption) {
4386     return;
4387   }
4388   CompileTask::print_inlining_tty(callee, scope()->level(), bci(), msg);
4389   if (success && CIPrintMethodCodes) {
4390     callee->print_codes();
4391   }
4392 }
4393 
4394 void GraphBuilder::append_unsafe_get_and_set(ciMethod* callee, bool is_add) {
4395   Values* args = state()->pop_arguments(callee->arg_size());
4396   BasicType t = callee->return_type()->basic_type();
4397   null_check(args->at(0));
4398   Instruction* offset = args->at(2);
4399 #ifndef _LP64
4400   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4401 #endif
4402   Instruction* op = append(new UnsafeGetAndSet(t, args->at(1), offset, args->at(3), is_add));
4403   compilation()->set_has_unsafe_access(true);
4404   kill_all();
4405   push(op->type(), op);
4406 }
4407 
4408 #ifndef PRODUCT
4409 void GraphBuilder::print_stats() {
4410   vmap()->print();
4411 }
4412 #endif // PRODUCT
4413 
4414 void GraphBuilder::profile_call(ciMethod* callee, Value recv, ciKlass* known_holder, Values* obj_args, bool inlined) {
4415   assert(known_holder == NULL || (known_holder->is_instance_klass() &&
4416                                   (!known_holder->is_interface() ||
4417                                    ((ciInstanceKlass*)known_holder)->has_nonstatic_concrete_methods())), "should be non-static concrete method");
4418   if (known_holder != NULL) {
4419     if (known_holder->exact_klass() == NULL) {
4420       known_holder = compilation()->cha_exact_type(known_holder);
4421     }
4422   }
4423 
4424   append(new ProfileCall(method(), bci(), callee, recv, known_holder, obj_args, inlined));
4425 }
4426 
4427 void GraphBuilder::profile_return_type(Value ret, ciMethod* callee, ciMethod* m, int invoke_bci) {
4428   assert((m == NULL) == (invoke_bci < 0), "invalid method and invalid bci together");
4429   if (m == NULL) {
4430     m = method();
4431   }
4432   if (invoke_bci < 0) {
4433     invoke_bci = bci();
4434   }
4435   ciMethodData* md = m->method_data_or_null();
4436   ciProfileData* data = md->bci_to_data(invoke_bci);
4437   if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
4438     bool has_return = data->is_CallTypeData() ? ((ciCallTypeData*)data)->has_return() : ((ciVirtualCallTypeData*)data)->has_return();
4439     if (has_return) {
4440       append(new ProfileReturnType(m , invoke_bci, callee, ret));
4441     }
4442   }
4443 }
4444 
4445 void GraphBuilder::profile_invocation(ciMethod* callee, ValueStack* state) {
4446   append(new ProfileInvoke(callee, state));
4447 }