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