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