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