1 /*
   2  * Copyright (c) 2005, 2023, 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_Compilation.hpp"
  27 #include "c1/c1_Defs.hpp"
  28 #include "c1/c1_FrameMap.hpp"
  29 #include "c1/c1_Instruction.hpp"
  30 #include "c1/c1_LIRAssembler.hpp"
  31 #include "c1/c1_LIRGenerator.hpp"
  32 #include "c1/c1_ValueStack.hpp"
  33 #include "ci/ciArrayKlass.hpp"
  34 #include "ci/ciFlatArrayKlass.hpp"
  35 #include "ci/ciInlineKlass.hpp"
  36 #include "ci/ciInstance.hpp"
  37 #include "ci/ciObjArray.hpp"
  38 #include "ci/ciUtilities.hpp"
  39 #include "compiler/compilerDefinitions.inline.hpp"
  40 #include "gc/shared/barrierSet.hpp"
  41 #include "gc/shared/c1/barrierSetC1.hpp"
  42 #include "oops/klass.inline.hpp"
  43 #include "oops/methodCounters.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/stubRoutines.hpp"
  46 #include "runtime/vm_version.hpp"
  47 #include "utilities/bitMap.inline.hpp"
  48 #include "utilities/macros.hpp"
  49 #include "utilities/powerOfTwo.hpp"
  50 
  51 #ifdef ASSERT
  52 #define __ gen()->lir(__FILE__, __LINE__)->
  53 #else
  54 #define __ gen()->lir()->
  55 #endif
  56 
  57 #ifndef PATCHED_ADDR
  58 #define PATCHED_ADDR  (max_jint)
  59 #endif
  60 
  61 void PhiResolverState::reset() {
  62   _virtual_operands.clear();
  63   _other_operands.clear();
  64   _vreg_table.clear();
  65 }
  66 
  67 
  68 //--------------------------------------------------------------
  69 // PhiResolver
  70 
  71 // Resolves cycles:
  72 //
  73 //  r1 := r2  becomes  temp := r1
  74 //  r2 := r1           r1 := r2
  75 //                     r2 := temp
  76 // and orders moves:
  77 //
  78 //  r2 := r3  becomes  r1 := r2
  79 //  r1 := r2           r2 := r3
  80 
  81 PhiResolver::PhiResolver(LIRGenerator* gen)
  82  : _gen(gen)
  83  , _state(gen->resolver_state())
  84  , _loop(nullptr)
  85  , _temp(LIR_OprFact::illegalOpr)
  86 {
  87   // reinitialize the shared state arrays
  88   _state.reset();
  89 }
  90 
  91 
  92 void PhiResolver::emit_move(LIR_Opr src, LIR_Opr dest) {
  93   assert(src->is_valid(), "");
  94   assert(dest->is_valid(), "");
  95   __ move(src, dest);
  96 }
  97 
  98 
  99 void PhiResolver::move_temp_to(LIR_Opr dest) {
 100   assert(_temp->is_valid(), "");
 101   emit_move(_temp, dest);
 102   NOT_PRODUCT(_temp = LIR_OprFact::illegalOpr);
 103 }
 104 
 105 
 106 void PhiResolver::move_to_temp(LIR_Opr src) {
 107   assert(_temp->is_illegal(), "");
 108   _temp = _gen->new_register(src->type());
 109   emit_move(src, _temp);
 110 }
 111 
 112 
 113 // Traverse assignment graph in depth first order and generate moves in post order
 114 // ie. two assignments: b := c, a := b start with node c:
 115 // Call graph: move(null, c) -> move(c, b) -> move(b, a)
 116 // Generates moves in this order: move b to a and move c to b
 117 // ie. cycle a := b, b := a start with node a
 118 // Call graph: move(null, a) -> move(a, b) -> move(b, a)
 119 // Generates moves in this order: move b to temp, move a to b, move temp to a
 120 void PhiResolver::move(ResolveNode* src, ResolveNode* dest) {
 121   if (!dest->visited()) {
 122     dest->set_visited();
 123     for (int i = dest->no_of_destinations()-1; i >= 0; i --) {
 124       move(dest, dest->destination_at(i));
 125     }
 126   } else if (!dest->start_node()) {
 127     // cylce in graph detected
 128     assert(_loop == nullptr, "only one loop valid!");
 129     _loop = dest;
 130     move_to_temp(src->operand());
 131     return;
 132   } // else dest is a start node
 133 
 134   if (!dest->assigned()) {
 135     if (_loop == dest) {
 136       move_temp_to(dest->operand());
 137       dest->set_assigned();
 138     } else if (src != nullptr) {
 139       emit_move(src->operand(), dest->operand());
 140       dest->set_assigned();
 141     }
 142   }
 143 }
 144 
 145 
 146 PhiResolver::~PhiResolver() {
 147   int i;
 148   // resolve any cycles in moves from and to virtual registers
 149   for (i = virtual_operands().length() - 1; i >= 0; i --) {
 150     ResolveNode* node = virtual_operands().at(i);
 151     if (!node->visited()) {
 152       _loop = nullptr;
 153       move(nullptr, node);
 154       node->set_start_node();
 155       assert(_temp->is_illegal(), "move_temp_to() call missing");
 156     }
 157   }
 158 
 159   // generate move for move from non virtual register to abitrary destination
 160   for (i = other_operands().length() - 1; i >= 0; i --) {
 161     ResolveNode* node = other_operands().at(i);
 162     for (int j = node->no_of_destinations() - 1; j >= 0; j --) {
 163       emit_move(node->operand(), node->destination_at(j)->operand());
 164     }
 165   }
 166 }
 167 
 168 
 169 ResolveNode* PhiResolver::create_node(LIR_Opr opr, bool source) {
 170   ResolveNode* node;
 171   if (opr->is_virtual()) {
 172     int vreg_num = opr->vreg_number();
 173     node = vreg_table().at_grow(vreg_num, nullptr);
 174     assert(node == nullptr || node->operand() == opr, "");
 175     if (node == nullptr) {
 176       node = new ResolveNode(opr);
 177       vreg_table().at_put(vreg_num, node);
 178     }
 179     // Make sure that all virtual operands show up in the list when
 180     // they are used as the source of a move.
 181     if (source && !virtual_operands().contains(node)) {
 182       virtual_operands().append(node);
 183     }
 184   } else {
 185     assert(source, "");
 186     node = new ResolveNode(opr);
 187     other_operands().append(node);
 188   }
 189   return node;
 190 }
 191 
 192 
 193 void PhiResolver::move(LIR_Opr src, LIR_Opr dest) {
 194   assert(dest->is_virtual(), "");
 195   // tty->print("move "); src->print(); tty->print(" to "); dest->print(); tty->cr();
 196   assert(src->is_valid(), "");
 197   assert(dest->is_valid(), "");
 198   ResolveNode* source = source_node(src);
 199   source->append(destination_node(dest));
 200 }
 201 
 202 
 203 //--------------------------------------------------------------
 204 // LIRItem
 205 
 206 void LIRItem::set_result(LIR_Opr opr) {
 207   assert(value()->operand()->is_illegal() || value()->operand()->is_constant(), "operand should never change");
 208   value()->set_operand(opr);
 209 
 210   if (opr->is_virtual()) {
 211     _gen->_instruction_for_operand.at_put_grow(opr->vreg_number(), value(), nullptr);
 212   }
 213 
 214   _result = opr;
 215 }
 216 
 217 void LIRItem::load_item() {
 218   assert(!_gen->in_conditional_code(), "LIRItem cannot be loaded in conditional code");
 219 
 220   if (result()->is_illegal()) {
 221     // update the items result
 222     _result = value()->operand();
 223   }
 224   if (!result()->is_register()) {
 225     LIR_Opr reg = _gen->new_register(value()->type());
 226     __ move(result(), reg);
 227     if (result()->is_constant()) {
 228       _result = reg;
 229     } else {
 230       set_result(reg);
 231     }
 232   }
 233 }
 234 
 235 
 236 void LIRItem::load_for_store(BasicType type) {
 237   if (_gen->can_store_as_constant(value(), type)) {
 238     _result = value()->operand();
 239     if (!_result->is_constant()) {
 240       _result = LIR_OprFact::value_type(value()->type());
 241     }
 242   } else if (type == T_BYTE || type == T_BOOLEAN) {
 243     load_byte_item();
 244   } else {
 245     load_item();
 246   }
 247 }
 248 
 249 void LIRItem::load_item_force(LIR_Opr reg) {
 250   LIR_Opr r = result();
 251   if (r != reg) {
 252 #if !defined(ARM) && !defined(E500V2)
 253     if (r->type() != reg->type()) {
 254       // moves between different types need an intervening spill slot
 255       r = _gen->force_to_spill(r, reg->type());
 256     }
 257 #endif
 258     __ move(r, reg);
 259     _result = reg;
 260   }
 261 }
 262 
 263 ciObject* LIRItem::get_jobject_constant() const {
 264   ObjectType* oc = type()->as_ObjectType();
 265   if (oc) {
 266     return oc->constant_value();
 267   }
 268   return nullptr;
 269 }
 270 
 271 
 272 jint LIRItem::get_jint_constant() const {
 273   assert(is_constant() && value() != nullptr, "");
 274   assert(type()->as_IntConstant() != nullptr, "type check");
 275   return type()->as_IntConstant()->value();
 276 }
 277 
 278 
 279 jint LIRItem::get_address_constant() const {
 280   assert(is_constant() && value() != nullptr, "");
 281   assert(type()->as_AddressConstant() != nullptr, "type check");
 282   return type()->as_AddressConstant()->value();
 283 }
 284 
 285 
 286 jfloat LIRItem::get_jfloat_constant() const {
 287   assert(is_constant() && value() != nullptr, "");
 288   assert(type()->as_FloatConstant() != nullptr, "type check");
 289   return type()->as_FloatConstant()->value();
 290 }
 291 
 292 
 293 jdouble LIRItem::get_jdouble_constant() const {
 294   assert(is_constant() && value() != nullptr, "");
 295   assert(type()->as_DoubleConstant() != nullptr, "type check");
 296   return type()->as_DoubleConstant()->value();
 297 }
 298 
 299 
 300 jlong LIRItem::get_jlong_constant() const {
 301   assert(is_constant() && value() != nullptr, "");
 302   assert(type()->as_LongConstant() != nullptr, "type check");
 303   return type()->as_LongConstant()->value();
 304 }
 305 
 306 
 307 
 308 //--------------------------------------------------------------
 309 
 310 
 311 void LIRGenerator::block_do_prolog(BlockBegin* block) {
 312 #ifndef PRODUCT
 313   if (PrintIRWithLIR) {
 314     block->print();
 315   }
 316 #endif
 317 
 318   // set up the list of LIR instructions
 319   assert(block->lir() == nullptr, "LIR list already computed for this block");
 320   _lir = new LIR_List(compilation(), block);
 321   block->set_lir(_lir);
 322 
 323   __ branch_destination(block->label());
 324 
 325   if (LIRTraceExecution &&
 326       Compilation::current()->hir()->start()->block_id() != block->block_id() &&
 327       !block->is_set(BlockBegin::exception_entry_flag)) {
 328     assert(block->lir()->instructions_list()->length() == 1, "should come right after br_dst");
 329     trace_block_entry(block);
 330   }
 331 }
 332 
 333 
 334 void LIRGenerator::block_do_epilog(BlockBegin* block) {
 335 #ifndef PRODUCT
 336   if (PrintIRWithLIR) {
 337     tty->cr();
 338   }
 339 #endif
 340 
 341   // LIR_Opr for unpinned constants shouldn't be referenced by other
 342   // blocks so clear them out after processing the block.
 343   for (int i = 0; i < _unpinned_constants.length(); i++) {
 344     _unpinned_constants.at(i)->clear_operand();
 345   }
 346   _unpinned_constants.trunc_to(0);
 347 
 348   // clear our any registers for other local constants
 349   _constants.trunc_to(0);
 350   _reg_for_constants.trunc_to(0);
 351 }
 352 
 353 
 354 void LIRGenerator::block_do(BlockBegin* block) {
 355   CHECK_BAILOUT();
 356 
 357   block_do_prolog(block);
 358   set_block(block);
 359 
 360   for (Instruction* instr = block; instr != nullptr; instr = instr->next()) {
 361     if (instr->is_pinned()) do_root(instr);
 362   }
 363 
 364   set_block(nullptr);
 365   block_do_epilog(block);
 366 }
 367 
 368 
 369 //-------------------------LIRGenerator-----------------------------
 370 
 371 // This is where the tree-walk starts; instr must be root;
 372 void LIRGenerator::do_root(Value instr) {
 373   CHECK_BAILOUT();
 374 
 375   InstructionMark im(compilation(), instr);
 376 
 377   assert(instr->is_pinned(), "use only with roots");
 378   assert(instr->subst() == instr, "shouldn't have missed substitution");
 379 
 380   instr->visit(this);
 381 
 382   assert(!instr->has_uses() || instr->operand()->is_valid() ||
 383          instr->as_Constant() != nullptr || bailed_out(), "invalid item set");
 384 }
 385 
 386 
 387 // This is called for each node in tree; the walk stops if a root is reached
 388 void LIRGenerator::walk(Value instr) {
 389   InstructionMark im(compilation(), instr);
 390   //stop walk when encounter a root
 391   if ((instr->is_pinned() && instr->as_Phi() == nullptr) || instr->operand()->is_valid()) {
 392     assert(instr->operand() != LIR_OprFact::illegalOpr || instr->as_Constant() != nullptr, "this root has not yet been visited");
 393   } else {
 394     assert(instr->subst() == instr, "shouldn't have missed substitution");
 395     instr->visit(this);
 396     // assert(instr->use_count() > 0 || instr->as_Phi() != nullptr, "leaf instruction must have a use");
 397   }
 398 }
 399 
 400 
 401 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
 402   assert(state != nullptr, "state must be defined");
 403 
 404 #ifndef PRODUCT
 405   state->verify();
 406 #endif
 407 
 408   ValueStack* s = state;
 409   for_each_state(s) {
 410     if (s->kind() == ValueStack::EmptyExceptionState ||
 411         s->kind() == ValueStack::CallerEmptyExceptionState)
 412     {
 413 #ifdef ASSERT
 414       int index;
 415       Value value;
 416       for_each_stack_value(s, index, value) {
 417         fatal("state must be empty");
 418       }
 419       for_each_local_value(s, index, value) {
 420         fatal("state must be empty");
 421       }
 422 #endif
 423       assert(s->locks_size() == 0 || s->locks_size() == 1, "state must be empty");
 424       continue;
 425     }
 426 
 427     int index;
 428     Value value;
 429     for_each_stack_value(s, index, value) {
 430       assert(value->subst() == value, "missed substitution");
 431       if (!value->is_pinned() && value->as_Constant() == nullptr && value->as_Local() == nullptr) {
 432         walk(value);
 433         assert(value->operand()->is_valid(), "must be evaluated now");
 434       }
 435     }
 436 
 437     int bci = s->bci();
 438     IRScope* scope = s->scope();
 439     ciMethod* method = scope->method();
 440 
 441     MethodLivenessResult liveness = method->liveness_at_bci(bci);
 442     if (bci == SynchronizationEntryBCI) {
 443       if (x->as_ExceptionObject() || x->as_Throw()) {
 444         // all locals are dead on exit from the synthetic unlocker
 445         liveness.clear();
 446       } else {
 447         assert(x->as_MonitorEnter() || x->as_ProfileInvoke(), "only other cases are MonitorEnter and ProfileInvoke");
 448       }
 449     }
 450     if (!liveness.is_valid()) {
 451       // Degenerate or breakpointed method.
 452       bailout("Degenerate or breakpointed method");
 453     } else {
 454       assert((int)liveness.size() == s->locals_size(), "error in use of liveness");
 455       for_each_local_value(s, index, value) {
 456         assert(value->subst() == value, "missed substitution");
 457         if (liveness.at(index) && !value->type()->is_illegal()) {
 458           if (!value->is_pinned() && value->as_Constant() == nullptr && value->as_Local() == nullptr) {
 459             walk(value);
 460             assert(value->operand()->is_valid(), "must be evaluated now");
 461           }
 462         } else {
 463           // null out this local so that linear scan can assume that all non-null values are live.
 464           s->invalidate_local(index);
 465         }
 466       }
 467     }
 468   }
 469 
 470   return new CodeEmitInfo(state, ignore_xhandler ? nullptr : x->exception_handlers(), x->check_flag(Instruction::DeoptimizeOnException));
 471 }
 472 
 473 
 474 CodeEmitInfo* LIRGenerator::state_for(Instruction* x) {
 475   return state_for(x, x->exception_state());
 476 }
 477 
 478 
 479 void LIRGenerator::klass2reg_with_patching(LIR_Opr r, ciMetadata* obj, CodeEmitInfo* info, bool need_resolve) {
 480   /* C2 relies on constant pool entries being resolved (ciTypeFlow), so if tiered compilation
 481    * is active and the class hasn't yet been resolved we need to emit a patch that resolves
 482    * the class. */
 483   if ((!CompilerConfig::is_c1_only_no_jvmci() && need_resolve) || !obj->is_loaded() || PatchALot) {
 484     assert(info != nullptr, "info must be set if class is not loaded");
 485     __ klass2reg_patch(nullptr, r, info);
 486   } else {
 487     // no patching needed
 488     __ metadata2reg(obj->constant_encoding(), r);
 489   }
 490 }
 491 
 492 
 493 void LIRGenerator::array_range_check(LIR_Opr array, LIR_Opr index,
 494                                     CodeEmitInfo* null_check_info, CodeEmitInfo* range_check_info) {
 495   CodeStub* stub = new RangeCheckStub(range_check_info, index, array);
 496   if (index->is_constant()) {
 497     cmp_mem_int(lir_cond_belowEqual, array, arrayOopDesc::length_offset_in_bytes(),
 498                 index->as_jint(), null_check_info);
 499     __ branch(lir_cond_belowEqual, stub); // forward branch
 500   } else {
 501     cmp_reg_mem(lir_cond_aboveEqual, index, array,
 502                 arrayOopDesc::length_offset_in_bytes(), T_INT, null_check_info);
 503     __ branch(lir_cond_aboveEqual, stub); // forward branch
 504   }
 505 }
 506 
 507 void LIRGenerator::arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp_op, CodeEmitInfo* info) {
 508   LIR_Opr result_op = result;
 509   LIR_Opr left_op   = left;
 510   LIR_Opr right_op  = right;
 511 
 512   if (two_operand_lir_form && left_op != result_op) {
 513     assert(right_op != result_op, "malformed");
 514     __ move(left_op, result_op);
 515     left_op = result_op;
 516   }
 517 
 518   switch(code) {
 519     case Bytecodes::_dadd:
 520     case Bytecodes::_fadd:
 521     case Bytecodes::_ladd:
 522     case Bytecodes::_iadd:  __ add(left_op, right_op, result_op); break;
 523     case Bytecodes::_fmul:
 524     case Bytecodes::_lmul:  __ mul(left_op, right_op, result_op); break;
 525 
 526     case Bytecodes::_dmul:  __ mul(left_op, right_op, result_op, tmp_op); break;
 527 
 528     case Bytecodes::_imul:
 529       {
 530         bool did_strength_reduce = false;
 531 
 532         if (right->is_constant()) {
 533           jint c = right->as_jint();
 534           if (c > 0 && is_power_of_2(c)) {
 535             // do not need tmp here
 536             __ shift_left(left_op, exact_log2(c), result_op);
 537             did_strength_reduce = true;
 538           } else {
 539             did_strength_reduce = strength_reduce_multiply(left_op, c, result_op, tmp_op);
 540           }
 541         }
 542         // we couldn't strength reduce so just emit the multiply
 543         if (!did_strength_reduce) {
 544           __ mul(left_op, right_op, result_op);
 545         }
 546       }
 547       break;
 548 
 549     case Bytecodes::_dsub:
 550     case Bytecodes::_fsub:
 551     case Bytecodes::_lsub:
 552     case Bytecodes::_isub: __ sub(left_op, right_op, result_op); break;
 553 
 554     case Bytecodes::_fdiv: __ div (left_op, right_op, result_op); break;
 555     // ldiv and lrem are implemented with a direct runtime call
 556 
 557     case Bytecodes::_ddiv: __ div(left_op, right_op, result_op, tmp_op); break;
 558 
 559     case Bytecodes::_drem:
 560     case Bytecodes::_frem: __ rem (left_op, right_op, result_op); break;
 561 
 562     default: ShouldNotReachHere();
 563   }
 564 }
 565 
 566 
 567 void LIRGenerator::arithmetic_op_int(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 568   arithmetic_op(code, result, left, right, tmp);
 569 }
 570 
 571 
 572 void LIRGenerator::arithmetic_op_long(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info) {
 573   arithmetic_op(code, result, left, right, LIR_OprFact::illegalOpr, info);
 574 }
 575 
 576 
 577 void LIRGenerator::arithmetic_op_fpu(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 578   arithmetic_op(code, result, left, right, tmp);
 579 }
 580 
 581 
 582 void LIRGenerator::shift_op(Bytecodes::Code code, LIR_Opr result_op, LIR_Opr value, LIR_Opr count, LIR_Opr tmp) {
 583 
 584   if (two_operand_lir_form && value != result_op
 585       // Only 32bit right shifts require two operand form on S390.
 586       S390_ONLY(&& (code == Bytecodes::_ishr || code == Bytecodes::_iushr))) {
 587     assert(count != result_op, "malformed");
 588     __ move(value, result_op);
 589     value = result_op;
 590   }
 591 
 592   assert(count->is_constant() || count->is_register(), "must be");
 593   switch(code) {
 594   case Bytecodes::_ishl:
 595   case Bytecodes::_lshl: __ shift_left(value, count, result_op, tmp); break;
 596   case Bytecodes::_ishr:
 597   case Bytecodes::_lshr: __ shift_right(value, count, result_op, tmp); break;
 598   case Bytecodes::_iushr:
 599   case Bytecodes::_lushr: __ unsigned_shift_right(value, count, result_op, tmp); break;
 600   default: ShouldNotReachHere();
 601   }
 602 }
 603 
 604 
 605 void LIRGenerator::logic_op (Bytecodes::Code code, LIR_Opr result_op, LIR_Opr left_op, LIR_Opr right_op) {
 606   if (two_operand_lir_form && left_op != result_op) {
 607     assert(right_op != result_op, "malformed");
 608     __ move(left_op, result_op);
 609     left_op = result_op;
 610   }
 611 
 612   switch(code) {
 613     case Bytecodes::_iand:
 614     case Bytecodes::_land:  __ logical_and(left_op, right_op, result_op); break;
 615 
 616     case Bytecodes::_ior:
 617     case Bytecodes::_lor:   __ logical_or(left_op, right_op, result_op);  break;
 618 
 619     case Bytecodes::_ixor:
 620     case Bytecodes::_lxor:  __ logical_xor(left_op, right_op, result_op); break;
 621 
 622     default: ShouldNotReachHere();
 623   }
 624 }
 625 
 626 
 627 void LIRGenerator::monitor_enter(LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no,
 628                                  CodeEmitInfo* info_for_exception, CodeEmitInfo* info, CodeStub* throw_ie_stub) {
 629   if (!GenerateSynchronizationCode) return;
 630   // for slow path, use debug info for state after successful locking
 631   CodeStub* slow_path = new MonitorEnterStub(object, lock, info, throw_ie_stub, scratch);
 632   __ load_stack_address_monitor(monitor_no, lock);
 633   // for handling NullPointerException, use debug info representing just the lock stack before this monitorenter
 634   __ lock_object(hdr, object, lock, scratch, slow_path, info_for_exception, throw_ie_stub);
 635 }
 636 
 637 
 638 void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) {
 639   if (!GenerateSynchronizationCode) return;
 640   // setup registers
 641   LIR_Opr hdr = lock;
 642   lock = new_hdr;
 643   CodeStub* slow_path = new MonitorExitStub(lock, LockingMode != LM_MONITOR, monitor_no);
 644   __ load_stack_address_monitor(monitor_no, lock);
 645   __ unlock_object(hdr, object, lock, scratch, slow_path);
 646 }
 647 
 648 #ifndef PRODUCT
 649 void LIRGenerator::print_if_not_loaded(const NewInstance* new_instance) {
 650   if (PrintNotLoaded && !new_instance->klass()->is_loaded()) {
 651     tty->print_cr("   ###class not loaded at new bci %d", new_instance->printable_bci());
 652   } else if (PrintNotLoaded && (!CompilerConfig::is_c1_only_no_jvmci() && new_instance->is_unresolved())) {
 653     tty->print_cr("   ###class not resolved at new bci %d", new_instance->printable_bci());
 654   }
 655 }
 656 #endif
 657 
 658 void LIRGenerator::new_instance(LIR_Opr dst, ciInstanceKlass* klass, bool is_unresolved, bool allow_inline, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info) {
 659   if (allow_inline) {
 660     assert(!is_unresolved && klass->is_loaded(), "inline type klass should be resolved");
 661     __ metadata2reg(klass->constant_encoding(), klass_reg);
 662   } else {
 663     klass2reg_with_patching(klass_reg, klass, info, is_unresolved);
 664   }
 665   // If klass is not loaded we do not know if the klass has finalizers or is an unexpected inline klass
 666   if (UseFastNewInstance && klass->is_loaded() && (allow_inline || !klass->is_inlinetype())
 667       && !Klass::layout_helper_needs_slow_path(klass->layout_helper())) {
 668 
 669     Runtime1::StubID stub_id = klass->is_initialized() ? Runtime1::fast_new_instance_id : Runtime1::fast_new_instance_init_check_id;
 670 
 671     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, stub_id);
 672 
 673     assert(klass->is_loaded(), "must be loaded");
 674     // allocate space for instance
 675     assert(klass->size_helper() > 0, "illegal instance size");
 676     const int instance_size = align_object_size(klass->size_helper());
 677     __ allocate_object(dst, scratch1, scratch2, scratch3, scratch4,
 678                        oopDesc::header_size(), instance_size, klass_reg, !klass->is_initialized(), slow_path);
 679   } else {
 680     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, Runtime1::new_instance_id);
 681     __ jump(slow_path);
 682     __ branch_destination(slow_path->continuation());
 683   }
 684 }
 685 
 686 
 687 static bool is_constant_zero(Instruction* inst) {
 688   IntConstant* c = inst->type()->as_IntConstant();
 689   if (c) {
 690     return (c->value() == 0);
 691   }
 692   return false;
 693 }
 694 
 695 
 696 static bool positive_constant(Instruction* inst) {
 697   IntConstant* c = inst->type()->as_IntConstant();
 698   if (c) {
 699     return (c->value() >= 0);
 700   }
 701   return false;
 702 }
 703 
 704 
 705 static ciArrayKlass* as_array_klass(ciType* type) {
 706   if (type != nullptr && type->is_array_klass() && type->is_loaded()) {
 707     return (ciArrayKlass*)type;
 708   } else {
 709     return nullptr;
 710   }
 711 }
 712 
 713 static ciType* phi_declared_type(Phi* phi) {
 714   ciType* t = phi->operand_at(0)->declared_type();
 715   if (t == nullptr) {
 716     return nullptr;
 717   }
 718   for(int i = 1; i < phi->operand_count(); i++) {
 719     if (t != phi->operand_at(i)->declared_type()) {
 720       return nullptr;
 721     }
 722   }
 723   return t;
 724 }
 725 
 726 void LIRGenerator::arraycopy_helper(Intrinsic* x, int* flagsp, ciArrayKlass** expected_typep) {
 727   Instruction* src     = x->argument_at(0);
 728   Instruction* src_pos = x->argument_at(1);
 729   Instruction* dst     = x->argument_at(2);
 730   Instruction* dst_pos = x->argument_at(3);
 731   Instruction* length  = x->argument_at(4);
 732 
 733   // first try to identify the likely type of the arrays involved
 734   ciArrayKlass* expected_type = nullptr;
 735   bool is_exact = false, src_objarray = false, dst_objarray = false;
 736   {
 737     ciArrayKlass* src_exact_type    = as_array_klass(src->exact_type());
 738     ciArrayKlass* src_declared_type = as_array_klass(src->declared_type());
 739     Phi* phi;
 740     if (src_declared_type == nullptr && (phi = src->as_Phi()) != nullptr) {
 741       src_declared_type = as_array_klass(phi_declared_type(phi));
 742     }
 743     ciArrayKlass* dst_exact_type    = as_array_klass(dst->exact_type());
 744     ciArrayKlass* dst_declared_type = as_array_klass(dst->declared_type());
 745     if (dst_declared_type == nullptr && (phi = dst->as_Phi()) != nullptr) {
 746       dst_declared_type = as_array_klass(phi_declared_type(phi));
 747     }
 748 
 749     if (src_exact_type != nullptr && src_exact_type == dst_exact_type) {
 750       // the types exactly match so the type is fully known
 751       is_exact = true;
 752       expected_type = src_exact_type;
 753     } else if (dst_exact_type != nullptr && dst_exact_type->is_obj_array_klass()) {
 754       ciArrayKlass* dst_type = (ciArrayKlass*) dst_exact_type;
 755       ciArrayKlass* src_type = nullptr;
 756       if (src_exact_type != nullptr && src_exact_type->is_obj_array_klass()) {
 757         src_type = (ciArrayKlass*) src_exact_type;
 758       } else if (src_declared_type != nullptr && src_declared_type->is_obj_array_klass()) {
 759         src_type = (ciArrayKlass*) src_declared_type;
 760       }
 761       if (src_type != nullptr) {
 762         if (src_type->element_type()->is_subtype_of(dst_type->element_type())) {
 763           is_exact = true;
 764           expected_type = dst_type;
 765         }
 766       }
 767     }
 768     // at least pass along a good guess
 769     if (expected_type == nullptr) expected_type = dst_exact_type;
 770     if (expected_type == nullptr) expected_type = src_declared_type;
 771     if (expected_type == nullptr) expected_type = dst_declared_type;
 772 
 773     src_objarray = (src_exact_type && src_exact_type->is_obj_array_klass()) || (src_declared_type && src_declared_type->is_obj_array_klass());
 774     dst_objarray = (dst_exact_type && dst_exact_type->is_obj_array_klass()) || (dst_declared_type && dst_declared_type->is_obj_array_klass());
 775   }
 776 
 777   // if a probable array type has been identified, figure out if any
 778   // of the required checks for a fast case can be elided.
 779   int flags = LIR_OpArrayCopy::all_flags;
 780 
 781   if (!src->is_loaded_flat_array() && !dst->is_loaded_flat_array()) {
 782     flags &= ~LIR_OpArrayCopy::always_slow_path;
 783   }
 784   if (!src->maybe_flat_array()) {
 785     flags &= ~LIR_OpArrayCopy::src_inlinetype_check;
 786   }
 787   if (!dst->maybe_flat_array() && !dst->maybe_null_free_array()) {
 788     flags &= ~LIR_OpArrayCopy::dst_inlinetype_check;
 789   }
 790 
 791   if (!src_objarray)
 792     flags &= ~LIR_OpArrayCopy::src_objarray;
 793   if (!dst_objarray)
 794     flags &= ~LIR_OpArrayCopy::dst_objarray;
 795 
 796   if (!x->arg_needs_null_check(0))
 797     flags &= ~LIR_OpArrayCopy::src_null_check;
 798   if (!x->arg_needs_null_check(2))
 799     flags &= ~LIR_OpArrayCopy::dst_null_check;
 800 
 801 
 802   if (expected_type != nullptr) {
 803     Value length_limit = nullptr;
 804 
 805     IfOp* ifop = length->as_IfOp();
 806     if (ifop != nullptr) {
 807       // look for expressions like min(v, a.length) which ends up as
 808       //   x > y ? y : x  or  x >= y ? y : x
 809       if ((ifop->cond() == If::gtr || ifop->cond() == If::geq) &&
 810           ifop->x() == ifop->fval() &&
 811           ifop->y() == ifop->tval()) {
 812         length_limit = ifop->y();
 813       }
 814     }
 815 
 816     // try to skip null checks and range checks
 817     NewArray* src_array = src->as_NewArray();
 818     if (src_array != nullptr) {
 819       flags &= ~LIR_OpArrayCopy::src_null_check;
 820       if (length_limit != nullptr &&
 821           src_array->length() == length_limit &&
 822           is_constant_zero(src_pos)) {
 823         flags &= ~LIR_OpArrayCopy::src_range_check;
 824       }
 825     }
 826 
 827     NewArray* dst_array = dst->as_NewArray();
 828     if (dst_array != nullptr) {
 829       flags &= ~LIR_OpArrayCopy::dst_null_check;
 830       if (length_limit != nullptr &&
 831           dst_array->length() == length_limit &&
 832           is_constant_zero(dst_pos)) {
 833         flags &= ~LIR_OpArrayCopy::dst_range_check;
 834       }
 835     }
 836 
 837     // check from incoming constant values
 838     if (positive_constant(src_pos))
 839       flags &= ~LIR_OpArrayCopy::src_pos_positive_check;
 840     if (positive_constant(dst_pos))
 841       flags &= ~LIR_OpArrayCopy::dst_pos_positive_check;
 842     if (positive_constant(length))
 843       flags &= ~LIR_OpArrayCopy::length_positive_check;
 844 
 845     // see if the range check can be elided, which might also imply
 846     // that src or dst is non-null.
 847     ArrayLength* al = length->as_ArrayLength();
 848     if (al != nullptr) {
 849       if (al->array() == src) {
 850         // it's the length of the source array
 851         flags &= ~LIR_OpArrayCopy::length_positive_check;
 852         flags &= ~LIR_OpArrayCopy::src_null_check;
 853         if (is_constant_zero(src_pos))
 854           flags &= ~LIR_OpArrayCopy::src_range_check;
 855       }
 856       if (al->array() == dst) {
 857         // it's the length of the destination array
 858         flags &= ~LIR_OpArrayCopy::length_positive_check;
 859         flags &= ~LIR_OpArrayCopy::dst_null_check;
 860         if (is_constant_zero(dst_pos))
 861           flags &= ~LIR_OpArrayCopy::dst_range_check;
 862       }
 863     }
 864     if (is_exact) {
 865       flags &= ~LIR_OpArrayCopy::type_check;
 866     }
 867   }
 868 
 869   IntConstant* src_int = src_pos->type()->as_IntConstant();
 870   IntConstant* dst_int = dst_pos->type()->as_IntConstant();
 871   if (src_int && dst_int) {
 872     int s_offs = src_int->value();
 873     int d_offs = dst_int->value();
 874     if (src_int->value() >= dst_int->value()) {
 875       flags &= ~LIR_OpArrayCopy::overlapping;
 876     }
 877     if (expected_type != nullptr) {
 878       BasicType t = expected_type->element_type()->basic_type();
 879       int element_size = type2aelembytes(t);
 880       if (((arrayOopDesc::base_offset_in_bytes(t) + (uint)s_offs * element_size) % HeapWordSize == 0) &&
 881           ((arrayOopDesc::base_offset_in_bytes(t) + (uint)d_offs * element_size) % HeapWordSize == 0)) {
 882         flags &= ~LIR_OpArrayCopy::unaligned;
 883       }
 884     }
 885   } else if (src_pos == dst_pos || is_constant_zero(dst_pos)) {
 886     // src and dest positions are the same, or dst is zero so assume
 887     // nonoverlapping copy.
 888     flags &= ~LIR_OpArrayCopy::overlapping;
 889   }
 890 
 891   if (src == dst) {
 892     // moving within a single array so no type checks are needed
 893     if (flags & LIR_OpArrayCopy::type_check) {
 894       flags &= ~LIR_OpArrayCopy::type_check;
 895     }
 896   }
 897   *flagsp = flags;
 898   *expected_typep = (ciArrayKlass*)expected_type;
 899 }
 900 
 901 
 902 LIR_Opr LIRGenerator::round_item(LIR_Opr opr) {
 903   assert(opr->is_register(), "why spill if item is not register?");
 904 
 905   if (strict_fp_requires_explicit_rounding) {
 906 #ifdef IA32
 907     if (UseSSE < 1 && opr->is_single_fpu()) {
 908       LIR_Opr result = new_register(T_FLOAT);
 909       set_vreg_flag(result, must_start_in_memory);
 910       assert(opr->is_register(), "only a register can be spilled");
 911       assert(opr->value_type()->is_float(), "rounding only for floats available");
 912       __ roundfp(opr, LIR_OprFact::illegalOpr, result);
 913       return result;
 914     }
 915 #else
 916     Unimplemented();
 917 #endif // IA32
 918   }
 919   return opr;
 920 }
 921 
 922 
 923 LIR_Opr LIRGenerator::force_to_spill(LIR_Opr value, BasicType t) {
 924   assert(type2size[t] == type2size[value->type()],
 925          "size mismatch: t=%s, value->type()=%s", type2name(t), type2name(value->type()));
 926   if (!value->is_register()) {
 927     // force into a register
 928     LIR_Opr r = new_register(value->type());
 929     __ move(value, r);
 930     value = r;
 931   }
 932 
 933   // create a spill location
 934   LIR_Opr tmp = new_register(t);
 935   set_vreg_flag(tmp, LIRGenerator::must_start_in_memory);
 936 
 937   // move from register to spill
 938   __ move(value, tmp);
 939   return tmp;
 940 }
 941 
 942 void LIRGenerator::profile_branch(If* if_instr, If::Condition cond) {
 943   if (if_instr->should_profile()) {
 944     ciMethod* method = if_instr->profiled_method();
 945     assert(method != nullptr, "method should be set if branch is profiled");
 946     ciMethodData* md = method->method_data_or_null();
 947     assert(md != nullptr, "Sanity");
 948     ciProfileData* data = md->bci_to_data(if_instr->profiled_bci());
 949     assert(data != nullptr, "must have profiling data");
 950     assert(data->is_BranchData(), "need BranchData for two-way branches");
 951     int taken_count_offset     = md->byte_offset_of_slot(data, BranchData::taken_offset());
 952     int not_taken_count_offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
 953     if (if_instr->is_swapped()) {
 954       int t = taken_count_offset;
 955       taken_count_offset = not_taken_count_offset;
 956       not_taken_count_offset = t;
 957     }
 958 
 959     LIR_Opr md_reg = new_register(T_METADATA);
 960     __ metadata2reg(md->constant_encoding(), md_reg);
 961 
 962     LIR_Opr data_offset_reg = new_pointer_register();
 963     __ cmove(lir_cond(cond),
 964              LIR_OprFact::intptrConst(taken_count_offset),
 965              LIR_OprFact::intptrConst(not_taken_count_offset),
 966              data_offset_reg, as_BasicType(if_instr->x()->type()));
 967 
 968     // MDO cells are intptr_t, so the data_reg width is arch-dependent.
 969     LIR_Opr data_reg = new_pointer_register();
 970     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
 971     __ move(data_addr, data_reg);
 972     // Use leal instead of add to avoid destroying condition codes on x86
 973     LIR_Address* fake_incr_value = new LIR_Address(data_reg, DataLayout::counter_increment, T_INT);
 974     __ leal(LIR_OprFact::address(fake_incr_value), data_reg);
 975     __ move(data_reg, data_addr);
 976   }
 977 }
 978 
 979 // Phi technique:
 980 // This is about passing live values from one basic block to the other.
 981 // In code generated with Java it is rather rare that more than one
 982 // value is on the stack from one basic block to the other.
 983 // We optimize our technique for efficient passing of one value
 984 // (of type long, int, double..) but it can be extended.
 985 // When entering or leaving a basic block, all registers and all spill
 986 // slots are release and empty. We use the released registers
 987 // and spill slots to pass the live values from one block
 988 // to the other. The topmost value, i.e., the value on TOS of expression
 989 // stack is passed in registers. All other values are stored in spilling
 990 // area. Every Phi has an index which designates its spill slot
 991 // At exit of a basic block, we fill the register(s) and spill slots.
 992 // At entry of a basic block, the block_prolog sets up the content of phi nodes
 993 // and locks necessary registers and spilling slots.
 994 
 995 
 996 // move current value to referenced phi function
 997 void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_val) {
 998   Phi* phi = sux_val->as_Phi();
 999   // cur_val can be null without phi being null in conjunction with inlining
1000   if (phi != nullptr && cur_val != nullptr && cur_val != phi && !phi->is_illegal()) {
1001     if (phi->is_local()) {
1002       for (int i = 0; i < phi->operand_count(); i++) {
1003         Value op = phi->operand_at(i);
1004         if (op != nullptr && op->type()->is_illegal()) {
1005           bailout("illegal phi operand");
1006         }
1007       }
1008     }
1009     Phi* cur_phi = cur_val->as_Phi();
1010     if (cur_phi != nullptr && cur_phi->is_illegal()) {
1011       // Phi and local would need to get invalidated
1012       // (which is unexpected for Linear Scan).
1013       // But this case is very rare so we simply bail out.
1014       bailout("propagation of illegal phi");
1015       return;
1016     }
1017     LIR_Opr operand = cur_val->operand();
1018     if (operand->is_illegal()) {
1019       assert(cur_val->as_Constant() != nullptr || cur_val->as_Local() != nullptr,
1020              "these can be produced lazily");
1021       operand = operand_for_instruction(cur_val);
1022     }
1023     resolver->move(operand, operand_for_instruction(phi));
1024   }
1025 }
1026 
1027 
1028 // Moves all stack values into their PHI position
1029 void LIRGenerator::move_to_phi(ValueStack* cur_state) {
1030   BlockBegin* bb = block();
1031   if (bb->number_of_sux() == 1) {
1032     BlockBegin* sux = bb->sux_at(0);
1033     assert(sux->number_of_preds() > 0, "invalid CFG");
1034 
1035     // a block with only one predecessor never has phi functions
1036     if (sux->number_of_preds() > 1) {
1037       PhiResolver resolver(this);
1038 
1039       ValueStack* sux_state = sux->state();
1040       Value sux_value;
1041       int index;
1042 
1043       assert(cur_state->scope() == sux_state->scope(), "not matching");
1044       assert(cur_state->locals_size() == sux_state->locals_size(), "not matching");
1045       assert(cur_state->stack_size() == sux_state->stack_size(), "not matching");
1046 
1047       for_each_stack_value(sux_state, index, sux_value) {
1048         move_to_phi(&resolver, cur_state->stack_at(index), sux_value);
1049       }
1050 
1051       for_each_local_value(sux_state, index, sux_value) {
1052         move_to_phi(&resolver, cur_state->local_at(index), sux_value);
1053       }
1054 
1055       assert(cur_state->caller_state() == sux_state->caller_state(), "caller states must be equal");
1056     }
1057   }
1058 }
1059 
1060 
1061 LIR_Opr LIRGenerator::new_register(BasicType type) {
1062   int vreg_num = _virtual_register_number;
1063   // Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out
1064   // a few extra registers before we really run out which helps to avoid to trip over assertions.
1065   if (vreg_num + 20 >= LIR_Opr::vreg_max) {
1066     bailout("out of virtual registers in LIR generator");
1067     if (vreg_num + 2 >= LIR_Opr::vreg_max) {
1068       // Wrap it around and continue until bailout really happens to avoid hitting assertions.
1069       _virtual_register_number = LIR_Opr::vreg_base;
1070       vreg_num = LIR_Opr::vreg_base;
1071     }
1072   }
1073   _virtual_register_number += 1;
1074   LIR_Opr vreg = LIR_OprFact::virtual_register(vreg_num, type);
1075   assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");
1076   return vreg;
1077 }
1078 
1079 
1080 // Try to lock using register in hint
1081 LIR_Opr LIRGenerator::rlock(Value instr) {
1082   return new_register(instr->type());
1083 }
1084 
1085 
1086 // does an rlock and sets result
1087 LIR_Opr LIRGenerator::rlock_result(Value x) {
1088   LIR_Opr reg = rlock(x);
1089   set_result(x, reg);
1090   return reg;
1091 }
1092 
1093 
1094 // does an rlock and sets result
1095 LIR_Opr LIRGenerator::rlock_result(Value x, BasicType type) {
1096   LIR_Opr reg;
1097   switch (type) {
1098   case T_BYTE:
1099   case T_BOOLEAN:
1100     reg = rlock_byte(type);
1101     break;
1102   default:
1103     reg = rlock(x);
1104     break;
1105   }
1106 
1107   set_result(x, reg);
1108   return reg;
1109 }
1110 
1111 
1112 //---------------------------------------------------------------------
1113 ciObject* LIRGenerator::get_jobject_constant(Value value) {
1114   ObjectType* oc = value->type()->as_ObjectType();
1115   if (oc) {
1116     return oc->constant_value();
1117   }
1118   return nullptr;
1119 }
1120 
1121 
1122 void LIRGenerator::do_ExceptionObject(ExceptionObject* x) {
1123   assert(block()->is_set(BlockBegin::exception_entry_flag), "ExceptionObject only allowed in exception handler block");
1124   assert(block()->next() == x, "ExceptionObject must be first instruction of block");
1125 
1126   // no moves are created for phi functions at the begin of exception
1127   // handlers, so assign operands manually here
1128   for_each_phi_fun(block(), phi,
1129                    if (!phi->is_illegal()) { operand_for_instruction(phi); });
1130 
1131   LIR_Opr thread_reg = getThreadPointer();
1132   __ move_wide(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT),
1133                exceptionOopOpr());
1134   __ move_wide(LIR_OprFact::oopConst(nullptr),
1135                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT));
1136   __ move_wide(LIR_OprFact::oopConst(nullptr),
1137                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_pc_offset()), T_OBJECT));
1138 
1139   LIR_Opr result = new_register(T_OBJECT);
1140   __ move(exceptionOopOpr(), result);
1141   set_result(x, result);
1142 }
1143 
1144 
1145 //----------------------------------------------------------------------
1146 //----------------------------------------------------------------------
1147 //----------------------------------------------------------------------
1148 //----------------------------------------------------------------------
1149 //                        visitor functions
1150 //----------------------------------------------------------------------
1151 //----------------------------------------------------------------------
1152 //----------------------------------------------------------------------
1153 //----------------------------------------------------------------------
1154 
1155 void LIRGenerator::do_Phi(Phi* x) {
1156   // phi functions are never visited directly
1157   ShouldNotReachHere();
1158 }
1159 
1160 
1161 // Code for a constant is generated lazily unless the constant is frequently used and can't be inlined.
1162 void LIRGenerator::do_Constant(Constant* x) {
1163   if (x->state_before() != nullptr) {
1164     // Any constant with a ValueStack requires patching so emit the patch here
1165     LIR_Opr reg = rlock_result(x);
1166     CodeEmitInfo* info = state_for(x, x->state_before());
1167     __ oop2reg_patch(nullptr, reg, info);
1168   } else if (x->use_count() > 1 && !can_inline_as_constant(x)) {
1169     if (!x->is_pinned()) {
1170       // unpinned constants are handled specially so that they can be
1171       // put into registers when they are used multiple times within a
1172       // block.  After the block completes their operand will be
1173       // cleared so that other blocks can't refer to that register.
1174       set_result(x, load_constant(x));
1175     } else {
1176       LIR_Opr res = x->operand();
1177       if (!res->is_valid()) {
1178         res = LIR_OprFact::value_type(x->type());
1179       }
1180       if (res->is_constant()) {
1181         LIR_Opr reg = rlock_result(x);
1182         __ move(res, reg);
1183       } else {
1184         set_result(x, res);
1185       }
1186     }
1187   } else {
1188     set_result(x, LIR_OprFact::value_type(x->type()));
1189   }
1190 }
1191 
1192 
1193 void LIRGenerator::do_Local(Local* x) {
1194   // operand_for_instruction has the side effect of setting the result
1195   // so there's no need to do it here.
1196   operand_for_instruction(x);
1197 }
1198 
1199 
1200 void LIRGenerator::do_Return(Return* x) {
1201   if (compilation()->env()->dtrace_method_probes()) {
1202     BasicTypeList signature;
1203     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
1204     signature.append(T_METADATA); // Method*
1205     LIR_OprList* args = new LIR_OprList();
1206     args->append(getThreadPointer());
1207     LIR_Opr meth = new_register(T_METADATA);
1208     __ metadata2reg(method()->constant_encoding(), meth);
1209     args->append(meth);
1210     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), voidType, nullptr);
1211   }
1212 
1213   if (x->type()->is_void()) {
1214     __ return_op(LIR_OprFact::illegalOpr);
1215   } else {
1216     LIR_Opr reg = result_register_for(x->type(), /*callee=*/true);
1217     LIRItem result(x->result(), this);
1218 
1219     result.load_item_force(reg);
1220     __ return_op(result.result());
1221   }
1222   set_no_result(x);
1223 }
1224 
1225 // Example: ref.get()
1226 // Combination of LoadField and g1 pre-write barrier
1227 void LIRGenerator::do_Reference_get(Intrinsic* x) {
1228 
1229   const int referent_offset = java_lang_ref_Reference::referent_offset();
1230 
1231   assert(x->number_of_arguments() == 1, "wrong type");
1232 
1233   LIRItem reference(x->argument_at(0), this);
1234   reference.load_item();
1235 
1236   // need to perform the null check on the reference object
1237   CodeEmitInfo* info = nullptr;
1238   if (x->needs_null_check()) {
1239     info = state_for(x);
1240   }
1241 
1242   LIR_Opr result = rlock_result(x, T_OBJECT);
1243   access_load_at(IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT,
1244                  reference, LIR_OprFact::intConst(referent_offset), result,
1245                  nullptr, info);
1246 }
1247 
1248 // Example: clazz.isInstance(object)
1249 void LIRGenerator::do_isInstance(Intrinsic* x) {
1250   assert(x->number_of_arguments() == 2, "wrong type");
1251 
1252   // TODO could try to substitute this node with an equivalent InstanceOf
1253   // if clazz is known to be a constant Class. This will pick up newly found
1254   // constants after HIR construction. I'll leave this to a future change.
1255 
1256   // as a first cut, make a simple leaf call to runtime to stay platform independent.
1257   // could follow the aastore example in a future change.
1258 
1259   LIRItem clazz(x->argument_at(0), this);
1260   LIRItem object(x->argument_at(1), this);
1261   clazz.load_item();
1262   object.load_item();
1263   LIR_Opr result = rlock_result(x);
1264 
1265   // need to perform null check on clazz
1266   if (x->needs_null_check()) {
1267     CodeEmitInfo* info = state_for(x);
1268     __ null_check(clazz.result(), info);
1269   }
1270 
1271   LIR_Opr call_result = call_runtime(clazz.value(), object.value(),
1272                                      CAST_FROM_FN_PTR(address, Runtime1::is_instance_of),
1273                                      x->type(),
1274                                      nullptr); // null CodeEmitInfo results in a leaf call
1275   __ move(call_result, result);
1276 }
1277 
1278 void LIRGenerator::load_klass(LIR_Opr obj, LIR_Opr klass, CodeEmitInfo* null_check_info) {
1279   __ load_klass(obj, klass, null_check_info);
1280 }
1281 
1282 // Example: object.getClass ()
1283 void LIRGenerator::do_getClass(Intrinsic* x) {
1284   assert(x->number_of_arguments() == 1, "wrong type");
1285 
1286   LIRItem rcvr(x->argument_at(0), this);
1287   rcvr.load_item();
1288   LIR_Opr temp = new_register(T_ADDRESS);
1289   LIR_Opr result = rlock_result(x);
1290 
1291   // need to perform the null check on the rcvr
1292   CodeEmitInfo* info = nullptr;
1293   if (x->needs_null_check()) {
1294     info = state_for(x);
1295   }
1296 
1297   LIR_Opr klass = new_register(T_METADATA);
1298   load_klass(rcvr.result(), klass, info);
1299   __ move_wide(new LIR_Address(klass, in_bytes(Klass::java_mirror_offset()), T_ADDRESS), temp);
1300   // mirror = ((OopHandle)mirror)->resolve();
1301   access_load(IN_NATIVE, T_OBJECT,
1302               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), result);
1303 }
1304 
1305 // java.lang.Class::isPrimitive()
1306 void LIRGenerator::do_isPrimitive(Intrinsic* x) {
1307   assert(x->number_of_arguments() == 1, "wrong type");
1308 
1309   LIRItem rcvr(x->argument_at(0), this);
1310   rcvr.load_item();
1311   LIR_Opr temp = new_register(T_METADATA);
1312   LIR_Opr result = rlock_result(x);
1313 
1314   CodeEmitInfo* info = nullptr;
1315   if (x->needs_null_check()) {
1316     info = state_for(x);
1317   }
1318 
1319   __ move(new LIR_Address(rcvr.result(), java_lang_Class::klass_offset(), T_ADDRESS), temp, info);
1320   __ cmp(lir_cond_notEqual, temp, LIR_OprFact::metadataConst(0));
1321   __ cmove(lir_cond_notEqual, LIR_OprFact::intConst(0), LIR_OprFact::intConst(1), result, T_BOOLEAN);
1322 }
1323 
1324 // Example: Foo.class.getModifiers()
1325 void LIRGenerator::do_getModifiers(Intrinsic* x) {
1326   assert(x->number_of_arguments() == 1, "wrong type");
1327 
1328   LIRItem receiver(x->argument_at(0), this);
1329   receiver.load_item();
1330   LIR_Opr result = rlock_result(x);
1331 
1332   CodeEmitInfo* info = nullptr;
1333   if (x->needs_null_check()) {
1334     info = state_for(x);
1335   }
1336 
1337   // While reading off the universal constant mirror is less efficient than doing
1338   // another branch and returning the constant answer, this branchless code runs into
1339   // much less risk of confusion for C1 register allocator. The choice of the universe
1340   // object here is correct as long as it returns the same modifiers we would expect
1341   // from the primitive class itself. See spec for Class.getModifiers that provides
1342   // the typed array klasses with similar modifiers as their component types.
1343 
1344   // Valhalla update: the code is now a bit convuloted because arrays and primitive
1345   // classes don't have the same modifiers set anymore, but we cannot introduce
1346   // branches in LIR generation (JDK-8211231). So, the first part of the code remains
1347   // identical, using the byteArrayKlass object to avoid a NPE when accessing the
1348   // modifiers. But then the code also prepares the correct modifiers set for
1349   // primitive classes, and there's a second conditional move to put the right
1350   // value into result.
1351 
1352 
1353   Klass* univ_klass_obj = Universe::byteArrayKlassObj();
1354   assert(univ_klass_obj->modifier_flags() == (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC
1355                                               | (Arguments::enable_preview() ? JVM_ACC_IDENTITY : 0)), "Sanity");
1356   LIR_Opr prim_klass = LIR_OprFact::metadataConst(univ_klass_obj);
1357 
1358   LIR_Opr recv_klass = new_register(T_METADATA);
1359   __ move(new LIR_Address(receiver.result(), java_lang_Class::klass_offset(), T_ADDRESS), recv_klass, info);
1360 
1361   // Check if this is a Java mirror of primitive type, and select the appropriate klass.
1362   LIR_Opr klass = new_register(T_METADATA);
1363   __ cmp(lir_cond_equal, recv_klass, LIR_OprFact::metadataConst(0));
1364   __ cmove(lir_cond_equal, prim_klass, recv_klass, klass, T_ADDRESS);
1365   LIR_Opr klass_modifiers = new_register(T_INT);
1366   __ move(new LIR_Address(klass, in_bytes(Klass::modifier_flags_offset()), T_INT), klass_modifiers);
1367 
1368   LIR_Opr prim_modifiers = load_immediate(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC, T_INT);
1369 
1370   __ cmp(lir_cond_equal, recv_klass, LIR_OprFact::metadataConst(0));
1371   __ cmove(lir_cond_equal, prim_modifiers, klass_modifiers, result, T_INT);
1372 
1373 }
1374 
1375 void LIRGenerator::do_getObjectSize(Intrinsic* x) {
1376   assert(x->number_of_arguments() == 3, "wrong type");
1377   LIR_Opr result_reg = rlock_result(x);
1378 
1379   LIRItem value(x->argument_at(2), this);
1380   value.load_item();
1381 
1382   LIR_Opr klass = new_register(T_METADATA);
1383   load_klass(value.result(), klass, nullptr);
1384   LIR_Opr layout = new_register(T_INT);
1385   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
1386 
1387   LabelObj* L_done = new LabelObj();
1388   LabelObj* L_array = new LabelObj();
1389 
1390   __ cmp(lir_cond_lessEqual, layout, 0);
1391   __ branch(lir_cond_lessEqual, L_array->label());
1392 
1393   // Instance case: the layout helper gives us instance size almost directly,
1394   // but we need to mask out the _lh_instance_slow_path_bit.
1395 
1396   assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
1397 
1398   LIR_Opr mask = load_immediate(~(jint) right_n_bits(LogBytesPerLong), T_INT);
1399   __ logical_and(layout, mask, layout);
1400   __ convert(Bytecodes::_i2l, layout, result_reg);
1401 
1402   __ branch(lir_cond_always, L_done->label());
1403 
1404   // Array case: size is round(header + element_size*arraylength).
1405   // Since arraylength is different for every array instance, we have to
1406   // compute the whole thing at runtime.
1407 
1408   __ branch_destination(L_array->label());
1409 
1410   int round_mask = MinObjAlignmentInBytes - 1;
1411 
1412   // Figure out header sizes first.
1413   LIR_Opr hss = load_immediate(Klass::_lh_header_size_shift, T_INT);
1414   LIR_Opr hsm = load_immediate(Klass::_lh_header_size_mask, T_INT);
1415 
1416   LIR_Opr header_size = new_register(T_INT);
1417   __ move(layout, header_size);
1418   LIR_Opr tmp = new_register(T_INT);
1419   __ unsigned_shift_right(header_size, hss, header_size, tmp);
1420   __ logical_and(header_size, hsm, header_size);
1421   __ add(header_size, LIR_OprFact::intConst(round_mask), header_size);
1422 
1423   // Figure out the array length in bytes
1424   assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
1425   LIR_Opr l2esm = load_immediate(Klass::_lh_log2_element_size_mask, T_INT);
1426   __ logical_and(layout, l2esm, layout);
1427 
1428   LIR_Opr length_int = new_register(T_INT);
1429   __ move(new LIR_Address(value.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), length_int);
1430 
1431 #ifdef _LP64
1432   LIR_Opr length = new_register(T_LONG);
1433   __ convert(Bytecodes::_i2l, length_int, length);
1434 #endif
1435 
1436   // Shift-left awkwardness. Normally it is just:
1437   //   __ shift_left(length, layout, length);
1438   // But C1 cannot perform shift_left with non-constant count, so we end up
1439   // doing the per-bit loop dance here. x86_32 also does not know how to shift
1440   // longs, so we have to act on ints.
1441   LabelObj* L_shift_loop = new LabelObj();
1442   LabelObj* L_shift_exit = new LabelObj();
1443 
1444   __ branch_destination(L_shift_loop->label());
1445   __ cmp(lir_cond_equal, layout, 0);
1446   __ branch(lir_cond_equal, L_shift_exit->label());
1447 
1448 #ifdef _LP64
1449   __ shift_left(length, 1, length);
1450 #else
1451   __ shift_left(length_int, 1, length_int);
1452 #endif
1453 
1454   __ sub(layout, LIR_OprFact::intConst(1), layout);
1455 
1456   __ branch(lir_cond_always, L_shift_loop->label());
1457   __ branch_destination(L_shift_exit->label());
1458 
1459   // Mix all up, round, and push to the result.
1460 #ifdef _LP64
1461   LIR_Opr header_size_long = new_register(T_LONG);
1462   __ convert(Bytecodes::_i2l, header_size, header_size_long);
1463   __ add(length, header_size_long, length);
1464   if (round_mask != 0) {
1465     LIR_Opr round_mask_opr = load_immediate(~(jlong)round_mask, T_LONG);
1466     __ logical_and(length, round_mask_opr, length);
1467   }
1468   __ move(length, result_reg);
1469 #else
1470   __ add(length_int, header_size, length_int);
1471   if (round_mask != 0) {
1472     LIR_Opr round_mask_opr = load_immediate(~round_mask, T_INT);
1473     __ logical_and(length_int, round_mask_opr, length_int);
1474   }
1475   __ convert(Bytecodes::_i2l, length_int, result_reg);
1476 #endif
1477 
1478   __ branch_destination(L_done->label());
1479 }
1480 
1481 void LIRGenerator::do_scopedValueCache(Intrinsic* x) {
1482   do_JavaThreadField(x, JavaThread::scopedValueCache_offset());
1483 }
1484 
1485 // Example: Thread.currentCarrierThread()
1486 void LIRGenerator::do_currentCarrierThread(Intrinsic* x) {
1487   do_JavaThreadField(x, JavaThread::threadObj_offset());
1488 }
1489 
1490 void LIRGenerator::do_vthread(Intrinsic* x) {
1491   do_JavaThreadField(x, JavaThread::vthread_offset());
1492 }
1493 
1494 void LIRGenerator::do_JavaThreadField(Intrinsic* x, ByteSize offset) {
1495   assert(x->number_of_arguments() == 0, "wrong type");
1496   LIR_Opr temp = new_register(T_ADDRESS);
1497   LIR_Opr reg = rlock_result(x);
1498   __ move(new LIR_Address(getThreadPointer(), in_bytes(offset), T_ADDRESS), temp);
1499   access_load(IN_NATIVE, T_OBJECT,
1500               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), reg);
1501 }
1502 
1503 void LIRGenerator::do_RegisterFinalizer(Intrinsic* x) {
1504   assert(x->number_of_arguments() == 1, "wrong type");
1505   LIRItem receiver(x->argument_at(0), this);
1506 
1507   receiver.load_item();
1508   BasicTypeList signature;
1509   signature.append(T_OBJECT); // receiver
1510   LIR_OprList* args = new LIR_OprList();
1511   args->append(receiver.result());
1512   CodeEmitInfo* info = state_for(x, x->state());
1513   call_runtime(&signature, args,
1514                CAST_FROM_FN_PTR(address, Runtime1::entry_for(Runtime1::register_finalizer_id)),
1515                voidType, info);
1516 
1517   set_no_result(x);
1518 }
1519 
1520 
1521 //------------------------local access--------------------------------------
1522 
1523 LIR_Opr LIRGenerator::operand_for_instruction(Instruction* x) {
1524   if (x->operand()->is_illegal()) {
1525     Constant* c = x->as_Constant();
1526     if (c != nullptr) {
1527       x->set_operand(LIR_OprFact::value_type(c->type()));
1528     } else {
1529       assert(x->as_Phi() || x->as_Local() != nullptr, "only for Phi and Local");
1530       // allocate a virtual register for this local or phi
1531       x->set_operand(rlock(x));
1532       _instruction_for_operand.at_put_grow(x->operand()->vreg_number(), x, nullptr);
1533     }
1534   }
1535   return x->operand();
1536 }
1537 
1538 
1539 Instruction* LIRGenerator::instruction_for_opr(LIR_Opr opr) {
1540   if (opr->is_virtual()) {
1541     return instruction_for_vreg(opr->vreg_number());
1542   }
1543   return nullptr;
1544 }
1545 
1546 
1547 Instruction* LIRGenerator::instruction_for_vreg(int reg_num) {
1548   if (reg_num < _instruction_for_operand.length()) {
1549     return _instruction_for_operand.at(reg_num);
1550   }
1551   return nullptr;
1552 }
1553 
1554 
1555 void LIRGenerator::set_vreg_flag(int vreg_num, VregFlag f) {
1556   if (_vreg_flags.size_in_bits() == 0) {
1557     BitMap2D temp(100, num_vreg_flags);
1558     _vreg_flags = temp;
1559   }
1560   _vreg_flags.at_put_grow(vreg_num, f, true);
1561 }
1562 
1563 bool LIRGenerator::is_vreg_flag_set(int vreg_num, VregFlag f) {
1564   if (!_vreg_flags.is_valid_index(vreg_num, f)) {
1565     return false;
1566   }
1567   return _vreg_flags.at(vreg_num, f);
1568 }
1569 
1570 
1571 // Block local constant handling.  This code is useful for keeping
1572 // unpinned constants and constants which aren't exposed in the IR in
1573 // registers.  Unpinned Constant instructions have their operands
1574 // cleared when the block is finished so that other blocks can't end
1575 // up referring to their registers.
1576 
1577 LIR_Opr LIRGenerator::load_constant(Constant* x) {
1578   assert(!x->is_pinned(), "only for unpinned constants");
1579   _unpinned_constants.append(x);
1580   return load_constant(LIR_OprFact::value_type(x->type())->as_constant_ptr());
1581 }
1582 
1583 
1584 LIR_Opr LIRGenerator::load_constant(LIR_Const* c) {
1585   BasicType t = c->type();
1586   for (int i = 0; i < _constants.length(); i++) {
1587     LIR_Const* other = _constants.at(i);
1588     if (t == other->type()) {
1589       switch (t) {
1590       case T_INT:
1591       case T_FLOAT:
1592         if (c->as_jint_bits() != other->as_jint_bits()) continue;
1593         break;
1594       case T_LONG:
1595       case T_DOUBLE:
1596         if (c->as_jint_hi_bits() != other->as_jint_hi_bits()) continue;
1597         if (c->as_jint_lo_bits() != other->as_jint_lo_bits()) continue;
1598         break;
1599       case T_OBJECT:
1600         if (c->as_jobject() != other->as_jobject()) continue;
1601         break;
1602       default:
1603         break;
1604       }
1605       return _reg_for_constants.at(i);
1606     }
1607   }
1608 
1609   LIR_Opr result = new_register(t);
1610   __ move((LIR_Opr)c, result);
1611   if (!in_conditional_code()) {
1612     _constants.append(c);
1613     _reg_for_constants.append(result);
1614   }
1615   return result;
1616 }
1617 
1618 void LIRGenerator::set_in_conditional_code(bool v) {
1619   assert(v != _in_conditional_code, "must change state");
1620   _in_conditional_code = v;
1621 }
1622 
1623 
1624 //------------------------field access--------------------------------------
1625 
1626 void LIRGenerator::do_CompareAndSwap(Intrinsic* x, ValueType* type) {
1627   assert(x->number_of_arguments() == 4, "wrong type");
1628   LIRItem obj   (x->argument_at(0), this);  // object
1629   LIRItem offset(x->argument_at(1), this);  // offset of field
1630   LIRItem cmp   (x->argument_at(2), this);  // value to compare with field
1631   LIRItem val   (x->argument_at(3), this);  // replace field with val if matches cmp
1632   assert(obj.type()->tag() == objectTag, "invalid type");
1633   assert(cmp.type()->tag() == type->tag(), "invalid type");
1634   assert(val.type()->tag() == type->tag(), "invalid type");
1635 
1636   LIR_Opr result = access_atomic_cmpxchg_at(IN_HEAP, as_BasicType(type),
1637                                             obj, offset, cmp, val);
1638   set_result(x, result);
1639 }
1640 
1641 // Comment copied form templateTable_i486.cpp
1642 // ----------------------------------------------------------------------------
1643 // Volatile variables demand their effects be made known to all CPU's in
1644 // order.  Store buffers on most chips allow reads & writes to reorder; the
1645 // JMM's ReadAfterWrite.java test fails in -Xint mode without some kind of
1646 // memory barrier (i.e., it's not sufficient that the interpreter does not
1647 // reorder volatile references, the hardware also must not reorder them).
1648 //
1649 // According to the new Java Memory Model (JMM):
1650 // (1) All volatiles are serialized wrt to each other.
1651 // ALSO reads & writes act as acquire & release, so:
1652 // (2) A read cannot let unrelated NON-volatile memory refs that happen after
1653 // the read float up to before the read.  It's OK for non-volatile memory refs
1654 // that happen before the volatile read to float down below it.
1655 // (3) Similar a volatile write cannot let unrelated NON-volatile memory refs
1656 // that happen BEFORE the write float down to after the write.  It's OK for
1657 // non-volatile memory refs that happen after the volatile write to float up
1658 // before it.
1659 //
1660 // We only put in barriers around volatile refs (they are expensive), not
1661 // _between_ memory refs (that would require us to track the flavor of the
1662 // previous memory refs).  Requirements (2) and (3) require some barriers
1663 // before volatile stores and after volatile loads.  These nearly cover
1664 // requirement (1) but miss the volatile-store-volatile-load case.  This final
1665 // case is placed after volatile-stores although it could just as well go
1666 // before volatile-loads.
1667 
1668 
1669 void LIRGenerator::do_StoreField(StoreField* x) {
1670   bool needs_patching = x->needs_patching();
1671   bool is_volatile = x->field()->is_volatile();
1672   BasicType field_type = x->field_type();
1673 
1674   CodeEmitInfo* info = nullptr;
1675   if (needs_patching) {
1676     assert(x->explicit_null_check() == nullptr, "can't fold null check into patching field access");
1677     info = state_for(x, x->state_before());
1678   } else if (x->needs_null_check()) {
1679     NullCheck* nc = x->explicit_null_check();
1680     if (nc == nullptr) {
1681       info = state_for(x);
1682     } else {
1683       info = state_for(nc);
1684     }
1685   }
1686 
1687   LIRItem object(x->obj(), this);
1688   LIRItem value(x->value(),  this);
1689 
1690   object.load_item();
1691 
1692   if (is_volatile || needs_patching) {
1693     // load item if field is volatile (fewer special cases for volatiles)
1694     // load item if field not initialized
1695     // load item if field not constant
1696     // because of code patching we cannot inline constants
1697     if (field_type == T_BYTE || field_type == T_BOOLEAN) {
1698       value.load_byte_item();
1699     } else  {
1700       value.load_item();
1701     }
1702   } else {
1703     value.load_for_store(field_type);
1704   }
1705 
1706   set_no_result(x);
1707 
1708 #ifndef PRODUCT
1709   if (PrintNotLoaded && needs_patching) {
1710     tty->print_cr("   ###class not loaded at store_%s bci %d",
1711                   x->is_static() ?  "static" : "field", x->printable_bci());
1712   }
1713 #endif
1714 
1715   if (x->needs_null_check() &&
1716       (needs_patching ||
1717        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1718     // Emit an explicit null check because the offset is too large.
1719     // If the class is not loaded and the object is null, we need to deoptimize to throw a
1720     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
1721     __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
1722   }
1723 
1724   DecoratorSet decorators = IN_HEAP;
1725   if (is_volatile) {
1726     decorators |= MO_SEQ_CST;
1727   }
1728   if (needs_patching) {
1729     decorators |= C1_NEEDS_PATCHING;
1730   }
1731 
1732   access_store_at(decorators, field_type, object, LIR_OprFact::intConst(x->offset()),
1733                   value.result(), info != nullptr ? new CodeEmitInfo(info) : nullptr, info);
1734 }
1735 
1736 // FIXME -- I can't find any other way to pass an address to access_load_at().
1737 class TempResolvedAddress: public Instruction {
1738  public:
1739   TempResolvedAddress(ValueType* type, LIR_Opr addr) : Instruction(type) {
1740     set_operand(addr);
1741   }
1742   virtual void input_values_do(ValueVisitor*) {}
1743   virtual void visit(InstructionVisitor* v)   {}
1744   virtual const char* name() const  { return "TempResolvedAddress"; }
1745 };
1746 
1747 LIR_Opr LIRGenerator::get_and_load_element_address(LIRItem& array, LIRItem& index) {
1748   ciType* array_type = array.value()->declared_type();
1749   ciFlatArrayKlass* flat_array_klass = array_type->as_flat_array_klass();
1750   assert(flat_array_klass->is_loaded(), "must be");
1751 
1752   int array_header_size = flat_array_klass->array_header_in_bytes();
1753   int shift = flat_array_klass->log2_element_size();
1754 
1755 #ifndef _LP64
1756   LIR_Opr index_op = new_register(T_INT);
1757   // FIXME -- on 32-bit, the shift below can overflow, so we need to check that
1758   // the top (shift+1) bits of index_op must be zero, or
1759   // else throw ArrayIndexOutOfBoundsException
1760   if (index.result()->is_constant()) {
1761     jint const_index = index.result()->as_jint();
1762     __ move(LIR_OprFact::intConst(const_index << shift), index_op);
1763   } else {
1764     __ shift_left(index_op, shift, index.result());
1765   }
1766 #else
1767   LIR_Opr index_op = new_register(T_LONG);
1768   if (index.result()->is_constant()) {
1769     jint const_index = index.result()->as_jint();
1770     __ move(LIR_OprFact::longConst(const_index << shift), index_op);
1771   } else {
1772     __ convert(Bytecodes::_i2l, index.result(), index_op);
1773     // Need to shift manually, as LIR_Address can scale only up to 3.
1774     __ shift_left(index_op, shift, index_op);
1775   }
1776 #endif
1777 
1778   LIR_Opr elm_op = new_pointer_register();
1779   LIR_Address* elm_address = generate_address(array.result(), index_op, 0, array_header_size, T_ADDRESS);
1780   __ leal(LIR_OprFact::address(elm_address), elm_op);
1781   return elm_op;
1782 }
1783 
1784 void LIRGenerator::access_sub_element(LIRItem& array, LIRItem& index, LIR_Opr& result, ciField* field, int sub_offset) {
1785   assert(field != nullptr, "Need a subelement type specified");
1786 
1787   // Find the starting address of the source (inside the array)
1788   LIR_Opr elm_op = get_and_load_element_address(array, index);
1789 
1790   BasicType subelt_type = field->type()->basic_type();
1791   TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(subelt_type), elm_op);
1792   LIRItem elm_item(elm_resolved_addr, this);
1793 
1794   DecoratorSet decorators = IN_HEAP;
1795   access_load_at(decorators, subelt_type,
1796                      elm_item, LIR_OprFact::intConst(sub_offset), result,
1797                      nullptr, nullptr);
1798 
1799   if (field->is_null_free()) {
1800     assert(field->type()->is_loaded(), "Must be");
1801     assert(field->type()->is_inlinetype(), "Must be if loaded");
1802     assert(field->type()->as_inline_klass()->is_initialized(), "Must be");
1803     LabelObj* L_end = new LabelObj();
1804     __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(nullptr));
1805     __ branch(lir_cond_notEqual, L_end->label());
1806     set_in_conditional_code(true);
1807     Constant* default_value = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1808     if (default_value->is_pinned()) {
1809       __ move(LIR_OprFact::value_type(default_value->type()), result);
1810     } else {
1811       __ move(load_constant(default_value), result);
1812     }
1813     __ branch_destination(L_end->label());
1814     set_in_conditional_code(false);
1815   }
1816 }
1817 
1818 void LIRGenerator::access_flat_array(bool is_load, LIRItem& array, LIRItem& index, LIRItem& obj_item,
1819                                           ciField* field, int sub_offset) {
1820   assert(sub_offset == 0 || field != nullptr, "Sanity check");
1821 
1822   // Find the starting address of the source (inside the array)
1823   LIR_Opr elm_op = get_and_load_element_address(array, index);
1824 
1825   ciInlineKlass* elem_klass = nullptr;
1826   if (field != nullptr) {
1827     elem_klass = field->type()->as_inline_klass();
1828   } else {
1829     elem_klass = array.value()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
1830   }
1831   for (int i = 0; i < elem_klass->nof_nonstatic_fields(); i++) {
1832     ciField* inner_field = elem_klass->nonstatic_field_at(i);
1833     assert(!inner_field->is_flat(), "flat fields must have been expanded");
1834     int obj_offset = inner_field->offset_in_bytes();
1835     int elm_offset = obj_offset - elem_klass->first_field_offset() + sub_offset; // object header is not stored in array.
1836     BasicType field_type = inner_field->type()->basic_type();
1837 
1838     // Types which are smaller than int are still passed in an int register.
1839     BasicType reg_type = field_type;
1840     switch (reg_type) {
1841     case T_BYTE:
1842     case T_BOOLEAN:
1843     case T_SHORT:
1844     case T_CHAR:
1845       reg_type = T_INT;
1846       break;
1847     default:
1848       break;
1849     }
1850 
1851     LIR_Opr temp = new_register(reg_type);
1852     TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(field_type), elm_op);
1853     LIRItem elm_item(elm_resolved_addr, this);
1854 
1855     DecoratorSet decorators = IN_HEAP;
1856     if (is_load) {
1857       access_load_at(decorators, field_type,
1858                      elm_item, LIR_OprFact::intConst(elm_offset), temp,
1859                      nullptr, nullptr);
1860       access_store_at(decorators, field_type,
1861                       obj_item, LIR_OprFact::intConst(obj_offset), temp,
1862                       nullptr, nullptr);
1863     } else {
1864       access_load_at(decorators, field_type,
1865                      obj_item, LIR_OprFact::intConst(obj_offset), temp,
1866                      nullptr, nullptr);
1867       access_store_at(decorators, field_type,
1868                       elm_item, LIR_OprFact::intConst(elm_offset), temp,
1869                       nullptr, nullptr);
1870     }
1871   }
1872 }
1873 
1874 void LIRGenerator::check_flat_array(LIR_Opr array, LIR_Opr value, CodeStub* slow_path) {
1875   LIR_Opr tmp = new_register(T_METADATA);
1876   __ check_flat_array(array, value, tmp, slow_path);
1877 }
1878 
1879 void LIRGenerator::check_null_free_array(LIRItem& array, LIRItem& value, CodeEmitInfo* info) {
1880   LabelObj* L_end = new LabelObj();
1881   LIR_Opr tmp = new_register(T_METADATA);
1882   __ check_null_free_array(array.result(), tmp);
1883   __ branch(lir_cond_equal, L_end->label());
1884   __ null_check(value.result(), info);
1885   __ branch_destination(L_end->label());
1886 }
1887 
1888 bool LIRGenerator::needs_flat_array_store_check(StoreIndexed* x) {
1889   if (x->elt_type() == T_OBJECT && x->array()->maybe_flat_array()) {
1890     ciType* type = x->value()->declared_type();
1891     if (type != nullptr && type->is_klass()) {
1892       ciKlass* klass = type->as_klass();
1893       if (!klass->can_be_inline_klass() || (klass->is_inlinetype() && !klass->as_inline_klass()->flat_in_array())) {
1894         // This is known to be a non-flat object. If the array is a flat array,
1895         // it will be caught by the code generated by array_store_check().
1896         return false;
1897       }
1898     }
1899     // We're not 100% sure, so let's do the flat_array_store_check.
1900     return true;
1901   }
1902   return false;
1903 }
1904 
1905 bool LIRGenerator::needs_null_free_array_store_check(StoreIndexed* x) {
1906   return x->elt_type() == T_OBJECT && x->array()->maybe_null_free_array();
1907 }
1908 
1909 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
1910   assert(x->is_pinned(),"");
1911   assert(x->elt_type() != T_ARRAY, "never used");
1912   bool is_loaded_flat_array = x->array()->is_loaded_flat_array();
1913   bool needs_range_check = x->compute_needs_range_check();
1914   bool use_length = x->length() != nullptr;
1915   bool obj_store = is_reference_type(x->elt_type());
1916   bool needs_store_check = obj_store && !(is_loaded_flat_array && x->is_exact_flat_array_store()) &&
1917                                         (x->value()->as_Constant() == nullptr ||
1918                                          !get_jobject_constant(x->value())->is_null_object());
1919 
1920   LIRItem array(x->array(), this);
1921   LIRItem index(x->index(), this);
1922   LIRItem value(x->value(), this);
1923   LIRItem length(this);
1924 
1925   array.load_item();
1926   index.load_nonconstant();
1927 
1928   if (use_length && needs_range_check) {
1929     length.set_instruction(x->length());
1930     length.load_item();
1931   }
1932 
1933   if (needs_store_check || x->check_boolean()
1934       || is_loaded_flat_array || needs_flat_array_store_check(x) || needs_null_free_array_store_check(x)) {
1935     value.load_item();
1936   } else {
1937     value.load_for_store(x->elt_type());
1938   }
1939 
1940   set_no_result(x);
1941 
1942   // the CodeEmitInfo must be duplicated for each different
1943   // LIR-instruction because spilling can occur anywhere between two
1944   // instructions and so the debug information must be different
1945   CodeEmitInfo* range_check_info = state_for(x);
1946   CodeEmitInfo* null_check_info = nullptr;
1947   if (x->needs_null_check()) {
1948     null_check_info = new CodeEmitInfo(range_check_info);
1949   }
1950 
1951   if (needs_range_check) {
1952     if (use_length) {
1953       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1954       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
1955     } else {
1956       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1957       // range_check also does the null check
1958       null_check_info = nullptr;
1959     }
1960   }
1961 
1962   if (x->should_profile()) {
1963     if (x->array()->is_loaded_flat_array()) {
1964       // No need to profile a store to a flat array of known type. This can happen if
1965       // the type only became known after optimizations (for example, after the PhiSimplifier).
1966       x->set_should_profile(false);
1967     } else {
1968       int bci = x->profiled_bci();
1969       ciMethodData* md = x->profiled_method()->method_data();
1970       assert(md != nullptr, "Sanity");
1971       ciProfileData* data = md->bci_to_data(bci);
1972       assert(data != nullptr && data->is_ArrayStoreData(), "incorrect profiling entry");
1973       ciArrayStoreData* store_data = (ciArrayStoreData*)data;
1974       profile_array_type(x, md, store_data);
1975       assert(store_data->is_ArrayStoreData(), "incorrect profiling entry");
1976       if (x->array()->maybe_null_free_array()) {
1977         profile_null_free_array(array, md, store_data);
1978       }
1979     }
1980   }
1981 
1982   if (GenerateArrayStoreCheck && needs_store_check) {
1983     CodeEmitInfo* store_check_info = new CodeEmitInfo(range_check_info);
1984     array_store_check(value.result(), array.result(), store_check_info, x->profiled_method(), x->profiled_bci());
1985   }
1986 
1987   if (is_loaded_flat_array) {
1988     if (!x->value()->is_null_free()) {
1989       __ null_check(value.result(), new CodeEmitInfo(range_check_info));
1990     }
1991     // If array element is an empty inline type, no need to copy anything
1992     if (!x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
1993       access_flat_array(false, array, index, value);
1994     }
1995   } else {
1996     StoreFlattenedArrayStub* slow_path = nullptr;
1997 
1998     if (needs_flat_array_store_check(x)) {
1999       // Check if we indeed have a flat array
2000       index.load_item();
2001       slow_path = new StoreFlattenedArrayStub(array.result(), index.result(), value.result(), state_for(x, x->state_before()));
2002       check_flat_array(array.result(), value.result(), slow_path);
2003       set_in_conditional_code(true);
2004     } else if (needs_null_free_array_store_check(x)) {
2005       CodeEmitInfo* info = new CodeEmitInfo(range_check_info);
2006       check_null_free_array(array, value, info);
2007     }
2008 
2009     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
2010     if (x->check_boolean()) {
2011       decorators |= C1_MASK_BOOLEAN;
2012     }
2013 
2014     access_store_at(decorators, x->elt_type(), array, index.result(), value.result(),
2015                     nullptr, null_check_info);
2016     if (slow_path != nullptr) {
2017       __ branch_destination(slow_path->continuation());
2018       set_in_conditional_code(false);
2019     }
2020   }
2021 }
2022 
2023 void LIRGenerator::access_load_at(DecoratorSet decorators, BasicType type,
2024                                   LIRItem& base, LIR_Opr offset, LIR_Opr result,
2025                                   CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info) {
2026   decorators |= ACCESS_READ;
2027   LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info);
2028   if (access.is_raw()) {
2029     _barrier_set->BarrierSetC1::load_at(access, result);
2030   } else {
2031     _barrier_set->load_at(access, result);
2032   }
2033 }
2034 
2035 void LIRGenerator::access_load(DecoratorSet decorators, BasicType type,
2036                                LIR_Opr addr, LIR_Opr result) {
2037   decorators |= ACCESS_READ;
2038   LIRAccess access(this, decorators, LIR_OprFact::illegalOpr, LIR_OprFact::illegalOpr, type);
2039   access.set_resolved_addr(addr);
2040   if (access.is_raw()) {
2041     _barrier_set->BarrierSetC1::load(access, result);
2042   } else {
2043     _barrier_set->load(access, result);
2044   }
2045 }
2046 
2047 void LIRGenerator::access_store_at(DecoratorSet decorators, BasicType type,
2048                                    LIRItem& base, LIR_Opr offset, LIR_Opr value,
2049                                    CodeEmitInfo* patch_info, CodeEmitInfo* store_emit_info) {
2050   decorators |= ACCESS_WRITE;
2051   LIRAccess access(this, decorators, base, offset, type, patch_info, store_emit_info);
2052   if (access.is_raw()) {
2053     _barrier_set->BarrierSetC1::store_at(access, value);
2054   } else {
2055     _barrier_set->store_at(access, value);
2056   }
2057 }
2058 
2059 LIR_Opr LIRGenerator::access_atomic_cmpxchg_at(DecoratorSet decorators, BasicType type,
2060                                                LIRItem& base, LIRItem& offset, LIRItem& cmp_value, LIRItem& new_value) {
2061   decorators |= ACCESS_READ;
2062   decorators |= ACCESS_WRITE;
2063   // Atomic operations are SEQ_CST by default
2064   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2065   LIRAccess access(this, decorators, base, offset, type);
2066   if (access.is_raw()) {
2067     return _barrier_set->BarrierSetC1::atomic_cmpxchg_at(access, cmp_value, new_value);
2068   } else {
2069     return _barrier_set->atomic_cmpxchg_at(access, cmp_value, new_value);
2070   }
2071 }
2072 
2073 LIR_Opr LIRGenerator::access_atomic_xchg_at(DecoratorSet decorators, BasicType type,
2074                                             LIRItem& base, LIRItem& offset, LIRItem& value) {
2075   decorators |= ACCESS_READ;
2076   decorators |= ACCESS_WRITE;
2077   // Atomic operations are SEQ_CST by default
2078   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2079   LIRAccess access(this, decorators, base, offset, type);
2080   if (access.is_raw()) {
2081     return _barrier_set->BarrierSetC1::atomic_xchg_at(access, value);
2082   } else {
2083     return _barrier_set->atomic_xchg_at(access, value);
2084   }
2085 }
2086 
2087 LIR_Opr LIRGenerator::access_atomic_add_at(DecoratorSet decorators, BasicType type,
2088                                            LIRItem& base, LIRItem& offset, LIRItem& value) {
2089   decorators |= ACCESS_READ;
2090   decorators |= ACCESS_WRITE;
2091   // Atomic operations are SEQ_CST by default
2092   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2093   LIRAccess access(this, decorators, base, offset, type);
2094   if (access.is_raw()) {
2095     return _barrier_set->BarrierSetC1::atomic_add_at(access, value);
2096   } else {
2097     return _barrier_set->atomic_add_at(access, value);
2098   }
2099 }
2100 
2101 void LIRGenerator::do_LoadField(LoadField* x) {
2102   bool needs_patching = x->needs_patching();
2103   bool is_volatile = x->field()->is_volatile();
2104   BasicType field_type = x->field_type();
2105 
2106   CodeEmitInfo* info = nullptr;
2107   if (needs_patching) {
2108     assert(x->explicit_null_check() == nullptr, "can't fold null check into patching field access");
2109     info = state_for(x, x->state_before());
2110   } else if (x->needs_null_check()) {
2111     NullCheck* nc = x->explicit_null_check();
2112     if (nc == nullptr) {
2113       info = state_for(x);
2114     } else {
2115       info = state_for(nc);
2116     }
2117   }
2118 
2119   LIRItem object(x->obj(), this);
2120 
2121   object.load_item();
2122 
2123 #ifndef PRODUCT
2124   if (PrintNotLoaded && needs_patching) {
2125     tty->print_cr("   ###class not loaded at load_%s bci %d",
2126                   x->is_static() ?  "static" : "field", x->printable_bci());
2127   }
2128 #endif
2129 
2130   bool stress_deopt = StressLoopInvariantCodeMotion && info && info->deoptimize_on_exception();
2131   if (x->needs_null_check() &&
2132       (needs_patching ||
2133        MacroAssembler::needs_explicit_null_check(x->offset()) ||
2134        stress_deopt)) {
2135     LIR_Opr obj = object.result();
2136     if (stress_deopt) {
2137       obj = new_register(T_OBJECT);
2138       __ move(LIR_OprFact::oopConst(nullptr), obj);
2139     }
2140     // Emit an explicit null check because the offset is too large.
2141     // If the class is not loaded and the object is null, we need to deoptimize to throw a
2142     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
2143     __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
2144   }
2145 
2146   DecoratorSet decorators = IN_HEAP;
2147   if (is_volatile) {
2148     decorators |= MO_SEQ_CST;
2149   }
2150   if (needs_patching) {
2151     decorators |= C1_NEEDS_PATCHING;
2152   }
2153 
2154   LIR_Opr result = rlock_result(x, field_type);
2155   access_load_at(decorators, field_type,
2156                  object, LIR_OprFact::intConst(x->offset()), result,
2157                  info ? new CodeEmitInfo(info) : nullptr, info);
2158 
2159   ciField* field = x->field();
2160   if (field->is_null_free()) {
2161     // Load from non-flat inline type field requires
2162     // a null check to replace null with the default value.
2163     ciInstanceKlass* holder = field->holder();
2164     if (field->is_static() && holder->is_loaded()) {
2165       ciObject* val = holder->java_mirror()->field_value(field).as_object();
2166       if (!val->is_null_object()) {
2167         // Static field is initialized, we don't need to perform a null check.
2168         return;
2169       }
2170     }
2171     ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2172     if (inline_klass->is_initialized()) {
2173       LabelObj* L_end = new LabelObj();
2174       __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(nullptr));
2175       __ branch(lir_cond_notEqual, L_end->label());
2176       set_in_conditional_code(true);
2177       Constant* default_value = new Constant(new InstanceConstant(inline_klass->default_instance()));
2178       if (default_value->is_pinned()) {
2179         __ move(LIR_OprFact::value_type(default_value->type()), result);
2180       } else {
2181         __ move(load_constant(default_value), result);
2182       }
2183       __ branch_destination(L_end->label());
2184       set_in_conditional_code(false);
2185     } else {
2186       info = state_for(x, x->state_before());
2187       __ cmp(lir_cond_equal, result, LIR_OprFact::oopConst(nullptr));
2188       __ branch(lir_cond_equal, new DeoptimizeStub(info, Deoptimization::Reason_uninitialized,
2189                                                          Deoptimization::Action_make_not_entrant));
2190     }
2191   }
2192 }
2193 
2194 // int/long jdk.internal.util.Preconditions.checkIndex
2195 void LIRGenerator::do_PreconditionsCheckIndex(Intrinsic* x, BasicType type) {
2196   assert(x->number_of_arguments() == 3, "wrong type");
2197   LIRItem index(x->argument_at(0), this);
2198   LIRItem length(x->argument_at(1), this);
2199   LIRItem oobef(x->argument_at(2), this);
2200 
2201   index.load_item();
2202   length.load_item();
2203   oobef.load_item();
2204 
2205   LIR_Opr result = rlock_result(x);
2206   // x->state() is created from copy_state_for_exception, it does not contains arguments
2207   // we should prepare them before entering into interpreter mode due to deoptimization.
2208   ValueStack* state = x->state();
2209   for (int i = 0; i < x->number_of_arguments(); i++) {
2210     Value arg = x->argument_at(i);
2211     state->push(arg->type(), arg);
2212   }
2213   CodeEmitInfo* info = state_for(x, state);
2214 
2215   LIR_Opr len = length.result();
2216   LIR_Opr zero;
2217   if (type == T_INT) {
2218     zero = LIR_OprFact::intConst(0);
2219     if (length.result()->is_constant()){
2220       len = LIR_OprFact::intConst(length.result()->as_jint());
2221     }
2222   } else {
2223     assert(type == T_LONG, "sanity check");
2224     zero = LIR_OprFact::longConst(0);
2225     if (length.result()->is_constant()){
2226       len = LIR_OprFact::longConst(length.result()->as_jlong());
2227     }
2228   }
2229   // C1 can not handle the case that comparing index with constant value while condition
2230   // is neither lir_cond_equal nor lir_cond_notEqual, see LIR_Assembler::comp_op.
2231   LIR_Opr zero_reg = new_register(type);
2232   __ move(zero, zero_reg);
2233 #if defined(X86) && !defined(_LP64)
2234   // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
2235   LIR_Opr index_copy = new_register(index.type());
2236   // index >= 0
2237   __ move(index.result(), index_copy);
2238   __ cmp(lir_cond_less, index_copy, zero_reg);
2239   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2240                                                     Deoptimization::Action_make_not_entrant));
2241   // index < length
2242   __ move(index.result(), index_copy);
2243   __ cmp(lir_cond_greaterEqual, index_copy, len);
2244   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2245                                                             Deoptimization::Action_make_not_entrant));
2246 #else
2247   // index >= 0
2248   __ cmp(lir_cond_less, index.result(), zero_reg);
2249   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2250                                                     Deoptimization::Action_make_not_entrant));
2251   // index < length
2252   __ cmp(lir_cond_greaterEqual, index.result(), len);
2253   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2254                                                             Deoptimization::Action_make_not_entrant));
2255 #endif
2256   __ move(index.result(), result);
2257 }
2258 
2259 //------------------------array access--------------------------------------
2260 
2261 
2262 void LIRGenerator::do_ArrayLength(ArrayLength* x) {
2263   LIRItem array(x->array(), this);
2264   array.load_item();
2265   LIR_Opr reg = rlock_result(x);
2266 
2267   CodeEmitInfo* info = nullptr;
2268   if (x->needs_null_check()) {
2269     NullCheck* nc = x->explicit_null_check();
2270     if (nc == nullptr) {
2271       info = state_for(x);
2272     } else {
2273       info = state_for(nc);
2274     }
2275     if (StressLoopInvariantCodeMotion && info->deoptimize_on_exception()) {
2276       LIR_Opr obj = new_register(T_OBJECT);
2277       __ move(LIR_OprFact::oopConst(nullptr), obj);
2278       __ null_check(obj, new CodeEmitInfo(info));
2279     }
2280   }
2281   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
2282 }
2283 
2284 
2285 void LIRGenerator::do_LoadIndexed(LoadIndexed* x) {
2286   bool use_length = x->length() != nullptr;
2287   LIRItem array(x->array(), this);
2288   LIRItem index(x->index(), this);
2289   LIRItem length(this);
2290   bool needs_range_check = x->compute_needs_range_check();
2291 
2292   if (use_length && needs_range_check) {
2293     length.set_instruction(x->length());
2294     length.load_item();
2295   }
2296 
2297   array.load_item();
2298   if (index.is_constant() && can_inline_as_constant(x->index())) {
2299     // let it be a constant
2300     index.dont_load_item();
2301   } else {
2302     index.load_item();
2303   }
2304 
2305   CodeEmitInfo* range_check_info = state_for(x);
2306   CodeEmitInfo* null_check_info = nullptr;
2307   if (x->needs_null_check()) {
2308     NullCheck* nc = x->explicit_null_check();
2309     if (nc != nullptr) {
2310       null_check_info = state_for(nc);
2311     } else {
2312       null_check_info = range_check_info;
2313     }
2314     if (StressLoopInvariantCodeMotion && null_check_info->deoptimize_on_exception()) {
2315       LIR_Opr obj = new_register(T_OBJECT);
2316       __ move(LIR_OprFact::oopConst(nullptr), obj);
2317       __ null_check(obj, new CodeEmitInfo(null_check_info));
2318     }
2319   }
2320 
2321   if (needs_range_check) {
2322     if (StressLoopInvariantCodeMotion && range_check_info->deoptimize_on_exception()) {
2323       __ branch(lir_cond_always, new RangeCheckStub(range_check_info, index.result(), array.result()));
2324     } else if (use_length) {
2325       // TODO: use a (modified) version of array_range_check that does not require a
2326       //       constant length to be loaded to a register
2327       __ cmp(lir_cond_belowEqual, length.result(), index.result());
2328       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
2329     } else {
2330       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
2331       // The range check performs the null check, so clear it out for the load
2332       null_check_info = nullptr;
2333     }
2334   }
2335 
2336   ciMethodData* md = nullptr;
2337   ciArrayLoadData* load_data = nullptr;
2338   if (x->should_profile()) {
2339     if (x->array()->is_loaded_flat_array()) {
2340       // No need to profile a load from a flat array of known type. This can happen if
2341       // the type only became known after optimizations (for example, after the PhiSimplifier).
2342       x->set_should_profile(false);
2343     } else {
2344       int bci = x->profiled_bci();
2345       md = x->profiled_method()->method_data();
2346       assert(md != nullptr, "Sanity");
2347       ciProfileData* data = md->bci_to_data(bci);
2348       assert(data != nullptr && data->is_ArrayLoadData(), "incorrect profiling entry");
2349       load_data = (ciArrayLoadData*)data;
2350       profile_array_type(x, md, load_data);
2351     }
2352   }
2353 
2354   Value element;
2355   if (x->vt() != nullptr) {
2356     assert(x->array()->is_loaded_flat_array(), "must be");
2357     // Find the destination address (of the NewInlineTypeInstance).
2358     LIRItem obj_item(x->vt(), this);
2359 
2360     access_flat_array(true, array, index, obj_item,
2361                       x->delayed() == nullptr ? 0 : x->delayed()->field(),
2362                       x->delayed() == nullptr ? 0 : x->delayed()->offset());
2363     set_no_result(x);
2364   } else if (x->delayed() != nullptr) {
2365     assert(x->array()->is_loaded_flat_array(), "must be");
2366     LIR_Opr result = rlock_result(x, x->delayed()->field()->type()->basic_type());
2367     access_sub_element(array, index, result, x->delayed()->field(), x->delayed()->offset());
2368   } else if (x->array() != nullptr && x->array()->is_loaded_flat_array() &&
2369              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_initialized() &&
2370              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
2371     // Load the default instance instead of reading the element
2372     ciInlineKlass* elem_klass = x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
2373     LIR_Opr result = rlock_result(x, x->elt_type());
2374     assert(elem_klass->is_initialized(), "Must be");
2375     Constant* default_value = new Constant(new InstanceConstant(elem_klass->default_instance()));
2376     if (default_value->is_pinned()) {
2377       __ move(LIR_OprFact::value_type(default_value->type()), result);
2378     } else {
2379       __ move(load_constant(default_value), result);
2380     }
2381   } else {
2382     LIR_Opr result = rlock_result(x, x->elt_type());
2383     LoadFlattenedArrayStub* slow_path = nullptr;
2384 
2385     if (x->should_profile() && x->array()->maybe_null_free_array()) {
2386       profile_null_free_array(array, md, load_data);
2387     }
2388 
2389     if (x->elt_type() == T_OBJECT && x->array()->maybe_flat_array()) {
2390       assert(x->delayed() == nullptr, "Delayed LoadIndexed only apply to loaded_flat_arrays");
2391       index.load_item();
2392       // if we are loading from a flat array, load it using a runtime call
2393       slow_path = new LoadFlattenedArrayStub(array.result(), index.result(), result, state_for(x, x->state_before()));
2394       check_flat_array(array.result(), LIR_OprFact::illegalOpr, slow_path);
2395       set_in_conditional_code(true);
2396     }
2397 
2398     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
2399     access_load_at(decorators, x->elt_type(),
2400                    array, index.result(), result,
2401                    nullptr, null_check_info);
2402 
2403     if (slow_path != nullptr) {
2404       __ branch_destination(slow_path->continuation());
2405       set_in_conditional_code(false);
2406     }
2407 
2408     element = x;
2409   }
2410 
2411   if (x->should_profile()) {
2412     profile_element_type(element, md, load_data);
2413   }
2414 }
2415 
2416 
2417 void LIRGenerator::do_NullCheck(NullCheck* x) {
2418   if (x->can_trap()) {
2419     LIRItem value(x->obj(), this);
2420     value.load_item();
2421     CodeEmitInfo* info = state_for(x);
2422     __ null_check(value.result(), info);
2423   }
2424 }
2425 
2426 
2427 void LIRGenerator::do_TypeCast(TypeCast* x) {
2428   LIRItem value(x->obj(), this);
2429   value.load_item();
2430   // the result is the same as from the node we are casting
2431   set_result(x, value.result());
2432 }
2433 
2434 
2435 void LIRGenerator::do_Throw(Throw* x) {
2436   LIRItem exception(x->exception(), this);
2437   exception.load_item();
2438   set_no_result(x);
2439   LIR_Opr exception_opr = exception.result();
2440   CodeEmitInfo* info = state_for(x, x->state());
2441 
2442 #ifndef PRODUCT
2443   if (PrintC1Statistics) {
2444     increment_counter(Runtime1::throw_count_address(), T_INT);
2445   }
2446 #endif
2447 
2448   // check if the instruction has an xhandler in any of the nested scopes
2449   bool unwind = false;
2450   if (info->exception_handlers()->length() == 0) {
2451     // this throw is not inside an xhandler
2452     unwind = true;
2453   } else {
2454     // get some idea of the throw type
2455     bool type_is_exact = true;
2456     ciType* throw_type = x->exception()->exact_type();
2457     if (throw_type == nullptr) {
2458       type_is_exact = false;
2459       throw_type = x->exception()->declared_type();
2460     }
2461     if (throw_type != nullptr && throw_type->is_instance_klass()) {
2462       ciInstanceKlass* throw_klass = (ciInstanceKlass*)throw_type;
2463       unwind = !x->exception_handlers()->could_catch(throw_klass, type_is_exact);
2464     }
2465   }
2466 
2467   // do null check before moving exception oop into fixed register
2468   // to avoid a fixed interval with an oop during the null check.
2469   // Use a copy of the CodeEmitInfo because debug information is
2470   // different for null_check and throw.
2471   if (x->exception()->as_NewInstance() == nullptr && x->exception()->as_ExceptionObject() == nullptr) {
2472     // if the exception object wasn't created using new then it might be null.
2473     __ null_check(exception_opr, new CodeEmitInfo(info, x->state()->copy(ValueStack::ExceptionState, x->state()->bci())));
2474   }
2475 
2476   if (compilation()->env()->jvmti_can_post_on_exceptions()) {
2477     // we need to go through the exception lookup path to get JVMTI
2478     // notification done
2479     unwind = false;
2480   }
2481 
2482   // move exception oop into fixed register
2483   __ move(exception_opr, exceptionOopOpr());
2484 
2485   if (unwind) {
2486     __ unwind_exception(exceptionOopOpr());
2487   } else {
2488     __ throw_exception(exceptionPcOpr(), exceptionOopOpr(), info);
2489   }
2490 }
2491 
2492 
2493 void LIRGenerator::do_RoundFP(RoundFP* x) {
2494   assert(strict_fp_requires_explicit_rounding, "not required");
2495 
2496   LIRItem input(x->input(), this);
2497   input.load_item();
2498   LIR_Opr input_opr = input.result();
2499   assert(input_opr->is_register(), "why round if value is not in a register?");
2500   assert(input_opr->is_single_fpu() || input_opr->is_double_fpu(), "input should be floating-point value");
2501   if (input_opr->is_single_fpu()) {
2502     set_result(x, round_item(input_opr)); // This code path not currently taken
2503   } else {
2504     LIR_Opr result = new_register(T_DOUBLE);
2505     set_vreg_flag(result, must_start_in_memory);
2506     __ roundfp(input_opr, LIR_OprFact::illegalOpr, result);
2507     set_result(x, result);
2508   }
2509 }
2510 
2511 
2512 void LIRGenerator::do_UnsafeGet(UnsafeGet* x) {
2513   BasicType type = x->basic_type();
2514   LIRItem src(x->object(), this);
2515   LIRItem off(x->offset(), this);
2516 
2517   off.load_item();
2518   src.load_item();
2519 
2520   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2521 
2522   if (x->is_volatile()) {
2523     decorators |= MO_SEQ_CST;
2524   }
2525   if (type == T_BOOLEAN) {
2526     decorators |= C1_MASK_BOOLEAN;
2527   }
2528   if (is_reference_type(type)) {
2529     decorators |= ON_UNKNOWN_OOP_REF;
2530   }
2531 
2532   LIR_Opr result = rlock_result(x, type);
2533   if (!x->is_raw()) {
2534     access_load_at(decorators, type, src, off.result(), result);
2535   } else {
2536     // Currently it is only used in GraphBuilder::setup_osr_entry_block.
2537     // It reads the value from [src + offset] directly.
2538 #ifdef _LP64
2539     LIR_Opr offset = new_register(T_LONG);
2540     __ convert(Bytecodes::_i2l, off.result(), offset);
2541 #else
2542     LIR_Opr offset = off.result();
2543 #endif
2544     LIR_Address* addr = new LIR_Address(src.result(), offset, type);
2545     if (is_reference_type(type)) {
2546       __ move_wide(addr, result);
2547     } else {
2548       __ move(addr, result);
2549     }
2550   }
2551 }
2552 
2553 
2554 void LIRGenerator::do_UnsafePut(UnsafePut* x) {
2555   BasicType type = x->basic_type();
2556   LIRItem src(x->object(), this);
2557   LIRItem off(x->offset(), this);
2558   LIRItem data(x->value(), this);
2559 
2560   src.load_item();
2561   if (type == T_BOOLEAN || type == T_BYTE) {
2562     data.load_byte_item();
2563   } else {
2564     data.load_item();
2565   }
2566   off.load_item();
2567 
2568   set_no_result(x);
2569 
2570   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2571   if (is_reference_type(type)) {
2572     decorators |= ON_UNKNOWN_OOP_REF;
2573   }
2574   if (x->is_volatile()) {
2575     decorators |= MO_SEQ_CST;
2576   }
2577   access_store_at(decorators, type, src, off.result(), data.result());
2578 }
2579 
2580 void LIRGenerator::do_UnsafeGetAndSet(UnsafeGetAndSet* x) {
2581   BasicType type = x->basic_type();
2582   LIRItem src(x->object(), this);
2583   LIRItem off(x->offset(), this);
2584   LIRItem value(x->value(), this);
2585 
2586   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS | MO_SEQ_CST;
2587 
2588   if (is_reference_type(type)) {
2589     decorators |= ON_UNKNOWN_OOP_REF;
2590   }
2591 
2592   LIR_Opr result;
2593   if (x->is_add()) {
2594     result = access_atomic_add_at(decorators, type, src, off, value);
2595   } else {
2596     result = access_atomic_xchg_at(decorators, type, src, off, value);
2597   }
2598   set_result(x, result);
2599 }
2600 
2601 void LIRGenerator::do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux) {
2602   int lng = x->length();
2603 
2604   for (int i = 0; i < lng; i++) {
2605     C1SwitchRange* one_range = x->at(i);
2606     int low_key = one_range->low_key();
2607     int high_key = one_range->high_key();
2608     BlockBegin* dest = one_range->sux();
2609     if (low_key == high_key) {
2610       __ cmp(lir_cond_equal, value, low_key);
2611       __ branch(lir_cond_equal, dest);
2612     } else if (high_key - low_key == 1) {
2613       __ cmp(lir_cond_equal, value, low_key);
2614       __ branch(lir_cond_equal, dest);
2615       __ cmp(lir_cond_equal, value, high_key);
2616       __ branch(lir_cond_equal, dest);
2617     } else {
2618       LabelObj* L = new LabelObj();
2619       __ cmp(lir_cond_less, value, low_key);
2620       __ branch(lir_cond_less, L->label());
2621       __ cmp(lir_cond_lessEqual, value, high_key);
2622       __ branch(lir_cond_lessEqual, dest);
2623       __ branch_destination(L->label());
2624     }
2625   }
2626   __ jump(default_sux);
2627 }
2628 
2629 
2630 SwitchRangeArray* LIRGenerator::create_lookup_ranges(TableSwitch* x) {
2631   SwitchRangeList* res = new SwitchRangeList();
2632   int len = x->length();
2633   if (len > 0) {
2634     BlockBegin* sux = x->sux_at(0);
2635     int low = x->lo_key();
2636     BlockBegin* default_sux = x->default_sux();
2637     C1SwitchRange* range = new C1SwitchRange(low, sux);
2638     for (int i = 0; i < len; i++) {
2639       int key = low + i;
2640       BlockBegin* new_sux = x->sux_at(i);
2641       if (sux == new_sux) {
2642         // still in same range
2643         range->set_high_key(key);
2644       } else {
2645         // skip tests which explicitly dispatch to the default
2646         if (sux != default_sux) {
2647           res->append(range);
2648         }
2649         range = new C1SwitchRange(key, new_sux);
2650       }
2651       sux = new_sux;
2652     }
2653     if (res->length() == 0 || res->last() != range)  res->append(range);
2654   }
2655   return res;
2656 }
2657 
2658 
2659 // we expect the keys to be sorted by increasing value
2660 SwitchRangeArray* LIRGenerator::create_lookup_ranges(LookupSwitch* x) {
2661   SwitchRangeList* res = new SwitchRangeList();
2662   int len = x->length();
2663   if (len > 0) {
2664     BlockBegin* default_sux = x->default_sux();
2665     int key = x->key_at(0);
2666     BlockBegin* sux = x->sux_at(0);
2667     C1SwitchRange* range = new C1SwitchRange(key, sux);
2668     for (int i = 1; i < len; i++) {
2669       int new_key = x->key_at(i);
2670       BlockBegin* new_sux = x->sux_at(i);
2671       if (key+1 == new_key && sux == new_sux) {
2672         // still in same range
2673         range->set_high_key(new_key);
2674       } else {
2675         // skip tests which explicitly dispatch to the default
2676         if (range->sux() != default_sux) {
2677           res->append(range);
2678         }
2679         range = new C1SwitchRange(new_key, new_sux);
2680       }
2681       key = new_key;
2682       sux = new_sux;
2683     }
2684     if (res->length() == 0 || res->last() != range)  res->append(range);
2685   }
2686   return res;
2687 }
2688 
2689 
2690 void LIRGenerator::do_TableSwitch(TableSwitch* x) {
2691   LIRItem tag(x->tag(), this);
2692   tag.load_item();
2693   set_no_result(x);
2694 
2695   if (x->is_safepoint()) {
2696     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2697   }
2698 
2699   // move values into phi locations
2700   move_to_phi(x->state());
2701 
2702   int lo_key = x->lo_key();
2703   int len = x->length();
2704   assert(lo_key <= (lo_key + (len - 1)), "integer overflow");
2705   LIR_Opr value = tag.result();
2706 
2707   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2708     ciMethod* method = x->state()->scope()->method();
2709     ciMethodData* md = method->method_data_or_null();
2710     assert(md != nullptr, "Sanity");
2711     ciProfileData* data = md->bci_to_data(x->state()->bci());
2712     assert(data != nullptr, "must have profiling data");
2713     assert(data->is_MultiBranchData(), "bad profile data?");
2714     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2715     LIR_Opr md_reg = new_register(T_METADATA);
2716     __ metadata2reg(md->constant_encoding(), md_reg);
2717     LIR_Opr data_offset_reg = new_pointer_register();
2718     LIR_Opr tmp_reg = new_pointer_register();
2719 
2720     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2721     for (int i = 0; i < len; i++) {
2722       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2723       __ cmp(lir_cond_equal, value, i + lo_key);
2724       __ move(data_offset_reg, tmp_reg);
2725       __ cmove(lir_cond_equal,
2726                LIR_OprFact::intptrConst(count_offset),
2727                tmp_reg,
2728                data_offset_reg, T_INT);
2729     }
2730 
2731     LIR_Opr data_reg = new_pointer_register();
2732     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2733     __ move(data_addr, data_reg);
2734     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2735     __ move(data_reg, data_addr);
2736   }
2737 
2738   if (UseTableRanges) {
2739     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2740   } else {
2741     for (int i = 0; i < len; i++) {
2742       __ cmp(lir_cond_equal, value, i + lo_key);
2743       __ branch(lir_cond_equal, x->sux_at(i));
2744     }
2745     __ jump(x->default_sux());
2746   }
2747 }
2748 
2749 
2750 void LIRGenerator::do_LookupSwitch(LookupSwitch* x) {
2751   LIRItem tag(x->tag(), this);
2752   tag.load_item();
2753   set_no_result(x);
2754 
2755   if (x->is_safepoint()) {
2756     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2757   }
2758 
2759   // move values into phi locations
2760   move_to_phi(x->state());
2761 
2762   LIR_Opr value = tag.result();
2763   int len = x->length();
2764 
2765   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2766     ciMethod* method = x->state()->scope()->method();
2767     ciMethodData* md = method->method_data_or_null();
2768     assert(md != nullptr, "Sanity");
2769     ciProfileData* data = md->bci_to_data(x->state()->bci());
2770     assert(data != nullptr, "must have profiling data");
2771     assert(data->is_MultiBranchData(), "bad profile data?");
2772     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2773     LIR_Opr md_reg = new_register(T_METADATA);
2774     __ metadata2reg(md->constant_encoding(), md_reg);
2775     LIR_Opr data_offset_reg = new_pointer_register();
2776     LIR_Opr tmp_reg = new_pointer_register();
2777 
2778     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2779     for (int i = 0; i < len; i++) {
2780       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2781       __ cmp(lir_cond_equal, value, x->key_at(i));
2782       __ move(data_offset_reg, tmp_reg);
2783       __ cmove(lir_cond_equal,
2784                LIR_OprFact::intptrConst(count_offset),
2785                tmp_reg,
2786                data_offset_reg, T_INT);
2787     }
2788 
2789     LIR_Opr data_reg = new_pointer_register();
2790     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2791     __ move(data_addr, data_reg);
2792     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2793     __ move(data_reg, data_addr);
2794   }
2795 
2796   if (UseTableRanges) {
2797     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2798   } else {
2799     int len = x->length();
2800     for (int i = 0; i < len; i++) {
2801       __ cmp(lir_cond_equal, value, x->key_at(i));
2802       __ branch(lir_cond_equal, x->sux_at(i));
2803     }
2804     __ jump(x->default_sux());
2805   }
2806 }
2807 
2808 
2809 void LIRGenerator::do_Goto(Goto* x) {
2810   set_no_result(x);
2811 
2812   if (block()->next()->as_OsrEntry()) {
2813     // need to free up storage used for OSR entry point
2814     LIR_Opr osrBuffer = block()->next()->operand();
2815     BasicTypeList signature;
2816     signature.append(NOT_LP64(T_INT) LP64_ONLY(T_LONG)); // pass a pointer to osrBuffer
2817     CallingConvention* cc = frame_map()->c_calling_convention(&signature);
2818     __ move(osrBuffer, cc->args()->at(0));
2819     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
2820                          getThreadTemp(), LIR_OprFact::illegalOpr, cc->args());
2821   }
2822 
2823   if (x->is_safepoint()) {
2824     ValueStack* state = x->state_before() ? x->state_before() : x->state();
2825 
2826     // increment backedge counter if needed
2827     CodeEmitInfo* info = state_for(x, state);
2828     increment_backedge_counter(info, x->profiled_bci());
2829     CodeEmitInfo* safepoint_info = state_for(x, state);
2830     __ safepoint(safepoint_poll_register(), safepoint_info);
2831   }
2832 
2833   // Gotos can be folded Ifs, handle this case.
2834   if (x->should_profile()) {
2835     ciMethod* method = x->profiled_method();
2836     assert(method != nullptr, "method should be set if branch is profiled");
2837     ciMethodData* md = method->method_data_or_null();
2838     assert(md != nullptr, "Sanity");
2839     ciProfileData* data = md->bci_to_data(x->profiled_bci());
2840     assert(data != nullptr, "must have profiling data");
2841     int offset;
2842     if (x->direction() == Goto::taken) {
2843       assert(data->is_BranchData(), "need BranchData for two-way branches");
2844       offset = md->byte_offset_of_slot(data, BranchData::taken_offset());
2845     } else if (x->direction() == Goto::not_taken) {
2846       assert(data->is_BranchData(), "need BranchData for two-way branches");
2847       offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
2848     } else {
2849       assert(data->is_JumpData(), "need JumpData for branches");
2850       offset = md->byte_offset_of_slot(data, JumpData::taken_offset());
2851     }
2852     LIR_Opr md_reg = new_register(T_METADATA);
2853     __ metadata2reg(md->constant_encoding(), md_reg);
2854 
2855     increment_counter(new LIR_Address(md_reg, offset,
2856                                       NOT_LP64(T_INT) LP64_ONLY(T_LONG)), DataLayout::counter_increment);
2857   }
2858 
2859   // emit phi-instruction move after safepoint since this simplifies
2860   // describing the state as the safepoint.
2861   move_to_phi(x->state());
2862 
2863   __ jump(x->default_sux());
2864 }
2865 
2866 /**
2867  * Emit profiling code if needed for arguments, parameters, return value types
2868  *
2869  * @param md                    MDO the code will update at runtime
2870  * @param md_base_offset        common offset in the MDO for this profile and subsequent ones
2871  * @param md_offset             offset in the MDO (on top of md_base_offset) for this profile
2872  * @param profiled_k            current profile
2873  * @param obj                   IR node for the object to be profiled
2874  * @param mdp                   register to hold the pointer inside the MDO (md + md_base_offset).
2875  *                              Set once we find an update to make and use for next ones.
2876  * @param not_null              true if we know obj cannot be null
2877  * @param signature_at_call_k   signature at call for obj
2878  * @param callee_signature_k    signature of callee for obj
2879  *                              at call and callee signatures differ at method handle call
2880  * @return                      the only klass we know will ever be seen at this profile point
2881  */
2882 ciKlass* LIRGenerator::profile_type(ciMethodData* md, int md_base_offset, int md_offset, intptr_t profiled_k,
2883                                     Value obj, LIR_Opr& mdp, bool not_null, ciKlass* signature_at_call_k,
2884                                     ciKlass* callee_signature_k) {
2885   ciKlass* result = nullptr;
2886   bool do_null = !not_null && !TypeEntries::was_null_seen(profiled_k);
2887   bool do_update = !TypeEntries::is_type_unknown(profiled_k);
2888   // known not to be null or null bit already set and already set to
2889   // unknown: nothing we can do to improve profiling
2890   if (!do_null && !do_update) {
2891     return result;
2892   }
2893 
2894   ciKlass* exact_klass = nullptr;
2895   Compilation* comp = Compilation::current();
2896   if (do_update) {
2897     // try to find exact type, using CHA if possible, so that loading
2898     // the klass from the object can be avoided
2899     ciType* type = obj->exact_type();
2900     if (type == nullptr) {
2901       type = obj->declared_type();
2902       type = comp->cha_exact_type(type);
2903     }
2904     assert(type == nullptr || type->is_klass(), "type should be class");
2905     exact_klass = (type != nullptr && type->is_loaded()) ? (ciKlass*)type : nullptr;
2906 
2907     do_update = exact_klass == nullptr || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2908   }
2909 
2910   if (!do_null && !do_update) {
2911     return result;
2912   }
2913 
2914   ciKlass* exact_signature_k = nullptr;
2915   if (do_update && signature_at_call_k != nullptr) {
2916     // Is the type from the signature exact (the only one possible)?
2917     exact_signature_k = signature_at_call_k->exact_klass();
2918     if (exact_signature_k == nullptr) {
2919       exact_signature_k = comp->cha_exact_type(signature_at_call_k);
2920     } else {
2921       result = exact_signature_k;
2922       // Known statically. No need to emit any code: prevent
2923       // LIR_Assembler::emit_profile_type() from emitting useless code
2924       profiled_k = ciTypeEntries::with_status(result, profiled_k);
2925     }
2926     // exact_klass and exact_signature_k can be both non null but
2927     // different if exact_klass is loaded after the ciObject for
2928     // exact_signature_k is created.
2929     if (exact_klass == nullptr && exact_signature_k != nullptr && exact_klass != exact_signature_k) {
2930       // sometimes the type of the signature is better than the best type
2931       // the compiler has
2932       exact_klass = exact_signature_k;
2933     }
2934     if (callee_signature_k != nullptr &&
2935         callee_signature_k != signature_at_call_k) {
2936       ciKlass* improved_klass = callee_signature_k->exact_klass();
2937       if (improved_klass == nullptr) {
2938         improved_klass = comp->cha_exact_type(callee_signature_k);
2939       }
2940       if (exact_klass == nullptr && improved_klass != nullptr && exact_klass != improved_klass) {
2941         exact_klass = exact_signature_k;
2942       }
2943     }
2944     do_update = exact_klass == nullptr || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2945   }
2946 
2947   if (!do_null && !do_update) {
2948     return result;
2949   }
2950 
2951   if (mdp == LIR_OprFact::illegalOpr) {
2952     mdp = new_register(T_METADATA);
2953     __ metadata2reg(md->constant_encoding(), mdp);
2954     if (md_base_offset != 0) {
2955       LIR_Address* base_type_address = new LIR_Address(mdp, md_base_offset, T_ADDRESS);
2956       mdp = new_pointer_register();
2957       __ leal(LIR_OprFact::address(base_type_address), mdp);
2958     }
2959   }
2960   LIRItem value(obj, this);
2961   value.load_item();
2962   __ profile_type(new LIR_Address(mdp, md_offset, T_METADATA),
2963                   value.result(), exact_klass, profiled_k, new_pointer_register(), not_null, exact_signature_k != nullptr);
2964   return result;
2965 }
2966 
2967 // profile parameters on entry to the root of the compilation
2968 void LIRGenerator::profile_parameters(Base* x) {
2969   if (compilation()->profile_parameters()) {
2970     CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2971     ciMethodData* md = scope()->method()->method_data_or_null();
2972     assert(md != nullptr, "Sanity");
2973 
2974     if (md->parameters_type_data() != nullptr) {
2975       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
2976       ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
2977       LIR_Opr mdp = LIR_OprFact::illegalOpr;
2978       for (int java_index = 0, i = 0, j = 0; j < parameters_type_data->number_of_parameters(); i++) {
2979         LIR_Opr src = args->at(i);
2980         assert(!src->is_illegal(), "check");
2981         BasicType t = src->type();
2982         if (is_reference_type(t)) {
2983           intptr_t profiled_k = parameters->type(j);
2984           Local* local = x->state()->local_at(java_index)->as_Local();
2985           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
2986                                         in_bytes(ParametersTypeData::type_offset(j)) - in_bytes(ParametersTypeData::type_offset(0)),
2987                                         profiled_k, local, mdp, false, local->declared_type()->as_klass(), nullptr);
2988           // If the profile is known statically set it once for all and do not emit any code
2989           if (exact != nullptr) {
2990             md->set_parameter_type(j, exact);
2991           }
2992           j++;
2993         }
2994         java_index += type2size[t];
2995       }
2996     }
2997   }
2998 }
2999 
3000 void LIRGenerator::profile_flags(ciMethodData* md, ciProfileData* data, int flag, LIR_Condition condition) {
3001   assert(md != nullptr && data != nullptr, "should have been initialized");
3002   LIR_Opr mdp = new_register(T_METADATA);
3003   __ metadata2reg(md->constant_encoding(), mdp);
3004   LIR_Address* addr = new LIR_Address(mdp, md->byte_offset_of_slot(data, DataLayout::flags_offset()), T_BYTE);
3005   LIR_Opr flags = new_register(T_INT);
3006   __ move(addr, flags);
3007   if (condition != lir_cond_always) {
3008     LIR_Opr update = new_register(T_INT);
3009     __ cmove(condition, LIR_OprFact::intConst(0), LIR_OprFact::intConst(flag), update, T_INT);
3010   } else {
3011     __ logical_or(flags, LIR_OprFact::intConst(flag), flags);
3012   }
3013   __ store(flags, addr);
3014 }
3015 
3016 template <class ArrayData> void LIRGenerator::profile_null_free_array(LIRItem array, ciMethodData* md, ArrayData* load_store) {
3017   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3018   LabelObj* L_end = new LabelObj();
3019   LIR_Opr tmp = new_register(T_METADATA);
3020   __ check_null_free_array(array.result(), tmp);
3021 
3022   profile_flags(md, load_store, ArrayStoreData::null_free_array_byte_constant(), lir_cond_equal);
3023 }
3024 
3025 template <class ArrayData> void LIRGenerator::profile_array_type(AccessIndexed* x, ciMethodData*& md, ArrayData*& load_store) {
3026   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3027   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3028   profile_type(md, md->byte_offset_of_slot(load_store, ArrayData::array_offset()), 0,
3029                load_store->array()->type(), x->array(), mdp, true, nullptr, nullptr);
3030 }
3031 
3032 void LIRGenerator::profile_element_type(Value element, ciMethodData* md, ciArrayLoadData* load_data) {
3033   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3034   assert(md != nullptr && load_data != nullptr, "should have been initialized");
3035   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3036   profile_type(md, md->byte_offset_of_slot(load_data, ArrayLoadData::element_offset()), 0,
3037                load_data->element()->type(), element, mdp, false, nullptr, nullptr);
3038 }
3039 
3040 void LIRGenerator::do_Base(Base* x) {
3041   __ std_entry(LIR_OprFact::illegalOpr);
3042   // Emit moves from physical registers / stack slots to virtual registers
3043   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
3044   IRScope* irScope = compilation()->hir()->top_scope();
3045   int java_index = 0;
3046   for (int i = 0; i < args->length(); i++) {
3047     LIR_Opr src = args->at(i);
3048     assert(!src->is_illegal(), "check");
3049     BasicType t = src->type();
3050 
3051     // Types which are smaller than int are passed as int, so
3052     // correct the type which passed.
3053     switch (t) {
3054     case T_BYTE:
3055     case T_BOOLEAN:
3056     case T_SHORT:
3057     case T_CHAR:
3058       t = T_INT;
3059       break;
3060     default:
3061       break;
3062     }
3063 
3064     LIR_Opr dest = new_register(t);
3065     __ move(src, dest);
3066 
3067     // Assign new location to Local instruction for this local
3068     Local* local = x->state()->local_at(java_index)->as_Local();
3069     assert(local != nullptr, "Locals for incoming arguments must have been created");
3070 #ifndef __SOFTFP__
3071     // The java calling convention passes double as long and float as int.
3072     assert(as_ValueType(t)->tag() == local->type()->tag(), "check");
3073 #endif // __SOFTFP__
3074     local->set_operand(dest);
3075     _instruction_for_operand.at_put_grow(dest->vreg_number(), local, nullptr);
3076     java_index += type2size[t];
3077   }
3078 
3079   if (compilation()->env()->dtrace_method_probes()) {
3080     BasicTypeList signature;
3081     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3082     signature.append(T_METADATA); // Method*
3083     LIR_OprList* args = new LIR_OprList();
3084     args->append(getThreadPointer());
3085     LIR_Opr meth = new_register(T_METADATA);
3086     __ metadata2reg(method()->constant_encoding(), meth);
3087     args->append(meth);
3088     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), voidType, nullptr);
3089   }
3090 
3091   if (method()->is_synchronized()) {
3092     LIR_Opr obj;
3093     if (method()->is_static()) {
3094       obj = new_register(T_OBJECT);
3095       __ oop2reg(method()->holder()->java_mirror()->constant_encoding(), obj);
3096     } else {
3097       Local* receiver = x->state()->local_at(0)->as_Local();
3098       assert(receiver != nullptr, "must already exist");
3099       obj = receiver->operand();
3100     }
3101     assert(obj->is_valid(), "must be valid");
3102 
3103     if (method()->is_synchronized() && GenerateSynchronizationCode) {
3104       LIR_Opr lock = syncLockOpr();
3105       __ load_stack_address_monitor(0, lock);
3106 
3107       CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), nullptr, x->check_flag(Instruction::DeoptimizeOnException));
3108       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
3109 
3110       // receiver is guaranteed non-null so don't need CodeEmitInfo
3111       __ lock_object(syncTempOpr(), obj, lock, new_register(T_OBJECT), slow_path, nullptr);
3112     }
3113   }
3114   // increment invocation counters if needed
3115   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
3116     profile_parameters(x);
3117     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), nullptr, false);
3118     increment_invocation_counter(info);
3119   }
3120   if (method()->has_scalarized_args()) {
3121     // Check if deoptimization was triggered (i.e. orig_pc was set) while buffering scalarized inline type arguments
3122     // in the entry point (see comments in frame::deoptimize). If so, deoptimize only now that we have the right state.
3123     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, 0), nullptr, false);
3124     CodeStub* deopt_stub = new DeoptimizeStub(info, Deoptimization::Reason_none, Deoptimization::Action_none);
3125     __ append(new LIR_Op0(lir_check_orig_pc));
3126     __ branch(lir_cond_notEqual, deopt_stub);
3127   }
3128 
3129   // all blocks with a successor must end with an unconditional jump
3130   // to the successor even if they are consecutive
3131   __ jump(x->default_sux());
3132 }
3133 
3134 
3135 void LIRGenerator::do_OsrEntry(OsrEntry* x) {
3136   // construct our frame and model the production of incoming pointer
3137   // to the OSR buffer.
3138   __ osr_entry(LIR_Assembler::osrBufferPointer());
3139   LIR_Opr result = rlock_result(x);
3140   __ move(LIR_Assembler::osrBufferPointer(), result);
3141 }
3142 
3143 void LIRGenerator::invoke_load_one_argument(LIRItem* param, LIR_Opr loc) {
3144   if (loc->is_register()) {
3145     param->load_item_force(loc);
3146   } else {
3147     LIR_Address* addr = loc->as_address_ptr();
3148     param->load_for_store(addr->type());
3149     if (addr->type() == T_OBJECT) {
3150       __ move_wide(param->result(), addr);
3151     } else {
3152       __ move(param->result(), addr);
3153     }
3154   }
3155 }
3156 
3157 void LIRGenerator::invoke_load_arguments(Invoke* x, LIRItemList* args, const LIR_OprList* arg_list) {
3158   assert(args->length() == arg_list->length(),
3159          "args=%d, arg_list=%d", args->length(), arg_list->length());
3160   for (int i = x->has_receiver() ? 1 : 0; i < args->length(); i++) {
3161     LIRItem* param = args->at(i);
3162     LIR_Opr loc = arg_list->at(i);
3163     invoke_load_one_argument(param, loc);
3164   }
3165 
3166   if (x->has_receiver()) {
3167     LIRItem* receiver = args->at(0);
3168     LIR_Opr loc = arg_list->at(0);
3169     if (loc->is_register()) {
3170       receiver->load_item_force(loc);
3171     } else {
3172       assert(loc->is_address(), "just checking");
3173       receiver->load_for_store(T_OBJECT);
3174       __ move_wide(receiver->result(), loc->as_address_ptr());
3175     }
3176   }
3177 }
3178 
3179 
3180 // Visits all arguments, returns appropriate items without loading them
3181 LIRItemList* LIRGenerator::invoke_visit_arguments(Invoke* x) {
3182   LIRItemList* argument_items = new LIRItemList();
3183   if (x->has_receiver()) {
3184     LIRItem* receiver = new LIRItem(x->receiver(), this);
3185     argument_items->append(receiver);
3186   }
3187   for (int i = 0; i < x->number_of_arguments(); i++) {
3188     LIRItem* param = new LIRItem(x->argument_at(i), this);
3189     argument_items->append(param);
3190   }
3191   return argument_items;
3192 }
3193 
3194 
3195 // The invoke with receiver has following phases:
3196 //   a) traverse and load/lock receiver;
3197 //   b) traverse all arguments -> item-array (invoke_visit_argument)
3198 //   c) push receiver on stack
3199 //   d) load each of the items and push on stack
3200 //   e) unlock receiver
3201 //   f) move receiver into receiver-register %o0
3202 //   g) lock result registers and emit call operation
3203 //
3204 // Before issuing a call, we must spill-save all values on stack
3205 // that are in caller-save register. "spill-save" moves those registers
3206 // either in a free callee-save register or spills them if no free
3207 // callee save register is available.
3208 //
3209 // The problem is where to invoke spill-save.
3210 // - if invoked between e) and f), we may lock callee save
3211 //   register in "spill-save" that destroys the receiver register
3212 //   before f) is executed
3213 // - if we rearrange f) to be earlier (by loading %o0) it
3214 //   may destroy a value on the stack that is currently in %o0
3215 //   and is waiting to be spilled
3216 // - if we keep the receiver locked while doing spill-save,
3217 //   we cannot spill it as it is spill-locked
3218 //
3219 void LIRGenerator::do_Invoke(Invoke* x) {
3220   CallingConvention* cc = frame_map()->java_calling_convention(x->signature(), true);
3221 
3222   LIR_OprList* arg_list = cc->args();
3223   LIRItemList* args = invoke_visit_arguments(x);
3224   LIR_Opr receiver = LIR_OprFact::illegalOpr;
3225 
3226   // setup result register
3227   LIR_Opr result_register = LIR_OprFact::illegalOpr;
3228   if (x->type() != voidType) {
3229     result_register = result_register_for(x->type());
3230   }
3231 
3232   CodeEmitInfo* info = state_for(x, x->state());
3233 
3234   invoke_load_arguments(x, args, arg_list);
3235 
3236   if (x->has_receiver()) {
3237     args->at(0)->load_item_force(LIR_Assembler::receiverOpr());
3238     receiver = args->at(0)->result();
3239   }
3240 
3241   // emit invoke code
3242   assert(receiver->is_illegal() || receiver->is_equal(LIR_Assembler::receiverOpr()), "must match");
3243 
3244   // JSR 292
3245   // Preserve the SP over MethodHandle call sites, if needed.
3246   ciMethod* target = x->target();
3247   bool is_method_handle_invoke = (// %%% FIXME: Are both of these relevant?
3248                                   target->is_method_handle_intrinsic() ||
3249                                   target->is_compiled_lambda_form());
3250   if (is_method_handle_invoke) {
3251     info->set_is_method_handle_invoke(true);
3252     if(FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3253         __ move(FrameMap::stack_pointer(), FrameMap::method_handle_invoke_SP_save_opr());
3254     }
3255   }
3256 
3257   switch (x->code()) {
3258     case Bytecodes::_invokestatic:
3259       __ call_static(target, result_register,
3260                      SharedRuntime::get_resolve_static_call_stub(),
3261                      arg_list, info);
3262       break;
3263     case Bytecodes::_invokespecial:
3264     case Bytecodes::_invokevirtual:
3265     case Bytecodes::_invokeinterface:
3266       // for loaded and final (method or class) target we still produce an inline cache,
3267       // in order to be able to call mixed mode
3268       if (x->code() == Bytecodes::_invokespecial || x->target_is_final()) {
3269         __ call_opt_virtual(target, receiver, result_register,
3270                             SharedRuntime::get_resolve_opt_virtual_call_stub(),
3271                             arg_list, info);
3272       } else {
3273         __ call_icvirtual(target, receiver, result_register,
3274                           SharedRuntime::get_resolve_virtual_call_stub(),
3275                           arg_list, info);
3276       }
3277       break;
3278     case Bytecodes::_invokedynamic: {
3279       __ call_dynamic(target, receiver, result_register,
3280                       SharedRuntime::get_resolve_static_call_stub(),
3281                       arg_list, info);
3282       break;
3283     }
3284     default:
3285       fatal("unexpected bytecode: %s", Bytecodes::name(x->code()));
3286       break;
3287   }
3288 
3289   // JSR 292
3290   // Restore the SP after MethodHandle call sites, if needed.
3291   if (is_method_handle_invoke
3292       && FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3293     __ move(FrameMap::method_handle_invoke_SP_save_opr(), FrameMap::stack_pointer());
3294   }
3295 
3296   if (result_register->is_valid()) {
3297     LIR_Opr result = rlock_result(x);
3298     __ move(result_register, result);
3299   }
3300 }
3301 
3302 
3303 void LIRGenerator::do_FPIntrinsics(Intrinsic* x) {
3304   assert(x->number_of_arguments() == 1, "wrong type");
3305   LIRItem value       (x->argument_at(0), this);
3306   LIR_Opr reg = rlock_result(x);
3307   value.load_item();
3308   LIR_Opr tmp = force_to_spill(value.result(), as_BasicType(x->type()));
3309   __ move(tmp, reg);
3310 }
3311 
3312 
3313 
3314 // Code for  :  x->x() {x->cond()} x->y() ? x->tval() : x->fval()
3315 void LIRGenerator::do_IfOp(IfOp* x) {
3316 #ifdef ASSERT
3317   {
3318     ValueTag xtag = x->x()->type()->tag();
3319     ValueTag ttag = x->tval()->type()->tag();
3320     assert(xtag == intTag || xtag == objectTag, "cannot handle others");
3321     assert(ttag == addressTag || ttag == intTag || ttag == objectTag || ttag == longTag, "cannot handle others");
3322     assert(ttag == x->fval()->type()->tag(), "cannot handle others");
3323   }
3324 #endif
3325 
3326   LIRItem left(x->x(), this);
3327   LIRItem right(x->y(), this);
3328   left.load_item();
3329   if (can_inline_as_constant(right.value()) && !x->substitutability_check()) {
3330     right.dont_load_item();
3331   } else {
3332     // substitutability_check() needs to use right as a base register.
3333     right.load_item();
3334   }
3335 
3336   LIRItem t_val(x->tval(), this);
3337   LIRItem f_val(x->fval(), this);
3338   t_val.dont_load_item();
3339   f_val.dont_load_item();
3340 
3341   if (x->substitutability_check()) {
3342     substitutability_check(x, left, right, t_val, f_val);
3343   } else {
3344     LIR_Opr reg = rlock_result(x);
3345     __ cmp(lir_cond(x->cond()), left.result(), right.result());
3346     __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg, as_BasicType(x->x()->type()));
3347   }
3348 }
3349 
3350 void LIRGenerator::substitutability_check(IfOp* x, LIRItem& left, LIRItem& right, LIRItem& t_val, LIRItem& f_val) {
3351   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3352   bool is_acmpeq = (x->cond() == If::eql);
3353   LIR_Opr equal_result     = is_acmpeq ? t_val.result() : f_val.result();
3354   LIR_Opr not_equal_result = is_acmpeq ? f_val.result() : t_val.result();
3355   LIR_Opr result = rlock_result(x);
3356   CodeEmitInfo* info = state_for(x, x->state_before());
3357 
3358   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3359 }
3360 
3361 void LIRGenerator::substitutability_check(If* x, LIRItem& left, LIRItem& right) {
3362   LIR_Opr equal_result     = LIR_OprFact::intConst(1);
3363   LIR_Opr not_equal_result = LIR_OprFact::intConst(0);
3364   LIR_Opr result = new_register(T_INT);
3365   CodeEmitInfo* info = state_for(x, x->state_before());
3366 
3367   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3368 
3369   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3370   __ cmp(lir_cond(x->cond()), result, equal_result);
3371 }
3372 
3373 void LIRGenerator::substitutability_check_common(Value left_val, Value right_val, LIRItem& left, LIRItem& right,
3374                                                  LIR_Opr equal_result, LIR_Opr not_equal_result, LIR_Opr result,
3375                                                  CodeEmitInfo* info) {
3376   LIR_Opr tmp1 = LIR_OprFact::illegalOpr;
3377   LIR_Opr tmp2 = LIR_OprFact::illegalOpr;
3378   LIR_Opr left_klass_op = LIR_OprFact::illegalOpr;
3379   LIR_Opr right_klass_op = LIR_OprFact::illegalOpr;
3380 
3381   ciKlass* left_klass  = left_val ->as_loaded_klass_or_null();
3382   ciKlass* right_klass = right_val->as_loaded_klass_or_null();
3383 
3384   if ((left_klass == nullptr || right_klass == nullptr) ||// The klass is still unloaded, or came from a Phi node.
3385       !left_klass->is_inlinetype() || !right_klass->is_inlinetype()) {
3386     init_temps_for_substitutability_check(tmp1, tmp2);
3387   }
3388 
3389   if (left_klass != nullptr && left_klass->is_inlinetype() && left_klass == right_klass) {
3390     // No need to load klass -- the operands are statically known to be the same inline klass.
3391   } else {
3392     BasicType t_klass = UseCompressedOops ? T_INT : T_METADATA;
3393     left_klass_op = new_register(t_klass);
3394     right_klass_op = new_register(t_klass);
3395   }
3396 
3397   CodeStub* slow_path = new SubstitutabilityCheckStub(left.result(), right.result(), info);
3398   __ substitutability_check(result, left.result(), right.result(), equal_result, not_equal_result,
3399                             tmp1, tmp2,
3400                             left_klass, right_klass, left_klass_op, right_klass_op, info, slow_path);
3401 }
3402 
3403 void LIRGenerator::do_RuntimeCall(address routine, Intrinsic* x) {
3404   assert(x->number_of_arguments() == 0, "wrong type");
3405   // Enforce computation of _reserved_argument_area_size which is required on some platforms.
3406   BasicTypeList signature;
3407   CallingConvention* cc = frame_map()->c_calling_convention(&signature);
3408   LIR_Opr reg = result_register_for(x->type());
3409   __ call_runtime_leaf(routine, getThreadTemp(),
3410                        reg, new LIR_OprList());
3411   LIR_Opr result = rlock_result(x);
3412   __ move(reg, result);
3413 }
3414 
3415 
3416 
3417 void LIRGenerator::do_Intrinsic(Intrinsic* x) {
3418   switch (x->id()) {
3419   case vmIntrinsics::_intBitsToFloat      :
3420   case vmIntrinsics::_doubleToRawLongBits :
3421   case vmIntrinsics::_longBitsToDouble    :
3422   case vmIntrinsics::_floatToRawIntBits   : {
3423     do_FPIntrinsics(x);
3424     break;
3425   }
3426 
3427 #ifdef JFR_HAVE_INTRINSICS
3428   case vmIntrinsics::_counterTime:
3429     do_RuntimeCall(CAST_FROM_FN_PTR(address, JfrTime::time_function()), x);
3430     break;
3431 #endif
3432 
3433   case vmIntrinsics::_currentTimeMillis:
3434     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeMillis), x);
3435     break;
3436 
3437   case vmIntrinsics::_nanoTime:
3438     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeNanos), x);
3439     break;
3440 
3441   case vmIntrinsics::_Object_init:    do_RegisterFinalizer(x); break;
3442   case vmIntrinsics::_isInstance:     do_isInstance(x);    break;
3443   case vmIntrinsics::_isPrimitive:    do_isPrimitive(x);   break;
3444   case vmIntrinsics::_getModifiers:   do_getModifiers(x);  break;
3445   case vmIntrinsics::_getClass:       do_getClass(x);      break;
3446   case vmIntrinsics::_getObjectSize:  do_getObjectSize(x); break;
3447   case vmIntrinsics::_currentCarrierThread: do_currentCarrierThread(x); break;
3448   case vmIntrinsics::_currentThread:  do_vthread(x);       break;
3449   case vmIntrinsics::_scopedValueCache: do_scopedValueCache(x); break;
3450 
3451   case vmIntrinsics::_dlog:           // fall through
3452   case vmIntrinsics::_dlog10:         // fall through
3453   case vmIntrinsics::_dabs:           // fall through
3454   case vmIntrinsics::_dsqrt:          // fall through
3455   case vmIntrinsics::_dsqrt_strict:   // fall through
3456   case vmIntrinsics::_dtan:           // fall through
3457   case vmIntrinsics::_dsin :          // fall through
3458   case vmIntrinsics::_dcos :          // fall through
3459   case vmIntrinsics::_dexp :          // fall through
3460   case vmIntrinsics::_dpow :          do_MathIntrinsic(x); break;
3461   case vmIntrinsics::_arraycopy:      do_ArrayCopy(x);     break;
3462 
3463   case vmIntrinsics::_fmaD:           do_FmaIntrinsic(x); break;
3464   case vmIntrinsics::_fmaF:           do_FmaIntrinsic(x); break;
3465 
3466   // Use java.lang.Math intrinsics code since it works for these intrinsics too.
3467   case vmIntrinsics::_floatToFloat16: // fall through
3468   case vmIntrinsics::_float16ToFloat: do_MathIntrinsic(x); break;
3469 
3470   case vmIntrinsics::_Preconditions_checkIndex:
3471     do_PreconditionsCheckIndex(x, T_INT);
3472     break;
3473   case vmIntrinsics::_Preconditions_checkLongIndex:
3474     do_PreconditionsCheckIndex(x, T_LONG);
3475     break;
3476 
3477   case vmIntrinsics::_compareAndSetReference:
3478     do_CompareAndSwap(x, objectType);
3479     break;
3480   case vmIntrinsics::_compareAndSetInt:
3481     do_CompareAndSwap(x, intType);
3482     break;
3483   case vmIntrinsics::_compareAndSetLong:
3484     do_CompareAndSwap(x, longType);
3485     break;
3486 
3487   case vmIntrinsics::_loadFence :
3488     __ membar_acquire();
3489     break;
3490   case vmIntrinsics::_storeFence:
3491     __ membar_release();
3492     break;
3493   case vmIntrinsics::_storeStoreFence:
3494     __ membar_storestore();
3495     break;
3496   case vmIntrinsics::_fullFence :
3497     __ membar();
3498     break;
3499   case vmIntrinsics::_onSpinWait:
3500     __ on_spin_wait();
3501     break;
3502   case vmIntrinsics::_Reference_get:
3503     do_Reference_get(x);
3504     break;
3505 
3506   case vmIntrinsics::_updateCRC32:
3507   case vmIntrinsics::_updateBytesCRC32:
3508   case vmIntrinsics::_updateByteBufferCRC32:
3509     do_update_CRC32(x);
3510     break;
3511 
3512   case vmIntrinsics::_updateBytesCRC32C:
3513   case vmIntrinsics::_updateDirectByteBufferCRC32C:
3514     do_update_CRC32C(x);
3515     break;
3516 
3517   case vmIntrinsics::_vectorizedMismatch:
3518     do_vectorizedMismatch(x);
3519     break;
3520 
3521   case vmIntrinsics::_blackhole:
3522     do_blackhole(x);
3523     break;
3524 
3525   default: ShouldNotReachHere(); break;
3526   }
3527 }
3528 
3529 void LIRGenerator::profile_arguments(ProfileCall* x) {
3530   if (compilation()->profile_arguments()) {
3531     int bci = x->bci_of_invoke();
3532     ciMethodData* md = x->method()->method_data_or_null();
3533     assert(md != nullptr, "Sanity");
3534     ciProfileData* data = md->bci_to_data(bci);
3535     if (data != nullptr) {
3536       if ((data->is_CallTypeData() && data->as_CallTypeData()->has_arguments()) ||
3537           (data->is_VirtualCallTypeData() && data->as_VirtualCallTypeData()->has_arguments())) {
3538         ByteSize extra = data->is_CallTypeData() ? CallTypeData::args_data_offset() : VirtualCallTypeData::args_data_offset();
3539         int base_offset = md->byte_offset_of_slot(data, extra);
3540         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3541         ciTypeStackSlotEntries* args = data->is_CallTypeData() ? ((ciCallTypeData*)data)->args() : ((ciVirtualCallTypeData*)data)->args();
3542 
3543         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3544         int start = 0;
3545         int stop = data->is_CallTypeData() ? ((ciCallTypeData*)data)->number_of_arguments() : ((ciVirtualCallTypeData*)data)->number_of_arguments();
3546         if (x->callee()->is_loaded() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
3547           // first argument is not profiled at call (method handle invoke)
3548           assert(x->method()->raw_code_at_bci(bci) == Bytecodes::_invokehandle, "invokehandle expected");
3549           start = 1;
3550         }
3551         ciSignature* callee_signature = x->callee()->signature();
3552         // method handle call to virtual method
3553         bool has_receiver = x->callee()->is_loaded() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
3554         ciSignatureStream callee_signature_stream(callee_signature, has_receiver ? x->callee()->holder() : nullptr);
3555 
3556         bool ignored_will_link;
3557         ciSignature* signature_at_call = nullptr;
3558         x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3559         ciSignatureStream signature_at_call_stream(signature_at_call);
3560 
3561         // if called through method handle invoke, some arguments may have been popped
3562         for (int i = 0; i < stop && i+start < x->nb_profiled_args(); i++) {
3563           int off = in_bytes(TypeEntriesAtCall::argument_type_offset(i)) - in_bytes(TypeEntriesAtCall::args_data_offset());
3564           ciKlass* exact = profile_type(md, base_offset, off,
3565               args->type(i), x->profiled_arg_at(i+start), mdp,
3566               !x->arg_needs_null_check(i+start),
3567               signature_at_call_stream.next_klass(), callee_signature_stream.next_klass());
3568           if (exact != nullptr) {
3569             md->set_argument_type(bci, i, exact);
3570           }
3571         }
3572       } else {
3573 #ifdef ASSERT
3574         Bytecodes::Code code = x->method()->raw_code_at_bci(x->bci_of_invoke());
3575         int n = x->nb_profiled_args();
3576         assert(MethodData::profile_parameters() && (MethodData::profile_arguments_jsr292_only() ||
3577             (x->inlined() && ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)))),
3578             "only at JSR292 bytecodes");
3579 #endif
3580       }
3581     }
3582   }
3583 }
3584 
3585 // profile parameters on entry to an inlined method
3586 void LIRGenerator::profile_parameters_at_call(ProfileCall* x) {
3587   if (compilation()->profile_parameters() && x->inlined()) {
3588     ciMethodData* md = x->callee()->method_data_or_null();
3589     if (md != nullptr) {
3590       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
3591       if (parameters_type_data != nullptr) {
3592         ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
3593         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3594         bool has_receiver = !x->callee()->is_static();
3595         ciSignature* sig = x->callee()->signature();
3596         ciSignatureStream sig_stream(sig, has_receiver ? x->callee()->holder() : nullptr);
3597         int i = 0; // to iterate on the Instructions
3598         Value arg = x->recv();
3599         bool not_null = false;
3600         int bci = x->bci_of_invoke();
3601         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3602         // The first parameter is the receiver so that's what we start
3603         // with if it exists. One exception is method handle call to
3604         // virtual method: the receiver is in the args list
3605         if (arg == nullptr || !Bytecodes::has_receiver(bc)) {
3606           i = 1;
3607           arg = x->profiled_arg_at(0);
3608           not_null = !x->arg_needs_null_check(0);
3609         }
3610         int k = 0; // to iterate on the profile data
3611         for (;;) {
3612           intptr_t profiled_k = parameters->type(k);
3613           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
3614                                         in_bytes(ParametersTypeData::type_offset(k)) - in_bytes(ParametersTypeData::type_offset(0)),
3615                                         profiled_k, arg, mdp, not_null, sig_stream.next_klass(), nullptr);
3616           // If the profile is known statically set it once for all and do not emit any code
3617           if (exact != nullptr) {
3618             md->set_parameter_type(k, exact);
3619           }
3620           k++;
3621           if (k >= parameters_type_data->number_of_parameters()) {
3622 #ifdef ASSERT
3623             int extra = 0;
3624             if (MethodData::profile_arguments() && TypeProfileParmsLimit != -1 &&
3625                 x->nb_profiled_args() >= TypeProfileParmsLimit &&
3626                 x->recv() != nullptr && Bytecodes::has_receiver(bc)) {
3627               extra += 1;
3628             }
3629             assert(i == x->nb_profiled_args() - extra || (TypeProfileParmsLimit != -1 && TypeProfileArgsLimit > TypeProfileParmsLimit), "unused parameters?");
3630 #endif
3631             break;
3632           }
3633           arg = x->profiled_arg_at(i);
3634           not_null = !x->arg_needs_null_check(i);
3635           i++;
3636         }
3637       }
3638     }
3639   }
3640 }
3641 
3642 void LIRGenerator::do_ProfileCall(ProfileCall* x) {
3643   // Need recv in a temporary register so it interferes with the other temporaries
3644   LIR_Opr recv = LIR_OprFact::illegalOpr;
3645   LIR_Opr mdo = new_register(T_METADATA);
3646   // tmp is used to hold the counters on SPARC
3647   LIR_Opr tmp = new_pointer_register();
3648 
3649   if (x->nb_profiled_args() > 0) {
3650     profile_arguments(x);
3651   }
3652 
3653   // profile parameters on inlined method entry including receiver
3654   if (x->recv() != nullptr || x->nb_profiled_args() > 0) {
3655     profile_parameters_at_call(x);
3656   }
3657 
3658   if (x->recv() != nullptr) {
3659     LIRItem value(x->recv(), this);
3660     value.load_item();
3661     recv = new_register(T_OBJECT);
3662     __ move(value.result(), recv);
3663   }
3664   __ profile_call(x->method(), x->bci_of_invoke(), x->callee(), mdo, recv, tmp, x->known_holder());
3665 }
3666 
3667 void LIRGenerator::do_ProfileReturnType(ProfileReturnType* x) {
3668   int bci = x->bci_of_invoke();
3669   ciMethodData* md = x->method()->method_data_or_null();
3670   assert(md != nullptr, "Sanity");
3671   ciProfileData* data = md->bci_to_data(bci);
3672   if (data != nullptr) {
3673     assert(data->is_CallTypeData() || data->is_VirtualCallTypeData(), "wrong profile data type");
3674     ciSingleTypeEntry* ret = data->is_CallTypeData() ? ((ciCallTypeData*)data)->ret() : ((ciVirtualCallTypeData*)data)->ret();
3675     LIR_Opr mdp = LIR_OprFact::illegalOpr;
3676 
3677     bool ignored_will_link;
3678     ciSignature* signature_at_call = nullptr;
3679     x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3680 
3681     // The offset within the MDO of the entry to update may be too large
3682     // to be used in load/store instructions on some platforms. So have
3683     // profile_type() compute the address of the profile in a register.
3684     ciKlass* exact = profile_type(md, md->byte_offset_of_slot(data, ret->type_offset()), 0,
3685         ret->type(), x->ret(), mdp,
3686         !x->needs_null_check(),
3687         signature_at_call->return_type()->as_klass(),
3688         x->callee()->signature()->return_type()->as_klass());
3689     if (exact != nullptr) {
3690       md->set_return_type(bci, exact);
3691     }
3692   }
3693 }
3694 
3695 bool LIRGenerator::profile_inline_klass(ciMethodData* md, ciProfileData* data, Value value, int flag) {
3696   ciKlass* klass = value->as_loaded_klass_or_null();
3697   if (klass != nullptr) {
3698     if (klass->is_inlinetype()) {
3699       profile_flags(md, data, flag, lir_cond_always);
3700     } else if (klass->can_be_inline_klass()) {
3701       return false;
3702     }
3703   } else {
3704     return false;
3705   }
3706   return true;
3707 }
3708 
3709 
3710 void LIRGenerator::do_ProfileACmpTypes(ProfileACmpTypes* x) {
3711   ciMethod* method = x->method();
3712   assert(method != nullptr, "method should be set if branch is profiled");
3713   ciMethodData* md = method->method_data_or_null();
3714   assert(md != nullptr, "Sanity");
3715   ciProfileData* data = md->bci_to_data(x->bci());
3716   assert(data != nullptr, "must have profiling data");
3717   assert(data->is_ACmpData(), "need BranchData for two-way branches");
3718   ciACmpData* acmp = (ciACmpData*)data;
3719   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3720   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()), 0,
3721                acmp->left()->type(), x->left(), mdp, !x->left_maybe_null(), nullptr, nullptr);
3722   int flags_offset = md->byte_offset_of_slot(data, DataLayout::flags_offset());
3723   if (!profile_inline_klass(md, acmp, x->left(), ACmpData::left_inline_type_byte_constant())) {
3724     LIR_Opr mdp = new_register(T_METADATA);
3725     __ metadata2reg(md->constant_encoding(), mdp);
3726     LIRItem value(x->left(), this);
3727     value.load_item();
3728     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::left_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3729   }
3730   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()),
3731                in_bytes(ACmpData::right_offset()) - in_bytes(ACmpData::left_offset()),
3732                acmp->right()->type(), x->right(), mdp, !x->right_maybe_null(), nullptr, nullptr);
3733   if (!profile_inline_klass(md, acmp, x->right(), ACmpData::right_inline_type_byte_constant())) {
3734     LIR_Opr mdp = new_register(T_METADATA);
3735     __ metadata2reg(md->constant_encoding(), mdp);
3736     LIRItem value(x->right(), this);
3737     value.load_item();
3738     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::right_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3739   }
3740 }
3741 
3742 void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) {
3743   // We can safely ignore accessors here, since c2 will inline them anyway,
3744   // accessors are also always mature.
3745   if (!x->inlinee()->is_accessor()) {
3746     CodeEmitInfo* info = state_for(x, x->state(), true);
3747     // Notify the runtime very infrequently only to take care of counter overflows
3748     int freq_log = Tier23InlineeNotifyFreqLog;
3749     double scale;
3750     if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3751       freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3752     }
3753     increment_event_counter_impl(info, x->inlinee(), LIR_OprFact::intConst(InvocationCounter::count_increment), right_n_bits(freq_log), InvocationEntryBci, false, true);
3754   }
3755 }
3756 
3757 void LIRGenerator::increment_backedge_counter_conditionally(LIR_Condition cond, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info, int left_bci, int right_bci, int bci) {
3758   if (compilation()->is_profiling()) {
3759 #if defined(X86) && !defined(_LP64)
3760     // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
3761     LIR_Opr left_copy = new_register(left->type());
3762     __ move(left, left_copy);
3763     __ cmp(cond, left_copy, right);
3764 #else
3765     __ cmp(cond, left, right);
3766 #endif
3767     LIR_Opr step = new_register(T_INT);
3768     LIR_Opr plus_one = LIR_OprFact::intConst(InvocationCounter::count_increment);
3769     LIR_Opr zero = LIR_OprFact::intConst(0);
3770     __ cmove(cond,
3771         (left_bci < bci) ? plus_one : zero,
3772         (right_bci < bci) ? plus_one : zero,
3773         step, left->type());
3774     increment_backedge_counter(info, step, bci);
3775   }
3776 }
3777 
3778 
3779 void LIRGenerator::increment_event_counter(CodeEmitInfo* info, LIR_Opr step, int bci, bool backedge) {
3780   int freq_log = 0;
3781   int level = compilation()->env()->comp_level();
3782   if (level == CompLevel_limited_profile) {
3783     freq_log = (backedge ? Tier2BackedgeNotifyFreqLog : Tier2InvokeNotifyFreqLog);
3784   } else if (level == CompLevel_full_profile) {
3785     freq_log = (backedge ? Tier3BackedgeNotifyFreqLog : Tier3InvokeNotifyFreqLog);
3786   } else {
3787     ShouldNotReachHere();
3788   }
3789   // Increment the appropriate invocation/backedge counter and notify the runtime.
3790   double scale;
3791   if (_method->has_option_value(CompileCommand::CompileThresholdScaling, scale)) {
3792     freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3793   }
3794   increment_event_counter_impl(info, info->scope()->method(), step, right_n_bits(freq_log), bci, backedge, true);
3795 }
3796 
3797 void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info,
3798                                                 ciMethod *method, LIR_Opr step, int frequency,
3799                                                 int bci, bool backedge, bool notify) {
3800   assert(frequency == 0 || is_power_of_2(frequency + 1), "Frequency must be x^2 - 1 or 0");
3801   int level = _compilation->env()->comp_level();
3802   assert(level > CompLevel_simple, "Shouldn't be here");
3803 
3804   int offset = -1;
3805   LIR_Opr counter_holder;
3806   if (level == CompLevel_limited_profile) {
3807     MethodCounters* counters_adr = method->ensure_method_counters();
3808     if (counters_adr == nullptr) {
3809       bailout("method counters allocation failed");
3810       return;
3811     }
3812     counter_holder = new_pointer_register();
3813     __ move(LIR_OprFact::intptrConst(counters_adr), counter_holder);
3814     offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() :
3815                                  MethodCounters::invocation_counter_offset());
3816   } else if (level == CompLevel_full_profile) {
3817     counter_holder = new_register(T_METADATA);
3818     offset = in_bytes(backedge ? MethodData::backedge_counter_offset() :
3819                                  MethodData::invocation_counter_offset());
3820     ciMethodData* md = method->method_data_or_null();
3821     assert(md != nullptr, "Sanity");
3822     __ metadata2reg(md->constant_encoding(), counter_holder);
3823   } else {
3824     ShouldNotReachHere();
3825   }
3826   LIR_Address* counter = new LIR_Address(counter_holder, offset, T_INT);
3827   LIR_Opr result = new_register(T_INT);
3828   __ load(counter, result);
3829   __ add(result, step, result);
3830   __ store(result, counter);
3831   if (notify && (!backedge || UseOnStackReplacement)) {
3832     LIR_Opr meth = LIR_OprFact::metadataConst(method->constant_encoding());
3833     // The bci for info can point to cmp for if's we want the if bci
3834     CodeStub* overflow = new CounterOverflowStub(info, bci, meth);
3835     int freq = frequency << InvocationCounter::count_shift;
3836     if (freq == 0) {
3837       if (!step->is_constant()) {
3838         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3839         __ branch(lir_cond_notEqual, overflow);
3840       } else {
3841         __ branch(lir_cond_always, overflow);
3842       }
3843     } else {
3844       LIR_Opr mask = load_immediate(freq, T_INT);
3845       if (!step->is_constant()) {
3846         // If step is 0, make sure the overflow check below always fails
3847         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3848         __ cmove(lir_cond_notEqual, result, LIR_OprFact::intConst(InvocationCounter::count_increment), result, T_INT);
3849       }
3850       __ logical_and(result, mask, result);
3851       __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
3852       __ branch(lir_cond_equal, overflow);
3853     }
3854     __ branch_destination(overflow->continuation());
3855   }
3856 }
3857 
3858 void LIRGenerator::do_RuntimeCall(RuntimeCall* x) {
3859   LIR_OprList* args = new LIR_OprList(x->number_of_arguments());
3860   BasicTypeList* signature = new BasicTypeList(x->number_of_arguments());
3861 
3862   if (x->pass_thread()) {
3863     signature->append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3864     args->append(getThreadPointer());
3865   }
3866 
3867   for (int i = 0; i < x->number_of_arguments(); i++) {
3868     Value a = x->argument_at(i);
3869     LIRItem* item = new LIRItem(a, this);
3870     item->load_item();
3871     args->append(item->result());
3872     signature->append(as_BasicType(a->type()));
3873   }
3874 
3875   LIR_Opr result = call_runtime(signature, args, x->entry(), x->type(), nullptr);
3876   if (x->type() == voidType) {
3877     set_no_result(x);
3878   } else {
3879     __ move(result, rlock_result(x));
3880   }
3881 }
3882 
3883 #ifdef ASSERT
3884 void LIRGenerator::do_Assert(Assert *x) {
3885   ValueTag tag = x->x()->type()->tag();
3886   If::Condition cond = x->cond();
3887 
3888   LIRItem xitem(x->x(), this);
3889   LIRItem yitem(x->y(), this);
3890   LIRItem* xin = &xitem;
3891   LIRItem* yin = &yitem;
3892 
3893   assert(tag == intTag, "Only integer assertions are valid!");
3894 
3895   xin->load_item();
3896   yin->dont_load_item();
3897 
3898   set_no_result(x);
3899 
3900   LIR_Opr left = xin->result();
3901   LIR_Opr right = yin->result();
3902 
3903   __ lir_assert(lir_cond(x->cond()), left, right, x->message(), true);
3904 }
3905 #endif
3906 
3907 void LIRGenerator::do_RangeCheckPredicate(RangeCheckPredicate *x) {
3908 
3909 
3910   Instruction *a = x->x();
3911   Instruction *b = x->y();
3912   if (!a || StressRangeCheckElimination) {
3913     assert(!b || StressRangeCheckElimination, "B must also be null");
3914 
3915     CodeEmitInfo *info = state_for(x, x->state());
3916     CodeStub* stub = new PredicateFailedStub(info);
3917 
3918     __ jump(stub);
3919   } else if (a->type()->as_IntConstant() && b->type()->as_IntConstant()) {
3920     int a_int = a->type()->as_IntConstant()->value();
3921     int b_int = b->type()->as_IntConstant()->value();
3922 
3923     bool ok = false;
3924 
3925     switch(x->cond()) {
3926       case Instruction::eql: ok = (a_int == b_int); break;
3927       case Instruction::neq: ok = (a_int != b_int); break;
3928       case Instruction::lss: ok = (a_int < b_int); break;
3929       case Instruction::leq: ok = (a_int <= b_int); break;
3930       case Instruction::gtr: ok = (a_int > b_int); break;
3931       case Instruction::geq: ok = (a_int >= b_int); break;
3932       case Instruction::aeq: ok = ((unsigned int)a_int >= (unsigned int)b_int); break;
3933       case Instruction::beq: ok = ((unsigned int)a_int <= (unsigned int)b_int); break;
3934       default: ShouldNotReachHere();
3935     }
3936 
3937     if (ok) {
3938 
3939       CodeEmitInfo *info = state_for(x, x->state());
3940       CodeStub* stub = new PredicateFailedStub(info);
3941 
3942       __ jump(stub);
3943     }
3944   } else {
3945 
3946     ValueTag tag = x->x()->type()->tag();
3947     If::Condition cond = x->cond();
3948     LIRItem xitem(x->x(), this);
3949     LIRItem yitem(x->y(), this);
3950     LIRItem* xin = &xitem;
3951     LIRItem* yin = &yitem;
3952 
3953     assert(tag == intTag, "Only integer deoptimizations are valid!");
3954 
3955     xin->load_item();
3956     yin->dont_load_item();
3957     set_no_result(x);
3958 
3959     LIR_Opr left = xin->result();
3960     LIR_Opr right = yin->result();
3961 
3962     CodeEmitInfo *info = state_for(x, x->state());
3963     CodeStub* stub = new PredicateFailedStub(info);
3964 
3965     __ cmp(lir_cond(cond), left, right);
3966     __ branch(lir_cond(cond), stub);
3967   }
3968 }
3969 
3970 void LIRGenerator::do_blackhole(Intrinsic *x) {
3971   assert(!x->has_receiver(), "Should have been checked before: only static methods here");
3972   for (int c = 0; c < x->number_of_arguments(); c++) {
3973     // Load the argument
3974     LIRItem vitem(x->argument_at(c), this);
3975     vitem.load_item();
3976     // ...and leave it unused.
3977   }
3978 }
3979 
3980 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
3981   LIRItemList args(1);
3982   LIRItem value(arg1, this);
3983   args.append(&value);
3984   BasicTypeList signature;
3985   signature.append(as_BasicType(arg1->type()));
3986 
3987   return call_runtime(&signature, &args, entry, result_type, info);
3988 }
3989 
3990 
3991 LIR_Opr LIRGenerator::call_runtime(Value arg1, Value arg2, address entry, ValueType* result_type, CodeEmitInfo* info) {
3992   LIRItemList args(2);
3993   LIRItem value1(arg1, this);
3994   LIRItem value2(arg2, this);
3995   args.append(&value1);
3996   args.append(&value2);
3997   BasicTypeList signature;
3998   signature.append(as_BasicType(arg1->type()));
3999   signature.append(as_BasicType(arg2->type()));
4000 
4001   return call_runtime(&signature, &args, entry, result_type, info);
4002 }
4003 
4004 
4005 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIR_OprList* args,
4006                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4007   // get a result register
4008   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4009   LIR_Opr result = LIR_OprFact::illegalOpr;
4010   if (result_type->tag() != voidTag) {
4011     result = new_register(result_type);
4012     phys_reg = result_register_for(result_type);
4013   }
4014 
4015   // move the arguments into the correct location
4016   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4017   assert(cc->length() == args->length(), "argument mismatch");
4018   for (int i = 0; i < args->length(); i++) {
4019     LIR_Opr arg = args->at(i);
4020     LIR_Opr loc = cc->at(i);
4021     if (loc->is_register()) {
4022       __ move(arg, loc);
4023     } else {
4024       LIR_Address* addr = loc->as_address_ptr();
4025 //           if (!can_store_as_constant(arg)) {
4026 //             LIR_Opr tmp = new_register(arg->type());
4027 //             __ move(arg, tmp);
4028 //             arg = tmp;
4029 //           }
4030       __ move(arg, addr);
4031     }
4032   }
4033 
4034   if (info) {
4035     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4036   } else {
4037     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4038   }
4039   if (result->is_valid()) {
4040     __ move(phys_reg, result);
4041   }
4042   return result;
4043 }
4044 
4045 
4046 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIRItemList* args,
4047                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4048   // get a result register
4049   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4050   LIR_Opr result = LIR_OprFact::illegalOpr;
4051   if (result_type->tag() != voidTag) {
4052     result = new_register(result_type);
4053     phys_reg = result_register_for(result_type);
4054   }
4055 
4056   // move the arguments into the correct location
4057   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4058 
4059   assert(cc->length() == args->length(), "argument mismatch");
4060   for (int i = 0; i < args->length(); i++) {
4061     LIRItem* arg = args->at(i);
4062     LIR_Opr loc = cc->at(i);
4063     if (loc->is_register()) {
4064       arg->load_item_force(loc);
4065     } else {
4066       LIR_Address* addr = loc->as_address_ptr();
4067       arg->load_for_store(addr->type());
4068       __ move(arg->result(), addr);
4069     }
4070   }
4071 
4072   if (info) {
4073     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4074   } else {
4075     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4076   }
4077   if (result->is_valid()) {
4078     __ move(phys_reg, result);
4079   }
4080   return result;
4081 }
4082 
4083 void LIRGenerator::do_MemBar(MemBar* x) {
4084   LIR_Code code = x->code();
4085   switch(code) {
4086   case lir_membar_acquire   : __ membar_acquire(); break;
4087   case lir_membar_release   : __ membar_release(); break;
4088   case lir_membar           : __ membar(); break;
4089   case lir_membar_loadload  : __ membar_loadload(); break;
4090   case lir_membar_storestore: __ membar_storestore(); break;
4091   case lir_membar_loadstore : __ membar_loadstore(); break;
4092   case lir_membar_storeload : __ membar_storeload(); break;
4093   default                   : ShouldNotReachHere(); break;
4094   }
4095 }
4096 
4097 LIR_Opr LIRGenerator::mask_boolean(LIR_Opr array, LIR_Opr value, CodeEmitInfo*& null_check_info) {
4098   LIR_Opr value_fixed = rlock_byte(T_BYTE);
4099   if (two_operand_lir_form) {
4100     __ move(value, value_fixed);
4101     __ logical_and(value_fixed, LIR_OprFact::intConst(1), value_fixed);
4102   } else {
4103     __ logical_and(value, LIR_OprFact::intConst(1), value_fixed);
4104   }
4105   LIR_Opr klass = new_register(T_METADATA);
4106   load_klass(array, klass, null_check_info);
4107   null_check_info = nullptr;
4108   LIR_Opr layout = new_register(T_INT);
4109   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
4110   int diffbit = Klass::layout_helper_boolean_diffbit();
4111   __ logical_and(layout, LIR_OprFact::intConst(diffbit), layout);
4112   __ cmp(lir_cond_notEqual, layout, LIR_OprFact::intConst(0));
4113   __ cmove(lir_cond_notEqual, value_fixed, value, value_fixed, T_BYTE);
4114   value = value_fixed;
4115   return value;
4116 }