1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "c1/c1_CFGPrinter.hpp"
  27 #include "c1/c1_Canonicalizer.hpp"
  28 #include "c1/c1_Compilation.hpp"
  29 #include "c1/c1_GraphBuilder.hpp"
  30 #include "c1/c1_InstructionPrinter.hpp"
  31 #include "ci/ciCallSite.hpp"
  32 #include "ci/ciField.hpp"
  33 #include "ci/ciFlatArrayKlass.hpp"
  34 #include "ci/ciInlineKlass.hpp"
  35 #include "ci/ciKlass.hpp"
  36 #include "ci/ciMemberName.hpp"
  37 #include "ci/ciSymbols.hpp"
  38 #include "ci/ciUtilities.inline.hpp"
  39 #include "compiler/compilationPolicy.hpp"
  40 #include "compiler/compileBroker.hpp"
  41 #include "compiler/compilerEvent.hpp"
  42 #include "interpreter/bytecode.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/vm_version.hpp"
  48 #include "utilities/bitMap.inline.hpp"
  49 #include "utilities/powerOfTwo.hpp"
  50 
  51 class BlockListBuilder {
  52  private:
  53   Compilation* _compilation;
  54   IRScope*     _scope;
  55 
  56   BlockList    _blocks;                // internal list of all blocks
  57   BlockList*   _bci2block;             // mapping from bci to blocks for GraphBuilder
  58 
  59   // fields used by mark_loops
  60   ResourceBitMap _active;              // for iteration of control flow graph
  61   ResourceBitMap _visited;             // for iteration of control flow graph
  62   intArray       _loop_map;            // caches the information if a block is contained in a loop
  63   int            _next_loop_index;     // next free loop number
  64   int            _next_block_number;   // for reverse postorder numbering of blocks
  65 
  66   // accessors
  67   Compilation*  compilation() const              { return _compilation; }
  68   IRScope*      scope() const                    { return _scope; }
  69   ciMethod*     method() const                   { return scope()->method(); }
  70   XHandlers*    xhandlers() const                { return scope()->xhandlers(); }
  71 
  72   // unified bailout support
  73   void          bailout(const char* msg) const   { compilation()->bailout(msg); }
  74   bool          bailed_out() const               { return compilation()->bailed_out(); }
  75 
  76   // helper functions
  77   BlockBegin* make_block_at(int bci, BlockBegin* predecessor);
  78   void handle_exceptions(BlockBegin* current, int cur_bci);
  79   void handle_jsr(BlockBegin* current, int sr_bci, int next_bci);
  80   void store_one(BlockBegin* current, int local);
  81   void store_two(BlockBegin* current, int local);
  82   void set_entries(int osr_bci);
  83   void set_leaders();
  84 
  85   void make_loop_header(BlockBegin* block);
  86   void mark_loops();
  87   int  mark_loops(BlockBegin* b, bool in_subroutine);
  88 
  89   // debugging
  90 #ifndef PRODUCT
  91   void print();
  92 #endif
  93 
  94  public:
  95   // creation
  96   BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci);
  97 
  98   // accessors for GraphBuilder
  99   BlockList*    bci2block() const                { return _bci2block; }
 100 };
 101 
 102 
 103 // Implementation of BlockListBuilder
 104 
 105 BlockListBuilder::BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci)
 106  : _compilation(compilation)
 107  , _scope(scope)
 108  , _blocks(16)
 109  , _bci2block(new BlockList(scope->method()->code_size(), NULL))
 110  , _active()         // size not known yet
 111  , _visited()        // size not known yet
 112  , _loop_map() // size not known yet
 113  , _next_loop_index(0)
 114  , _next_block_number(0)
 115 {
 116   set_entries(osr_bci);
 117   set_leaders();
 118   CHECK_BAILOUT();
 119 
 120   mark_loops();
 121   NOT_PRODUCT(if (PrintInitialBlockList) print());
 122 
 123 #ifndef PRODUCT
 124   if (PrintCFGToFile) {
 125     stringStream title;
 126     title.print("BlockListBuilder ");
 127     scope->method()->print_name(&title);
 128     CFGPrinter::print_cfg(_bci2block, title.as_string(), false, false);
 129   }
 130 #endif
 131 }
 132 
 133 
 134 void BlockListBuilder::set_entries(int osr_bci) {
 135   // generate start blocks
 136   BlockBegin* std_entry = make_block_at(0, NULL);
 137   if (scope()->caller() == NULL) {
 138     std_entry->set(BlockBegin::std_entry_flag);
 139   }
 140   if (osr_bci != -1) {
 141     BlockBegin* osr_entry = make_block_at(osr_bci, NULL);
 142     osr_entry->set(BlockBegin::osr_entry_flag);
 143   }
 144 
 145   // generate exception entry blocks
 146   XHandlers* list = xhandlers();
 147   const int n = list->length();
 148   for (int i = 0; i < n; i++) {
 149     XHandler* h = list->handler_at(i);
 150     BlockBegin* entry = make_block_at(h->handler_bci(), NULL);
 151     entry->set(BlockBegin::exception_entry_flag);
 152     h->set_entry_block(entry);
 153   }
 154 }
 155 
 156 
 157 BlockBegin* BlockListBuilder::make_block_at(int cur_bci, BlockBegin* predecessor) {
 158   assert(method()->bci_block_start().at(cur_bci), "wrong block starts of MethodLivenessAnalyzer");
 159 
 160   BlockBegin* block = _bci2block->at(cur_bci);
 161   if (block == NULL) {
 162     block = new BlockBegin(cur_bci);
 163     block->init_stores_to_locals(method()->max_locals());
 164     _bci2block->at_put(cur_bci, block);
 165     _blocks.append(block);
 166 
 167     assert(predecessor == NULL || predecessor->bci() < cur_bci, "targets for backward branches must already exist");
 168   }
 169 
 170   if (predecessor != NULL) {
 171     if (block->is_set(BlockBegin::exception_entry_flag)) {
 172       BAILOUT_("Exception handler can be reached by both normal and exceptional control flow", block);
 173     }
 174 
 175     predecessor->add_successor(block);
 176     block->increment_total_preds();
 177   }
 178 
 179   return block;
 180 }
 181 
 182 
 183 inline void BlockListBuilder::store_one(BlockBegin* current, int local) {
 184   current->stores_to_locals().set_bit(local);
 185 }
 186 inline void BlockListBuilder::store_two(BlockBegin* current, int local) {
 187   store_one(current, local);
 188   store_one(current, local + 1);
 189 }
 190 
 191 
 192 void BlockListBuilder::handle_exceptions(BlockBegin* current, int cur_bci) {
 193   // Draws edges from a block to its exception handlers
 194   XHandlers* list = xhandlers();
 195   const int n = list->length();
 196 
 197   for (int i = 0; i < n; i++) {
 198     XHandler* h = list->handler_at(i);
 199 
 200     if (h->covers(cur_bci)) {
 201       BlockBegin* entry = h->entry_block();
 202       assert(entry != NULL && entry == _bci2block->at(h->handler_bci()), "entry must be set");
 203       assert(entry->is_set(BlockBegin::exception_entry_flag), "flag must be set");
 204 
 205       // add each exception handler only once
 206       if (!current->is_successor(entry)) {
 207         current->add_successor(entry);
 208         entry->increment_total_preds();
 209       }
 210 
 211       // stop when reaching catchall
 212       if (h->catch_type() == 0) break;
 213     }
 214   }
 215 }
 216 
 217 void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) {
 218   // start a new block after jsr-bytecode and link this block into cfg
 219   make_block_at(next_bci, current);
 220 
 221   // start a new block at the subroutine entry at mark it with special flag
 222   BlockBegin* sr_block = make_block_at(sr_bci, current);
 223   if (!sr_block->is_set(BlockBegin::subroutine_entry_flag)) {
 224     sr_block->set(BlockBegin::subroutine_entry_flag);
 225   }
 226 }
 227 
 228 
 229 void BlockListBuilder::set_leaders() {
 230   bool has_xhandlers = xhandlers()->has_handlers();
 231   BlockBegin* current = NULL;
 232 
 233   // The information which bci starts a new block simplifies the analysis
 234   // Without it, backward branches could jump to a bci where no block was created
 235   // during bytecode iteration. This would require the creation of a new block at the
 236   // branch target and a modification of the successor lists.
 237   const BitMap& bci_block_start = method()->bci_block_start();
 238 
 239   ciBytecodeStream s(method());
 240   while (s.next() != ciBytecodeStream::EOBC()) {
 241     int cur_bci = s.cur_bci();
 242 
 243     if (bci_block_start.at(cur_bci)) {
 244       current = make_block_at(cur_bci, current);
 245     }
 246     assert(current != NULL, "must have current block");
 247 
 248     if (has_xhandlers && GraphBuilder::can_trap(method(), s.cur_bc())) {
 249       handle_exceptions(current, cur_bci);
 250     }
 251 
 252     switch (s.cur_bc()) {
 253       // track stores to local variables for selective creation of phi functions
 254       case Bytecodes::_iinc:     store_one(current, s.get_index()); break;
 255       case Bytecodes::_istore:   store_one(current, s.get_index()); break;
 256       case Bytecodes::_lstore:   store_two(current, s.get_index()); break;
 257       case Bytecodes::_fstore:   store_one(current, s.get_index()); break;
 258       case Bytecodes::_dstore:   store_two(current, s.get_index()); break;
 259       case Bytecodes::_astore:   store_one(current, s.get_index()); break;
 260       case Bytecodes::_istore_0: store_one(current, 0); break;
 261       case Bytecodes::_istore_1: store_one(current, 1); break;
 262       case Bytecodes::_istore_2: store_one(current, 2); break;
 263       case Bytecodes::_istore_3: store_one(current, 3); break;
 264       case Bytecodes::_lstore_0: store_two(current, 0); break;
 265       case Bytecodes::_lstore_1: store_two(current, 1); break;
 266       case Bytecodes::_lstore_2: store_two(current, 2); break;
 267       case Bytecodes::_lstore_3: store_two(current, 3); break;
 268       case Bytecodes::_fstore_0: store_one(current, 0); break;
 269       case Bytecodes::_fstore_1: store_one(current, 1); break;
 270       case Bytecodes::_fstore_2: store_one(current, 2); break;
 271       case Bytecodes::_fstore_3: store_one(current, 3); break;
 272       case Bytecodes::_dstore_0: store_two(current, 0); break;
 273       case Bytecodes::_dstore_1: store_two(current, 1); break;
 274       case Bytecodes::_dstore_2: store_two(current, 2); break;
 275       case Bytecodes::_dstore_3: store_two(current, 3); break;
 276       case Bytecodes::_astore_0: store_one(current, 0); break;
 277       case Bytecodes::_astore_1: store_one(current, 1); break;
 278       case Bytecodes::_astore_2: store_one(current, 2); break;
 279       case Bytecodes::_astore_3: store_one(current, 3); break;
 280 
 281       // track bytecodes that affect the control flow
 282       case Bytecodes::_athrow:  // fall through
 283       case Bytecodes::_ret:     // fall through
 284       case Bytecodes::_ireturn: // fall through
 285       case Bytecodes::_lreturn: // fall through
 286       case Bytecodes::_freturn: // fall through
 287       case Bytecodes::_dreturn: // fall through
 288       case Bytecodes::_areturn: // fall through
 289       case Bytecodes::_return:
 290         current = NULL;
 291         break;
 292 
 293       case Bytecodes::_ifeq:      // fall through
 294       case Bytecodes::_ifne:      // fall through
 295       case Bytecodes::_iflt:      // fall through
 296       case Bytecodes::_ifge:      // fall through
 297       case Bytecodes::_ifgt:      // fall through
 298       case Bytecodes::_ifle:      // fall through
 299       case Bytecodes::_if_icmpeq: // fall through
 300       case Bytecodes::_if_icmpne: // fall through
 301       case Bytecodes::_if_icmplt: // fall through
 302       case Bytecodes::_if_icmpge: // fall through
 303       case Bytecodes::_if_icmpgt: // fall through
 304       case Bytecodes::_if_icmple: // fall through
 305       case Bytecodes::_if_acmpeq: // fall through
 306       case Bytecodes::_if_acmpne: // fall through
 307       case Bytecodes::_ifnull:    // fall through
 308       case Bytecodes::_ifnonnull:
 309         make_block_at(s.next_bci(), current);
 310         make_block_at(s.get_dest(), current);
 311         current = NULL;
 312         break;
 313 
 314       case Bytecodes::_goto:
 315         make_block_at(s.get_dest(), current);
 316         current = NULL;
 317         break;
 318 
 319       case Bytecodes::_goto_w:
 320         make_block_at(s.get_far_dest(), current);
 321         current = NULL;
 322         break;
 323 
 324       case Bytecodes::_jsr:
 325         handle_jsr(current, s.get_dest(), s.next_bci());
 326         current = NULL;
 327         break;
 328 
 329       case Bytecodes::_jsr_w:
 330         handle_jsr(current, s.get_far_dest(), s.next_bci());
 331         current = NULL;
 332         break;
 333 
 334       case Bytecodes::_tableswitch: {
 335         // set block for each case
 336         Bytecode_tableswitch sw(&s);
 337         int l = sw.length();
 338         for (int i = 0; i < l; i++) {
 339           make_block_at(cur_bci + sw.dest_offset_at(i), current);
 340         }
 341         make_block_at(cur_bci + sw.default_offset(), current);
 342         current = NULL;
 343         break;
 344       }
 345 
 346       case Bytecodes::_lookupswitch: {
 347         // set block for each case
 348         Bytecode_lookupswitch sw(&s);
 349         int l = sw.number_of_pairs();
 350         for (int i = 0; i < l; i++) {
 351           make_block_at(cur_bci + sw.pair_at(i).offset(), current);
 352         }
 353         make_block_at(cur_bci + sw.default_offset(), current);
 354         current = NULL;
 355         break;
 356       }
 357 
 358       default:
 359         break;
 360     }
 361   }
 362 }
 363 
 364 
 365 void BlockListBuilder::mark_loops() {
 366   ResourceMark rm;
 367 
 368   _active.initialize(BlockBegin::number_of_blocks());
 369   _visited.initialize(BlockBegin::number_of_blocks());
 370   _loop_map = intArray(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), 0);
 371   _next_loop_index = 0;
 372   _next_block_number = _blocks.length();
 373 
 374   // recursively iterate the control flow graph
 375   mark_loops(_bci2block->at(0), false);
 376   assert(_next_block_number >= 0, "invalid block numbers");
 377 
 378   // Remove dangling Resource pointers before the ResourceMark goes out-of-scope.
 379   _active.resize(0);
 380   _visited.resize(0);
 381 }
 382 
 383 void BlockListBuilder::make_loop_header(BlockBegin* block) {
 384   if (block->is_set(BlockBegin::exception_entry_flag)) {
 385     // exception edges may look like loops but don't mark them as such
 386     // since it screws up block ordering.
 387     return;
 388   }
 389   if (!block->is_set(BlockBegin::parser_loop_header_flag)) {
 390     block->set(BlockBegin::parser_loop_header_flag);
 391 
 392     assert(_loop_map.at(block->block_id()) == 0, "must not be set yet");
 393     assert(0 <= _next_loop_index && _next_loop_index < BitsPerInt, "_next_loop_index is used as a bit-index in integer");
 394     _loop_map.at_put(block->block_id(), 1 << _next_loop_index);
 395     if (_next_loop_index < 31) _next_loop_index++;
 396   } else {
 397     // block already marked as loop header
 398     assert(is_power_of_2((unsigned int)_loop_map.at(block->block_id())), "exactly one bit must be set");
 399   }
 400 }
 401 
 402 int BlockListBuilder::mark_loops(BlockBegin* block, bool in_subroutine) {
 403   int block_id = block->block_id();
 404 
 405   if (_visited.at(block_id)) {
 406     if (_active.at(block_id)) {
 407       // reached block via backward branch
 408       make_loop_header(block);
 409     }
 410     // return cached loop information for this block
 411     return _loop_map.at(block_id);
 412   }
 413 
 414   if (block->is_set(BlockBegin::subroutine_entry_flag)) {
 415     in_subroutine = true;
 416   }
 417 
 418   // set active and visited bits before successors are processed
 419   _visited.set_bit(block_id);
 420   _active.set_bit(block_id);
 421 
 422   intptr_t loop_state = 0;
 423   for (int i = block->number_of_sux() - 1; i >= 0; i--) {
 424     // recursively process all successors
 425     loop_state |= mark_loops(block->sux_at(i), in_subroutine);
 426   }
 427 
 428   // clear active-bit after all successors are processed
 429   _active.clear_bit(block_id);
 430 
 431   // reverse-post-order numbering of all blocks
 432   block->set_depth_first_number(_next_block_number);
 433   _next_block_number--;
 434 
 435   if (loop_state != 0 || in_subroutine ) {
 436     // block is contained at least in one loop, so phi functions are necessary
 437     // phi functions are also necessary for all locals stored in a subroutine
 438     scope()->requires_phi_function().set_union(block->stores_to_locals());
 439   }
 440 
 441   if (block->is_set(BlockBegin::parser_loop_header_flag)) {
 442     int header_loop_state = _loop_map.at(block_id);
 443     assert(is_power_of_2((unsigned)header_loop_state), "exactly one bit must be set");
 444 
 445     // If the highest bit is set (i.e. when integer value is negative), the method
 446     // has 32 or more loops. This bit is never cleared because it is used for multiple loops
 447     if (header_loop_state >= 0) {
 448       clear_bits(loop_state, header_loop_state);
 449     }
 450   }
 451 
 452   // cache and return loop information for this block
 453   _loop_map.at_put(block_id, loop_state);
 454   return loop_state;
 455 }
 456 
 457 
 458 #ifndef PRODUCT
 459 
 460 int compare_depth_first(BlockBegin** a, BlockBegin** b) {
 461   return (*a)->depth_first_number() - (*b)->depth_first_number();
 462 }
 463 
 464 void BlockListBuilder::print() {
 465   tty->print("----- initial block list of BlockListBuilder for method ");
 466   method()->print_short_name();
 467   tty->cr();
 468 
 469   // better readability if blocks are sorted in processing order
 470   _blocks.sort(compare_depth_first);
 471 
 472   for (int i = 0; i < _blocks.length(); i++) {
 473     BlockBegin* cur = _blocks.at(i);
 474     tty->print("%4d: B%-4d bci: %-4d  preds: %-4d ", cur->depth_first_number(), cur->block_id(), cur->bci(), cur->total_preds());
 475 
 476     tty->print(cur->is_set(BlockBegin::std_entry_flag)               ? " std" : "    ");
 477     tty->print(cur->is_set(BlockBegin::osr_entry_flag)               ? " osr" : "    ");
 478     tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
 479     tty->print(cur->is_set(BlockBegin::subroutine_entry_flag)        ? " sr" : "   ");
 480     tty->print(cur->is_set(BlockBegin::parser_loop_header_flag)      ? " lh" : "   ");
 481 
 482     if (cur->number_of_sux() > 0) {
 483       tty->print("    sux: ");
 484       for (int j = 0; j < cur->number_of_sux(); j++) {
 485         BlockBegin* sux = cur->sux_at(j);
 486         tty->print("B%d ", sux->block_id());
 487       }
 488     }
 489     tty->cr();
 490   }
 491 }
 492 
 493 #endif
 494 
 495 
 496 // A simple growable array of Values indexed by ciFields
 497 class FieldBuffer: public CompilationResourceObj {
 498  private:
 499   GrowableArray<Value> _values;
 500 
 501  public:
 502   FieldBuffer() {}
 503 
 504   void kill() {
 505     _values.trunc_to(0);
 506   }
 507 
 508   Value at(ciField* field) {
 509     assert(field->holder()->is_loaded(), "must be a loaded field");
 510     int offset = field->offset();
 511     if (offset < _values.length()) {
 512       return _values.at(offset);
 513     } else {
 514       return NULL;
 515     }
 516   }
 517 
 518   void at_put(ciField* field, Value value) {
 519     assert(field->holder()->is_loaded(), "must be a loaded field");
 520     int offset = field->offset();
 521     _values.at_put_grow(offset, value, NULL);
 522   }
 523 
 524 };
 525 
 526 
 527 // MemoryBuffer is fairly simple model of the current state of memory.
 528 // It partitions memory into several pieces.  The first piece is
 529 // generic memory where little is known about the owner of the memory.
 530 // This is conceptually represented by the tuple <O, F, V> which says
 531 // that the field F of object O has value V.  This is flattened so
 532 // that F is represented by the offset of the field and the parallel
 533 // arrays _objects and _values are used for O and V.  Loads of O.F can
 534 // simply use V.  Newly allocated objects are kept in a separate list
 535 // along with a parallel array for each object which represents the
 536 // current value of its fields.  Stores of the default value to fields
 537 // which have never been stored to before are eliminated since they
 538 // are redundant.  Once newly allocated objects are stored into
 539 // another object or they are passed out of the current compile they
 540 // are treated like generic memory.
 541 
 542 class MemoryBuffer: public CompilationResourceObj {
 543  private:
 544   FieldBuffer                 _values;
 545   GrowableArray<Value>        _objects;
 546   GrowableArray<Value>        _newobjects;
 547   GrowableArray<FieldBuffer*> _fields;
 548 
 549  public:
 550   MemoryBuffer() {}
 551 
 552   StoreField* store(StoreField* st) {
 553     if (!EliminateFieldAccess) {
 554       return st;
 555     }
 556 
 557     Value object = st->obj();
 558     Value value = st->value();
 559     ciField* field = st->field();
 560     if (field->holder()->is_loaded()) {
 561       int offset = field->offset();
 562       int index = _newobjects.find(object);
 563       if (index != -1) {
 564         // newly allocated object with no other stores performed on this field
 565         FieldBuffer* buf = _fields.at(index);
 566         if (buf->at(field) == NULL && is_default_value(value)) {
 567 #ifndef PRODUCT
 568           if (PrintIRDuringConstruction && Verbose) {
 569             tty->print_cr("Eliminated store for object %d:", index);
 570             st->print_line();
 571           }
 572 #endif
 573           return NULL;
 574         } else {
 575           buf->at_put(field, value);
 576         }
 577       } else {
 578         _objects.at_put_grow(offset, object, NULL);
 579         _values.at_put(field, value);
 580       }
 581 
 582       store_value(value);
 583     } else {
 584       // if we held onto field names we could alias based on names but
 585       // we don't know what's being stored to so kill it all.
 586       kill();
 587     }
 588     return st;
 589   }
 590 
 591 
 592   // return true if this value correspond to the default value of a field.
 593   bool is_default_value(Value value) {
 594     Constant* con = value->as_Constant();
 595     if (con) {
 596       switch (con->type()->tag()) {
 597         case intTag:    return con->type()->as_IntConstant()->value() == 0;
 598         case longTag:   return con->type()->as_LongConstant()->value() == 0;
 599         case floatTag:  return jint_cast(con->type()->as_FloatConstant()->value()) == 0;
 600         case doubleTag: return jlong_cast(con->type()->as_DoubleConstant()->value()) == jlong_cast(0);
 601         case objectTag: return con->type() == objectNull;
 602         default:  ShouldNotReachHere();
 603       }
 604     }
 605     return false;
 606   }
 607 
 608 
 609   // return either the actual value of a load or the load itself
 610   Value load(LoadField* load) {
 611     if (!EliminateFieldAccess) {
 612       return load;
 613     }
 614 
 615     if (strict_fp_requires_explicit_rounding && load->type()->is_float_kind()) {
 616 #ifdef IA32
 617       if (UseSSE < 2) {
 618         // can't skip load since value might get rounded as a side effect
 619         return load;
 620       }
 621 #else
 622       Unimplemented();
 623 #endif // IA32
 624     }
 625 
 626     ciField* field = load->field();
 627     Value object   = load->obj();
 628     if (field->holder()->is_loaded() && !field->is_volatile()) {
 629       int offset = field->offset();
 630       Value result = NULL;
 631       int index = _newobjects.find(object);
 632       if (index != -1) {
 633         result = _fields.at(index)->at(field);
 634       } else if (_objects.at_grow(offset, NULL) == object) {
 635         result = _values.at(field);
 636       }
 637       if (result != NULL) {
 638 #ifndef PRODUCT
 639         if (PrintIRDuringConstruction && Verbose) {
 640           tty->print_cr("Eliminated load: ");
 641           load->print_line();
 642         }
 643 #endif
 644         assert(result->type()->tag() == load->type()->tag(), "wrong types");
 645         return result;
 646       }
 647     }
 648     return load;
 649   }
 650 
 651   // Record this newly allocated object
 652   void new_instance(NewInstance* object) {
 653     int index = _newobjects.length();
 654     _newobjects.append(object);
 655     if (_fields.at_grow(index, NULL) == NULL) {
 656       _fields.at_put(index, new FieldBuffer());
 657     } else {
 658       _fields.at(index)->kill();
 659     }
 660   }
 661 
 662   // Record this newly allocated object
 663   void new_instance(NewInlineTypeInstance* object) {
 664     int index = _newobjects.length();
 665     _newobjects.append(object);
 666     if (_fields.at_grow(index, NULL) == NULL) {
 667       _fields.at_put(index, new FieldBuffer());
 668     } else {
 669       _fields.at(index)->kill();
 670     }
 671   }
 672 
 673   void store_value(Value value) {
 674     int index = _newobjects.find(value);
 675     if (index != -1) {
 676       // stored a newly allocated object into another object.
 677       // Assume we've lost track of it as separate slice of memory.
 678       // We could do better by keeping track of whether individual
 679       // fields could alias each other.
 680       _newobjects.remove_at(index);
 681       // pull out the field info and store it at the end up the list
 682       // of field info list to be reused later.
 683       _fields.append(_fields.at(index));
 684       _fields.remove_at(index);
 685     }
 686   }
 687 
 688   void kill() {
 689     _newobjects.trunc_to(0);
 690     _objects.trunc_to(0);
 691     _values.kill();
 692   }
 693 };
 694 
 695 
 696 // Implementation of GraphBuilder's ScopeData
 697 
 698 GraphBuilder::ScopeData::ScopeData(ScopeData* parent)
 699   : _parent(parent)
 700   , _bci2block(NULL)
 701   , _scope(NULL)
 702   , _has_handler(false)
 703   , _stream(NULL)
 704   , _work_list(NULL)
 705   , _caller_stack_size(-1)
 706   , _continuation(NULL)
 707   , _parsing_jsr(false)
 708   , _jsr_xhandlers(NULL)
 709   , _num_returns(0)
 710   , _cleanup_block(NULL)
 711   , _cleanup_return_prev(NULL)
 712   , _cleanup_state(NULL)
 713   , _ignore_return(false)
 714 {
 715   if (parent != NULL) {
 716     _max_inline_size = (intx) ((float) NestedInliningSizeRatio * (float) parent->max_inline_size() / 100.0f);
 717   } else {
 718     _max_inline_size = C1MaxInlineSize;
 719   }
 720   if (_max_inline_size < C1MaxTrivialSize) {
 721     _max_inline_size = C1MaxTrivialSize;
 722   }
 723 }
 724 
 725 
 726 void GraphBuilder::kill_all() {
 727   if (UseLocalValueNumbering) {
 728     vmap()->kill_all();
 729   }
 730   _memory->kill();
 731 }
 732 
 733 
 734 BlockBegin* GraphBuilder::ScopeData::block_at(int bci) {
 735   if (parsing_jsr()) {
 736     // It is necessary to clone all blocks associated with a
 737     // subroutine, including those for exception handlers in the scope
 738     // of the method containing the jsr (because those exception
 739     // handlers may contain ret instructions in some cases).
 740     BlockBegin* block = bci2block()->at(bci);
 741     if (block != NULL && block == parent()->bci2block()->at(bci)) {
 742       BlockBegin* new_block = new BlockBegin(block->bci());
 743       if (PrintInitialBlockList) {
 744         tty->print_cr("CFG: cloned block %d (bci %d) as block %d for jsr",
 745                       block->block_id(), block->bci(), new_block->block_id());
 746       }
 747       // copy data from cloned blocked
 748       new_block->set_depth_first_number(block->depth_first_number());
 749       if (block->is_set(BlockBegin::parser_loop_header_flag)) new_block->set(BlockBegin::parser_loop_header_flag);
 750       // Preserve certain flags for assertion checking
 751       if (block->is_set(BlockBegin::subroutine_entry_flag)) new_block->set(BlockBegin::subroutine_entry_flag);
 752       if (block->is_set(BlockBegin::exception_entry_flag))  new_block->set(BlockBegin::exception_entry_flag);
 753 
 754       // copy was_visited_flag to allow early detection of bailouts
 755       // if a block that is used in a jsr has already been visited before,
 756       // it is shared between the normal control flow and a subroutine
 757       // BlockBegin::try_merge returns false when the flag is set, this leads
 758       // to a compilation bailout
 759       if (block->is_set(BlockBegin::was_visited_flag))  new_block->set(BlockBegin::was_visited_flag);
 760 
 761       bci2block()->at_put(bci, new_block);
 762       block = new_block;
 763     }
 764     return block;
 765   } else {
 766     return bci2block()->at(bci);
 767   }
 768 }
 769 
 770 
 771 XHandlers* GraphBuilder::ScopeData::xhandlers() const {
 772   if (_jsr_xhandlers == NULL) {
 773     assert(!parsing_jsr(), "");
 774     return scope()->xhandlers();
 775   }
 776   assert(parsing_jsr(), "");
 777   return _jsr_xhandlers;
 778 }
 779 
 780 
 781 void GraphBuilder::ScopeData::set_scope(IRScope* scope) {
 782   _scope = scope;
 783   bool parent_has_handler = false;
 784   if (parent() != NULL) {
 785     parent_has_handler = parent()->has_handler();
 786   }
 787   _has_handler = parent_has_handler || scope->xhandlers()->has_handlers();
 788 }
 789 
 790 
 791 void GraphBuilder::ScopeData::set_inline_cleanup_info(BlockBegin* block,
 792                                                       Instruction* return_prev,
 793                                                       ValueStack* return_state) {
 794   _cleanup_block       = block;
 795   _cleanup_return_prev = return_prev;
 796   _cleanup_state       = return_state;
 797 }
 798 
 799 
 800 void GraphBuilder::ScopeData::add_to_work_list(BlockBegin* block) {
 801   if (_work_list == NULL) {
 802     _work_list = new BlockList();
 803   }
 804 
 805   if (!block->is_set(BlockBegin::is_on_work_list_flag)) {
 806     // Do not start parsing the continuation block while in a
 807     // sub-scope
 808     if (parsing_jsr()) {
 809       if (block == jsr_continuation()) {
 810         return;
 811       }
 812     } else {
 813       if (block == continuation()) {
 814         return;
 815       }
 816     }
 817     block->set(BlockBegin::is_on_work_list_flag);
 818     _work_list->push(block);
 819 
 820     sort_top_into_worklist(_work_list, block);
 821   }
 822 }
 823 
 824 
 825 void GraphBuilder::sort_top_into_worklist(BlockList* worklist, BlockBegin* top) {
 826   assert(worklist->top() == top, "");
 827   // sort block descending into work list
 828   const int dfn = top->depth_first_number();
 829   assert(dfn != -1, "unknown depth first number");
 830   int i = worklist->length()-2;
 831   while (i >= 0) {
 832     BlockBegin* b = worklist->at(i);
 833     if (b->depth_first_number() < dfn) {
 834       worklist->at_put(i+1, b);
 835     } else {
 836       break;
 837     }
 838     i --;
 839   }
 840   if (i >= -1) worklist->at_put(i + 1, top);
 841 }
 842 
 843 
 844 BlockBegin* GraphBuilder::ScopeData::remove_from_work_list() {
 845   if (is_work_list_empty()) {
 846     return NULL;
 847   }
 848   return _work_list->pop();
 849 }
 850 
 851 
 852 bool GraphBuilder::ScopeData::is_work_list_empty() const {
 853   return (_work_list == NULL || _work_list->length() == 0);
 854 }
 855 
 856 
 857 void GraphBuilder::ScopeData::setup_jsr_xhandlers() {
 858   assert(parsing_jsr(), "");
 859   // clone all the exception handlers from the scope
 860   XHandlers* handlers = new XHandlers(scope()->xhandlers());
 861   const int n = handlers->length();
 862   for (int i = 0; i < n; i++) {
 863     // The XHandlers need to be adjusted to dispatch to the cloned
 864     // handler block instead of the default one but the synthetic
 865     // unlocker needs to be handled specially.  The synthetic unlocker
 866     // should be left alone since there can be only one and all code
 867     // should dispatch to the same one.
 868     XHandler* h = handlers->handler_at(i);
 869     assert(h->handler_bci() != SynchronizationEntryBCI, "must be real");
 870     h->set_entry_block(block_at(h->handler_bci()));
 871   }
 872   _jsr_xhandlers = handlers;
 873 }
 874 
 875 
 876 int GraphBuilder::ScopeData::num_returns() {
 877   if (parsing_jsr()) {
 878     return parent()->num_returns();
 879   }
 880   return _num_returns;
 881 }
 882 
 883 
 884 void GraphBuilder::ScopeData::incr_num_returns() {
 885   if (parsing_jsr()) {
 886     parent()->incr_num_returns();
 887   } else {
 888     ++_num_returns;
 889   }
 890 }
 891 
 892 
 893 // Implementation of GraphBuilder
 894 
 895 #define INLINE_BAILOUT(msg)        { inline_bailout(msg); return false; }
 896 
 897 
 898 void GraphBuilder::load_constant() {
 899   ciConstant con = stream()->get_constant();
 900   if (con.basic_type() == T_ILLEGAL) {
 901     // FIXME: an unresolved Dynamic constant can get here,
 902     // and that should not terminate the whole compilation.
 903     BAILOUT("could not resolve a constant");
 904   } else {
 905     ValueType* t = illegalType;
 906     ValueStack* patch_state = NULL;
 907     switch (con.basic_type()) {
 908       case T_BOOLEAN: t = new IntConstant     (con.as_boolean()); break;
 909       case T_BYTE   : t = new IntConstant     (con.as_byte   ()); break;
 910       case T_CHAR   : t = new IntConstant     (con.as_char   ()); break;
 911       case T_SHORT  : t = new IntConstant     (con.as_short  ()); break;
 912       case T_INT    : t = new IntConstant     (con.as_int    ()); break;
 913       case T_LONG   : t = new LongConstant    (con.as_long   ()); break;
 914       case T_FLOAT  : t = new FloatConstant   (con.as_float  ()); break;
 915       case T_DOUBLE : t = new DoubleConstant  (con.as_double ()); break;
 916       case T_ARRAY  : t = new ArrayConstant   (con.as_object ()->as_array   ()); break;
 917       case T_OBJECT :
 918        {
 919         ciObject* obj = con.as_object();
 920         if (!obj->is_loaded()
 921             || (PatchALot && obj->klass() != ciEnv::current()->String_klass())) {
 922           // A Class, MethodType, MethodHandle, or String.
 923           // Unloaded condy nodes show up as T_ILLEGAL, above.
 924           patch_state = copy_state_before();
 925           t = new ObjectConstant(obj);
 926         } else {
 927           // Might be a Class, MethodType, MethodHandle, or Dynamic constant
 928           // result, which might turn out to be an array.
 929           if (obj->is_null_object())
 930             t = objectNull;
 931           else if (obj->is_array())
 932             t = new ArrayConstant(obj->as_array());
 933           else
 934             t = new InstanceConstant(obj->as_instance());
 935         }
 936         break;
 937        }
 938       default       : ShouldNotReachHere();
 939     }
 940     Value x;
 941     if (patch_state != NULL) {
 942       x = new Constant(t, patch_state);
 943     } else {
 944       x = new Constant(t);
 945     }
 946     push(t, append(x));
 947   }
 948 }
 949 
 950 
 951 void GraphBuilder::load_local(ValueType* type, int index) {
 952   Value x = state()->local_at(index);
 953   assert(x != NULL && !x->type()->is_illegal(), "access of illegal local variable");
 954   push(type, x);
 955   if (x->as_NewInlineTypeInstance() != NULL && x->as_NewInlineTypeInstance()->in_larval_state()) {
 956     if (x->as_NewInlineTypeInstance()->on_stack_count() == 1) {
 957       x->as_NewInlineTypeInstance()->set_not_larva_anymore();
 958     } else {
 959       x->as_NewInlineTypeInstance()->increment_on_stack_count();
 960     }
 961   }
 962 }
 963 
 964 
 965 void GraphBuilder::store_local(ValueType* type, int index) {
 966   Value x = pop(type);
 967   store_local(state(), x, index);
 968   if (x->as_NewInlineTypeInstance() != NULL) {
 969     x->as_NewInlineTypeInstance()->set_local_index(index);
 970   }
 971 }
 972 
 973 
 974 void GraphBuilder::store_local(ValueStack* state, Value x, int index) {
 975   if (parsing_jsr()) {
 976     // We need to do additional tracking of the location of the return
 977     // address for jsrs since we don't handle arbitrary jsr/ret
 978     // constructs. Here we are figuring out in which circumstances we
 979     // need to bail out.
 980     if (x->type()->is_address()) {
 981       scope_data()->set_jsr_return_address_local(index);
 982 
 983       // Also check parent jsrs (if any) at this time to see whether
 984       // they are using this local. We don't handle skipping over a
 985       // ret.
 986       for (ScopeData* cur_scope_data = scope_data()->parent();
 987            cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
 988            cur_scope_data = cur_scope_data->parent()) {
 989         if (cur_scope_data->jsr_return_address_local() == index) {
 990           BAILOUT("subroutine overwrites return address from previous subroutine");
 991         }
 992       }
 993     } else if (index == scope_data()->jsr_return_address_local()) {
 994       scope_data()->set_jsr_return_address_local(-1);
 995     }
 996   }
 997 
 998   state->store_local(index, round_fp(x));
 999   if (x->as_NewInlineTypeInstance() != NULL) {
1000     x->as_NewInlineTypeInstance()->set_local_index(index);
1001   }
1002 }
1003 
1004 
1005 void GraphBuilder::load_indexed(BasicType type) {
1006   // In case of in block code motion in range check elimination
1007   ValueStack* state_before = NULL;
1008   int array_idx = state()->stack_size() - 2;
1009   if (type == T_OBJECT && state()->stack_at(array_idx)->maybe_flattened_array()) {
1010     // Save the entire state and re-execute on deopt when accessing flattened arrays
1011     state_before = copy_state_before();
1012     state_before->set_should_reexecute(true);
1013   } else {
1014     state_before = copy_state_indexed_access();
1015   }
1016   compilation()->set_has_access_indexed(true);
1017   Value index = ipop();
1018   Value array = apop();
1019   Value length = NULL;
1020   if (CSEArrayLength ||
1021       (array->as_Constant() != NULL) ||
1022       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1023       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1024       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1025     length = append(new ArrayLength(array, state_before));
1026   }
1027 
1028   bool need_membar = false;
1029   LoadIndexed* load_indexed = NULL;
1030   Instruction* result = NULL;
1031   if (array->is_loaded_flattened_array()) {
1032     ciType* array_type = array->declared_type();
1033     ciInlineKlass* elem_klass = array_type->as_flat_array_klass()->element_klass()->as_inline_klass();
1034 
1035     bool can_delay_access = false;
1036     ciBytecodeStream s(method());
1037     s.force_bci(bci());
1038     s.next();
1039     if (s.cur_bc() == Bytecodes::_getfield) {
1040       bool will_link;
1041       ciField* next_field = s.get_field(will_link);
1042       bool next_needs_patching = !next_field->holder()->is_loaded() ||
1043                                  !next_field->will_link(method(), Bytecodes::_getfield) ||
1044                                  PatchALot;
1045       can_delay_access = C1UseDelayedFlattenedFieldReads && !next_needs_patching;
1046     }
1047     if (can_delay_access) {
1048       // potentially optimizable array access, storing information for delayed decision
1049       LoadIndexed* li = new LoadIndexed(array, index, length, type, state_before);
1050       DelayedLoadIndexed* dli = new DelayedLoadIndexed(li, state_before);
1051       li->set_delayed(dli);
1052       set_pending_load_indexed(dli);
1053       return; // Nothing else to do for now
1054     } else {
1055       if (elem_klass->is_empty()) {
1056         // No need to create a new instance, the default instance will be used instead
1057         load_indexed = new LoadIndexed(array, index, length, type, state_before);
1058         apush(append(load_indexed));
1059       } else {
1060         NewInlineTypeInstance* new_instance = new NewInlineTypeInstance(elem_klass, state_before);
1061         _memory->new_instance(new_instance);
1062         apush(append_split(new_instance));
1063         load_indexed = new LoadIndexed(array, index, length, type, state_before);
1064         load_indexed->set_vt(new_instance);
1065         // The LoadIndexed node will initialise this instance by copying from
1066         // the flattened field.  Ensure these stores are visible before any
1067         // subsequent store that publishes this reference.
1068         need_membar = true;
1069       }
1070     }
1071   } else {
1072     load_indexed = new LoadIndexed(array, index, length, type, state_before);
1073     if (profile_array_accesses() && is_reference_type(type)) {
1074       compilation()->set_would_profile(true);
1075       load_indexed->set_should_profile(true);
1076       load_indexed->set_profiled_method(method());
1077       load_indexed->set_profiled_bci(bci());
1078     }
1079   }
1080   result = append(load_indexed);
1081   if (need_membar) {
1082     append(new MemBar(lir_membar_storestore));
1083   }
1084   assert(!load_indexed->should_profile() || load_indexed == result, "should not be optimized out");
1085   if (!array->is_loaded_flattened_array()) {
1086     push(as_ValueType(type), result);
1087   }
1088 }
1089 
1090 
1091 void GraphBuilder::store_indexed(BasicType type) {
1092   // In case of in block code motion in range check elimination
1093   ValueStack* state_before = NULL;
1094   int array_idx = state()->stack_size() - 3;
1095   if (type == T_OBJECT && state()->stack_at(array_idx)->maybe_flattened_array()) {
1096     // Save the entire state and re-execute on deopt when accessing flattened arrays
1097     state_before = copy_state_before();
1098     state_before->set_should_reexecute(true);
1099   } else {
1100     state_before = copy_state_indexed_access();
1101   }
1102   compilation()->set_has_access_indexed(true);
1103   Value value = pop(as_ValueType(type));
1104   Value index = ipop();
1105   Value array = apop();
1106   Value length = NULL;
1107   if (CSEArrayLength ||
1108       (array->as_Constant() != NULL) ||
1109       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1110       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1111       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1112     length = append(new ArrayLength(array, state_before));
1113   }
1114   ciType* array_type = array->declared_type();
1115   bool check_boolean = false;
1116   if (array_type != NULL) {
1117     if (array_type->is_loaded() &&
1118       array_type->as_array_klass()->element_type()->basic_type() == T_BOOLEAN) {
1119       assert(type == T_BYTE, "boolean store uses bastore");
1120       Value mask = append(new Constant(new IntConstant(1)));
1121       value = append(new LogicOp(Bytecodes::_iand, value, mask));
1122     }
1123   } else if (type == T_BYTE) {
1124     check_boolean = true;
1125   }



1126 
1127   StoreIndexed* store_indexed = new StoreIndexed(array, index, length, type, value, state_before, check_boolean);
1128   if (profile_array_accesses() && is_reference_type(type) && !array->is_loaded_flattened_array()) {
1129     compilation()->set_would_profile(true);
1130     store_indexed->set_should_profile(true);
1131     store_indexed->set_profiled_method(method());
1132     store_indexed->set_profiled_bci(bci());



1133   }
1134   Instruction* result = append(store_indexed);
1135   assert(!store_indexed->should_profile() || store_indexed == result, "should not be optimized out");
1136   _memory->store_value(value);
1137 }
1138 

1139 void GraphBuilder::stack_op(Bytecodes::Code code) {
1140   switch (code) {
1141     case Bytecodes::_pop:
1142       { Value w = state()->raw_pop();
1143         update_larva_stack_count(w);
1144       }
1145       break;
1146     case Bytecodes::_pop2:
1147       { Value w1 = state()->raw_pop();
1148         Value w2 = state()->raw_pop();
1149         update_larva_stack_count(w1);
1150         update_larva_stack_count(w2);
1151       }
1152       break;
1153     case Bytecodes::_dup:
1154       { Value w = state()->raw_pop();
1155         update_larval_state(w);
1156         state()->raw_push(w);
1157         state()->raw_push(w);
1158       }
1159       break;
1160     case Bytecodes::_dup_x1:
1161       { Value w1 = state()->raw_pop();
1162         Value w2 = state()->raw_pop();
1163         update_larval_state(w1);
1164         state()->raw_push(w1);
1165         state()->raw_push(w2);
1166         state()->raw_push(w1);
1167       }
1168       break;
1169     case Bytecodes::_dup_x2:
1170       { Value w1 = state()->raw_pop();
1171         Value w2 = state()->raw_pop();
1172         Value w3 = state()->raw_pop();
1173         // special handling for the dup_x2/pop sequence (see JDK-8251046)
1174         if (w1 != NULL && w1->as_NewInlineTypeInstance() != NULL) {
1175           ciBytecodeStream s(method());
1176           s.force_bci(bci());
1177           s.next();
1178           if (s.cur_bc() != Bytecodes::_pop) {
1179             w1->as_NewInlineTypeInstance()->set_not_larva_anymore();
1180           }  else {
1181             w1->as_NewInlineTypeInstance()->increment_on_stack_count();
1182            }
1183         }
1184         state()->raw_push(w1);
1185         state()->raw_push(w3);
1186         state()->raw_push(w2);
1187         state()->raw_push(w1);
1188       }
1189       break;
1190     case Bytecodes::_dup2:
1191       { Value w1 = state()->raw_pop();
1192         Value w2 = state()->raw_pop();
1193         update_larval_state(w1);
1194         update_larval_state(w2);
1195         state()->raw_push(w2);
1196         state()->raw_push(w1);
1197         state()->raw_push(w2);
1198         state()->raw_push(w1);
1199       }
1200       break;
1201     case Bytecodes::_dup2_x1:
1202       { Value w1 = state()->raw_pop();
1203         Value w2 = state()->raw_pop();
1204         Value w3 = state()->raw_pop();
1205         update_larval_state(w1);
1206         update_larval_state(w2);
1207         state()->raw_push(w2);
1208         state()->raw_push(w1);
1209         state()->raw_push(w3);
1210         state()->raw_push(w2);
1211         state()->raw_push(w1);
1212       }
1213       break;
1214     case Bytecodes::_dup2_x2:
1215       { Value w1 = state()->raw_pop();
1216         Value w2 = state()->raw_pop();
1217         Value w3 = state()->raw_pop();
1218         Value w4 = state()->raw_pop();
1219         update_larval_state(w1);
1220         update_larval_state(w2);
1221         state()->raw_push(w2);
1222         state()->raw_push(w1);
1223         state()->raw_push(w4);
1224         state()->raw_push(w3);
1225         state()->raw_push(w2);
1226         state()->raw_push(w1);
1227       }
1228       break;
1229     case Bytecodes::_swap:
1230       { Value w1 = state()->raw_pop();
1231         Value w2 = state()->raw_pop();
1232         state()->raw_push(w1);
1233         state()->raw_push(w2);
1234       }
1235       break;
1236     default:
1237       ShouldNotReachHere();
1238       break;
1239   }
1240 }
1241 
1242 
1243 void GraphBuilder::arithmetic_op(ValueType* type, Bytecodes::Code code, ValueStack* state_before) {
1244   Value y = pop(type);
1245   Value x = pop(type);
1246   Value res = new ArithmeticOp(code, x, y, state_before);
1247   // Note: currently single-precision floating-point rounding on Intel is handled at the LIRGenerator level
1248   res = append(res);
1249   res = round_fp(res);
1250   push(type, res);
1251 }
1252 
1253 
1254 void GraphBuilder::negate_op(ValueType* type) {
1255   push(type, append(new NegateOp(pop(type))));
1256 }
1257 
1258 
1259 void GraphBuilder::shift_op(ValueType* type, Bytecodes::Code code) {
1260   Value s = ipop();
1261   Value x = pop(type);
1262   // try to simplify
1263   // Note: This code should go into the canonicalizer as soon as it can
1264   //       can handle canonicalized forms that contain more than one node.
1265   if (CanonicalizeNodes && code == Bytecodes::_iushr) {
1266     // pattern: x >>> s
1267     IntConstant* s1 = s->type()->as_IntConstant();
1268     if (s1 != NULL) {
1269       // pattern: x >>> s1, with s1 constant
1270       ShiftOp* l = x->as_ShiftOp();
1271       if (l != NULL && l->op() == Bytecodes::_ishl) {
1272         // pattern: (a << b) >>> s1
1273         IntConstant* s0 = l->y()->type()->as_IntConstant();
1274         if (s0 != NULL) {
1275           // pattern: (a << s0) >>> s1
1276           const int s0c = s0->value() & 0x1F; // only the low 5 bits are significant for shifts
1277           const int s1c = s1->value() & 0x1F; // only the low 5 bits are significant for shifts
1278           if (s0c == s1c) {
1279             if (s0c == 0) {
1280               // pattern: (a << 0) >>> 0 => simplify to: a
1281               ipush(l->x());
1282             } else {
1283               // pattern: (a << s0c) >>> s0c => simplify to: a & m, with m constant
1284               assert(0 < s0c && s0c < BitsPerInt, "adjust code below to handle corner cases");
1285               const int m = (1 << (BitsPerInt - s0c)) - 1;
1286               Value s = append(new Constant(new IntConstant(m)));
1287               ipush(append(new LogicOp(Bytecodes::_iand, l->x(), s)));
1288             }
1289             return;
1290           }
1291         }
1292       }
1293     }
1294   }
1295   // could not simplify
1296   push(type, append(new ShiftOp(code, x, s)));
1297 }
1298 
1299 
1300 void GraphBuilder::logic_op(ValueType* type, Bytecodes::Code code) {
1301   Value y = pop(type);
1302   Value x = pop(type);
1303   push(type, append(new LogicOp(code, x, y)));
1304 }
1305 
1306 
1307 void GraphBuilder::compare_op(ValueType* type, Bytecodes::Code code) {
1308   ValueStack* state_before = copy_state_before();
1309   Value y = pop(type);
1310   Value x = pop(type);
1311   ipush(append(new CompareOp(code, x, y, state_before)));
1312 }
1313 
1314 
1315 void GraphBuilder::convert(Bytecodes::Code op, BasicType from, BasicType to) {
1316   push(as_ValueType(to), append(new Convert(op, pop(as_ValueType(from)), as_ValueType(to))));
1317 }
1318 
1319 
1320 void GraphBuilder::increment() {
1321   int index = stream()->get_index();
1322   int delta = stream()->is_wide() ? (signed short)Bytes::get_Java_u2(stream()->cur_bcp() + 4) : (signed char)(stream()->cur_bcp()[2]);
1323   load_local(intType, index);
1324   ipush(append(new Constant(new IntConstant(delta))));
1325   arithmetic_op(intType, Bytecodes::_iadd);
1326   store_local(intType, index);
1327 }
1328 
1329 
1330 void GraphBuilder::_goto(int from_bci, int to_bci) {
1331   Goto *x = new Goto(block_at(to_bci), to_bci <= from_bci);
1332   if (is_profiling()) {
1333     compilation()->set_would_profile(true);
1334     x->set_profiled_bci(bci());
1335     if (profile_branches()) {
1336       x->set_profiled_method(method());
1337       x->set_should_profile(true);
1338     }
1339   }
1340   append(x);
1341 }
1342 
1343 
1344 void GraphBuilder::if_node(Value x, If::Condition cond, Value y, ValueStack* state_before) {
1345   BlockBegin* tsux = block_at(stream()->get_dest());
1346   BlockBegin* fsux = block_at(stream()->next_bci());
1347   bool is_bb = tsux->bci() < stream()->cur_bci() || fsux->bci() < stream()->cur_bci();
1348 
1349   bool subst_check = false;
1350   if (EnableValhalla && (stream()->cur_bc() == Bytecodes::_if_acmpeq || stream()->cur_bc() == Bytecodes::_if_acmpne)) {
1351     ValueType* left_vt = x->type();
1352     ValueType* right_vt = y->type();
1353     if (left_vt->is_object()) {
1354       assert(right_vt->is_object(), "must be");
1355       ciKlass* left_klass = x->as_loaded_klass_or_null();
1356       ciKlass* right_klass = y->as_loaded_klass_or_null();
1357 
1358       if (left_klass == NULL || right_klass == NULL) {
1359         // The klass is still unloaded, or came from a Phi node. Go slow case;
1360         subst_check = true;
1361       } else if (left_klass->can_be_inline_klass() || right_klass->can_be_inline_klass()) {
1362         // Either operand may be a value object, but we're not sure. Go slow case;
1363         subst_check = true;
1364       } else {
1365         // No need to do substitutability check
1366       }
1367     }
1368   }
1369   if ((stream()->cur_bc() == Bytecodes::_if_acmpeq || stream()->cur_bc() == Bytecodes::_if_acmpne) &&
1370       is_profiling() && profile_branches()) {
1371     compilation()->set_would_profile(true);
1372     append(new ProfileACmpTypes(method(), bci(), x, y));
1373   }
1374 
1375   // In case of loop invariant code motion or predicate insertion
1376   // before the body of a loop the state is needed
1377   Instruction *i = append(new If(x, cond, false, y, tsux, fsux, (is_bb || compilation()->is_optimistic() || subst_check) ? state_before : NULL, is_bb, subst_check));
1378 
1379   assert(i->as_Goto() == NULL ||
1380          (i->as_Goto()->sux_at(0) == tsux  && i->as_Goto()->is_safepoint() == tsux->bci() < stream()->cur_bci()) ||
1381          (i->as_Goto()->sux_at(0) == fsux  && i->as_Goto()->is_safepoint() == fsux->bci() < stream()->cur_bci()),
1382          "safepoint state of Goto returned by canonicalizer incorrect");
1383 
1384   if (is_profiling()) {
1385     If* if_node = i->as_If();
1386     if (if_node != NULL) {
1387       // Note that we'd collect profile data in this method if we wanted it.
1388       compilation()->set_would_profile(true);
1389       // At level 2 we need the proper bci to count backedges
1390       if_node->set_profiled_bci(bci());
1391       if (profile_branches()) {
1392         // Successors can be rotated by the canonicalizer, check for this case.
1393         if_node->set_profiled_method(method());
1394         if_node->set_should_profile(true);
1395         if (if_node->tsux() == fsux) {
1396           if_node->set_swapped(true);
1397         }
1398       }
1399       return;
1400     }
1401 
1402     // Check if this If was reduced to Goto.
1403     Goto *goto_node = i->as_Goto();
1404     if (goto_node != NULL) {
1405       compilation()->set_would_profile(true);
1406       goto_node->set_profiled_bci(bci());
1407       if (profile_branches()) {
1408         goto_node->set_profiled_method(method());
1409         goto_node->set_should_profile(true);
1410         // Find out which successor is used.
1411         if (goto_node->default_sux() == tsux) {
1412           goto_node->set_direction(Goto::taken);
1413         } else if (goto_node->default_sux() == fsux) {
1414           goto_node->set_direction(Goto::not_taken);
1415         } else {
1416           ShouldNotReachHere();
1417         }
1418       }
1419       return;
1420     }
1421   }
1422 }
1423 
1424 
1425 void GraphBuilder::if_zero(ValueType* type, If::Condition cond) {
1426   Value y = append(new Constant(intZero));
1427   ValueStack* state_before = copy_state_before();
1428   Value x = ipop();
1429   if_node(x, cond, y, state_before);
1430 }
1431 
1432 
1433 void GraphBuilder::if_null(ValueType* type, If::Condition cond) {
1434   Value y = append(new Constant(objectNull));
1435   ValueStack* state_before = copy_state_before();
1436   Value x = apop();
1437   if_node(x, cond, y, state_before);
1438 }
1439 
1440 
1441 void GraphBuilder::if_same(ValueType* type, If::Condition cond) {
1442   ValueStack* state_before = copy_state_before();
1443   Value y = pop(type);
1444   Value x = pop(type);
1445   if_node(x, cond, y, state_before);
1446 }
1447 
1448 
1449 void GraphBuilder::jsr(int dest) {
1450   // We only handle well-formed jsrs (those which are "block-structured").
1451   // If the bytecodes are strange (jumping out of a jsr block) then we
1452   // might end up trying to re-parse a block containing a jsr which
1453   // has already been activated. Watch for this case and bail out.
1454   for (ScopeData* cur_scope_data = scope_data();
1455        cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
1456        cur_scope_data = cur_scope_data->parent()) {
1457     if (cur_scope_data->jsr_entry_bci() == dest) {
1458       BAILOUT("too-complicated jsr/ret structure");
1459     }
1460   }
1461 
1462   push(addressType, append(new Constant(new AddressConstant(next_bci()))));
1463   if (!try_inline_jsr(dest)) {
1464     return; // bailed out while parsing and inlining subroutine
1465   }
1466 }
1467 
1468 
1469 void GraphBuilder::ret(int local_index) {
1470   if (!parsing_jsr()) BAILOUT("ret encountered while not parsing subroutine");
1471 
1472   if (local_index != scope_data()->jsr_return_address_local()) {
1473     BAILOUT("can not handle complicated jsr/ret constructs");
1474   }
1475 
1476   // Rets simply become (NON-SAFEPOINT) gotos to the jsr continuation
1477   append(new Goto(scope_data()->jsr_continuation(), false));
1478 }
1479 
1480 
1481 void GraphBuilder::table_switch() {
1482   Bytecode_tableswitch sw(stream());
1483   const int l = sw.length();
1484   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1485     // total of 2 successors => use If instead of switch
1486     // Note: This code should go into the canonicalizer as soon as it can
1487     //       can handle canonicalized forms that contain more than one node.
1488     Value key = append(new Constant(new IntConstant(sw.low_key())));
1489     BlockBegin* tsux = block_at(bci() + sw.dest_offset_at(0));
1490     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1491     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1492     // In case of loop invariant code motion or predicate insertion
1493     // before the body of a loop the state is needed
1494     ValueStack* state_before = copy_state_if_bb(is_bb);
1495     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1496   } else {
1497     // collect successors
1498     BlockList* sux = new BlockList(l + 1, NULL);
1499     int i;
1500     bool has_bb = false;
1501     for (i = 0; i < l; i++) {
1502       sux->at_put(i, block_at(bci() + sw.dest_offset_at(i)));
1503       if (sw.dest_offset_at(i) < 0) has_bb = true;
1504     }
1505     // add default successor
1506     if (sw.default_offset() < 0) has_bb = true;
1507     sux->at_put(i, block_at(bci() + sw.default_offset()));
1508     // In case of loop invariant code motion or predicate insertion
1509     // before the body of a loop the state is needed
1510     ValueStack* state_before = copy_state_if_bb(has_bb);
1511     Instruction* res = append(new TableSwitch(ipop(), sux, sw.low_key(), state_before, has_bb));
1512 #ifdef ASSERT
1513     if (res->as_Goto()) {
1514       for (i = 0; i < l; i++) {
1515         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1516           assert(res->as_Goto()->is_safepoint() == sw.dest_offset_at(i) < 0, "safepoint state of Goto returned by canonicalizer incorrect");
1517         }
1518       }
1519     }
1520 #endif
1521   }
1522 }
1523 
1524 
1525 void GraphBuilder::lookup_switch() {
1526   Bytecode_lookupswitch sw(stream());
1527   const int l = sw.number_of_pairs();
1528   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1529     // total of 2 successors => use If instead of switch
1530     // Note: This code should go into the canonicalizer as soon as it can
1531     //       can handle canonicalized forms that contain more than one node.
1532     // simplify to If
1533     LookupswitchPair pair = sw.pair_at(0);
1534     Value key = append(new Constant(new IntConstant(pair.match())));
1535     BlockBegin* tsux = block_at(bci() + pair.offset());
1536     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1537     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1538     // In case of loop invariant code motion or predicate insertion
1539     // before the body of a loop the state is needed
1540     ValueStack* state_before = copy_state_if_bb(is_bb);;
1541     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1542   } else {
1543     // collect successors & keys
1544     BlockList* sux = new BlockList(l + 1, NULL);
1545     intArray* keys = new intArray(l, l, 0);
1546     int i;
1547     bool has_bb = false;
1548     for (i = 0; i < l; i++) {
1549       LookupswitchPair pair = sw.pair_at(i);
1550       if (pair.offset() < 0) has_bb = true;
1551       sux->at_put(i, block_at(bci() + pair.offset()));
1552       keys->at_put(i, pair.match());
1553     }
1554     // add default successor
1555     if (sw.default_offset() < 0) has_bb = true;
1556     sux->at_put(i, block_at(bci() + sw.default_offset()));
1557     // In case of loop invariant code motion or predicate insertion
1558     // before the body of a loop the state is needed
1559     ValueStack* state_before = copy_state_if_bb(has_bb);
1560     Instruction* res = append(new LookupSwitch(ipop(), sux, keys, state_before, has_bb));
1561 #ifdef ASSERT
1562     if (res->as_Goto()) {
1563       for (i = 0; i < l; i++) {
1564         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1565           assert(res->as_Goto()->is_safepoint() == sw.pair_at(i).offset() < 0, "safepoint state of Goto returned by canonicalizer incorrect");
1566         }
1567       }
1568     }
1569 #endif
1570   }
1571 }
1572 
1573 void GraphBuilder::call_register_finalizer() {
1574   // If the receiver requires finalization then emit code to perform
1575   // the registration on return.
1576 
1577   // Gather some type information about the receiver
1578   Value receiver = state()->local_at(0);
1579   assert(receiver != NULL, "must have a receiver");
1580   ciType* declared_type = receiver->declared_type();
1581   ciType* exact_type = receiver->exact_type();
1582   if (exact_type == NULL &&
1583       receiver->as_Local() &&
1584       receiver->as_Local()->java_index() == 0) {
1585     ciInstanceKlass* ik = compilation()->method()->holder();
1586     if (ik->is_final()) {
1587       exact_type = ik;
1588     } else if (UseCHA && !(ik->has_subklass() || ik->is_interface())) {
1589       // test class is leaf class
1590       compilation()->dependency_recorder()->assert_leaf_type(ik);
1591       exact_type = ik;
1592     } else {
1593       declared_type = ik;
1594     }
1595   }
1596 
1597   // see if we know statically that registration isn't required
1598   bool needs_check = true;
1599   if (exact_type != NULL) {
1600     needs_check = exact_type->as_instance_klass()->has_finalizer();
1601   } else if (declared_type != NULL) {
1602     ciInstanceKlass* ik = declared_type->as_instance_klass();
1603     if (!Dependencies::has_finalizable_subclass(ik)) {
1604       compilation()->dependency_recorder()->assert_has_no_finalizable_subclasses(ik);
1605       needs_check = false;
1606     }
1607   }
1608 
1609   if (needs_check) {
1610     // Perform the registration of finalizable objects.
1611     ValueStack* state_before = copy_state_for_exception();
1612     load_local(objectType, 0);
1613     append_split(new Intrinsic(voidType, vmIntrinsics::_Object_init,
1614                                state()->pop_arguments(1),
1615                                true, state_before, true));
1616   }
1617 }
1618 
1619 
1620 void GraphBuilder::method_return(Value x, bool ignore_return) {
1621   if (RegisterFinalizersAtInit &&
1622       method()->intrinsic_id() == vmIntrinsics::_Object_init) {
1623     call_register_finalizer();
1624   }
1625 
1626   // The conditions for a memory barrier are described in Parse::do_exits().
1627   bool need_mem_bar = false;
1628   if ((method()->is_object_constructor() || method()->is_static_init_factory()) &&
1629        (scope()->wrote_final() ||
1630          (AlwaysSafeConstructors && scope()->wrote_fields()) ||
1631          (support_IRIW_for_not_multiple_copy_atomic_cpu && scope()->wrote_volatile()))) {
1632     need_mem_bar = true;
1633   }
1634 
1635   BasicType bt = method()->return_type()->basic_type();
1636   switch (bt) {
1637     case T_BYTE:
1638     {
1639       Value shift = append(new Constant(new IntConstant(24)));
1640       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1641       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1642       break;
1643     }
1644     case T_SHORT:
1645     {
1646       Value shift = append(new Constant(new IntConstant(16)));
1647       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1648       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1649       break;
1650     }
1651     case T_CHAR:
1652     {
1653       Value mask = append(new Constant(new IntConstant(0xFFFF)));
1654       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1655       break;
1656     }
1657     case T_BOOLEAN:
1658     {
1659       Value mask = append(new Constant(new IntConstant(1)));
1660       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1661       break;
1662     }
1663     default:
1664       break;
1665   }
1666 
1667   // Check to see whether we are inlining. If so, Return
1668   // instructions become Gotos to the continuation point.
1669   if (continuation() != NULL) {
1670 
1671     int invoke_bci = state()->caller_state()->bci();
1672 
1673     if (x != NULL  && !ignore_return) {
1674       ciMethod* caller = state()->scope()->caller()->method();
1675       Bytecodes::Code invoke_raw_bc = caller->raw_code_at_bci(invoke_bci);
1676       if (invoke_raw_bc == Bytecodes::_invokehandle || invoke_raw_bc == Bytecodes::_invokedynamic) {
1677         ciType* declared_ret_type = caller->get_declared_signature_at_bci(invoke_bci)->return_type();
1678         if (declared_ret_type->is_klass() && x->exact_type() == NULL &&
1679             x->declared_type() != declared_ret_type && declared_ret_type != compilation()->env()->Object_klass()) {
1680           x = append(new TypeCast(declared_ret_type->as_klass(), x, copy_state_before()));
1681         }
1682       }
1683     }
1684 
1685     assert(!method()->is_synchronized() || InlineSynchronizedMethods, "can not inline synchronized methods yet");
1686 
1687     if (compilation()->env()->dtrace_method_probes()) {
1688       // Report exit from inline methods
1689       Values* args = new Values(1);
1690       args->push(append(new Constant(new MethodConstant(method()))));
1691       append(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args));
1692     }
1693 
1694     // If the inlined method is synchronized, the monitor must be
1695     // released before we jump to the continuation block.
1696     if (method()->is_synchronized()) {
1697       assert(state()->locks_size() == 1, "receiver must be locked here");
1698       monitorexit(state()->lock_at(0), SynchronizationEntryBCI);
1699     }
1700 
1701     if (need_mem_bar) {
1702       append(new MemBar(lir_membar_storestore));
1703     }
1704 
1705     // State at end of inlined method is the state of the caller
1706     // without the method parameters on stack, including the
1707     // return value, if any, of the inlined method on operand stack.
1708     set_state(state()->caller_state()->copy_for_parsing());
1709     if (x != NULL) {
1710       if (!ignore_return) {
1711         state()->push(x->type(), x);
1712       }
1713       if (profile_return() && x->type()->is_object_kind()) {
1714         ciMethod* caller = state()->scope()->method();
1715         profile_return_type(x, method(), caller, invoke_bci);
1716       }
1717     }
1718     Goto* goto_callee = new Goto(continuation(), false);
1719 
1720     // See whether this is the first return; if so, store off some
1721     // of the state for later examination
1722     if (num_returns() == 0) {
1723       set_inline_cleanup_info();
1724     }
1725 
1726     // The current bci() is in the wrong scope, so use the bci() of
1727     // the continuation point.
1728     append_with_bci(goto_callee, scope_data()->continuation()->bci());
1729     incr_num_returns();
1730     return;
1731   }
1732 
1733   state()->truncate_stack(0);
1734   if (method()->is_synchronized()) {
1735     // perform the unlocking before exiting the method
1736     Value receiver;
1737     if (!method()->is_static()) {
1738       receiver = _initial_state->local_at(0);
1739     } else {
1740       receiver = append(new Constant(new ClassConstant(method()->holder())));
1741     }
1742     append_split(new MonitorExit(receiver, state()->unlock()));
1743   }
1744 
1745   if (need_mem_bar) {
1746       append(new MemBar(lir_membar_storestore));
1747   }
1748 
1749   assert(!ignore_return, "Ignoring return value works only for inlining");
1750   append(new Return(x));
1751 }
1752 
1753 Value GraphBuilder::make_constant(ciConstant field_value, ciField* field) {
1754   if (!field_value.is_valid())  return NULL;
1755 
1756   BasicType field_type = field_value.basic_type();
1757   ValueType* value = as_ValueType(field_value);
1758 
1759   // Attach dimension info to stable arrays.
1760   if (FoldStableValues &&
1761       field->is_stable() && field_type == T_ARRAY && !field_value.is_null_or_zero()) {
1762     ciArray* array = field_value.as_object()->as_array();
1763     jint dimension = field->type()->as_array_klass()->dimension();
1764     value = new StableArrayConstant(array, dimension);
1765   }
1766 
1767   switch (field_type) {
1768     case T_ARRAY:
1769     case T_OBJECT:
1770       if (field_value.as_object()->should_be_constant()) {
1771         return new Constant(value);
1772       }
1773       return NULL; // Not a constant.
1774     default:
1775       return new Constant(value);
1776   }
1777 }
1778 
1779 void GraphBuilder::copy_inline_content(ciInlineKlass* vk, Value src, int src_off, Value dest, int dest_off, ValueStack* state_before, ciField* enclosing_field) {
1780   for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1781     ciField* inner_field = vk->nonstatic_field_at(i);
1782     assert(!inner_field->is_flattened(), "the iteration over nested fields is handled by the loop itself");
1783     int off = inner_field->offset() - vk->first_field_offset();
1784     LoadField* load = new LoadField(src, src_off + off, inner_field, false, state_before, false);
1785     Value replacement = append(load);
1786     StoreField* store = new StoreField(dest, dest_off + off, inner_field, replacement, false, state_before, false);
1787     store->set_enclosing_field(enclosing_field);
1788     append(store);
1789   }
1790 }
1791 
1792 void GraphBuilder::access_field(Bytecodes::Code code) {
1793   bool will_link;
1794   ciField* field = stream()->get_field(will_link);
1795   ciInstanceKlass* holder = field->holder();
1796   BasicType field_type = field->type()->basic_type();
1797   ValueType* type = as_ValueType(field_type);
1798 
1799   // call will_link again to determine if the field is valid.
1800   const bool needs_patching = !holder->is_loaded() ||
1801                               !field->will_link(method(), code) ||
1802                               (!field->is_flattened() && PatchALot);
1803 
1804   ValueStack* state_before = NULL;
1805   if (!holder->is_initialized() || needs_patching) {
1806     // save state before instruction for debug info when
1807     // deoptimization happens during patching
1808     state_before = copy_state_before();
1809   }
1810 
1811   Value obj = NULL;
1812   if (code == Bytecodes::_getstatic || code == Bytecodes::_putstatic) {
1813     if (state_before != NULL) {
1814       // build a patching constant
1815       obj = new Constant(new InstanceConstant(holder->java_mirror()), state_before);
1816     } else {
1817       obj = new Constant(new InstanceConstant(holder->java_mirror()));
1818     }
1819   }
1820 
1821   if (field->is_final() && code == Bytecodes::_putfield) {
1822     scope()->set_wrote_final();
1823   }
1824 
1825   if (code == Bytecodes::_putfield) {
1826     scope()->set_wrote_fields();
1827     if (field->is_volatile()) {
1828       scope()->set_wrote_volatile();
1829     }
1830   }
1831 
1832   int offset = !needs_patching ? field->offset() : -1;
1833   switch (code) {
1834     case Bytecodes::_getstatic: {
1835       // check for compile-time constants, i.e., initialized static final fields
1836       Value constant = NULL;
1837       if (field->is_static_constant() && !PatchALot) {
1838         ciConstant field_value = field->constant_value();
1839         assert(!field->is_stable() || !field_value.is_null_or_zero(),
1840                "stable static w/ default value shouldn't be a constant");
1841         constant = make_constant(field_value, field);
1842       } else if (field->is_null_free() && field->type()->as_instance_klass()->is_initialized() &&
1843                  field->type()->as_inline_klass()->is_empty()) {
1844         // Loading from a field of an empty inline type. Just return the default instance.
1845         constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1846       }
1847       if (constant != NULL) {
1848         push(type, append(constant));
1849       } else {
1850         if (state_before == NULL) {
1851           state_before = copy_state_for_exception();
1852         }
1853         LoadField* load_field = new LoadField(append(obj), offset, field, true,
1854                                         state_before, needs_patching);
1855         push(type, append(load_field));
1856       }
1857       break;
1858     }
1859     case Bytecodes::_putstatic: {
1860       Value val = pop(type);
1861       if (state_before == NULL) {
1862         state_before = copy_state_for_exception();
1863       }
1864       if (field_type == T_BOOLEAN) {
1865         Value mask = append(new Constant(new IntConstant(1)));
1866         val = append(new LogicOp(Bytecodes::_iand, val, mask));
1867       }
1868       if (field->is_null_free() && field->type()->is_loaded() && field->type()->as_inline_klass()->is_empty()) {
1869         // Storing to a field of an empty inline type. Ignore.
1870         break;
1871       }
1872       append(new StoreField(append(obj), offset, field, val, true, state_before, needs_patching));
1873       break;
1874     }
1875     case Bytecodes::_getfield: {
1876       // Check for compile-time constants, i.e., trusted final non-static fields.
1877       Value constant = NULL;
1878       if (state_before == NULL && field->is_flattened()) {
1879         // Save the entire state and re-execute on deopt when accessing flattened fields
1880         assert(Interpreter::bytecode_should_reexecute(code), "should reexecute");
1881         state_before = copy_state_before();
1882       }
1883       if (!has_pending_field_access() && !has_pending_load_indexed()) {
1884         obj = apop();
1885         ObjectType* obj_type = obj->type()->as_ObjectType();
1886         if (field->is_null_free() && field->type()->as_instance_klass()->is_initialized()
1887             && field->type()->as_inline_klass()->is_empty()) {
1888           // Loading from a field of an empty inline type. Just return the default instance.
1889           null_check(obj);
1890           constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1891         } else if (field->is_constant() && !field->is_flattened() && obj_type->is_constant() && !PatchALot) {
1892           ciObject* const_oop = obj_type->constant_value();
1893           if (!const_oop->is_null_object() && const_oop->is_loaded()) {
1894             ciConstant field_value = field->constant_value_of(const_oop);
1895             if (field_value.is_valid()) {
1896               if (field->is_null_free() && field_value.is_null_or_zero()) {
1897                 // Non-flattened inline type field. Replace null by the default value.
1898                 constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1899               } else {
1900                 constant = make_constant(field_value, field);
1901               }
1902               // For CallSite objects add a dependency for invalidation of the optimization.
1903               if (field->is_call_site_target()) {
1904                 ciCallSite* call_site = const_oop->as_call_site();
1905                 if (!call_site->is_fully_initialized_constant_call_site()) {
1906                   ciMethodHandle* target = field_value.as_object()->as_method_handle();
1907                   dependency_recorder()->assert_call_site_target_value(call_site, target);
1908                 }
1909               }
1910             }
1911           }
1912         }
1913       }
1914       if (constant != NULL) {
1915         push(type, append(constant));
1916       } else {
1917         if (state_before == NULL) {
1918           state_before = copy_state_for_exception();
1919         }
1920         if (!field->is_flattened()) {
1921           if (has_pending_field_access()) {
1922             assert(!needs_patching, "Can't patch delayed field access");
1923             obj = pending_field_access()->obj();
1924             offset += pending_field_access()->offset() - field->holder()->as_inline_klass()->first_field_offset();
1925             field = pending_field_access()->holder()->get_field_by_offset(offset, false);
1926             assert(field != NULL, "field not found");
1927             set_pending_field_access(NULL);
1928           } else if (has_pending_load_indexed()) {
1929             assert(!needs_patching, "Can't patch delayed field access");
1930             pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
1931             LoadIndexed* li = pending_load_indexed()->load_instr();
1932             li->set_type(type);
1933             push(type, append(li));
1934             set_pending_load_indexed(NULL);




1935             break;
1936           }
1937           LoadField* load = new LoadField(obj, offset, field, false, state_before, needs_patching);
1938           Value replacement = !needs_patching ? _memory->load(load) : load;
1939           if (replacement != load) {
1940             assert(replacement->is_linked() || !replacement->can_be_linked(), "should already by linked");
1941             // Writing an (integer) value to a boolean, byte, char or short field includes an implicit narrowing
1942             // conversion. Emit an explicit conversion here to get the correct field value after the write.
1943             switch (field_type) {
1944             case T_BOOLEAN:
1945             case T_BYTE:
1946               replacement = append(new Convert(Bytecodes::_i2b, replacement, type));
1947               break;
1948             case T_CHAR:
1949               replacement = append(new Convert(Bytecodes::_i2c, replacement, type));
1950               break;
1951             case T_SHORT:
1952               replacement = append(new Convert(Bytecodes::_i2s, replacement, type));
1953               break;
1954             default:
1955               break;
1956             }
1957             push(type, replacement);
1958           } else {
1959             push(type, append(load));
1960           }
1961         } else {
1962           // Look at the next bytecode to check if we can delay the field access
1963           bool can_delay_access = false;
1964           ciBytecodeStream s(method());
1965           s.force_bci(bci());
1966           s.next();
1967           if (s.cur_bc() == Bytecodes::_getfield && !needs_patching) {
1968             ciField* next_field = s.get_field(will_link);
1969             bool next_needs_patching = !next_field->holder()->is_loaded() ||
1970                                        !next_field->will_link(method(), Bytecodes::_getfield) ||
1971                                        PatchALot;
1972             can_delay_access = C1UseDelayedFlattenedFieldReads && !next_needs_patching;
1973           }
1974           if (can_delay_access) {
1975             if (has_pending_load_indexed()) {
1976               pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
1977             } else if (has_pending_field_access()) {
1978               pending_field_access()->inc_offset(offset - field->holder()->as_inline_klass()->first_field_offset());
1979             } else {
1980               null_check(obj);
1981               DelayedFieldAccess* dfa = new DelayedFieldAccess(obj, field->holder(), field->offset());
1982               set_pending_field_access(dfa);
1983             }
1984           } else {
1985             ciInlineKlass* inline_klass = field->type()->as_inline_klass();
1986             scope()->set_wrote_final();
1987             scope()->set_wrote_fields();
1988             bool need_membar = false;
1989             if (inline_klass->is_initialized() && inline_klass->is_empty()) {
1990               apush(append(new Constant(new InstanceConstant(inline_klass->default_instance()))));
1991               if (has_pending_field_access()) {
1992                 set_pending_field_access(NULL);
1993               } else if (has_pending_load_indexed()) {
1994                 set_pending_load_indexed(NULL);
1995               }
1996             } else if (has_pending_load_indexed()) {
1997               assert(!needs_patching, "Can't patch delayed field access");
1998               pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
1999               NewInlineTypeInstance* vt = new NewInlineTypeInstance(inline_klass, pending_load_indexed()->state_before());
2000               _memory->new_instance(vt);
2001               pending_load_indexed()->load_instr()->set_vt(vt);
2002               apush(append_split(vt));
2003               append(pending_load_indexed()->load_instr());
2004               set_pending_load_indexed(NULL);
2005               need_membar = true;
2006             } else {
2007               NewInlineTypeInstance* new_instance = new NewInlineTypeInstance(inline_klass, state_before);
2008               _memory->new_instance(new_instance);
2009               apush(append_split(new_instance));
2010               assert(!needs_patching, "Can't patch flattened inline type field access");
2011               if (has_pending_field_access()) {
2012                 copy_inline_content(inline_klass, pending_field_access()->obj(),
2013                                     pending_field_access()->offset() + field->offset() - field->holder()->as_inline_klass()->first_field_offset(),
2014                                     new_instance, inline_klass->first_field_offset(), state_before);
2015                 set_pending_field_access(NULL);
2016               } else {
2017                 copy_inline_content(inline_klass, obj, field->offset(), new_instance, inline_klass->first_field_offset(), state_before);
2018               }
2019               need_membar = true;
2020             }
2021             if (need_membar) {
2022               // If we allocated a new instance ensure the stores to copy the
2023               // field contents are visible before any subsequent store that
2024               // publishes this reference.
2025               append(new MemBar(lir_membar_storestore));
2026             }
2027           }
2028         }
2029       }
2030       break;
2031     }
2032     case Bytecodes::_putfield: {
2033       Value val = pop(type);
2034       obj = apop();
2035       if (state_before == NULL) {
2036         state_before = copy_state_for_exception();
2037       }
2038       if (field_type == T_BOOLEAN) {
2039         Value mask = append(new Constant(new IntConstant(1)));
2040         val = append(new LogicOp(Bytecodes::_iand, val, mask));
2041       }
2042       if (field->is_null_free() && field->type()->is_loaded() && field->type()->as_inline_klass()->is_empty()) {
2043         // Storing to a field of an empty inline type. Ignore.
2044         null_check(obj);
2045       } else if (!field->is_flattened()) {
2046         StoreField* store = new StoreField(obj, offset, field, val, false, state_before, needs_patching);
2047         if (!needs_patching) store = _memory->store(store);
2048         if (store != NULL) {
2049           append(store);
2050         }
2051       } else {
2052         assert(!needs_patching, "Can't patch flattened inline type field access");
2053         ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2054         copy_inline_content(inline_klass, val, inline_klass->first_field_offset(), obj, offset, state_before, field);
2055       }
2056       break;
2057     }
2058     default:
2059       ShouldNotReachHere();
2060       break;
2061   }
2062 }
2063 
2064 // Baseline version of withfield, allocate every time
2065 void GraphBuilder::withfield(int field_index) {
2066   // Save the entire state and re-execute on deopt
2067   ValueStack* state_before = copy_state_before();
2068   state_before->set_should_reexecute(true);
2069 
2070   bool will_link;
2071   ciField* field_modify = stream()->get_field(will_link);
2072   ciInstanceKlass* holder = field_modify->holder();
2073   BasicType field_type = field_modify->type()->basic_type();
2074   ValueType* type = as_ValueType(field_type);
2075   Value val = pop(type);
2076   Value obj = apop();
2077 
2078   if (!holder->is_loaded() || !holder->is_inlinetype()) {
2079     apush(append_split(new Deoptimize(holder, state_before)));
2080     return;
2081   }
2082 
2083   // call will_link again to determine if the field is valid.
2084   const bool needs_patching = !field_modify->will_link(method(), Bytecodes::_withfield) ||
2085                               (!field_modify->is_flattened() && PatchALot);
2086   const int offset_modify = !needs_patching ? field_modify->offset() : -1;
2087 
2088   scope()->set_wrote_final();
2089   scope()->set_wrote_fields();
2090 
2091   NewInlineTypeInstance* new_instance;
2092   if (obj->as_NewInlineTypeInstance() != NULL && obj->as_NewInlineTypeInstance()->in_larval_state()) {
2093     new_instance = obj->as_NewInlineTypeInstance();
2094     apush(append_split(new_instance));
2095   } else {
2096     new_instance = new NewInlineTypeInstance(holder->as_inline_klass(), state_before);
2097     _memory->new_instance(new_instance);
2098     apush(append_split(new_instance));
2099 
2100     // Initialize fields which are not modified
2101     for (int i = 0; i < holder->nof_nonstatic_fields(); i++) {
2102       ciField* field = holder->nonstatic_field_at(i);
2103       int offset = field->offset();
2104       // Don't use offset_modify here, it might be set to -1 if needs_patching
2105       if (offset != field_modify->offset()) {
2106         if (field->is_flattened()) {
2107           ciInlineKlass* vk = field->type()->as_inline_klass();
2108           if (!vk->is_empty()) {
2109             copy_inline_content(vk, obj, offset, new_instance, vk->first_field_offset(), state_before, field);
2110           }
2111         } else {
2112           LoadField* load = new LoadField(obj, offset, field, false, state_before, false);
2113           Value replacement = append(load);
2114           StoreField* store = new StoreField(new_instance, offset, field, replacement, false, state_before, false);
2115           append(store);
2116         }
2117       }
2118     }
2119   }
2120 
2121   // Field to modify
2122   if (field_type == T_BOOLEAN) {
2123     Value mask = append(new Constant(new IntConstant(1)));
2124     val = append(new LogicOp(Bytecodes::_iand, val, mask));
2125   }
2126   if (field_modify->is_flattened()) {
2127     assert(!needs_patching, "Can't patch flattened inline type field access");
2128     ciInlineKlass* vk = field_modify->type()->as_inline_klass();
2129     if (!vk->is_empty()) {
2130       copy_inline_content(vk, val, vk->first_field_offset(), new_instance, offset_modify, state_before, field_modify);
2131     }
2132   } else {
2133     StoreField* store = new StoreField(new_instance, offset_modify, field_modify, val, false, state_before, needs_patching);
2134     append(store);
2135   }
2136 }
2137 
2138 Dependencies* GraphBuilder::dependency_recorder() const {
2139   assert(DeoptC1, "need debug information");
2140   return compilation()->dependency_recorder();
2141 }
2142 
2143 // How many arguments do we want to profile?
2144 Values* GraphBuilder::args_list_for_profiling(ciMethod* target, int& start, bool may_have_receiver) {
2145   int n = 0;
2146   bool has_receiver = may_have_receiver && Bytecodes::has_receiver(method()->java_code_at_bci(bci()));
2147   start = has_receiver ? 1 : 0;
2148   if (profile_arguments()) {
2149     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2150     if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
2151       n = data->is_CallTypeData() ? data->as_CallTypeData()->number_of_arguments() : data->as_VirtualCallTypeData()->number_of_arguments();
2152     }
2153   }
2154   // If we are inlining then we need to collect arguments to profile parameters for the target
2155   if (profile_parameters() && target != NULL) {
2156     if (target->method_data() != NULL && target->method_data()->parameters_type_data() != NULL) {
2157       // The receiver is profiled on method entry so it's included in
2158       // the number of parameters but here we're only interested in
2159       // actual arguments.
2160       n = MAX2(n, target->method_data()->parameters_type_data()->number_of_parameters() - start);
2161     }
2162   }
2163   if (n > 0) {
2164     return new Values(n);
2165   }
2166   return NULL;
2167 }
2168 
2169 void GraphBuilder::check_args_for_profiling(Values* obj_args, int expected) {
2170 #ifdef ASSERT
2171   bool ignored_will_link;
2172   ciSignature* declared_signature = NULL;
2173   ciMethod* real_target = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
2174   assert(expected == obj_args->max_length() || real_target->is_method_handle_intrinsic(), "missed on arg?");
2175 #endif
2176 }
2177 
2178 // Collect arguments that we want to profile in a list
2179 Values* GraphBuilder::collect_args_for_profiling(Values* args, ciMethod* target, bool may_have_receiver) {
2180   int start = 0;
2181   Values* obj_args = args_list_for_profiling(target, start, may_have_receiver);
2182   if (obj_args == NULL) {
2183     return NULL;
2184   }
2185   int s = obj_args->max_length();
2186   // if called through method handle invoke, some arguments may have been popped
2187   for (int i = start, j = 0; j < s && i < args->length(); i++) {
2188     if (args->at(i)->type()->is_object_kind()) {
2189       obj_args->push(args->at(i));
2190       j++;
2191     }
2192   }
2193   check_args_for_profiling(obj_args, s);
2194   return obj_args;
2195 }
2196 
2197 
2198 void GraphBuilder::invoke(Bytecodes::Code code) {
2199   bool will_link;
2200   ciSignature* declared_signature = NULL;
2201   ciMethod*             target = stream()->get_method(will_link, &declared_signature);
2202   ciKlass*              holder = stream()->get_declared_method_holder();
2203   const Bytecodes::Code bc_raw = stream()->cur_bc_raw();
2204   assert(declared_signature != NULL, "cannot be null");
2205   assert(will_link == target->is_loaded(), "");
2206 
2207   ciInstanceKlass* klass = target->holder();
2208   assert(!target->is_loaded() || klass->is_loaded(), "loaded target must imply loaded klass");
2209 
2210   // check if CHA possible: if so, change the code to invoke_special
2211   ciInstanceKlass* calling_klass = method()->holder();
2212   ciInstanceKlass* callee_holder = ciEnv::get_instance_klass_for_declared_method_holder(holder);
2213   ciInstanceKlass* actual_recv = callee_holder;
2214 
2215   CompileLog* log = compilation()->log();
2216   if (log != NULL)
2217       log->elem("call method='%d' instr='%s'",
2218                 log->identify(target),
2219                 Bytecodes::name(code));
2220 
2221   // invoke-special-super
2222   if (bc_raw == Bytecodes::_invokespecial && !target->is_object_constructor()) {
2223     ciInstanceKlass* sender_klass = calling_klass;
2224     if (sender_klass->is_interface()) {
2225       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
2226       Value receiver = state()->stack_at(index);
2227       CheckCast* c = new CheckCast(sender_klass, receiver, copy_state_before());
2228       c->set_invokespecial_receiver_check();
2229       state()->stack_at_put(index, append_split(c));
2230     }
2231   }
2232 
2233   // Some methods are obviously bindable without any type checks so
2234   // convert them directly to an invokespecial or invokestatic.
2235   if (target->is_loaded() && !target->is_abstract() && target->can_be_statically_bound()) {
2236     switch (bc_raw) {
2237     case Bytecodes::_invokevirtual:
2238       code = Bytecodes::_invokespecial;
2239       break;
2240     case Bytecodes::_invokehandle:
2241       code = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokespecial;
2242       break;
2243     default:
2244       break;
2245     }
2246   } else {
2247     if (bc_raw == Bytecodes::_invokehandle) {
2248       assert(!will_link, "should come here only for unlinked call");
2249       code = Bytecodes::_invokespecial;
2250     }
2251   }
2252 
2253   // Push appendix argument (MethodType, CallSite, etc.), if one.
2254   bool patch_for_appendix = false;
2255   int patching_appendix_arg = 0;
2256   if (Bytecodes::has_optional_appendix(bc_raw) && (!will_link || PatchALot)) {
2257     Value arg = append(new Constant(new ObjectConstant(compilation()->env()->unloaded_ciinstance()), copy_state_before()));
2258     apush(arg);
2259     patch_for_appendix = true;
2260     patching_appendix_arg = (will_link && stream()->has_appendix()) ? 0 : 1;
2261   } else if (stream()->has_appendix()) {
2262     ciObject* appendix = stream()->get_appendix();
2263     Value arg = append(new Constant(new ObjectConstant(appendix)));
2264     apush(arg);
2265   }
2266 
2267   ciMethod* cha_monomorphic_target = NULL;
2268   ciMethod* exact_target = NULL;
2269   Value better_receiver = NULL;
2270   if (UseCHA && DeoptC1 && target->is_loaded() &&
2271       !(// %%% FIXME: Are both of these relevant?
2272         target->is_method_handle_intrinsic() ||
2273         target->is_compiled_lambda_form()) &&
2274       !patch_for_appendix) {
2275     Value receiver = NULL;
2276     ciInstanceKlass* receiver_klass = NULL;
2277     bool type_is_exact = false;
2278     // try to find a precise receiver type
2279     if (will_link && !target->is_static()) {
2280       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
2281       receiver = state()->stack_at(index);
2282       ciType* type = receiver->exact_type();
2283       if (type != NULL && type->is_loaded() &&
2284           type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
2285         receiver_klass = (ciInstanceKlass*) type;
2286         type_is_exact = true;
2287       }
2288       if (type == NULL) {
2289         type = receiver->declared_type();
2290         if (type != NULL && type->is_loaded() &&
2291             type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
2292           receiver_klass = (ciInstanceKlass*) type;
2293           if (receiver_klass->is_leaf_type() && !receiver_klass->is_final()) {
2294             // Insert a dependency on this type since
2295             // find_monomorphic_target may assume it's already done.
2296             dependency_recorder()->assert_leaf_type(receiver_klass);
2297             type_is_exact = true;
2298           }
2299         }
2300       }
2301     }
2302     if (receiver_klass != NULL && type_is_exact &&
2303         receiver_klass->is_loaded() && code != Bytecodes::_invokespecial) {
2304       // If we have the exact receiver type we can bind directly to
2305       // the method to call.
2306       exact_target = target->resolve_invoke(calling_klass, receiver_klass);
2307       if (exact_target != NULL) {
2308         target = exact_target;
2309         code = Bytecodes::_invokespecial;
2310       }
2311     }
2312     if (receiver_klass != NULL &&
2313         receiver_klass->is_subtype_of(actual_recv) &&
2314         actual_recv->is_initialized()) {
2315       actual_recv = receiver_klass;
2316     }
2317 
2318     if ((code == Bytecodes::_invokevirtual && callee_holder->is_initialized()) ||
2319         (code == Bytecodes::_invokeinterface && callee_holder->is_initialized() && !actual_recv->is_interface())) {
2320       // Use CHA on the receiver to select a more precise method.
2321       cha_monomorphic_target = target->find_monomorphic_target(calling_klass, callee_holder, actual_recv);
2322     } else if (code == Bytecodes::_invokeinterface && callee_holder->is_loaded() && receiver != NULL) {
2323       assert(callee_holder->is_interface(), "invokeinterface to non interface?");
2324       // If there is only one implementor of this interface then we
2325       // may be able bind this invoke directly to the implementing
2326       // klass but we need both a dependence on the single interface
2327       // and on the method we bind to.  Additionally since all we know
2328       // about the receiver type is the it's supposed to implement the
2329       // interface we have to insert a check that it's the class we
2330       // expect.  Interface types are not checked by the verifier so
2331       // they are roughly equivalent to Object.
2332       // The number of implementors for declared_interface is less or
2333       // equal to the number of implementors for target->holder() so
2334       // if number of implementors of target->holder() == 1 then
2335       // number of implementors for decl_interface is 0 or 1. If
2336       // it's 0 then no class implements decl_interface and there's
2337       // no point in inlining.
2338       ciInstanceKlass* declared_interface = callee_holder;
2339       ciInstanceKlass* singleton = declared_interface->unique_implementor();
2340       if (singleton != NULL) {
2341         assert(singleton != declared_interface, "not a unique implementor");
2342         cha_monomorphic_target = target->find_monomorphic_target(calling_klass, declared_interface, singleton);
2343         if (cha_monomorphic_target != NULL) {
2344           if (cha_monomorphic_target->holder() != compilation()->env()->Object_klass()) {
2345             // If CHA is able to bind this invoke then update the class
2346             // to match that class, otherwise klass will refer to the
2347             // interface.
2348             klass = cha_monomorphic_target->holder();
2349             actual_recv = declared_interface;
2350 
2351             // insert a check it's really the expected class.
2352             CheckCast* c = new CheckCast(klass, receiver, copy_state_for_exception());
2353             c->set_incompatible_class_change_check();
2354             c->set_direct_compare(klass->is_final());
2355             // pass the result of the checkcast so that the compiler has
2356             // more accurate type info in the inlinee
2357             better_receiver = append_split(c);
2358           } else {
2359             cha_monomorphic_target = NULL; // subtype check against Object is useless
2360           }
2361         }
2362       }
2363     }
2364   }
2365 
2366   if (cha_monomorphic_target != NULL) {
2367     assert(!target->can_be_statically_bound() || target == cha_monomorphic_target, "");
2368     assert(!cha_monomorphic_target->is_abstract(), "");
2369     if (!cha_monomorphic_target->can_be_statically_bound(actual_recv)) {
2370       // If we inlined because CHA revealed only a single target method,
2371       // then we are dependent on that target method not getting overridden
2372       // by dynamic class loading.  Be sure to test the "static" receiver
2373       // dest_method here, as opposed to the actual receiver, which may
2374       // falsely lead us to believe that the receiver is final or private.
2375       dependency_recorder()->assert_unique_concrete_method(actual_recv, cha_monomorphic_target, callee_holder, target);
2376     }
2377     code = Bytecodes::_invokespecial;
2378   }
2379 
2380   // check if we could do inlining
2381   if (!PatchALot && Inline && target->is_loaded() && callee_holder->is_linked() && !patch_for_appendix) {
2382     // callee is known => check if we have static binding
2383     if ((code == Bytecodes::_invokestatic && callee_holder->is_initialized()) || // invokestatic involves an initialization barrier on resolved klass
2384         code == Bytecodes::_invokespecial ||
2385         (code == Bytecodes::_invokevirtual && target->is_final_method()) ||
2386         code == Bytecodes::_invokedynamic) {
2387       // static binding => check if callee is ok
2388       ciMethod* inline_target = (cha_monomorphic_target != NULL) ? cha_monomorphic_target : target;
2389       bool holder_known = (cha_monomorphic_target != NULL) || (exact_target != NULL);
2390       bool success = try_inline(inline_target, holder_known, false /* ignore_return */, code, better_receiver);
2391 
2392       CHECK_BAILOUT();
2393       clear_inline_bailout();
2394 
2395       if (success) {
2396         // Register dependence if JVMTI has either breakpoint
2397         // setting or hotswapping of methods capabilities since they may
2398         // cause deoptimization.
2399         if (compilation()->env()->jvmti_can_hotswap_or_post_breakpoint()) {
2400           dependency_recorder()->assert_evol_method(inline_target);
2401         }
2402         return;
2403       }
2404     } else {
2405       print_inlining(target, "no static binding", /*success*/ false);
2406     }
2407   } else {
2408     print_inlining(target, "not inlineable", /*success*/ false);
2409   }
2410 
2411   // If we attempted an inline which did not succeed because of a
2412   // bailout during construction of the callee graph, the entire
2413   // compilation has to be aborted. This is fairly rare and currently
2414   // seems to only occur for jasm-generated classes which contain
2415   // jsr/ret pairs which are not associated with finally clauses and
2416   // do not have exception handlers in the containing method, and are
2417   // therefore not caught early enough to abort the inlining without
2418   // corrupting the graph. (We currently bail out with a non-empty
2419   // stack at a ret in these situations.)
2420   CHECK_BAILOUT();
2421 
2422   // inlining not successful => standard invoke
2423   ValueType* result_type = as_ValueType(declared_signature->return_type());
2424   ValueStack* state_before = copy_state_exhandling();
2425 
2426   // The bytecode (code) might change in this method so we are checking this very late.
2427   const bool has_receiver =
2428     code == Bytecodes::_invokespecial   ||
2429     code == Bytecodes::_invokevirtual   ||
2430     code == Bytecodes::_invokeinterface;
2431   Values* args = state()->pop_arguments(target->arg_size_no_receiver() + patching_appendix_arg);
2432   Value recv = has_receiver ? apop() : NULL;
2433 
2434   // A null check is required here (when there is a receiver) for any of the following cases
2435   // - invokespecial, always need a null check.
2436   // - invokevirtual, when the target is final and loaded. Calls to final targets will become optimized
2437   //   and require null checking. If the target is loaded a null check is emitted here.
2438   //   If the target isn't loaded the null check must happen after the call resolution. We achieve that
2439   //   by using the target methods unverified entry point (see CompiledIC::compute_monomorphic_entry).
2440   //   (The JVM specification requires that LinkageError must be thrown before a NPE. An unloaded target may
2441   //   potentially fail, and can't have the null check before the resolution.)
2442   // - A call that will be profiled. (But we can't add a null check when the target is unloaded, by the same
2443   //   reason as above, so calls with a receiver to unloaded targets can't be profiled.)
2444   //
2445   // Normal invokevirtual will perform the null check during lookup
2446 
2447   bool need_null_check = (code == Bytecodes::_invokespecial) ||
2448       (target->is_loaded() && (target->is_final_method() || (is_profiling() && profile_calls())));
2449 
2450   if (need_null_check) {
2451     if (recv != NULL) {
2452       null_check(recv);
2453     }
2454 
2455     if (is_profiling()) {
2456       // Note that we'd collect profile data in this method if we wanted it.
2457       compilation()->set_would_profile(true);
2458 
2459       if (profile_calls()) {
2460         assert(cha_monomorphic_target == NULL || exact_target == NULL, "both can not be set");
2461         ciKlass* target_klass = NULL;
2462         if (cha_monomorphic_target != NULL) {
2463           target_klass = cha_monomorphic_target->holder();
2464         } else if (exact_target != NULL) {
2465           target_klass = exact_target->holder();
2466         }
2467         profile_call(target, recv, target_klass, collect_args_for_profiling(args, NULL, false), false);
2468       }
2469     }
2470   }
2471 
2472   Invoke* result = new Invoke(code, result_type, recv, args, target, state_before,
2473                               declared_signature->returns_null_free_inline_type());
2474   // push result
2475   append_split(result);
2476 
2477   if (result_type != voidType) {
2478     push(result_type, round_fp(result));
2479   }
2480   if (profile_return() && result_type->is_object_kind()) {
2481     profile_return_type(result, target);
2482   }
2483 }
2484 
2485 
2486 void GraphBuilder::new_instance(int klass_index) {
2487   ValueStack* state_before = copy_state_exhandling();
2488   bool will_link;
2489   ciKlass* klass = stream()->get_klass(will_link);
2490   assert(klass->is_instance_klass(), "must be an instance klass");
2491   NewInstance* new_instance = new NewInstance(klass->as_instance_klass(), state_before, stream()->is_unresolved_klass());
2492   _memory->new_instance(new_instance);
2493   apush(append_split(new_instance));
2494 }
2495 
2496 void GraphBuilder::default_value(int klass_index) {
2497   bool will_link;
2498   ciKlass* klass = stream()->get_klass(will_link);
2499   if (!stream()->is_unresolved_klass() && klass->is_inlinetype() &&
2500       klass->as_inline_klass()->is_initialized()) {
2501     ciInlineKlass* vk = klass->as_inline_klass();
2502     apush(append(new Constant(new InstanceConstant(vk->default_instance()))));
2503   } else {
2504     apush(append_split(new Deoptimize(klass, copy_state_before())));
2505   }
2506 }
2507 
2508 void GraphBuilder::new_type_array() {
2509   ValueStack* state_before = copy_state_exhandling();
2510   apush(append_split(new NewTypeArray(ipop(), (BasicType)stream()->get_index(), state_before)));
2511 }
2512 
2513 
2514 void GraphBuilder::new_object_array() {
2515   bool will_link;
2516   ciKlass* klass = stream()->get_klass(will_link);
2517   bool null_free = stream()->has_Q_signature();
2518   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2519   NewArray* n = new NewObjectArray(klass, ipop(), state_before, null_free);
2520   apush(append_split(n));
2521 }
2522 
2523 
2524 bool GraphBuilder::direct_compare(ciKlass* k) {
2525   if (k->is_loaded() && k->is_instance_klass() && !UseSlowPath) {
2526     ciInstanceKlass* ik = k->as_instance_klass();
2527     if (ik->is_final()) {
2528       return true;
2529     } else {
2530       if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {
2531         // test class is leaf class
2532         dependency_recorder()->assert_leaf_type(ik);
2533         return true;
2534       }
2535     }
2536   }
2537   return false;
2538 }
2539 
2540 
2541 void GraphBuilder::check_cast(int klass_index) {
2542   bool will_link;
2543   ciKlass* klass = stream()->get_klass(will_link);
2544   bool null_free = stream()->has_Q_signature();
2545   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_for_exception();
2546   CheckCast* c = new CheckCast(klass, apop(), state_before, null_free);
2547   apush(append_split(c));
2548   c->set_direct_compare(direct_compare(klass));
2549 
2550   if (is_profiling()) {
2551     // Note that we'd collect profile data in this method if we wanted it.
2552     compilation()->set_would_profile(true);
2553 
2554     if (profile_checkcasts()) {
2555       c->set_profiled_method(method());
2556       c->set_profiled_bci(bci());
2557       c->set_should_profile(true);
2558     }
2559   }
2560 }
2561 
2562 
2563 void GraphBuilder::instance_of(int klass_index) {
2564   bool will_link;
2565   ciKlass* klass = stream()->get_klass(will_link);
2566   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2567   InstanceOf* i = new InstanceOf(klass, apop(), state_before);
2568   ipush(append_split(i));
2569   i->set_direct_compare(direct_compare(klass));
2570 
2571   if (is_profiling()) {
2572     // Note that we'd collect profile data in this method if we wanted it.
2573     compilation()->set_would_profile(true);
2574 
2575     if (profile_checkcasts()) {
2576       i->set_profiled_method(method());
2577       i->set_profiled_bci(bci());
2578       i->set_should_profile(true);
2579     }
2580   }
2581 }
2582 
2583 
2584 void GraphBuilder::monitorenter(Value x, int bci) {
2585   bool maybe_inlinetype = false;
2586   if (bci == InvocationEntryBci) {
2587     // Called by GraphBuilder::inline_sync_entry.
2588 #ifdef ASSERT
2589     ciType* obj_type = x->declared_type();
2590     assert(obj_type == NULL || !obj_type->is_inlinetype(), "inline types cannot have synchronized methods");
2591 #endif
2592   } else {
2593     // We are compiling a monitorenter bytecode
2594     if (EnableValhalla) {
2595       ciType* obj_type = x->declared_type();
2596       if (obj_type == NULL || obj_type->as_klass()->can_be_inline_klass()) {
2597         // If we're (possibly) locking on an inline type, check for markWord::always_locked_pattern
2598         // and throw IMSE. (obj_type is null for Phi nodes, so let's just be conservative).
2599         maybe_inlinetype = true;
2600       }
2601     }
2602   }
2603 
2604   // save state before locking in case of deoptimization after a NullPointerException
2605   ValueStack* state_before = copy_state_for_exception_with_bci(bci);
2606   append_with_bci(new MonitorEnter(x, state()->lock(x), state_before, maybe_inlinetype), bci);
2607   kill_all();
2608 }
2609 
2610 
2611 void GraphBuilder::monitorexit(Value x, int bci) {
2612   append_with_bci(new MonitorExit(x, state()->unlock()), bci);
2613   kill_all();
2614 }
2615 
2616 
2617 void GraphBuilder::new_multi_array(int dimensions) {
2618   bool will_link;
2619   ciKlass* klass = stream()->get_klass(will_link);
2620   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2621 
2622   Values* dims = new Values(dimensions, dimensions, NULL);
2623   // fill in all dimensions
2624   int i = dimensions;
2625   while (i-- > 0) dims->at_put(i, ipop());
2626   // create array
2627   NewArray* n = new NewMultiArray(klass, dims, state_before);
2628   apush(append_split(n));
2629 }
2630 
2631 
2632 void GraphBuilder::throw_op(int bci) {
2633   // We require that the debug info for a Throw be the "state before"
2634   // the Throw (i.e., exception oop is still on TOS)
2635   ValueStack* state_before = copy_state_before_with_bci(bci);
2636   Throw* t = new Throw(apop(), state_before);
2637   // operand stack not needed after a throw
2638   state()->truncate_stack(0);
2639   append_with_bci(t, bci);
2640 }
2641 
2642 
2643 Value GraphBuilder::round_fp(Value fp_value) {
2644   if (strict_fp_requires_explicit_rounding) {
2645 #ifdef IA32
2646     // no rounding needed if SSE2 is used
2647     if (UseSSE < 2) {
2648       // Must currently insert rounding node for doubleword values that
2649       // are results of expressions (i.e., not loads from memory or
2650       // constants)
2651       if (fp_value->type()->tag() == doubleTag &&
2652           fp_value->as_Constant() == NULL &&
2653           fp_value->as_Local() == NULL &&       // method parameters need no rounding
2654           fp_value->as_RoundFP() == NULL) {
2655         return append(new RoundFP(fp_value));
2656       }
2657     }
2658 #else
2659     Unimplemented();
2660 #endif // IA32
2661   }
2662   return fp_value;
2663 }
2664 
2665 
2666 Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) {
2667   Canonicalizer canon(compilation(), instr, bci);
2668   Instruction* i1 = canon.canonical();
2669   if (i1->is_linked() || !i1->can_be_linked()) {
2670     // Canonicalizer returned an instruction which was already
2671     // appended so simply return it.
2672     return i1;
2673   }
2674 
2675   if (UseLocalValueNumbering) {
2676     // Lookup the instruction in the ValueMap and add it to the map if
2677     // it's not found.
2678     Instruction* i2 = vmap()->find_insert(i1);
2679     if (i2 != i1) {
2680       // found an entry in the value map, so just return it.
2681       assert(i2->is_linked(), "should already be linked");
2682       return i2;
2683     }
2684     ValueNumberingEffects vne(vmap());
2685     i1->visit(&vne);
2686   }
2687 
2688   // i1 was not eliminated => append it
2689   assert(i1->next() == NULL, "shouldn't already be linked");
2690   _last = _last->set_next(i1, canon.bci());
2691 
2692   if (++_instruction_count >= InstructionCountCutoff && !bailed_out()) {
2693     // set the bailout state but complete normal processing.  We
2694     // might do a little more work before noticing the bailout so we
2695     // want processing to continue normally until it's noticed.
2696     bailout("Method and/or inlining is too large");
2697   }
2698 
2699 #ifndef PRODUCT
2700   if (PrintIRDuringConstruction) {
2701     InstructionPrinter ip;
2702     ip.print_line(i1);
2703     if (Verbose) {
2704       state()->print();
2705     }
2706   }
2707 #endif
2708 
2709   // save state after modification of operand stack for StateSplit instructions
2710   StateSplit* s = i1->as_StateSplit();
2711   if (s != NULL) {
2712     if (EliminateFieldAccess) {
2713       Intrinsic* intrinsic = s->as_Intrinsic();
2714       if (s->as_Invoke() != NULL || (intrinsic && !intrinsic->preserves_state())) {
2715         _memory->kill();
2716       }
2717     }
2718     s->set_state(state()->copy(ValueStack::StateAfter, canon.bci()));
2719   }
2720 
2721   // set up exception handlers for this instruction if necessary
2722   if (i1->can_trap()) {
2723     i1->set_exception_handlers(handle_exception(i1));
2724     assert(i1->exception_state() != NULL || !i1->needs_exception_state() || bailed_out(), "handle_exception must set exception state");
2725   }
2726   return i1;
2727 }
2728 
2729 
2730 Instruction* GraphBuilder::append(Instruction* instr) {
2731   assert(instr->as_StateSplit() == NULL || instr->as_BlockEnd() != NULL, "wrong append used");
2732   return append_with_bci(instr, bci());
2733 }
2734 
2735 
2736 Instruction* GraphBuilder::append_split(StateSplit* instr) {
2737   return append_with_bci(instr, bci());
2738 }
2739 
2740 
2741 void GraphBuilder::null_check(Value value) {
2742   if (value->as_NewArray() != NULL || value->as_NewInstance() != NULL) {
2743     return;
2744   } else {
2745     Constant* con = value->as_Constant();
2746     if (con) {
2747       ObjectType* c = con->type()->as_ObjectType();
2748       if (c && c->is_loaded()) {
2749         ObjectConstant* oc = c->as_ObjectConstant();
2750         if (!oc || !oc->value()->is_null_object()) {
2751           return;
2752         }
2753       }
2754     }
2755   }
2756   append(new NullCheck(value, copy_state_for_exception()));
2757 }
2758 
2759 
2760 
2761 XHandlers* GraphBuilder::handle_exception(Instruction* instruction) {
2762   if (!has_handler() && (!instruction->needs_exception_state() || instruction->exception_state() != NULL)) {
2763     assert(instruction->exception_state() == NULL
2764            || instruction->exception_state()->kind() == ValueStack::EmptyExceptionState
2765            || (instruction->exception_state()->kind() == ValueStack::ExceptionState && _compilation->env()->should_retain_local_variables()),
2766            "exception_state should be of exception kind");
2767     return new XHandlers();
2768   }
2769 
2770   XHandlers*  exception_handlers = new XHandlers();
2771   ScopeData*  cur_scope_data = scope_data();
2772   ValueStack* cur_state = instruction->state_before();
2773   ValueStack* prev_state = NULL;
2774   int scope_count = 0;
2775 
2776   assert(cur_state != NULL, "state_before must be set");
2777   do {
2778     int cur_bci = cur_state->bci();
2779     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2780     assert(cur_bci == SynchronizationEntryBCI || cur_bci == cur_scope_data->stream()->cur_bci()
2781            || has_pending_field_access() || has_pending_load_indexed(), "invalid bci");
2782 
2783 
2784     // join with all potential exception handlers
2785     XHandlers* list = cur_scope_data->xhandlers();
2786     const int n = list->length();
2787     for (int i = 0; i < n; i++) {
2788       XHandler* h = list->handler_at(i);
2789       if (h->covers(cur_bci)) {
2790         // h is a potential exception handler => join it
2791         compilation()->set_has_exception_handlers(true);
2792 
2793         BlockBegin* entry = h->entry_block();
2794         if (entry == block()) {
2795           // It's acceptable for an exception handler to cover itself
2796           // but we don't handle that in the parser currently.  It's
2797           // very rare so we bailout instead of trying to handle it.
2798           BAILOUT_("exception handler covers itself", exception_handlers);
2799         }
2800         assert(entry->bci() == h->handler_bci(), "must match");
2801         assert(entry->bci() == -1 || entry == cur_scope_data->block_at(entry->bci()), "blocks must correspond");
2802 
2803         // previously this was a BAILOUT, but this is not necessary
2804         // now because asynchronous exceptions are not handled this way.
2805         assert(entry->state() == NULL || cur_state->total_locks_size() == entry->state()->total_locks_size(), "locks do not match");
2806 
2807         // xhandler start with an empty expression stack
2808         if (cur_state->stack_size() != 0) {
2809           cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());
2810         }
2811         if (instruction->exception_state() == NULL) {
2812           instruction->set_exception_state(cur_state);
2813         }
2814 
2815         // Note: Usually this join must work. However, very
2816         // complicated jsr-ret structures where we don't ret from
2817         // the subroutine can cause the objects on the monitor
2818         // stacks to not match because blocks can be parsed twice.
2819         // The only test case we've seen so far which exhibits this
2820         // problem is caught by the infinite recursion test in
2821         // GraphBuilder::jsr() if the join doesn't work.
2822         if (!entry->try_merge(cur_state)) {
2823           BAILOUT_("error while joining with exception handler, prob. due to complicated jsr/rets", exception_handlers);
2824         }
2825 
2826         // add current state for correct handling of phi functions at begin of xhandler
2827         int phi_operand = entry->add_exception_state(cur_state);
2828 
2829         // add entry to the list of xhandlers of this block
2830         _block->add_exception_handler(entry);
2831 
2832         // add back-edge from xhandler entry to this block
2833         if (!entry->is_predecessor(_block)) {
2834           entry->add_predecessor(_block);
2835         }
2836 
2837         // clone XHandler because phi_operand and scope_count can not be shared
2838         XHandler* new_xhandler = new XHandler(h);
2839         new_xhandler->set_phi_operand(phi_operand);
2840         new_xhandler->set_scope_count(scope_count);
2841         exception_handlers->append(new_xhandler);
2842 
2843         // fill in exception handler subgraph lazily
2844         assert(!entry->is_set(BlockBegin::was_visited_flag), "entry must not be visited yet");
2845         cur_scope_data->add_to_work_list(entry);
2846 
2847         // stop when reaching catchall
2848         if (h->catch_type() == 0) {
2849           return exception_handlers;
2850         }
2851       }
2852     }
2853 
2854     if (exception_handlers->length() == 0) {
2855       // This scope and all callees do not handle exceptions, so the local
2856       // variables of this scope are not needed. However, the scope itself is
2857       // required for a correct exception stack trace -> clear out the locals.
2858       if (_compilation->env()->should_retain_local_variables()) {
2859         cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());
2860       } else {
2861         cur_state = cur_state->copy(ValueStack::EmptyExceptionState, cur_state->bci());
2862       }
2863       if (prev_state != NULL) {
2864         prev_state->set_caller_state(cur_state);
2865       }
2866       if (instruction->exception_state() == NULL) {
2867         instruction->set_exception_state(cur_state);
2868       }
2869     }
2870 
2871     // Set up iteration for next time.
2872     // If parsing a jsr, do not grab exception handlers from the
2873     // parent scopes for this method (already got them, and they
2874     // needed to be cloned)
2875 
2876     while (cur_scope_data->parsing_jsr()) {
2877       cur_scope_data = cur_scope_data->parent();
2878     }
2879 
2880     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2881     assert(cur_state->locks_size() == 0 || cur_state->locks_size() == 1, "unlocking must be done in a catchall exception handler");
2882 
2883     prev_state = cur_state;
2884     cur_state = cur_state->caller_state();
2885     cur_scope_data = cur_scope_data->parent();
2886     scope_count++;
2887   } while (cur_scope_data != NULL);
2888 
2889   return exception_handlers;
2890 }
2891 
2892 
2893 // Helper class for simplifying Phis.
2894 class PhiSimplifier : public BlockClosure {
2895  private:
2896   bool _has_substitutions;
2897   Value simplify(Value v);
2898 
2899  public:
2900   PhiSimplifier(BlockBegin* start) : _has_substitutions(false) {
2901     start->iterate_preorder(this);
2902     if (_has_substitutions) {
2903       SubstitutionResolver sr(start);
2904     }
2905   }
2906   void block_do(BlockBegin* b);
2907   bool has_substitutions() const { return _has_substitutions; }
2908 };
2909 
2910 
2911 Value PhiSimplifier::simplify(Value v) {
2912   Phi* phi = v->as_Phi();
2913 
2914   if (phi == NULL) {
2915     // no phi function
2916     return v;
2917   } else if (v->has_subst()) {
2918     // already substituted; subst can be phi itself -> simplify
2919     return simplify(v->subst());
2920   } else if (phi->is_set(Phi::cannot_simplify)) {
2921     // already tried to simplify phi before
2922     return phi;
2923   } else if (phi->is_set(Phi::visited)) {
2924     // break cycles in phi functions
2925     return phi;
2926   } else if (phi->type()->is_illegal()) {
2927     // illegal phi functions are ignored anyway
2928     return phi;
2929 
2930   } else {
2931     // mark phi function as processed to break cycles in phi functions
2932     phi->set(Phi::visited);
2933 
2934     // simplify x = [y, x] and x = [y, y] to y
2935     Value subst = NULL;
2936     int opd_count = phi->operand_count();
2937     for (int i = 0; i < opd_count; i++) {
2938       Value opd = phi->operand_at(i);
2939       assert(opd != NULL, "Operand must exist!");
2940 
2941       if (opd->type()->is_illegal()) {
2942         // if one operand is illegal, the entire phi function is illegal
2943         phi->make_illegal();
2944         phi->clear(Phi::visited);
2945         return phi;
2946       }
2947 
2948       Value new_opd = simplify(opd);
2949       assert(new_opd != NULL, "Simplified operand must exist!");
2950 
2951       if (new_opd != phi && new_opd != subst) {
2952         if (subst == NULL) {
2953           subst = new_opd;
2954         } else {
2955           // no simplification possible
2956           phi->set(Phi::cannot_simplify);
2957           phi->clear(Phi::visited);
2958           return phi;
2959         }
2960       }
2961     }
2962 
2963     // sucessfully simplified phi function
2964     assert(subst != NULL, "illegal phi function");
2965     _has_substitutions = true;
2966     phi->clear(Phi::visited);
2967     phi->set_subst(subst);
2968 
2969 #ifndef PRODUCT
2970     if (PrintPhiFunctions) {
2971       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());
2972     }
2973 #endif
2974 
2975     return subst;
2976   }
2977 }
2978 
2979 
2980 void PhiSimplifier::block_do(BlockBegin* b) {
2981   for_each_phi_fun(b, phi,
2982     simplify(phi);
2983   );
2984 
2985 #ifdef ASSERT
2986   for_each_phi_fun(b, phi,
2987                    assert(phi->operand_count() != 1 || phi->subst() != phi || phi->is_illegal(), "missed trivial simplification");
2988   );
2989 
2990   ValueStack* state = b->state()->caller_state();
2991   for_each_state_value(state, value,
2992     Phi* phi = value->as_Phi();
2993     assert(phi == NULL || phi->block() != b, "must not have phi function to simplify in caller state");
2994   );
2995 #endif
2996 }
2997 
2998 // This method is called after all blocks are filled with HIR instructions
2999 // It eliminates all Phi functions of the form x = [y, y] and x = [y, x]
3000 void GraphBuilder::eliminate_redundant_phis(BlockBegin* start) {
3001   PhiSimplifier simplifier(start);
3002 }
3003 
3004 
3005 void GraphBuilder::connect_to_end(BlockBegin* beg) {
3006   // setup iteration
3007   kill_all();
3008   _block = beg;
3009   _state = beg->state()->copy_for_parsing();
3010   _last  = beg;
3011   iterate_bytecodes_for_block(beg->bci());
3012 }
3013 
3014 
3015 BlockEnd* GraphBuilder::iterate_bytecodes_for_block(int bci) {
3016 #ifndef PRODUCT
3017   if (PrintIRDuringConstruction) {
3018     tty->cr();
3019     InstructionPrinter ip;
3020     ip.print_instr(_block); tty->cr();
3021     ip.print_stack(_block->state()); tty->cr();
3022     ip.print_inline_level(_block);
3023     ip.print_head();
3024     tty->print_cr("locals size: %d stack size: %d", state()->locals_size(), state()->stack_size());
3025   }
3026 #endif
3027   _skip_block = false;
3028   assert(state() != NULL, "ValueStack missing!");
3029   CompileLog* log = compilation()->log();
3030   ciBytecodeStream s(method());
3031   s.reset_to_bci(bci);
3032   int prev_bci = bci;
3033   scope_data()->set_stream(&s);
3034   // iterate
3035   Bytecodes::Code code = Bytecodes::_illegal;
3036   bool push_exception = false;
3037 
3038   if (block()->is_set(BlockBegin::exception_entry_flag) && block()->next() == NULL) {
3039     // first thing in the exception entry block should be the exception object.
3040     push_exception = true;
3041   }
3042 
3043   bool ignore_return = scope_data()->ignore_return();
3044 
3045   while (!bailed_out() && last()->as_BlockEnd() == NULL &&
3046          (code = stream()->next()) != ciBytecodeStream::EOBC() &&
3047          (block_at(s.cur_bci()) == NULL || block_at(s.cur_bci()) == block())) {
3048     assert(state()->kind() == ValueStack::Parsing, "invalid state kind");
3049 
3050     if (log != NULL)
3051       log->set_context("bc code='%d' bci='%d'", (int)code, s.cur_bci());
3052 
3053     // Check for active jsr during OSR compilation
3054     if (compilation()->is_osr_compile()
3055         && scope()->is_top_scope()
3056         && parsing_jsr()
3057         && s.cur_bci() == compilation()->osr_bci()) {
3058       bailout("OSR not supported while a jsr is active");
3059     }
3060 
3061     if (push_exception) {
3062       apush(append(new ExceptionObject()));
3063       push_exception = false;
3064     }
3065 
3066     // handle bytecode
3067     switch (code) {
3068       case Bytecodes::_nop            : /* nothing to do */ break;
3069       case Bytecodes::_aconst_null    : apush(append(new Constant(objectNull            ))); break;
3070       case Bytecodes::_iconst_m1      : ipush(append(new Constant(new IntConstant   (-1)))); break;
3071       case Bytecodes::_iconst_0       : ipush(append(new Constant(intZero               ))); break;
3072       case Bytecodes::_iconst_1       : ipush(append(new Constant(intOne                ))); break;
3073       case Bytecodes::_iconst_2       : ipush(append(new Constant(new IntConstant   ( 2)))); break;
3074       case Bytecodes::_iconst_3       : ipush(append(new Constant(new IntConstant   ( 3)))); break;
3075       case Bytecodes::_iconst_4       : ipush(append(new Constant(new IntConstant   ( 4)))); break;
3076       case Bytecodes::_iconst_5       : ipush(append(new Constant(new IntConstant   ( 5)))); break;
3077       case Bytecodes::_lconst_0       : lpush(append(new Constant(new LongConstant  ( 0)))); break;
3078       case Bytecodes::_lconst_1       : lpush(append(new Constant(new LongConstant  ( 1)))); break;
3079       case Bytecodes::_fconst_0       : fpush(append(new Constant(new FloatConstant ( 0)))); break;
3080       case Bytecodes::_fconst_1       : fpush(append(new Constant(new FloatConstant ( 1)))); break;
3081       case Bytecodes::_fconst_2       : fpush(append(new Constant(new FloatConstant ( 2)))); break;
3082       case Bytecodes::_dconst_0       : dpush(append(new Constant(new DoubleConstant( 0)))); break;
3083       case Bytecodes::_dconst_1       : dpush(append(new Constant(new DoubleConstant( 1)))); break;
3084       case Bytecodes::_bipush         : ipush(append(new Constant(new IntConstant(((signed char*)s.cur_bcp())[1])))); break;
3085       case Bytecodes::_sipush         : ipush(append(new Constant(new IntConstant((short)Bytes::get_Java_u2(s.cur_bcp()+1))))); break;
3086       case Bytecodes::_ldc            : // fall through
3087       case Bytecodes::_ldc_w          : // fall through
3088       case Bytecodes::_ldc2_w         : load_constant(); break;
3089       case Bytecodes::_iload          : load_local(intType     , s.get_index()); break;
3090       case Bytecodes::_lload          : load_local(longType    , s.get_index()); break;
3091       case Bytecodes::_fload          : load_local(floatType   , s.get_index()); break;
3092       case Bytecodes::_dload          : load_local(doubleType  , s.get_index()); break;
3093       case Bytecodes::_aload          : load_local(instanceType, s.get_index()); break;
3094       case Bytecodes::_iload_0        : load_local(intType   , 0); break;
3095       case Bytecodes::_iload_1        : load_local(intType   , 1); break;
3096       case Bytecodes::_iload_2        : load_local(intType   , 2); break;
3097       case Bytecodes::_iload_3        : load_local(intType   , 3); break;
3098       case Bytecodes::_lload_0        : load_local(longType  , 0); break;
3099       case Bytecodes::_lload_1        : load_local(longType  , 1); break;
3100       case Bytecodes::_lload_2        : load_local(longType  , 2); break;
3101       case Bytecodes::_lload_3        : load_local(longType  , 3); break;
3102       case Bytecodes::_fload_0        : load_local(floatType , 0); break;
3103       case Bytecodes::_fload_1        : load_local(floatType , 1); break;
3104       case Bytecodes::_fload_2        : load_local(floatType , 2); break;
3105       case Bytecodes::_fload_3        : load_local(floatType , 3); break;
3106       case Bytecodes::_dload_0        : load_local(doubleType, 0); break;
3107       case Bytecodes::_dload_1        : load_local(doubleType, 1); break;
3108       case Bytecodes::_dload_2        : load_local(doubleType, 2); break;
3109       case Bytecodes::_dload_3        : load_local(doubleType, 3); break;
3110       case Bytecodes::_aload_0        : load_local(objectType, 0); break;
3111       case Bytecodes::_aload_1        : load_local(objectType, 1); break;
3112       case Bytecodes::_aload_2        : load_local(objectType, 2); break;
3113       case Bytecodes::_aload_3        : load_local(objectType, 3); break;
3114       case Bytecodes::_iaload         : load_indexed(T_INT   ); break;
3115       case Bytecodes::_laload         : load_indexed(T_LONG  ); break;
3116       case Bytecodes::_faload         : load_indexed(T_FLOAT ); break;
3117       case Bytecodes::_daload         : load_indexed(T_DOUBLE); break;
3118       case Bytecodes::_aaload         : load_indexed(T_OBJECT); break;
3119       case Bytecodes::_baload         : load_indexed(T_BYTE  ); break;
3120       case Bytecodes::_caload         : load_indexed(T_CHAR  ); break;
3121       case Bytecodes::_saload         : load_indexed(T_SHORT ); break;
3122       case Bytecodes::_istore         : store_local(intType   , s.get_index()); break;
3123       case Bytecodes::_lstore         : store_local(longType  , s.get_index()); break;
3124       case Bytecodes::_fstore         : store_local(floatType , s.get_index()); break;
3125       case Bytecodes::_dstore         : store_local(doubleType, s.get_index()); break;
3126       case Bytecodes::_astore         : store_local(objectType, s.get_index()); break;
3127       case Bytecodes::_istore_0       : store_local(intType   , 0); break;
3128       case Bytecodes::_istore_1       : store_local(intType   , 1); break;
3129       case Bytecodes::_istore_2       : store_local(intType   , 2); break;
3130       case Bytecodes::_istore_3       : store_local(intType   , 3); break;
3131       case Bytecodes::_lstore_0       : store_local(longType  , 0); break;
3132       case Bytecodes::_lstore_1       : store_local(longType  , 1); break;
3133       case Bytecodes::_lstore_2       : store_local(longType  , 2); break;
3134       case Bytecodes::_lstore_3       : store_local(longType  , 3); break;
3135       case Bytecodes::_fstore_0       : store_local(floatType , 0); break;
3136       case Bytecodes::_fstore_1       : store_local(floatType , 1); break;
3137       case Bytecodes::_fstore_2       : store_local(floatType , 2); break;
3138       case Bytecodes::_fstore_3       : store_local(floatType , 3); break;
3139       case Bytecodes::_dstore_0       : store_local(doubleType, 0); break;
3140       case Bytecodes::_dstore_1       : store_local(doubleType, 1); break;
3141       case Bytecodes::_dstore_2       : store_local(doubleType, 2); break;
3142       case Bytecodes::_dstore_3       : store_local(doubleType, 3); break;
3143       case Bytecodes::_astore_0       : store_local(objectType, 0); break;
3144       case Bytecodes::_astore_1       : store_local(objectType, 1); break;
3145       case Bytecodes::_astore_2       : store_local(objectType, 2); break;
3146       case Bytecodes::_astore_3       : store_local(objectType, 3); break;
3147       case Bytecodes::_iastore        : store_indexed(T_INT   ); break;
3148       case Bytecodes::_lastore        : store_indexed(T_LONG  ); break;
3149       case Bytecodes::_fastore        : store_indexed(T_FLOAT ); break;
3150       case Bytecodes::_dastore        : store_indexed(T_DOUBLE); break;
3151       case Bytecodes::_aastore        : store_indexed(T_OBJECT); break;
3152       case Bytecodes::_bastore        : store_indexed(T_BYTE  ); break;
3153       case Bytecodes::_castore        : store_indexed(T_CHAR  ); break;
3154       case Bytecodes::_sastore        : store_indexed(T_SHORT ); break;
3155       case Bytecodes::_pop            : // fall through
3156       case Bytecodes::_pop2           : // fall through
3157       case Bytecodes::_dup            : // fall through
3158       case Bytecodes::_dup_x1         : // fall through
3159       case Bytecodes::_dup_x2         : // fall through
3160       case Bytecodes::_dup2           : // fall through
3161       case Bytecodes::_dup2_x1        : // fall through
3162       case Bytecodes::_dup2_x2        : // fall through
3163       case Bytecodes::_swap           : stack_op(code); break;
3164       case Bytecodes::_iadd           : arithmetic_op(intType   , code); break;
3165       case Bytecodes::_ladd           : arithmetic_op(longType  , code); break;
3166       case Bytecodes::_fadd           : arithmetic_op(floatType , code); break;
3167       case Bytecodes::_dadd           : arithmetic_op(doubleType, code); break;
3168       case Bytecodes::_isub           : arithmetic_op(intType   , code); break;
3169       case Bytecodes::_lsub           : arithmetic_op(longType  , code); break;
3170       case Bytecodes::_fsub           : arithmetic_op(floatType , code); break;
3171       case Bytecodes::_dsub           : arithmetic_op(doubleType, code); break;
3172       case Bytecodes::_imul           : arithmetic_op(intType   , code); break;
3173       case Bytecodes::_lmul           : arithmetic_op(longType  , code); break;
3174       case Bytecodes::_fmul           : arithmetic_op(floatType , code); break;
3175       case Bytecodes::_dmul           : arithmetic_op(doubleType, code); break;
3176       case Bytecodes::_idiv           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
3177       case Bytecodes::_ldiv           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
3178       case Bytecodes::_fdiv           : arithmetic_op(floatType , code); break;
3179       case Bytecodes::_ddiv           : arithmetic_op(doubleType, code); break;
3180       case Bytecodes::_irem           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
3181       case Bytecodes::_lrem           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
3182       case Bytecodes::_frem           : arithmetic_op(floatType , code); break;
3183       case Bytecodes::_drem           : arithmetic_op(doubleType, code); break;
3184       case Bytecodes::_ineg           : negate_op(intType   ); break;
3185       case Bytecodes::_lneg           : negate_op(longType  ); break;
3186       case Bytecodes::_fneg           : negate_op(floatType ); break;
3187       case Bytecodes::_dneg           : negate_op(doubleType); break;
3188       case Bytecodes::_ishl           : shift_op(intType , code); break;
3189       case Bytecodes::_lshl           : shift_op(longType, code); break;
3190       case Bytecodes::_ishr           : shift_op(intType , code); break;
3191       case Bytecodes::_lshr           : shift_op(longType, code); break;
3192       case Bytecodes::_iushr          : shift_op(intType , code); break;
3193       case Bytecodes::_lushr          : shift_op(longType, code); break;
3194       case Bytecodes::_iand           : logic_op(intType , code); break;
3195       case Bytecodes::_land           : logic_op(longType, code); break;
3196       case Bytecodes::_ior            : logic_op(intType , code); break;
3197       case Bytecodes::_lor            : logic_op(longType, code); break;
3198       case Bytecodes::_ixor           : logic_op(intType , code); break;
3199       case Bytecodes::_lxor           : logic_op(longType, code); break;
3200       case Bytecodes::_iinc           : increment(); break;
3201       case Bytecodes::_i2l            : convert(code, T_INT   , T_LONG  ); break;
3202       case Bytecodes::_i2f            : convert(code, T_INT   , T_FLOAT ); break;
3203       case Bytecodes::_i2d            : convert(code, T_INT   , T_DOUBLE); break;
3204       case Bytecodes::_l2i            : convert(code, T_LONG  , T_INT   ); break;
3205       case Bytecodes::_l2f            : convert(code, T_LONG  , T_FLOAT ); break;
3206       case Bytecodes::_l2d            : convert(code, T_LONG  , T_DOUBLE); break;
3207       case Bytecodes::_f2i            : convert(code, T_FLOAT , T_INT   ); break;
3208       case Bytecodes::_f2l            : convert(code, T_FLOAT , T_LONG  ); break;
3209       case Bytecodes::_f2d            : convert(code, T_FLOAT , T_DOUBLE); break;
3210       case Bytecodes::_d2i            : convert(code, T_DOUBLE, T_INT   ); break;
3211       case Bytecodes::_d2l            : convert(code, T_DOUBLE, T_LONG  ); break;
3212       case Bytecodes::_d2f            : convert(code, T_DOUBLE, T_FLOAT ); break;
3213       case Bytecodes::_i2b            : convert(code, T_INT   , T_BYTE  ); break;
3214       case Bytecodes::_i2c            : convert(code, T_INT   , T_CHAR  ); break;
3215       case Bytecodes::_i2s            : convert(code, T_INT   , T_SHORT ); break;
3216       case Bytecodes::_lcmp           : compare_op(longType  , code); break;
3217       case Bytecodes::_fcmpl          : compare_op(floatType , code); break;
3218       case Bytecodes::_fcmpg          : compare_op(floatType , code); break;
3219       case Bytecodes::_dcmpl          : compare_op(doubleType, code); break;
3220       case Bytecodes::_dcmpg          : compare_op(doubleType, code); break;
3221       case Bytecodes::_ifeq           : if_zero(intType   , If::eql); break;
3222       case Bytecodes::_ifne           : if_zero(intType   , If::neq); break;
3223       case Bytecodes::_iflt           : if_zero(intType   , If::lss); break;
3224       case Bytecodes::_ifge           : if_zero(intType   , If::geq); break;
3225       case Bytecodes::_ifgt           : if_zero(intType   , If::gtr); break;
3226       case Bytecodes::_ifle           : if_zero(intType   , If::leq); break;
3227       case Bytecodes::_if_icmpeq      : if_same(intType   , If::eql); break;
3228       case Bytecodes::_if_icmpne      : if_same(intType   , If::neq); break;
3229       case Bytecodes::_if_icmplt      : if_same(intType   , If::lss); break;
3230       case Bytecodes::_if_icmpge      : if_same(intType   , If::geq); break;
3231       case Bytecodes::_if_icmpgt      : if_same(intType   , If::gtr); break;
3232       case Bytecodes::_if_icmple      : if_same(intType   , If::leq); break;
3233       case Bytecodes::_if_acmpeq      : if_same(objectType, If::eql); break;
3234       case Bytecodes::_if_acmpne      : if_same(objectType, If::neq); break;
3235       case Bytecodes::_goto           : _goto(s.cur_bci(), s.get_dest()); break;
3236       case Bytecodes::_jsr            : jsr(s.get_dest()); break;
3237       case Bytecodes::_ret            : ret(s.get_index()); break;
3238       case Bytecodes::_tableswitch    : table_switch(); break;
3239       case Bytecodes::_lookupswitch   : lookup_switch(); break;
3240       case Bytecodes::_ireturn        : method_return(ipop(), ignore_return); break;
3241       case Bytecodes::_lreturn        : method_return(lpop(), ignore_return); break;
3242       case Bytecodes::_freturn        : method_return(fpop(), ignore_return); break;
3243       case Bytecodes::_dreturn        : method_return(dpop(), ignore_return); break;
3244       case Bytecodes::_areturn        : method_return(apop(), ignore_return); break;
3245       case Bytecodes::_return         : method_return(NULL  , ignore_return); break;
3246       case Bytecodes::_getstatic      : // fall through
3247       case Bytecodes::_putstatic      : // fall through
3248       case Bytecodes::_getfield       : // fall through
3249       case Bytecodes::_putfield       : access_field(code); break;
3250       case Bytecodes::_invokevirtual  : // fall through
3251       case Bytecodes::_invokespecial  : // fall through
3252       case Bytecodes::_invokestatic   : // fall through
3253       case Bytecodes::_invokedynamic  : // fall through
3254       case Bytecodes::_invokeinterface: invoke(code); break;
3255       case Bytecodes::_new            : new_instance(s.get_index_u2()); break;
3256       case Bytecodes::_newarray       : new_type_array(); break;
3257       case Bytecodes::_anewarray      : new_object_array(); break;
3258       case Bytecodes::_arraylength    : { ValueStack* state_before = copy_state_for_exception(); ipush(append(new ArrayLength(apop(), state_before))); break; }
3259       case Bytecodes::_athrow         : throw_op(s.cur_bci()); break;
3260       case Bytecodes::_checkcast      : check_cast(s.get_index_u2()); break;
3261       case Bytecodes::_instanceof     : instance_of(s.get_index_u2()); break;
3262       case Bytecodes::_monitorenter   : monitorenter(apop(), s.cur_bci()); break;
3263       case Bytecodes::_monitorexit    : monitorexit (apop(), s.cur_bci()); break;
3264       case Bytecodes::_wide           : ShouldNotReachHere(); break;
3265       case Bytecodes::_multianewarray : new_multi_array(s.cur_bcp()[3]); break;
3266       case Bytecodes::_ifnull         : if_null(objectType, If::eql); break;
3267       case Bytecodes::_ifnonnull      : if_null(objectType, If::neq); break;
3268       case Bytecodes::_goto_w         : _goto(s.cur_bci(), s.get_far_dest()); break;
3269       case Bytecodes::_jsr_w          : jsr(s.get_far_dest()); break;
3270       case Bytecodes::_defaultvalue   : default_value(s.get_index_u2()); break;
3271       case Bytecodes::_withfield      : withfield(s.get_index_u2()); break;
3272       case Bytecodes::_breakpoint     : BAILOUT_("concurrent setting of breakpoint", NULL);
3273       default                         : ShouldNotReachHere(); break;
3274     }
3275 
3276     if (log != NULL)
3277       log->clear_context(); // skip marker if nothing was printed
3278 
3279     // save current bci to setup Goto at the end
3280     prev_bci = s.cur_bci();
3281 
3282   }
3283   CHECK_BAILOUT_(NULL);
3284   // stop processing of this block (see try_inline_full)
3285   if (_skip_block) {
3286     _skip_block = false;
3287     assert(_last && _last->as_BlockEnd(), "");
3288     return _last->as_BlockEnd();
3289   }
3290   // if there are any, check if last instruction is a BlockEnd instruction
3291   BlockEnd* end = last()->as_BlockEnd();
3292   if (end == NULL) {
3293     // all blocks must end with a BlockEnd instruction => add a Goto
3294     end = new Goto(block_at(s.cur_bci()), false);
3295     append(end);
3296   }
3297   assert(end == last()->as_BlockEnd(), "inconsistency");
3298 
3299   assert(end->state() != NULL, "state must already be present");
3300   assert(end->as_Return() == NULL || end->as_Throw() == NULL || end->state()->stack_size() == 0, "stack not needed for return and throw");
3301 
3302   // connect to begin & set state
3303   // NOTE that inlining may have changed the block we are parsing
3304   block()->set_end(end);
3305   // propagate state
3306   for (int i = end->number_of_sux() - 1; i >= 0; i--) {
3307     BlockBegin* sux = end->sux_at(i);
3308     assert(sux->is_predecessor(block()), "predecessor missing");
3309     // be careful, bailout if bytecodes are strange
3310     if (!sux->try_merge(end->state())) BAILOUT_("block join failed", NULL);
3311     scope_data()->add_to_work_list(end->sux_at(i));
3312   }
3313 
3314   scope_data()->set_stream(NULL);
3315 
3316   // done
3317   return end;
3318 }
3319 
3320 
3321 void GraphBuilder::iterate_all_blocks(bool start_in_current_block_for_inlining) {
3322   do {
3323     if (start_in_current_block_for_inlining && !bailed_out()) {
3324       iterate_bytecodes_for_block(0);
3325       start_in_current_block_for_inlining = false;
3326     } else {
3327       BlockBegin* b;
3328       while ((b = scope_data()->remove_from_work_list()) != NULL) {
3329         if (!b->is_set(BlockBegin::was_visited_flag)) {
3330           if (b->is_set(BlockBegin::osr_entry_flag)) {
3331             // we're about to parse the osr entry block, so make sure
3332             // we setup the OSR edge leading into this block so that
3333             // Phis get setup correctly.
3334             setup_osr_entry_block();
3335             // this is no longer the osr entry block, so clear it.
3336             b->clear(BlockBegin::osr_entry_flag);
3337           }
3338           b->set(BlockBegin::was_visited_flag);
3339           connect_to_end(b);
3340         }
3341       }
3342     }
3343   } while (!bailed_out() && !scope_data()->is_work_list_empty());
3344 }
3345 
3346 
3347 bool GraphBuilder::_can_trap      [Bytecodes::number_of_java_codes];
3348 
3349 void GraphBuilder::initialize() {
3350   // the following bytecodes are assumed to potentially
3351   // throw exceptions in compiled code - note that e.g.
3352   // monitorexit & the return bytecodes do not throw
3353   // exceptions since monitor pairing proved that they
3354   // succeed (if monitor pairing succeeded)
3355   Bytecodes::Code can_trap_list[] =
3356     { Bytecodes::_ldc
3357     , Bytecodes::_ldc_w
3358     , Bytecodes::_ldc2_w
3359     , Bytecodes::_iaload
3360     , Bytecodes::_laload
3361     , Bytecodes::_faload
3362     , Bytecodes::_daload
3363     , Bytecodes::_aaload
3364     , Bytecodes::_baload
3365     , Bytecodes::_caload
3366     , Bytecodes::_saload
3367     , Bytecodes::_iastore
3368     , Bytecodes::_lastore
3369     , Bytecodes::_fastore
3370     , Bytecodes::_dastore
3371     , Bytecodes::_aastore
3372     , Bytecodes::_bastore
3373     , Bytecodes::_castore
3374     , Bytecodes::_sastore
3375     , Bytecodes::_idiv
3376     , Bytecodes::_ldiv
3377     , Bytecodes::_irem
3378     , Bytecodes::_lrem
3379     , Bytecodes::_getstatic
3380     , Bytecodes::_putstatic
3381     , Bytecodes::_getfield
3382     , Bytecodes::_putfield
3383     , Bytecodes::_invokevirtual
3384     , Bytecodes::_invokespecial
3385     , Bytecodes::_invokestatic
3386     , Bytecodes::_invokedynamic
3387     , Bytecodes::_invokeinterface
3388     , Bytecodes::_new
3389     , Bytecodes::_newarray
3390     , Bytecodes::_anewarray
3391     , Bytecodes::_arraylength
3392     , Bytecodes::_athrow
3393     , Bytecodes::_checkcast
3394     , Bytecodes::_instanceof
3395     , Bytecodes::_monitorenter
3396     , Bytecodes::_multianewarray
3397     };
3398 
3399   // inititialize trap tables
3400   for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
3401     _can_trap[i] = false;
3402   }
3403   // set standard trap info
3404   for (uint j = 0; j < ARRAY_SIZE(can_trap_list); j++) {
3405     _can_trap[can_trap_list[j]] = true;
3406   }
3407 }
3408 
3409 
3410 BlockBegin* GraphBuilder::header_block(BlockBegin* entry, BlockBegin::Flag f, ValueStack* state) {
3411   assert(entry->is_set(f), "entry/flag mismatch");
3412   // create header block
3413   BlockBegin* h = new BlockBegin(entry->bci());
3414   h->set_depth_first_number(0);
3415 
3416   Value l = h;
3417   BlockEnd* g = new Goto(entry, false);
3418   l->set_next(g, entry->bci());
3419   h->set_end(g);
3420   h->set(f);
3421   // setup header block end state
3422   ValueStack* s = state->copy(ValueStack::StateAfter, entry->bci()); // can use copy since stack is empty (=> no phis)
3423   assert(s->stack_is_empty(), "must have empty stack at entry point");
3424   g->set_state(s);
3425   return h;
3426 }
3427 
3428 
3429 
3430 BlockBegin* GraphBuilder::setup_start_block(int osr_bci, BlockBegin* std_entry, BlockBegin* osr_entry, ValueStack* state) {
3431   BlockBegin* start = new BlockBegin(0);
3432 
3433   // This code eliminates the empty start block at the beginning of
3434   // each method.  Previously, each method started with the
3435   // start-block created below, and this block was followed by the
3436   // header block that was always empty.  This header block is only
3437   // necesary if std_entry is also a backward branch target because
3438   // then phi functions may be necessary in the header block.  It's
3439   // also necessary when profiling so that there's a single block that
3440   // can increment the the counters.
3441   // In addition, with range check elimination, we may need a valid block
3442   // that dominates all the rest to insert range predicates.
3443   BlockBegin* new_header_block;
3444   if (std_entry->number_of_preds() > 0 || is_profiling() || RangeCheckElimination) {
3445     new_header_block = header_block(std_entry, BlockBegin::std_entry_flag, state);
3446   } else {
3447     new_header_block = std_entry;
3448   }
3449 
3450   // setup start block (root for the IR graph)
3451   Base* base =
3452     new Base(
3453       new_header_block,
3454       osr_entry
3455     );
3456   start->set_next(base, 0);
3457   start->set_end(base);
3458   // create & setup state for start block
3459   start->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3460   base->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3461 
3462   if (base->std_entry()->state() == NULL) {
3463     // setup states for header blocks
3464     base->std_entry()->merge(state);
3465   }
3466 
3467   assert(base->std_entry()->state() != NULL, "");
3468   return start;
3469 }
3470 
3471 
3472 void GraphBuilder::setup_osr_entry_block() {
3473   assert(compilation()->is_osr_compile(), "only for osrs");
3474 
3475   int osr_bci = compilation()->osr_bci();
3476   ciBytecodeStream s(method());
3477   s.reset_to_bci(osr_bci);
3478   s.next();
3479   scope_data()->set_stream(&s);
3480 
3481   // create a new block to be the osr setup code
3482   _osr_entry = new BlockBegin(osr_bci);
3483   _osr_entry->set(BlockBegin::osr_entry_flag);
3484   _osr_entry->set_depth_first_number(0);
3485   BlockBegin* target = bci2block()->at(osr_bci);
3486   assert(target != NULL && target->is_set(BlockBegin::osr_entry_flag), "must be there");
3487   // the osr entry has no values for locals
3488   ValueStack* state = target->state()->copy();
3489   _osr_entry->set_state(state);
3490 
3491   kill_all();
3492   _block = _osr_entry;
3493   _state = _osr_entry->state()->copy();
3494   assert(_state->bci() == osr_bci, "mismatch");
3495   _last  = _osr_entry;
3496   Value e = append(new OsrEntry());
3497   e->set_needs_null_check(false);
3498 
3499   // OSR buffer is
3500   //
3501   // locals[nlocals-1..0]
3502   // monitors[number_of_locks-1..0]
3503   //
3504   // locals is a direct copy of the interpreter frame so in the osr buffer
3505   // so first slot in the local array is the last local from the interpreter
3506   // and last slot is local[0] (receiver) from the interpreter
3507   //
3508   // Similarly with locks. The first lock slot in the osr buffer is the nth lock
3509   // from the interpreter frame, the nth lock slot in the osr buffer is 0th lock
3510   // in the interpreter frame (the method lock if a sync method)
3511 
3512   // Initialize monitors in the compiled activation.
3513 
3514   int index;
3515   Value local;
3516 
3517   // find all the locals that the interpreter thinks contain live oops
3518   const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci);
3519 
3520   // compute the offset into the locals so that we can treat the buffer
3521   // as if the locals were still in the interpreter frame
3522   int locals_offset = BytesPerWord * (method()->max_locals() - 1);
3523   for_each_local_value(state, index, local) {
3524     int offset = locals_offset - (index + local->type()->size() - 1) * BytesPerWord;
3525     Value get;
3526     if (local->type()->is_object_kind() && !live_oops.at(index)) {
3527       // The interpreter thinks this local is dead but the compiler
3528       // doesn't so pretend that the interpreter passed in null.
3529       get = append(new Constant(objectNull));
3530     } else {
3531       Value off_val = append(new Constant(new IntConstant(offset)));
3532       get = append(new UnsafeGet(as_BasicType(local->type()), e,
3533                                  off_val,
3534                                  false/*is_volatile*/,
3535                                  true/*is_raw*/));
3536     }
3537     _state->store_local(index, get);
3538   }
3539 
3540   // the storage for the OSR buffer is freed manually in the LIRGenerator.
3541 
3542   assert(state->caller_state() == NULL, "should be top scope");
3543   state->clear_locals();
3544   Goto* g = new Goto(target, false);
3545   append(g);
3546   _osr_entry->set_end(g);
3547   target->merge(_osr_entry->end()->state());
3548 
3549   scope_data()->set_stream(NULL);
3550 }
3551 
3552 
3553 ValueStack* GraphBuilder::state_at_entry() {
3554   ValueStack* state = new ValueStack(scope(), NULL);
3555 
3556   // Set up locals for receiver
3557   int idx = 0;
3558   if (!method()->is_static()) {
3559     // we should always see the receiver
3560     state->store_local(idx, new Local(method()->holder(), objectType, idx,
3561              /*receiver*/ true, /*null_free*/ method()->holder()->is_flat_array_klass()));
3562     idx = 1;
3563   }
3564 
3565   // Set up locals for incoming arguments
3566   ciSignature* sig = method()->signature();
3567   for (int i = 0; i < sig->count(); i++) {
3568     ciType* type = sig->type_at(i);
3569     BasicType basic_type = type->basic_type();
3570     // don't allow T_ARRAY to propagate into locals types
3571     if (is_reference_type(basic_type)) basic_type = T_OBJECT;
3572     ValueType* vt = as_ValueType(basic_type);
3573     state->store_local(idx, new Local(type, vt, idx, false, sig->is_null_free_at(i)));
3574     idx += type->size();
3575   }
3576 
3577   // lock synchronized method
3578   if (method()->is_synchronized()) {
3579     state->lock(NULL);
3580   }
3581 
3582   return state;
3583 }
3584 
3585 
3586 GraphBuilder::GraphBuilder(Compilation* compilation, IRScope* scope)
3587   : _scope_data(NULL)
3588   , _compilation(compilation)
3589   , _memory(new MemoryBuffer())
3590   , _inline_bailout_msg(NULL)
3591   , _instruction_count(0)
3592   , _osr_entry(NULL)
3593   , _pending_field_access(NULL)
3594   , _pending_load_indexed(NULL)
3595 {
3596   int osr_bci = compilation->osr_bci();
3597 
3598   // determine entry points and bci2block mapping
3599   BlockListBuilder blm(compilation, scope, osr_bci);
3600   CHECK_BAILOUT();
3601 
3602   BlockList* bci2block = blm.bci2block();
3603   BlockBegin* start_block = bci2block->at(0);
3604 
3605   push_root_scope(scope, bci2block, start_block);
3606 
3607   // setup state for std entry
3608   _initial_state = state_at_entry();
3609   start_block->merge(_initial_state);
3610 
3611   // complete graph
3612   _vmap        = new ValueMap();
3613   switch (scope->method()->intrinsic_id()) {
3614   case vmIntrinsics::_dabs          : // fall through
3615   case vmIntrinsics::_dsqrt         : // fall through
3616   case vmIntrinsics::_dsin          : // fall through
3617   case vmIntrinsics::_dcos          : // fall through
3618   case vmIntrinsics::_dtan          : // fall through
3619   case vmIntrinsics::_dlog          : // fall through
3620   case vmIntrinsics::_dlog10        : // fall through
3621   case vmIntrinsics::_dexp          : // fall through
3622   case vmIntrinsics::_dpow          : // fall through
3623     {
3624       // Compiles where the root method is an intrinsic need a special
3625       // compilation environment because the bytecodes for the method
3626       // shouldn't be parsed during the compilation, only the special
3627       // Intrinsic node should be emitted.  If this isn't done the the
3628       // code for the inlined version will be different than the root
3629       // compiled version which could lead to monotonicity problems on
3630       // intel.
3631       if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3632         BAILOUT("failed to inline intrinsic, method not annotated");
3633       }
3634 
3635       // Set up a stream so that appending instructions works properly.
3636       ciBytecodeStream s(scope->method());
3637       s.reset_to_bci(0);
3638       scope_data()->set_stream(&s);
3639       s.next();
3640 
3641       // setup the initial block state
3642       _block = start_block;
3643       _state = start_block->state()->copy_for_parsing();
3644       _last  = start_block;
3645       load_local(doubleType, 0);
3646       if (scope->method()->intrinsic_id() == vmIntrinsics::_dpow) {
3647         load_local(doubleType, 2);
3648       }
3649 
3650       // Emit the intrinsic node.
3651       bool result = try_inline_intrinsics(scope->method());
3652       if (!result) BAILOUT("failed to inline intrinsic");
3653       method_return(dpop());
3654 
3655       // connect the begin and end blocks and we're all done.
3656       BlockEnd* end = last()->as_BlockEnd();
3657       block()->set_end(end);
3658       break;
3659     }
3660 
3661   case vmIntrinsics::_Reference_get:
3662     {
3663       {
3664         // With java.lang.ref.reference.get() we must go through the
3665         // intrinsic - when G1 is enabled - even when get() is the root
3666         // method of the compile so that, if necessary, the value in
3667         // the referent field of the reference object gets recorded by
3668         // the pre-barrier code.
3669         // Specifically, if G1 is enabled, the value in the referent
3670         // field is recorded by the G1 SATB pre barrier. This will
3671         // result in the referent being marked live and the reference
3672         // object removed from the list of discovered references during
3673         // reference processing.
3674         if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3675           BAILOUT("failed to inline intrinsic, method not annotated");
3676         }
3677 
3678         // Also we need intrinsic to prevent commoning reads from this field
3679         // across safepoint since GC can change its value.
3680 
3681         // Set up a stream so that appending instructions works properly.
3682         ciBytecodeStream s(scope->method());
3683         s.reset_to_bci(0);
3684         scope_data()->set_stream(&s);
3685         s.next();
3686 
3687         // setup the initial block state
3688         _block = start_block;
3689         _state = start_block->state()->copy_for_parsing();
3690         _last  = start_block;
3691         load_local(objectType, 0);
3692 
3693         // Emit the intrinsic node.
3694         bool result = try_inline_intrinsics(scope->method());
3695         if (!result) BAILOUT("failed to inline intrinsic");
3696         method_return(apop());
3697 
3698         // connect the begin and end blocks and we're all done.
3699         BlockEnd* end = last()->as_BlockEnd();
3700         block()->set_end(end);
3701         break;
3702       }
3703       // Otherwise, fall thru
3704     }
3705 
3706   default:
3707     scope_data()->add_to_work_list(start_block);
3708     iterate_all_blocks();
3709     break;
3710   }
3711   CHECK_BAILOUT();
3712 
3713   _start = setup_start_block(osr_bci, start_block, _osr_entry, _initial_state);
3714 
3715   eliminate_redundant_phis(_start);
3716 
3717   NOT_PRODUCT(if (PrintValueNumbering && Verbose) print_stats());
3718   // for osr compile, bailout if some requirements are not fulfilled
3719   if (osr_bci != -1) {
3720     BlockBegin* osr_block = blm.bci2block()->at(osr_bci);
3721     if (!osr_block->is_set(BlockBegin::was_visited_flag)) {
3722       BAILOUT("osr entry must have been visited for osr compile");
3723     }
3724 
3725     // check if osr entry point has empty stack - we cannot handle non-empty stacks at osr entry points
3726     if (!osr_block->state()->stack_is_empty()) {
3727       BAILOUT("stack not empty at OSR entry point");
3728     }
3729   }
3730 #ifndef PRODUCT
3731   if (PrintCompilation && Verbose) tty->print_cr("Created %d Instructions", _instruction_count);
3732 #endif
3733 }
3734 
3735 
3736 ValueStack* GraphBuilder::copy_state_before() {
3737   return copy_state_before_with_bci(bci());
3738 }
3739 
3740 ValueStack* GraphBuilder::copy_state_exhandling() {
3741   return copy_state_exhandling_with_bci(bci());
3742 }
3743 
3744 ValueStack* GraphBuilder::copy_state_for_exception() {
3745   return copy_state_for_exception_with_bci(bci());
3746 }
3747 
3748 ValueStack* GraphBuilder::copy_state_before_with_bci(int bci) {
3749   return state()->copy(ValueStack::StateBefore, bci);
3750 }
3751 
3752 ValueStack* GraphBuilder::copy_state_exhandling_with_bci(int bci) {
3753   if (!has_handler()) return NULL;
3754   return state()->copy(ValueStack::StateBefore, bci);
3755 }
3756 
3757 ValueStack* GraphBuilder::copy_state_for_exception_with_bci(int bci) {
3758   ValueStack* s = copy_state_exhandling_with_bci(bci);
3759   if (s == NULL) {
3760     if (_compilation->env()->should_retain_local_variables()) {
3761       s = state()->copy(ValueStack::ExceptionState, bci);
3762     } else {
3763       s = state()->copy(ValueStack::EmptyExceptionState, bci);
3764     }
3765   }
3766   return s;
3767 }
3768 
3769 int GraphBuilder::recursive_inline_level(ciMethod* cur_callee) const {
3770   int recur_level = 0;
3771   for (IRScope* s = scope(); s != NULL; s = s->caller()) {
3772     if (s->method() == cur_callee) {
3773       ++recur_level;
3774     }
3775   }
3776   return recur_level;
3777 }
3778 
3779 
3780 bool GraphBuilder::try_inline(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
3781   const char* msg = NULL;
3782 
3783   // clear out any existing inline bailout condition
3784   clear_inline_bailout();
3785 
3786   // exclude methods we don't want to inline
3787   msg = should_not_inline(callee);
3788   if (msg != NULL) {
3789     print_inlining(callee, msg, /*success*/ false);
3790     return false;
3791   }
3792 
3793   // method handle invokes
3794   if (callee->is_method_handle_intrinsic()) {
3795     if (try_method_handle_inline(callee, ignore_return)) {
3796       if (callee->has_reserved_stack_access()) {
3797         compilation()->set_has_reserved_stack_access(true);
3798       }
3799       return true;
3800     }
3801     return false;
3802   }
3803 
3804   // handle intrinsics
3805   if (callee->intrinsic_id() != vmIntrinsics::_none &&
3806       callee->check_intrinsic_candidate()) {
3807     if (try_inline_intrinsics(callee, ignore_return)) {
3808       print_inlining(callee, "intrinsic");
3809       if (callee->has_reserved_stack_access()) {
3810         compilation()->set_has_reserved_stack_access(true);
3811       }
3812       return true;
3813     }
3814     // try normal inlining
3815   }
3816 
3817   // certain methods cannot be parsed at all
3818   msg = check_can_parse(callee);
3819   if (msg != NULL) {
3820     print_inlining(callee, msg, /*success*/ false);
3821     return false;
3822   }
3823 
3824   // If bytecode not set use the current one.
3825   if (bc == Bytecodes::_illegal) {
3826     bc = code();
3827   }
3828   if (try_inline_full(callee, holder_known, ignore_return, bc, receiver)) {
3829     if (callee->has_reserved_stack_access()) {
3830       compilation()->set_has_reserved_stack_access(true);
3831     }
3832     return true;
3833   }
3834 
3835   // Entire compilation could fail during try_inline_full call.
3836   // In that case printing inlining decision info is useless.
3837   if (!bailed_out())
3838     print_inlining(callee, _inline_bailout_msg, /*success*/ false);
3839 
3840   return false;
3841 }
3842 
3843 
3844 const char* GraphBuilder::check_can_parse(ciMethod* callee) const {
3845   // Certain methods cannot be parsed at all:
3846   if ( callee->is_native())            return "native method";
3847   if ( callee->is_abstract())          return "abstract method";
3848   if (!callee->can_be_parsed())        return "cannot be parsed";
3849   return NULL;
3850 }
3851 
3852 // negative filter: should callee NOT be inlined?  returns NULL, ok to inline, or rejection msg
3853 const char* GraphBuilder::should_not_inline(ciMethod* callee) const {
3854   if ( compilation()->directive()->should_not_inline(callee)) return "disallowed by CompileCommand";
3855   if ( callee->dont_inline())          return "don't inline by annotation";
3856   return NULL;
3857 }
3858 
3859 void GraphBuilder::build_graph_for_intrinsic(ciMethod* callee, bool ignore_return) {
3860   vmIntrinsics::ID id = callee->intrinsic_id();
3861   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
3862 
3863   // Some intrinsics need special IR nodes.
3864   switch(id) {
3865   case vmIntrinsics::_getReference           : append_unsafe_get(callee, T_OBJECT,  false); return;
3866   case vmIntrinsics::_getBoolean             : append_unsafe_get(callee, T_BOOLEAN, false); return;
3867   case vmIntrinsics::_getByte                : append_unsafe_get(callee, T_BYTE,    false); return;
3868   case vmIntrinsics::_getShort               : append_unsafe_get(callee, T_SHORT,   false); return;
3869   case vmIntrinsics::_getChar                : append_unsafe_get(callee, T_CHAR,    false); return;
3870   case vmIntrinsics::_getInt                 : append_unsafe_get(callee, T_INT,     false); return;
3871   case vmIntrinsics::_getLong                : append_unsafe_get(callee, T_LONG,    false); return;
3872   case vmIntrinsics::_getFloat               : append_unsafe_get(callee, T_FLOAT,   false); return;
3873   case vmIntrinsics::_getDouble              : append_unsafe_get(callee, T_DOUBLE,  false); return;
3874   case vmIntrinsics::_putReference           : append_unsafe_put(callee, T_OBJECT,  false); return;
3875   case vmIntrinsics::_putBoolean             : append_unsafe_put(callee, T_BOOLEAN, false); return;
3876   case vmIntrinsics::_putByte                : append_unsafe_put(callee, T_BYTE,    false); return;
3877   case vmIntrinsics::_putShort               : append_unsafe_put(callee, T_SHORT,   false); return;
3878   case vmIntrinsics::_putChar                : append_unsafe_put(callee, T_CHAR,    false); return;
3879   case vmIntrinsics::_putInt                 : append_unsafe_put(callee, T_INT,     false); return;
3880   case vmIntrinsics::_putLong                : append_unsafe_put(callee, T_LONG,    false); return;
3881   case vmIntrinsics::_putFloat               : append_unsafe_put(callee, T_FLOAT,   false); return;
3882   case vmIntrinsics::_putDouble              : append_unsafe_put(callee, T_DOUBLE,  false); return;
3883   case vmIntrinsics::_getShortUnaligned      : append_unsafe_get(callee, T_SHORT,   false); return;
3884   case vmIntrinsics::_getCharUnaligned       : append_unsafe_get(callee, T_CHAR,    false); return;
3885   case vmIntrinsics::_getIntUnaligned        : append_unsafe_get(callee, T_INT,     false); return;
3886   case vmIntrinsics::_getLongUnaligned       : append_unsafe_get(callee, T_LONG,    false); return;
3887   case vmIntrinsics::_putShortUnaligned      : append_unsafe_put(callee, T_SHORT,   false); return;
3888   case vmIntrinsics::_putCharUnaligned       : append_unsafe_put(callee, T_CHAR,    false); return;
3889   case vmIntrinsics::_putIntUnaligned        : append_unsafe_put(callee, T_INT,     false); return;
3890   case vmIntrinsics::_putLongUnaligned       : append_unsafe_put(callee, T_LONG,    false); return;
3891   case vmIntrinsics::_getReferenceVolatile   : append_unsafe_get(callee, T_OBJECT,  true); return;
3892   case vmIntrinsics::_getBooleanVolatile     : append_unsafe_get(callee, T_BOOLEAN, true); return;
3893   case vmIntrinsics::_getByteVolatile        : append_unsafe_get(callee, T_BYTE,    true); return;
3894   case vmIntrinsics::_getShortVolatile       : append_unsafe_get(callee, T_SHORT,   true); return;
3895   case vmIntrinsics::_getCharVolatile        : append_unsafe_get(callee, T_CHAR,    true); return;
3896   case vmIntrinsics::_getIntVolatile         : append_unsafe_get(callee, T_INT,     true); return;
3897   case vmIntrinsics::_getLongVolatile        : append_unsafe_get(callee, T_LONG,    true); return;
3898   case vmIntrinsics::_getFloatVolatile       : append_unsafe_get(callee, T_FLOAT,   true); return;
3899   case vmIntrinsics::_getDoubleVolatile      : append_unsafe_get(callee, T_DOUBLE,  true); return;
3900   case vmIntrinsics::_putReferenceVolatile   : append_unsafe_put(callee, T_OBJECT,  true); return;
3901   case vmIntrinsics::_putBooleanVolatile     : append_unsafe_put(callee, T_BOOLEAN, true); return;
3902   case vmIntrinsics::_putByteVolatile        : append_unsafe_put(callee, T_BYTE,    true); return;
3903   case vmIntrinsics::_putShortVolatile       : append_unsafe_put(callee, T_SHORT,   true); return;
3904   case vmIntrinsics::_putCharVolatile        : append_unsafe_put(callee, T_CHAR,    true); return;
3905   case vmIntrinsics::_putIntVolatile         : append_unsafe_put(callee, T_INT,     true); return;
3906   case vmIntrinsics::_putLongVolatile        : append_unsafe_put(callee, T_LONG,    true); return;
3907   case vmIntrinsics::_putFloatVolatile       : append_unsafe_put(callee, T_FLOAT,   true); return;
3908   case vmIntrinsics::_putDoubleVolatile      : append_unsafe_put(callee, T_DOUBLE,  true); return;
3909   case vmIntrinsics::_compareAndSetLong:
3910   case vmIntrinsics::_compareAndSetInt:
3911   case vmIntrinsics::_compareAndSetReference : append_unsafe_CAS(callee); return;
3912   case vmIntrinsics::_getAndAddInt:
3913   case vmIntrinsics::_getAndAddLong          : append_unsafe_get_and_set(callee, true); return;
3914   case vmIntrinsics::_getAndSetInt           :
3915   case vmIntrinsics::_getAndSetLong          :
3916   case vmIntrinsics::_getAndSetReference     : append_unsafe_get_and_set(callee, false); return;
3917   case vmIntrinsics::_getCharStringU         : append_char_access(callee, false); return;
3918   case vmIntrinsics::_putCharStringU         : append_char_access(callee, true); return;
3919   default:
3920     break;
3921   }
3922 
3923   // create intrinsic node
3924   const bool has_receiver = !callee->is_static();
3925   ValueType* result_type = as_ValueType(callee->return_type());
3926   ValueStack* state_before = copy_state_for_exception();
3927 
3928   Values* args = state()->pop_arguments(callee->arg_size());
3929 
3930   if (is_profiling()) {
3931     // Don't profile in the special case where the root method
3932     // is the intrinsic
3933     if (callee != method()) {
3934       // Note that we'd collect profile data in this method if we wanted it.
3935       compilation()->set_would_profile(true);
3936       if (profile_calls()) {
3937         Value recv = NULL;
3938         if (has_receiver) {
3939           recv = args->at(0);
3940           null_check(recv);
3941         }
3942         profile_call(callee, recv, NULL, collect_args_for_profiling(args, callee, true), true);
3943       }
3944     }
3945   }
3946 
3947   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(),
3948                                     args, has_receiver, state_before,
3949                                     vmIntrinsics::preserves_state(id),
3950                                     vmIntrinsics::can_trap(id));
3951   // append instruction & push result
3952   Value value = append_split(result);
3953   if (result_type != voidType && !ignore_return) {
3954     push(result_type, value);
3955   }
3956 
3957   if (callee != method() && profile_return() && result_type->is_object_kind()) {
3958     profile_return_type(result, callee);
3959   }
3960 }
3961 
3962 bool GraphBuilder::try_inline_intrinsics(ciMethod* callee, bool ignore_return) {
3963   // For calling is_intrinsic_available we need to transition to
3964   // the '_thread_in_vm' state because is_intrinsic_available()
3965   // accesses critical VM-internal data.
3966   bool is_available = false;
3967   {
3968     VM_ENTRY_MARK;
3969     methodHandle mh(THREAD, callee->get_Method());
3970     is_available = _compilation->compiler()->is_intrinsic_available(mh, _compilation->directive());
3971   }
3972 
3973   if (!is_available) {
3974     if (!InlineNatives) {
3975       // Return false and also set message that the inlining of
3976       // intrinsics has been disabled in general.
3977       INLINE_BAILOUT("intrinsic method inlining disabled");
3978     } else {
3979       return false;
3980     }
3981   }
3982   build_graph_for_intrinsic(callee, ignore_return);
3983   return true;
3984 }
3985 
3986 
3987 bool GraphBuilder::try_inline_jsr(int jsr_dest_bci) {
3988   // Introduce a new callee continuation point - all Ret instructions
3989   // will be replaced with Gotos to this point.
3990   BlockBegin* cont = block_at(next_bci());
3991   assert(cont != NULL, "continuation must exist (BlockListBuilder starts a new block after a jsr");
3992 
3993   // Note: can not assign state to continuation yet, as we have to
3994   // pick up the state from the Ret instructions.
3995 
3996   // Push callee scope
3997   push_scope_for_jsr(cont, jsr_dest_bci);
3998 
3999   // Temporarily set up bytecode stream so we can append instructions
4000   // (only using the bci of this stream)
4001   scope_data()->set_stream(scope_data()->parent()->stream());
4002 
4003   BlockBegin* jsr_start_block = block_at(jsr_dest_bci);
4004   assert(jsr_start_block != NULL, "jsr start block must exist");
4005   assert(!jsr_start_block->is_set(BlockBegin::was_visited_flag), "should not have visited jsr yet");
4006   Goto* goto_sub = new Goto(jsr_start_block, false);
4007   // Must copy state to avoid wrong sharing when parsing bytecodes
4008   assert(jsr_start_block->state() == NULL, "should have fresh jsr starting block");
4009   jsr_start_block->set_state(copy_state_before_with_bci(jsr_dest_bci));
4010   append(goto_sub);
4011   _block->set_end(goto_sub);
4012   _last = _block = jsr_start_block;
4013 
4014   // Clear out bytecode stream
4015   scope_data()->set_stream(NULL);
4016 
4017   scope_data()->add_to_work_list(jsr_start_block);
4018 
4019   // Ready to resume parsing in subroutine
4020   iterate_all_blocks();
4021 
4022   // If we bailed out during parsing, return immediately (this is bad news)
4023   CHECK_BAILOUT_(false);
4024 
4025   // Detect whether the continuation can actually be reached. If not,
4026   // it has not had state set by the join() operations in
4027   // iterate_bytecodes_for_block()/ret() and we should not touch the
4028   // iteration state. The calling activation of
4029   // iterate_bytecodes_for_block will then complete normally.
4030   if (cont->state() != NULL) {
4031     if (!cont->is_set(BlockBegin::was_visited_flag)) {
4032       // add continuation to work list instead of parsing it immediately
4033       scope_data()->parent()->add_to_work_list(cont);
4034     }
4035   }
4036 
4037   assert(jsr_continuation() == cont, "continuation must not have changed");
4038   assert(!jsr_continuation()->is_set(BlockBegin::was_visited_flag) ||
4039          jsr_continuation()->is_set(BlockBegin::parser_loop_header_flag),
4040          "continuation can only be visited in case of backward branches");
4041   assert(_last && _last->as_BlockEnd(), "block must have end");
4042 
4043   // continuation is in work list, so end iteration of current block
4044   _skip_block = true;
4045   pop_scope_for_jsr();
4046 
4047   return true;
4048 }
4049 
4050 
4051 // Inline the entry of a synchronized method as a monitor enter and
4052 // register the exception handler which releases the monitor if an
4053 // exception is thrown within the callee. Note that the monitor enter
4054 // cannot throw an exception itself, because the receiver is
4055 // guaranteed to be non-null by the explicit null check at the
4056 // beginning of inlining.
4057 void GraphBuilder::inline_sync_entry(Value lock, BlockBegin* sync_handler) {
4058   assert(lock != NULL && sync_handler != NULL, "lock or handler missing");
4059 
4060   monitorenter(lock, SynchronizationEntryBCI);
4061   assert(_last->as_MonitorEnter() != NULL, "monitor enter expected");
4062   _last->set_needs_null_check(false);
4063 
4064   sync_handler->set(BlockBegin::exception_entry_flag);
4065   sync_handler->set(BlockBegin::is_on_work_list_flag);
4066 
4067   ciExceptionHandler* desc = new ciExceptionHandler(method()->holder(), 0, method()->code_size(), -1, 0);
4068   XHandler* h = new XHandler(desc);
4069   h->set_entry_block(sync_handler);
4070   scope_data()->xhandlers()->append(h);
4071   scope_data()->set_has_handler();
4072 }
4073 
4074 
4075 // If an exception is thrown and not handled within an inlined
4076 // synchronized method, the monitor must be released before the
4077 // exception is rethrown in the outer scope. Generate the appropriate
4078 // instructions here.
4079 void GraphBuilder::fill_sync_handler(Value lock, BlockBegin* sync_handler, bool default_handler) {
4080   BlockBegin* orig_block = _block;
4081   ValueStack* orig_state = _state;
4082   Instruction* orig_last = _last;
4083   _last = _block = sync_handler;
4084   _state = sync_handler->state()->copy();
4085 
4086   assert(sync_handler != NULL, "handler missing");
4087   assert(!sync_handler->is_set(BlockBegin::was_visited_flag), "is visited here");
4088 
4089   assert(lock != NULL || default_handler, "lock or handler missing");
4090 
4091   XHandler* h = scope_data()->xhandlers()->remove_last();
4092   assert(h->entry_block() == sync_handler, "corrupt list of handlers");
4093 
4094   block()->set(BlockBegin::was_visited_flag);
4095   Value exception = append_with_bci(new ExceptionObject(), SynchronizationEntryBCI);
4096   assert(exception->is_pinned(), "must be");
4097 
4098   int bci = SynchronizationEntryBCI;
4099   if (compilation()->env()->dtrace_method_probes()) {
4100     // Report exit from inline methods.  We don't have a stream here
4101     // so pass an explicit bci of SynchronizationEntryBCI.
4102     Values* args = new Values(1);
4103     args->push(append_with_bci(new Constant(new MethodConstant(method())), bci));
4104     append_with_bci(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args), bci);
4105   }
4106 
4107   if (lock) {
4108     assert(state()->locks_size() > 0 && state()->lock_at(state()->locks_size() - 1) == lock, "lock is missing");
4109     if (!lock->is_linked()) {
4110       lock = append_with_bci(lock, bci);
4111     }
4112 
4113     // exit the monitor in the context of the synchronized method
4114     monitorexit(lock, bci);
4115 
4116     // exit the context of the synchronized method
4117     if (!default_handler) {
4118       pop_scope();
4119       bci = _state->caller_state()->bci();
4120       _state = _state->caller_state()->copy_for_parsing();
4121     }
4122   }
4123 
4124   // perform the throw as if at the the call site
4125   apush(exception);
4126   throw_op(bci);
4127 
4128   BlockEnd* end = last()->as_BlockEnd();
4129   block()->set_end(end);
4130 
4131   _block = orig_block;
4132   _state = orig_state;
4133   _last = orig_last;
4134 }
4135 
4136 
4137 bool GraphBuilder::try_inline_full(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
4138   assert(!callee->is_native(), "callee must not be native");
4139   if (CompilationPolicy::should_not_inline(compilation()->env(), callee)) {
4140     INLINE_BAILOUT("inlining prohibited by policy");
4141   }
4142   // first perform tests of things it's not possible to inline
4143   if (callee->has_exception_handlers() &&
4144       !InlineMethodsWithExceptionHandlers) INLINE_BAILOUT("callee has exception handlers");
4145   if (callee->is_synchronized() &&
4146       !InlineSynchronizedMethods         ) INLINE_BAILOUT("callee is synchronized");
4147   if (!callee->holder()->is_linked())      INLINE_BAILOUT("callee's klass not linked yet");
4148   if (bc == Bytecodes::_invokestatic &&
4149       !callee->holder()->is_initialized()) INLINE_BAILOUT("callee's klass not initialized yet");
4150   if (!callee->has_balanced_monitors())    INLINE_BAILOUT("callee's monitors do not match");
4151 
4152   // Proper inlining of methods with jsrs requires a little more work.
4153   if (callee->has_jsrs()                 ) INLINE_BAILOUT("jsrs not handled properly by inliner yet");
4154 
4155   if (is_profiling() && !callee->ensure_method_data()) {
4156     INLINE_BAILOUT("mdo allocation failed");
4157   }
4158 
4159   const bool is_invokedynamic = (bc == Bytecodes::_invokedynamic);
4160   const bool has_receiver = (bc != Bytecodes::_invokestatic && !is_invokedynamic);
4161 
4162   const int args_base = state()->stack_size() - callee->arg_size();
4163   assert(args_base >= 0, "stack underflow during inlining");
4164 
4165   Value recv = NULL;
4166   if (has_receiver) {
4167     assert(!callee->is_static(), "callee must not be static");
4168     assert(callee->arg_size() > 0, "must have at least a receiver");
4169 
4170     recv = state()->stack_at(args_base);
4171     if (recv->is_null_obj()) {
4172       INLINE_BAILOUT("receiver is always null");
4173     }
4174   }
4175 
4176   // now perform tests that are based on flag settings
4177   bool inlinee_by_directive = compilation()->directive()->should_inline(callee);
4178   if (callee->force_inline() || inlinee_by_directive) {
4179     if (inline_level() > MaxForceInlineLevel                      ) INLINE_BAILOUT("MaxForceInlineLevel");
4180     if (recursive_inline_level(callee) > C1MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");
4181 
4182     const char* msg = "";
4183     if (callee->force_inline())  msg = "force inline by annotation";
4184     if (inlinee_by_directive)    msg = "force inline by CompileCommand";
4185     print_inlining(callee, msg);
4186   } else {
4187     // use heuristic controls on inlining
4188     if (inline_level() > C1MaxInlineLevel                       ) INLINE_BAILOUT("inlining too deep");
4189     int callee_recursive_level = recursive_inline_level(callee);
4190     if (callee_recursive_level > C1MaxRecursiveInlineLevel      ) INLINE_BAILOUT("recursive inlining too deep");
4191     if (callee->code_size_for_inlining() > max_inline_size()    ) INLINE_BAILOUT("callee is too large");
4192     // Additional condition to limit stack usage for non-recursive calls.
4193     if ((callee_recursive_level == 0) &&
4194         (callee->max_stack() + callee->max_locals() - callee->size_of_parameters() > C1InlineStackLimit)) {
4195       INLINE_BAILOUT("callee uses too much stack");
4196     }
4197 
4198     // don't inline throwable methods unless the inlining tree is rooted in a throwable class
4199     if (callee->name() == ciSymbols::object_initializer_name() &&
4200         callee->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
4201       // Throwable constructor call
4202       IRScope* top = scope();
4203       while (top->caller() != NULL) {
4204         top = top->caller();
4205       }
4206       if (!top->method()->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
4207         INLINE_BAILOUT("don't inline Throwable constructors");
4208       }
4209     }
4210 
4211     if (compilation()->env()->num_inlined_bytecodes() > DesiredMethodLimit) {
4212       INLINE_BAILOUT("total inlining greater than DesiredMethodLimit");
4213     }
4214     // printing
4215     print_inlining(callee, "inline", /*success*/ true);
4216   }
4217 
4218   assert(bc != Bytecodes::_invokestatic || callee->holder()->is_initialized(), "required");
4219 
4220   // NOTE: Bailouts from this point on, which occur at the
4221   // GraphBuilder level, do not cause bailout just of the inlining but
4222   // in fact of the entire compilation.
4223 
4224   BlockBegin* orig_block = block();
4225 
4226   // Insert null check if necessary
4227   if (has_receiver) {
4228     // note: null check must happen even if first instruction of callee does
4229     //       an implicit null check since the callee is in a different scope
4230     //       and we must make sure exception handling does the right thing
4231     null_check(recv);
4232   }
4233 
4234   if (is_profiling()) {
4235     // Note that we'd collect profile data in this method if we wanted it.
4236     // this may be redundant here...
4237     compilation()->set_would_profile(true);
4238 
4239     if (profile_calls()) {
4240       int start = 0;
4241       Values* obj_args = args_list_for_profiling(callee, start, has_receiver);
4242       if (obj_args != NULL) {
4243         int s = obj_args->max_length();
4244         // if called through method handle invoke, some arguments may have been popped
4245         for (int i = args_base+start, j = 0; j < obj_args->max_length() && i < state()->stack_size(); ) {
4246           Value v = state()->stack_at_inc(i);
4247           if (v->type()->is_object_kind()) {
4248             obj_args->push(v);
4249             j++;
4250           }
4251         }
4252         check_args_for_profiling(obj_args, s);
4253       }
4254       profile_call(callee, recv, holder_known ? callee->holder() : NULL, obj_args, true);
4255     }
4256   }
4257 
4258   // Introduce a new callee continuation point - if the callee has
4259   // more than one return instruction or the return does not allow
4260   // fall-through of control flow, all return instructions of the
4261   // callee will need to be replaced by Goto's pointing to this
4262   // continuation point.
4263   BlockBegin* cont = block_at(next_bci());
4264   bool continuation_existed = true;
4265   if (cont == NULL) {
4266     cont = new BlockBegin(next_bci());
4267     // low number so that continuation gets parsed as early as possible
4268     cont->set_depth_first_number(0);
4269     if (PrintInitialBlockList) {
4270       tty->print_cr("CFG: created block %d (bci %d) as continuation for inline at bci %d",
4271                     cont->block_id(), cont->bci(), bci());
4272     }
4273     continuation_existed = false;
4274   }
4275   // Record number of predecessors of continuation block before
4276   // inlining, to detect if inlined method has edges to its
4277   // continuation after inlining.
4278   int continuation_preds = cont->number_of_preds();
4279 
4280   // Push callee scope
4281   push_scope(callee, cont);
4282 
4283   // the BlockListBuilder for the callee could have bailed out
4284   if (bailed_out())
4285       return false;
4286 
4287   // Temporarily set up bytecode stream so we can append instructions
4288   // (only using the bci of this stream)
4289   scope_data()->set_stream(scope_data()->parent()->stream());
4290 
4291   // Pass parameters into callee state: add assignments
4292   // note: this will also ensure that all arguments are computed before being passed
4293   ValueStack* callee_state = state();
4294   ValueStack* caller_state = state()->caller_state();
4295   for (int i = args_base; i < caller_state->stack_size(); ) {
4296     const int arg_no = i - args_base;
4297     Value arg = caller_state->stack_at_inc(i);
4298     store_local(callee_state, arg, arg_no);
4299   }
4300 
4301   // Remove args from stack.
4302   // Note that we preserve locals state in case we can use it later
4303   // (see use of pop_scope() below)
4304   caller_state->truncate_stack(args_base);
4305   assert(callee_state->stack_size() == 0, "callee stack must be empty");
4306 
4307   Value lock = NULL;
4308   BlockBegin* sync_handler = NULL;
4309 
4310   // Inline the locking of the receiver if the callee is synchronized
4311   if (callee->is_synchronized()) {
4312     lock = callee->is_static() ? append(new Constant(new InstanceConstant(callee->holder()->java_mirror())))
4313                                : state()->local_at(0);
4314     sync_handler = new BlockBegin(SynchronizationEntryBCI);
4315     inline_sync_entry(lock, sync_handler);
4316   }
4317 
4318   if (compilation()->env()->dtrace_method_probes()) {
4319     Values* args = new Values(1);
4320     args->push(append(new Constant(new MethodConstant(method()))));
4321     append(new RuntimeCall(voidType, "dtrace_method_entry", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), args));
4322   }
4323 
4324   if (profile_inlined_calls()) {
4325     profile_invocation(callee, copy_state_before_with_bci(SynchronizationEntryBCI));
4326   }
4327 
4328   BlockBegin* callee_start_block = block_at(0);
4329   if (callee_start_block != NULL) {
4330     assert(callee_start_block->is_set(BlockBegin::parser_loop_header_flag), "must be loop header");
4331     Goto* goto_callee = new Goto(callee_start_block, false);
4332     // The state for this goto is in the scope of the callee, so use
4333     // the entry bci for the callee instead of the call site bci.
4334     append_with_bci(goto_callee, 0);
4335     _block->set_end(goto_callee);
4336     callee_start_block->merge(callee_state);
4337 
4338     _last = _block = callee_start_block;
4339 
4340     scope_data()->add_to_work_list(callee_start_block);
4341   }
4342 
4343   // Clear out bytecode stream
4344   scope_data()->set_stream(NULL);
4345   scope_data()->set_ignore_return(ignore_return);
4346 
4347   CompileLog* log = compilation()->log();
4348   if (log != NULL) log->head("parse method='%d'", log->identify(callee));
4349 
4350   // Ready to resume parsing in callee (either in the same block we
4351   // were in before or in the callee's start block)
4352   iterate_all_blocks(callee_start_block == NULL);
4353 
4354   if (log != NULL) log->done("parse");
4355 
4356   // If we bailed out during parsing, return immediately (this is bad news)
4357   if (bailed_out())
4358       return false;
4359 
4360   // iterate_all_blocks theoretically traverses in random order; in
4361   // practice, we have only traversed the continuation if we are
4362   // inlining into a subroutine
4363   assert(continuation_existed ||
4364          !continuation()->is_set(BlockBegin::was_visited_flag),
4365          "continuation should not have been parsed yet if we created it");
4366 
4367   // At this point we are almost ready to return and resume parsing of
4368   // the caller back in the GraphBuilder. The only thing we want to do
4369   // first is an optimization: during parsing of the callee we
4370   // generated at least one Goto to the continuation block. If we
4371   // generated exactly one, and if the inlined method spanned exactly
4372   // one block (and we didn't have to Goto its entry), then we snip
4373   // off the Goto to the continuation, allowing control to fall
4374   // through back into the caller block and effectively performing
4375   // block merging. This allows load elimination and CSE to take place
4376   // across multiple callee scopes if they are relatively simple, and
4377   // is currently essential to making inlining profitable.
4378   if (num_returns() == 1
4379       && block() == orig_block
4380       && block() == inline_cleanup_block()) {
4381     _last  = inline_cleanup_return_prev();
4382     _state = inline_cleanup_state();
4383   } else if (continuation_preds == cont->number_of_preds()) {
4384     // Inlining caused that the instructions after the invoke in the
4385     // caller are not reachable any more. So skip filling this block
4386     // with instructions!
4387     assert(cont == continuation(), "");
4388     assert(_last && _last->as_BlockEnd(), "");
4389     _skip_block = true;
4390   } else {
4391     // Resume parsing in continuation block unless it was already parsed.
4392     // Note that if we don't change _last here, iteration in
4393     // iterate_bytecodes_for_block will stop when we return.
4394     if (!continuation()->is_set(BlockBegin::was_visited_flag)) {
4395       // add continuation to work list instead of parsing it immediately
4396       assert(_last && _last->as_BlockEnd(), "");
4397       scope_data()->parent()->add_to_work_list(continuation());
4398       _skip_block = true;
4399     }
4400   }
4401 
4402   // Fill the exception handler for synchronized methods with instructions
4403   if (callee->is_synchronized() && sync_handler->state() != NULL) {
4404     fill_sync_handler(lock, sync_handler);
4405   } else {
4406     pop_scope();
4407   }
4408 
4409   compilation()->notice_inlined_method(callee);
4410 
4411   return true;
4412 }
4413 
4414 
4415 bool GraphBuilder::try_method_handle_inline(ciMethod* callee, bool ignore_return) {
4416   ValueStack* state_before = copy_state_before();
4417   vmIntrinsics::ID iid = callee->intrinsic_id();
4418   switch (iid) {
4419   case vmIntrinsics::_invokeBasic:
4420     {
4421       // get MethodHandle receiver
4422       const int args_base = state()->stack_size() - callee->arg_size();
4423       ValueType* type = state()->stack_at(args_base)->type();
4424       if (type->is_constant()) {
4425         ciMethod* target = type->as_ObjectType()->constant_value()->as_method_handle()->get_vmtarget();
4426         // We don't do CHA here so only inline static and statically bindable methods.
4427         if (target->is_static() || target->can_be_statically_bound()) {
4428           if (ciMethod::is_consistent_info(callee, target)) {
4429             Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4430             ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4431             if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4432               return true;
4433             }
4434           } else {
4435             print_inlining(target, "signatures mismatch", /*success*/ false);
4436           }
4437         } else {
4438           print_inlining(target, "not static or statically bindable", /*success*/ false);
4439         }
4440       } else {
4441         print_inlining(callee, "receiver not constant", /*success*/ false);
4442       }
4443     }
4444     break;
4445 
4446   case vmIntrinsics::_linkToVirtual:
4447   case vmIntrinsics::_linkToStatic:
4448   case vmIntrinsics::_linkToSpecial:
4449   case vmIntrinsics::_linkToInterface:
4450     {
4451       // pop MemberName argument
4452       const int args_base = state()->stack_size() - callee->arg_size();
4453       ValueType* type = apop()->type();
4454       if (type->is_constant()) {
4455         ciMethod* target = type->as_ObjectType()->constant_value()->as_member_name()->get_vmtarget();
4456         ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4457         // If the target is another method handle invoke, try to recursively get
4458         // a better target.
4459         if (target->is_method_handle_intrinsic()) {
4460           if (try_method_handle_inline(target, ignore_return)) {
4461             return true;
4462           }
4463         } else if (!ciMethod::is_consistent_info(callee, target)) {
4464           print_inlining(target, "signatures mismatch", /*success*/ false);
4465         } else {
4466           ciSignature* signature = target->signature();
4467           const int receiver_skip = target->is_static() ? 0 : 1;
4468           // Cast receiver to its type.
4469           if (!target->is_static()) {
4470             ciKlass* tk = signature->accessing_klass();
4471             Value obj = state()->stack_at(args_base);
4472             if (obj->exact_type() == NULL &&
4473                 obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4474               TypeCast* c = new TypeCast(tk, obj, state_before);
4475               append(c);
4476               state()->stack_at_put(args_base, c);
4477             }
4478           }
4479           // Cast reference arguments to its type.
4480           for (int i = 0, j = 0; i < signature->count(); i++) {
4481             ciType* t = signature->type_at(i);
4482             if (t->is_klass()) {
4483               ciKlass* tk = t->as_klass();
4484               Value obj = state()->stack_at(args_base + receiver_skip + j);
4485               if (obj->exact_type() == NULL &&
4486                   obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4487                 TypeCast* c = new TypeCast(t, obj, state_before);
4488                 append(c);
4489                 state()->stack_at_put(args_base + receiver_skip + j, c);
4490               }
4491             }
4492             j += t->size();  // long and double take two slots
4493           }
4494           // We don't do CHA here so only inline static and statically bindable methods.
4495           if (target->is_static() || target->can_be_statically_bound()) {
4496             Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4497             if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4498               return true;
4499             }
4500           } else {
4501             print_inlining(target, "not static or statically bindable", /*success*/ false);
4502           }
4503         }
4504       } else {
4505         print_inlining(callee, "MemberName not constant", /*success*/ false);
4506       }
4507     }
4508     break;
4509 
4510   case vmIntrinsics::_linkToNative:
4511     break; // TODO: NYI
4512 
4513   default:
4514     fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
4515     break;
4516   }
4517   set_state(state_before->copy_for_parsing());
4518   return false;
4519 }
4520 
4521 
4522 void GraphBuilder::inline_bailout(const char* msg) {
4523   assert(msg != NULL, "inline bailout msg must exist");
4524   _inline_bailout_msg = msg;
4525 }
4526 
4527 
4528 void GraphBuilder::clear_inline_bailout() {
4529   _inline_bailout_msg = NULL;
4530 }
4531 
4532 
4533 void GraphBuilder::push_root_scope(IRScope* scope, BlockList* bci2block, BlockBegin* start) {
4534   ScopeData* data = new ScopeData(NULL);
4535   data->set_scope(scope);
4536   data->set_bci2block(bci2block);
4537   _scope_data = data;
4538   _block = start;
4539 }
4540 
4541 
4542 void GraphBuilder::push_scope(ciMethod* callee, BlockBegin* continuation) {
4543   IRScope* callee_scope = new IRScope(compilation(), scope(), bci(), callee, -1, false);
4544   scope()->add_callee(callee_scope);
4545 
4546   BlockListBuilder blb(compilation(), callee_scope, -1);
4547   CHECK_BAILOUT();
4548 
4549   if (!blb.bci2block()->at(0)->is_set(BlockBegin::parser_loop_header_flag)) {
4550     // this scope can be inlined directly into the caller so remove
4551     // the block at bci 0.
4552     blb.bci2block()->at_put(0, NULL);
4553   }
4554 
4555   set_state(new ValueStack(callee_scope, state()->copy(ValueStack::CallerState, bci())));
4556 
4557   ScopeData* data = new ScopeData(scope_data());
4558   data->set_scope(callee_scope);
4559   data->set_bci2block(blb.bci2block());
4560   data->set_continuation(continuation);
4561   _scope_data = data;
4562 }
4563 
4564 
4565 void GraphBuilder::push_scope_for_jsr(BlockBegin* jsr_continuation, int jsr_dest_bci) {
4566   ScopeData* data = new ScopeData(scope_data());
4567   data->set_parsing_jsr();
4568   data->set_jsr_entry_bci(jsr_dest_bci);
4569   data->set_jsr_return_address_local(-1);
4570   // Must clone bci2block list as we will be mutating it in order to
4571   // properly clone all blocks in jsr region as well as exception
4572   // handlers containing rets
4573   BlockList* new_bci2block = new BlockList(bci2block()->length());
4574   new_bci2block->appendAll(bci2block());
4575   data->set_bci2block(new_bci2block);
4576   data->set_scope(scope());
4577   data->setup_jsr_xhandlers();
4578   data->set_continuation(continuation());
4579   data->set_jsr_continuation(jsr_continuation);
4580   _scope_data = data;
4581 }
4582 
4583 
4584 void GraphBuilder::pop_scope() {
4585   int number_of_locks = scope()->number_of_locks();
4586   _scope_data = scope_data()->parent();
4587   // accumulate minimum number of monitor slots to be reserved
4588   scope()->set_min_number_of_locks(number_of_locks);
4589 }
4590 
4591 
4592 void GraphBuilder::pop_scope_for_jsr() {
4593   _scope_data = scope_data()->parent();
4594 }
4595 
4596 void GraphBuilder::append_unsafe_get(ciMethod* callee, BasicType t, bool is_volatile) {
4597   Values* args = state()->pop_arguments(callee->arg_size());
4598   null_check(args->at(0));
4599   Instruction* offset = args->at(2);
4600 #ifndef _LP64
4601   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4602 #endif
4603   Instruction* op = append(new UnsafeGet(t, args->at(1), offset, is_volatile));
4604   push(op->type(), op);
4605   compilation()->set_has_unsafe_access(true);
4606 }
4607 
4608 
4609 void GraphBuilder::append_unsafe_put(ciMethod* callee, BasicType t, bool is_volatile) {
4610   Values* args = state()->pop_arguments(callee->arg_size());
4611   null_check(args->at(0));
4612   Instruction* offset = args->at(2);
4613 #ifndef _LP64
4614   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4615 #endif
4616   Value val = args->at(3);
4617   if (t == T_BOOLEAN) {
4618     Value mask = append(new Constant(new IntConstant(1)));
4619     val = append(new LogicOp(Bytecodes::_iand, val, mask));
4620   }
4621   Instruction* op = append(new UnsafePut(t, args->at(1), offset, val, is_volatile));
4622   compilation()->set_has_unsafe_access(true);
4623   kill_all();
4624 }
4625 
4626 void GraphBuilder::append_unsafe_CAS(ciMethod* callee) {
4627   ValueStack* state_before = copy_state_for_exception();
4628   ValueType* result_type = as_ValueType(callee->return_type());
4629   assert(result_type->is_int(), "int result");
4630   Values* args = state()->pop_arguments(callee->arg_size());
4631 
4632   // Pop off some args to specially handle, then push back
4633   Value newval = args->pop();
4634   Value cmpval = args->pop();
4635   Value offset = args->pop();
4636   Value src = args->pop();
4637   Value unsafe_obj = args->pop();
4638 
4639   // Separately handle the unsafe arg. It is not needed for code
4640   // generation, but must be null checked
4641   null_check(unsafe_obj);
4642 
4643 #ifndef _LP64
4644   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4645 #endif
4646 
4647   args->push(src);
4648   args->push(offset);
4649   args->push(cmpval);
4650   args->push(newval);
4651 
4652   // An unsafe CAS can alias with other field accesses, but we don't
4653   // know which ones so mark the state as no preserved.  This will
4654   // cause CSE to invalidate memory across it.
4655   bool preserves_state = false;
4656   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(), args, false, state_before, preserves_state);
4657   append_split(result);
4658   push(result_type, result);
4659   compilation()->set_has_unsafe_access(true);
4660 }
4661 
4662 void GraphBuilder::append_char_access(ciMethod* callee, bool is_store) {
4663   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
4664   // correctly requires matched array shapes.
4665   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
4666           "sanity: byte[] and char[] bases agree");
4667   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
4668           "sanity: byte[] and char[] scales agree");
4669 
4670   ValueStack* state_before = copy_state_indexed_access();
4671   compilation()->set_has_access_indexed(true);
4672   Values* args = state()->pop_arguments(callee->arg_size());
4673   Value array = args->at(0);
4674   Value index = args->at(1);
4675   if (is_store) {
4676     Value value = args->at(2);
4677     Instruction* store = append(new StoreIndexed(array, index, NULL, T_CHAR, value, state_before, false, true));
4678     store->set_flag(Instruction::NeedsRangeCheckFlag, false);
4679     _memory->store_value(value);
4680   } else {
4681     Instruction* load = append(new LoadIndexed(array, index, NULL, T_CHAR, state_before, true));
4682     load->set_flag(Instruction::NeedsRangeCheckFlag, false);
4683     push(load->type(), load);
4684   }
4685 }
4686 
4687 void GraphBuilder::print_inlining(ciMethod* callee, const char* msg, bool success) {
4688   CompileLog* log = compilation()->log();
4689   if (log != NULL) {
4690     assert(msg != NULL, "inlining msg should not be null!");
4691     if (success) {
4692       log->inline_success(msg);
4693     } else {
4694       log->inline_fail(msg);
4695     }
4696   }
4697   EventCompilerInlining event;
4698   if (event.should_commit()) {
4699     CompilerEvent::InlineEvent::post(event, compilation()->env()->task()->compile_id(), method()->get_Method(), callee, success, msg, bci());
4700   }
4701 
4702   CompileTask::print_inlining_ul(callee, scope()->level(), bci(), msg);
4703 
4704   if (!compilation()->directive()->PrintInliningOption) {
4705     return;
4706   }
4707   CompileTask::print_inlining_tty(callee, scope()->level(), bci(), msg);
4708   if (success && CIPrintMethodCodes) {
4709     callee->print_codes();
4710   }
4711 }
4712 
4713 void GraphBuilder::append_unsafe_get_and_set(ciMethod* callee, bool is_add) {
4714   Values* args = state()->pop_arguments(callee->arg_size());
4715   BasicType t = callee->return_type()->basic_type();
4716   null_check(args->at(0));
4717   Instruction* offset = args->at(2);
4718 #ifndef _LP64
4719   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4720 #endif
4721   Instruction* op = append(new UnsafeGetAndSet(t, args->at(1), offset, args->at(3), is_add));
4722   compilation()->set_has_unsafe_access(true);
4723   kill_all();
4724   push(op->type(), op);
4725 }
4726 
4727 #ifndef PRODUCT
4728 void GraphBuilder::print_stats() {
4729   vmap()->print();
4730 }
4731 #endif // PRODUCT
4732 
4733 void GraphBuilder::profile_call(ciMethod* callee, Value recv, ciKlass* known_holder, Values* obj_args, bool inlined) {
4734   assert(known_holder == NULL || (known_holder->is_instance_klass() &&
4735                                   (!known_holder->is_interface() ||
4736                                    ((ciInstanceKlass*)known_holder)->has_nonstatic_concrete_methods())), "should be non-static concrete method");
4737   if (known_holder != NULL) {
4738     if (known_holder->exact_klass() == NULL) {
4739       known_holder = compilation()->cha_exact_type(known_holder);
4740     }
4741   }
4742 
4743   append(new ProfileCall(method(), bci(), callee, recv, known_holder, obj_args, inlined));
4744 }
4745 
4746 void GraphBuilder::profile_return_type(Value ret, ciMethod* callee, ciMethod* m, int invoke_bci) {
4747   assert((m == NULL) == (invoke_bci < 0), "invalid method and invalid bci together");
4748   if (m == NULL) {
4749     m = method();
4750   }
4751   if (invoke_bci < 0) {
4752     invoke_bci = bci();
4753   }
4754   ciMethodData* md = m->method_data_or_null();
4755   ciProfileData* data = md->bci_to_data(invoke_bci);
4756   if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
4757     bool has_return = data->is_CallTypeData() ? ((ciCallTypeData*)data)->has_return() : ((ciVirtualCallTypeData*)data)->has_return();
4758     if (has_return) {
4759       append(new ProfileReturnType(m , invoke_bci, callee, ret));
4760     }
4761   }
4762 }
4763 
4764 void GraphBuilder::profile_invocation(ciMethod* callee, ValueStack* state) {
4765   append(new ProfileInvoke(callee, state));
4766 }
--- EOF ---