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