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