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