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