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